Skip to main content

engenho_controllers/
replicaset.rs

1//! `ReplicaSetController` — keeps the observed pod count matching
2//! `spec.replicas` per `ReplicaSet`.
3//!
4//! The reconciliation rule:
5//!   * count the LIVE Pods owned by the `ReplicaSet` (controller-owned,
6//!     not Terminating — upstream's `FilterActivePods`)
7//!   * if count < replicas: create the difference (each Pod cloned
8//!     from `spec.template` + owner-referenced + named uniquely)
9//!   * if count > replicas: delete the excess among the live pods
10//!     (eviction by name order for predictability)
11//!
12//! A Terminating pod is on its way out: it is not counted, never chosen
13//! for eviction, and still holds its name, so its replacement takes the
14//! next free index rather than its own.
15//!
16//! No scheduling here — that's the scheduler's job. The Pods get
17//! created without `spec.nodeName`; the scheduler binds them in
18//! its own loop.
19
20use std::sync::Arc;
21
22use async_trait::async_trait;
23use engenho_store::{
24    StoreMesh,
25    command::{Reason, ResourceCommand},
26    resource::ResourceKey,
27};
28use serde_json::{Value, json};
29
30use crate::error::ControllerError;
31use crate::event_recorder::Reason as EventReason;
32use crate::meta::{ObjectMeta, REPLICAS, ShapeError};
33use crate::owned_children::{
34    OwnedChildrenReconciler, ParentGvk, ReconcileDelta, live_children, pod_from_template,
35};
36use crate::owner::{OwnerReference, owner_ref_for};
37use crate::reads::gvk;
38use crate::status::pod_is_ready;
39use crate::sweep::{Sweep, impl_sweep_event_sink};
40use engenho_types::kind::GroupVersionKind;
41
42pub struct ReplicaSetController {
43    store: Arc<StoreMesh>,
44    /// Optional namespace scope. None = all namespaces.
45    namespace: Option<String>,
46    /// Per-`ReplicaSet` isolation: a `ReplicaSet` whose template has the wrong
47    /// shape gets a `FailedCreate` Event and the others still converge.
48    sweep: Sweep,
49}
50
51impl_sweep_event_sink!(ReplicaSetController);
52
53impl ReplicaSetController {
54    #[must_use]
55    pub fn new(store: Arc<StoreMesh>, namespace: Option<String>) -> Self {
56        Self {
57            store,
58            namespace,
59            sweep: Sweep::new("replicaset-controller", EventReason::FailedCreate),
60        }
61    }
62
63    /// Construct a Pod object from a `ReplicaSet`'s `spec.template`,
64    /// owned by `owner`. Names the Pod `{rs_name}-{index}`, deterministic
65    /// for tests + readable for operators.
66    ///
67    /// `Ok(None)` when the `ReplicaSet` has no name or no template.
68    ///
69    /// # Errors
70    ///
71    /// [`ShapeError`] when the template has the wrong JSON shape.
72    fn build_pod_from_template(
73        rs: &Value,
74        index: usize,
75        owner: OwnerReference,
76    ) -> Result<Option<(String, Value)>, ShapeError> {
77        let Some(rs_name) = rs.name() else {
78            return Ok(None);
79        };
80        // Pod lives in the SAME namespace as its parent ReplicaSet — the
81        // namespace the blanket gathers owned pods from. Never the
82        // controller's scope namespace (an all-namespace controller has none).
83        let rs_namespace = rs.namespace().unwrap_or("default");
84        // Generate a deterministic-ish name: {rs}-{index}
85        // (Production K8s uses random hashes; for R9 we keep it
86        // deterministic for test reproducibility. R9.5+ can swap
87        // in nanoid if name collisions matter.)
88        let pod_name = format!("{rs_name}-{index}");
89        let pod = pod_from_template(rs, &pod_name, rs_namespace, owner)?;
90        Ok(pod.map(|pod| (pod_name, pod)))
91    }
92}
93
94/// The set of `<rs>-<index>` suffix indices already in use among the owned
95/// pods. A pod whose name is `<rs_name>-<n>` (with `<n>` a parseable usize)
96/// contributes `n`; any other shape is ignored (it can't collide on an index).
97/// `rs_name = None` (a freshly-minted RS with no name) yields the empty set.
98fn used_indices(
99    rs_name: Option<&str>,
100    owned_pods: &[(ResourceKey, Value)],
101) -> std::collections::BTreeSet<usize> {
102    let mut used = std::collections::BTreeSet::new();
103    let Some(rs_name) = rs_name else {
104        return used;
105    };
106    let prefix = format!("{rs_name}-");
107    for (key, _) in owned_pods {
108        if let Some(suffix) = key.name.strip_prefix(&prefix)
109            && let Ok(n) = suffix.parse::<usize>()
110        {
111            used.insert(n);
112        }
113    }
114    used
115}
116
117/// The lowest `count` indices NOT in `used`, ascending. Fills freed slots
118/// first (so a middle delete recreates the freed index, never clobbering a
119/// surviving pod), then extends past the high-water mark.
120fn free_indices(used: &std::collections::BTreeSet<usize>, count: usize) -> Vec<usize> {
121    let mut out = Vec::with_capacity(count);
122    let mut idx = 0usize;
123    while out.len() < count {
124        if !used.contains(&idx) {
125            out.push(idx);
126        }
127        idx += 1;
128    }
129    out
130}
131
132#[async_trait]
133impl OwnedChildrenReconciler for ReplicaSetController {
134    fn name(&self) -> &'static str {
135        "replicaset"
136    }
137
138    fn parent_gvk(&self) -> ParentGvk {
139        ParentGvk::new("apps", "v1", "ReplicaSet", "apps/v1")
140    }
141
142    fn child_kinds(&self) -> &'static [GroupVersionKind] {
143        const CHILD_KINDS: &[GroupVersionKind] = &[gvk("", "v1", "Pod")];
144        CHILD_KINDS
145    }
146
147    fn also_reads(&self) -> &'static [GroupVersionKind] {
148        &[]
149    }
150
151    fn store(&self) -> &StoreMesh {
152        &self.store
153    }
154
155    fn namespace(&self) -> Option<&str> {
156        self.namespace.as_deref()
157    }
158
159    fn sweep(&self) -> &Sweep {
160        &self.sweep
161    }
162
163    async fn reconcile_one(
164        &self,
165        rs_value: &Value,
166        owned_pods: &[(ResourceKey, Value)],
167    ) -> Result<ReconcileDelta, ControllerError> {
168        // A `spec.replicas` that is not an integer fails this ReplicaSet
169        // (an Event on it) with nothing created or evicted — never the
170        // default's count.
171        let desired = REPLICAS.read(rs_value)?.max(0) as usize;
172        // A Terminating pod is already going: counting it would leave the
173        // set a replica short until its finalizers clear, and evicting it
174        // again would be a delete that changes nothing while a live pod the
175        // count needs gone stays (I3).
176        let live: Vec<&(ResourceKey, Value)> = live_children(owned_pods).collect();
177        let observed = live.len();
178
179        // Fixpoint — nothing to create or evict.
180        if observed == desired {
181            return Ok(ReconcileDelta::none());
182        }
183
184        // Lazily build the owner ref; skip (empty delta) when the parent
185        // has no uid/name yet (a freshly minted RS). The blanket already
186        // skipped no-uid parents, but name may still be missing.
187        let Some(owner_ref) = owner_ref_for(rs_value, "apps/v1", "ReplicaSet") else {
188            return Ok(ReconcileDelta::none());
189        };
190        let pod_ns = crate::owned_children::child_namespace(rs_value, self.namespace.as_deref());
191        let mut commands = Vec::new();
192
193        if observed < desired {
194            // Create the difference at the LOWEST FREE indices — NOT
195            // `observed + i`. The old `observed + i` basis CLOBBERED a
196            // surviving pod when a MIDDLE pod was deleted: deleting `<rs>-0`
197            // left `observed=1`, so the recreate targeted index 1 → the name
198            // `<rs>-1` COLLIDED with the surviving `<rs>-1` pod, and the
199            // `Put { expected: None }` overwrote it (resetting its
200            // scheduler-assigned `spec.nodeName` from the template → the
201            // kubelet then orphaned + removed its container → churn). Filling
202            // the lowest free index instead recreates `<rs>-0` (the freed
203            // slot), so the survivor `<rs>-1` is never touched. Names stay
204            // deterministic for tests; self-heal after a middle delete works.
205            // Every owned pod, Terminating ones included: a Terminating pod
206            // still holds its name until its finalizers clear.
207            let used = used_indices(rs_value.name(), owned_pods);
208            let free = free_indices(&used, desired - observed);
209            for idx in free {
210                let Some((pod_name, pod)) =
211                    Self::build_pod_from_template(rs_value, idx, owner_ref.clone())?
212                else {
213                    continue;
214                };
215                let pod_key = ResourceKey::namespaced("", "v1", "Pod", &pod_ns, &pod_name);
216                commands.push(ResourceCommand::Put {
217                    key: pod_key,
218                    value: pod,
219                    expected: None,
220                    reason: Reason::Controller,
221                });
222            }
223        } else {
224            // observed > desired — evict the excess live pods by name order
225            // (highest names first) for deterministic eviction.
226            let to_delete = observed - desired;
227            let mut live_sorted = live;
228            live_sorted.sort_by(|a, b| a.0.name.cmp(&b.0.name));
229            for (pod_key, _) in live_sorted.iter().rev().take(to_delete) {
230                commands.push(ResourceCommand::delete(
231                    (*pod_key).clone(),
232                    Reason::Controller,
233                ));
234            }
235        }
236
237        Ok(ReconcileDelta::from_commands(commands))
238    }
239
240    fn compute_status(
241        &self,
242        _rs_value: &Value,
243        owned_now: &[(ResourceKey, Value)],
244        observed_generation: i64,
245    ) -> Option<Value> {
246        // Status computed from the owned pods AFTER the reconcile delta,
247        // counting only the live ones (upstream `calculateStatus` over
248        // `FilterActivePods`): a Terminating pod is not a replica.
249        // readyReplicas counts Ready=True pods; availableReplicas ==
250        // readyReplicas at M0.1 (no minReadySeconds); fullyLabeledReplicas
251        // == replicas.
252        let live: Vec<&(ResourceKey, Value)> = live_children(owned_now).collect();
253        let replicas = i64::try_from(live.len()).unwrap_or(i64::MAX);
254        let ready =
255            i64::try_from(live.iter().filter(|(_, p)| pod_is_ready(p)).count()).unwrap_or(i64::MAX);
256        Some(json!({
257            "replicas": replicas,
258            "readyReplicas": ready,
259            "availableReplicas": ready,
260            "fullyLabeledReplicas": replicas,
261            "observedGeneration": observed_generation,
262        }))
263    }
264}
265
266#[cfg(test)]
267mod tests {
268    use super::*;
269
270    #[test]
271    fn replicas_defaults_to_1() {
272        let rs = json!({"metadata": {"name": "rs"}, "spec": {}});
273        assert_eq!(REPLICAS.read(&rs), Ok(1));
274    }
275
276    #[test]
277    fn replicas_reads_spec_field() {
278        let rs = json!({"spec": {"replicas": 5}});
279        assert_eq!(REPLICAS.read(&rs), Ok(5));
280    }
281
282    fn rs_owner() -> OwnerReference {
283        OwnerReference {
284            api_version: "apps/v1".into(),
285            kind: "ReplicaSet".into(),
286            name: "rs1".into(),
287            uid: "uid-rs1".into(),
288            controller: true,
289            block_owner_deletion: true,
290        }
291    }
292
293    #[test]
294    fn build_pod_from_template_sets_name_and_metadata() {
295        let rs = json!({
296            "metadata": {"name": "rs1"},
297            "spec": {
298                "template": {
299                    "metadata": {"labels": {"app": "rs1"}},
300                    "spec": {"containers": [{"name": "c", "image": "img"}]}
301                }
302            }
303        });
304        let (name, pod) = ReplicaSetController::build_pod_from_template(&rs, 0, rs_owner())
305            .unwrap()
306            .unwrap();
307        assert_eq!(name, "rs1-0");
308        assert_eq!(
309            pod["status"]["phase"], "Pending",
310            "a controller-built pod is born with status: {pod}"
311        );
312        assert_eq!(pod.get("kind").unwrap(), "Pod");
313        assert_eq!(pod.get("apiVersion").unwrap(), "v1");
314        assert_eq!(pod.get("metadata").unwrap().get("name").unwrap(), "rs1-0");
315        // No RS namespace → the pod defaults to "default".
316        assert_eq!(
317            pod.get("metadata").unwrap().get("namespace").unwrap(),
318            "default"
319        );
320        // Template labels survive.
321        assert_eq!(
322            pod.get("metadata")
323                .unwrap()
324                .get("labels")
325                .unwrap()
326                .get("app")
327                .unwrap(),
328            "rs1"
329        );
330    }
331
332    #[test]
333    fn build_pod_from_template_inherits_the_replicasets_namespace() {
334        // The Pod MUST land in the parent RS's namespace — not "default".
335        // Regression test for the bug where an RS in ns `team-b` produced
336        // pods in `default`, breaking the owned-pod gathering + scheduling.
337        let rs = json!({
338            "metadata": {"name": "rs1", "namespace": "team-b"},
339            "spec": {"template": {
340                "metadata": {"labels": {"app": "rs1"}},
341                "spec": {"containers": [{"name": "c", "image": "img"}]}
342            }}
343        });
344        let (name, pod) = ReplicaSetController::build_pod_from_template(&rs, 2, rs_owner())
345            .unwrap()
346            .unwrap();
347        assert_eq!(name, "rs1-2");
348        assert_eq!(
349            pod.get("metadata").unwrap().get("namespace").unwrap(),
350            "team-b"
351        );
352    }
353
354    #[test]
355    fn owner_ref_for_constructs_typed_ref() {
356        let rs = json!({
357            "metadata": {"name": "rs1", "uid": "uid-1"},
358            "spec": {"replicas": 1}
359        });
360        let owner = owner_ref_for(&rs, "apps/v1", "ReplicaSet").unwrap();
361        assert_eq!(owner.api_version, "apps/v1");
362        assert_eq!(owner.kind, "ReplicaSet");
363        assert_eq!(owner.uid, "uid-1");
364        assert!(owner.controller);
365        assert!(owner.block_owner_deletion);
366    }
367
368    #[test]
369    fn owner_ref_for_returns_none_without_uid() {
370        let rs = json!({"metadata": {"name": "rs1"}});
371        assert!(owner_ref_for(&rs, "apps/v1", "ReplicaSet").is_none());
372    }
373
374    // ── collision-free index allocation (middle-delete self-heal) ─────────
375
376    fn owned(rs: &str, idx: usize) -> (ResourceKey, Value) {
377        let name = format!("{rs}-{idx}");
378        (
379            ResourceKey::namespaced("", "v1", "Pod", "default", &name),
380            json!({"metadata": {"name": name}}),
381        )
382    }
383
384    #[test]
385    fn used_indices_extracts_suffix_numbers() {
386        let pods = vec![owned("rs1", 0), owned("rs1", 2), owned("rs1", 5)];
387        let used = used_indices(Some("rs1"), &pods);
388        assert_eq!(used.into_iter().collect::<Vec<_>>(), vec![0, 2, 5]);
389    }
390
391    #[test]
392    fn used_indices_ignores_foreign_names() {
393        // A pod whose name isn't `<rs>-<n>` contributes nothing.
394        let pods = vec![owned("rs1", 1), owned("other", 0)];
395        let used = used_indices(Some("rs1"), &pods);
396        assert_eq!(used.into_iter().collect::<Vec<_>>(), vec![1]);
397    }
398
399    #[test]
400    fn free_indices_fills_freed_middle_slot_first() {
401        // The bug scenario: pods -0 deleted, survivor -1 in use → recreate
402        // must target the FREED index 0, NOT collide on 1.
403        let used: std::collections::BTreeSet<usize> = [1usize].into_iter().collect();
404        assert_eq!(free_indices(&used, 1), vec![0]);
405    }
406
407    #[test]
408    fn free_indices_extends_past_high_water_mark() {
409        // No freed slots → extend upward from the lowest unused index.
410        let used: std::collections::BTreeSet<usize> = [0usize, 1].into_iter().collect();
411        assert_eq!(free_indices(&used, 2), vec![2, 3]);
412    }
413
414    #[test]
415    fn free_indices_mixed_freed_and_extend() {
416        // Freed 0 + survivors {1,3} → fill 0, then 2, then extend to 4.
417        let used: std::collections::BTreeSet<usize> = [1usize, 3].into_iter().collect();
418        assert_eq!(free_indices(&used, 3), vec![0, 2, 4]);
419    }
420
421    #[test]
422    fn middle_delete_recreates_freed_index_not_survivor() {
423        // End-to-end of the fix: RS desired=2, only `rs1-1` survives (the `-0`
424        // was deleted). The recreate must allocate index 0 (the freed slot),
425        // never re-Put `rs1-1` (which would clobber the survivor's nodeName).
426        let surviving = vec![owned("rs1", 1)];
427        let used = used_indices(Some("rs1"), &surviving);
428        let free = free_indices(&used, 2 - surviving.len());
429        assert_eq!(
430            free,
431            vec![0],
432            "must recreate the freed index 0, not collide on 1"
433        );
434    }
435}