Skip to main content

engenho_controllers/
statefulset.rs

1//! R15 — `StatefulSet` controller.
2//!
3//! Like `ReplicaSetController` but with **ordered, persistent
4//! identity**: pods get names `{sts}-0`, `{sts}-1`, ...
5//! Replacement keeps the same name + PVC mapping.
6//!
7//! ## Reconcile rule
8//!
9//! For each `StatefulSet`:
10//!   1. `desired_replicas` = spec.replicas (default 1)
11//!   2. owned pods = pods with controller-ref UID matching
12//!   3. for i in `0..desired_replicas`:
13//!         `expected_name` = "{sts}-{i}"
14//!         if no pod with that name exists → create from template
15//!   4. for each owned pod with ordinal >= `desired_replicas`:
16//!         delete (scale-down evicts highest-ordinal first)
17//!
18//! Identity is preserved across restart: pod `web-2` always has
19//! the same volume claims + (with R13 wiring) the same persistent
20//! volume.
21//!
22//! ## Updates (`spec.updateStrategy`)
23//!
24//!   5. every pod is stamped with its template revision
25//!      ([`crate::rollout`]); a `Failed` ordinal is deleted and recreated;
26//!   6. under `RollingUpdate` (the default, as upstream) the highest
27//!      out-of-date ordinal at or above `partition` is deleted, one at a
28//!      time, the next only once every ordinal above it is current and
29//!      Ready; under `OnDelete` nothing is replaced by the controller.
30
31use std::sync::Arc;
32
33use async_trait::async_trait;
34use engenho_store::{
35    StoreMesh,
36    command::{Reason, ResourceCommand},
37    resource::ResourceKey,
38};
39use serde_json::{Value, json};
40use tracing::{debug, info};
41
42use crate::error::ControllerError;
43use crate::event_recorder::Reason as EventReason;
44use crate::meta::ObjectMeta;
45use crate::meta::{REPLICAS, ShapeError, array_mut};
46use crate::owned_children::{OwnedChildrenReconciler, ParentGvk, ReconcileDelta};
47use crate::owned_children::{TEMPLATE, pod_from_template};
48use crate::owner::{OwnerReference, owner_ref_for};
49use crate::reads::gvk;
50use crate::rollout::{TemplateRevision, UpdateStrategy, pod_is_failed};
51use crate::status::pod_is_ready;
52use crate::sweep::{Sweep, impl_sweep_event_sink};
53use engenho_types::kind::GroupVersionKind;
54
55/// Where a pod's volumes live.
56const POD_VOLUMES: &[&str] = &["spec", "volumes"];
57
58/// `StatefulSet` controller — peer to `ReplicaSetController` with
59/// ordered identity semantics.
60pub struct StatefulSetController {
61    store: Arc<StoreMesh>,
62    namespace: Option<String>,
63    /// Per-StatefulSet isolation (`FailedCreate` on a malformed template).
64    sweep: Sweep,
65}
66
67impl_sweep_event_sink!(StatefulSetController);
68
69impl StatefulSetController {
70    /// Construct with optional namespace scope.
71    #[must_use]
72    pub fn new(store: Arc<StoreMesh>, namespace: Option<String>) -> Self {
73        Self {
74            store,
75            namespace,
76            sweep: Sweep::new("statefulset-controller", EventReason::FailedCreate),
77        }
78    }
79
80    /// Build a Pod from the `StatefulSet` template at ordinal `i`.
81    /// The name is `{sts_name}-{i}` — ordered + persistent.
82    ///
83    /// The Pod inherits the parent `StatefulSet`'s namespace — the
84    /// namespace the blanket gathers owned pods from. Never the
85    /// controller's scope namespace (an all-namespace controller has
86    /// none). Mirrors `ReplicaSetController::build_pod_from_template`;
87    /// keying a pod under the controller scope ns instead of the
88    /// parent's broke owned-pod gathering for namespaced parents (the
89    /// same just-fixed bug as deployment→RS and replicaset→pod).
90    ///
91    /// `volumeClaimTemplates` (PVC provisioning) is scoped OUT at M0 —
92    /// the PVC/storage subsystem is a separate engenho gap. BUT when the
93    /// `StatefulSet` declares `spec.volumeClaimTemplates`, the pod's
94    /// matching `spec.volumes[].persistentVolumeClaim.claimName` is set
95    /// to the deterministic per-pod PVC name `{template}-{sts}-{ordinal}`
96    /// (the K8s naming contract) so the wiring is CORRECT the moment PVCs
97    /// land — no rename needed.
98    ///
99    /// `Ok(None)` when the `StatefulSet` has no name or no template.
100    ///
101    /// # Errors
102    ///
103    /// [`ShapeError`] when the template, its `spec`, or its `spec.volumes`
104    /// has the wrong JSON shape.
105    fn build_pod(
106        sts: &Value,
107        ordinal: usize,
108        owner: OwnerReference,
109    ) -> Result<Option<(String, Value)>, ShapeError> {
110        let Some(sts_name) = sts.name() else {
111            return Ok(None);
112        };
113        let sts_namespace = sts.namespace().unwrap_or("default");
114        let pod_name = format!("{sts_name}-{ordinal}");
115        let Some(mut pod) = pod_from_template(sts, &pod_name, sts_namespace, owner)? else {
116            return Ok(None);
117        };
118
119        // Per-pod PVC volume wiring from volumeClaimTemplates (deterministic
120        // name; provisioning itself is a separate gap — see doc above).
121        Self::wire_pvc_volumes(sts, &mut pod, sts_name, ordinal).map_err(|e| e.under(TEMPLATE))?;
122
123        Ok(Some((pod_name, pod)))
124    }
125
126    /// Materialize `spec.volumeClaimTemplates` into real per-pod PVCs.
127    ///
128    /// ── ★ WHY THIS EXISTS ──────────────────────────────────────────────
129    /// The naming contract and the pod-side wiring shipped at M0; only the
130    /// CLAIM was missing, so a `StatefulSet` with storage produced a pod
131    /// referencing `{template}-{sts}-{ordinal}` that nothing ever created.
132    /// The pod then waits on a volume forever, which presents as a slow
133    /// scheduler rather than as a missing subsystem.
134    ///
135    /// Measured 2026-09-14 on ryn: a MySQL `StatefulSet` reached `mysql-0`
136    /// with `persistentVolumeClaim.claimName: data-mysql-0` and
137    /// `kubectl get pvc` returned nothing at all.
138    ///
139    /// Each claim is the template's own `spec` verbatim — accessModes,
140    /// resources, storageClassName, and `dataSource` — so a claim whose
141    /// template names a `VolumeSnapshot` restores from it through the same
142    /// binder path an explicit PVC uses. That is what lets a restore vector
143    /// be expressed as `VolumeSnapshot -> StatefulSet` with no hand-written
144    /// PVC in between.
145    ///
146    /// Returns `(name, object)` pairs; empty when the set declares no
147    /// templates, so a storage-less `StatefulSet` is untouched.
148    fn build_pvcs(
149        sts: &Value,
150        sts_name: &str,
151        ordinal: usize,
152        namespace: &str,
153    ) -> Vec<(String, Value)> {
154        let Some(vcts) = sts
155            .get("spec")
156            .and_then(|s| s.get("volumeClaimTemplates"))
157            .and_then(|v| v.as_array())
158        else {
159            return Vec::new();
160        };
161        let mut out = Vec::new();
162        for vct in vcts {
163            let Some(tpl_name) = vct
164                .get("metadata")
165                .and_then(|m| m.get("name"))
166                .and_then(Value::as_str)
167            else {
168                // A template with no name has no derivable claim name. Skip
169                // it rather than invent one: a guessed name would not match
170                // what `wire_pvc_volumes` put on the pod.
171                continue;
172            };
173            let claim_name = format!("{tpl_name}-{sts_name}-{ordinal}");
174            // The template's spec verbatim — including dataSource, which is
175            // the restore-from-snapshot path.
176            let spec = vct.get("spec").cloned().unwrap_or_else(|| json!({}));
177            out.push((
178                claim_name.clone(),
179                json!({
180                    "apiVersion": "v1",
181                    "kind": "PersistentVolumeClaim",
182                    "metadata": {
183                        "name": claim_name,
184                        "namespace": namespace,
185                        // The upstream label, so a claim is traceable to its
186                        // set without an ownerReference (see the retention
187                        // note at the call site).
188                        "labels": { "app.kubernetes.io/managed-by": "engenho-statefulset" },
189                    },
190                    "spec": spec,
191                }),
192            ));
193        }
194        out
195    }
196
197    /// For each `spec.volumeClaimTemplates[i].metadata.name`, append a
198    /// `spec.volumes` entry on the pod referencing the deterministic
199    /// per-pod claim `{template}-{sts}-{ordinal}` (the K8s naming
200    /// contract). PVC objects themselves are NOT created here (storage is
201    /// a separate engenho gap) — only the pod-side reference, so the pod
202    /// is correct once PVCs land. Idempotent: skips a volume name already
203    /// present on the pod template.
204    fn wire_pvc_volumes(
205        sts: &Value,
206        pod: &mut Value,
207        sts_name: &str,
208        ordinal: usize,
209    ) -> Result<(), ShapeError> {
210        let Some(vcts) = sts
211            .get("spec")
212            .and_then(|s| s.get("volumeClaimTemplates"))
213            .and_then(|v| v.as_array())
214        else {
215            return Ok(());
216        };
217        if vcts.is_empty() {
218            return Ok(());
219        }
220        let arr = array_mut(pod, POD_VOLUMES)?;
221        for vct in vcts {
222            let Some(tmpl_name) = vct
223                .get("metadata")
224                .and_then(|m| m.get("name"))
225                .and_then(|n| n.as_str())
226            else {
227                continue;
228            };
229            // Idempotence: a template that already declares this volume name
230            // (operator pre-wired it) is left untouched.
231            let already = arr
232                .iter()
233                .any(|v| v.get("name").and_then(|n| n.as_str()) == Some(tmpl_name));
234            if already {
235                continue;
236            }
237            let claim_name = Self::pvc_claim_name(tmpl_name, sts_name, ordinal);
238            arr.push(json!({
239                "name": tmpl_name,
240                "persistentVolumeClaim": { "claimName": claim_name }
241            }));
242        }
243        Ok(())
244    }
245
246    /// The deterministic per-pod PVC name for a volumeClaimTemplate:
247    /// `{template}-{sts}-{ordinal}` (the K8s `StatefulSet` PVC naming
248    /// contract). Pure + total — the name is correct the moment PVC
249    /// provisioning lands.
250    #[must_use]
251    fn pvc_claim_name(template_name: &str, sts_name: &str, ordinal: usize) -> String {
252        format!("{template_name}-{sts_name}-{ordinal}")
253    }
254
255    /// The pods to delete for an update this pass.
256    fn update_deletions<'o>(
257        sts_name: &str,
258        desired: usize,
259        owned: &'o [(ResourceKey, Value)],
260        revision: Option<&TemplateRevision>,
261        strategy: UpdateStrategy,
262    ) -> Vec<&'o ResourceKey> {
263        let mut out = Vec::new();
264        // ── ★ A FAILED ORDINAL IS RECREATED ────────────────────────────────
265        // Upstream deletes a pod in phase `Failed` and recreates it under the
266        // same ordinal, from the current template. engenho kept it: the
267        // ordinal was held by name. A native pod whose closure is gone fails
268        // as `ImageUnavailable`, so this is what frees an ordinal the rollout
269        // below would otherwise wait on forever (upstream waits on an
270        // unhealthy pod, and so does this).
271        let by_ordinal: std::collections::BTreeMap<usize, &(ResourceKey, Value)> = owned
272            .iter()
273            .filter_map(|kv| Self::ordinal_of(&kv.0.name, sts_name).map(|o| (o, kv)))
274            .collect();
275        let mut deleted: std::collections::BTreeSet<usize> = std::collections::BTreeSet::new();
276        for (&ord, &kv) in &by_ordinal {
277            let (pod_key, pod) = kv;
278            if ord < desired && !pod.is_terminating() && pod_is_failed(pod) {
279                info!(
280                    sts = sts_name,
281                    pod = %pod_key.label(),
282                    "deleting failed pod so its ordinal is recreated"
283                );
284                out.push(&kv.0);
285                deleted.insert(ord);
286            }
287        }
288
289        // ── ★ ROLLING UPDATE ───────────────────────────────────────────────
290        // Upstream's `updateStatefulSet` for `RollingUpdate`: from the highest
291        // ordinal down to `partition`, delete the first pod not built from the
292        // current revision and stop; stop too at the first pod that is not
293        // Ready (or is still going), so exactly one ordinal is ever down for
294        // an update. `OnDelete` replaces only what something else deleted.
295        if let (Some(rev), UpdateStrategy::RollingUpdate { partition, .. }) = (revision, strategy)
296            && deleted.is_empty()
297        {
298            let floor = (partition as usize).min(desired);
299            for ord in (floor..desired).rev() {
300                let Some(&kv) = by_ordinal.get(&ord) else {
301                    break; // being created: wait for it
302                };
303                let (pod_key, pod) = kv;
304                if pod.is_terminating() {
305                    break;
306                }
307                if !rev.is_current(pod) {
308                    info!(
309                        sts = sts_name,
310                        pod = %pod_key.label(),
311                        from = TemplateRevision::of_pod(pod).unwrap_or("<none>"),
312                        to = rev.as_str(),
313                        "rolling update: replacing out-of-date pod"
314                    );
315                    out.push(&kv.0);
316                    break;
317                }
318                if !pod_is_ready(pod) {
319                    break;
320                }
321            }
322        }
323
324        out
325    }
326
327    /// Extract the ordinal from "{sts}-{n}". Returns None for
328    /// names that don't match.
329    fn ordinal_of(pod_name: &str, sts_name: &str) -> Option<usize> {
330        let prefix = format!("{sts_name}-");
331        pod_name
332            .strip_prefix(&prefix)
333            .and_then(|s| s.parse::<usize>().ok())
334    }
335}
336
337#[async_trait]
338impl OwnedChildrenReconciler for StatefulSetController {
339    fn name(&self) -> &'static str {
340        "statefulset"
341    }
342
343    fn parent_gvk(&self) -> ParentGvk {
344        ParentGvk::new("apps", "v1", "StatefulSet", "apps/v1")
345    }
346
347    fn child_kinds(&self) -> &'static [GroupVersionKind] {
348        const CHILD_KINDS: &[GroupVersionKind] = &[gvk("", "v1", "Pod")];
349        CHILD_KINDS
350    }
351
352    /// The claims it creates from `volumeClaimTemplates` when absent: a
353    /// claim deleted out from under a replica is recreated on the event,
354    /// not a fallback interval later.
355    fn also_reads(&self) -> &'static [GroupVersionKind] {
356        const ALSO: &[GroupVersionKind] = &[gvk("", "v1", "PersistentVolumeClaim")];
357        ALSO
358    }
359
360    fn store(&self) -> &StoreMesh {
361        &self.store
362    }
363
364    fn namespace(&self) -> Option<&str> {
365        self.namespace.as_deref()
366    }
367
368    fn sweep(&self) -> &Sweep {
369        &self.sweep
370    }
371
372    async fn reconcile_one(
373        &self,
374        sts_value: &Value,
375        owned: &[(ResourceKey, Value)],
376    ) -> Result<ReconcileDelta, ControllerError> {
377        // Malformed `spec.replicas` → this StatefulSet fails (an Event on
378        // it) with no pod created or removed.
379        let desired = REPLICAS.read(sts_value)?.max(0) as usize;
380        // No name / owner-ref → no-op (parent freshly minted; blanket
381        // already skipped no-uid parents).
382        let Some(sts_name) = sts_value.name() else {
383            return Ok(ReconcileDelta::none());
384        };
385        let Some(owner_ref) = owner_ref_for(sts_value, "apps/v1", "StatefulSet") else {
386            return Ok(ReconcileDelta::none());
387        };
388        // A strategy engenho cannot read refuses THIS StatefulSet (an Event
389        // on it), before anything is created or deleted for it.
390        let strategy = UpdateStrategy::of(sts_value)?;
391        let revision = TemplateRevision::of(sts_value);
392        let pod_ns = crate::owned_children::child_namespace(sts_value, self.namespace.as_deref());
393
394        // Every owned pod, Terminating ones included: an ordinal is an
395        // identity, and a Terminating `{sts}-{n}` still holds it until its
396        // finalizers clear (upstream waits too). Deleting a Terminating pod
397        // again on scale-down is left out by the blanket (I3).
398        let existing_ordinals: std::collections::BTreeSet<usize> = owned
399            .iter()
400            .filter_map(|(k, _)| Self::ordinal_of(&k.name, sts_name))
401            .collect();
402
403        let mut commands = Vec::new();
404
405        // ── PVCs: CREATE-IF-ABSENT, before any pod ───────────────────────
406        // Ordering is load-bearing in both directions.
407        //
408        // Before the pod, because the pod's volumes already name
409        // `{template}-{sts}-{ordinal}` — a pod created ahead of its claim sits
410        // in ContainerCreating until a later tick.
411        //
412        // And create-IF-ABSENT rather than Put, because an unconditional Put
413        // is a WRITE FIGHT with the binder: the binder stamps
414        // `status.phase: Bound` + `spec.volumeName`, this controller rewrites
415        // the claim from the template, and the pair loop forever. Measured
416        // 2026-09-14 on ryn — `pv-binder examined=2 changed=1` every tick with
417        // the phase flapping Bound/unset between reads. Kubernetes never
418        // rewrites an existing claim from its template either; the template is
419        // a creation-time shape, not a desired state.
420        let existing_pvcs: std::collections::BTreeSet<String> = self
421            .store
422            .list("", "v1", "PersistentVolumeClaim", Some(&pod_ns))
423            .await
424            .into_iter()
425            .map(|(k, _)| k.name)
426            .collect();
427        for ordinal in 0..desired {
428            for (pvc_name, pvc) in Self::build_pvcs(sts_value, sts_name, ordinal, &pod_ns) {
429                if existing_pvcs.contains(&pvc_name) {
430                    continue;
431                }
432                debug!(sts = sts_name, pvc = %pvc_name, "creating claim from volumeClaimTemplate");
433                commands.push(ResourceCommand::Put {
434                    key: ResourceKey::namespaced(
435                        "",
436                        "v1",
437                        "PersistentVolumeClaim",
438                        &pod_ns,
439                        &pvc_name,
440                    ),
441                    value: pvc,
442                    expected: None,
443                    reason: Reason::Controller,
444                });
445            }
446        }
447
448        // Create missing ordinals 0..desired.
449        for ordinal in 0..desired {
450            if existing_ordinals.contains(&ordinal) {
451                continue;
452            }
453            let Some((pod_name, mut pod)) = Self::build_pod(sts_value, ordinal, owner_ref.clone())?
454            else {
455                continue;
456            };
457            if let Some(rev) = &revision {
458                rev.stamp(&mut pod, None).map_err(|e| e.under(TEMPLATE))?;
459            }
460            let pod_key = ResourceKey::namespaced("", "v1", "Pod", &pod_ns, &pod_name);
461            debug!(sts = sts_name, ordinal, "creating ordered pod");
462            commands.push(ResourceCommand::Put {
463                key: pod_key,
464                value: pod,
465                expected: None,
466                reason: Reason::Controller,
467            });
468        }
469
470        // Scale-down: remove pods with ordinal >= desired.
471        for (pod_key, _) in owned {
472            if let Some(ord) = Self::ordinal_of(&pod_key.name, sts_name)
473                && ord >= desired
474            {
475                debug!(sts = sts_name, pod = %pod_key.label(), "scaling down ordered pod");
476                commands.push(ResourceCommand::delete(pod_key.clone(), Reason::Controller));
477            }
478        }
479
480        // Failed ordinals, then the rolling update (see `update_deletions`).
481        commands.extend(
482            Self::update_deletions(sts_name, desired, owned, revision.as_ref(), strategy)
483                .into_iter()
484                .map(|k| ResourceCommand::delete(k.clone(), Reason::Controller)),
485        );
486
487        Ok(ReconcileDelta::from_commands(commands))
488    }
489
490    fn compute_status(
491        &self,
492        sts_value: &Value,
493        owned_now: &[(ResourceKey, Value)],
494        observed_generation: i64,
495    ) -> Option<Value> {
496        // Computed from the LIVE owned pods after the reconcile.
497        // `replicas` = owned pod count; `readyReplicas`/`availableReplicas`
498        // = ready owned pods; `updatedReplicas` = pods built from the current
499        // template revision, which `updateRevision` names.
500        let replicas = i64::try_from(owned_now.len()).unwrap_or(i64::MAX);
501        let ready = i64::try_from(owned_now.iter().filter(|(_, p)| pod_is_ready(p)).count())
502            .unwrap_or(i64::MAX);
503        let revision = TemplateRevision::of(sts_value);
504        let updated = revision.as_ref().map_or(replicas, |rev| {
505            i64::try_from(owned_now.iter().filter(|(_, p)| rev.is_current(p)).count())
506                .unwrap_or(i64::MAX)
507        });
508        let mut status = json!({
509            "replicas": replicas,
510            "readyReplicas": ready,
511            "availableReplicas": ready,
512            "updatedReplicas": updated,
513            "currentReplicas": replicas,
514            "observedGeneration": observed_generation,
515        });
516        if let Some(rev) = revision {
517            status["updateRevision"] = Value::from(rev.as_str());
518        }
519        Some(status)
520    }
521}
522
523#[cfg(test)]
524mod tests {
525    use super::*;
526    use crate::controller::Controller; // brings `.tick()` (blanket via OwnedChildrenReconciler) into scope
527    use serde_json::json;
528
529    fn sts_owner() -> OwnerReference {
530        OwnerReference {
531            api_version: "apps/v1".into(),
532            kind: "StatefulSet".into(),
533            name: "web".into(),
534            uid: "uid-sts".into(),
535            controller: true,
536            block_owner_deletion: true,
537        }
538    }
539
540    #[test]
541    fn ordinal_of_parses_correct_format() {
542        assert_eq!(StatefulSetController::ordinal_of("web-0", "web"), Some(0));
543        assert_eq!(StatefulSetController::ordinal_of("web-12", "web"), Some(12));
544        assert_eq!(StatefulSetController::ordinal_of("web", "web"), None);
545        assert_eq!(StatefulSetController::ordinal_of("other-1", "web"), None);
546        assert_eq!(StatefulSetController::ordinal_of("web-abc", "web"), None);
547    }
548
549    #[test]
550    fn replicas_defaults_to_1() {
551        let sts = json!({"metadata": {"name": "x"}, "spec": {}});
552        assert_eq!(REPLICAS.read(&sts), Ok(1));
553    }
554
555    #[test]
556    fn replicas_reads_spec_field() {
557        let sts = json!({"spec": {"replicas": 3}});
558        assert_eq!(REPLICAS.read(&sts), Ok(3));
559    }
560
561    #[test]
562    fn build_pod_names_with_ordinal() {
563        let sts = json!({
564            "metadata": {"name": "web"},
565            "spec": {
566                "template": {
567                    "metadata": {"labels": {"app": "web"}},
568                    "spec": {"containers": [{"image": "nginx"}]}
569                }
570            }
571        });
572        for ord in [0usize, 1, 7] {
573            let (name, pod) = StatefulSetController::build_pod(&sts, ord, sts_owner())
574                .unwrap()
575                .unwrap();
576            assert_eq!(name, format!("web-{ord}"));
577            assert_eq!(
578                pod["status"]["phase"], "Pending",
579                "a controller-built pod is born with status: {pod}"
580            );
581            assert_eq!(pod.get("kind").unwrap(), "Pod");
582            assert_eq!(pod.get("metadata").unwrap().get("name").unwrap(), &name);
583        }
584    }
585
586    #[test]
587    fn owner_ref_for_constructs_typed_ref() {
588        let sts = json!({"metadata": {"name": "web", "uid": "u-1"}});
589        let r = owner_ref_for(&sts, "apps/v1", "StatefulSet").unwrap();
590        assert_eq!(r.kind, "StatefulSet");
591        assert_eq!(r.api_version, "apps/v1");
592        assert_eq!(r.uid, "u-1");
593        assert!(r.controller);
594    }
595
596    #[test]
597    fn owner_ref_none_without_uid() {
598        let sts = json!({"metadata": {"name": "web"}});
599        assert!(owner_ref_for(&sts, "apps/v1", "StatefulSet").is_none());
600    }
601
602    #[test]
603    fn build_pod_inherits_the_statefulsets_namespace() {
604        // The Pod MUST land in the parent STS's namespace — not the
605        // controller scope ns. Regression test for the bug where a STS in
606        // ns `db` produced pods in `default`, breaking owned-pod gathering.
607        let sts = json!({
608            "metadata": {"name": "vm", "namespace": "monitoring"},
609            "spec": {"template": {
610                "metadata": {"labels": {"app": "vm"}},
611                "spec": {"containers": [{"name": "c", "image": "img"}]}
612            }}
613        });
614        let (name, pod) = StatefulSetController::build_pod(&sts, 0, sts_owner())
615            .unwrap()
616            .unwrap();
617        assert_eq!(name, "vm-0");
618        assert_eq!(
619            pod.get("metadata").unwrap().get("namespace").unwrap(),
620            "monitoring"
621        );
622    }
623
624    #[test]
625    fn build_pod_defaults_namespace_when_parent_has_none() {
626        let sts = json!({
627            "metadata": {"name": "web"},
628            "spec": {"template": {"spec": {"containers": []}}}
629        });
630        let (_, pod) = StatefulSetController::build_pod(&sts, 0, sts_owner())
631            .unwrap()
632            .unwrap();
633        assert_eq!(
634            pod.get("metadata").unwrap().get("namespace").unwrap(),
635            "default"
636        );
637    }
638
639    // ── volumeClaimTemplates → deterministic per-pod PVC volume name ───
640
641    #[test]
642    fn pvc_claim_name_follows_k8s_contract() {
643        assert_eq!(
644            StatefulSetController::pvc_claim_name("data", "vm", 2),
645            "data-vm-2"
646        );
647    }
648
649    #[test]
650    fn build_pod_wires_pvc_volume_from_volume_claim_template() {
651        // A STS with a volumeClaimTemplate gets a pod-side volume reference
652        // to the deterministic per-pod PVC name `{template}-{sts}-{ordinal}`.
653        // PVC provisioning itself is OUT of scope, but the reference is
654        // correct the moment PVCs land.
655        let sts = json!({
656            "metadata": {"name": "vm", "namespace": "monitoring"},
657            "spec": {
658                "volumeClaimTemplates": [
659                    {"metadata": {"name": "data"}, "spec": {"resources": {}}}
660                ],
661                "template": {
662                    "metadata": {"labels": {"app": "vm"}},
663                    "spec": {"containers": [{"name": "c", "image": "img"}]}
664                }
665            }
666        });
667        let (_, pod) = StatefulSetController::build_pod(&sts, 1, sts_owner())
668            .unwrap()
669            .unwrap();
670        let volumes = pod
671            .get("spec")
672            .and_then(|s| s.get("volumes"))
673            .and_then(|v| v.as_array())
674            .expect("pod has volumes wired from the template");
675        assert_eq!(volumes.len(), 1);
676        assert_eq!(volumes[0].get("name").unwrap(), "data");
677        assert_eq!(
678            volumes[0]
679                .get("persistentVolumeClaim")
680                .unwrap()
681                .get("claimName")
682                .unwrap(),
683            "data-vm-1"
684        );
685    }
686
687    #[test]
688    fn build_pod_pvc_wiring_is_idempotent_with_pre_declared_volume() {
689        // If the operator pre-declared the volume on the pod template, the
690        // controller leaves it untouched (no duplicate).
691        let sts = json!({
692            "metadata": {"name": "vm"},
693            "spec": {
694                "volumeClaimTemplates": [{"metadata": {"name": "data"}}],
695                "template": {"spec": {
696                    "containers": [],
697                    "volumes": [{"name": "data", "emptyDir": {}}]
698                }}
699            }
700        });
701        let (_, pod) = StatefulSetController::build_pod(&sts, 0, sts_owner())
702            .unwrap()
703            .unwrap();
704        let volumes = pod
705            .get("spec")
706            .and_then(|s| s.get("volumes"))
707            .and_then(|v| v.as_array())
708            .unwrap();
709        assert_eq!(volumes.len(), 1, "pre-declared volume not duplicated");
710        // The pre-declared emptyDir wins (operator override).
711        assert!(volumes[0].get("emptyDir").is_some());
712    }
713
714    #[test]
715    fn build_pod_no_volumes_without_volume_claim_templates() {
716        let sts = json!({
717            "metadata": {"name": "vm"},
718            "spec": {"template": {"spec": {"containers": []}}}
719        });
720        let (_, pod) = StatefulSetController::build_pod(&sts, 0, sts_owner())
721            .unwrap()
722            .unwrap();
723        // No volumeClaimTemplates → no volumes injected.
724        assert!(pod.get("spec").and_then(|s| s.get("volumes")).is_none());
725    }
726
727    // ── integration over the store: ordinal scale-up / scale-down ──────
728
729    use engenho_store::command::Reason;
730    use engenho_store::{InProcessRouter, default_config};
731    use std::sync::Arc;
732    use std::time::Duration;
733
734    async fn test_store() -> Arc<StoreMesh> {
735        let router = InProcessRouter::new();
736        let cfg = default_config("controllers-statefulset").unwrap();
737        let store = Arc::new(
738            StoreMesh::start(1, "in-process://1".into(), router, cfg)
739                .await
740                .unwrap(),
741        );
742        store.initialize_singleton().await.unwrap();
743        assert!(store.wait_for_leadership(Duration::from_secs(3)).await);
744        store
745    }
746
747    async fn seed_sts(store: &StoreMesh, ns: &str, name: &str, replicas: i64) -> String {
748        let key = ResourceKey::namespaced("apps", "v1", "StatefulSet", ns, name);
749        store
750            .propose(ResourceCommand::put(
751                key.clone(),
752                json!({
753                    "kind": "StatefulSet", "apiVersion": "apps/v1",
754                    "metadata": {"name": name, "namespace": ns},
755                    "spec": {
756                        "replicas": replicas,
757                        "template": {
758                            "metadata": {"labels": {"app": name}},
759                            "spec": {"containers": [{"name": "c", "image": "img"}]}
760                        }
761                    }
762                }),
763                Reason::Operator,
764            ))
765            .await
766            .unwrap();
767        store.get(&key).await.unwrap().uid().unwrap().to_string()
768    }
769
770    async fn owned_pod_names(store: &StoreMesh, ns: &str, uid: &str) -> Vec<String> {
771        let pods = store.list("", "v1", "Pod", Some(ns)).await;
772        let mut names: Vec<String> = pods
773            .iter()
774            .filter(|(_, p)| crate::owner::is_owned_by(p, uid))
775            .map(|(k, _)| k.name.clone())
776            .collect();
777        names.sort();
778        names
779    }
780
781    #[tokio::test]
782    async fn ordinal_naming_and_namespace_inherited() {
783        let store = test_store().await;
784        let uid = seed_sts(&store, "monitoring", "vm", 3).await;
785        let c = StatefulSetController::new(store.clone(), None);
786        c.tick().await.unwrap();
787
788        let names = owned_pod_names(&store, "monitoring", &uid).await;
789        assert_eq!(names, vec!["vm-0", "vm-1", "vm-2"], "ordinal pod names");
790
791        // All pods land in the STS namespace, not "default".
792        let in_default = store.list("", "v1", "Pod", Some("default")).await;
793        assert!(in_default.is_empty(), "no STS pods in default namespace");
794    }
795
796    #[tokio::test]
797    async fn scale_up_adds_the_next_highest_ordinal() {
798        let store = test_store().await;
799        let uid = seed_sts(&store, "default", "vm", 1).await;
800        let c = StatefulSetController::new(store.clone(), None);
801        c.tick().await.unwrap();
802        assert_eq!(owned_pod_names(&store, "default", &uid).await, vec!["vm-0"]);
803
804        // Scale to 3 → adds vm-1, vm-2 (vm-0 untouched).
805        store
806            .propose(ResourceCommand::patch(
807                ResourceKey::namespaced("apps", "v1", "StatefulSet", "default", "vm"),
808                json!({"spec": {"replicas": 3}}),
809                Reason::Operator,
810            ))
811            .await
812            .unwrap();
813        c.tick().await.unwrap();
814        assert_eq!(
815            owned_pod_names(&store, "default", &uid).await,
816            vec!["vm-0", "vm-1", "vm-2"]
817        );
818    }
819
820    #[tokio::test]
821    async fn scale_down_removes_the_highest_ordinals() {
822        let store = test_store().await;
823        let uid = seed_sts(&store, "default", "vm", 3).await;
824        let c = StatefulSetController::new(store.clone(), None);
825        c.tick().await.unwrap();
826        assert_eq!(
827            owned_pod_names(&store, "default", &uid).await,
828            vec!["vm-0", "vm-1", "vm-2"]
829        );
830
831        // Scale to 1 → removes vm-2, vm-1 (highest first), keeps vm-0.
832        store
833            .propose(ResourceCommand::patch(
834                ResourceKey::namespaced("apps", "v1", "StatefulSet", "default", "vm"),
835                json!({"spec": {"replicas": 1}}),
836                Reason::Operator,
837            ))
838            .await
839            .unwrap();
840        c.tick().await.unwrap();
841        assert_eq!(owned_pod_names(&store, "default", &uid).await, vec!["vm-0"]);
842    }
843
844    #[tokio::test]
845    async fn statefulset_no_thrash_stable_across_ticks() {
846        let store = test_store().await;
847        let _uid = seed_sts(&store, "default", "vm", 2).await;
848        let c = StatefulSetController::new(store.clone(), None);
849        c.tick().await.unwrap();
850        let rev_a = store.current_revision().await;
851        for _ in 0..3 {
852            c.tick().await.unwrap();
853        }
854        let rev_b = store.current_revision().await;
855        assert_eq!(rev_a, rev_b, "converged StatefulSet must not thrash");
856    }
857}
858
859#[cfg(test)]
860mod volume_claim_templates {
861    use super::StatefulSetController;
862    use serde_json::json;
863
864    fn sts_with(vcts: serde_json::Value) -> serde_json::Value {
865        json!({
866            "metadata": {"name": "mysql", "namespace": "pitr"},
867            "spec": {"replicas": 1, "volumeClaimTemplates": vcts},
868        })
869    }
870
871    /// The K8s naming contract. `wire_pvc_volumes` already puts this exact
872    /// string on the pod, so a claim named anything else is a volume the pod
873    /// can never bind — the pod waits in `ContainerCreating` forever.
874    #[test]
875    fn claim_name_follows_the_kubernetes_contract() {
876        let sts = sts_with(json!([{"metadata": {"name": "data"}, "spec": {}}]));
877        let pvcs = StatefulSetController::build_pvcs(&sts, "mysql", 0, "pitr");
878        assert_eq!(pvcs.len(), 1);
879        assert_eq!(pvcs[0].0, "data-mysql-0");
880    }
881
882    #[test]
883    fn each_ordinal_gets_its_own_claim() {
884        let sts = sts_with(json!([{"metadata": {"name": "data"}, "spec": {}}]));
885        let a = StatefulSetController::build_pvcs(&sts, "mysql", 0, "pitr");
886        let b = StatefulSetController::build_pvcs(&sts, "mysql", 1, "pitr");
887        assert_ne!(a[0].0, b[0].0, "two ordinals sharing a claim is data loss");
888    }
889
890    /// ★ THE RESTORE PATH. A volumeClaimTemplate naming a `VolumeSnapshot` is
891    /// how `VolumeSnapshot -> StatefulSet` is expressed with no hand-written
892    /// PVC in between — which is the shape a PITR restore vector needs. If the
893    /// template's spec were rebuilt field-by-field instead of carried
894    /// verbatim, dataSource would be silently dropped and the restored set
895    /// would come up EMPTY while reporting healthy.
896    #[test]
897    fn the_templates_spec_is_carried_verbatim_including_datasource() {
898        let sts = sts_with(json!([{
899            "metadata": {"name": "data"},
900            "spec": {
901                "accessModes": ["ReadWriteOnce"],
902                "storageClassName": "engenho-local-path",
903                "resources": {"requests": {"storage": "2Gi"}},
904                "dataSource": {
905                    "apiGroup": "snapshot.storage.k8s.io",
906                    "kind": "VolumeSnapshot",
907                    "name": "db-snap"
908                }
909            }
910        }]));
911        let pvcs = StatefulSetController::build_pvcs(&sts, "mysql", 0, "pitr");
912        let spec = &pvcs[0].1["spec"];
913        assert_eq!(spec["dataSource"]["name"], "db-snap");
914        assert_eq!(spec["dataSource"]["kind"], "VolumeSnapshot");
915        assert_eq!(spec["storageClassName"], "engenho-local-path");
916        assert_eq!(spec["resources"]["requests"]["storage"], "2Gi");
917    }
918
919    /// ★ NEGATIVE CONTROL. Without this, `build_pvcs` could return a claim
920    /// unconditionally and every assertion above would still pass while every
921    /// storage-less `StatefulSet` acquired a phantom volume.
922    #[test]
923    fn a_statefulset_without_templates_gets_no_claims() {
924        let no_key = json!({"metadata": {"name": "x"}, "spec": {"replicas": 1}});
925        assert!(StatefulSetController::build_pvcs(&no_key, "x", 0, "ns").is_empty());
926        let empty = sts_with(json!([]));
927        assert!(StatefulSetController::build_pvcs(&empty, "mysql", 0, "pitr").is_empty());
928    }
929
930    /// A nameless template has no derivable claim name. Skipped rather than
931    /// invented: a guessed name would not match what the pod was wired to.
932    #[test]
933    fn a_nameless_template_is_skipped_not_guessed() {
934        let sts = sts_with(json!([{"spec": {}}, {"metadata": {"name": "ok"}, "spec": {}}]));
935        let pvcs = StatefulSetController::build_pvcs(&sts, "mysql", 0, "pitr");
936        assert_eq!(pvcs.len(), 1);
937        assert_eq!(pvcs[0].0, "ok-mysql-0");
938    }
939
940    /// ★ RETENTION. Kubernetes keeps a `StatefulSet`'s PVCs when the set is
941    /// deleted — the data outlives the workload. An ownerReference would
942    /// garbage-collect them, which on a PITR restore target would delete the
943    /// very data the drill exists to prove recoverable.
944    #[test]
945    fn claims_carry_no_owner_reference() {
946        let sts = sts_with(json!([{"metadata": {"name": "data"}, "spec": {}}]));
947        let pvcs = StatefulSetController::build_pvcs(&sts, "mysql", 0, "pitr");
948        assert!(
949            pvcs[0].1["metadata"].get("ownerReferences").is_none(),
950            "an ownerReference here deletes restored data on teardown"
951        );
952    }
953
954    #[test]
955    fn claims_land_in_the_statefulsets_namespace() {
956        let sts = sts_with(json!([{"metadata": {"name": "data"}, "spec": {}}]));
957        let pvcs = StatefulSetController::build_pvcs(&sts, "mysql", 0, "pitr");
958        assert_eq!(pvcs[0].1["metadata"]["namespace"], "pitr");
959    }
960}