Skip to main content

engenho_controllers/
node_readiness.rs

1//! Publishing a node's `Ready` condition as a store write, WITHOUT undoing
2//! anyone else's write to the Node (T1.3b).
3//!
4//! ── ★ THE ONE WRITER OF `Ready` ───────────────────────────────────────────
5//! The condition reaches a client only through a committed write: a write
6//! bumps `metadata.resourceVersion` and fans a `MODIFIED` to every watcher,
7//! so an informer keyed on the revision sees each transition. Two callers
8//! share this module and nothing else writes the condition:
9//!
10//!   * the kubelet, for its own node, every tick (it also refreshes the
11//!     heartbeat every [`REPORT_FREQUENCY`], as upstream's kubelet posts
12//!     status at least every `nodeStatusReportFrequency`);
13//!   * the node-lifecycle controller ([`crate::node_lifecycle`]), for every
14//!     Node, so a node whose kubelet wedged or whose process died is moved to
15//!     `Unknown` by a process that is still running.
16//!
17//! Until 2026-10-15 the apiserver re-derived the condition on every GET and
18//! LIST instead. That served content that changed under one
19//! `resourceVersion` (measured on ryn: three reads 12 s apart, one revision,
20//! three heartbeats; a LIST reading `NotReady` and a GET reading `Ready` at
21//! the same revision), so no watch cache ever saw a heartbeat or a Ready
22//! transition.
23//!
24//! ── ★ THE DEFECT THE PRECONDITION CLOSES ──────────────────────────────────
25//! The kubelet read the whole Node, merged its `Ready` condition in, and wrote
26//! the whole Node back with no precondition. Anything that committed between
27//! that read and that write — `kubectl cordon` setting `spec.unschedulable`,
28//! a taint, a label — was replaced by the kubelet's older copy. Nothing
29//! errored: the write succeeded, the condition it carried was correct, and the
30//! cordon was simply gone. The scheduler then placed onto a node an operator
31//! had just drained.
32//!
33//! ── ★ THE SHAPE ───────────────────────────────────────────────────────────
34//! The write is a `Put` whose precondition is the per-key revision the Node
35//! carried when it was read. [`ObservedNode`] is the only thing the write
36//! accepts, and it cannot be built without that revision, so this module has
37//! no path to a Node write without a precondition. A lost race is refused by
38//! the store (replicated CAS: no mutation, no revision, no watch event); the
39//! Node is re-read, the condition is re-derived against the fresh copy, and
40//! the write is tried ONCE more. A second loss is dropped: the next tick
41//! recomputes from whatever is current then, so a busy concurrent writer can
42//! delay a readiness publish by a tick but can never be overwritten by one.
43//!
44//! The condition itself comes from
45//! [`crate::node_lease::project_ready_condition`], the one derivation of
46//! `Ready` from a Lease, so the kubelet and the lifecycle controller cannot
47//! compute it two ways.
48//!
49//! ── ★ TIER, STATED ────────────────────────────────────────────────────────
50//! A stale write being refused is enforced by the store's CAS, identically on
51//! every replica. That this module always states a precondition is a
52//! construction discipline local to this file (a value that carries its
53//! revision), not a crate-wide type: another module holding the store can
54//! still issue an unconditional Node `Put`.
55
56use std::time::Duration;
57
58use crate::effect::Effect;
59use crate::node_lease::{find_ready_condition, project_ready_condition};
60use crate::status::resource_version_of;
61use engenho_store::{
62    ResourceKey, ResourceValue, StoreError, StoreMesh,
63    command::{Reason, ResourceCommand, ResourceOp},
64    revision::Revision,
65};
66use serde_json::Value;
67
68pub const REPORT_FREQUENCY: Duration = Duration::from_secs(5 * 60);
69
70/// A Node as read from the store, paired with the revision it was read at.
71///
72/// Every Node write in this module takes one of these, and the write's
73/// precondition is `revision` — so what was written is always what was
74/// derived from, or nothing.
75#[derive(Debug, Clone)]
76pub struct ObservedNode {
77    value: ResourceValue,
78    revision: Revision,
79}
80
81/// Why a Node could not be observed at a revision.
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub enum Unobservable {
84    /// No object at the key: registration has not landed, or the Node was
85    /// deleted.
86    Absent,
87    /// The stored object carries no parseable `metadata.resourceVersion`.
88    /// The store stamps one on every write, so this is a store defect; it is
89    /// still a state rather than a guess, because the alternative — writing
90    /// with no precondition — is the defect this module exists to remove.
91    Unversioned,
92}
93
94impl ObservedNode {
95    /// Pair a stored Node with the revision it carries.
96    ///
97    /// # Errors
98    ///
99    /// [`Unobservable::Unversioned`] when `metadata.resourceVersion` is
100    /// absent or not a revision.
101    pub fn from_stored(value: ResourceValue) -> Result<Self, Unobservable> {
102        let revision = resource_version_of(&value).ok_or(Unobservable::Unversioned)?;
103        Ok(Self { value, revision })
104    }
105
106    /// Read the Node at `key` together with its revision.
107    ///
108    /// # Errors
109    ///
110    /// [`Unobservable::Absent`] when there is no object at `key`;
111    /// [`Unobservable::Unversioned`] as for [`Self::from_stored`].
112    pub async fn read(store: &StoreMesh, key: &ResourceKey) -> Result<Self, Unobservable> {
113        let value = store.get(key).await.ok_or(Unobservable::Absent)?;
114        Self::from_stored(value)
115    }
116}
117
118/// What one readiness publish did. Each arm is a fact the publish observed;
119/// none is inferred from another.
120#[derive(Debug)]
121pub enum ReadinessPublish {
122    /// The derived condition committed. `retried` is true when the first write
123    /// lost to a concurrent one and the re-derived write committed instead.
124    /// `condition` is the `Ready` condition as written.
125    Published {
126        /// Whether the committed write was the second attempt.
127        retried: bool,
128        /// The `Ready` condition that was written.
129        condition: Value,
130        /// What the store did with the write.
131        effect: Effect,
132    },
133    /// The stored `Ready` condition already carries the derived status and
134    /// reason, and its heartbeat is younger than the refresh interval the
135    /// caller asked for. Nothing was proposed: writing on every tick would
136    /// grow the journal without bound on an idle cluster.
137    Unchanged,
138    /// There is no Node at the key. It is never created here: a Node deleted
139    /// between the read and the write stays deleted.
140    NoNode,
141    /// The stored Node carries no revision, so no precondition can be stated
142    /// and nothing was proposed.
143    Unversioned,
144    /// The stored Node is not a JSON object, so it cannot carry a condition.
145    /// Nothing was proposed: rewriting it is not the kubelet's call.
146    Malformed,
147    /// Both attempts lost to concurrent writes. Dropped; the next tick
148    /// re-derives from the Node as it is then.
149    Contended,
150    /// The store could not take the proposal at all.
151    Store(StoreError),
152}
153
154impl From<Unobservable> for ReadinessPublish {
155    fn from(why: Unobservable) -> Self {
156        match why {
157            Unobservable::Absent => Self::NoNode,
158            Unobservable::Unversioned => Self::Unversioned,
159        }
160    }
161}
162
163/// One CAS attempt, before the retry decision.
164enum Attempt {
165    Written(Value, Effect),
166    Unchanged,
167    Malformed,
168    Lost,
169    Failed(StoreError),
170}
171
172impl Attempt {
173    /// The publish outcome for an attempt that did not lose the race.
174    /// `Lost` is resolved by the caller, which alone knows whether a retry
175    /// remains.
176    fn settled(self, retried: bool) -> Option<ReadinessPublish> {
177        match self {
178            Self::Written(condition, effect) => Some(ReadinessPublish::Published {
179                retried,
180                condition,
181                effect,
182            }),
183            Self::Unchanged => Some(ReadinessPublish::Unchanged),
184            Self::Malformed => Some(ReadinessPublish::Malformed),
185            Self::Failed(e) => Some(ReadinessPublish::Store(e)),
186            Self::Lost => None,
187        }
188    }
189}
190
191/// Read the Node at `key`, derive its `Ready` condition from `lease`, and
192/// write it with a precondition — retrying once after a re-read if a
193/// concurrent write got there first.
194///
195/// `lease` is this node's Lease as read from the store (`None` when it has
196/// none); `now` stamps `lastHeartbeatTime`. `refresh` is how old a stored
197/// heartbeat may grow before an unchanged condition is written again; `None`
198/// writes only on a change of status or reason.
199pub async fn publish_ready(
200    store: &StoreMesh,
201    key: &ResourceKey,
202    lease: Option<&ResourceValue>,
203    now: &str,
204    refresh: Option<Duration>,
205) -> ReadinessPublish {
206    match ObservedNode::read(store, key).await {
207        Ok(observed) => publish_ready_onto(store, key, observed, lease, now, refresh).await,
208        Err(why) => why.into(),
209    }
210}
211
212/// [`publish_ready`] from a Node already read.
213///
214/// The seam exists so the race is testable: a caller may hand in an
215/// observation that a concurrent write has since superseded, which is exactly
216/// what happens when a cordon lands between the read and the write.
217pub async fn publish_ready_onto(
218    store: &StoreMesh,
219    key: &ResourceKey,
220    observed: ObservedNode,
221    lease: Option<&ResourceValue>,
222    now: &str,
223    refresh: Option<Duration>,
224) -> ReadinessPublish {
225    if let Some(done) = attempt(store, key, &observed, lease, now, refresh)
226        .await
227        .settled(false)
228    {
229        return done;
230    }
231    // Lost the race once: whatever committed since our read is now the base.
232    let fresh = match ObservedNode::read(store, key).await {
233        Ok(fresh) => fresh,
234        Err(why) => return why.into(),
235    };
236    attempt(store, key, &fresh, lease, now, refresh)
237        .await
238        .settled(true)
239        .unwrap_or(ReadinessPublish::Contended)
240}
241
242/// Derive the condition onto `observed` and write it at `observed.revision`.
243async fn attempt(
244    store: &StoreMesh,
245    key: &ResourceKey,
246    observed: &ObservedNode,
247    lease: Option<&ResourceValue>,
248    now: &str,
249    refresh: Option<Duration>,
250) -> Attempt {
251    let mut desired = observed.value.clone();
252    project_ready_condition(&mut desired, lease, now);
253    // `project_ready_condition` leaves a Ready condition on every JSON
254    // object, so its absence here means the stored Node is not one.
255    let Some(condition) = find_ready_condition(&desired).cloned() else {
256        return Attempt::Malformed;
257    };
258
259    let unchanged = find_ready_condition(&observed.value).is_some_and(|previous| {
260        previous.get("status") == condition.get("status")
261            && previous.get("reason") == condition.get("reason")
262            && !heartbeat_due(previous, refresh)
263    });
264    if unchanged {
265        return Attempt::Unchanged;
266    }
267
268    match store
269        .propose(ResourceCommand::Put {
270            key: key.clone(),
271            value: desired,
272            expected: Some(observed.revision),
273            reason: Reason::Controller,
274        })
275        .await
276    {
277        Ok(applied) if applied.op == ResourceOp::Conflict => Attempt::Lost,
278        Ok(applied) => Attempt::Written(condition, Effect::of(applied.op)),
279        Err(e) => Attempt::Failed(e),
280    }
281}
282
283fn heartbeat_due(previous: &Value, refresh: Option<Duration>) -> bool {
284    let Some(refresh) = refresh else {
285        return false;
286    };
287    previous
288        .get("lastHeartbeatTime")
289        .and_then(Value::as_str)
290        .and_then(engenho_types::time::age_since_rfc3339)
291        .is_none_or(|age| age >= refresh)
292}
293
294#[cfg(test)]
295mod tests {
296    use std::sync::Arc;
297    use std::time::Duration;
298
299    use crate::node_lease::lease_value;
300    use engenho_store::{InProcessRouter, default_config};
301    use serde_json::json;
302
303    use super::*;
304
305    async fn boot(name: &str) -> Arc<StoreMesh> {
306        let router = InProcessRouter::new();
307        let cfg = default_config(name).unwrap();
308        let store = Arc::new(
309            StoreMesh::start(1, "in-process://1".into(), router, cfg)
310                .await
311                .unwrap(),
312        );
313        store.initialize_singleton().await.unwrap();
314        assert!(store.wait_for_leadership(Duration::from_secs(3)).await);
315        store
316    }
317
318    async fn shutdown(store: Arc<StoreMesh>) {
319        Arc::try_unwrap(store)
320            .ok()
321            .unwrap()
322            .terminate()
323            .await
324            .unwrap();
325    }
326
327    fn node_key() -> ResourceKey {
328        ResourceKey::cluster_scoped("", "v1", "Node", "node-A")
329    }
330
331    /// A lease renewed just now — derives `Ready`.
332    fn fresh_lease() -> ResourceValue {
333        lease_value("node-A", &engenho_types::time::now_rfc3339_utc(), 0)
334    }
335
336    /// Seed the Node the way `register_node` stamps it at boot, plus a
337    /// condition this kubelet does not own.
338    async fn seed_node(store: &StoreMesh) {
339        store
340            .propose(ResourceCommand::Put {
341                key: node_key(),
342                value: json!({
343                    "kind": "Node",
344                    "apiVersion": "v1",
345                    "metadata": { "name": "node-A" },
346                    "status": { "conditions": [
347                        { "type": "Ready", "status": "True" },
348                        { "type": "MemoryPressure", "status": "False" }
349                    ]}
350                }),
351                expected: None,
352                reason: Reason::Operator,
353            })
354            .await
355            .unwrap();
356    }
357
358    /// `kubectl cordon` plus a taint and a label, committed as an operator
359    /// write on top of whatever the Node currently is.
360    async fn cordon(store: &StoreMesh) {
361        let mut node = store.get(&node_key()).await.unwrap();
362        node["spec"] = json!({
363            "unschedulable": true,
364            "taints": [{
365                "key": "node.kubernetes.io/unschedulable",
366                "effect": "NoSchedule"
367            }]
368        });
369        node["metadata"]["labels"] = json!({ "drain": "in-progress" });
370        store
371            .propose(ResourceCommand::Put {
372                key: node_key(),
373                value: node,
374                expected: None,
375                reason: Reason::Operator,
376            })
377            .await
378            .unwrap();
379    }
380
381    #[tokio::test]
382    async fn a_cordon_committed_between_read_and_write_survives() {
383        let store = boot("readiness-cordon-race").await;
384        seed_node(&store).await;
385
386        // The kubelet reads the Node...
387        let stale = ObservedNode::read(&store, &node_key()).await.unwrap();
388        // ...an operator cordons it...
389        cordon(&store).await;
390        // ...and the kubelet writes what it derived from the older read.
391        let lease = fresh_lease();
392        let outcome = publish_ready_onto(
393            &store,
394            &node_key(),
395            stale,
396            Some(&lease),
397            &engenho_types::time::now_rfc3339_utc(),
398            None,
399        )
400        .await;
401
402        let node = store.get(&node_key()).await.unwrap();
403        assert_eq!(
404            node["spec"]["unschedulable"], true,
405            "a readiness publish must never undo a cordon that committed after its read: {node}"
406        );
407        assert_eq!(
408            node["spec"]["taints"][0]["key"], "node.kubernetes.io/unschedulable",
409            "nor the taint that came with it: {node}"
410        );
411        assert_eq!(
412            node["metadata"]["labels"]["drain"], "in-progress",
413            "nor a label: {node}"
414        );
415
416        // Losing the race is not a reason to publish nothing: the retry
417        // re-derives onto the cordoned Node and commits.
418        assert!(
419            matches!(outcome, ReadinessPublish::Published { retried: true, .. }),
420            "the first write loses, the re-read write commits: {outcome:?}"
421        );
422        let ready = find_ready_condition(&node).expect("Ready was published");
423        assert_eq!(ready["status"], "True", "{node}");
424        assert_eq!(ready["reason"], "KubeletReady", "{node}");
425        assert!(
426            node["status"]["conditions"]
427                .as_array()
428                .is_some_and(|cs| cs.iter().any(|c| c["type"] == "MemoryPressure")),
429            "a condition this kubelet does not own survives the merge: {node}"
430        );
431
432        shutdown(store).await;
433    }
434
435    #[tokio::test]
436    async fn a_node_deleted_between_read_and_write_is_not_recreated() {
437        let store = boot("readiness-delete-race").await;
438        seed_node(&store).await;
439
440        let stale = ObservedNode::read(&store, &node_key()).await.unwrap();
441        store
442            .propose(ResourceCommand::delete(node_key(), Reason::Operator))
443            .await
444            .unwrap();
445
446        let lease = fresh_lease();
447        let outcome = publish_ready_onto(
448            &store,
449            &node_key(),
450            stale,
451            Some(&lease),
452            &engenho_types::time::now_rfc3339_utc(),
453            None,
454        )
455        .await;
456
457        assert!(
458            store.get(&node_key()).await.is_none(),
459            "a readiness publish must not resurrect a deleted Node"
460        );
461        assert!(
462            matches!(outcome, ReadinessPublish::NoNode),
463            "the re-read finds nothing and says so: {outcome:?}"
464        );
465
466        shutdown(store).await;
467    }
468
469    #[tokio::test]
470    async fn an_uncontended_publish_commits_first_time_then_holds() {
471        let store = boot("readiness-uncontended").await;
472        seed_node(&store).await;
473        let lease = fresh_lease();
474
475        let first = publish_ready(
476            &store,
477            &node_key(),
478            Some(&lease),
479            &engenho_types::time::now_rfc3339_utc(),
480            None,
481        )
482        .await;
483        assert!(
484            matches!(first, ReadinessPublish::Published { retried: false, .. }),
485            "nothing raced it, so the first write commits: {first:?}"
486        );
487
488        // Same derivation again: nothing an operator acts on changed, so
489        // nothing is proposed and the revision does not move.
490        let before = store.current_revision().await;
491        let second = publish_ready(
492            &store,
493            &node_key(),
494            Some(&lease),
495            &engenho_types::time::now_rfc3339_utc(),
496            None,
497        )
498        .await;
499        assert!(matches!(second, ReadinessPublish::Unchanged), "{second:?}");
500        assert_eq!(store.current_revision().await, before);
501
502        shutdown(store).await;
503    }
504
505    #[tokio::test]
506    async fn no_node_means_nothing_is_written() {
507        let store = boot("readiness-no-node").await;
508        let lease = fresh_lease();
509        let outcome = publish_ready(
510            &store,
511            &node_key(),
512            Some(&lease),
513            &engenho_types::time::now_rfc3339_utc(),
514            None,
515        )
516        .await;
517        assert!(matches!(outcome, ReadinessPublish::NoNode), "{outcome:?}");
518        assert!(
519            store.get(&node_key()).await.is_none(),
520            "registration creates Nodes; a readiness publish never does"
521        );
522        shutdown(store).await;
523    }
524
525    #[tokio::test]
526    async fn an_unchanged_condition_is_written_again_once_its_heartbeat_is_due() {
527        let store = boot("readiness-heartbeat-refresh").await;
528        seed_node(&store).await;
529        let lease = fresh_lease();
530        let now = engenho_types::time::now_rfc3339_utc();
531        let first = publish_ready(&store, &node_key(), Some(&lease), &now, None).await;
532        assert!(
533            matches!(first, ReadinessPublish::Published { .. }),
534            "{first:?}"
535        );
536
537        let held = store.current_revision().await;
538        let young = publish_ready(
539            &store,
540            &node_key(),
541            Some(&lease),
542            &now,
543            Some(REPORT_FREQUENCY),
544        )
545        .await;
546        assert!(matches!(young, ReadinessPublish::Unchanged), "{young:?}");
547        assert_eq!(store.current_revision().await, held);
548
549        let mut node = store.get(&node_key()).await.unwrap();
550        for c in node["status"]["conditions"].as_array_mut().unwrap() {
551            if c["type"] == "Ready" {
552                c["lastHeartbeatTime"] = serde_json::json!("2020-01-01T00:00:00Z");
553            }
554        }
555        store
556            .propose(ResourceCommand::Put {
557                key: node_key(),
558                value: node,
559                expected: None,
560                reason: Reason::Operator,
561            })
562            .await
563            .unwrap();
564        let stale_rv = resource_version_of(&store.get(&node_key()).await.unwrap()).unwrap();
565
566        let due = publish_ready(
567            &store,
568            &node_key(),
569            Some(&lease),
570            &now,
571            Some(REPORT_FREQUENCY),
572        )
573        .await;
574        assert!(matches!(due, ReadinessPublish::Published { .. }), "{due:?}");
575        let node = store.get(&node_key()).await.unwrap();
576        let ready = find_ready_condition(&node).unwrap();
577        assert_eq!(ready["lastHeartbeatTime"], now.as_str(), "{node}");
578        assert_ne!(
579            resource_version_of(&node).unwrap(),
580            stale_rv,
581            "a moved heartbeat is a new revision: {node}"
582        );
583
584        shutdown(store).await;
585    }
586
587    #[test]
588    fn a_node_without_a_revision_cannot_be_observed() {
589        // No revision, no precondition — and so no write. An observation that
590        // silently defaulted the revision would reopen the unconditional put.
591        let unversioned = json!({ "kind": "Node", "metadata": { "name": "node-A" } });
592        assert_eq!(
593            ObservedNode::from_stored(unversioned).err(),
594            Some(Unobservable::Unversioned)
595        );
596        let garbage = json!({ "metadata": { "resourceVersion": "not-a-number" } });
597        assert_eq!(
598            ObservedNode::from_stored(garbage).err(),
599            Some(Unobservable::Unversioned)
600        );
601    }
602}