engenho_controllers/owned_children.rs
1//! `OwnedChildrenReconciler` — the blanket-impl collapse of the
2//! owned-children controller family.
3//!
4//! ## The duplication this primitive removes
5//!
6//! Four status-writing workload controllers (`ReplicaSet` / Deployment /
7//! `StatefulSet` / Job) carried a byte-identical `tick` skeleton: list
8//! parents → skip parents with no `metadata.uid` → build the parent's
9//! owner-ref → gather owned children → reconcile the child delta →
10//! re-list the children → write `.status` via CAS. The ONLY thing that
11//! differed between them was (a) which parent kind they sweep and (b)
12//! the per-parent reconcile body (`reconcile_one`) + status math
13//! (`compute_status`).
14//!
15//! Per the Prime Directive (extend a primitive; collapse duplication to
16//! a trait + blanket impl, the way [`crate::status::write_status_cas`]
17//! collapsed the status half) this module hoists the shared S1–S6
18//! skeleton into ONE place. Each concrete controller now reduces to:
19//!
20//! * [`OwnedChildrenReconciler::parent_gvk`] — the parent it sweeps,
21//! * [`OwnedChildrenReconciler::child_kinds`] — the child kind(s) it
22//! gathers as owned children,
23//! * [`OwnedChildrenReconciler::also_reads`] — any kind its per-parent
24//! logic reads beyond those two,
25//! * [`OwnedChildrenReconciler::reconcile_one`] — the per-parent child
26//! delta (typed [`ResourceCommand`]s, never `format!()` of JSON),
27//! * [`OwnedChildrenReconciler::compute_status`] — the `.status` JSON
28//! computed from the LIVE children AFTER the delta committed.
29//!
30//! The blanket `impl<T: OwnedChildrenReconciler> Controller for T` runs
31//! the shared skeleton exactly once per parent, in the same order the
32//! hand-written ticks did. Its report counts parents (changed, unchanged,
33//! skipped, failed), not the writes made for them; see
34//! [`crate::sweep::SweepReport`].
35//!
36//! A second blanket, `impl<T: OwnedChildrenReconciler> DeclaresReads for
37//! T`, declares what the controller reads from the same three answers: the
38//! parent kind and child kinds the skeleton lists, plus
39//! [`OwnedChildrenReconciler::also_reads`]. The runtime derives the
40//! driver's wake filter from that (T1.7), so the kinds the skeleton reads
41//! and the kinds that wake it cannot disagree.
42//!
43//! ## Out of family (left as raw `impl Controller`)
44//!
45//! `endpoints` (selector-based, not owner-based; idempotency via a
46//! custom subset diff, NOT `write_status_cas`) and `gc` (an orphan
47//! sweep with NO single parent kind) are SIBLING shapes — they stay raw.
48//! Per the Prime Directive's "stop at diminishing returns," the blanket
49//! is NOT over-fit to those two outliers; if a third selector-shaped
50//! controller ripens, a sibling `SelectorReconciler` trait is the move.
51//!
52//! ## One parent's failure is that parent's (T4.3)
53//!
54//! The blanket runs each parent through the controller's
55//! [`Sweep`](crate::sweep::Sweep): an Item-scoped error from one parent —
56//! a template of the wrong JSON type, reported as
57//! [`ControllerError::Shape`] — becomes a Warning Event on that parent and
58//! the sweep moves to the next one. Only a store error still ends the tick.
59//! Before this, the templated-child writers panicked on a wrong-shaped
60//! template (`expect("ownerReferences must be array")`), and the panic took
61//! the controller task and every parent after it in the list.
62//!
63//! [`pod_from_template`] is the one place a Pod is cloned from a parent's
64//! `spec.template`, and every write into the clone goes through the total
65//! accessors in [`crate::meta`], so a wrong shape is an error naming the
66//! field in the PARENT (`spec.template.metadata.ownerReferences`), never a
67//! panic and never a silent skip.
68//!
69//! ## A Terminating child is left alone (I3)
70//!
71//! Since a delete carries its clock (store T3.6), a child with finalizers
72//! goes Terminating instead of vanishing, and stays in the store until its
73//! finalizers clear. Every writer in the family names its children
74//! deterministically (`{rs}-{n}`, `{sts}-{ordinal}`, `{ds}-{node}`,
75//! `{job}-{n}`, `{deployment}-{hash}`), so the name a writer wants can be
76//! held by a Terminating object: this parent's own child on its way out, or
77//! a previous incarnation's (a parent deleted and recreated under the same
78//! name while its children waited on finalizers).
79//!
80//! The blanket proposes no `Put` and no `Delete` to a key whose object is
81//! Terminating ([`ChildWrite::of`]), whichever writer asked:
82//!
83//! * a `Put` would REPLACE it: the new body carries no
84//! `deletionTimestamp`, so the store would store a live object where a
85//! Terminating one stood, clearing a stamp upstream never lets anything
86//! clear, and reusing a name its finalizers still hold;
87//! * a `Delete` is the store's `NoOp`, proposed again on every tick for as
88//! long as the finalizer holds: one Raft entry per child per tick for
89//! nothing.
90//!
91//! A `Patch` still goes through: a patch is how a Terminating object's
92//! finalizers are released, and a writer that scales a Terminating child
93//! converges after one write.
94//!
95//! Tier: enforced at this one propose site for every
96//! [`OwnedChildrenReconciler`], present and future, so a writer cannot opt
97//! out of it; a raw [`Controller`] that proposes on its own (gc, namespace,
98//! cronjob) applies [`ObjectMeta::is_terminating`] itself. Which children a
99//! writer COUNTS is still its own decision: a `ReplicaSet` counts only its
100//! live pods (see [`live_children`]).
101
102use async_trait::async_trait;
103use engenho_store::{StoreMesh, command::ResourceCommand, resource::ResourceKey};
104use engenho_types::kind::GroupVersionKind;
105use serde_json::Value;
106
107use crate::controller::{Controller, ReconcileOutcome};
108use crate::create_stamp::{CreateClock, stamp_create_timestamp, wall_clock};
109use crate::effect::Effect;
110use crate::error::ControllerError;
111use crate::meta::{ObjectMeta, ShapeError, object_mut};
112use crate::owner::{OwnerReference, is_owned_by, set_owner_reference};
113use crate::reads::{DeclaresReads, Reads, gvk};
114use crate::status::{generation_of, write_status_cas};
115use crate::sweep::{ObjectOutcome, Sweep};
116
117/// The parent field a templated child is cloned from.
118pub const TEMPLATE: &[&str] = &["spec", "template"];
119
120/// The owned children that are not Terminating: the ones a writer counts
121/// toward its desired set, and the only ones it chooses among to evict.
122///
123/// A Terminating child still holds its NAME: a writer allocating a name
124/// for a new child reads every owned child, not just these.
125pub fn live_children(
126 owned: &[(ResourceKey, Value)],
127) -> impl Iterator<Item = &(ResourceKey, Value)> {
128 owned.iter().filter(|(_, child)| !child.is_terminating())
129}
130
131/// What the blanket does with one child command, decided from the object
132/// the store holds at the command's key when it is about to propose it.
133#[derive(Debug, Clone, Copy, PartialEq, Eq)]
134pub enum ChildWrite {
135 /// A `Put` to an empty key: a create. The blanket freezes the child's
136 /// `metadata.creationTimestamp` into it before proposing.
137 Create,
138 /// Proposed as written.
139 Propose,
140 /// The key holds a Terminating object and the command is a `Put` or a
141 /// `Delete`: not proposed (see the module docs). The object is left to
142 /// its finalizers; the writer asks again on a later tick, once it is
143 /// gone.
144 LeaveTerminating,
145}
146
147impl ChildWrite {
148 /// The decision for `command` given `live`, the object the store holds
149 /// at [`child_write_target`]`(command)` (`None`: the key is empty, or the
150 /// command has no single target).
151 #[must_use]
152 pub fn of(command: &ResourceCommand, live: Option<&Value>) -> Self {
153 let terminating = live.is_some_and(ObjectMeta::is_terminating);
154 match command {
155 ResourceCommand::Put { .. } | ResourceCommand::Delete { .. } if terminating => {
156 Self::LeaveTerminating
157 }
158 ResourceCommand::Put { .. } if live.is_none() => Self::Create,
159 ResourceCommand::Put { .. }
160 | ResourceCommand::Delete { .. }
161 | ResourceCommand::Patch { .. }
162 | ResourceCommand::Txn { .. } => Self::Propose,
163 }
164 }
165}
166
167/// The key the blanket reads before proposing `command`: the target of a
168/// `Put` or a `Delete`, the two commands [`ChildWrite::of`] can leave
169/// unproposed. `None` for a `Patch` (always proposed) and a `Txn` (no
170/// single target). Exhaustive with no wildcard, so a new command variant
171/// does not compile until it is placed.
172#[must_use]
173pub const fn child_write_target(command: &ResourceCommand) -> Option<&ResourceKey> {
174 match command {
175 ResourceCommand::Put { key, .. } | ResourceCommand::Delete { key, .. } => Some(key),
176 ResourceCommand::Patch { .. } | ResourceCommand::Txn { .. } => None,
177 }
178}
179
180#[must_use]
181pub fn child_namespace(parent: &Value, scope: Option<&str>) -> String {
182 parent.namespace().or(scope).unwrap_or("default").to_owned()
183}
184
185/// A Pod cloned from `parent`'s `spec.template`: `kind`/`apiVersion`
186/// stamped, `metadata.name` set to `name`, `metadata.namespace` to
187/// `namespace`, and owned by `owner`.
188///
189/// `Ok(None)` when the parent declares no template (absent or `null`) —
190/// nothing to clone, the caller creates nothing.
191///
192/// # Errors
193///
194/// [`ShapeError`] when the template, its `metadata`, or its
195/// `metadata.ownerReferences` holds the wrong JSON type. The path is
196/// re-anchored under [`TEMPLATE`], so it names the field the operator
197/// declared on the parent.
198pub fn pod_from_template(
199 parent: &Value,
200 name: &str,
201 namespace: &str,
202 owner: OwnerReference,
203) -> Result<Option<Value>, ShapeError> {
204 let Some(template) = parent
205 .get("spec")
206 .and_then(|s| s.get("template"))
207 .filter(|t| !t.is_null())
208 else {
209 return Ok(None);
210 };
211 let mut pod = template.clone();
212 stamp_pod(&mut pod, name, namespace, owner).map_err(|e| e.under(TEMPLATE))?;
213 Ok(Some(pod))
214}
215
216/// The writes [`pod_from_template`] makes into its clone, with paths
217/// relative to the clone.
218fn stamp_pod(
219 pod: &mut Value,
220 name: &str,
221 namespace: &str,
222 owner: OwnerReference,
223) -> Result<(), ShapeError> {
224 let root = object_mut(pod, &[])?;
225 root.insert("kind".into(), Value::from("Pod"));
226 root.insert("apiVersion".into(), Value::from("v1"));
227 let metadata = object_mut(pod, &["metadata"])?;
228 metadata.insert("name".into(), Value::from(name));
229 metadata.insert("namespace".into(), Value::from(namespace));
230 set_owner_reference(pod, owner)?;
231 engenho_types::pod::stamp_birth_status(pod);
232 Ok(())
233}
234
235/// The object at `path` inside a Pod built by [`pod_from_template`], for a
236/// controller's own additions (a `DaemonSet`'s `spec.nodeName`, a Job's
237/// `spec.restartPolicy`); a wrong shape is reported under [`TEMPLATE`].
238///
239/// # Errors
240///
241/// [`ShapeError`] when a step of `path` in the template holds the wrong
242/// JSON type.
243pub fn template_object_mut<'v>(
244 pod: &'v mut Value,
245 path: &'static [&'static str],
246) -> Result<&'v mut serde_json::Map<String, Value>, ShapeError> {
247 object_mut(pod, path).map_err(|e| e.under(TEMPLATE))
248}
249
250/// The `(group, version, kind)` of the parent an owned-children
251/// controller sweeps, plus the `apiVersion` literal its owner-refs
252/// stamp. A typed struct (not a bare tuple) so the four fields can't be
253/// transposed at a call site.
254#[derive(Clone, Copy, Debug, PartialEq, Eq)]
255pub struct ParentGvk {
256 pub group: &'static str,
257 pub version: &'static str,
258 pub kind: &'static str,
259 /// The `apiVersion` literal owner-refs use (e.g. `"apps/v1"`,
260 /// `"batch/v1"`). Distinct from `group`/`version` because a child's
261 /// owner-ref carries the combined `apiVersion` string.
262 pub api_version: &'static str,
263}
264
265impl ParentGvk {
266 #[must_use]
267 pub const fn new(
268 group: &'static str,
269 version: &'static str,
270 kind: &'static str,
271 api_version: &'static str,
272 ) -> Self {
273 Self {
274 group,
275 version,
276 kind,
277 api_version,
278 }
279 }
280
281 /// The parent's `(group, version, kind)`, without the owner-ref
282 /// `apiVersion`.
283 #[must_use]
284 pub const fn gvk(self) -> GroupVersionKind {
285 gvk(self.group, self.version, self.kind)
286 }
287}
288
289/// The typed delta one owned-children parent produces in a tick: the
290/// child commands to propose (creates / evictions / scales) authored as
291/// typed [`ResourceCommand`]s — never `format!()` of JSON.
292#[derive(Debug, Default)]
293pub struct ReconcileDelta {
294 /// Commands to propose, in order. A parent any of whose commands (or
295 /// whose status write) committed is one changed object in the report.
296 pub commands: Vec<ResourceCommand>,
297}
298
299impl ReconcileDelta {
300 /// Empty delta — the parent is already at its fixpoint.
301 #[must_use]
302 pub fn none() -> Self {
303 Self::default()
304 }
305
306 /// Build a delta from a command vec.
307 #[must_use]
308 pub fn from_commands(commands: Vec<ResourceCommand>) -> Self {
309 Self { commands }
310 }
311}
312
313/// The shared owned-children reconcile shape. Implement this for a
314/// controller and it gets `Controller` for free via the blanket impl
315/// below — `parent_gvk` + `child_kinds` + `reconcile_one` +
316/// `compute_status` is the WHOLE per-controller surface.
317#[async_trait]
318pub trait OwnedChildrenReconciler: Send + Sync {
319 /// Stable controller name (telemetry + registration).
320 fn name(&self) -> &'static str;
321
322 /// The parent kind this controller sweeps + the `apiVersion` its
323 /// owner-refs stamp.
324 fn parent_gvk(&self) -> ParentGvk;
325
326 /// The child kind(s) the blanket gathers as owned children (filtered
327 /// by `is_owned_by(child, parent_uid)`). Usually a single kind
328 /// (ReplicaSet→Pod, Deployment→ReplicaSet); the slice supports
329 /// controllers that own more than one child kind.
330 fn child_kinds(&self) -> &'static [GroupVersionKind];
331
332 /// Every kind [`Self::reconcile_one`] reads from the store beyond the
333 /// parent and child kinds (the Nodes a `DaemonSet` places a pod on, the
334 /// claims a `StatefulSet` creates if absent). `&[]` when it reads none.
335 ///
336 /// No default: an implementer states it, so a read in `reconcile_one`
337 /// is not left out of the wake filter by forgetting to override one.
338 fn also_reads(&self) -> &'static [GroupVersionKind];
339
340 /// The store handle the blanket lists + proposes through.
341 fn store(&self) -> &StoreMesh;
342
343 /// Optional namespace scope (`None` = all namespaces).
344 fn namespace(&self) -> Option<&str>;
345
346 /// The per-parent isolation runner the blanket sweeps through. Built
347 /// with the controller's upstream component name and the reason a
348 /// failed parent is announced under; its event sink is wired by the
349 /// controller's `with_event_sink` builder.
350 fn sweep(&self) -> &Sweep;
351
352 /// The boundary clock the blanket reads ONCE per created child to
353 /// freeze `metadata.creationTimestamp` into the replicated `Put`
354 /// (see [`crate::create_stamp`]). Defaults to the production
355 /// wall-clock; unit tests override it to pin a fixed instant so the
356 /// reconcile stays deterministic + the stamped bytes are assertable.
357 fn create_clock(&self) -> CreateClock {
358 wall_clock
359 }
360
361 /// The ONLY per-controller child-reconcile logic: given one live
362 /// parent + the owned children gathered BEFORE this delta, return
363 /// the typed child delta (creates / evictions / scales). The blanket
364 /// proposes each command in order.
365 ///
366 /// # Errors
367 ///
368 /// A store failure while computing the delta ends the sweep; an
369 /// Item-scoped error ([`ControllerError::Shape`] for a template of the
370 /// wrong JSON type) fails this parent only, with an Event on it.
371 async fn reconcile_one(
372 &self,
373 parent: &Value,
374 owned: &[(ResourceKey, Value)],
375 ) -> Result<ReconcileDelta, ControllerError>;
376
377 /// Compute the parent's desired `.status` from the LIVE owned
378 /// children re-listed AFTER the delta committed. `None` means no
379 /// status is written this pass: a controller that has no status, or
380 /// one whose inputs it cannot read (a child whose status count is
381 /// malformed) — it says so with a warning rather than aggregating a
382 /// guess.
383 ///
384 /// `owned_after` is the post-delta owned-children set; the status
385 /// math is the per-controller logic (replica counting, phase
386 /// aggregation, …). `observed_generation` is the parent's
387 /// `metadata.generation`, read once by the blanket before anything
388 /// was written for the parent; a parent whose generation is malformed
389 /// never reaches here.
390 fn compute_status(
391 &self,
392 parent: &Value,
393 owned_after: &[(ResourceKey, Value)],
394 observed_generation: i64,
395 ) -> Option<Value>;
396}
397
398/// Gather the owned children of `parent_uid` across every kind in
399/// `child_kinds`, namespaced to `ns`. The single place
400/// `is_owned_by(child, uid)` is applied for the family.
401async fn gather_owned(
402 store: &StoreMesh,
403 child_kinds: &'static [GroupVersionKind],
404 parent_uid: &str,
405 ns: Option<&str>,
406) -> Vec<(ResourceKey, Value)> {
407 let mut owned = Vec::new();
408 for ck in child_kinds {
409 let all = store.list(ck.group, ck.version, ck.kind, ns).await;
410 for (k, v) in all {
411 if is_owned_by(&v, parent_uid) {
412 owned.push((k, v));
413 }
414 }
415 }
416 owned
417}
418
419#[async_trait]
420impl<T: OwnedChildrenReconciler> Controller for T {
421 fn name(&self) -> &'static str {
422 OwnedChildrenReconciler::name(self)
423 }
424
425 async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
426 let gvk = self.parent_gvk();
427
428 // S1 — list parents. The sweep counts them (examined is the sum of
429 // the per-parent outcomes).
430 let parents = self
431 .store()
432 .list(gvk.group, gvk.version, gvk.kind, self.namespace())
433 .await;
434
435 // S2–S6 per parent, isolated: an Item-scoped failure is recorded
436 // against its parent (Event, once per resourceVersion) and the
437 // sweep continues; a store failure ends the tick, as before.
438 let report = self
439 .sweep()
440 .run(&parents, |parent_key, parent_value| async move {
441 ObjectOutcome::settle(reconcile_parent(self, parent_key, parent_value).await)
442 })
443 .await?;
444 Ok(ReconcileOutcome::from(report))
445 }
446}
447
448/// What an owned-children controller reads: the parent kind and the child
449/// kinds its skeleton lists, and whatever its per-parent logic reads
450/// besides. The same three answers drive the reads, so the wake filter
451/// derived from this cannot miss a kind the skeleton lists.
452impl<T: OwnedChildrenReconciler> DeclaresReads for T {
453 fn reads(&self) -> Reads {
454 Reads::of(&[self.parent_gvk().gvk()])
455 .and(self.child_kinds().iter().copied())
456 .and(self.also_reads().iter().copied())
457 }
458}
459
460/// One parent's S2–S6, written with ordinary `?`; the sweep decides by the
461/// error's scope whether it ends this parent or the tick.
462async fn reconcile_parent<T: OwnedChildrenReconciler + ?Sized>(
463 this: &T,
464 parent_key: &ResourceKey,
465 parent_value: &Value,
466) -> Result<ObjectOutcome, ControllerError> {
467 let store = this.store();
468 let child_kinds = this.child_kinds();
469
470 // S2 — skip parents the apiserver hasn't stamped a uid on yet.
471 let Some(uid) = parent_value.uid() else {
472 tracing::debug!(
473 parent = %parent_key.label(),
474 "skipping parent with no metadata.uid"
475 );
476 return Ok(ObjectOutcome::SKIPPED);
477 };
478 let ns = parent_key.namespace.as_deref();
479 // The generation its status will claim to have observed, read before
480 // anything is written for it: a malformed one fails this parent (a
481 // Declarative Shape error — an Event on it) with nothing written.
482 let generation = generation_of(parent_value)?;
483
484 // S3/S4 — gather the owned children (pre-delta) the per-parent logic
485 // reconciles against. Owner-ref construction itself is the
486 // per-controller logic's concern (it calls owner::owner_ref_for with
487 // its own apiVersion literal); the blanket only orchestrates the
488 // gather/propose/status order.
489 let owned = gather_owned(store, child_kinds, uid, ns).await;
490
491 // S5 — the ONLY per-controller child reconcile. The whole delta is
492 // computed before anything is proposed, so a parent that fails here
493 // has had nothing written for it.
494 //
495 // creationTimestamp boundary stamp (★★ determinism): a `Put` of a key
496 // NOT yet in the store is a CREATE — freeze
497 // `metadata.creationTimestamp` from ONE clock read HERE (the leader
498 // boundary, before propose) so every Raft replica replays identical
499 // bytes. An update-shaped `Put` (key exists) is left untouched: the
500 // field is create-time, never bumped.
501 let delta = this.reconcile_one(parent_value, &owned).await?;
502 // What this parent's writes did, read off each op the store returned:
503 // a child delete the store answered NoOp (already gone) is no change.
504 let mut effect = Effect::Unchanged;
505 let mut parent_written = false;
506 for mut command in delta.commands {
507 parent_written |=
508 matches!(&command, ResourceCommand::Patch { key, .. } if key == parent_key);
509 let live = match child_write_target(&command) {
510 Some(key) => store.get(key).await,
511 None => None,
512 };
513 match ChildWrite::of(&command, live.as_ref()) {
514 ChildWrite::LeaveTerminating => {
515 tracing::debug!(
516 parent = %parent_key.label(),
517 child = %child_write_target(&command).map(ResourceKey::label).unwrap_or_default(),
518 "child is Terminating; left to its finalizers"
519 );
520 continue;
521 }
522 ChildWrite::Create => {
523 if let ResourceCommand::Put { value, .. } = &mut command {
524 stamp_create_timestamp(value, this.create_clock());
525 }
526 }
527 ChildWrite::Propose => {}
528 }
529 effect = effect.and(Effect::of(store.propose(command).await?.op));
530 }
531
532 // S6 — re-list owned children AFTER the delta committed (the store
533 // applies proposals synchronously) so the status math reflects this
534 // tick's own creates/deletes. Then write the CAS status (the same
535 // `write_status_cas` primitive the hand-written ticks used).
536 let owned_after = gather_owned(store, child_kinds, uid, ns).await;
537 // A delta that wrote the parent itself (a Job's generated selector)
538 // moved its resourceVersion; the status CAS is taken against that write,
539 // not against the copy listed before it.
540 let rewritten = if parent_written {
541 store.get(parent_key).await
542 } else {
543 None
544 };
545 let parent_value = rewritten.as_ref().unwrap_or(parent_value);
546 let generation = if parent_written {
547 generation_of(parent_value)?
548 } else {
549 generation
550 };
551 if let Some(desired_status) = this.compute_status(parent_value, &owned_after, generation) {
552 let status = write_status_cas(store, parent_key, parent_value, &desired_status).await?;
553 effect = effect.and(status.effect());
554 }
555
556 Ok(ObjectOutcome::from(effect))
557}
558
559#[cfg(test)]
560mod tests {
561 use super::*;
562 use engenho_store::command::{Reason, ResourceCommand};
563 use engenho_store::{InProcessRouter, default_config};
564 use serde_json::json;
565 use std::sync::Arc;
566 use std::time::Duration;
567
568 const FIXED_TS: &str = "2026-06-14T12:00:00Z";
569 fn fixed_clock() -> String {
570 FIXED_TS.to_string()
571 }
572
573 async fn test_store() -> Arc<StoreMesh> {
574 let router = InProcessRouter::new();
575 let cfg = default_config("controllers-owned-children").unwrap();
576 let store = Arc::new(
577 StoreMesh::start(1, "in-process://1".into(), router, cfg)
578 .await
579 .unwrap(),
580 );
581 store.initialize_singleton().await.unwrap();
582 assert!(store.wait_for_leadership(Duration::from_secs(3)).await);
583 store
584 }
585
586 /// A minimal owned-children controller: a "Widget" parent owns one
587 /// "Gadget" child it creates (a single child per parent, never
588 /// updated). The fixed clock proves the blanket stamps
589 /// creationTimestamp on the CREATE Put, frozen at the boundary.
590 struct WidgetReconciler {
591 store: Arc<StoreMesh>,
592 sweep: Sweep,
593 }
594
595 impl WidgetReconciler {
596 fn new(store: Arc<StoreMesh>) -> Self {
597 Self {
598 store,
599 sweep: Sweep::new(
600 "widget-controller",
601 crate::event_recorder::Reason::FailedCreate,
602 ),
603 }
604 }
605 }
606
607 #[async_trait]
608 impl OwnedChildrenReconciler for WidgetReconciler {
609 fn name(&self) -> &'static str {
610 "widget"
611 }
612 fn parent_gvk(&self) -> ParentGvk {
613 ParentGvk::new("demo", "v1", "Widget", "demo/v1")
614 }
615 fn child_kinds(&self) -> &'static [GroupVersionKind] {
616 const CK: &[GroupVersionKind] = &[gvk("demo", "v1", "Gadget")];
617 CK
618 }
619 fn also_reads(&self) -> &'static [GroupVersionKind] {
620 const ALSO: &[GroupVersionKind] = &[gvk("demo", "v1", "Sprocket")];
621 ALSO
622 }
623 fn store(&self) -> &StoreMesh {
624 &self.store
625 }
626 fn namespace(&self) -> Option<&str> {
627 None
628 }
629 fn sweep(&self) -> &Sweep {
630 &self.sweep
631 }
632 fn create_clock(&self) -> CreateClock {
633 fixed_clock
634 }
635 async fn reconcile_one(
636 &self,
637 parent: &Value,
638 owned: &[(ResourceKey, Value)],
639 ) -> Result<ReconcileDelta, ControllerError> {
640 if !owned.is_empty() {
641 return Ok(ReconcileDelta::none());
642 }
643 let ns = parent.namespace().unwrap_or("default").to_string();
644 let owner = crate::owner::owner_ref_for(parent, "demo/v1", "Widget").unwrap();
645 let mut child = json!({
646 "kind": "Gadget", "apiVersion": "demo/v1",
647 "metadata": {"name": "g", "namespace": ns}
648 });
649 crate::owner::set_owner_reference(&mut child, owner)?;
650 let key = ResourceKey::namespaced("demo", "v1", "Gadget", &ns, "g");
651 Ok(ReconcileDelta::from_commands(vec![ResourceCommand::Put {
652 key,
653 value: child,
654 expected: None,
655 reason: Reason::Controller,
656 }]))
657 }
658 fn compute_status(
659 &self,
660 _parent: &Value,
661 _owned_after: &[(ResourceKey, Value)],
662 _observed_generation: i64,
663 ) -> Option<Value> {
664 None
665 }
666 }
667
668 #[tokio::test]
669 async fn blanket_stamps_creation_timestamp_on_created_child() {
670 let store = test_store().await;
671 // Seed a parent Widget (the apiserver path would stamp its uid; here
672 // we propose it as Operator so the store mints uid deterministically).
673 let parent_key = ResourceKey::namespaced("demo", "v1", "Widget", "team-x", "w");
674 store
675 .propose(ResourceCommand::put(
676 parent_key,
677 json!({"kind": "Widget", "apiVersion": "demo/v1",
678 "metadata": {"name": "w", "namespace": "team-x"}}),
679 Reason::Operator,
680 ))
681 .await
682 .unwrap();
683
684 let c = WidgetReconciler::new(store.clone());
685 let out = c.tick().await.unwrap();
686 assert!(out.objects_changed >= 1, "the child was created");
687
688 // The created child carries the FROZEN creationTimestamp.
689 let child = store
690 .get(&ResourceKey::namespaced(
691 "demo", "v1", "Gadget", "team-x", "g",
692 ))
693 .await
694 .expect("child Gadget exists");
695 assert_eq!(
696 child
697 .get("metadata")
698 .unwrap()
699 .get("creationTimestamp")
700 .unwrap(),
701 FIXED_TS,
702 "controller-created child must carry the boundary-frozen creationTimestamp"
703 );
704 }
705
706 #[tokio::test]
707 async fn blanket_does_not_bump_creation_timestamp_on_subsequent_ticks() {
708 let store = test_store().await;
709 let parent_key = ResourceKey::namespaced("demo", "v1", "Widget", "team-y", "w");
710 store
711 .propose(ResourceCommand::put(
712 parent_key,
713 json!({"kind": "Widget", "apiVersion": "demo/v1",
714 "metadata": {"name": "w", "namespace": "team-y"}}),
715 Reason::Operator,
716 ))
717 .await
718 .unwrap();
719
720 let c = WidgetReconciler::new(store.clone());
721 // First tick creates the child + stamps the timestamp.
722 c.tick().await.unwrap();
723 let key = ResourceKey::namespaced("demo", "v1", "Gadget", "team-y", "g");
724 let ts1 = store
725 .get(&key)
726 .await
727 .unwrap()
728 .get("metadata")
729 .unwrap()
730 .get("creationTimestamp")
731 .unwrap()
732 .clone();
733 assert_eq!(ts1, FIXED_TS);
734
735 // Several more ticks: the child already exists (reconcile_one returns
736 // none), and even if a Put were re-issued the store-get-is-none guard
737 // prevents a re-stamp. The timestamp is STABLE — never bumped.
738 for _ in 0..3 {
739 c.tick().await.unwrap();
740 }
741 let ts2 = store
742 .get(&key)
743 .await
744 .unwrap()
745 .get("metadata")
746 .unwrap()
747 .get("creationTimestamp")
748 .unwrap()
749 .clone();
750 assert_eq!(
751 ts1, ts2,
752 "creationTimestamp must be stable across reconciles"
753 );
754 }
755
756 #[test]
757 fn parent_gvk_carries_four_fields() {
758 let g = ParentGvk::new("apps", "v1", "ReplicaSet", "apps/v1");
759 assert_eq!(g.group, "apps");
760 assert_eq!(g.version, "v1");
761 assert_eq!(g.kind, "ReplicaSet");
762 assert_eq!(g.api_version, "apps/v1");
763 }
764
765 #[test]
766 fn parent_gvk_drops_only_the_api_version() {
767 let g = ParentGvk::new("apps", "v1", "ReplicaSet", "apps/v1").gvk();
768 assert_eq!(g, gvk("apps", "v1", "ReplicaSet"));
769 }
770
771 /// The wake filter is derived from these reads (T1.7): the parent the
772 /// skeleton lists, the children it gathers, and what the per-parent
773 /// logic reads besides — and nothing it does not read.
774 #[tokio::test]
775 async fn an_owned_children_controller_reads_its_parent_children_and_extras() {
776 let c = WidgetReconciler::new(test_store().await);
777 let reads = c.reads();
778 assert_eq!(
779 reads.kinds(),
780 Some(
781 &[
782 gvk("demo", "v1", "Widget"),
783 gvk("demo", "v1", "Gadget"),
784 gvk("demo", "v1", "Sprocket"),
785 ][..]
786 )
787 );
788 let wakes = reads.filter();
789 for kind in ["Widget", "Gadget", "Sprocket"] {
790 assert!(wakes.wakes_on(kind), "{kind} does not wake it");
791 }
792 assert!(!wakes.wakes_on("Pod"));
793 }
794
795 #[test]
796 fn reconcile_delta_none_is_empty() {
797 let d = ReconcileDelta::none();
798 assert!(d.commands.is_empty());
799 }
800
801 // ── a Terminating child is left alone (I3) ───────────────────────────
802
803 fn child_key() -> ResourceKey {
804 ResourceKey::namespaced("", "v1", "Pod", "ns", "rs-0")
805 }
806
807 fn live_child() -> Value {
808 json!({"metadata": {"name": "rs-0", "finalizers": ["example.com/hold"]}})
809 }
810
811 fn terminating_child() -> Value {
812 json!({"metadata": {
813 "name": "rs-0",
814 "finalizers": ["example.com/hold"],
815 "deletionTimestamp": "2026-09-19T00:00:00Z"
816 }})
817 }
818
819 /// One command of each kind at the child's key.
820 fn every_command() -> [ResourceCommand; 4] {
821 [
822 ResourceCommand::put(child_key(), live_child(), Reason::Controller),
823 ResourceCommand::delete(child_key(), Reason::Controller),
824 ResourceCommand::patch(
825 child_key(),
826 json!({"metadata": {"finalizers": []}}),
827 Reason::Controller,
828 ),
829 ResourceCommand::Txn {
830 compares: Vec::new(),
831 success: Vec::new(),
832 failure: Vec::new(),
833 reason: Reason::Controller,
834 },
835 ]
836 }
837
838 #[test]
839 fn a_put_or_delete_to_a_terminating_child_is_not_proposed() {
840 let [put, delete, patch, txn] = every_command();
841 let terminating = terminating_child();
842 assert_eq!(
843 ChildWrite::of(&put, Some(&terminating)),
844 ChildWrite::LeaveTerminating,
845 "a Put would replace a Terminating object with a live one"
846 );
847 assert_eq!(
848 ChildWrite::of(&delete, Some(&terminating)),
849 ChildWrite::LeaveTerminating,
850 "a second delete of a Terminating object is the store's NoOp"
851 );
852 assert_eq!(
853 ChildWrite::of(&patch, Some(&terminating)),
854 ChildWrite::Propose,
855 "a patch is how a Terminating object's finalizers are released"
856 );
857 assert_eq!(ChildWrite::of(&txn, None), ChildWrite::Propose);
858 }
859
860 #[test]
861 fn a_live_or_absent_child_is_written_as_asked() {
862 let [put, delete, patch, _] = every_command();
863 let live = live_child();
864 assert_eq!(ChildWrite::of(&put, None), ChildWrite::Create);
865 assert_eq!(ChildWrite::of(&put, Some(&live)), ChildWrite::Propose);
866 assert_eq!(ChildWrite::of(&delete, Some(&live)), ChildWrite::Propose);
867 assert_eq!(ChildWrite::of(&delete, None), ChildWrite::Propose);
868 assert_eq!(ChildWrite::of(&patch, Some(&live)), ChildWrite::Propose);
869 }
870
871 #[test]
872 fn only_a_put_or_a_delete_names_a_key_to_read() {
873 let [put, delete, patch, txn] = every_command();
874 assert_eq!(child_write_target(&put), Some(&child_key()));
875 assert_eq!(child_write_target(&delete), Some(&child_key()));
876 assert_eq!(child_write_target(&patch), None);
877 assert_eq!(child_write_target(&txn), None);
878 }
879
880 #[test]
881 fn live_children_leaves_out_the_terminating_ones() {
882 let owned = vec![
883 (child_key(), terminating_child()),
884 (
885 ResourceKey::namespaced("", "v1", "Pod", "ns", "rs-1"),
886 json!({"metadata": {"name": "rs-1"}}),
887 ),
888 ];
889 let live: Vec<&str> = live_children(&owned)
890 .map(|(k, _)| k.name.as_str())
891 .collect();
892 assert_eq!(live, ["rs-1"]);
893 }
894}