engenho_controllers/node_lease.rs
1//! NODE HEARTBEATS — the Lease a node renews to prove it is alive.
2//!
3//! ★ WHY THIS EXISTS. A Node was registered once at boot with a hardcoded
4//! `[{type: Ready, status: True}]` and nothing ever updated it again. The
5//! `kube-node-lease` namespace was seeded and `coordination.k8s.io` was
6//! served, but no Lease was ever written or renewed. The consequence is
7//! the worst kind of monitoring failure: **a node that has crashed,
8//! partitioned, or been powered off reports `Ready` forever.** A scheduler
9//! keeps placing pods on it; `kubectl get nodes` shows a healthy cluster;
10//! nothing ever transitions to `NotReady`.
11//!
12//! ★ WHY A LEASE AND NOT A STATUS WRITE. Upstream moved node heartbeats to
13//! `coordination.k8s.io/v1 Lease` precisely because writing
14//! `Node.status` every few seconds is expensive — the object is large,
15//! every write wakes every Node watcher, and on a big cluster that traffic
16//! dominates the apiserver. A Lease is a tiny object whose only job is to
17//! carry `renewTime`. engenho gets the same property for the same reason,
18//! and gets it in the shape every existing tool already reads.
19//!
20//! ★ LIVENESS IS DERIVED, NEVER ASSERTED. `Ready` is computed from the
21//! lease's age against a grace period. Nothing writes "I am healthy" —
22//! a node proves it by renewing, and stops proving it by failing to. That
23//! inversion is the entire point: an asserted condition survives the death
24//! of whatever asserted it, which is exactly the bug being fixed here.
25//!
26//! ★ CLOCK-INJECTED AND PURE, so the whole grace-period curve is tested
27//! without sleeping.
28
29use std::time::Duration;
30
31use engenho_store::{ResourceKey, ResourceValue};
32use serde_json::json;
33
34/// How often a node renews its lease. Upstream's default.
35pub const RENEW_INTERVAL: Duration = Duration::from_secs(10);
36
37/// How stale a lease may get before the node is judged [`NodeReadiness::Stale`].
38///
39/// Upstream's default is 40s — four missed renewals. Deliberately several
40/// intervals, not one: a single missed renewal is a hiccup, and flapping a
41/// node stale on one slow tick would evict workloads for nothing.
42pub const GRACE_PERIOD: Duration = Duration::from_secs(40);
43
44/// The namespace node leases live in.
45pub const LEASE_NAMESPACE: &str = "kube-node-lease";
46
47/// Build the `Lease` object for a node.
48///
49/// `holder` is the node name — upstream sets `holderIdentity` to it, which
50/// is what makes the lease attributable when several exist.
51#[must_use]
52pub fn lease_value(node: &str, renew_time: &str, transitions: u64) -> ResourceValue {
53 json!({
54 "apiVersion": "coordination.k8s.io/v1",
55 "kind": "Lease",
56 "metadata": { "name": node, "namespace": LEASE_NAMESPACE },
57 "spec": {
58 "holderIdentity": node,
59 // Seconds, not the Duration — upstream's field is an int32 of
60 // seconds and a client comparing against it would misread a
61 // millisecond value by three orders of magnitude.
62 "leaseDurationSeconds": GRACE_PERIOD.as_secs(),
63 "renewTime": renew_time,
64 "leaseTransitions": transitions,
65 }
66 })
67}
68
69/// The store key for a node's lease.
70#[must_use]
71pub fn lease_key(node: &str) -> ResourceKey {
72 ResourceKey::namespaced("coordination.k8s.io", "v1", "Lease", LEASE_NAMESPACE, node)
73}
74
75/// A node's readiness, DERIVED from how stale its heartbeat is.
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77pub enum NodeReadiness {
78 /// Renewed within the grace period.
79 Ready,
80 /// The heartbeat is older than the grace period, so this node's health
81 /// is no longer KNOWN.
82 ///
83 /// ── ★ RENAMED FROM `NotReady` AND ITS WIRE VALUE CORRECTED 2026-09-14 ──
84 /// It rendered `status: "False"` while carrying `reason:
85 /// "NodeStatusUnknown"` and `message: "Kubelet stopped posting node
86 /// status"` — upstream's **Unknown** pair, verbatim. The struct disagreed
87 /// with itself, and the wire value was the half that was wrong.
88 ///
89 /// Upstream distinguishes two different facts and engenho can only observe
90 /// one of them:
91 /// * `Ready=False` is what a LIVE kubelet posts about ITSELF when it
92 /// knows it is unhealthy (reason `KubeletNotReady`) — the runtime is
93 /// down, the network plugin is not ready. It means "I am here and I am
94 /// broken."
95 /// * `Ready=Unknown` is what the node-lifecycle-controller posts when the
96 /// heartbeat has simply STOPPED. It means "nobody is answering."
97 ///
98 /// A stale lease is the second. engenho has no health probe on the
99 /// container runtime at all (`ContainerRuntime` has no `health()` — its
100 /// `status` asks about one container), so it cannot honestly produce the
101 /// first, and claiming `False` asserts knowledge it does not have.
102 ///
103 /// The distinction is not cosmetic: upstream's taint manager applies
104 /// `node.kubernetes.io/unreachable` for Unknown and
105 /// `node.kubernetes.io/not-ready` for False, and workloads tolerate them
106 /// differently.
107 Stale,
108 /// No lease has ever been observed.
109 ///
110 /// Distinct from [`Self::Stale`] on purpose: a node that has never
111 /// heartbeat is mid-registration, while one that HAS and then stopped
112 /// has failed. Collapsing them would make a booting node look like a
113 /// dying one, and every autoscaler treats those differently.
114 Unknown,
115}
116
117impl NodeReadiness {
118 /// The `status` string of the `Ready` condition.
119 #[must_use]
120 pub fn condition_status(self) -> &'static str {
121 match self {
122 Self::Ready => "True",
123 // "Unknown", NOT "False" — see the variant's doc. A stale
124 // heartbeat means nobody is answering, which is not the same
125 // claim as "I am here and broken".
126 Self::Stale => "Unknown",
127 // Upstream's third value. Not "False": a node whose state
128 // cannot be determined is not the same as one known to be bad.
129 Self::Unknown => "Unknown",
130 }
131 }
132
133 /// The `reason` upstream pairs with the condition.
134 #[must_use]
135 pub fn reason(self) -> &'static str {
136 match self {
137 Self::Ready => "KubeletReady",
138 Self::Stale => "NodeStatusUnknown",
139 Self::Unknown => "NodeStatusNeverUpdated",
140 }
141 }
142}
143
144/// Judge a node from the age of its last heartbeat.
145///
146/// `since_renew` is `None` when no lease has ever been seen.
147#[must_use]
148pub fn readiness(since_renew: Option<Duration>) -> NodeReadiness {
149 match since_renew {
150 None => NodeReadiness::Unknown,
151 Some(age) if age <= GRACE_PERIOD => NodeReadiness::Ready,
152 Some(_) => NodeReadiness::Stale,
153 }
154}
155
156/// The `Ready` condition to publish on `Node.status`.
157///
158/// `previous` is the condition currently on the Node, when there is one.
159///
160/// ── ★ THE TWO TIMESTAMPS ARE NOT THE SAME TIMESTAMP ───────────────────────
161/// This function used to stamp both with `now` unconditionally, which makes
162/// `lastTransitionTime` a synonym for `lastHeartbeatTime` and destroys the only
163/// question either field exists to answer: **how long has the node been in this
164/// state?** With both moving every tick, a node that went unreachable an hour
165/// ago reports a transition time of *now*, forever.
166///
167/// That is load-bearing rather than cosmetic. Upstream's pod-eviction path is
168/// driven by how long `Ready` has been non-`True` (`--pod-eviction-timeout`
169/// against `lastTransitionTime`), so a transition time that always reads
170/// "just now" is a timer that never fires. It is also what `kubectl describe
171/// node` prints, so an operator reading it is told every outage is fresh.
172///
173/// Hence:
174/// * `lastHeartbeatTime` — **always** `now`. It records that we looked.
175/// * `lastTransitionTime` — `now` ONLY when the status string differs from
176/// `previous`; otherwise the previous value is carried forward verbatim.
177///
178/// A `previous` with no readable `lastTransitionTime` (a hand-written Node, or
179/// the boot-time literal this replaces) falls back to `now`, which is the
180/// honest answer: we genuinely do not know when it transitioned.
181#[must_use]
182pub fn ready_condition(
183 state: NodeReadiness,
184 now: &str,
185 previous: Option<&ResourceValue>,
186) -> ResourceValue {
187 let status = state.condition_status();
188 let last_transition = previous
189 .filter(|p| p.get("status").and_then(|s| s.as_str()) == Some(status))
190 .and_then(|p| p.get("lastTransitionTime"))
191 .and_then(|t| t.as_str())
192 .unwrap_or(now);
193 json!({
194 "type": "Ready",
195 "status": status,
196 "reason": state.reason(),
197 "message": match state {
198 NodeReadiness::Ready => "kubelet is posting ready status",
199 NodeReadiness::Stale => "Kubelet stopped posting node status",
200 NodeReadiness::Unknown => "Kubelet never posted node status",
201 },
202 "lastHeartbeatTime": now,
203 "lastTransitionTime": last_transition,
204 })
205}
206
207/// Find the `Ready` condition in a Node's `status.conditions`, if present.
208///
209/// By `type`, never by index: the array's order is not a contract, and
210/// `conditions[0]` happens to be Ready only until something else writes one.
211#[must_use]
212pub fn find_ready_condition(node: &ResourceValue) -> Option<&ResourceValue> {
213 node.get("status")?
214 .get("conditions")?
215 .as_array()?
216 .iter()
217 .find(|c| c.get("type").and_then(|t| t.as_str()) == Some("Ready"))
218}
219
220// =================================================================
221// The one derivation of Ready from a Lease
222// =================================================================
223
224/// Project the `Ready` condition a Node's Lease implies onto that Node.
225///
226/// The one derivation of `Ready`. Its callers WRITE what it returns
227/// ([`crate::node_readiness`], from the kubelet and from
228/// [`crate::node_lifecycle`]) or judge with it in memory (the scheduler's
229/// filter). The apiserver no longer applies it to what it serves: it did
230/// until 2026-10-15, and a value that changed with the passage of time under
231/// one `resourceVersion` reached no watch and was content no revision
232/// identified (QUALIFICATION row 32). A wedged kubelet beside a live process,
233/// and a peer whose process died, are now moved to `Unknown` by the
234/// node-lifecycle controller's write.
235///
236/// `lease` is that node's Lease, `None` when it has none. Conditions the
237/// kubelet does not own are preserved; only `Ready` is replaced.
238pub fn project_ready_condition(node: &mut ResourceValue, lease: Option<&ResourceValue>, now: &str) {
239 let since_renew = lease
240 .and_then(|l| l.get("spec"))
241 .and_then(|s| s.get("renewTime"))
242 .and_then(|t| t.as_str())
243 .and_then(engenho_types::time::age_since_rfc3339);
244 let state = readiness(since_renew);
245
246 // Carry `lastTransitionTime` from whatever is stored, so the derived value
247 // still answers "how long has it been like this" when the status agrees.
248 let previous = find_ready_condition(node).cloned();
249 let condition = ready_condition(state, now, previous.as_ref());
250
251 let mut conditions: Vec<ResourceValue> = node
252 .get("status")
253 .and_then(|s| s.get("conditions"))
254 .and_then(|c| c.as_array())
255 .cloned()
256 .unwrap_or_default()
257 .into_iter()
258 .filter(|c| c.get("type").and_then(|t| t.as_str()) != Some("Ready"))
259 .collect();
260 conditions.push(condition);
261
262 if let Some(obj) = node.as_object_mut() {
263 let status = obj.entry("status").or_insert_with(|| json!({}));
264 if let Some(status_obj) = status.as_object_mut() {
265 status_obj.insert("conditions".to_string(), json!(conditions));
266 }
267 }
268}
269#[cfg(test)]
270mod tests {
271 use super::*;
272
273 const S: fn(u64) -> Duration = Duration::from_secs;
274
275 #[test]
276 fn a_node_that_stops_renewing_becomes_not_ready() {
277 // The whole bug: before this, a powered-off node reported Ready
278 // forever and the scheduler kept placing pods on it.
279 assert_eq!(readiness(Some(S(0))), NodeReadiness::Ready);
280 assert_eq!(readiness(Some(GRACE_PERIOD)), NodeReadiness::Ready);
281 assert_eq!(readiness(Some(GRACE_PERIOD + S(1))), NodeReadiness::Stale);
282 }
283
284 #[test]
285 fn the_grace_period_is_several_intervals_not_one() {
286 // A single missed renewal is a hiccup. Flapping to Stale on one
287 // slow tick would evict workloads for nothing.
288 assert!(
289 GRACE_PERIOD >= RENEW_INTERVAL * 3,
290 "grace must tolerate several missed renewals"
291 );
292 assert_eq!(readiness(Some(RENEW_INTERVAL * 2)), NodeReadiness::Ready);
293 }
294
295 #[test]
296 fn never_heartbeat_is_distinct_from_stopped_heartbeating() {
297 // A booting node must not look like a dying one — every autoscaler
298 // treats those differently.
299 assert_eq!(readiness(None), NodeReadiness::Unknown);
300 assert_eq!(NodeReadiness::Unknown.condition_status(), "Unknown");
301 // ★ Both render "Unknown" on the wire, and that is CORRECT — upstream
302 // has no third status for "we used to hear from it". They stay
303 // distinct in the REASON, which is the field that carries the
304 // difference an autoscaler acts on.
305 assert_eq!(NodeReadiness::Stale.condition_status(), "Unknown");
306 assert_ne!(
307 NodeReadiness::Unknown.reason(),
308 NodeReadiness::Stale.reason()
309 );
310 }
311
312 #[test]
313 fn the_condition_carries_what_kubectl_describe_node_prints() {
314 let c = ready_condition(NodeReadiness::Ready, "2026-08-29T21:00:00Z", None);
315 assert_eq!(c["type"], "Ready");
316 assert_eq!(c["status"], "True");
317 assert_eq!(c["reason"], "KubeletReady");
318 assert_eq!(c["lastHeartbeatTime"], "2026-08-29T21:00:00Z");
319 // With no previous condition there is nothing to carry, so the
320 // transition is honestly "now".
321 assert_eq!(c["lastTransitionTime"], "2026-08-29T21:00:00Z");
322 }
323
324 #[test]
325 fn last_transition_time_only_moves_when_the_status_does() {
326 // THE bug this signature exists to make impossible: both stamps set to
327 // `now` every tick makes "how long has this node been down" always
328 // read zero, which is the input upstream's eviction timer runs on.
329 let first = ready_condition(NodeReadiness::Ready, "2026-01-01T00:00:00Z", None);
330 // Same status, later heartbeat -> transition carried forward.
331 let later = ready_condition(NodeReadiness::Ready, "2026-01-01T01:00:00Z", Some(&first));
332 assert_eq!(later["lastHeartbeatTime"], "2026-01-01T01:00:00Z");
333 assert_eq!(
334 later["lastTransitionTime"], "2026-01-01T00:00:00Z",
335 "a steady node has not transitioned; its transition time must not move"
336 );
337 // Status CHANGES -> transition is now.
338 let flipped = ready_condition(NodeReadiness::Stale, "2026-01-01T02:00:00Z", Some(&later));
339 assert_eq!(flipped["status"], "Unknown");
340 assert_eq!(flipped["lastTransitionTime"], "2026-01-01T02:00:00Z");
341 // And back again, from the flipped one.
342 let back = ready_condition(NodeReadiness::Ready, "2026-01-01T03:00:00Z", Some(&flipped));
343 assert_eq!(back["lastTransitionTime"], "2026-01-01T03:00:00Z");
344 }
345
346 #[test]
347 fn a_stale_lease_makes_a_stored_ready_true_read_as_unknown() {
348 // THE POINT. This is the rio failure exactly: the kubelet wedged, the
349 // Node kept its last-published `Ready=True`, and the apiserver served
350 // it for three days. Derivation means the stored value cannot lie,
351 // because it is not what gets served.
352 let mut node = json!({"status": {"conditions": [
353 {"type": "Ready", "status": "True", "reason": "KubeletReady",
354 "lastTransitionTime": "2026-01-01T00:00:00Z"}
355 ]}});
356 let stale = json!({"spec": {"renewTime": "2020-01-01T00:00:00Z"}});
357 project_ready_condition(&mut node, Some(&stale), "2026-09-14T12:00:00Z");
358 let ready = find_ready_condition(&node).expect("Ready");
359 assert_eq!(
360 ready["status"], "Unknown",
361 "a stale heartbeat cannot read Ready: {node}"
362 );
363 assert_eq!(ready["reason"], "NodeStatusUnknown");
364 // The status CHANGED, so the transition time moves to now.
365 assert_eq!(ready["lastTransitionTime"], "2026-09-14T12:00:00Z");
366 }
367
368 #[test]
369 fn no_lease_at_all_reads_as_unknown_never_as_ready() {
370 // A Node object with a stored Ready=True and NO lease — the shape
371 // `register_node` wrote on every boot before T1.3a, and what a Node
372 // the kubelet once published Ready on looks like after its lease is
373 // lost.
374 let mut node = json!({"status": {"conditions": [
375 {"type": "Ready", "status": "True"}
376 ]}});
377 project_ready_condition(&mut node, None, "2026-09-14T12:00:00Z");
378 let ready = find_ready_condition(&node).expect("Ready");
379 assert_eq!(ready["status"], "Unknown");
380 assert_eq!(ready["reason"], "NodeStatusNeverUpdated", "{node}");
381 }
382
383 #[test]
384 fn a_fresh_lease_reads_ready_and_preserves_foreign_conditions() {
385 let mut node = json!({"status": {"conditions": [
386 {"type": "MemoryPressure", "status": "False"},
387 {"type": "Ready", "status": "Unknown",
388 "lastTransitionTime": "2026-01-01T00:00:00Z"}
389 ]}});
390 let fresh = json!({"spec": {"renewTime": engenho_types::time::now_rfc3339_utc()}});
391 project_ready_condition(&mut node, Some(&fresh), "2026-09-14T12:00:00Z");
392 let ready = find_ready_condition(&node).expect("Ready");
393 assert_eq!(ready["status"], "True");
394 // NEGATIVE CONTROL: the projection must REPLACE only Ready. A
395 // condition it does not own surviving is what separates this from a
396 // renderer that rebuilds the array.
397 assert!(
398 node["status"]["conditions"]
399 .as_array()
400 .unwrap()
401 .iter()
402 .any(|c| c["type"] == "MemoryPressure"),
403 "a foreign condition must survive the projection: {node}"
404 );
405 // And exactly one Ready, not one appended beside the old.
406 let n = node["status"]["conditions"]
407 .as_array()
408 .unwrap()
409 .iter()
410 .filter(|c| c["type"] == "Ready")
411 .count();
412 assert_eq!(n, 1, "{node}");
413 }
414
415 #[test]
416 fn an_unparseable_renew_time_reads_unknown_rather_than_fresh() {
417 // A future or malformed timestamp must not read as a 0-second-old
418 // heartbeat, which is exactly what a healthy node looks like. This is
419 // the most convincing possible lie.
420 let mut node = json!({});
421 let future = json!({"spec": {"renewTime": "2099-01-01T00:00:00Z"}});
422 project_ready_condition(&mut node, Some(&future), "2026-09-14T12:00:00Z");
423 assert_eq!(find_ready_condition(&node).unwrap()["status"], "Unknown");
424 let garbage = json!({"spec": {"renewTime": "not-a-time"}});
425 let mut node2 = json!({});
426 project_ready_condition(&mut node2, Some(&garbage), "2026-09-14T12:00:00Z");
427 assert_eq!(find_ready_condition(&node2).unwrap()["status"], "Unknown");
428 }
429
430 #[test]
431 fn the_ready_condition_is_found_by_type_not_by_index() {
432 // conditions[] order is not a contract; Ready is conditions[0] only
433 // until something else writes one.
434 let node = json!({"status": {"conditions": [
435 {"type": "MemoryPressure", "status": "False"},
436 {"type": "Ready", "status": "True", "lastTransitionTime": "T"}
437 ]}});
438 let found = find_ready_condition(&node).expect("Ready is present");
439 assert_eq!(found["lastTransitionTime"], "T");
440 assert!(find_ready_condition(&json!({"status": {"conditions": []}})).is_none());
441 assert!(find_ready_condition(&json!({})).is_none());
442 }
443
444 #[test]
445 fn lease_duration_is_seconds_because_upstreams_field_is() {
446 // A millisecond value here would be misread by three orders of
447 // magnitude by anything comparing against it.
448 let v = lease_value("cid", "2026-08-29T21:00:00Z", 0);
449 assert_eq!(v["spec"]["leaseDurationSeconds"], 40);
450 assert_eq!(v["spec"]["holderIdentity"], "cid");
451 assert_eq!(v["metadata"]["namespace"], LEASE_NAMESPACE);
452 assert_eq!(v["apiVersion"], "coordination.k8s.io/v1");
453 }
454
455 #[test]
456 fn the_lease_lands_where_every_tool_looks_for_it() {
457 let k = lease_key("cid");
458 assert_eq!(k.group, "coordination.k8s.io");
459 assert_eq!(k.kind, "Lease");
460 assert_eq!(k.namespace.as_deref(), Some("kube-node-lease"));
461 assert_eq!(k.name, "cid");
462 }
463}