Skip to main content

engenho_controllers/
heartbeat.rs

1//! `Heartbeat` — what a supervised child last did, readable from outside
2//! without a lock.
3//!
4//! One per [`crate::WatchDriver`], and one per runtime listener. The child
5//! writes it; the runtime's supervisor and (from T2.8) the liveness
6//! projection read it. Every field is an atomic, so a reader never blocks a
7//! tick and a tick never waits for a reader.
8//!
9//! It records FACTS, not a verdict: when a tick last started and ended, how
10//! the last one ended, and how many panics the supervisor saw. Turning those
11//! into Alive / Stalled / Dead is the liveness projection's job, which is why
12//! there is no `is_healthy` here — a heartbeat that has never beaten reads as
13//! "never", not as "fine".
14//!
15//! ## Why it exists
16//!
17//! On ryn (2026-09-18) the kubelet's driver stopped ticking for 12 hours and
18//! the only evidence was the ABSENCE of a log line among three healthy
19//! controllers. Nothing in the process could say when a given controller last
20//! finished a tick. This is that record.
21//!
22//! ## Consistency
23//!
24//! Each field is individually consistent; a [`Beat`] is not a transaction. A
25//! snapshot taken while a tick starts may see the new start count with the
26//! previous start time. That is fine for what reads it — ages measured in
27//! seconds — and it is why the counts are written LAST (release) and read
28//! FIRST (acquire): a reader that sees a count also sees the time written
29//! before it.
30
31use std::sync::atomic::{AtomicU8, AtomicU64, Ordering};
32use std::time::Duration;
33
34use shigoto_types::failure::FailureKind;
35use tokio::time::Instant;
36
37use crate::controller::ReconcileOutcome;
38use crate::error::ControllerError;
39
40crate::closed_enum! {
41    /// How one tick of a child ended.
42    ///
43    /// Stored in a [`Heartbeat`] as a one-byte code, `0` meaning "never", so
44    /// a child that has not finished a tick has no class at all rather than a
45    /// default one that reads as success.
46    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
47    pub enum TickClass {
48        /// `Ok` + `ReconcileResult::Done`.
49        Done,
50        /// `Ok` + a requeue.
51        Requeued,
52        /// `Err`, classified Transient: it will be retried on the curve.
53        Transient,
54        /// `Err`, classified Declarative: it is surfaced, not retried.
55        Declarative,
56        /// `Err` in a failure class this crate does not know yet
57        /// (`FailureKind` is `#[non_exhaustive]`). Recorded as unknown
58        /// rather than rounded to either known class.
59        Unclassified,
60        /// A child that is not a tick loop — a listener — stopped doing its
61        /// work: its bind failed or its server returned. It rebinds on a
62        /// growing backoff (T2.7). A listener serves while its heartbeat is
63        /// in flight; `Halted` with nothing in flight is one waiting to
64        /// rebind, and liveness must read that as not-ok.
65        Halted,
66        /// The tick panicked and the driver contained it (T2.7): only a
67        /// Stateless child's tick is contained. Counted as a panic, and
68        /// re-ticked by the next event or the fallback — never by a
69        /// targeted retry. Its own class so a bug is never read as a
70        /// malformed declaration.
71        Panicked,
72    }
73}
74
75impl TickClass {
76    /// Classify one controller tick's result.
77    #[must_use]
78    pub fn of(result: &Result<ReconcileOutcome, ControllerError>) -> Self {
79        match result {
80            Ok(outcome) if outcome.result.requeue_after().is_some() => Self::Requeued,
81            Ok(_) => Self::Done,
82            Err(ControllerError::Panicked(_)) => Self::Panicked,
83            Err(e) => match e.classify() {
84                FailureKind::Transient => Self::Transient,
85                FailureKind::Declarative => Self::Declarative,
86                // `FailureKind` is `#[non_exhaustive]`: a class shigoto adds
87                // later lands here and is recorded as exactly that — unknown.
88                _ => Self::Unclassified,
89            },
90        }
91    }
92
93    /// The stored code: the discriminant plus one, so `0` is "never".
94    const fn code(self) -> u8 {
95        // A fieldless enum's discriminants are 0..N in declaration order.
96        self as u8 + 1
97    }
98
99    /// Decode a stored code. `0` (never recorded) and any code past the
100    /// catalog decode to `None`.
101    fn from_code(code: u8) -> Option<Self> {
102        let index = usize::from(code.checked_sub(1)?);
103        Self::ALL.get(index).copied()
104    }
105}
106
107/// The lock-free record of a child's ticks.
108#[derive(Debug)]
109pub struct Heartbeat {
110    /// Every stored time is measured from here. `tokio::time::Instant`, so
111    /// paused-time tests read the same clock the loop runs on.
112    epoch: Instant,
113    started: AtomicU64,
114    finished: AtomicU64,
115    /// Microseconds since `epoch`, plus one; `0` = never.
116    last_start: AtomicU64,
117    /// Microseconds since `epoch`, plus one; `0` = never.
118    last_end: AtomicU64,
119    /// [`TickClass::code`]; `0` = never.
120    last_class: AtomicU8,
121    panics: AtomicU64,
122}
123
124impl Default for Heartbeat {
125    fn default() -> Self {
126        Self::new()
127    }
128}
129
130impl Heartbeat {
131    /// A heartbeat that has never beaten.
132    #[must_use]
133    pub fn new() -> Self {
134        Self {
135            epoch: Instant::now(),
136            started: AtomicU64::new(0),
137            finished: AtomicU64::new(0),
138            last_start: AtomicU64::new(0),
139            last_end: AtomicU64::new(0),
140            last_class: AtomicU8::new(0),
141            panics: AtomicU64::new(0),
142        }
143    }
144
145    /// A tick (or, for a listener, its serve) has started.
146    pub fn begin(&self) {
147        self.last_start.store(self.stamp(), Ordering::Release);
148        self.started.fetch_add(1, Ordering::Release);
149    }
150
151    /// The tick that last [`begin`](Self::begin)-ed has ended as `class`.
152    ///
153    /// A tick that ended [`TickClass::Panicked`] is also a panic this
154    /// heartbeat counts: the class is the one decision, so a contained panic
155    /// cannot be recorded without being counted.
156    pub fn end(&self, class: TickClass) {
157        if class == TickClass::Panicked {
158            self.record_panic();
159        }
160        self.last_end.store(self.stamp(), Ordering::Release);
161        self.last_class.store(class.code(), Ordering::Release);
162        self.finished.fetch_add(1, Ordering::Release);
163    }
164
165    /// A panic in this child: its task's, seen by the supervisor, or a
166    /// contained tick's, recorded by [`end`](Self::end).
167    pub fn record_panic(&self) {
168        self.panics.fetch_add(1, Ordering::Release);
169    }
170
171    /// What this heartbeat has recorded, as plain values.
172    #[must_use]
173    pub fn snapshot(&self) -> Beat {
174        // Counts first (acquire): the times written before them are visible.
175        let ticks_finished = self.finished.load(Ordering::Acquire);
176        let ticks_started = self.started.load(Ordering::Acquire);
177        Beat {
178            ticks_started,
179            ticks_finished,
180            last_start: self.at(self.last_start.load(Ordering::Acquire)),
181            last_end: self.at(self.last_end.load(Ordering::Acquire)),
182            last_class: TickClass::from_code(self.last_class.load(Ordering::Acquire)),
183            panics: self.panics.load(Ordering::Acquire),
184        }
185    }
186
187    /// Now, as a stored stamp: microseconds since `epoch` plus one,
188    /// saturating rather than wrapping.
189    fn stamp(&self) -> u64 {
190        u64::try_from(self.epoch.elapsed().as_micros())
191            .unwrap_or(u64::MAX)
192            .saturating_add(1)
193    }
194
195    /// A stored stamp back to an instant; `0` is "never".
196    fn at(&self, stamp: u64) -> Option<Instant> {
197        let micros = stamp.checked_sub(1)?;
198        self.epoch.checked_add(Duration::from_micros(micros))
199    }
200}
201
202/// A [`Heartbeat`] read at one moment.
203#[derive(Debug, Clone, Copy, PartialEq, Eq)]
204pub struct Beat {
205    /// Ticks begun since the child was spawned.
206    pub ticks_started: u64,
207    /// Ticks ended since the child was spawned.
208    pub ticks_finished: u64,
209    /// When the last tick began; `None` if none has.
210    pub last_start: Option<Instant>,
211    /// When the last tick ended; `None` if none has.
212    pub last_end: Option<Instant>,
213    /// How the last tick ended; `None` if none has.
214    pub last_class: Option<TickClass>,
215    /// Panics observed in this child: contained ticks' and its task's.
216    pub panics: u64,
217}
218
219impl Beat {
220    /// A tick has begun and not ended. For a tick loop that is a tick in
221    /// progress (or one that will never end, if the task died inside it);
222    /// for a listener it is the serving state.
223    #[must_use]
224    pub const fn in_flight(&self) -> bool {
225        self.ticks_started > self.ticks_finished
226    }
227}
228
229#[cfg(test)]
230mod tests {
231    use super::*;
232    use crate::controller::{ReconcileReport, ReconcileResult};
233
234    #[test]
235    fn a_heartbeat_that_never_beat_says_never() {
236        let beat = Heartbeat::new().snapshot();
237        assert_eq!(beat.ticks_started, 0);
238        assert_eq!(beat.ticks_finished, 0);
239        assert_eq!(beat.last_start, None);
240        assert_eq!(beat.last_end, None);
241        assert_eq!(
242            beat.last_class, None,
243            "no tick has ended, so there is no class — not a default one"
244        );
245        assert!(!beat.in_flight());
246    }
247
248    #[tokio::test(start_paused = true)]
249    async fn begin_and_end_record_times_counts_and_class() {
250        let hb = Heartbeat::new();
251        tokio::time::advance(Duration::from_secs(5)).await;
252        hb.begin();
253        let mid = hb.snapshot();
254        assert!(mid.in_flight(), "a begun tick is in flight until it ends");
255        assert_eq!(mid.last_end, None);
256
257        tokio::time::advance(Duration::from_secs(2)).await;
258        hb.end(TickClass::Transient);
259        let after = hb.snapshot();
260        assert!(!after.in_flight());
261        assert_eq!((after.ticks_started, after.ticks_finished), (1, 1));
262        assert_eq!(after.last_class, Some(TickClass::Transient));
263        let (start, end) = (after.last_start.unwrap(), after.last_end.unwrap());
264        assert_eq!(end - start, Duration::from_secs(2));
265    }
266
267    #[test]
268    fn every_class_round_trips_through_its_stored_code() {
269        for class in TickClass::ALL {
270            assert_ne!(class.code(), 0, "{class:?}: 0 is reserved for never");
271            assert_eq!(TickClass::from_code(class.code()), Some(*class));
272        }
273        let past = u8::try_from(TickClass::ALL.len() + 1).unwrap();
274        assert_eq!(TickClass::from_code(0), None);
275        assert_eq!(TickClass::from_code(past), None);
276    }
277
278    #[test]
279    fn panics_are_counted() {
280        let hb = Heartbeat::new();
281        hb.record_panic();
282        hb.record_panic();
283        assert_eq!(hb.snapshot().panics, 2);
284    }
285
286    #[test]
287    fn a_tick_result_classifies_by_outcome_and_failure_class() {
288        let ok = |r| Ok(ReconcileOutcome::new(ReconcileReport::default(), r));
289        assert_eq!(TickClass::of(&ok(ReconcileResult::Done)), TickClass::Done);
290        assert_eq!(
291            TickClass::of(&ok(ReconcileResult::Requeue(Duration::from_secs(1)))),
292            TickClass::Requeued
293        );
294        assert_eq!(
295            TickClass::of(&Err(ControllerError::Store(
296                engenho_store::StoreError::ClientWriteFailed("no leader".into())
297            ))),
298            TickClass::Transient
299        );
300        assert_eq!(
301            TickClass::of(&Err(ControllerError::InvalidResource("bad".into()))),
302            TickClass::Declarative
303        );
304    }
305
306    /// A contained panic classifies as a panic, not as the Declarative
307    /// failure its retry class shares — a bug is never read as a malformed
308    /// declaration.
309    #[test]
310    fn a_contained_panic_is_its_own_class() {
311        let panicked = Err(ControllerError::Panicked(crate::PanicMessage::Opaque));
312        assert_eq!(TickClass::of(&panicked), TickClass::Panicked);
313    }
314
315    /// Ending a tick as `Panicked` counts the panic; no other class does.
316    #[test]
317    fn a_tick_that_ended_in_a_panic_is_counted_as_one() {
318        for class in TickClass::ALL {
319            let hb = Heartbeat::new();
320            hb.begin();
321            hb.end(*class);
322            let want = u64::from(*class == TickClass::Panicked);
323            assert_eq!(hb.snapshot().panics, want, "{class:?}");
324        }
325    }
326}