diff --git a/seaweed-block/core/replication/probe_loop.go b/seaweed-block/core/replication/probe_loop.go new file mode 100644 index 0000000000..a6ce249cbf --- /dev/null +++ b/seaweed-block/core/replication/probe_loop.go @@ -0,0 +1,299 @@ +package replication + +import ( + "context" + "fmt" + "log" + "sync" + "sync/atomic" + "time" +) + +// ProbeLoop is the per-volume primary-side degraded-peer probe loop +// (G5-5C). It iterates over peers in ReplicaDegraded state at a bounded +// interval, calls a host-injected probe function on each, and applies +// per-peer cooldown (with backoff) so flapping peers do not cause a +// retrigger storm. +// +// Layering (G5-5C §1.G): this loop is runtime / wiring. It owns the +// timer, iteration discipline, cooldown progression, and in-flight +// guard. It does NOT own the recovery FSM (engine), the probe +// transport (BlockExecutor), or the peer state machine (ReplicaPeer). +// A degraded peer's transition back to Healthy / CatchingUp / +// NeedsRebuild is driven by the engine on probe-result ingest, NOT +// by this loop. +// +// Authority bound (G5-5C §1.E): the loop's peer source is a function +// that snapshots the current ReplicationVolume.peers map under lock. +// It does NOT consult master, does NOT enumerate network-discoverable +// addresses. Only master-admitted peers are eligible. +// +// Backoff (G5-5C §1.G #7): per-peer cooldown starts at base (5 s), +// doubles on consecutive probe failures up to a cap (60 s), and +// resets to base on first success. +// +// Pinned by: +// - INV-G5-5C-PRIMARY-RECOVERY-AUTHORITY-BOUNDED +// - INV-G5-5C-SINGLE-INFLIGHT-PER-PEER +// - INV-G5-5C-RECOVERY-BACKOFF +type ProbeLoop struct { + cfg ProbeLoopConfig + peersFn PeerSourceFn + probeFn ProbeFn + cooldownFn CooldownFn // per-peer cooldown gate + + startOnce sync.Once + stopOnce sync.Once + stopCh chan struct{} + doneCh chan struct{} + + state atomic.Uint32 // probeLoopState +} + +// ProbeLoopConfig holds the loop's tuning knobs. Defaults match the +// architect-bound G5-5C §1.A shape: 5 s interval, 1 max concurrent. +type ProbeLoopConfig struct { + // Interval between iterations. Must be > 0; 0 disables the loop + // (Start returns without spawning a goroutine). + Interval time.Duration + + // MaxConcurrent caps the number of probe calls in flight in a + // single iteration. <= 1 means strictly sequential; we never + // exceed 1 in G5-5C v0.5 — kept as a config knob for future + // scaling. + MaxConcurrent int + + // CooldownBase is the per-peer cooldown after a probe attempt. + // Default 5 s. On consecutive failures the cooldown doubles up + // to CooldownCap; on success it resets to CooldownBase. + CooldownBase time.Duration + + // CooldownCap caps the backoff. Default 60 s. + CooldownCap time.Duration +} + +// DefaultProbeLoopConfig returns the architect-bound G5-5C defaults. +func DefaultProbeLoopConfig() ProbeLoopConfig { + return ProbeLoopConfig{ + Interval: 5 * time.Second, + MaxConcurrent: 1, + CooldownBase: 5 * time.Second, + CooldownCap: 60 * time.Second, + } +} + +// PeerSourceFn returns a snapshot of the current peer set. Called once +// per iteration. Implementation MUST acquire the appropriate lock on +// ReplicationVolume so the slice is internally consistent. The loop +// does not mutate the returned slice. +type PeerSourceFn func() []*ReplicaPeer + +// ProbeFn is invoked by the loop for each eligible peer. Returns nil +// on success (probe completed and feed-back-to-engine succeeded), +// non-nil on any failure path. The loop uses success/failure for +// cooldown progression but does NOT itself mutate peer state — that +// is the engine's job via OnProbeResult. +type ProbeFn func(ctx context.Context, peer *ReplicaPeer) error + +// CooldownFn gates whether a peer is currently eligible for a probe +// attempt. Called once per peer per iteration. Returns true if the +// peer should be probed; false if it is in cooldown or has an +// in-flight session. Implementation tracks per-peer cooldown +// progression independently of the loop (see ReplicaPeer's probe +// gate methods, added in step 2 of the G5-5C plan). +// +// Default implementation (used when not overridden): time-based +// cooldown stored on the peer itself. +type CooldownFn func(peer *ReplicaPeer) bool + +// probeLoopState is the loop's lifecycle state. +type probeLoopState uint32 + +const ( + probeLoopStateNew probeLoopState = iota + probeLoopStateRunning + probeLoopStateStopped +) + +// NewProbeLoop constructs a probe loop with the given config + seams. +// Returns an error if the config is invalid (e.g., zero interval). +// +// Called by: ReplicationVolume at construction time when a host +// configures probe-loop wiring. ReplicationVolume retains the +// returned *ProbeLoop and calls Start / Stop in its lifecycle. +// Owns: nothing yet — Start spawns the goroutine. +// Borrows: peersFn + probeFn + cooldownFn — caller retains. +func NewProbeLoop(cfg ProbeLoopConfig, peersFn PeerSourceFn, probeFn ProbeFn, cooldownFn CooldownFn) (*ProbeLoop, error) { + if cfg.Interval <= 0 { + return nil, fmt.Errorf("replication: ProbeLoop: interval must be > 0 (got %v)", cfg.Interval) + } + if cfg.MaxConcurrent <= 0 { + cfg.MaxConcurrent = 1 + } + if cfg.CooldownBase <= 0 { + cfg.CooldownBase = 5 * time.Second + } + if cfg.CooldownCap <= 0 { + cfg.CooldownCap = 60 * time.Second + } + if cfg.CooldownCap < cfg.CooldownBase { + cfg.CooldownCap = cfg.CooldownBase + } + if peersFn == nil { + return nil, fmt.Errorf("replication: ProbeLoop: peersFn is nil") + } + if probeFn == nil { + return nil, fmt.Errorf("replication: ProbeLoop: probeFn is nil") + } + if cooldownFn == nil { + return nil, fmt.Errorf("replication: ProbeLoop: cooldownFn is nil") + } + return &ProbeLoop{ + cfg: cfg, + peersFn: peersFn, + probeFn: probeFn, + cooldownFn: cooldownFn, + stopCh: make(chan struct{}), + doneCh: make(chan struct{}), + }, nil +} + +// Start begins the loop. Idempotent — second and later calls are +// no-ops. Returns nil on success. Safe to call before Stop; safe to +// call after Stop (returns nil but does not restart — once stopped, +// the loop is terminal). +// +// CP4B-2 lesson 1: Stop-before-Start MUST NOT deadlock. We use sync.Once +// for both Start and Stop so neither blocks on the other. +// +// Called by: ReplicationVolume when a primary role is admitted and +// probe-loop wiring is configured. +// Owns: spawns the loop goroutine (one per ProbeLoop instance). +// Borrows: nothing. +func (l *ProbeLoop) Start() error { + if l == nil { + return nil + } + var startErr error + l.startOnce.Do(func() { + // If already stopped before Start, skip the goroutine entirely. + // The doneCh stays open until first Start; if Stop already ran, + // it closed doneCh as well so subsequent waits return immediately. + if l.state.Load() == uint32(probeLoopStateStopped) { + return + } + l.state.Store(uint32(probeLoopStateRunning)) + go l.run() + }) + return startErr +} + +// Stop signals the loop to terminate and waits for the goroutine to +// exit. Idempotent. Safe to call before Start (returns immediately). +// Safe to call from any goroutine. +// +// CP4B-2 lesson 1: Stop must not deadlock when called before Start. +// We close stopCh and doneCh atomically via sync.Once. +// +// Called by: ReplicationVolume.Close. +// Owns: closes stopCh; waits on doneCh. +// Borrows: nothing. +func (l *ProbeLoop) Stop() { + if l == nil { + return + } + l.stopOnce.Do(func() { + close(l.stopCh) + // If the loop was never started, doneCh would never close on + // its own; close it here so any future external wait returns. + // We detect "never started" by observing state remained New. + if l.state.Load() == uint32(probeLoopStateNew) { + l.state.Store(uint32(probeLoopStateStopped)) + close(l.doneCh) + return + } + l.state.Store(uint32(probeLoopStateStopped)) + }) + // Wait outside the Once so concurrent Stop callers all see the goroutine exit. + <-l.doneCh +} + +// run is the loop body. Spawned by Start; exits when stopCh is closed. +func (l *ProbeLoop) run() { + defer close(l.doneCh) + + ticker := time.NewTicker(l.cfg.Interval) + defer ticker.Stop() + + for { + select { + case <-l.stopCh: + return + case <-ticker.C: + l.tick() + } + } +} + +// tick runs one iteration of the loop: snapshot peers, filter to +// degraded + cooldown-eligible, call probeFn on each up to +// MaxConcurrent, do not block forever on any single probe. +// +// CP4B-2 lesson 3: callback panic must NOT crash the goroutine. We +// wrap each probeFn call in a recover. +func (l *ProbeLoop) tick() { + peers := l.peersFn() + if len(peers) == 0 { + return + } + + // Sequential dispatch in v0.5 (MaxConcurrent=1 default). Parallel + // dispatch is a future optimization; out of scope for G5-5C. + for _, peer := range peers { + select { + case <-l.stopCh: + return + default: + } + + // Authority-bounded (§1.E): peer was sourced from + // ReplicationVolume.peers (master-admitted). No additional + // authority check needed here. + + // Single in-flight + cooldown gate (§1.G #3 + #7). + // cooldownFn is the canonical gate; ReplicaPeer ProbeIfDegraded + // wraps the state-check + cooldown atomically (added in step 2). + if !l.cooldownFn(peer) { + continue + } + + l.dispatchProbe(peer) + } +} + +// dispatchProbe invokes probeFn on a single peer, with panic recovery +// per CP4B-2 lesson 3 (callback panic must not crash the loop). +func (l *ProbeLoop) dispatchProbe(peer *ReplicaPeer) { + defer func() { + if r := recover(); r != nil { + log.Printf("replication: ProbeLoop probeFn panic peer=%s: %v", + peer.target.ReplicaID, r) + } + }() + // Best-effort context for the probe call. Tied to stopCh so a + // long-running probe is unblocked by Stop. + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + go func() { + select { + case <-l.stopCh: + cancel() + case <-ctx.Done(): + } + }() + + if err := l.probeFn(ctx, peer); err != nil { + log.Printf("replication: ProbeLoop probe failed peer=%s: %v", + peer.target.ReplicaID, err) + } +} diff --git a/seaweed-block/core/replication/probe_loop_test.go b/seaweed-block/core/replication/probe_loop_test.go new file mode 100644 index 0000000000..1994952fd2 --- /dev/null +++ b/seaweed-block/core/replication/probe_loop_test.go @@ -0,0 +1,305 @@ +package replication + +import ( + "context" + "errors" + "sync" + "sync/atomic" + "testing" + "time" +) + +// G5-5C §2 #2 lifecycle tests: +// - Start before run (no panic; no goroutine leak) +// - Stop while running (clean exit; goroutine returns) +// - Stop-before-Start (idempotent; no deadlock — CP4B-2 lesson 1) +// - Zero-interval guard (rejected at construction — CP4B-2 lesson 2) +// - Callback panic isolation (CP4B-2 lesson 3) +// +// These tests exercise the loop machinery without engaging real +// peers, executors, or adapters — peersFn / probeFn / cooldownFn are +// stubs that record interactions. + +func newProbeLoopForTest( + t *testing.T, + interval time.Duration, + peersFn PeerSourceFn, + probeFn ProbeFn, + cooldownFn CooldownFn, +) *ProbeLoop { + t.Helper() + cfg := DefaultProbeLoopConfig() + cfg.Interval = interval + cfg.CooldownBase = 100 * time.Millisecond + cfg.CooldownCap = 400 * time.Millisecond + loop, err := NewProbeLoop(cfg, peersFn, probeFn, cooldownFn) + if err != nil { + t.Fatalf("NewProbeLoop: %v", err) + } + return loop +} + +// TestProbeLoop_Lifecycle_StartStop verifies a clean start → tick → stop. +// Goal: no panic, goroutine exits, the probeFn is reachable from the +// loop iteration. +func TestProbeLoop_Lifecycle_StartStop(t *testing.T) { + var probeCalls atomic.Int64 + peersFn := func() []*ReplicaPeer { + // One synthetic peer; State is not relevant because cooldownFn + // always returns true here. + return []*ReplicaPeer{{target: ReplicaTarget{ReplicaID: "r1"}}} + } + probeFn := func(_ context.Context, _ *ReplicaPeer) error { + probeCalls.Add(1) + return nil + } + cooldownFn := func(_ *ReplicaPeer) bool { return true } + + loop := newProbeLoopForTest(t, 20*time.Millisecond, peersFn, probeFn, cooldownFn) + + if err := loop.Start(); err != nil { + t.Fatalf("Start: %v", err) + } + + // Wait for at least one tick to fire. + deadline := time.Now().Add(2 * time.Second) + for probeCalls.Load() == 0 && time.Now().Before(deadline) { + time.Sleep(10 * time.Millisecond) + } + if probeCalls.Load() == 0 { + t.Fatal("probeFn was never called within 2s") + } + + loop.Stop() + + // After Stop returns, the loop goroutine must be gone. Verify by + // observing no further calls. + beforeStop := probeCalls.Load() + time.Sleep(80 * time.Millisecond) + if got := probeCalls.Load(); got != beforeStop { + t.Fatalf("probeFn called after Stop: before=%d after=%d", beforeStop, got) + } +} + +// TestProbeLoop_Lifecycle_StopBeforeStart verifies CP4B-2 lesson 1: +// Stop called before Start must NOT deadlock. Once stopped before +// start, Start is a no-op (terminal state). +func TestProbeLoop_Lifecycle_StopBeforeStart(t *testing.T) { + peersFn := func() []*ReplicaPeer { return nil } + probeFn := func(_ context.Context, _ *ReplicaPeer) error { return nil } + cooldownFn := func(_ *ReplicaPeer) bool { return true } + + loop := newProbeLoopForTest(t, 50*time.Millisecond, peersFn, probeFn, cooldownFn) + + done := make(chan struct{}) + go func() { + loop.Stop() + close(done) + }() + select { + case <-done: + case <-time.After(2 * time.Second): + t.Fatal("Stop before Start deadlocked") + } + + // Calling Start after Stop returns nil but does not spawn a goroutine. + if err := loop.Start(); err != nil { + t.Fatalf("Start after Stop: %v", err) + } + // Calling Stop again is a no-op. + loop.Stop() +} + +// TestProbeLoop_Lifecycle_StopIdempotent verifies multiple Stop calls +// from concurrent goroutines all return cleanly. +func TestProbeLoop_Lifecycle_StopIdempotent(t *testing.T) { + peersFn := func() []*ReplicaPeer { return nil } + probeFn := func(_ context.Context, _ *ReplicaPeer) error { return nil } + cooldownFn := func(_ *ReplicaPeer) bool { return true } + + loop := newProbeLoopForTest(t, 50*time.Millisecond, peersFn, probeFn, cooldownFn) + if err := loop.Start(); err != nil { + t.Fatalf("Start: %v", err) + } + + const N = 8 + var wg sync.WaitGroup + wg.Add(N) + for i := 0; i < N; i++ { + go func() { + defer wg.Done() + loop.Stop() + }() + } + done := make(chan struct{}) + go func() { + wg.Wait() + close(done) + }() + select { + case <-done: + case <-time.After(2 * time.Second): + t.Fatal("concurrent Stop calls deadlocked") + } +} + +// TestProbeLoop_ZeroInterval_Rejected verifies CP4B-2 lesson 2: +// zero or negative interval must be rejected at construction so the +// loop never spins at top speed. +func TestProbeLoop_ZeroInterval_Rejected(t *testing.T) { + peersFn := func() []*ReplicaPeer { return nil } + probeFn := func(_ context.Context, _ *ReplicaPeer) error { return nil } + cooldownFn := func(_ *ReplicaPeer) bool { return true } + + cfg := DefaultProbeLoopConfig() + cfg.Interval = 0 + if _, err := NewProbeLoop(cfg, peersFn, probeFn, cooldownFn); err == nil { + t.Fatal("zero interval should be rejected at construction") + } + + cfg.Interval = -1 * time.Second + if _, err := NewProbeLoop(cfg, peersFn, probeFn, cooldownFn); err == nil { + t.Fatal("negative interval should be rejected at construction") + } +} + +// TestProbeLoop_CallbackPanic_Isolated verifies CP4B-2 lesson 3: +// a panic inside probeFn does NOT crash the loop goroutine. The loop +// keeps ticking, just logging the panic. +func TestProbeLoop_CallbackPanic_Isolated(t *testing.T) { + var calls atomic.Int64 + peersFn := func() []*ReplicaPeer { + return []*ReplicaPeer{{target: ReplicaTarget{ReplicaID: "r1"}}} + } + probeFn := func(_ context.Context, _ *ReplicaPeer) error { + c := calls.Add(1) + if c <= 2 { + panic("simulated probeFn panic") + } + return nil + } + cooldownFn := func(_ *ReplicaPeer) bool { return true } + + loop := newProbeLoopForTest(t, 20*time.Millisecond, peersFn, probeFn, cooldownFn) + if err := loop.Start(); err != nil { + t.Fatalf("Start: %v", err) + } + defer loop.Stop() + + // Wait until the loop has called probeFn at least 3 times. If the + // panic crashed the goroutine we would never get past 1. + deadline := time.Now().Add(3 * time.Second) + for calls.Load() < 3 && time.Now().Before(deadline) { + time.Sleep(10 * time.Millisecond) + } + if calls.Load() < 3 { + t.Fatalf("probeFn called only %d times — panic likely crashed loop", calls.Load()) + } +} + +// TestProbeLoop_OnlyEligiblePeers_AreProbed verifies the cooldownFn +// gate: peers for which cooldownFn returns false are skipped without +// any probeFn call. Pins INV-G5-5C-RECOVERY-BACKOFF (gating happens +// before dispatch) and INV-G5-5C-PROBE-LOOP-001 (loop only acts on +// eligible peers). +func TestProbeLoop_OnlyEligiblePeers_AreProbed(t *testing.T) { + probed := make(map[string]int) + var probedMu sync.Mutex + + r1 := &ReplicaPeer{target: ReplicaTarget{ReplicaID: "r1"}} + r2 := &ReplicaPeer{target: ReplicaTarget{ReplicaID: "r2"}} + r3 := &ReplicaPeer{target: ReplicaTarget{ReplicaID: "r3"}} + + peersFn := func() []*ReplicaPeer { return []*ReplicaPeer{r1, r2, r3} } + probeFn := func(_ context.Context, p *ReplicaPeer) error { + probedMu.Lock() + probed[p.target.ReplicaID]++ + probedMu.Unlock() + return nil + } + // Only r2 is eligible; r1 and r3 are gated out by cooldownFn. + cooldownFn := func(p *ReplicaPeer) bool { + return p.target.ReplicaID == "r2" + } + + loop := newProbeLoopForTest(t, 20*time.Millisecond, peersFn, probeFn, cooldownFn) + if err := loop.Start(); err != nil { + t.Fatalf("Start: %v", err) + } + defer loop.Stop() + + deadline := time.Now().Add(2 * time.Second) + for { + probedMu.Lock() + r2Count := probed["r2"] + probedMu.Unlock() + if r2Count >= 2 { + break + } + if time.Now().After(deadline) { + t.Fatal("r2 was not probed at least twice within 2s") + } + time.Sleep(10 * time.Millisecond) + } + + probedMu.Lock() + if probed["r1"] != 0 { + t.Errorf("r1 was probed %d times; expected 0 (cooldownFn=false)", probed["r1"]) + } + if probed["r3"] != 0 { + t.Errorf("r3 was probed %d times; expected 0 (cooldownFn=false)", probed["r3"]) + } + probedMu.Unlock() +} + +// TestProbeLoop_NilPeersOK verifies an empty peer set causes no probe +// calls and no panic. +func TestProbeLoop_NilPeersOK(t *testing.T) { + var calls atomic.Int64 + peersFn := func() []*ReplicaPeer { return nil } + probeFn := func(_ context.Context, _ *ReplicaPeer) error { + calls.Add(1) + return nil + } + cooldownFn := func(_ *ReplicaPeer) bool { return true } + + loop := newProbeLoopForTest(t, 20*time.Millisecond, peersFn, probeFn, cooldownFn) + if err := loop.Start(); err != nil { + t.Fatalf("Start: %v", err) + } + time.Sleep(120 * time.Millisecond) + loop.Stop() + + if calls.Load() != 0 { + t.Fatalf("probeFn called %d times despite empty peer set", calls.Load()) + } +} + +// TestProbeLoop_ProbeFnError_DoesNotStop verifies the loop continues +// after a probeFn error (errors are forwarded to cooldownFn for +// backoff progression, not to the loop's lifecycle). +func TestProbeLoop_ProbeFnError_DoesNotStop(t *testing.T) { + var calls atomic.Int64 + peersFn := func() []*ReplicaPeer { + return []*ReplicaPeer{{target: ReplicaTarget{ReplicaID: "r1"}}} + } + probeFn := func(_ context.Context, _ *ReplicaPeer) error { + calls.Add(1) + return errors.New("simulated probe failure") + } + cooldownFn := func(_ *ReplicaPeer) bool { return true } + + loop := newProbeLoopForTest(t, 20*time.Millisecond, peersFn, probeFn, cooldownFn) + if err := loop.Start(); err != nil { + t.Fatalf("Start: %v", err) + } + defer loop.Stop() + + deadline := time.Now().Add(2 * time.Second) + for calls.Load() < 3 && time.Now().Before(deadline) { + time.Sleep(10 * time.Millisecond) + } + if calls.Load() < 3 { + t.Fatalf("probeFn called only %d times — error likely halted loop", calls.Load()) + } +}