Skip to main content

engenho_controllers/
contain.rs

1//! Panic containment for a driver's tick (T2.7).
2//!
3//! ## What a panic in a tick used to do
4//!
5//! A `tick()` that panicked unwound through the driver loop and ended the
6//! driver's task. T2.6 made that visible — the runtime's child set sees the
7//! task end and marks the child Dead — but a Dead child is never respawned,
8//! so one bad object that tripped an `unwrap` retired a whole controller for
9//! the life of the process. Every other object of that kind stopped
10//! converging with it.
11//!
12//! ## What it does now, and why only for some children
13//!
14//! What a panic may do depends on what the tick leaves behind, which is the
15//! child's [`TickState`]:
16//!
17//! * **Stateless** — the tick re-reads everything it needs from the store
18//!   every time, so nothing it half-did survives into the next tick except
19//!   what the store holds, and the store is consistent by construction. The
20//!   driver contains the panic ([`contained`]), turns it into
21//!   [`crate::ControllerError::Panicked`] and carries on. That error class
22//!   gets no targeted retry: the next event or the fallback re-ticks it. A
23//!   panic caused by bad data therefore costs one counted tick per fallback
24//!   interval, not the controller. This is what controller-runtime's
25//!   `RecoverPanic` relies on, and for the same reason.
26//! * **Stateful** — the tick holds in-memory state across ticks: a map it
27//!   half-updated, a std `Mutex` the panic poisoned, a tokio lock guarding a
28//!   torn value. Re-ticking over that is acting on state that is no longer
29//!   true. The driver does not contain the panic; it ends the child's task,
30//!   and the runtime marks it Dead and logs it at ERROR. `/livez` reports it
31//!   only once a liveness source reads the children (T2.8); until then the
32//!   ERROR line is the notice. For the kubelet, Dead is the park.
33//!
34//! When in doubt a child is Stateful: the wrong answer in that direction
35//! costs availability, the wrong answer in the other costs correctness.
36//!
37//! ## Tier
38//!
39//! Mitigated, not unrepresentable. A contained panic is still a bug; it is
40//! counted (in the driver's heartbeat, and by the runtime's process-wide
41//! panic hook) so it is seen, and it is re-ticked so it costs one tick
42//! instead of one controller. Whether a child is Stateless is a judgement
43//! recorded in the runtime's catalog, not something the compiler checks.
44
45use std::any::Any;
46use std::fmt;
47use std::future::Future;
48use std::panic::AssertUnwindSafe;
49use std::task::Poll;
50
51/// Whether a child's tick leaves state behind that the next tick relies on.
52///
53/// Decides what a panic inside the tick does; see the [module
54/// docs](self). The runtime's child catalog declares one per child, and the
55/// [`crate::WatchDriver`] acts on it through
56/// [`crate::WatchDriverConfig::tick_state`].
57#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
58pub enum TickState {
59    /// Re-reads everything from the store every tick. A panic in a tick is
60    /// contained, counted and re-ticked by the next event or the fallback.
61    Stateless,
62    /// Holds in-memory state across ticks. A panic in a tick is not
63    /// contained: it ends the child, which its owner marks Dead.
64    Stateful,
65}
66
67/// What a panic said, as far as its payload lets anyone tell.
68///
69/// A panic payload is `Box<dyn Any + Send>`. `panic!("…")` with no
70/// arguments carries a `&'static str`, a formatted `panic!` carries a
71/// `String`, and `std::panic::panic_any` can carry anything at all — which
72/// is not text, and is said to be not text rather than printed as nothing.
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub enum PanicMessage {
75    /// The payload was text.
76    Text(String),
77    /// The payload was some other type.
78    Opaque,
79}
80
81impl PanicMessage {
82    /// Read a panic payload.
83    #[must_use]
84    pub fn of(payload: &(dyn Any + Send)) -> Self {
85        payload
86            .downcast_ref::<&str>()
87            .map(|text| (*text).to_owned())
88            .or_else(|| payload.downcast_ref::<String>().cloned())
89            .map_or(Self::Opaque, Self::Text)
90    }
91}
92
93impl fmt::Display for PanicMessage {
94    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95        match self {
96            Self::Text(text) => f.write_str(text),
97            Self::Opaque => f.write_str("(the panic payload is not text)"),
98        }
99    }
100}
101
102/// Run `fut` to completion, turning a panic in any poll of it into
103/// `Err`.
104///
105/// The future is polled inside [`std::panic::catch_unwind`] each time it is
106/// polled, so a panic after an `.await` is caught as surely as one before
107/// the first. After a panic the future is never polled again.
108///
109/// `AssertUnwindSafe` is the whole question, and the answer is the caller's:
110/// only a [`TickState::Stateless`] tick may be run through this, because
111/// only its state is all re-read from the store on the next tick.
112pub(crate) async fn contained<F: Future>(fut: F) -> Result<F::Output, PanicMessage> {
113    let mut fut = std::pin::pin!(fut);
114    std::future::poll_fn(move |cx| {
115        match std::panic::catch_unwind(AssertUnwindSafe(|| fut.as_mut().poll(cx))) {
116            Ok(poll) => poll.map(Ok),
117            Err(payload) => Poll::Ready(Err(PanicMessage::of(payload.as_ref()))),
118        }
119    })
120    .await
121}
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126
127    #[tokio::test]
128    async fn a_future_that_completes_is_returned_as_is() {
129        assert_eq!(contained(async { 7 }).await, Ok(7));
130    }
131
132    #[tokio::test]
133    async fn a_panic_before_the_first_await_is_caught_with_its_text() {
134        let got = contained(async {
135            panic!("bad object");
136        })
137        .await;
138        assert_eq!(got, Err::<(), _>(PanicMessage::Text("bad object".into())));
139    }
140
141    /// The panic lands on a LATER poll, after the future has already
142    /// returned `Pending` once: containment covers every poll, not only the
143    /// first.
144    #[tokio::test]
145    async fn a_panic_after_an_await_is_caught_too() {
146        let code = 42;
147        let got = contained(async move {
148            tokio::task::yield_now().await;
149            panic!("index {code} out of range");
150        })
151        .await;
152        assert_eq!(
153            got,
154            Err::<(), _>(PanicMessage::Text("index 42 out of range".into()))
155        );
156    }
157
158    #[test]
159    fn a_payload_that_is_not_text_is_said_to_be_opaque() {
160        let payload: Box<dyn Any + Send> = Box::new(17_u32);
161        assert_eq!(PanicMessage::of(payload.as_ref()), PanicMessage::Opaque);
162        assert_ne!(PanicMessage::Opaque.to_string(), "");
163    }
164
165    #[test]
166    fn both_text_payload_shapes_are_read() {
167        let literal: Box<dyn Any + Send> = Box::new("literal");
168        let formatted: Box<dyn Any + Send> = Box::new(String::from("formatted"));
169        assert_eq!(
170            PanicMessage::of(literal.as_ref()),
171            PanicMessage::Text("literal".into())
172        );
173        assert_eq!(
174            PanicMessage::of(formatted.as_ref()),
175            PanicMessage::Text("formatted".into())
176        );
177    }
178}