Skip to main content

engenho_controllers/
status.rs

1//! M0.1 item 8 — shared status-subresource write primitive.
2//!
3//! Every workload controller (Deployment / `ReplicaSet` / `StatefulSet` /
4//! Job) computes a `.status` from the LIVE owned children it already
5//! listed in its tick + writes it back. Per the Prime Directive this is
6//! solved ONCE here: [`write_status_cas`] is the single shape all four
7//! controllers consume.
8//!
9//! ## Three invariants this primitive enforces
10//!
11//! 1. **Idempotent skip (the primary hot-loop defense).** The desired
12//!    status is compared field-by-field against the status already on the
13//!    live object; if they are equal AND `status.observedGeneration`
14//!    already equals `metadata.generation`, NO command is proposed
15//!    ([`StatusWriteOutcome::NoChange`]). A no-op reconcile tick mutates
16//!    nothing, so the watch event it would otherwise produce never
17//!    happens and the loop terminates.
18//!
19//! 2. **Optimistic concurrency (item-5 CAS).** The status `Patch` carries
20//!    `expected: Some(rv)` where `rv` is the object's
21//!    `metadata.resourceVersion` AS SEEN THIS TICK. If a concurrent spec
22//!    change (operator scale) committed between the controller's list and
23//!    this write, `mod_revision` advanced, the precondition fails, and
24//!    the store returns `ResourceOp::Conflict`. That is a benign retry
25//!    (`Proposed(Rejected(Conflict))`) — the write is dropped, the next
26//!    watch-wake re-reads fresh state and recomputes. A status write thus
27//!    NEVER clobbers a concurrent spec change.
28//!
29//!    What the store did is read through [`Effect::of`], never by testing
30//!    for one op: a patch the store refused for any reason
31//!    (`PatchRejected`, `ApplyConflict`) is reported refused, not
32//!    `Written`.
33//!
34//! 3. **Typed emission.** The status JSON is authored as a typed
35//!    `serde_json::Value` (the store is opaque-JSON); no `format!()` of
36//!    JSON.
37//!
38//! ## The second shape: an edit of the object as read (T2.5)
39//!
40//! [`write_status_cas`] writes a status computed from what the controller
41//! LISTED, so after a conflict it cannot recompute: it drops the write and
42//! the next watch-wake starts over. [`edit_status_cas`] is for a status
43//! that is a function of the object itself, such as one condition set by
44//! type ([`upsert_condition_cas`]). It reads the object, asks the edit what
45//! to write, writes that at the revision it read, and on a conflict reads
46//! again and retries exactly once. Its outcome names each way nothing was
47//! written ([`StatusEditOutcome`]), where [`StatusWriteOutcome::NoChange`]
48//! folds "already current" and "no revision" into one arm.
49//!
50//! The reads and writes go through [`CasEnv`], the store in production
51//! ([`StoreCasEnv`]) and a fake that races a concurrent writer in tests.
52
53use async_trait::async_trait;
54use engenho_store::{
55    ApplyResult, StoreMesh,
56    command::{Reason, ResourceCommand},
57    resource::ResourceKey,
58    revision::Revision,
59};
60use serde_json::{Map, Value};
61use tracing::{debug, warn};
62
63use crate::condition::{DesiredCondition, upsert_condition};
64use crate::effect::{Effect, Refusal};
65use crate::error::ControllerError;
66use crate::meta::{DefaultedInt, ShapeError};
67
68/// Outcome of a [`write_status_cas`] call.
69#[derive(Clone, Copy, Debug, PartialEq, Eq)]
70pub enum StatusWriteOutcome {
71    /// Nothing was proposed: the computed status already matched the live
72    /// one (which carries `observedGeneration`, so the generation has been
73    /// observed too), or the parent had no resourceVersion to CAS against.
74    /// The idempotent-skip hot-loop defense: no Raft round trip.
75    NoChange,
76    /// A status patch was proposed, and this is what the store did with it:
77    /// `Written` when it landed, `Rejected(Conflict)` when a concurrent spec
78    /// change moved the object first (benign — the next watch-wake
79    /// recomputes), `Rejected(PatchRejected | ApplyConflict)` when the store
80    /// refused the patch itself.
81    Proposed(Effect),
82}
83
84impl StatusWriteOutcome {
85    /// What this call did, as one [`Effect`]: nothing proposed is
86    /// `Unchanged`.
87    pub const fn effect(self) -> Effect {
88        match self {
89            Self::NoChange => Effect::Unchanged,
90            Self::Proposed(effect) => effect,
91        }
92    }
93
94    /// True iff a status patch landed.
95    #[must_use]
96    pub const fn changed(self) -> bool {
97        self.effect().landed()
98    }
99}
100
101/// Parse a stored object's `metadata.resourceVersion` string into a
102/// [`Revision`] — the CAS `expected` value for the status write.
103///
104/// Returns `None` when the field is absent or unparseable (a freshly
105/// minted object the controller hasn't re-read yet); the caller then
106/// skips the CAS write this tick rather than issuing an unconditional one
107/// that could clobber a concurrent spec change.
108#[must_use]
109pub fn resource_version_of(value: &Value) -> Option<Revision> {
110    value
111        .get("metadata")
112        .and_then(|m| m.get("resourceVersion"))
113        .and_then(|rv| rv.as_str())
114        .and_then(|s| s.parse::<u64>().ok())
115        .map(Revision)
116}
117
118/// `metadata.generation`, the spec-intent revision `observedGeneration`
119/// reconciles against. The store stamps it on every write; `0` (never
120/// stamped) when absent.
121pub const GENERATION: DefaultedInt = DefaultedInt::new(&["metadata", "generation"], 0);
122
123/// Read `metadata.generation` off a stored object. `0` when absent.
124///
125/// # Errors
126///
127/// [`ShapeError::NotAnInteger`] when the field holds anything but an
128/// integer: a status claiming to have observed it would be a guess.
129pub fn generation_of(value: &Value) -> Result<i64, ShapeError> {
130    GENERATION.read(value)
131}
132
133/// Borrow the live `.status` object, or a static empty object when
134/// absent — so the idempotent comparison treats "no status yet" as an
135/// empty status (any non-empty desired status differs → first write).
136#[must_use]
137fn live_status(value: &Value) -> Value {
138    value
139        .get("status")
140        .cloned()
141        .unwrap_or_else(|| Value::Object(serde_json::Map::new()))
142}
143
144/// Write a controller-computed `.status` onto `parent` via an
145/// optimistic-concurrency `Patch`, skipping the write entirely when the
146/// status is already current.
147///
148/// `parent` is the LIVE object the controller listed this tick (it
149/// carries `metadata.resourceVersion` + `metadata.generation` +
150/// existing `.status`). `desired_status` is the status object computed
151/// from the live owned children — it MUST already include
152/// `observedGeneration` set to the parent's `metadata.generation` (the
153/// owned-children blanket reads it once through [`generation_of`] and
154/// hands it to `compute_status`).
155///
156/// # Errors
157///
158/// [`ControllerError::Store`] only on a genuine store/transport failure.
159/// A write the store refused is NOT an error — it returns
160/// `Proposed(Effect::Rejected(_))`, naming the refusal.
161pub async fn write_status_cas(
162    store: &StoreMesh,
163    key: &ResourceKey,
164    parent: &Value,
165    desired_status: &Value,
166) -> Result<StatusWriteOutcome, ControllerError> {
167    // Idempotent skip (hot-loop defense): if the live status already
168    // equals the desired status (which carries observedGeneration), there
169    // is nothing to write. Because desired_status embeds
170    // observedGeneration == generation, equality here also implies the
171    // generation has been observed — one comparison covers both.
172    if &live_status(parent) == desired_status {
173        return Ok(StatusWriteOutcome::NoChange);
174    }
175
176    // CAS precondition = the object's resourceVersion as seen this tick.
177    // When it's missing/unparseable the object was just minted and not
178    // re-read; skip rather than issue an unconditional clobbering write.
179    let Some(expected) = resource_version_of(parent) else {
180        debug!(
181            key = %key.label(),
182            "status write skipped: parent has no parseable resourceVersion this tick"
183        );
184        return Ok(StatusWriteOutcome::NoChange);
185    };
186
187    let result = store
188        .propose(ResourceCommand::patch_cas(
189            key.clone(),
190            serde_json::json!({ "status": desired_status }),
191            Some(expected),
192            Reason::Controller,
193        ))
194        .await?;
195
196    Ok(read_answer(key, expected, &result))
197}
198
199/// Read the store's answer to a proposed status patch, by [`Effect::of`]:
200/// every op the store can return is placed, so a refusal of any kind is
201/// reported refused and only a landed patch is `Written`.
202fn read_answer(key: &ResourceKey, expected: Revision, answer: &ApplyResult) -> StatusWriteOutcome {
203    let effect = read_effect(key, answer);
204    if effect == Effect::Rejected(Refusal::Conflict) {
205        // A concurrent spec change advanced mod_revision between the
206        // list and this write. Benign — dropped; the next watch-wake
207        // re-reads fresh state and recomputes.
208        debug!(
209            key = %key.label(),
210            expected = %expected,
211            "status write conflicted with a concurrent spec change; dropping (will recompute on next wake)"
212        );
213    }
214    StatusWriteOutcome::Proposed(effect)
215}
216
217/// What the store did with a proposed status patch, logging a refusal of
218/// the patch itself. A conflict is the caller's to explain: one drops the
219/// write, the other retries it.
220fn read_effect(key: &ResourceKey, answer: &ApplyResult) -> Effect {
221    let effect = Effect::of(answer.op);
222    if let Effect::Rejected(refusal @ (Refusal::PatchRejected | Refusal::ApplyConflict)) = effect {
223        // The store refused the patch itself. Nothing was written, and
224        // proposing the same patch again will not change that.
225        warn!(
226            key = %key.label(),
227            %refusal,
228            detail = answer.patch_error.as_deref().unwrap_or(""),
229            "status write refused; nothing was written"
230        );
231    }
232    effect
233}
234
235/// The reads and writes of a read-modify-write: read the object, and write
236/// an RFC 7396 merge patch conditioned on the revision read.
237///
238/// [`StoreCasEnv`] in production; a fake in tests, which can move the
239/// object between the read and the write.
240#[async_trait]
241pub trait CasEnv: Send + Sync {
242    /// The live object at `key`, if any.
243    async fn get(&self, key: &ResourceKey) -> Option<Value>;
244
245    /// Merge `patch` into the object at `key` if it is still at revision
246    /// `pinned`, and return the store's answer.
247    ///
248    /// # Errors
249    ///
250    /// [`ControllerError::Store`] on a transport failure. A refused write
251    /// is an answer (`ResourceOp::Conflict`, …), not an error.
252    async fn patch_at(
253        &self,
254        key: &ResourceKey,
255        patch: Value,
256        pinned: Revision,
257    ) -> Result<ApplyResult, ControllerError>;
258}
259
260/// [`CasEnv`] over the store, writing as one [`Reason`].
261#[derive(Clone, Copy)]
262pub struct StoreCasEnv<'a> {
263    store: &'a StoreMesh,
264    reason: Reason,
265}
266
267impl<'a> StoreCasEnv<'a> {
268    /// Read `store`, and write to it as `reason` (the scheduler writes as
269    /// [`Reason::Scheduler`], a controller as [`Reason::Controller`]).
270    #[must_use]
271    pub const fn new(store: &'a StoreMesh, reason: Reason) -> Self {
272        Self { store, reason }
273    }
274}
275
276#[async_trait]
277impl CasEnv for StoreCasEnv<'_> {
278    async fn get(&self, key: &ResourceKey) -> Option<Value> {
279        self.store.get(key).await
280    }
281
282    async fn patch_at(
283        &self,
284        key: &ResourceKey,
285        patch: Value,
286        pinned: Revision,
287    ) -> Result<ApplyResult, ControllerError> {
288        Ok(self
289            .store
290            .propose(ResourceCommand::patch_cas(
291                key.clone(),
292                patch,
293                Some(pinned),
294                self.reason,
295            ))
296            .await?)
297    }
298}
299
300/// What an edit makes of the object it was handed.
301#[derive(Debug, Clone, PartialEq)]
302pub enum StatusEdit {
303    /// The object already says what the edit would write.
304    Current,
305    /// The object no longer calls for this edit: it moved on since the
306    /// caller decided to make it (a pod bound in the meantime).
307    Superseded,
308    /// Merge these fields into `.status`.
309    Write(Map<String, Value>),
310}
311
312/// Outcome of an [`edit_status_cas`] call. Every arm but `Proposed` means
313/// nothing was proposed, and each says why.
314#[derive(Clone, Copy, Debug, PartialEq, Eq)]
315pub enum StatusEditOutcome {
316    /// The object already carries the edit. No Raft round trip, no event.
317    Unchanged,
318    /// The edit no longer applies ([`StatusEdit::Superseded`]).
319    Superseded,
320    /// There is no object at the key.
321    Absent,
322    /// The object has no parseable `metadata.resourceVersion` to write at.
323    /// An unconditional write could clobber a concurrent one, so none is
324    /// made.
325    NoRevision,
326    /// A patch was proposed at the revision read, and this is what the
327    /// store did with it. When the first attempt conflicted, this is the
328    /// answer to the one retry.
329    Proposed(Effect),
330}
331
332impl StatusEditOutcome {
333    /// What this call did, as one [`Effect`]: nothing proposed is
334    /// `Unchanged`.
335    pub const fn effect(self) -> Effect {
336        match self {
337            Self::Unchanged | Self::Superseded | Self::Absent | Self::NoRevision => {
338                Effect::Unchanged
339            }
340            Self::Proposed(effect) => effect,
341        }
342    }
343
344    /// True iff a status patch landed.
345    #[must_use]
346    pub const fn changed(self) -> bool {
347        self.effect().landed()
348    }
349}
350
351/// Read the object at `key`, ask `edit` what to merge into its `.status`,
352/// and write that at the revision read. On a conflict, read again and retry
353/// exactly once.
354///
355/// The retry re-runs `edit` on the object as re-read, so it writes on top of
356/// whatever the concurrent writer did, and finds `Unchanged` or `Superseded`
357/// when that writer made the edit unnecessary. A second conflict is
358/// returned as `Proposed(Rejected(Conflict))`; the write that moved the
359/// object fires a watch event, which re-ticks the caller.
360///
361/// # Errors
362///
363/// [`ControllerError::Store`] on a transport failure, and
364/// [`ControllerError::Shape`] when `edit` finds the object malformed. A
365/// write the store refused is an outcome, not an error.
366pub async fn edit_status_cas<E, F>(
367    env: &E,
368    key: &ResourceKey,
369    edit: F,
370) -> Result<StatusEditOutcome, ControllerError>
371where
372    E: CasEnv + ?Sized,
373    F: Fn(&Value) -> Result<StatusEdit, ShapeError> + Sync,
374{
375    match edit_once(env, key, &edit).await? {
376        StatusEditOutcome::Proposed(Effect::Rejected(Refusal::Conflict)) => {
377            debug!(
378                key = %key.label(),
379                "status edit conflicted with a concurrent write; reading again and retrying once"
380            );
381            edit_once(env, key, &edit).await
382        }
383        outcome => Ok(outcome),
384    }
385}
386
387/// One read, one edit, at most one write.
388async fn edit_once<E, F>(
389    env: &E,
390    key: &ResourceKey,
391    edit: &F,
392) -> Result<StatusEditOutcome, ControllerError>
393where
394    E: CasEnv + ?Sized,
395    F: Fn(&Value) -> Result<StatusEdit, ShapeError> + Sync,
396{
397    let Some(object) = env.get(key).await else {
398        return Ok(StatusEditOutcome::Absent);
399    };
400    let fields = match edit(&object)? {
401        StatusEdit::Current => return Ok(StatusEditOutcome::Unchanged),
402        StatusEdit::Superseded => return Ok(StatusEditOutcome::Superseded),
403        StatusEdit::Write(fields) => fields,
404    };
405    let Some(pinned) = resource_version_of(&object) else {
406        debug!(
407            key = %key.label(),
408            "status edit skipped: the object has no parseable resourceVersion"
409        );
410        return Ok(StatusEditOutcome::NoRevision);
411    };
412    let mut patch = Map::new();
413    patch.insert("status".to_owned(), Value::Object(fields));
414    let answer = env.patch_at(key, Value::Object(patch), pinned).await?;
415    Ok(StatusEditOutcome::Proposed(read_effect(key, &answer)))
416}
417
418/// Set one condition on the object at `key`, by type
419/// ([`upsert_condition`]), writing at the revision read and retrying once
420/// on a conflict ([`edit_status_cas`]).
421///
422/// `Unchanged` when the object already carries the condition: nothing is
423/// proposed, so a controller that asserts the same condition every tick does
424/// not wake itself. `now` is the RFC 3339 instant recorded as
425/// `lastTransitionTime` when the status transitions.
426///
427/// # Errors
428///
429/// As [`edit_status_cas`].
430pub async fn upsert_condition_cas<E>(
431    env: &E,
432    key: &ResourceKey,
433    desired: &DesiredCondition,
434    now: &str,
435) -> Result<StatusEditOutcome, ControllerError>
436where
437    E: CasEnv + ?Sized,
438{
439    edit_status_cas(env, key, |object| {
440        Ok(upsert_condition(object, desired, now)?
441            .into_status_fields()
442            .map_or(StatusEdit::Current, StatusEdit::Write))
443    })
444    .await
445}
446
447/// True iff `pod` reports a `status.conditions[type=Ready,status=True]`.
448/// The shared readiness predicate for the replica-counting controllers.
449#[must_use]
450pub fn pod_is_ready(pod: &Value) -> bool {
451    pod.get("status")
452        .and_then(|s| s.get("conditions"))
453        .and_then(|c| c.as_array())
454        .is_some_and(|conds| {
455            conds.iter().any(|c| {
456                c.get("type").and_then(|t| t.as_str()) == Some("Ready")
457                    && c.get("status").and_then(|s| s.as_str()) == Some("True")
458            })
459        })
460}
461
462#[cfg(test)]
463mod tests {
464    use super::*;
465    use serde_json::json;
466
467    #[test]
468    fn resource_version_parses_string_field() {
469        let v = json!({"metadata": {"resourceVersion": "42"}});
470        assert_eq!(resource_version_of(&v), Some(Revision(42)));
471    }
472
473    #[test]
474    fn resource_version_none_when_absent_or_bad() {
475        assert_eq!(resource_version_of(&json!({"metadata": {}})), None);
476        assert_eq!(
477            resource_version_of(&json!({"metadata": {"resourceVersion": "x"}})),
478            None
479        );
480    }
481
482    #[test]
483    fn generation_reads_metadata_field() {
484        assert_eq!(
485            generation_of(&json!({"metadata": {"generation": 3}})),
486            Ok(3)
487        );
488        assert_eq!(generation_of(&json!({"metadata": {}})), Ok(0));
489    }
490
491    /// A generation that is not an integer is not generation 0: a status
492    /// stamped `observedGeneration: 0` from it would claim to have
493    /// observed a spec revision nobody can name.
494    #[test]
495    fn a_malformed_generation_is_an_error_not_zero() {
496        assert_eq!(
497            generation_of(&json!({"metadata": {"generation": "3"}}))
498                .unwrap_err()
499                .to_string(),
500            "metadata.generation is not an integer (found a string)"
501        );
502    }
503
504    #[test]
505    fn live_status_defaults_to_empty_object() {
506        assert_eq!(live_status(&json!({})), json!({}));
507        assert_eq!(
508            live_status(&json!({"status": {"replicas": 2}})),
509            json!({"replicas": 2})
510        );
511    }
512
513    #[test]
514    fn pod_is_ready_detects_ready_condition() {
515        let ready = json!({"status": {"conditions": [{"type": "Ready", "status": "True"}]}});
516        let not_ready = json!({"status": {"conditions": [{"type": "Ready", "status": "False"}]}});
517        let no_status = json!({"metadata": {"name": "p"}});
518        assert!(pod_is_ready(&ready));
519        assert!(!pod_is_ready(&not_ready));
520        assert!(!pod_is_ready(&no_status));
521    }
522
523    fn answer(op: engenho_store::command::ResourceOp) -> ApplyResult {
524        ApplyResult {
525            op,
526            ..ApplyResult::default()
527        }
528    }
529
530    /// A status patch the store refused is reported refused, naming why —
531    /// never `Written`. Only `Conflict` used to be read; `PatchRejected` and
532    /// `ApplyConflict` fell through to `Written`, so a controller counted a
533    /// status change the catalog never saw.
534    #[test]
535    fn a_refused_status_patch_is_reported_refused() {
536        use engenho_store::command::ResourceOp;
537        let key = ResourceKey::namespaced("apps", "v1", "Deployment", "ns", "web");
538        for (op, refusal) in [
539            (ResourceOp::Conflict, Refusal::Conflict),
540            (ResourceOp::PatchRejected, Refusal::PatchRejected),
541            (ResourceOp::ApplyConflict, Refusal::ApplyConflict),
542        ] {
543            let outcome = read_answer(&key, Revision(7), &answer(op));
544            assert_eq!(
545                outcome,
546                StatusWriteOutcome::Proposed(Effect::Rejected(refusal)),
547                "{op:?}"
548            );
549            assert!(!outcome.changed(), "{op:?} wrote nothing");
550        }
551        assert!(read_answer(&key, Revision(7), &answer(ResourceOp::Patched)).changed());
552        assert_eq!(
553            read_answer(&key, Revision(7), &answer(ResourceOp::NoOp)).effect(),
554            Effect::Unchanged
555        );
556    }
557
558    #[test]
559    fn outcome_changed_only_when_the_patch_landed() {
560        use engenho_store::command::ResourceOp;
561        assert!(StatusWriteOutcome::Proposed(Effect::of(ResourceOp::Patched)).changed());
562        assert!(!StatusWriteOutcome::NoChange.changed());
563        for refused in [
564            ResourceOp::Conflict,
565            ResourceOp::PatchRejected,
566            ResourceOp::ApplyConflict,
567            ResourceOp::NoOp,
568        ] {
569            assert!(
570                !StatusWriteOutcome::Proposed(Effect::of(refused)).changed(),
571                "{refused:?} wrote nothing"
572            );
573        }
574    }
575
576    #[tokio::test]
577    async fn a_pod_status_write_is_a_new_revision_and_a_modified_event() {
578        use engenho_store::command::{Reason, ResourceCommand};
579        use engenho_store::{
580            InProcessRouter, StoreMesh, WatchEventKind, WatchOpts, WatchSignal, default_config,
581        };
582
583        let store = StoreMesh::start(
584            1,
585            "in-process://1".into(),
586            InProcessRouter::new(),
587            default_config("pod-status-revision").unwrap(),
588        )
589        .await
590        .unwrap();
591        store.initialize_singleton().await.unwrap();
592        assert!(
593            store
594                .wait_for_leadership(std::time::Duration::from_secs(3))
595                .await
596        );
597        let key = ResourceKey::namespaced("", "v1", "Pod", "default", "p");
598        store
599            .propose(ResourceCommand::put(
600                key.clone(),
601                serde_json::json!({"metadata": {"name": "p", "namespace": "default"},
602                    "spec": {"containers": [{"name": "c", "image": "i"}]},
603                    "status": {"phase": "Pending", "qosClass": "BestEffort"}}),
604                Reason::Operator,
605            ))
606            .await
607            .unwrap();
608        let pod = store.get(&key).await.unwrap();
609        let mut watch = store
610            .watch_from(WatchOpts::from_revision(store.current_revision().await))
611            .await
612            .unwrap();
613        let running = serde_json::json!({"phase": "Running", "qosClass": "BestEffort"});
614        assert!(
615            write_status_cas(&store, &key, &pod, &running)
616                .await
617                .unwrap()
618                .changed()
619        );
620        let after = store.get(&key).await.unwrap();
621        assert!(
622            resource_version_of(&after) > resource_version_of(&pod),
623            "{after}"
624        );
625        let Some(Ok(WatchSignal::Event(event))) =
626            tokio::time::timeout(std::time::Duration::from_secs(2), watch.next())
627                .await
628                .unwrap()
629        else {
630            panic!("no event for a pod status write");
631        };
632        assert_eq!(event.kind, WatchEventKind::Modified);
633        assert_eq!(event.object["status"]["phase"], "Running");
634        assert!(matches!(
635            write_status_cas(&store, &key, &after, &running)
636                .await
637                .unwrap(),
638            StatusWriteOutcome::NoChange
639        ));
640    }
641}