Skip to main content

engenho_controllers/
watch_driver.rs

1//! `WatchDriver` — event-driven controller wakeup.
2//!
3//! Wraps any [`Controller`] + an `Arc<StoreMesh>`. Subscribes to
4//! `store.watch()` (the live-tail [`WatchStream`]); when a signal of
5//! interest arrives, calls `controller.tick()`. Includes a periodic
6//! fallback tick so missed signals don't strand the controller.
7//!
8//! ## Why
9//!
10//! Pre-C2 every controller polled at a fixed interval — typically
11//! 30s in production. After C2, controllers can react in
12//! microseconds to a commit. `WatchDriver` is the canonical glue.
13//!
14//! ## Filtering
15//!
16//! Each driver instance carries a [`KindFilter`] declaring which
17//! resource kinds it cares about. The driver only wakes the
18//! controller for matching events; everything else is dropped
19//! before the controller sees it. Bookmarks are progress markers, not
20//! state changes — they never wake the controller.
21//!
22//! ## Backpressure (M0.1 item 3 — resumable watch backend)
23//!
24//! The per-watcher stream surfaces a typed
25//! [`engenho_store::WatchGone`] terminal instead of a silent
26//! `broadcast::RecvError::Lagged`. On `WatchGone::Overflow` the driver
27//! ticks once (the periodic fallback would catch it eventually, but we
28//! don't want to wait) AND RE-ESTABLISHES the stream from the live
29//! tail — the controller's `tick()` reads current state, so a fresh
30//! live-tail subscription is a correct (if coarse) recovery: the next
31//! commit wakes it again, and the immediate tick covers the gap. On
32//! `WatchGone::CompactedTooOld` (only reachable via `watch_from`, not
33//! the live-tail shim) the driver likewise re-subscribes + ticks.
34//!
35//! ## Coalescing
36//!
37//! Events frequently bunch: a single kubectl apply produces N
38//! create events; without coalescing the controller ticks N
39//! times. `WatchDriver` collects events in a short debounce
40//! window (default 50ms) + ticks once per window when at least
41//! one event matched.
42//!
43//! ## Requeue: one slot per driver
44//!
45//! A controller asks to be ticked again by returning
46//! `ReconcileResult::Requeue(after)`; a Transient error asks the same
47//! thing implicitly. Both become ONE deadline in a `RequeueSlot` owned
48//! by the loop — never a task. [`next_wake`] is the single decision
49//! (outcome → delay); the slot is cleared when any tick starts, because a
50//! tick is a full sweep and satisfies whatever was pending, then re-armed
51//! from that tick's outcome. `wait_for_relevant_event` sleeps until the
52//! earlier of the fallback and the slot's deadline.
53//!
54//! ## Retries grow
55//!
56//! A Transient failure's targeted retry is read off [`TRANSIENT_RETRY`]
57//! (1 s doubling to 60 s) at the driver's count of consecutive failed
58//! ticks, which any `Ok` resets — upstream's per-item rate limiter,
59//! per driver. A re-subscribe after the stream ends is read off
60//! [`RESUBSCRIBE`] (100 ms doubling to 30 s), reset by a delivered event.
61//! Both are one [`Curve`]; neither is a flat retry, because a flat retry
62//! against a store that is down is a hot loop for as long as it is down.
63//!
64//! So a driver has at most one pending re-tick and at most one tick in
65//! flight, whatever the controller returns. The previous shape spawned a
66//! detached sleep-then-tick task per requeue: every such tick armed
67//! another, so each event or fallback tick left behind a chain that
68//! re-armed itself forever, and the chains ran `tick` concurrently. The
69//! tick rate grew with uptime, and a sleeping chain kept its
70//! `Arc<StoreMesh>` alive past `handle.abort()`.
71//!
72//! ## The loop cannot return (T2.6)
73//!
74//! [`WatchDriver::run`] is `-> Infallible`. A driver loop that returns is a
75//! type error (E0308), not a silent retirement: the only ways a driver task
76//! ends are a panic and an abort, and the runtime's supervisor observes both.
77//! There is no `spawn()` here any more — the caller spawns the future into
78//! whatever owns it (the runtime's child set in production), so no driver is
79//! detached with nobody holding its join handle.
80//!
81//! Every tick is recorded in the driver's [`Heartbeat`]: when it began and
82//! ended and how it ended, readable without a lock by whoever supervises it.
83//!
84//! ## A panic in a tick (T2.7)
85//!
86//! What a tick's panic does is decided by the driver's
87//! [`WatchDriverConfig::tick_state`] — see [`crate::contain`]. A
88//! [`TickState::Stateless`] tick is contained: the panic becomes
89//! [`ControllerError::Panicked`], is counted in the heartbeat, gets no
90//! targeted retry, and the next event or the fallback re-ticks it. A
91//! [`TickState::Stateful`] tick is not: the panic ends the driver's task,
92//! which the task's owner sees and marks Dead. The default is Stateful.
93
94use std::convert::Infallible;
95use std::sync::Arc;
96use std::time::Duration;
97
98use engenho_store::{StoreMesh, WatchEvent, WatchGone, WatchSignal, WatchStream};
99use tokio::time::Instant;
100use tracing::{debug, info, warn};
101
102use shigoto_types::failure::FailureKind;
103
104use crate::contain::{TickState, contained};
105use crate::controller::{Controller, ReconcileOutcome};
106use crate::curve::{Curve, Streak};
107use crate::error::ControllerError;
108use crate::heartbeat::{Heartbeat, TickClass};
109
110/// Filter: which resource kinds wake this driver's controller?
111#[derive(Clone, Debug)]
112pub enum KindFilter {
113    /// Wake on any committed mutation.
114    All,
115    /// Wake only on events whose `key.kind` is in the list. Match
116    /// is case-sensitive — pass canonical K8s kind names
117    /// ("Pod", "`ReplicaSet`", "Service", …).
118    Kinds(Vec<String>),
119}
120
121impl KindFilter {
122    /// Convenience: filter for a single kind.
123    #[must_use]
124    pub fn kind(name: impl Into<String>) -> Self {
125        Self::Kinds(vec![name.into()])
126    }
127
128    /// Whether an event on an object of `kind` wakes the controller.
129    #[must_use]
130    pub fn wakes_on(&self, kind: &str) -> bool {
131        match self {
132            Self::All => true,
133            Self::Kinds(list) => list.iter().any(|k| k == kind),
134        }
135    }
136
137    /// Whether no event can wake the controller: it runs on its fallback
138    /// alone.
139    #[must_use]
140    pub fn wakes_on_nothing(&self) -> bool {
141        matches!(self, Self::Kinds(list) if list.is_empty())
142    }
143
144    fn matches(&self, ev: &WatchEvent) -> bool {
145        self.wakes_on(&ev.key.kind)
146    }
147}
148
149#[derive(Clone, Debug)]
150pub struct WatchDriverConfig {
151    /// Filter for which events wake the controller.
152    pub filter: KindFilter,
153    /// Debounce window: events arriving within this window
154    /// coalesce into one tick. Default 50ms.
155    pub debounce: Duration,
156    /// Periodic fallback tick — runs even with zero events,
157    /// covering missed events (Lagged) + cold start. Default
158    /// 30s. Set to `Duration::MAX` to disable. This is upstream's
159    /// informer `resyncPeriod` / kubelet housekeeping ticker: with no
160    /// events at all the controller still runs.
161    pub fallback_interval: Duration,
162    /// How long one `tick()` may run before the driver starts reporting
163    /// it as BLOCKED, once per window, until it returns.
164    ///
165    /// The tick is **never cancelled**. Upstream does not cancel a slow
166    /// `syncLoop` either — it fails `/healthz`'s `syncLoop` check (no
167    /// iteration within `2 * SyncFrequency`) so the process is visibly
168    /// unhealthy and gets restarted. Cancelling mid-tick here would drop
169    /// a `start()` that already spawned a process, leaving a running
170    /// container with no local record — a worse state than a slow one.
171    pub stuck_tick_after: Duration,
172    /// Whether the controller's tick leaves in-memory state the next tick
173    /// relies on, which decides what a panic in a tick does (T2.7).
174    /// Stateless: contained, counted, re-ticked by the next event or the
175    /// fallback. Stateful: the panic ends the driver's task.
176    ///
177    /// Default Stateful: wrong in that direction costs availability, wrong
178    /// in the other costs correctness. The runtime sets it from its child
179    /// catalog.
180    pub tick_state: TickState,
181}
182
183impl Default for WatchDriverConfig {
184    fn default() -> Self {
185        Self {
186            filter: KindFilter::All,
187            debounce: Duration::from_millis(50),
188            fallback_interval: Duration::from_secs(30),
189            stuck_tick_after: Duration::from_secs(120),
190            tick_state: TickState::Stateful,
191        }
192    }
193}
194
195/// The driver. Owns a `Controller` + an `Arc<StoreMesh>` +
196/// configuration + the [`Heartbeat`] its ticks are recorded in.
197/// [`WatchDriver::run`] is the event loop.
198pub struct WatchDriver<C: Controller> {
199    controller: Arc<C>,
200    store: Arc<StoreMesh>,
201    config: WatchDriverConfig,
202    beat: Arc<Heartbeat>,
203}
204
205impl<C: Controller + 'static> WatchDriver<C> {
206    #[must_use]
207    pub fn new(controller: C, store: Arc<StoreMesh>, config: WatchDriverConfig) -> Self {
208        Self {
209            controller: Arc::new(controller),
210            store,
211            config,
212            beat: Arc::new(Heartbeat::new()),
213        }
214    }
215
216    /// The heartbeat this driver's ticks are recorded in. Take it before
217    /// [`run`](Self::run) consumes the driver.
218    #[must_use]
219    pub fn heartbeat(&self) -> Arc<Heartbeat> {
220        self.beat.clone()
221    }
222
223    /// Which events wake this driver's controller. Read it before
224    /// [`run`](Self::run) consumes the driver.
225    #[must_use]
226    pub fn wakes(&self) -> &KindFilter {
227        &self.config.filter
228    }
229
230    /// The event loop. It never returns: the `Infallible` output makes a
231    /// loop that ends a type error. The task running it ends only by panic
232    /// or abort — the caller owns the task and sees both.
233    pub async fn run(self) -> Infallible {
234        run(self.controller, self.store, self.config, self.beat).await
235    }
236
237    /// One tick of the inner controller — useful in tests where
238    /// the caller wants synchronous reconcile without the event
239    /// loop. Returns the typed [`ReconcileOutcome`] (report + requeue
240    /// decision).
241    pub async fn tick_once(
242        &self,
243    ) -> Result<crate::controller::ReconcileOutcome, crate::error::ControllerError> {
244        self.controller.tick().await
245    }
246}
247
248/// How fast the driver re-subscribes after the stream ends: 100 ms
249/// doubling to 30 s, reset when a subscription delivers an event.
250///
251/// Upstream's reflector wraps `ListAndWatch` in `wait.BackoffUntil`, so a
252/// store that keeps ending the subscription is retried forever but never
253/// hot-looped. Same shape, same reason.
254pub const RESUBSCRIBE: Curve = Curve::from_millis::<100, 30_000>();
255
256/// The targeted retry after a Transient failure: 1 s doubling to 60 s,
257/// indexed by the driver's [`ConsecutiveFailures`] and reset by any `Ok`.
258///
259/// Upstream's controller workqueue does the same per item (5 ms doubling
260/// to 1000 s); this is per driver, because a driver's tick is a full sweep
261/// and its failure is the sweep's. The cap sits above the default 30 s
262/// fallback on purpose: a driver that has failed for a minute is re-ticked
263/// by its events and its fallback, not by a retry of its own.
264pub const TRANSIENT_RETRY: Curve = Curve::from_millis::<1_000, 60_000>();
265
266/// Where the loop gets its live-tail subscription.
267///
268/// Production is [`StoreMesh`]. The seam exists so the loop's scheduling —
269/// the requeue slot, the fallback, the re-subscribe path — can be driven
270/// under paused time by a feed the test controls, with no Raft group
271/// behind it. The loop owns an `Arc` of the source for its lifetime, so
272/// aborting the driver still drops the store clone it held.
273#[async_trait::async_trait]
274trait WatchSource: Send + Sync {
275    async fn watch(&self) -> Result<WatchStream, WatchGone>;
276}
277
278#[async_trait::async_trait]
279impl WatchSource for StoreMesh {
280    async fn watch(&self) -> Result<WatchStream, WatchGone> {
281        StoreMesh::watch(self).await
282    }
283}
284
285/// Subscribe, sleeping `delay` first (zero on the initial attempt).
286///
287/// Returns `None` when the store refuses a subscription; the caller keeps
288/// looping on its timers and tries again, exactly as `BackoffUntil`
289/// re-enters `ListAndWatch`.
290async fn subscribe<S: WatchSource + ?Sized>(
291    source: &S,
292    controller: &'static str,
293    delay: Duration,
294) -> Option<WatchStream> {
295    if !delay.is_zero() {
296        tokio::time::sleep(delay).await;
297    }
298    match source.watch().await {
299        Ok(s) => Some(s),
300        Err(e) => {
301            warn!(
302                controller,
303                error = %e,
304                "watch subscribe failed; fallback-tick only until the next attempt"
305            );
306            None
307        }
308    }
309}
310
311/// Re-subscribe after the stream ended or was refused, waiting the delay
312/// the next miss on `attempts` owes first.
313async fn resubscribe<S: WatchSource + ?Sized>(
314    source: &S,
315    controller: &'static str,
316    attempts: &mut Streak,
317) -> Option<WatchStream> {
318    subscribe(source, controller, attempts.miss()).await
319}
320
321async fn run<C: Controller + ?Sized + 'static, S: WatchSource + ?Sized>(
322    controller: Arc<C>,
323    store: Arc<S>,
324    config: WatchDriverConfig,
325    beat: Arc<Heartbeat>,
326) -> Infallible {
327    // Every field is bound by name, with no `..`: a field added to
328    // WatchDriverConfig does not compile here (E0027) until the loop
329    // consumes it — a config knob nothing reads cannot ship.
330    let WatchDriverConfig {
331        filter,
332        debounce,
333        fallback_interval,
334        stuck_tick_after,
335        tick_state,
336    } = config;
337    let name = controller.name();
338    let mut rx = subscribe(store.as_ref(), name, Duration::ZERO).await;
339    // Re-subscribes since the last delivered event: reset whenever a
340    // subscription actually delivers one — upstream resets its backoff on
341    // a watch that made progress.
342    let mut resubscribes = Streak::new(RESUBSCRIBE);
343    // The ONE pending re-tick this driver may have, and its failed ticks
344    // in a row. Every tick below goes through `ticker.tick()`, which
345    // clears the slot and re-arms it; nothing else can schedule a tick, so
346    // there is no second one to pile up.
347    let mut ticker = Ticker {
348        controller,
349        stuck_after: stuck_tick_after,
350        tick_state,
351        slot: RequeueSlot::default(),
352        failures: ConsecutiveFailures::default(),
353        beat,
354    };
355
356    info!(
357        controller = name,
358        debounce_ms = millis(debounce),
359        fallback_s = if fallback_interval == Duration::MAX {
360            0
361        } else {
362            fallback_interval.as_secs()
363        },
364        "watch driver started"
365    );
366
367    // ── THE LOOP NEVER RETURNS ─────────────────────────────────────────
368    //
369    // And it cannot: `run` is `-> Infallible`, so a `break` or `return`
370    // here is a type error. There is deliberately no in-band stop: stopping
371    // is aborting the task that runs this future, which is upstream's
372    // `stopCh` — a channel SEPARATE from the data. Conflating the two is what this
373    // loop used to do and what retired a controller for 12 hours:
374    //
375    //   1. a coalescing drain consumed the stream's one-shot terminal,
376    //   2. the drained stream then yielded `None` forever,
377    //   3. `None` was read as `Shutdown`, and `run` RETURNED.
378    //
379    // Nothing logged an error, nothing supervised the task, and the three
380    // other controllers kept ticking, so the daemon looked healthy while
381    // no pod on the node could be started, restarted or reaped. The
382    // `Shutdown` variant is gone: a data stream ending is a RE-SUBSCRIBE,
383    // the way a closed `ResultChan` sends upstream's reflector back
384    // through `ListAndWatch`.
385    // A driver no event can wake is a poller, and a poller polls first: its
386    // first pass is at start, not one whole fallback later. Without it a
387    // node-declared manifest waited ten seconds after boot to be applied,
388    // and three passes needed thirty seconds and change.
389    if filter.wakes_on_nothing() {
390        ticker.tick().await;
391    }
392    loop {
393        match wait_for_relevant_event(rx.as_mut(), &filter, fallback_interval, ticker.slot).await {
394            EventOrTimer::Event => {
395                resubscribes.reset();
396                // Coalesce the burst, then tick once.
397                tokio::time::sleep(debounce).await;
398                // A terminal can surface mid-drain. It is returned, never
399                // swallowed: the stream emits it EXACTLY ONCE, so dropping
400                // it here is how the subscription became silently dead.
401                let gone = rx
402                    .as_mut()
403                    .and_then(|stream| drain_pending(stream, name, &filter));
404                ticker.tick().await;
405                if let Some(gone) = gone {
406                    warn!(
407                        controller = name,
408                        gone = %gone,
409                        "watch stream gone while coalescing; re-subscribing"
410                    );
411                    rx = resubscribe(store.as_ref(), name, &mut resubscribes).await;
412                }
413            }
414            EventOrTimer::Gone(gone) => {
415                warn!(
416                    controller = name,
417                    gone = %gone,
418                    "watch stream gone; ticking + re-subscribing"
419                );
420                ticker.tick().await;
421                rx = resubscribe(store.as_ref(), name, &mut resubscribes).await;
422            }
423            EventOrTimer::StreamEnded => {
424                // NOT a shutdown. The subscription is over — the terminal
425                // was already delivered, or the store dropped the sender —
426                // and the controller still owns its resources.
427                warn!(
428                    controller = name,
429                    "watch stream ended; ticking + re-subscribing (not a shutdown)"
430                );
431                ticker.tick().await;
432                rx = resubscribe(store.as_ref(), name, &mut resubscribes).await;
433            }
434            wake @ (EventOrTimer::Requeue | EventOrTimer::FallbackTimer) => {
435                debug!(controller = name, ?wake, "timer wake");
436                ticker.tick().await;
437                // Either timer is the retry point for a refused
438                // subscription. Both must be: with a requeue due every
439                // second, the fallback (restarted on every wait) never
440                // fires, and a driver that re-subscribed only on the
441                // fallback would stay stream-less forever.
442                if rx.is_none() {
443                    rx = resubscribe(store.as_ref(), name, &mut resubscribes).await;
444                }
445            }
446        }
447    }
448}
449
450/// A driver's run of failed ticks in a row, read against
451/// [`TRANSIENT_RETRY`]. One per driver loop, owned by it; [`next_wake`]
452/// is the only thing that advances or resets it.
453///
454/// The curve is fixed by construction — there is no way to build one on a
455/// different curve — so every driver retries on the same schedule.
456#[derive(Debug, Clone, Copy, PartialEq, Eq)]
457pub struct ConsecutiveFailures(Streak);
458
459impl Default for ConsecutiveFailures {
460    fn default() -> Self {
461        Self(Streak::new(TRANSIENT_RETRY))
462    }
463}
464
465impl ConsecutiveFailures {
466    /// Failed ticks since the last `Ok`.
467    #[must_use]
468    pub const fn count(&self) -> u32 {
469        self.0.misses()
470    }
471}
472
473/// When the driver should tick again ON ITS OWN, given how the last tick
474/// ended — and fold that tick into the driver's `failures`. The one
475/// decision every self-scheduled re-tick goes through, in both drivers
476/// ([`WatchDriver`] and [`crate::ControllerRuntime`]).
477///
478///   * `Ok` + `Done` → `None`: the next event or the fallback wakes it.
479///   * `Ok` + `Requeue(d)` / `RequeueWithProgress(d)` → `Some(d)`.
480///   * `Err`, Declarative → `None`: a broken declaration does not fix
481///     itself by being retried. It is surfaced, and the next event or
482///     the fallback still re-ticks it coarsely.
483///   * `Err`, Transient → a targeted retry at [`TRANSIENT_RETRY`]'s next
484///     step: 1 s after the first failure in a row, doubling to 60 s.
485///
486/// Every `Ok` resets `failures`; every `Err`, of either class, extends it,
487/// so a Transient failure after a run of Declarative ones is retried as
488/// the Nth failure in a row, which it is.
489#[must_use]
490pub fn next_wake(
491    result: &Result<ReconcileOutcome, ControllerError>,
492    failures: &mut ConsecutiveFailures,
493) -> Option<Duration> {
494    match result {
495        Ok(outcome) => {
496            failures.0.reset();
497            outcome.result.requeue_after()
498        }
499        Err(e) => {
500            let owed = failures.0.miss();
501            match e.classify() {
502                FailureKind::Declarative => None,
503                FailureKind::Transient => Some(owed),
504                // `FailureKind` is `#[non_exhaustive]`, so a class shigoto
505                // adds later lands here. It is retried on the same growing
506                // curve — kept trying, never faster than a Transient — and
507                // never at a flat delay.
508                #[allow(
509                    clippy::match_same_arms,
510                    reason = "the known class and the unknown ones are separate decisions that happen to agree today"
511                )]
512                _ => Some(owed),
513            }
514        }
515    }
516}
517
518/// Log how a tick ended and what `wake` (its [`next_wake`]) will do
519/// about it. Shared by both drivers so the two loops cannot describe the
520/// same outcome differently.
521pub(crate) fn log_tick(
522    controller: &'static str,
523    result: &Result<ReconcileOutcome, ControllerError>,
524    wake: Option<Duration>,
525) {
526    match (result, wake) {
527        (Ok(outcome), None) => outcome.log(controller),
528        (Ok(outcome), Some(after)) => {
529            outcome.log(controller);
530            debug!(
531                controller,
532                after_ms = millis(after),
533                "controller requested requeue"
534            );
535        }
536        (Err(ControllerError::Panicked(panic)), _) => tracing::error!(
537            controller,
538            %panic,
539            "reconcile tick PANICKED and was contained (stateless); no targeted retry \u{2014} \
540             the next event or the fallback re-ticks it"
541        ),
542        (Err(e), None) => tracing::error!(
543            controller,
544            error = %e,
545            "reconcile failed (declarative — surfacing, not scheduling a targeted retry)"
546        ),
547        (Err(e), Some(after)) => warn!(
548            controller,
549            error = %e,
550            after_ms = millis(after),
551            "reconcile failed (transient — scheduling a targeted retry)"
552        ),
553    }
554}
555
556/// A duration as whole milliseconds for a log field, saturating rather
557/// than truncating: `Duration::MAX` does not fit in a `u64` of millis.
558fn millis(d: Duration) -> u64 {
559    u64::try_from(d.as_millis()).unwrap_or(u64::MAX)
560}
561
562/// The driver's ONE pending re-tick: a deadline held by the loop, never
563/// a task.
564///
565/// Owned by `run`'s [`Ticker`]: only [`Ticker::tick`] writes it, and
566/// `wait_for_relevant_event` gets a copy to sleep on. There is no
567/// second holder of a pending re-tick, so there is nothing to pile up.
568#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
569struct RequeueSlot {
570    at: Option<Instant>,
571}
572
573impl RequeueSlot {
574    /// A tick is a full sweep: whatever was pending is satisfied by it.
575    fn clear(&mut self) {
576        self.at = None;
577    }
578
579    /// Hold a re-tick at `deadline`. The earlier deadline wins, so arming
580    /// can never push a due re-tick further out.
581    fn arm(&mut self, deadline: Instant) {
582        self.at = Some(self.at.map_or(deadline, |at| at.min(deadline)));
583    }
584
585    /// Sleep until the deadline; pend forever when nothing is armed.
586    async fn due(self) {
587        match self.at {
588            Some(at) => tokio::time::sleep_until(at).await,
589            None => std::future::pending::<()>().await,
590        }
591    }
592}
593
594/// What `run` ticks through: the controller, the one requeue slot, the
595/// driver's failed ticks in a row, and the heartbeat every tick is recorded
596/// in. `tick` is the ONLY way `run` ticks.
597struct Ticker<C: Controller + ?Sized + 'static> {
598    controller: Arc<C>,
599    stuck_after: Duration,
600    tick_state: TickState,
601    slot: RequeueSlot,
602    failures: ConsecutiveFailures,
603    beat: Arc<Heartbeat>,
604}
605
606impl<C: Controller + ?Sized + 'static> Ticker<C> {
607    /// Tick through the slot: clear it, tick, log, re-arm from the outcome
608    /// (which also advances or resets the failure streak).
609    ///
610    /// A requeue far enough out that the deadline does not fit in an
611    /// `Instant` is left unarmed — it is further away than the fallback
612    /// anyway.
613    async fn tick(&mut self) {
614        self.slot.clear();
615        self.beat.begin();
616        let result = tick_observed(&self.controller, self.stuck_after, self.tick_state).await;
617        self.beat.end(TickClass::of(&result));
618        let wake = next_wake(&result, &mut self.failures);
619        log_tick(self.controller.name(), &result, wake);
620        if let Some(deadline) = wake.and_then(|after| Instant::now().checked_add(after)) {
621            self.slot.arm(deadline);
622        }
623    }
624}
625
626#[derive(Debug)]
627enum EventOrTimer {
628    Event,
629    /// The stream terminated with a typed [`WatchGone`] — tick + resub.
630    Gone(WatchGone),
631    /// The slot's deadline came first: the re-tick the last outcome asked
632    /// for.
633    Requeue,
634    FallbackTimer,
635    /// The subscription is over with no terminal left to read: the
636    /// one-shot [`WatchGone`] was already consumed, or the store dropped
637    /// the sender. It means RE-SUBSCRIBE, and it is spelled that way so
638    /// nobody can read it as a stop again — there is no `Shutdown`
639    /// variant to fall into. Stopping a driver is aborting its task, out
640    /// of band, the way upstream keeps `stopCh` separate from
641    /// `ResultChan`.
642    StreamEnded,
643}
644
645/// Wait for the first of: a matching event (or the stream's end), the
646/// requeue slot's deadline, the fallback. That is, sleep until
647/// `min(fallback, requeue)` unless the stream says something first.
648async fn wait_for_relevant_event(
649    rx: Option<&mut WatchStream>,
650    filter: &KindFilter,
651    fallback_interval: Duration,
652    slot: RequeueSlot,
653) -> EventOrTimer {
654    let fallback = tokio::time::sleep(fallback_interval);
655    tokio::pin!(fallback);
656    let requeue = slot.due();
657    tokio::pin!(requeue);
658
659    // No live stream → only the timers can fire.
660    let Some(rx) = rx else {
661        return tokio::select! {
662            biased;
663            () = &mut requeue => EventOrTimer::Requeue,
664            () = &mut fallback => EventOrTimer::FallbackTimer,
665        };
666    };
667
668    loop {
669        tokio::select! {
670            biased;
671            res = rx.next() => match res {
672                Some(Ok(WatchSignal::Event(ev))) => {
673                    if filter.matches(&ev) {
674                        return EventOrTimer::Event;
675                    }
676                    // Else loop — wait for the next signal.
677                }
678                // Bookmarks are progress markers, never wake the
679                // controller (no state change to reconcile).
680                Some(Ok(WatchSignal::Bookmark(_))) => {}
681                Some(Err(gone)) => return EventOrTimer::Gone(gone),
682                None => return EventOrTimer::StreamEnded,
683            },
684            () = &mut requeue => return EventOrTimer::Requeue,
685            () = &mut fallback => return EventOrTimer::FallbackTimer,
686        }
687    }
688}
689
690/// Drain whatever signals are already buffered (non-blocking), logging
691/// coalesced matching events.
692///
693/// Returns the terminal [`WatchGone`] if one surfaced, because the stream
694/// emits it **exactly once** and `try_next` CONSUMES it — after which the
695/// stream yields `None` forever. The previous version matched `Err(_) =>
696/// break` under a comment claiming it left the terminal "for the next
697/// `wait_for_relevant_event`". It did not: the value was already gone,
698/// the next wait saw `None`, and the driver retired the controller.
699/// Handing it back is what lets the coalescing path recover.
700#[must_use = "the terminal is one-shot: drop it and the subscription is silently dead"]
701fn drain_pending(
702    stream: &mut WatchStream,
703    controller_name: &'static str,
704    filter: &KindFilter,
705) -> Option<WatchGone> {
706    while let Some(item) = stream.try_next() {
707        match item {
708            Ok(WatchSignal::Event(ev)) => {
709                if filter.matches(&ev) {
710                    debug!(controller = controller_name, key = %ev.key.label(), "coalesced event");
711                }
712            }
713            Ok(WatchSignal::Bookmark(_)) => {}
714            Err(gone) => return Some(gone),
715        }
716    }
717    None
718}
719
720/// Run one `tick()`, contained when `tick_state` is Stateless, and reported
721/// as blocked while it has not returned.
722///
723/// A Stateless tick's panic comes back as [`ControllerError::Panicked`]; a
724/// Stateful tick's panic unwinds out of here and ends the driver's task
725/// (see [`crate::contain`]). The tick future is built inside the contained
726/// block, so a `tick` that panics before returning its future is contained
727/// too.
728async fn tick_observed<C: Controller + ?Sized + 'static>(
729    controller: &Arc<C>,
730    stuck_after: Duration,
731    tick_state: TickState,
732) -> Result<ReconcileOutcome, ControllerError> {
733    let name = controller.name();
734    let tick = async { controller.tick().await };
735    match tick_state {
736        TickState::Stateless => match observed(name, contained(tick), stuck_after).await {
737            Ok(result) => result,
738            Err(panic) => Err(ControllerError::Panicked(panic)),
739        },
740        TickState::Stateful => observed(name, tick, stuck_after).await,
741    }
742}
743
744/// Run `tick` to completion, reporting it at ERROR once per `stuck_after`
745/// window while it has not returned — and **never cancelling it**.
746///
747/// `tokio::time::timeout` takes `&mut fut`, so an elapsed window does not
748/// drop the tick; it only lets us say so. This is the kubelet
749/// `syncLoopHealthCheck` shape: upstream does not abort a slow sync, it
750/// makes the stall VISIBLE. A tick that hangs forever now produces a
751/// repeating ERROR naming the controller and the elapsed seconds, instead
752/// of the total silence that hid this defect for 12 hours.
753async fn observed<F: std::future::Future>(
754    controller: &'static str,
755    tick: F,
756    stuck_after: Duration,
757) -> F::Output {
758    let started = std::time::Instant::now();
759    tokio::pin!(tick);
760    loop {
761        if let Ok(outcome) = tokio::time::timeout(stuck_after, &mut tick).await {
762            return outcome;
763        }
764        tracing::error!(
765            controller,
766            elapsed_s = started.elapsed().as_secs(),
767            "reconcile tick has NOT returned; this controller is blocked (not cancelled \u{2014} cancelling mid-tick would strand side effects)"
768        );
769    }
770}
771
772#[cfg(test)]
773mod tests {
774    use super::*;
775    use serde_json::Value;
776
777    fn ev(kind: &str, name: &str) -> WatchEvent {
778        use engenho_store::ResourceKey;
779        WatchEvent {
780            kind: engenho_store::WatchEventKind::Added,
781            object: Value::Null,
782            key: ResourceKey::namespaced("", "v1", kind, "default", name),
783            resource_version: 1,
784        }
785    }
786
787    #[test]
788    fn kind_filter_all_matches_anything() {
789        let f = KindFilter::All;
790        assert!(f.matches(&ev("Pod", "x")));
791        assert!(f.matches(&ev("Service", "x")));
792    }
793
794    #[test]
795    fn kind_filter_specific_matches_only_listed() {
796        let f = KindFilter::Kinds(vec!["Pod".into(), "Endpoints".into()]);
797        assert!(f.matches(&ev("Pod", "x")));
798        assert!(f.matches(&ev("Endpoints", "x")));
799        assert!(!f.matches(&ev("Service", "x")));
800    }
801
802    #[test]
803    fn kind_filter_kind_helper() {
804        let f = KindFilter::kind("Pod");
805        assert!(f.matches(&ev("Pod", "p")));
806        assert!(!f.matches(&ev("Node", "n")));
807    }
808
809    #[test]
810    fn config_default_is_sensible() {
811        let cfg = WatchDriverConfig::default();
812        assert_eq!(cfg.debounce, Duration::from_millis(50));
813        assert_eq!(cfg.fallback_interval, Duration::from_secs(30));
814        assert!(matches!(cfg.filter, KindFilter::All));
815    }
816
817    // ── The 2026-09-18 ryn defect, sealed ──────────────────────────────
818    //
819    // engenho's kubelet controller stopped reconciling for 12 hours and
820    // nothing said so. The chain was:
821    //
822    //   1. a burst overflowed the kubelet's watch buffer, arming the
823    //      stream's ONE-SHOT terminal;
824    //   2. the coalescing drain read it with `try_next` and matched
825    //      `Err(_) => break`, under a comment claiming it left the
826    //      terminal "for the next wait_for_relevant_event";
827    //   3. the terminal was in fact CONSUMED, so the stream yielded
828    //      `None` forever;
829    //   4. `None` was mapped to `EventOrTimer::Shutdown` and `run`
830    //      RETURNED — retiring the controller permanently.
831    //
832    // Nothing logged an error. The driver task was never joined. Three
833    // other controllers kept ticking, so the daemon read as healthy while
834    // no pod on the node could start, restart or be reaped. The only
835    // evidence was the ABSENCE of one log line.
836    //
837    // These two tests pin the load-bearing half: the terminal comes back
838    // to the caller. The other half — a stream ending means re-subscribe,
839    // never stop — is enforced by there being no `Shutdown` variant left
840    // to return.
841
842    use engenho_store::watch_backend::WatcherRegistry;
843    use engenho_store::{Change, ChangeKind, ResourceKey, Revision, VersionMeta, WatchOpts};
844
845    fn change(rev: u64) -> Change {
846        change_at(Revision(rev))
847    }
848
849    fn change_at(r: Revision) -> Change {
850        Change {
851            revision: r,
852            key: ResourceKey::namespaced("", "v1", "Pod", "default", "p1"),
853            kind: ChangeKind::Put,
854            value: serde_json::json!({"spec": {}}),
855            prior: None,
856            version_meta: VersionMeta::created_at(r),
857        }
858    }
859
860    /// A tiny buffer plus a burst is exactly the production trigger.
861    fn overflowed_stream() -> WatchStream {
862        let mut reg = WatcherRegistry::new();
863        let stream = reg.register_captured(
864            Vec::new(),
865            Revision::ZERO,
866            &WatchOpts {
867                from: Revision::ZERO,
868                buffer: 2,
869                bookmark_every: Duration::ZERO,
870            },
871        );
872        for rev in 1..=8 {
873            reg.fan_change(&change(rev));
874        }
875        stream
876    }
877
878    #[test]
879    fn a_terminal_reached_while_coalescing_is_returned_to_the_caller() {
880        let mut stream = overflowed_stream();
881
882        let gone = drain_pending(&mut stream, "t", &KindFilter::All);
883
884        assert!(
885            gone.is_some(),
886            "the drain consumed the one-shot terminal and reported nothing; \
887             that is the exact swallow that retired the kubelet"
888        );
889        assert!(matches!(gone, Some(WatchGone::Overflow { .. })));
890    }
891
892    /// Why returning it is not merely tidier: once drained, the stream is
893    /// finished. If the caller does not act on what `drain_pending` hands
894    /// back, there is nothing left to notice the subscription is dead.
895    #[tokio::test]
896    async fn the_drained_stream_is_finished_so_the_terminal_is_the_only_notice() {
897        let mut stream = overflowed_stream();
898
899        let _ = drain_pending(&mut stream, "t", &KindFilter::All);
900
901        assert!(
902            stream.next().await.is_none(),
903            "expected the stream to be over after its terminal was read"
904        );
905    }
906
907    // ── T2.1: one requeue slot per driver ──────────────────────────────
908    //
909    // The shape this replaces spawned a detached sleep-then-tick task for
910    // every requeue. The re-tick armed another, so every event or fallback
911    // tick of a requeueing controller left behind a chain that re-armed
912    // itself forever: ~120 new chains an hour from the 30 s fallback
913    // alone, plus one per event, all running `tick` concurrently. The tick
914    // rate grew with uptime. On plo a Transient failure retried ~3.5x/s
915    // against an advertised 1 s backoff.
916    //
917    // These tests drive the real `run` loop for one VIRTUAL hour under
918    // paused time: an event every 5 s, a 30 s fallback, and a tick that
919    // takes 100 ms (it does I/O — which is what lets concurrent ticks
920    // overlap at all).
921
922    use std::sync::Mutex;
923    use std::sync::atomic::{AtomicUsize, Ordering};
924
925    use crate::controller::{ReconcileReport, ReconcileResult};
926
927    const HOUR: Duration = Duration::from_secs(3600);
928    const EVENT_EVERY: Duration = Duration::from_secs(5);
929    const FALLBACK: Duration = Duration::from_secs(30);
930    const TICK_TAKES: Duration = Duration::from_millis(100);
931    const REQUEUE_AFTER: Duration = Duration::from_secs(1);
932
933    const EVENTS: u64 = HOUR.as_secs() / EVENT_EVERY.as_secs();
934    const FALLBACKS: u64 = HOUR.as_secs() / FALLBACK.as_secs();
935    /// Every tick an event or the fallback explains on its own: 720 + 120.
936    const WITHOUT_TARGETED_RETRY: u64 = EVENTS + FALLBACKS;
937    /// What ONE slot can reach at most: one re-tick per requeue interval,
938    /// plus every event and every fallback — 3600 + 720 + 120 = 4440.
939    const ONE_SLOT_CEILING: u64 = HOUR.as_secs() / REQUEUE_AFTER.as_secs() + WITHOUT_TARGETED_RETRY;
940    const _: () = assert!(ONE_SLOT_CEILING == 4440, "the plan's bound, derived");
941
942    #[derive(Clone, Copy, Debug)]
943    enum Answer {
944        Done,
945        Requeue(Duration),
946        Transient,
947        Declarative,
948        /// The tick panics (after its sleep, with no lock held).
949        Panic,
950    }
951
952    impl Answer {
953        fn result(self) -> Result<ReconcileOutcome, ControllerError> {
954            match self {
955                Self::Done => Ok(ReconcileOutcome::new(
956                    ReconcileReport::default(),
957                    ReconcileResult::Done,
958                )),
959                Self::Requeue(after) => Ok(ReconcileOutcome::new(
960                    ReconcileReport::default(),
961                    ReconcileResult::Requeue(after),
962                )),
963                Self::Transient => Err(ControllerError::Store(
964                    engenho_store::StoreError::ClientWriteFailed("connection refused".into()),
965                )),
966                Self::Declarative => Err(ControllerError::InvalidResource(
967                    "spec.template is required".into(),
968                )),
969                Self::Panic => panic!("probe tick tripped over a bad object"),
970            }
971        }
972    }
973
974    #[derive(Debug, Default, Clone, Copy)]
975    struct Stats {
976        ticks: u64,
977        in_flight: u64,
978        max_in_flight: u64,
979        last_start: Option<Instant>,
980        /// Longest gap between two consecutive tick starts.
981        max_gap: Duration,
982    }
983
984    /// A controller that always answers the same way and records how it
985    /// was driven.
986    struct Probe {
987        answer: Answer,
988        /// How long one tick takes.
989        takes: Duration,
990        stats: Mutex<Stats>,
991        /// When each tick started, in order.
992        starts: Mutex<Vec<Instant>>,
993    }
994
995    impl Probe {
996        fn new(answer: Answer) -> Arc<Self> {
997            Self::taking(answer, TICK_TAKES)
998        }
999
1000        fn taking(answer: Answer, takes: Duration) -> Arc<Self> {
1001            Arc::new(Self {
1002                answer,
1003                takes,
1004                stats: Mutex::new(Stats::default()),
1005                starts: Mutex::new(Vec::new()),
1006            })
1007        }
1008
1009        fn stats(&self) -> Stats {
1010            *self.stats.lock().unwrap()
1011        }
1012
1013        /// The gaps between consecutive tick starts.
1014        fn gaps(&self) -> Vec<Duration> {
1015            gaps(&self.starts.lock().unwrap())
1016        }
1017    }
1018
1019    fn gaps(at: &[Instant]) -> Vec<Duration> {
1020        at.windows(2).map(|w| w[1] - w[0]).collect()
1021    }
1022
1023    #[async_trait::async_trait]
1024    impl Controller for Probe {
1025        fn name(&self) -> &'static str {
1026            "probe"
1027        }
1028
1029        async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
1030            {
1031                let now = Instant::now();
1032                let mut s = self.stats.lock().unwrap();
1033                if let Some(prev) = s.last_start {
1034                    s.max_gap = s.max_gap.max(now - prev);
1035                }
1036                s.last_start = Some(now);
1037                s.ticks += 1;
1038                s.in_flight += 1;
1039                s.max_in_flight = s.max_in_flight.max(s.in_flight);
1040                self.starts.lock().unwrap().push(now);
1041            }
1042            tokio::time::sleep(self.takes).await;
1043            self.stats.lock().unwrap().in_flight -= 1;
1044            self.answer.result()
1045        }
1046    }
1047
1048    /// The store's live tail reduced to what the loop reads: a registry
1049    /// the test fans changes into, which can refuse subscriptions or end
1050    /// every one it grants.
1051    struct Feed {
1052        state: Mutex<(WatcherRegistry, Revision)>,
1053        refuse_next: AtomicUsize,
1054        accepted: AtomicUsize,
1055        /// Grant each subscription from a registry that is dropped at
1056        /// once, so the stream ends as soon as it is read.
1057        end_every_stream: bool,
1058        /// When each subscription was asked for, in order.
1059        asked: Mutex<Vec<Instant>>,
1060    }
1061
1062    impl Feed {
1063        fn new() -> Arc<Self> {
1064            Self::refusing(0)
1065        }
1066
1067        fn refusing(n: usize) -> Arc<Self> {
1068            Arc::new(Self {
1069                state: Mutex::new((WatcherRegistry::new(), Revision::ZERO)),
1070                refuse_next: AtomicUsize::new(n),
1071                accepted: AtomicUsize::new(0),
1072                end_every_stream: false,
1073                asked: Mutex::new(Vec::new()),
1074            })
1075        }
1076
1077        fn ending_every_stream() -> Arc<Self> {
1078            Arc::new(Self {
1079                state: Mutex::new((WatcherRegistry::new(), Revision::ZERO)),
1080                refuse_next: AtomicUsize::new(0),
1081                accepted: AtomicUsize::new(0),
1082                end_every_stream: true,
1083                asked: Mutex::new(Vec::new()),
1084            })
1085        }
1086
1087        fn emit(&self) {
1088            let mut state = self.state.lock().unwrap();
1089            let (reg, rev) = &mut *state;
1090            *rev = rev.next();
1091            reg.fan_change(&change_at(*rev));
1092        }
1093    }
1094
1095    #[async_trait::async_trait]
1096    impl WatchSource for Feed {
1097        async fn watch(&self) -> Result<WatchStream, WatchGone> {
1098            self.asked.lock().unwrap().push(Instant::now());
1099            let refused = self
1100                .refuse_next
1101                .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |n| n.checked_sub(1))
1102                .is_ok();
1103            if refused {
1104                return Err(WatchGone::CompactedTooOld {
1105                    requested: Revision::ZERO,
1106                    compacted: Revision::ZERO,
1107                });
1108            }
1109            self.accepted.fetch_add(1, Ordering::SeqCst);
1110            let opts = |from| WatchOpts {
1111                from,
1112                buffer: 1024,
1113                bookmark_every: Duration::ZERO,
1114            };
1115            if self.end_every_stream {
1116                // The registry, and with it the stream's sender, is
1117                // dropped on return: the stream reads as ended.
1118                return Ok(WatcherRegistry::new().register_captured(
1119                    Vec::new(),
1120                    Revision::ZERO,
1121                    &opts(Revision::ZERO),
1122                ));
1123            }
1124            let mut state = self.state.lock().unwrap();
1125            let (reg, rev) = &mut *state;
1126            Ok(reg.register_captured(Vec::new(), *rev, &opts(*rev)))
1127        }
1128    }
1129
1130    /// Drive the real loop for one virtual hour: an event every 5 s and a
1131    /// 30 s fallback.
1132    async fn an_hour_of(probe: &Arc<Probe>, feed: &Arc<Feed>) -> Stats {
1133        drive(probe, feed, FALLBACK, Some(EVENT_EVERY), HOUR).await
1134    }
1135
1136    /// Drive the real loop for `run_for` of virtual time, with the given
1137    /// fallback, emitting an event every `event_every` if set.
1138    async fn drive(
1139        probe: &Arc<Probe>,
1140        feed: &Arc<Feed>,
1141        fallback: Duration,
1142        event_every: Option<Duration>,
1143        run_for: Duration,
1144    ) -> Stats {
1145        let config = WatchDriverConfig {
1146            fallback_interval: fallback,
1147            ..WatchDriverConfig::default()
1148        };
1149        let driver = tokio::spawn(run(
1150            probe.clone(),
1151            feed.clone(),
1152            config,
1153            Arc::new(Heartbeat::new()),
1154        ));
1155        let events = event_every.map(|every| {
1156            let feed = feed.clone();
1157            tokio::spawn(async move {
1158                loop {
1159                    tokio::time::sleep(every).await;
1160                    feed.emit();
1161                }
1162            })
1163        });
1164        tokio::time::sleep(run_for).await;
1165        driver.abort();
1166        let _ = driver.await;
1167        if let Some(events) = events {
1168            events.abort();
1169            let _ = events.await;
1170        }
1171        probe.stats()
1172    }
1173
1174    /// Ticks in the first `run_for` of a driver with `filter` and a
1175    /// fallback far longer than that.
1176    async fn ticks_before_the_fallback(filter: KindFilter) -> u64 {
1177        let probe = Probe::new(Answer::Done);
1178        let config = WatchDriverConfig {
1179            filter,
1180            fallback_interval: Duration::from_secs(600),
1181            ..WatchDriverConfig::default()
1182        };
1183        let driver = tokio::spawn(run(
1184            probe.clone(),
1185            Feed::new(),
1186            config,
1187            Arc::new(Heartbeat::new()),
1188        ));
1189        tokio::time::sleep(Duration::from_secs(60)).await;
1190        driver.abort();
1191        let _ = driver.await;
1192        probe.stats().ticks
1193    }
1194
1195    #[tokio::test(start_paused = true)]
1196    async fn a_poller_ticks_at_start_and_an_event_driven_driver_waits() {
1197        assert!(KindFilter::Kinds(Vec::new()).wakes_on_nothing());
1198        assert!(!KindFilter::kind("Pod").wakes_on_nothing());
1199        assert!(!KindFilter::All.wakes_on_nothing());
1200        assert_eq!(
1201            ticks_before_the_fallback(KindFilter::Kinds(Vec::new())).await,
1202            1,
1203            "a driver no event wakes polls first"
1204        );
1205        assert_eq!(
1206            ticks_before_the_fallback(KindFilter::kind("Pod")).await,
1207            0,
1208            "an event-driven driver is woken by its events"
1209        );
1210    }
1211
1212    #[tokio::test(start_paused = true)]
1213    async fn a_controller_that_always_requeues_gets_one_slot_not_a_chain() {
1214        let probe = Probe::new(Answer::Requeue(REQUEUE_AFTER));
1215        let s = an_hour_of(&probe, &Feed::new()).await;
1216
1217        assert_eq!(
1218            s.max_in_flight, 1,
1219            "{} ticks of one controller ran at once; a driver has one slot",
1220            s.max_in_flight
1221        );
1222        assert!(
1223            s.ticks <= ONE_SLOT_CEILING,
1224            "{} ticks in an hour, above the one-slot ceiling of {ONE_SLOT_CEILING}: \
1225             re-ticks are piling up",
1226            s.ticks
1227        );
1228        // …and the requeue is honoured, not swallowed.
1229        assert!(
1230            s.ticks > WITHOUT_TARGETED_RETRY,
1231            "{} ticks is no more than events + fallback explain; the requeue was dropped",
1232            s.ticks
1233        );
1234        assert!(
1235            s.max_gap <= REQUEUE_AFTER + TICK_TAKES + Duration::from_millis(10),
1236            "a {:?} gap between ticks: the 1 s requeue was not kept",
1237            s.max_gap
1238        );
1239    }
1240
1241    #[tokio::test(start_paused = true)]
1242    async fn a_controller_that_always_fails_transiently_gets_one_slot_not_a_chain() {
1243        let probe = Probe::new(Answer::Transient);
1244        assert!(
1245            next_wake(
1246                &Answer::Transient.result(),
1247                &mut ConsecutiveFailures::default()
1248            )
1249            .is_some(),
1250            "precondition: a Transient error is retried"
1251        );
1252        let s = an_hour_of(&probe, &Feed::new()).await;
1253
1254        assert_eq!(
1255            s.max_in_flight, 1,
1256            "{} failing ticks ran at once; retries must share one slot",
1257            s.max_in_flight
1258        );
1259        assert!(
1260            s.ticks <= ONE_SLOT_CEILING,
1261            "{} retries in an hour, above the one-slot ceiling of {ONE_SLOT_CEILING}",
1262            s.ticks
1263        );
1264    }
1265
1266    #[tokio::test(start_paused = true)]
1267    async fn a_declarative_failure_is_ticked_by_events_and_the_fallback_only() {
1268        let probe = Probe::new(Answer::Declarative);
1269        let s = an_hour_of(&probe, &Feed::new()).await;
1270
1271        assert!(
1272            s.ticks <= WITHOUT_TARGETED_RETRY,
1273            "{} ticks: a broken declaration got a targeted retry",
1274            s.ticks
1275        );
1276        // Surfaced, not retired: events still reach the controller. The
1277        // last event lands at the end of the hour, inside its debounce.
1278        assert!(
1279            s.ticks + 1 >= EVENTS,
1280            "{} ticks for {EVENTS} events: the driver stopped ticking a failing controller",
1281            s.ticks
1282        );
1283    }
1284
1285    /// `WatchDriverConfig::fallback_interval`'s doc says `Duration::MAX`
1286    /// disables the fallback. Nothing checked it (I20): a driver with no
1287    /// events and that fallback never ticks, while the same quiet day with
1288    /// a finite fallback ticks once per interval.
1289    #[tokio::test(start_paused = true)]
1290    async fn a_fallback_of_duration_max_never_fires() {
1291        let day = Duration::from_secs(24 * 3600);
1292
1293        let disabled = Probe::new(Answer::Done);
1294        let s = drive(&disabled, &Feed::new(), Duration::MAX, None, day).await;
1295        assert_eq!(
1296            s.ticks, 0,
1297            "{} ticks in a quiet day with the fallback disabled",
1298            s.ticks
1299        );
1300
1301        // The control: the same quiet day with a 30 s fallback. Each wait
1302        // starts after the previous 100 ms tick returns.
1303        let enabled = Probe::new(Answer::Done);
1304        let s = drive(&enabled, &Feed::new(), FALLBACK, None, day).await;
1305        let period = u64::try_from((FALLBACK + TICK_TAKES).as_millis()).unwrap();
1306        let expected = u64::try_from(day.as_millis()).unwrap() / period;
1307        assert!(
1308            s.ticks.abs_diff(expected) <= 1,
1309            "{} fallback ticks in a quiet day, expected about {expected}",
1310            s.ticks
1311        );
1312    }
1313
1314    /// A requeue due every second keeps restarting the wait, so the
1315    /// fallback never fires. A driver whose subscription was refused must
1316    /// retry it on the requeue wake too, or it stays stream-less forever.
1317    #[tokio::test(start_paused = true)]
1318    async fn a_refused_subscription_is_retried_even_when_requeues_outpace_the_fallback() {
1319        let probe = Probe::new(Answer::Requeue(REQUEUE_AFTER));
1320        let feed = Feed::refusing(3);
1321        let _ = an_hour_of(&probe, &feed).await;
1322
1323        assert!(
1324            feed.accepted.load(Ordering::SeqCst) >= 1,
1325            "the store refused three subscriptions and the driver never asked again"
1326        );
1327    }
1328
1329    #[test]
1330    fn next_wake_on_a_declarative_error_is_none() {
1331        let mut failures = ConsecutiveFailures::default();
1332        for _ in 0..3 {
1333            assert_eq!(
1334                next_wake(&Answer::Declarative.result(), &mut failures),
1335                None
1336            );
1337        }
1338    }
1339
1340    #[test]
1341    fn next_wake_follows_the_outcome() {
1342        let d = Duration::from_millis(250);
1343        let ok = |result| Ok(ReconcileOutcome::new(ReconcileReport::default(), result));
1344        let mut failures = ConsecutiveFailures::default();
1345        assert_eq!(next_wake(&ok(ReconcileResult::Done), &mut failures), None);
1346        assert_eq!(
1347            next_wake(&ok(ReconcileResult::Requeue(d)), &mut failures),
1348            Some(d)
1349        );
1350        assert_eq!(
1351            next_wake(&ok(ReconcileResult::RequeueWithProgress(d)), &mut failures),
1352            Some(d)
1353        );
1354        // The first Transient failure in a row is retried at the base.
1355        assert_eq!(
1356            next_wake(&Answer::Transient.result(), &mut failures),
1357            Some(Duration::from_secs(1))
1358        );
1359    }
1360
1361    // ── T2.2: retries grow ─────────────────────────────────────────────
1362    //
1363    // A Transient failure used to be retried at a flat 1 s for as long as
1364    // it lasted: a store that was down for an hour cost every driver 3,600
1365    // failed sweeps, each a log line and a round-trip. The retry now grows
1366    // on one curve, and forgets on success.
1367
1368    /// Measured on the real loop, with no events. The fallback fires the
1369    /// first tick and is longer than the cap, so it never fires again once
1370    /// the retries start: every later tick is a targeted retry. Each gap is
1371    /// at least 1.8x the one before until the cap, and then holds at it.
1372    #[tokio::test(start_paused = true)]
1373    async fn transient_retry_gaps_grow_until_the_cap() {
1374        const KICK: Duration = Duration::from_secs(90);
1375        const _: () = assert!(KICK.as_millis() > TRANSIENT_RETRY.cap().as_millis() + 100);
1376        let probe = Probe::new(Answer::Transient);
1377        let _ = drive(&probe, &Feed::new(), KICK, None, Duration::from_secs(600)).await;
1378        let gaps = probe.gaps();
1379        let cap = TRANSIENT_RETRY.cap() + TICK_TAKES;
1380
1381        assert_eq!(
1382            gaps.first().copied(),
1383            Some(TRANSIENT_RETRY.base() + TICK_TAKES),
1384            "the first retry is at the base: {gaps:?}"
1385        );
1386        assert_grows_then_holds(&gaps, cap);
1387        assert!(
1388            gaps.iter().filter(|g| **g == cap).count() >= 3,
1389            "ten minutes of failure never reached the {cap:?} cap: {gaps:?}"
1390        );
1391    }
1392
1393    /// Every gap is at least 1.8x the one before it until one reaches
1394    /// `cap`; from there every gap is exactly `cap`.
1395    fn assert_grows_then_holds(gaps: &[Duration], cap: Duration) {
1396        assert!(gaps.len() >= 3, "too few retries to see a curve: {gaps:?}");
1397        for pair in gaps.windows(2) {
1398            let (a, b) = (pair[0], pair[1]);
1399            assert!(b <= cap, "a {b:?} gap is past the {cap:?} cap: {gaps:?}");
1400            if a < cap {
1401                assert!(
1402                    b == cap || b.as_micros() * 10 >= a.as_micros() * 18,
1403                    "{a:?} then {b:?}: the retry gap did not grow 1.8x toward the cap: {gaps:?}"
1404                );
1405            } else {
1406                assert_eq!(b, cap, "past the cap the gap holds: {gaps:?}");
1407            }
1408        }
1409    }
1410
1411    #[test]
1412    fn a_success_resets_the_retry_curve() {
1413        let mut failures = ConsecutiveFailures::default();
1414        let owed: Vec<_> = (0..4)
1415            .map(|_| next_wake(&Answer::Transient.result(), &mut failures))
1416            .collect();
1417        assert_eq!(
1418            owed,
1419            [1, 2, 4, 8].map(|s| Some(Duration::from_secs(s))),
1420            "consecutive failures walk the curve"
1421        );
1422        assert_eq!(failures.count(), 4);
1423
1424        let _ = next_wake(&Answer::Done.result(), &mut failures);
1425        assert_eq!(failures.count(), 0, "an Ok ends the streak");
1426        assert_eq!(
1427            next_wake(&Answer::Transient.result(), &mut failures),
1428            Some(TRANSIENT_RETRY.base()),
1429            "the first failure after a success is retried at the base again"
1430        );
1431    }
1432
1433    /// A Declarative failure is not retried, but it is a failure in a row:
1434    /// a Transient one after it is retried further out, not at the base.
1435    #[test]
1436    fn a_declarative_failure_extends_the_streak_without_a_retry() {
1437        let mut failures = ConsecutiveFailures::default();
1438        assert_eq!(
1439            next_wake(&Answer::Declarative.result(), &mut failures),
1440            None
1441        );
1442        assert_eq!(failures.count(), 1);
1443        assert_eq!(
1444            next_wake(&Answer::Transient.result(), &mut failures),
1445            Some(TRANSIENT_RETRY.delay(1))
1446        );
1447    }
1448
1449    /// The re-subscribe path on the same curve family: a store that ends
1450    /// every stream it grants is asked again at gaps growing 1.8x per
1451    /// attempt up to the 30 s cap — never hot-looped, never abandoned.
1452    #[tokio::test(start_paused = true)]
1453    async fn resubscribe_gaps_grow_until_the_cap() {
1454        let probe = Probe::taking(Answer::Done, Duration::ZERO);
1455        let feed = Feed::ending_every_stream();
1456        let _ = drive(&probe, &feed, HOUR, None, Duration::from_secs(300)).await;
1457        let gaps = gaps(&feed.asked.lock().unwrap());
1458
1459        assert_eq!(
1460            gaps.first().copied(),
1461            Some(RESUBSCRIBE.base()),
1462            "the first re-subscribe waits the base: {gaps:?}"
1463        );
1464        assert_grows_then_holds(&gaps, RESUBSCRIBE.cap());
1465        assert!(
1466            gaps.iter().filter(|g| **g == RESUBSCRIBE.cap()).count() >= 3,
1467            "five minutes of ended streams never reached the cap: {gaps:?}"
1468        );
1469    }
1470
1471    #[test]
1472    fn the_slot_keeps_the_earlier_deadline_and_a_tick_clears_it() {
1473        let now = Instant::now();
1474        let mut slot = RequeueSlot::default();
1475        slot.arm(now + Duration::from_secs(5));
1476        slot.arm(now + Duration::from_secs(1));
1477        slot.arm(now + Duration::from_secs(3));
1478        assert_eq!(slot.at, Some(now + Duration::from_secs(1)));
1479        slot.clear();
1480        assert_eq!(slot, RequeueSlot::default());
1481    }
1482
1483    // ── T2.6: the loop's ticks are recorded where a supervisor can read them
1484    //
1485    // The ryn defect's only evidence was a missing log line. A driver now
1486    // writes every tick into its heartbeat — begun, ended, and how — so
1487    // "when did the kubelet last finish a tick?" has an answer in-process.
1488
1489    /// Drive the real loop with `answer` for `run_for`, returning the
1490    /// heartbeat it wrote.
1491    async fn heartbeat_of(probe: &Arc<Probe>, run_for: Duration) -> Arc<Heartbeat> {
1492        let beat = Arc::new(Heartbeat::new());
1493        let config = WatchDriverConfig {
1494            fallback_interval: FALLBACK,
1495            ..WatchDriverConfig::default()
1496        };
1497        let driver = tokio::spawn(run(probe.clone(), Feed::new(), config, beat.clone()));
1498        tokio::time::sleep(run_for).await;
1499        driver.abort();
1500        let _ = driver.await;
1501        beat
1502    }
1503
1504    #[tokio::test(start_paused = true)]
1505    async fn every_tick_is_recorded_in_the_heartbeat_with_its_class() {
1506        for (answer, class) in [
1507            (Answer::Done, TickClass::Done),
1508            (Answer::Requeue(REQUEUE_AFTER), TickClass::Requeued),
1509            (Answer::Transient, TickClass::Transient),
1510            (Answer::Declarative, TickClass::Declarative),
1511        ] {
1512            let probe = Probe::new(answer);
1513            let beat = heartbeat_of(&probe, Duration::from_secs(95))
1514                .await
1515                .snapshot();
1516            let ticks = probe.stats().ticks;
1517
1518            assert!(ticks >= 3, "{answer:?}: only {ticks} ticks in 95 s");
1519            assert_eq!(
1520                beat.ticks_started, ticks,
1521                "{answer:?}: the heartbeat missed a tick the controller saw"
1522            );
1523            // The abort can land inside a tick: that one began, never ended.
1524            assert!(
1525                beat.ticks_finished + 1 >= beat.ticks_started,
1526                "{answer:?}: {beat:?}"
1527            );
1528            assert_eq!(beat.last_class, Some(class), "{answer:?}: {beat:?}");
1529            assert!(beat.last_end.is_some() && beat.last_start.is_some());
1530        }
1531    }
1532
1533    /// A tick that has begun and not returned reads as in flight, with the
1534    /// time it began — the fact T2.8's stall detection is built on.
1535    #[tokio::test(start_paused = true)]
1536    async fn a_tick_in_progress_reads_as_in_flight() {
1537        let probe = Probe::taking(Answer::Done, Duration::from_secs(20));
1538        let beat = Arc::new(Heartbeat::new());
1539        let config = WatchDriverConfig {
1540            fallback_interval: FALLBACK,
1541            ..WatchDriverConfig::default()
1542        };
1543        let driver = tokio::spawn(run(probe.clone(), Feed::new(), config, beat.clone()));
1544        // The first fallback tick begins at 30 s and runs until 50 s.
1545        tokio::time::sleep(FALLBACK + Duration::from_secs(5)).await;
1546        let mid = beat.snapshot();
1547        driver.abort();
1548        let _ = driver.await;
1549
1550        assert!(
1551            mid.in_flight(),
1552            "a 20 s tick 5 s in is not in flight: {mid:?}"
1553        );
1554        assert_eq!((mid.ticks_started, mid.ticks_finished), (1, 0));
1555        assert_eq!(mid.last_class, None, "no tick has ended yet: {mid:?}");
1556        assert!(mid.last_start.is_some());
1557    }
1558
1559    // ── T2.7: a panic in a tick ────────────────────────────────────────
1560    //
1561    // A tick that panicked used to end the driver's task, so one object that
1562    // tripped an `unwrap` retired its whole controller for the life of the
1563    // process. Now what a panic does follows what the tick leaves behind.
1564
1565    /// Drive the real loop with `tick_state` over a controller whose every
1566    /// tick panics, with no events, for three fallbacks and a bit. Returns
1567    /// the probe, the heartbeat, and the driver's task, still unjoined.
1568    async fn a_panicking_driver(
1569        tick_state: TickState,
1570    ) -> (
1571        Arc<Probe>,
1572        Arc<Heartbeat>,
1573        tokio::task::JoinHandle<Infallible>,
1574    ) {
1575        let probe = Probe::new(Answer::Panic);
1576        let beat = Arc::new(Heartbeat::new());
1577        let config = WatchDriverConfig {
1578            fallback_interval: FALLBACK,
1579            tick_state,
1580            ..WatchDriverConfig::default()
1581        };
1582        let driver = tokio::spawn(run(probe.clone(), Feed::new(), config, beat.clone()));
1583        tokio::time::sleep(FALLBACK * 3 + Duration::from_secs(5)).await;
1584        (probe, beat, driver)
1585    }
1586
1587    /// Stateless: the panic is contained. The driver keeps running, every
1588    /// panicked tick is counted and classed as a panic, and the only thing
1589    /// that re-ticks it is the fallback — one tick per interval, no
1590    /// targeted retry.
1591    #[tokio::test(start_paused = true)]
1592    async fn a_stateless_panic_is_contained_counted_and_reticked_by_the_fallback() {
1593        let (probe, beat, driver) = a_panicking_driver(TickState::Stateless).await;
1594        let still_running = !driver.is_finished();
1595        driver.abort();
1596        let _ = driver.await;
1597        let ticks = probe.stats().ticks;
1598        let snap = beat.snapshot();
1599
1600        assert!(
1601            still_running,
1602            "a contained panic ended the driver: one bad object retired the controller"
1603        );
1604        assert_eq!(
1605            ticks, 3,
1606            "95 s with a 30 s fallback and no events is three ticks: a panic is \
1607             re-ticked by the fallback and never by a targeted retry"
1608        );
1609        assert_eq!(
1610            snap.panics, ticks,
1611            "every panicked tick is counted: {snap:?}"
1612        );
1613        assert_eq!(
1614            snap.ticks_finished, ticks,
1615            "each panicked tick ended: {snap:?}"
1616        );
1617        assert_eq!(snap.last_class, Some(TickClass::Panicked), "{snap:?}");
1618    }
1619
1620    /// Stateful: the panic is NOT contained. It ends the driver's task —
1621    /// the owner of that task sees a panic and marks the child Dead — and
1622    /// nothing re-ticks over the state the panic tore.
1623    #[tokio::test(start_paused = true)]
1624    async fn a_stateful_panic_ends_the_driver_task() {
1625        let (probe, beat, driver) = a_panicking_driver(TickState::Stateful).await;
1626        assert!(driver.is_finished(), "a stateful driver survived its panic");
1627        let ended = match driver.await {
1628            Ok(never) => match never {},
1629            Err(ended) => ended,
1630        };
1631        let snap = beat.snapshot();
1632
1633        assert!(
1634            ended.is_panic(),
1635            "the driver's task ended but not by panic: {ended:?}"
1636        );
1637        assert_eq!(
1638            probe.stats().ticks,
1639            1,
1640            "a stateful controller was re-ticked over the state its panic tore"
1641        );
1642        assert!(
1643            snap.in_flight(),
1644            "the panicked tick never ended; its heartbeat must not say it did: {snap:?}"
1645        );
1646        assert_eq!(
1647            snap.panics, 0,
1648            "the driver does not count a panic it did not contain — the task's \
1649             owner does: {snap:?}"
1650        );
1651    }
1652
1653    /// When nobody says, a tick is Stateful: a driver built without the
1654    /// catalog's word does not re-tick over torn state.
1655    #[test]
1656    fn a_driver_is_stateful_unless_told_otherwise() {
1657        assert_eq!(WatchDriverConfig::default().tick_state, TickState::Stateful);
1658    }
1659
1660    /// A contained panic's error takes the no-targeted-retry path, and it is
1661    /// a failure in a row like any other.
1662    #[test]
1663    fn a_contained_panic_gets_no_targeted_retry() {
1664        let mut failures = ConsecutiveFailures::default();
1665        let panicked = Err(ControllerError::Panicked(crate::PanicMessage::Opaque));
1666        assert_eq!(next_wake(&panicked, &mut failures), None);
1667        assert_eq!(failures.count(), 1);
1668    }
1669
1670    #[derive(Default)]
1671    struct Recorded(Mutex<Vec<String>>);
1672
1673    struct Fields<'a>(&'a mut String);
1674
1675    impl tracing::field::Visit for Fields<'_> {
1676        fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
1677            self.0.push_str(&format!("{}={value:?} ", field.name()));
1678        }
1679    }
1680
1681    struct Recorder(Arc<Recorded>);
1682
1683    impl tracing::Subscriber for Recorder {
1684        fn enabled(&self, _: &tracing::Metadata<'_>) -> bool {
1685            true
1686        }
1687        fn new_span(&self, _: &tracing::span::Attributes<'_>) -> tracing::span::Id {
1688            tracing::span::Id::from_u64(1)
1689        }
1690        fn record(&self, _: &tracing::span::Id, _: &tracing::span::Record<'_>) {}
1691        fn record_follows_from(&self, _: &tracing::span::Id, _: &tracing::span::Id) {}
1692        fn event(&self, event: &tracing::Event<'_>) {
1693            let mut line = format!("{} ", event.metadata().level());
1694            event.record(&mut Fields(&mut line));
1695            self.0.0.lock().unwrap().push(line);
1696        }
1697        fn enter(&self, _: &tracing::span::Id) {}
1698        fn exit(&self, _: &tracing::span::Id) {}
1699    }
1700
1701    fn logged(f: impl FnOnce()) -> Vec<String> {
1702        let recorded = Arc::new(Recorded::default());
1703        tracing::subscriber::with_default(Recorder(recorded.clone()), f);
1704        let lines = recorded.0.lock().unwrap().clone();
1705        lines
1706    }
1707
1708    #[test]
1709    fn a_failed_tick_is_logged_with_its_retry_in_milliseconds() {
1710        let transient = logged(|| {
1711            log_tick(
1712                "probe",
1713                &Answer::Transient.result(),
1714                Some(Duration::from_millis(1500)),
1715            );
1716        });
1717        assert_eq!(transient.len(), 1, "{transient:?}");
1718        assert!(transient[0].starts_with("WARN "), "{transient:?}");
1719        assert!(transient[0].contains("after_ms=1500 "), "{transient:?}");
1720
1721        let declarative = logged(|| log_tick("probe", &Answer::Declarative.result(), None));
1722        assert_eq!(declarative.len(), 1, "{declarative:?}");
1723        assert!(declarative[0].starts_with("ERROR "), "{declarative:?}");
1724    }
1725
1726    #[test]
1727    fn millis_is_whole_milliseconds_and_saturates() {
1728        assert_eq!(millis(Duration::from_millis(1500)), 1500);
1729        assert_eq!(millis(Duration::from_micros(2999)), 2);
1730        assert_eq!(millis(Duration::MAX), u64::MAX);
1731    }
1732
1733    #[tokio::test(start_paused = true)]
1734    async fn a_driver_hands_out_the_heartbeat_it_records_into_and_ticks_its_controller() {
1735        let router = engenho_store::InProcessRouter::new();
1736        let cfg = engenho_store::default_config("watch-driver-handle").unwrap();
1737        let store = Arc::new(
1738            StoreMesh::start(1, "in-process://1".into(), router, cfg)
1739                .await
1740                .unwrap(),
1741        );
1742        let probe = Arc::try_unwrap(Probe::new(Answer::Requeue(REQUEUE_AFTER)))
1743            .unwrap_or_else(|_| unreachable!("a fresh probe has one owner"));
1744        let driver = WatchDriver::new(probe, store, WatchDriverConfig::default());
1745        assert!(Arc::ptr_eq(&driver.heartbeat(), &driver.beat));
1746        let outcome = driver.tick_once().await.expect("the probe requeues");
1747        assert_eq!(outcome.result.requeue_after(), Some(REQUEUE_AFTER));
1748    }
1749}