Skip to main content

engenho_controllers/
condition.rs

1//! T2.5 — one condition, set by its type, carried at most once.
2//!
3//! ★ THE DEFECT. A controller that reports a condition by writing it every
4//! tick wakes itself: the write fires a watch event, the event re-ticks the
5//! controller, and the controller writes again. The scheduler did this to an
6//! unschedulable pod, about 19 times a second (38 ticks in 2 s, measured
7//! 2026-09-18). Two ways into that loop:
8//!
9//!   * proposing a condition the object already carries, and
10//!   * re-stamping `lastTransitionTime` on every write, so that each write
11//!     differs from the last one even when nothing about the condition did.
12//!
13//! ★ THE SHAPE. [`upsert_condition`] is the whole rule, as a pure function of
14//! the object read and the condition asserted:
15//!
16//!   * a condition of the same `type`, `status`, `reason` and `message` is
17//!     [`ConditionUpsert::Unchanged`]: there is nothing to write;
18//!   * otherwise the condition is set in place, at the position the type
19//!     already holds, or appended; every other condition is left as it was;
20//!   * `lastTransitionTime` moves only when `status` does. A write that only
21//!     rewords the message carries the recorded time forward, so "how long
22//!     has this been False" keeps its answer. When there is no recorded time
23//!     to carry, `now` is the honest fallback (the rule
24//!     [`crate::node_lease::ready_condition`] already follows for a Node);
25//!   * the result holds exactly one condition of the type: duplicates are
26//!     collapsed into the first.
27//!
28//! [`crate::status::upsert_condition_cas`] reads the object, applies this and
29//! writes the result at the revision it read. This mirrors upstream's
30//! `meta.SetStatusCondition` (apimachinery `pkg/api/meta/conditions.go`).
31
32use std::fmt;
33
34use serde_json::{Map, Value, json};
35
36use crate::meta::{ShapeError, array_mut, object_mut};
37
38crate::closed_enum! {
39    /// A condition's `status`: upstream's closed set.
40    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
41    pub enum ConditionStatus {
42        True,
43        False,
44        Unknown,
45    }
46}
47
48impl ConditionStatus {
49    /// The wire string.
50    #[must_use]
51    pub const fn as_str(self) -> &'static str {
52        match self {
53            Self::True => "True",
54            Self::False => "False",
55            Self::Unknown => "Unknown",
56        }
57    }
58}
59
60impl fmt::Display for ConditionStatus {
61    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62        f.write_str(self.as_str())
63    }
64}
65
66/// One condition as the controller that owns its `type` asserts it.
67///
68/// There is no `lastTransitionTime` field: when the condition transitioned
69/// is not the author's to say. [`upsert_condition`] decides it from the
70/// condition already recorded.
71#[derive(Debug, Clone, PartialEq, Eq)]
72pub struct DesiredCondition {
73    /// Which aspect of the object this condition reports (`PodScheduled`,
74    /// `Ready`). One controller owns a type.
75    pub condition_type: &'static str,
76    pub status: ConditionStatus,
77    /// A CamelCase identifier for why the condition is in this status.
78    pub reason: &'static str,
79    /// Human-readable detail.
80    pub message: String,
81}
82
83impl DesiredCondition {
84    /// Whether `recorded` already says what this condition says.
85    ///
86    /// `type` is matched by the caller. `lastTransitionTime` and any other
87    /// field (`lastProbeTime`, `observedGeneration`) are not compared: they
88    /// are not part of what the author asserts. An absent `reason` or
89    /// `message` reads as empty, the way upstream omits an empty one.
90    fn is_recorded_by(&self, recorded: &Value) -> bool {
91        text(recorded, "status") == self.status.as_str()
92            && text(recorded, "reason") == self.reason
93            && text(recorded, "message") == self.message
94    }
95
96    /// Whether `condition` is of this condition's type.
97    fn is_type_of(&self, condition: &Value) -> bool {
98        condition.get("type").and_then(Value::as_str) == Some(self.condition_type)
99    }
100
101    /// Set this condition's fields on the condition object `slot`, stamped
102    /// with `transition`. Fields the author does not assert are kept.
103    fn write_into(&self, slot: &mut Map<String, Value>, transition: String) {
104        slot.insert("type".to_owned(), json!(self.condition_type));
105        slot.insert("status".to_owned(), json!(self.status.as_str()));
106        slot.insert("reason".to_owned(), json!(self.reason));
107        slot.insert("message".to_owned(), json!(self.message));
108        slot.insert("lastTransitionTime".to_owned(), Value::String(transition));
109    }
110}
111
112/// A string field of a condition; empty when absent or not a string.
113fn text<'v>(condition: &'v Value, field: &str) -> &'v str {
114    condition.get(field).and_then(Value::as_str).unwrap_or("")
115}
116
117/// What [`upsert_condition`] makes of the conditions an object carries.
118#[derive(Debug, Clone, PartialEq)]
119pub enum ConditionUpsert {
120    /// The object already carries the condition, once. Nothing to write.
121    Unchanged,
122    /// The whole `status.conditions` list to write.
123    Changed(Vec<Value>),
124}
125
126impl ConditionUpsert {
127    /// The `.status` fields to merge for this upsert: `conditions`, or
128    /// nothing when unchanged. An RFC 7396 merge replaces a list whole, so
129    /// the list is the complete one [`upsert_condition`] computed.
130    #[must_use]
131    pub fn into_status_fields(self) -> Option<Map<String, Value>> {
132        match self {
133            Self::Unchanged => None,
134            Self::Changed(conditions) => {
135                let mut fields = Map::new();
136                fields.insert("conditions".to_owned(), Value::Array(conditions));
137                Some(fields)
138            }
139        }
140    }
141}
142
143/// Set `desired` on the conditions `object` carries, by type.
144///
145/// `now` is the RFC 3339 instant to record when the condition transitions
146/// (or when no transition time is recorded to carry forward).
147///
148/// # Errors
149///
150/// [`ShapeError::Wrong`] when `status` is not an object or
151/// `status.conditions` is not a list. Nothing can be set in place in a list
152/// that is not there, and replacing the value would discard what someone
153/// wrote.
154pub fn upsert_condition(
155    object: &Value,
156    desired: &DesiredCondition,
157    now: &str,
158) -> Result<ConditionUpsert, ShapeError> {
159    let mut status = object.get("status").cloned().unwrap_or(Value::Null);
160    let conditions = array_mut(&mut status, &["conditions"]).map_err(|e| e.under(&["status"]))?;
161
162    // Collapse duplicates of the type into the first one.
163    let before = conditions.len();
164    let mut seen = false;
165    conditions.retain(|c| {
166        let duplicate = desired.is_type_of(c) && seen;
167        seen |= desired.is_type_of(c);
168        !duplicate
169    });
170    let collapsed = conditions.len() != before;
171
172    let Some(recorded) = conditions.iter_mut().find(|c| desired.is_type_of(c)) else {
173        let mut appended = Map::new();
174        desired.write_into(&mut appended, now.to_owned());
175        conditions.push(Value::Object(appended));
176        return Ok(ConditionUpsert::Changed(std::mem::take(conditions)));
177    };
178    if !collapsed && desired.is_recorded_by(recorded) {
179        return Ok(ConditionUpsert::Unchanged);
180    }
181
182    let transition = match recorded.get("lastTransitionTime").and_then(Value::as_str) {
183        Some(at) if text(recorded, "status") == desired.status.as_str() => at.to_owned(),
184        _ => now.to_owned(),
185    };
186    // `recorded` has a `type`, so it is an object; `object_mut` says so
187    // without a panic path.
188    let slot = object_mut(recorded, &[]).map_err(|e| e.under(&["status", "conditions"]))?;
189    desired.write_into(slot, transition);
190    Ok(ConditionUpsert::Changed(std::mem::take(conditions)))
191}
192
193#[cfg(test)]
194mod tests {
195    use super::*;
196
197    const T0: &str = "2026-09-19T10:00:00Z";
198    const NOW: &str = "2026-09-19T12:00:00Z";
199
200    fn unschedulable(message: &str) -> DesiredCondition {
201        DesiredCondition {
202            condition_type: "PodScheduled",
203            status: ConditionStatus::False,
204            reason: "Unschedulable",
205            message: message.to_owned(),
206        }
207    }
208
209    fn recorded(status: &str, message: &str, at: &str) -> Value {
210        json!({"type": "PodScheduled", "status": status, "reason": "Unschedulable",
211               "message": message, "lastTransitionTime": at})
212    }
213
214    fn changed(upsert: ConditionUpsert) -> Vec<Value> {
215        match upsert {
216            ConditionUpsert::Changed(list) => list,
217            ConditionUpsert::Unchanged => panic!("expected a change"),
218        }
219    }
220
221    #[test]
222    fn every_status_renders_its_wire_string() {
223        let rendered: Vec<&str> = ConditionStatus::ALL.iter().map(|s| s.as_str()).collect();
224        assert_eq!(rendered, ["True", "False", "Unknown"]);
225    }
226
227    #[test]
228    fn a_missing_condition_is_appended_stamped_now() {
229        let pod = json!({"status": {"conditions": [{"type": "Initialized", "status": "True"}]}});
230        let list = changed(upsert_condition(&pod, &unschedulable("0/1 nodes"), NOW).unwrap());
231        assert_eq!(
232            list,
233            vec![
234                json!({"type": "Initialized", "status": "True"}),
235                recorded("False", "0/1 nodes", NOW),
236            ]
237        );
238    }
239
240    #[test]
241    fn an_object_with_no_status_gets_its_first_condition() {
242        let list = changed(upsert_condition(&json!({}), &unschedulable("m"), NOW).unwrap());
243        assert_eq!(list, vec![recorded("False", "m", NOW)]);
244    }
245
246    /// The hot-loop defense: the same assertion is not a change, whatever
247    /// the transition time or the clock says, and whatever other fields
248    /// the recorded condition carries.
249    #[test]
250    fn the_same_condition_is_unchanged_at_any_later_now() {
251        let mut carried = recorded("False", "0/1 nodes", T0);
252        carried["lastProbeTime"] = json!(T0);
253        let pod = json!({"status": {"conditions": [carried]}});
254        assert_eq!(
255            upsert_condition(&pod, &unschedulable("0/1 nodes"), NOW).unwrap(),
256            ConditionUpsert::Unchanged
257        );
258    }
259
260    /// Rewording is not a transition: the recorded time is carried
261    /// forward, in place, and other conditions keep their positions.
262    #[test]
263    fn a_new_message_keeps_the_transition_time_and_the_position() {
264        let pod = json!({"status": {"conditions": [
265            recorded("False", "0/1 nodes", T0),
266            {"type": "Initialized", "status": "True"},
267        ]}});
268        let list = changed(upsert_condition(&pod, &unschedulable("0/2 nodes"), NOW).unwrap());
269        assert_eq!(
270            list,
271            vec![
272                recorded("False", "0/2 nodes", T0),
273                json!({"type": "Initialized", "status": "True"}),
274            ]
275        );
276    }
277
278    #[test]
279    fn a_status_flip_stamps_now() {
280        let pod = json!({"status": {"conditions": [recorded("True", "", T0)]}});
281        let list = changed(upsert_condition(&pod, &unschedulable("m"), NOW).unwrap());
282        assert_eq!(list, vec![recorded("False", "m", NOW)]);
283    }
284
285    /// A recorded condition with no transition time has nothing to carry;
286    /// when it is rewritten for another reason, `now` is recorded.
287    #[test]
288    fn a_rewrite_with_no_recorded_time_stamps_now() {
289        let pod = json!({"status": {"conditions": [
290            {"type": "PodScheduled", "status": "False", "reason": "Unschedulable", "message": "old"}
291        ]}});
292        let list = changed(upsert_condition(&pod, &unschedulable("new"), NOW).unwrap());
293        assert_eq!(list, vec![recorded("False", "new", NOW)]);
294    }
295
296    /// Fields the author does not assert survive a rewrite.
297    #[test]
298    fn a_rewrite_keeps_fields_the_author_does_not_assert() {
299        let mut carried = recorded("False", "old", T0);
300        carried["lastProbeTime"] = json!(T0);
301        let pod = json!({"status": {"conditions": [carried]}});
302        let list = changed(upsert_condition(&pod, &unschedulable("new"), NOW).unwrap());
303        assert_eq!(list[0]["lastProbeTime"], T0);
304        assert_eq!(list[0]["message"], "new");
305    }
306
307    #[test]
308    fn duplicates_of_the_type_collapse_into_the_first() {
309        let pod = json!({"status": {"conditions": [
310            recorded("False", "m", T0),
311            {"type": "Initialized", "status": "True"},
312            recorded("False", "stale", T0),
313        ]}});
314        let list = changed(upsert_condition(&pod, &unschedulable("m"), NOW).unwrap());
315        assert_eq!(
316            list,
317            vec![
318                recorded("False", "m", T0),
319                json!({"type": "Initialized", "status": "True"}),
320            ]
321        );
322    }
323
324    #[test]
325    fn a_malformed_list_is_an_error_naming_it() {
326        for (pod, path) in [
327            (json!({"status": "Pending"}), "status"),
328            (json!({"status": {"conditions": {}}}), "status.conditions"),
329        ] {
330            let err = upsert_condition(&pod, &unschedulable("m"), NOW).unwrap_err();
331            assert_eq!(err.path().to_string(), path, "{pod}");
332        }
333    }
334
335    #[test]
336    fn only_a_change_carries_status_fields() {
337        assert_eq!(ConditionUpsert::Unchanged.into_status_fields(), None);
338        let fields = ConditionUpsert::Changed(vec![json!(1)])
339            .into_status_fields()
340            .unwrap();
341        assert_eq!(Value::Object(fields), json!({"conditions": [1]}));
342    }
343}