Skip to main content

engenho_controllers/
job.rs

1//! R16 — Job + R16b `CronJob` controllers.
2//!
3//! Job: runs N pods to completion. Tracks completions/failures.
4//! `CronJob`: time-triggered Job factory driven by a real 5-field cron
5//! parser ([`crate::cron::CronSchedule`]) against an injected
6//! [`Clock`] — so the whole `CronJob` → Job → Pod workload chain
7//! functions end-to-end (the `JobController` then runs the created Job's
8//! Pods via the kubelet).
9//!
10//! ## Job reconcile rule
11//!
12//! For each Job:
13//!   * `desired_completions` = spec.completions (default 1)
14//!   * `desired_parallelism` = spec.parallelism (default 1)
15//!   * `owned_pods` = pods with controller-ref UID matching
16//!   * succeeded = pods with status.phase == "Succeeded"
17//!   * if succeeded >= completions → mark Job complete (no-op)
18//!   * else if failed > `spec.backoffLimit` (default 6) → mark Job Failed
19//!     (`BackoffLimitExceeded`), create nothing
20//!   * else if active_pods < parallelism → create more
21//!
22//! ## `CronJob` reconcile rule
23//!
24//! Each tick, for every CronJob:
25//!   * delete finished Jobs beyond `successfulJobsHistoryLimit` (default 3)
26//!     and `failedJobsHistoryLimit` (default 1), oldest first — suspended
27//!     or not
28//!   * skip when `spec.suspend == true`
29//!   * parse `spec.schedule` (a 5-field cron expression); a malformed
30//!     schedule is a typed skip, never a panic
31//!   * compute the most recent scheduled minute strictly after the last
32//!     run anchor (`status.lastScheduleTime`, else the `CronJob`'s
33//!     creationTimestamp, else now) and at-or-before `clock.now()`
34//!   * honour `spec.startingDeadlineSeconds` — a due time older than the
35//!     deadline is missed and skipped
36//!   * apply `spec.concurrencyPolicy` (default `Allow`):
37//!       - `Forbid`  → skip when an active owned Job exists
38//!       - `Replace` → delete the active owned Job(s), then create
39//!       - `Allow`   → always create
40//!   * create a Job named `{cronjob}-{unix_ts}` from `spec.jobTemplate`,
41//!     owner-referenced back to the `CronJob` + labelled
42//!   * patch `status.lastScheduleTime` + `status.active`
43//!
44//! Deferred (named typed follow-ups): timezone-aware schedules
45//! (`spec.timeZone` — evaluated against UTC), and the missed-start
46//! catch-up bound beyond a single run.
47
48use std::sync::Arc;
49
50use async_trait::async_trait;
51use engenho_store::{
52    StoreMesh,
53    command::{Reason, ResourceCommand},
54    resource::ResourceKey,
55};
56use serde_json::{Value, json};
57
58use crate::controller::{Controller, ReconcileOutcome};
59use crate::effect::Effect;
60use crate::error::ControllerError;
61use crate::event_recorder::Reason as EventReason;
62use crate::meta::{DefaultedInt, ObjectMeta, ShapeError, int_at, object_mut};
63use crate::owned_children::{
64    OwnedChildrenReconciler, ParentGvk, ReconcileDelta, pod_from_template, template_object_mut,
65};
66use crate::owner::{OwnerReference, owner_ref_for, set_owner_reference};
67use crate::reads::{DeclaresReads, Reads, gvk};
68use crate::sweep::{ObjectOutcome, Sweep, impl_sweep_event_sink};
69use engenho_config::JobSelector;
70use engenho_types::kind::GroupVersionKind;
71
72/// Upstream's `batch.kubernetes.io/controller-uid` pod label and selector key.
73pub const JOB_CONTROLLER_UID_LABEL: &str = "batch.kubernetes.io/controller-uid";
74/// Upstream's `batch.kubernetes.io/job-name` pod label.
75pub const JOB_NAME_LABEL: &str = "batch.kubernetes.io/job-name";
76/// Upstream's legacy `controller-uid` pod label, still set beside the prefixed one.
77pub const LEGACY_CONTROLLER_UID_LABEL: &str = "controller-uid";
78/// Upstream's legacy `job-name` pod label, still set beside the prefixed one.
79pub const LEGACY_JOB_NAME_LABEL: &str = "job-name";
80
81/// Where a `CronJob`'s job labels are declared.
82const JOB_TEMPLATE_LABELS: &[&str] = &["spec", "jobTemplate", "metadata", "labels"];
83
84/// `batch/v1` `spec.completions`. Upstream leaves it unset (a work queue)
85/// when only `parallelism` is given; engenho reads an absent count as 1,
86/// the value upstream defaults it to when both are unset.
87pub const COMPLETIONS: DefaultedInt = DefaultedInt::new(&["spec", "completions"], 1);
88
89/// `batch/v1` `spec.parallelism`, defaulted to 1.
90pub const PARALLELISM: DefaultedInt = DefaultedInt::new(&["spec", "parallelism"], 1);
91
92pub const BACKOFF_LIMIT: DefaultedInt = DefaultedInt::new(&["spec", "backoffLimit"], 6);
93
94pub const SUCCESSFUL_JOBS_HISTORY_LIMIT: DefaultedInt =
95    DefaultedInt::new(&["spec", "successfulJobsHistoryLimit"], 3);
96
97pub const FAILED_JOBS_HISTORY_LIMIT: DefaultedInt =
98    DefaultedInt::new(&["spec", "failedJobsHistoryLimit"], 1);
99
100/// `batch/v1` `CronJob` `spec.startingDeadlineSeconds`: absent means no
101/// deadline, so it has no default to read as.
102const STARTING_DEADLINE_SECONDS: &[&str] = &["spec", "startingDeadlineSeconds"];
103
104// Clock primitives previously defined here have been consolidated to
105// engenho_substrate::relogio (Clock + WallClock + FrozenClock). The
106// substrate trait carries unix_secs() as a default method so the
107// migration is a one-line swap at every call site (was now_unix() →
108// is unix_secs()). Tests construct FrozenClock::at(ms) where ms is
109// physical milliseconds since epoch (multiply by 1_000 when porting
110// from second-precision tests).
111pub use engenho_substrate::{Clock, FrozenClock, WallClock};
112
113/// Backwards-compat alias for the previous `SystemClock` export.
114pub type SystemClock = WallClock;
115
116/// Backwards-compat constructor — tests should migrate to
117/// [`FrozenClock::at`] directly (ms-precision instead of seconds).
118#[must_use]
119pub fn fixed_clock(unix_secs: u64) -> std::sync::Arc<FrozenClock> {
120    std::sync::Arc::new(FrozenClock::at(unix_secs * 1000))
121}
122
123// =================================================================
124// JobController — R16
125// =================================================================
126
127/// Job controller — creates pods until `completions` succeed.
128pub struct JobController {
129    store: Arc<StoreMesh>,
130    namespace: Option<String>,
131    /// `controllers.job_selector`: upstream's generated selector and labels.
132    selector: JobSelector,
133    /// Per-Job isolation (`FailedCreate` on a malformed template).
134    sweep: Sweep,
135}
136
137impl_sweep_event_sink!(JobController);
138
139impl JobController {
140    /// New controller with optional namespace scope.
141    #[must_use]
142    pub fn new(store: Arc<StoreMesh>, namespace: Option<String>) -> Self {
143        Self {
144            store,
145            namespace,
146            selector: JobSelector::Generated,
147            sweep: Sweep::new("job-controller", EventReason::FailedCreate),
148        }
149    }
150
151    /// Whether this controller generates upstream's Job selector and labels.
152    #[must_use]
153    pub fn with_selector(mut self, selector: JobSelector) -> Self {
154        self.selector = selector;
155        self
156    }
157
158    fn pod_phase_is(pod: &Value, phase: &str) -> bool {
159        pod.get("status")
160            .and_then(|s| s.get("phase"))
161            .and_then(|p| p.as_str())
162            == Some(phase)
163    }
164
165    /// Upstream's `generateSelector`: unless `spec.manualSelector` is true,
166    /// the Job's pod template carries `controller-uid`, `job-name` and their
167    /// `batch.kubernetes.io/` forms, and `spec.selector` matches the uid.
168    /// `Some((merge patch, the Job with it applied))` when a label or the
169    /// selector is missing; `None` when nothing is, or under
170    /// [`JobSelector::Off`].
171    ///
172    /// # Errors
173    ///
174    /// [`ShapeError`] when the template's `metadata.labels` is not an object.
175    fn generated_selector(&self, job: &Value) -> Result<Option<(Value, Value)>, ShapeError> {
176        if self.selector == JobSelector::Off
177            || job.pointer("/spec/manualSelector") == Some(&Value::Bool(true))
178        {
179            return Ok(None);
180        }
181        let (Some(uid), Some(name)) = (job.uid(), job.name()) else {
182            return Ok(None);
183        };
184        let want = [
185            (JOB_CONTROLLER_UID_LABEL, uid),
186            (JOB_NAME_LABEL, name),
187            (LEGACY_CONTROLLER_UID_LABEL, uid),
188            (LEGACY_JOB_NAME_LABEL, name),
189        ];
190        let mut selected = job.clone();
191        let labels =
192            template_object_mut(&mut selected, &["spec", "template", "metadata", "labels"])?;
193        let mut missing = serde_json::Map::new();
194        for (key, value) in want {
195            if !labels.contains_key(key) {
196                labels.insert(key.into(), Value::from(value));
197                missing.insert(key.into(), Value::from(value));
198            }
199        }
200        let mut patch = json!({"spec": {}});
201        if !missing.is_empty() {
202            patch["spec"]["template"] = json!({"metadata": {"labels": missing}});
203        }
204        if job.pointer("/spec/selector").is_none_or(Value::is_null) {
205            let selector = json!({"matchLabels": {JOB_CONTROLLER_UID_LABEL: uid}});
206            patch["spec"]["selector"] = selector.clone();
207            selected["spec"]["selector"] = selector;
208        }
209        if patch["spec"]
210            .as_object()
211            .is_some_and(serde_json::Map::is_empty)
212        {
213            return Ok(None);
214        }
215        Ok(Some((patch, selected)))
216    }
217
218    fn job_key(job: &Value, namespace: &str) -> Option<ResourceKey> {
219        job.name()
220            .map(|name| ResourceKey::namespaced("batch", "v1", "Job", namespace, name))
221    }
222
223    /// Build a Pod from the Job template + index, owned by `owner`.
224    ///
225    /// `Ok(None)` when the Job has no name or no template.
226    ///
227    /// # Errors
228    ///
229    /// [`ShapeError`] when the template (or its `spec`) has the wrong JSON
230    /// shape.
231    fn build_pod(
232        job: &Value,
233        idx: usize,
234        owner: OwnerReference,
235    ) -> Result<Option<(String, Value)>, ShapeError> {
236        let Some(job_name) = job.name() else {
237            return Ok(None);
238        };
239        let pod_name = format!("{job_name}-{idx}");
240        let job_namespace = job.namespace().unwrap_or("default");
241        let Some(mut pod) = pod_from_template(job, &pod_name, job_namespace, owner)? else {
242            return Ok(None);
243        };
244        // RestartPolicy: Never (Jobs don't restart pods).
245        template_object_mut(&mut pod, &["spec"])?
246            .entry("restartPolicy")
247            .or_insert(Value::String("Never".into()));
248        Ok(Some((pod_name, pod)))
249    }
250}
251
252#[async_trait]
253impl OwnedChildrenReconciler for JobController {
254    fn name(&self) -> &'static str {
255        "job"
256    }
257
258    fn parent_gvk(&self) -> ParentGvk {
259        ParentGvk::new("batch", "v1", "Job", "batch/v1")
260    }
261
262    fn child_kinds(&self) -> &'static [GroupVersionKind] {
263        const CHILD_KINDS: &[GroupVersionKind] = &[gvk("", "v1", "Pod")];
264        CHILD_KINDS
265    }
266
267    fn also_reads(&self) -> &'static [GroupVersionKind] {
268        &[]
269    }
270
271    fn store(&self) -> &StoreMesh {
272        &self.store
273    }
274
275    fn namespace(&self) -> Option<&str> {
276        self.namespace.as_deref()
277    }
278
279    fn sweep(&self) -> &Sweep {
280        &self.sweep
281    }
282
283    async fn reconcile_one(
284        &self,
285        job_value: &Value,
286        owned: &[(ResourceKey, Value)],
287    ) -> Result<ReconcileDelta, ControllerError> {
288        // A count that is not an integer fails this Job (an Event on it)
289        // with no pod created — never the default's count. Read before
290        // any early return, so `compute_status` never meets one.
291        let completions = COMPLETIONS.read_count(job_value)?;
292        let parallelism = PARALLELISM.read_count(job_value)?;
293        let backoff_limit = BACKOFF_LIMIT.read_count(job_value)?;
294        let Some(owner_ref) = owner_ref_for(job_value, "batch/v1", "Job") else {
295            return Ok(ReconcileDelta::none());
296        };
297        let pod_ns = crate::owned_children::child_namespace(job_value, self.namespace.as_deref());
298
299        let mut commands = Vec::new();
300        let selected = match self.generated_selector(job_value)? {
301            Some((patch, selected)) => {
302                if let Some(key) = Self::job_key(job_value, &pod_ns) {
303                    commands.push(ResourceCommand::patch(key, patch, Reason::Controller));
304                }
305                Some(selected)
306            }
307            None => None,
308        };
309        let job_value = selected.as_ref().unwrap_or(job_value);
310
311        let succeeded = owned
312            .iter()
313            .filter(|(_, p)| Self::pod_phase_is(p, "Succeeded"))
314            .count();
315        let active = owned
316            .iter()
317            .filter(|(_, p)| {
318                !Self::pod_phase_is(p, "Succeeded") && !Self::pod_phase_is(p, "Failed")
319            })
320            .count();
321
322        // Already complete → no pods to create.
323        if succeeded >= completions {
324            return Ok(ReconcileDelta::from_commands(commands));
325        }
326
327        let failed = owned
328            .iter()
329            .filter(|(_, p)| Self::pod_phase_is(p, "Failed"))
330            .count();
331        if failed > backoff_limit {
332            return Ok(ReconcileDelta::from_commands(commands));
333        }
334
335        // Create up to `parallelism - active` more pods toward completions.
336        let needed = completions
337            .saturating_sub(succeeded)
338            .min(parallelism)
339            .saturating_sub(active);
340        if needed == 0 {
341            return Ok(ReconcileDelta::from_commands(commands));
342        }
343
344        let existing_indices: std::collections::BTreeSet<usize> = owned
345            .iter()
346            .filter_map(|(k, _)| {
347                let job_name = job_value.name()?;
348                let prefix = format!("{job_name}-");
349                k.name.strip_prefix(&prefix).and_then(|s| s.parse().ok())
350            })
351            .collect();
352
353        let mut to_create = needed;
354        let mut idx = 0usize;
355        while to_create > 0 {
356            while existing_indices.contains(&idx) {
357                idx += 1;
358            }
359            let Some((pod_name, pod)) = Self::build_pod(job_value, idx, owner_ref.clone())? else {
360                break;
361            };
362            let pod_key = ResourceKey::namespaced("", "v1", "Pod", &pod_ns, &pod_name);
363            commands.push(ResourceCommand::Put {
364                key: pod_key,
365                value: pod,
366                expected: None,
367                reason: Reason::Controller,
368            });
369            to_create -= 1;
370            idx += 1;
371        }
372
373        Ok(ReconcileDelta::from_commands(commands))
374    }
375
376    fn compute_status(
377        &self,
378        job_value: &Value,
379        owned_now: &[(ResourceKey, Value)],
380        observed_generation: i64,
381    ) -> Option<Value> {
382        // Computed from the LIVE owned-Pod phases AFTER the reconcile.
383        // On `succeeded >= completions` set a Complete=True condition.
384        // A malformed count already failed this Job in `reconcile_one`
385        // (with its Event), so the blanket never gets here with one; no
386        // status is written from a count nobody declared.
387        let Ok(completions) = COMPLETIONS.read_count(job_value) else {
388            return None;
389        };
390        let Ok(backoff_limit) = BACKOFF_LIMIT.read_count(job_value) else {
391            return None;
392        };
393        let succeeded_now = owned_now
394            .iter()
395            .filter(|(_, p)| Self::pod_phase_is(p, "Succeeded"))
396            .count();
397        let failed_now = owned_now
398            .iter()
399            .filter(|(_, p)| Self::pod_phase_is(p, "Failed"))
400            .count();
401        let active_now = owned_now
402            .iter()
403            .filter(|(_, p)| {
404                !Self::pod_phase_is(p, "Succeeded") && !Self::pod_phase_is(p, "Failed")
405            })
406            .count();
407        let mut desired_status = json!({
408            "active": i64::try_from(active_now).unwrap_or(i64::MAX),
409            "succeeded": i64::try_from(succeeded_now).unwrap_or(i64::MAX),
410            "failed": i64::try_from(failed_now).unwrap_or(i64::MAX),
411            "observedGeneration": observed_generation,
412        });
413        if succeeded_now >= completions {
414            desired_status["conditions"] = json!([{
415                "type": "Complete",
416                "status": "True",
417            }]);
418        } else if failed_now > backoff_limit {
419            desired_status["conditions"] = json!([{
420                "type": "Failed",
421                "status": "True",
422                "reason": "BackoffLimitExceeded",
423                "message": "Job has reached the specified backoff limit",
424            }]);
425        }
426        Some(desired_status)
427    }
428}
429
430// =================================================================
431// CronJobController — R16b
432// =================================================================
433
434/// Concurrency policy for a `CronJob`'s overlapping executions.
435///
436/// Parsed from `spec.concurrencyPolicy`; unknown / absent values default
437/// to [`ConcurrencyPolicy::Allow`] (the Kubernetes default).
438#[derive(Debug, Clone, Copy, PartialEq, Eq)]
439pub enum ConcurrencyPolicy {
440    /// Allow concurrent Jobs (default).
441    Allow,
442    /// Skip the new run while a prior run is still active.
443    Forbid,
444    /// Delete the active run, then start the new one.
445    Replace,
446}
447
448impl ConcurrencyPolicy {
449    /// Parse from the wire string; anything unrecognised is `Allow`.
450    #[must_use]
451    pub fn parse(s: Option<&str>) -> Self {
452        match s {
453            Some("Forbid") => Self::Forbid,
454            Some("Replace") => Self::Replace,
455            _ => Self::Allow,
456        }
457    }
458}
459
460/// `CronJob` controller — parses `spec.schedule` (5-field cron) and creates
461/// `batch/v1` Jobs at scheduled times against an injected [`Clock`].
462///
463/// The clock is the testability contract: tests construct a
464/// [`FrozenClock`], advance it, and assert a Job appears exactly when due
465/// — no wall-clock sleeps.
466pub struct CronJobController {
467    store: Arc<StoreMesh>,
468    clock: Arc<dyn Clock>,
469    namespace: Option<String>,
470    /// Per-`CronJob` isolation: a `CronJob` whose `jobTemplate` has the wrong
471    /// shape gets a `FailedCreate` Event and the others still fire.
472    sweep: Sweep,
473}
474
475impl_sweep_event_sink!(CronJobController);
476
477impl CronJobController {
478    /// New controller with the given clock + optional namespace scope.
479    #[must_use]
480    pub fn new(store: Arc<StoreMesh>, clock: Arc<dyn Clock>, namespace: Option<String>) -> Self {
481        Self {
482            store,
483            clock,
484            namespace,
485            sweep: Sweep::new("cronjob-controller", EventReason::FailedCreate),
486        }
487    }
488
489    /// The last-schedule anchor (unix seconds) the next-due search starts
490    /// strictly after: `status.lastScheduleTime` if present, else the
491    /// `CronJob`'s `metadata.creationTimestamp`, else `now` (a `CronJob` with
492    /// no creation stamp never back-fires for past minutes).
493    fn last_schedule_anchor(cj: &Value, now: u64) -> u64 {
494        if let Some(last) = cj
495            .get("status")
496            .and_then(|s| s.get("lastScheduleTime"))
497            .and_then(Value::as_str)
498            .and_then(parse_rfc3339_unix)
499        {
500            return last;
501        }
502        cj.get("metadata")
503            .and_then(|m| m.get("creationTimestamp"))
504            .and_then(Value::as_str)
505            .and_then(parse_rfc3339_unix)
506            .unwrap_or(now)
507    }
508
509    /// Construct a Job from the `CronJob`'s `spec.jobTemplate` (both its
510    /// `spec` AND any template metadata labels/annotations are carried
511    /// over). `ts` is the scheduled time in unix seconds — it names the
512    /// Job `{cronjob}-{ts}`.
513    ///
514    /// `Ok(None)` when the `CronJob` has no name or no `jobTemplate`.
515    ///
516    /// # Errors
517    ///
518    /// [`ShapeError`] when `spec.jobTemplate.metadata.labels` is not an
519    /// object (absent or `null` is an empty label set).
520    fn build_job(cj: &Value, ts: u64) -> Result<Option<(String, Value)>, ShapeError> {
521        let Some(cj_name) = cj.name() else {
522            return Ok(None);
523        };
524        let Some(template) = cj.get("spec").and_then(|s| s.get("jobTemplate")) else {
525            return Ok(None);
526        };
527        let job_spec = template.get("spec").cloned().unwrap_or_else(|| json!({}));
528        let job_name = format!("{cj_name}-{ts}");
529        // Carry over the jobTemplate's metadata.labels (if any) onto the
530        // Job, plus a controller-uid-free convenience label so a human can
531        // `kubectl get jobs -l engenho.io/cronjob=<name>`.
532        let mut labels = template
533            .get("metadata")
534            .and_then(|m| m.get("labels"))
535            .cloned()
536            .unwrap_or(Value::Null);
537        object_mut(&mut labels, &[])
538            .map_err(|e| e.under(JOB_TEMPLATE_LABELS))?
539            .entry("engenho.io/cronjob")
540            .or_insert_with(|| Value::String(cj_name.to_string()));
541        let job = json!({
542            "kind": "Job",
543            "apiVersion": "batch/v1",
544            "metadata": {"name": job_name, "labels": labels},
545            "spec": job_spec,
546        });
547        Ok(Some((job_name, job)))
548    }
549
550    /// Jobs in `owned` that are still active (no `Complete`/`Failed`
551    /// terminal condition) — used by the concurrency policy.
552    fn active_jobs(owned: &[(ResourceKey, Value)]) -> Vec<&(ResourceKey, Value)> {
553        owned.iter().filter(|(_, j)| !job_is_terminal(j)).collect()
554    }
555
556    /// All Jobs owned (controller-ref) by `cj_uid`, in this `CronJob`'s
557    /// namespace.
558    async fn owned_jobs(&self, cj_uid: &str, job_ns: &str) -> Vec<(ResourceKey, Value)> {
559        self.store
560            .list("batch", "v1", "Job", Some(job_ns))
561            .await
562            .into_iter()
563            .filter(|(_, j)| owned_by(j, cj_uid))
564            .collect()
565    }
566}
567
568#[async_trait]
569impl Controller for CronJobController {
570    fn name(&self) -> &'static str {
571        "cronjob"
572    }
573
574    async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
575        let cjs = self
576            .store
577            .list("batch", "v1", "CronJob", self.namespace.as_deref())
578            .await;
579        let now = self.clock.unix_secs();
580        // Each CronJob isolated: one whose jobTemplate cannot be built is
581        // announced on itself and the rest still fire; a store failure
582        // ends the tick, as before.
583        let report = self
584            .sweep
585            .run(&cjs, |cj_key, cj_value| async move {
586                ObjectOutcome::settle(
587                    self.reconcile_one_cronjob(cj_key, cj_value, now)
588                        .await
589                        .map(ObjectOutcome::from),
590                )
591            })
592            .await?;
593        Ok(ReconcileOutcome::from(report))
594    }
595}
596
597/// The `CronJob`s it fires, and the Jobs they own (the concurrency policy
598/// counts the active ones). Time itself wakes nothing: the fallback tick is
599/// what fires a schedule.
600impl DeclaresReads for CronJobController {
601    fn reads(&self) -> Reads {
602        Reads::of(&[gvk("batch", "v1", "CronJob"), gvk("batch", "v1", "Job")])
603    }
604}
605
606impl From<CronTickOutcome> for ObjectOutcome {
607    fn from(outcome: CronTickOutcome) -> Self {
608        match outcome {
609            CronTickOutcome::Fired(effect) | CronTickOutcome::Pruned(effect) => Self::from(effect),
610            CronTickOutcome::Skipped => Self::SKIPPED,
611            CronTickOutcome::NotDue => Self::Unchanged,
612        }
613    }
614}
615
616/// One `CronJob`'s per-tick outcome — becomes its sweep outcome.
617enum CronTickOutcome {
618    /// A Job was proposed (+ status patched), and this is what those
619    /// writes did: the `CronJob` changed only if one of them landed.
620    Fired(Effect),
621    /// The slot was deliberately skipped (suspended / bad schedule /
622    /// Forbid-with-active / missed-deadline): recorded as a skip.
623    Skipped,
624    /// No scheduled slot has come due since the anchor: a no-op.
625    NotDue,
626    Pruned(Effect),
627}
628
629impl CronTickOutcome {
630    fn after(self, pruned: Effect) -> Self {
631        match (self, pruned) {
632            (Self::Fired(fired), pruned) => Self::Fired(pruned.and(fired)),
633            (outcome, Effect::Unchanged) => outcome,
634            (_, pruned) => Self::Pruned(pruned),
635        }
636    }
637}
638
639impl CronJobController {
640    async fn reconcile_one_cronjob(
641        &self,
642        cj_key: &ResourceKey,
643        cj_value: &Value,
644        now: u64,
645    ) -> Result<CronTickOutcome, ControllerError> {
646        let pruned = self.prune_history(cj_key, cj_value).await?;
647        Ok(self.fire(cj_key, cj_value, now).await?.after(pruned))
648    }
649
650    async fn prune_history(
651        &self,
652        cj_key: &ResourceKey,
653        cj_value: &Value,
654    ) -> Result<Effect, ControllerError> {
655        let successful_limit = SUCCESSFUL_JOBS_HISTORY_LIMIT.read_count(cj_value)?;
656        let failed_limit = FAILED_JOBS_HISTORY_LIMIT.read_count(cj_value)?;
657        let cj_uid = cj_value
658            .get("metadata")
659            .and_then(|m| m.get("uid"))
660            .and_then(Value::as_str)
661            .unwrap_or_default();
662        let job_ns = cj_key.namespace.as_deref().unwrap_or("default");
663        let owned = self.owned_jobs(cj_uid, job_ns).await;
664        let mut pruned = Effect::Unchanged;
665        for (condition, limit) in [("Complete", successful_limit), ("Failed", failed_limit)] {
666            let mut finished: Vec<&(ResourceKey, Value)> = owned
667                .iter()
668                .filter(|(_, job)| job_condition_is_true(job, condition) && !job.is_terminating())
669                .collect();
670            finished.sort_by_key(|(key, job)| (creation_unix(job), key.name.clone()));
671            let excess = finished.len().saturating_sub(limit);
672            for (key, _) in finished.into_iter().take(excess) {
673                let applied = self
674                    .store
675                    .propose(ResourceCommand::delete(key.clone(), Reason::Controller))
676                    .await?;
677                pruned = pruned.and(Effect::of(applied.op));
678            }
679        }
680        Ok(pruned)
681    }
682
683    /// Reconcile a single CronJob at `now` (unix seconds). Pure decision
684    /// logic + store writes; returns the typed [`CronTickOutcome`] so
685    /// [`Self::tick`] stays a thin aggregator.
686    async fn fire(
687        &self,
688        cj_key: &ResourceKey,
689        cj_value: &Value,
690        now: u64,
691    ) -> Result<CronTickOutcome, ControllerError> {
692        // Suspended CronJobs never fire.
693        let suspended = cj_value
694            .get("spec")
695            .and_then(|s| s.get("suspend"))
696            .and_then(Value::as_bool)
697            .unwrap_or(false);
698        if suspended {
699            return Ok(CronTickOutcome::Skipped);
700        }
701
702        // Parse the schedule; a malformed expression is a typed skip.
703        let schedule_str = cj_value
704            .get("spec")
705            .and_then(|s| s.get("schedule"))
706            .and_then(Value::as_str)
707            .unwrap_or("");
708        let Ok(schedule) = crate::cron::CronSchedule::parse(schedule_str) else {
709            return Ok(CronTickOutcome::Skipped);
710        };
711
712        // Most-recent due minute strictly after the anchor + at-or-before now.
713        let anchor = Self::last_schedule_anchor(cj_value, now);
714        let Some(due) = most_recent_due(&schedule, anchor, now) else {
715            return Ok(CronTickOutcome::NotDue);
716        };
717
718        // startingDeadlineSeconds: a due time older than the deadline is
719        // "missed" — record the skip (advance lastScheduleTime) + no Job.
720        // A deadline that is not an integer fails this CronJob (an Event
721        // on it) before anything is written — never "no deadline".
722        if let Some(deadline) = int_at(cj_value, STARTING_DEADLINE_SECONDS)? {
723            let deadline = u64::try_from(deadline.max(0)).unwrap_or(0);
724            if now.saturating_sub(due) > deadline {
725                // A skip whatever this write did: the slot was not run.
726                let _skip_recorded = self.patch_last_schedule(cj_key, due, None).await?;
727                return Ok(CronTickOutcome::Skipped);
728            }
729        }
730
731        // Build the Job, and its owner reference, BEFORE the concurrency
732        // gate: a jobTemplate of the wrong shape fails this CronJob before
733        // `Replace` deletes the running Job it was going to replace.
734        let built = match Self::build_job(cj_value, due)? {
735            Some((job_name, mut job)) => {
736                if let Some(owner_ref) = owner_ref_for(cj_value, "batch/v1", "CronJob") {
737                    set_owner_reference(&mut job, owner_ref)?;
738                }
739                Some((job_name, job))
740            }
741            None => None,
742        };
743
744        let cj_uid = cj_value
745            .get("metadata")
746            .and_then(|m| m.get("uid"))
747            .and_then(Value::as_str)
748            .unwrap_or_default();
749        let job_ns = cj_key.namespace.as_deref().unwrap_or("default");
750
751        // Concurrency policy gate.
752        let policy = ConcurrencyPolicy::parse(
753            cj_value
754                .get("spec")
755                .and_then(|s| s.get("concurrencyPolicy"))
756                .and_then(Value::as_str),
757        );
758        let owned = self.owned_jobs(cj_uid, job_ns).await;
759        let active = CronJobController::active_jobs(&owned);
760        // What the Replace deletes did: a Job removed or stamped Terminating
761        // is a change made for this CronJob.
762        let mut replaced = Effect::Unchanged;
763        match policy {
764            ConcurrencyPolicy::Forbid if !active.is_empty() => {
765                // A prior run is still active → skip, but record the skip.
766                // A skip whatever this write did: the slot was not run.
767                let _skip_recorded = self.patch_last_schedule(cj_key, due, None).await?;
768                return Ok(CronTickOutcome::Skipped);
769            }
770            ConcurrencyPolicy::Replace => {
771                // Delete every active owned Job before creating the new one.
772                // A Job already Terminating was deleted before and waits on
773                // its finalizers: deleting it again is the store's NoOp, so
774                // it is left alone (I3). It still counts as active for
775                // Forbid, since its pods may still run.
776                for (k, _) in active.iter().filter(|(_, job)| !job.is_terminating()) {
777                    let applied = self
778                        .store
779                        .propose(ResourceCommand::delete(k.clone(), Reason::Controller))
780                        .await?;
781                    replaced = replaced.and(Effect::of(applied.op));
782                }
783            }
784            ConcurrencyPolicy::Allow | ConcurrencyPolicy::Forbid => {}
785        }
786
787        // Create the Job built above, owner-referenced back to the CronJob.
788        let Some((job_name, job)) = built else {
789            return Ok(CronTickOutcome::Skipped);
790        };
791        let job_key = ResourceKey::namespaced("batch", "v1", "Job", job_ns, &job_name);
792        let created = self
793            .store
794            .propose(ResourceCommand::Put {
795                key: job_key,
796                value: job,
797                expected: None,
798                reason: Reason::Controller,
799            })
800            .await?;
801
802        // Patch status: lastScheduleTime + an active ref to the new Job.
803        let active_ref = json!({
804            "apiVersion": "batch/v1",
805            "kind": "Job",
806            "name": job_name,
807            "namespace": job_ns,
808        });
809        let status = self
810            .patch_last_schedule(cj_key, due, Some(active_ref))
811            .await?;
812        Ok(CronTickOutcome::Fired(
813            replaced.and(Effect::of(created.op)).and(status),
814        ))
815    }
816
817    /// Patch the `CronJob`'s `status.lastScheduleTime` (always) and — when a
818    /// Job was created — its `status.active` list with the new Job's ref.
819    async fn patch_last_schedule(
820        &self,
821        cj_key: &ResourceKey,
822        due: u64,
823        active_ref: Option<Value>,
824    ) -> Result<Effect, ControllerError> {
825        let status = match active_ref {
826            Some(r) => json!({
827                "lastScheduleTime": unix_to_rfc3339(due),
828                "active": [r],
829            }),
830            None => json!({ "lastScheduleTime": unix_to_rfc3339(due) }),
831        };
832        let applied = self
833            .store
834            .propose(ResourceCommand::patch(
835                cj_key.clone(),
836                json!({ "status": status }),
837                Reason::Controller,
838            ))
839            .await?;
840        Ok(Effect::of(applied.op))
841    }
842}
843
844/// The most-recent cron-due minute strictly after `anchor` and at-or-
845/// before `now`. `None` when no slot has come due since the anchor.
846///
847/// We walk forward from the anchor (the search is bounded by
848/// [`crate::cron::CronSchedule::next_after_unix`]'s horizon) and keep the
849/// last slot ≤ now. This fires AT MOST ONCE per tick even when several
850/// slots elapsed between ticks (no catch-up storm) — the missed slots are
851/// collapsed to the latest, matching the Kubernetes single-fire-per-tick
852/// behaviour for a `CronJob` with no backlog policy.
853fn most_recent_due(schedule: &crate::cron::CronSchedule, anchor: u64, now: u64) -> Option<u64> {
854    let mut candidate = schedule.next_after_unix(anchor)?;
855    if candidate > now {
856        return None;
857    }
858    // Advance to the latest slot ≤ now.
859    while let Some(next) = schedule.next_after_unix(candidate) {
860        if next > now {
861            break;
862        }
863        candidate = next;
864    }
865    Some(candidate)
866}
867
868/// Is this Job in a terminal state (a `Complete` or `Failed` condition is
869/// True)? Used by the concurrency policy to decide what counts as active.
870fn job_is_terminal(job: &Value) -> bool {
871    job_condition_is_true(job, "Complete") || job_condition_is_true(job, "Failed")
872}
873
874fn job_condition_is_true(job: &Value, condition: &str) -> bool {
875    job.get("status")
876        .and_then(|s| s.get("conditions"))
877        .and_then(Value::as_array)
878        .is_some_and(|conds| {
879            conds.iter().any(|c| {
880                c.get("type").and_then(Value::as_str) == Some(condition)
881                    && c.get("status").and_then(Value::as_str) == Some("True")
882            })
883        })
884}
885
886fn creation_unix(object: &Value) -> Option<u64> {
887    object
888        .get("metadata")
889        .and_then(|m| m.get("creationTimestamp"))
890        .and_then(Value::as_str)
891        .and_then(parse_rfc3339_unix)
892}
893
894/// Is `child` controller-owned by an object with uid `owner_uid`?
895fn owned_by(child: &Value, owner_uid: &str) -> bool {
896    if owner_uid.is_empty() {
897        return false;
898    }
899    child
900        .get("metadata")
901        .and_then(|m| m.get("ownerReferences"))
902        .and_then(Value::as_array)
903        .is_some_and(|refs| {
904            refs.iter().any(|r| {
905                r.get("uid").and_then(Value::as_str) == Some(owner_uid)
906                    && r.get("controller").and_then(Value::as_bool) == Some(true)
907            })
908        })
909}
910
911/// Parse an RFC3339 timestamp string → unix seconds. `None` on malformed
912/// input (a skip-safe read of `status.lastScheduleTime` /
913/// `creationTimestamp`).
914fn parse_rfc3339_unix(s: &str) -> Option<u64> {
915    chrono::DateTime::parse_from_rfc3339(s)
916        .ok()
917        .and_then(|dt| u64::try_from(dt.timestamp()).ok())
918}
919
920/// Render unix seconds → the Kubernetes-wire RFC3339 UTC string (typed
921/// emission via engenho-types' `time` surface — no hand-`format!()`).
922fn unix_to_rfc3339(unix_secs: u64) -> String {
923    let secs = i64::try_from(unix_secs).unwrap_or(i64::MAX);
924    chrono::DateTime::<chrono::Utc>::from_timestamp(secs, 0)
925        .map_or_else(String::new, engenho_types::time::to_rfc3339_utc)
926}
927
928#[cfg(test)]
929mod tests {
930    use super::*;
931    use serde_json::json;
932
933    // ── Job ──────────────────────────────────────────────────
934
935    #[test]
936    fn job_completions_defaults_to_1() {
937        let j = json!({"spec": {}});
938        assert_eq!(COMPLETIONS.read(&j), Ok(1));
939    }
940
941    #[test]
942    fn job_parallelism_defaults_to_1() {
943        let j = json!({"spec": {}});
944        assert_eq!(PARALLELISM.read(&j), Ok(1));
945    }
946
947    #[test]
948    fn job_completions_reads_spec_field() {
949        let j = json!({"spec": {"completions": 5}});
950        assert_eq!(COMPLETIONS.read(&j), Ok(5));
951    }
952
953    #[test]
954    fn job_build_pod_inserts_restart_policy_never() {
955        let j = json!({
956            "metadata": {"name": "compute"},
957            "spec": {
958                "template": {
959                    "spec": {"containers": [{"image": "alpine"}]}
960                }
961            }
962        });
963        let owner = owner_ref_for(
964            &json!({"metadata": {"name": "compute", "uid": "u"}}),
965            "batch/v1",
966            "Job",
967        )
968        .unwrap();
969        let (name, pod) = JobController::build_pod(&j, 0, owner).unwrap().unwrap();
970        assert_eq!(name, "compute-0");
971        assert_eq!(
972            pod["status"]["phase"], "Pending",
973            "a controller-built pod is born with status: {pod}"
974        );
975        assert_eq!(
976            pod.get("spec").unwrap().get("restartPolicy").unwrap(),
977            "Never"
978        );
979    }
980
981    #[test]
982    fn job_owner_ref_has_batch_v1_api_version() {
983        let j = json!({"metadata": {"name": "x", "uid": "u"}});
984        let r = owner_ref_for(&j, "batch/v1", "Job").unwrap();
985        assert_eq!(r.api_version, "batch/v1");
986        assert_eq!(r.kind, "Job");
987    }
988
989    #[test]
990    fn job_pod_phase_helper_distinguishes_succeeded_failed() {
991        let succeeded = json!({"status": {"phase": "Succeeded"}});
992        let failed = json!({"status": {"phase": "Failed"}});
993        let running = json!({"status": {"phase": "Running"}});
994        assert!(JobController::pod_phase_is(&succeeded, "Succeeded"));
995        assert!(!JobController::pod_phase_is(&succeeded, "Failed"));
996        assert!(JobController::pod_phase_is(&failed, "Failed"));
997        assert!(!JobController::pod_phase_is(&running, "Succeeded"));
998    }
999
1000    // ── CronJob ─────────────────────────────────────────────
1001
1002    #[test]
1003    fn cronjob_build_job_format() {
1004        let cj = json!({
1005            "metadata": {"name": "nightly"},
1006            "spec": {
1007                "jobTemplate": {
1008                    "spec": {
1009                        "completions": 1,
1010                        "template": {
1011                            "spec": {"containers": [{"image": "alpine"}]}
1012                        }
1013                    }
1014                }
1015            }
1016        });
1017        let (name, job) = CronJobController::build_job(&cj, 1_700_000_000)
1018            .unwrap()
1019            .unwrap();
1020        assert_eq!(name, "nightly-1700000000");
1021        assert_eq!(job.get("kind").unwrap(), "Job");
1022        assert_eq!(job.get("apiVersion").unwrap(), "batch/v1");
1023        assert_eq!(job.get("metadata").unwrap().get("name").unwrap(), &name);
1024        assert!(job.get("spec").unwrap().get("template").is_some());
1025        // The convenience cronjob label is stamped on the built Job.
1026        assert_eq!(
1027            job["metadata"]["labels"]["engenho.io/cronjob"],
1028            json!("nightly")
1029        );
1030    }
1031
1032    #[test]
1033    fn concurrency_policy_parse() {
1034        assert_eq!(
1035            ConcurrencyPolicy::parse(Some("Forbid")),
1036            ConcurrencyPolicy::Forbid
1037        );
1038        assert_eq!(
1039            ConcurrencyPolicy::parse(Some("Replace")),
1040            ConcurrencyPolicy::Replace
1041        );
1042        assert_eq!(
1043            ConcurrencyPolicy::parse(Some("Allow")),
1044            ConcurrencyPolicy::Allow
1045        );
1046        // Unknown / absent → Allow (the K8s default).
1047        assert_eq!(
1048            ConcurrencyPolicy::parse(Some("Bogus")),
1049            ConcurrencyPolicy::Allow
1050        );
1051        assert_eq!(ConcurrencyPolicy::parse(None), ConcurrencyPolicy::Allow);
1052    }
1053
1054    #[test]
1055    fn job_is_terminal_detects_complete_and_failed() {
1056        let complete = json!({"status": {"conditions": [{"type": "Complete", "status": "True"}]}});
1057        let failed = json!({"status": {"conditions": [{"type": "Failed", "status": "True"}]}});
1058        let running = json!({"status": {"active": 1}});
1059        let complete_false =
1060            json!({"status": {"conditions": [{"type": "Complete", "status": "False"}]}});
1061        assert!(job_is_terminal(&complete));
1062        assert!(job_is_terminal(&failed));
1063        assert!(!job_is_terminal(&running));
1064        assert!(!job_is_terminal(&complete_false));
1065    }
1066
1067    #[test]
1068    fn owned_by_matches_controller_ref() {
1069        let child = json!({"metadata": {"ownerReferences": [
1070            {"uid": "cj-uid", "controller": true}
1071        ]}});
1072        assert!(owned_by(&child, "cj-uid"));
1073        assert!(!owned_by(&child, "other-uid"));
1074        // A non-controller owner ref does not count.
1075        let non_ctrl = json!({"metadata": {"ownerReferences": [{"uid": "cj-uid"}]}});
1076        assert!(!owned_by(&non_ctrl, "cj-uid"));
1077        // Empty uid never matches.
1078        assert!(!owned_by(&child, ""));
1079    }
1080
1081    #[test]
1082    fn rfc3339_round_trips_unix() {
1083        // 1_700_000_000 = 2023-11-14T22:13:20Z.
1084        let s = unix_to_rfc3339(1_700_000_000);
1085        assert_eq!(s, "2023-11-14T22:13:20Z");
1086        assert_eq!(parse_rfc3339_unix(&s), Some(1_700_000_000));
1087        assert_eq!(parse_rfc3339_unix("not-a-time"), None);
1088    }
1089
1090    #[test]
1091    fn most_recent_due_collapses_missed_slots_to_latest() {
1092        // Every-minute schedule. Anchor at t=0, now at t=600 (10 min later)
1093        // → the latest due slot is t=600 itself (minute-aligned, ≤ now).
1094        let s = crate::cron::CronSchedule::parse("* * * * *").unwrap();
1095        assert_eq!(most_recent_due(&s, 0, 600), Some(600));
1096        // Nothing due yet when now is before the first slot after anchor.
1097        // anchor=100 → first slot 120; now=110 < 120 → None.
1098        assert_eq!(most_recent_due(&s, 100, 110), None);
1099    }
1100
1101    #[test]
1102    fn frozen_clock_advances_unix_secs() {
1103        // Substrate FrozenClock is ms-precision; advance(50_000ms) →
1104        // unix_secs jumps by 50.
1105        let c = FrozenClock::at(100_000); // 100s
1106        assert_eq!(c.unix_secs(), 100);
1107        c.advance(50_000); // +50s
1108        assert_eq!(c.unix_secs(), 150);
1109    }
1110
1111    #[test]
1112    fn wall_clock_returns_nonzero() {
1113        // The actual time isn't important; just that it returns
1114        // a sensible value (greater than the unix epoch's first second).
1115        assert!(WallClock.unix_secs() > 1_000_000_000);
1116    }
1117
1118    #[test]
1119    fn fixed_clock_compat_helper_works() {
1120        // Backwards-compat for any caller that hadn't yet migrated to
1121        // the substrate's ms-precision FrozenClock.
1122        let c = fixed_clock(100);
1123        assert_eq!(c.unix_secs(), 100);
1124    }
1125
1126    #[test]
1127    fn cronjob_controller_name_is_stable() {
1128        struct F;
1129        #[async_trait]
1130        impl Controller for F {
1131            fn name(&self) -> &'static str {
1132                "cronjob"
1133            }
1134            async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
1135                Ok(crate::controller::ReconcileReport::default().into())
1136            }
1137        }
1138        assert_eq!(F.name(), "cronjob");
1139    }
1140
1141    // ── CronJob live-store reconcile (mockable clock, NO wall-clock) ──
1142
1143    use engenho_store::{InProcessRouter, default_config};
1144    use std::time::Duration;
1145
1146    /// Single-node in-memory `StoreMesh` — the controller-test rig the
1147    /// other reconciler tests use.
1148    async fn test_store(name: &str) -> Arc<StoreMesh> {
1149        let router = InProcessRouter::new();
1150        let cfg = default_config(name).unwrap();
1151        let store = Arc::new(
1152            StoreMesh::start(1, "in-process://1".into(), router, cfg)
1153                .await
1154                .unwrap(),
1155        );
1156        store.initialize_singleton().await.unwrap();
1157        assert!(store.wait_for_leadership(Duration::from_secs(3)).await);
1158        store
1159    }
1160
1161    async fn put(store: &StoreMesh, key: ResourceKey, value: Value) {
1162        store
1163            .propose(ResourceCommand::put(key, value, Reason::Operator))
1164            .await
1165            .expect("put");
1166    }
1167
1168    /// Seed a `CronJob` at `default/<name>` with the given schedule + a
1169    /// jobTemplate that runs one container. The creationTimestamp is the
1170    /// search anchor; pin it so a frozen clock can advance past a slot.
1171    fn cronjob_value(name: &str, schedule: &str, created: u64) -> Value {
1172        json!({
1173            "kind": "CronJob",
1174            "apiVersion": "batch/v1",
1175            "metadata": {
1176                "name": name,
1177                "namespace": "default",
1178                "uid": format!("{name}-uid"),
1179                "creationTimestamp": unix_to_rfc3339(created),
1180            },
1181            "spec": {
1182                "schedule": schedule,
1183                "jobTemplate": {
1184                    "spec": {
1185                        "template": {"spec": {"containers": [{"image": "alpine"}]}}
1186                    }
1187                }
1188            }
1189        })
1190    }
1191
1192    async fn list_jobs(store: &StoreMesh) -> Vec<(ResourceKey, Value)> {
1193        store.list("batch", "v1", "Job", Some("default")).await
1194    }
1195
1196    #[tokio::test]
1197    async fn cronjob_creates_one_job_when_a_minute_is_due() {
1198        let store = test_store("cronjob-due").await;
1199        // creationTimestamp at t=0; clock at t=120 (one whole minute past
1200        // the first due slot of an every-minute schedule).
1201        put(
1202            &store,
1203            ResourceKey::namespaced("batch", "v1", "CronJob", "default", "every"),
1204            cronjob_value("every", "* * * * *", 0),
1205        )
1206        .await;
1207        let clock = Arc::new(FrozenClock::at(120_000)); // 120s
1208        let c = CronJobController::new(store.clone(), clock.clone(), None);
1209
1210        let out = c.tick().await.unwrap();
1211        // One CronJob changed (its Job created and its status patched): the
1212        // sweep counts objects, not writes.
1213        assert_eq!(out.objects_changed, 1, "the one CronJob fired");
1214
1215        let jobs = list_jobs(&store).await;
1216        assert_eq!(jobs.len(), 1, "exactly one Job created");
1217        let (jk, jv) = &jobs[0];
1218        // Name = {cronjob}-{due_ts}; due is the latest slot ≤ now (120).
1219        assert_eq!(jk.name, "every-120");
1220        // ownerRef points back at the CronJob (controller=true).
1221        assert!(owned_by(jv, "every-uid"), "Job owner-referenced to CronJob");
1222        assert_eq!(jk.namespace.as_deref(), Some("default"));
1223        // jobTemplate.spec.template was copied into the Job.
1224        assert!(jv["spec"]["template"]["spec"]["containers"].is_array());
1225
1226        // status.lastScheduleTime updated on the CronJob.
1227        let cj = store
1228            .get(&ResourceKey::namespaced(
1229                "batch", "v1", "CronJob", "default", "every",
1230            ))
1231            .await
1232            .unwrap();
1233        assert_eq!(
1234            parse_rfc3339_unix(cj["status"]["lastScheduleTime"].as_str().unwrap()),
1235            Some(120)
1236        );
1237        assert_eq!(cj["status"]["active"][0]["name"], json!("every-120"));
1238    }
1239
1240    #[tokio::test]
1241    async fn a_job_a_cronjob_creates_is_born_with_its_server_owned_metadata() {
1242        let store = test_store("cronjob-born").await;
1243        put(
1244            &store,
1245            ResourceKey::namespaced("batch", "v1", "CronJob", "default", "every"),
1246            cronjob_value("every", "* * * * *", 0),
1247        )
1248        .await;
1249        let c = CronJobController::new(store.clone(), Arc::new(FrozenClock::at(120_000)), None);
1250        c.tick().await.unwrap();
1251        let jobs = list_jobs(&store).await;
1252        assert_eq!(jobs.len(), 1);
1253        let job = &jobs[0].1;
1254        assert!(
1255            job["metadata"]["creationTimestamp"]
1256                .as_str()
1257                .is_some_and(|t| parse_rfc3339_unix(t).is_some()),
1258            "{job}"
1259        );
1260        assert_eq!(job["metadata"]["namespace"], "default", "{job}");
1261        assert!(job["metadata"]["uid"].is_string(), "{job}");
1262        assert!(job["metadata"]["generation"].is_number(), "{job}");
1263    }
1264
1265    #[tokio::test]
1266    async fn cronjob_not_due_yet_creates_nothing() {
1267        let store = test_store("cronjob-notdue").await;
1268        put(
1269            &store,
1270            ResourceKey::namespaced("batch", "v1", "CronJob", "default", "every"),
1271            cronjob_value("every", "* * * * *", 100),
1272        )
1273        .await;
1274        // Anchor at t=100 → first due slot is t=120; clock at t=110 < 120.
1275        let clock = Arc::new(FrozenClock::at(110_000));
1276        let c = CronJobController::new(store.clone(), clock, None);
1277        let out = c.tick().await.unwrap();
1278        assert_eq!(out.objects_changed, 0);
1279        assert!(list_jobs(&store).await.is_empty());
1280    }
1281
1282    #[tokio::test]
1283    async fn cronjob_suspend_never_fires() {
1284        let store = test_store("cronjob-suspend").await;
1285        let mut cj = cronjob_value("every", "* * * * *", 0);
1286        cj["spec"]["suspend"] = json!(true);
1287        put(
1288            &store,
1289            ResourceKey::namespaced("batch", "v1", "CronJob", "default", "every"),
1290            cj,
1291        )
1292        .await;
1293        let clock = Arc::new(FrozenClock::at(600_000)); // way past several slots
1294        let c = CronJobController::new(store.clone(), clock, None);
1295        let out = c.tick().await.unwrap();
1296        assert_eq!(out.objects_skipped, 1);
1297        assert!(
1298            list_jobs(&store).await.is_empty(),
1299            "suspended → no Job ever"
1300        );
1301    }
1302
1303    #[tokio::test]
1304    async fn cronjob_forbid_skips_when_active_job_exists() {
1305        let store = test_store("cronjob-forbid").await;
1306        let mut cj = cronjob_value("every", "* * * * *", 0);
1307        cj["spec"]["concurrencyPolicy"] = json!("Forbid");
1308        put(
1309            &store,
1310            ResourceKey::namespaced("batch", "v1", "CronJob", "default", "every"),
1311            cj,
1312        )
1313        .await;
1314        // Seed an ALREADY-active owned Job (no terminal condition).
1315        put(
1316            &store,
1317            ResourceKey::namespaced("batch", "v1", "Job", "default", "every-60"),
1318            json!({
1319                "kind": "Job", "apiVersion": "batch/v1",
1320                "metadata": {"name": "every-60", "namespace": "default",
1321                    "ownerReferences": [{"uid": "every-uid", "controller": true}]},
1322                "status": {"active": 1}
1323            }),
1324        )
1325        .await;
1326        let clock = Arc::new(FrozenClock::at(120_000));
1327        let c = CronJobController::new(store.clone(), clock, None);
1328        let out = c.tick().await.unwrap();
1329        assert_eq!(out.objects_skipped, 1);
1330        // No NEW Job — still just the seeded one.
1331        assert_eq!(list_jobs(&store).await.len(), 1);
1332    }
1333
1334    #[tokio::test]
1335    async fn cronjob_replace_deletes_active_then_creates() {
1336        let store = test_store("cronjob-replace").await;
1337        let mut cj = cronjob_value("every", "* * * * *", 0);
1338        cj["spec"]["concurrencyPolicy"] = json!("Replace");
1339        put(
1340            &store,
1341            ResourceKey::namespaced("batch", "v1", "CronJob", "default", "every"),
1342            cj,
1343        )
1344        .await;
1345        // An active owned Job from a previous slot.
1346        put(
1347            &store,
1348            ResourceKey::namespaced("batch", "v1", "Job", "default", "every-60"),
1349            json!({
1350                "kind": "Job", "apiVersion": "batch/v1",
1351                "metadata": {"name": "every-60", "namespace": "default",
1352                    "ownerReferences": [{"uid": "every-uid", "controller": true}]},
1353                "status": {"active": 1}
1354            }),
1355        )
1356        .await;
1357        let clock = Arc::new(FrozenClock::at(120_000));
1358        let c = CronJobController::new(store.clone(), clock, None);
1359        c.tick().await.unwrap();
1360        let jobs = list_jobs(&store).await;
1361        // The old active Job was deleted; the new one created.
1362        let names: Vec<&str> = jobs.iter().map(|(k, _)| k.name.as_str()).collect();
1363        assert!(
1364            !names.contains(&"every-60"),
1365            "active Job replaced (deleted)"
1366        );
1367        assert!(names.contains(&"every-120"), "new Job created");
1368    }
1369
1370    #[tokio::test]
1371    async fn cronjob_starting_deadline_skips_stale_slot() {
1372        let store = test_store("cronjob-deadline").await;
1373        let mut cj = cronjob_value("every", "* * * * *", 0);
1374        // Deadline of 10s — the latest due slot must be within 10s of now.
1375        cj["spec"]["startingDeadlineSeconds"] = json!(10);
1376        put(
1377            &store,
1378            ResourceKey::namespaced("batch", "v1", "CronJob", "default", "every"),
1379            cj,
1380        )
1381        .await;
1382        // now=125 → latest slot ≤ now is 120, which is 5s old (≤ 10s) → fires.
1383        let clock = Arc::new(FrozenClock::at(125_000));
1384        let c = CronJobController::new(store.clone(), clock, None);
1385        c.tick().await.unwrap();
1386        assert_eq!(list_jobs(&store).await.len(), 1, "within deadline → fires");
1387    }
1388
1389    #[tokio::test]
1390    async fn cronjob_idempotent_on_repeated_tick_same_minute() {
1391        let store = test_store("cronjob-idem").await;
1392        put(
1393            &store,
1394            ResourceKey::namespaced("batch", "v1", "CronJob", "default", "every"),
1395            cronjob_value("every", "* * * * *", 0),
1396        )
1397        .await;
1398        let clock = Arc::new(FrozenClock::at(120_000));
1399        let c = CronJobController::new(store.clone(), clock.clone(), None);
1400        c.tick().await.unwrap();
1401        // Second tick with the SAME clock: lastScheduleTime now == 120, so
1402        // the next-due search finds no NEW slot ≤ now → no second Job.
1403        let out2 = c.tick().await.unwrap();
1404        assert_eq!(out2.objects_changed, 0, "no double-fire within a minute");
1405        assert_eq!(list_jobs(&store).await.len(), 1);
1406    }
1407
1408    // ── T4.3: a malformed jobTemplate costs that CronJob only ──
1409
1410    /// A jobTemplate whose `metadata.labels` is not an object fails THAT
1411    /// `CronJob` with a `FailedCreate` Event naming the field, before its
1412    /// `Replace` policy deletes the running Job; the `CronJob` listed after
1413    /// it still fires. Before T4.3 the labels were copied onto the Job
1414    /// verbatim (a Job whose labels are a string) AFTER the active Job had
1415    /// been deleted.
1416    #[tokio::test]
1417    async fn a_malformed_job_template_fails_that_cronjob_before_replace_deletes_anything() {
1418        let store = test_store("cronjob-t43").await;
1419        let mut bad = cronjob_value("a-bad", "* * * * *", 0);
1420        bad["spec"]["concurrencyPolicy"] = json!("Replace");
1421        bad["spec"]["jobTemplate"]["metadata"] = json!({"labels": "oops"});
1422        put(
1423            &store,
1424            ResourceKey::namespaced("batch", "v1", "CronJob", "default", "a-bad"),
1425            bad,
1426        )
1427        .await;
1428        put(
1429            &store,
1430            ResourceKey::namespaced("batch", "v1", "CronJob", "default", "b-clean"),
1431            cronjob_value("b-clean", "* * * * *", 0),
1432        )
1433        .await;
1434        // The malformed CronJob's running Job, which Replace would delete.
1435        let running = ResourceKey::namespaced("batch", "v1", "Job", "default", "a-bad-60");
1436        put(
1437            &store,
1438            running.clone(),
1439            json!({
1440                "kind": "Job", "apiVersion": "batch/v1",
1441                "metadata": {"name": "a-bad-60", "namespace": "default",
1442                    "ownerReferences": [{"uid": "a-bad-uid", "controller": true}]},
1443                "status": {"active": 1}
1444            }),
1445        )
1446        .await;
1447
1448        let events = Arc::new(crate::event_recorder::CollectingEventSink::new());
1449        let c = CronJobController::new(store.clone(), Arc::new(FrozenClock::at(120_000)), None)
1450            .with_event_sink(events.clone());
1451        let out = c
1452            .tick()
1453            .await
1454            .expect("one malformed CronJob is not the tick's failure");
1455        let sweep = out.sweep.expect("the CronJob tick runs through its sweep");
1456        assert_eq!((sweep.failed(), sweep.changed()), (1, 1));
1457
1458        assert!(
1459            store.get(&running).await.is_some(),
1460            "the running Job was not deleted for a Job that cannot be built"
1461        );
1462        let jobs = list_jobs(&store).await;
1463        assert!(
1464            jobs.iter()
1465                .any(|(k, v)| k.name == "b-clean-120" && owned_by(v, "b-clean-uid")),
1466            "the CronJob after the malformed one still fired: {jobs:?}"
1467        );
1468        assert!(
1469            !jobs.iter().any(|(k, _)| k.name == "a-bad-120"),
1470            "no Job from the malformed template"
1471        );
1472
1473        let recorded = events.drain();
1474        assert_eq!(recorded.len(), 1, "{recorded:?}");
1475        assert_eq!(recorded[0].reason, EventReason::FailedCreate);
1476        assert_eq!(recorded[0].involved.name, "a-bad");
1477        assert!(
1478            recorded[0]
1479                .message
1480                .contains("spec.jobTemplate.metadata.labels is a string, expected an object"),
1481            "{}",
1482            recorded[0].message
1483        );
1484    }
1485
1486    // ── T1.6: an integer that is not an integer is not absent ──
1487
1488    /// A `startingDeadlineSeconds` of `"10"` is not "no deadline": the
1489    /// `CronJob` fails with an Event naming the field and fires nothing,
1490    /// while the `CronJob` after it still fires. Before T1.6 the string
1491    /// read as absent and the slot fired regardless of any deadline.
1492    #[tokio::test]
1493    async fn a_quoted_starting_deadline_fails_that_cronjob_instead_of_dropping_the_deadline() {
1494        let store = test_store("cronjob-t16").await;
1495        let mut bad = cronjob_value("a-bad", "* * * * *", 0);
1496        bad["spec"]["startingDeadlineSeconds"] = json!("10");
1497        put(
1498            &store,
1499            ResourceKey::namespaced("batch", "v1", "CronJob", "default", "a-bad"),
1500            bad,
1501        )
1502        .await;
1503        put(
1504            &store,
1505            ResourceKey::namespaced("batch", "v1", "CronJob", "default", "b-clean"),
1506            cronjob_value("b-clean", "* * * * *", 0),
1507        )
1508        .await;
1509
1510        let events = Arc::new(crate::event_recorder::CollectingEventSink::new());
1511        let c = CronJobController::new(store.clone(), Arc::new(FrozenClock::at(120_000)), None)
1512            .with_event_sink(events.clone());
1513        let out = c
1514            .tick()
1515            .await
1516            .expect("one malformed CronJob is not the tick's failure");
1517        let sweep = out.sweep.expect("the CronJob tick runs through its sweep");
1518        assert_eq!((sweep.failed(), sweep.changed()), (1, 1));
1519
1520        let names: Vec<String> = list_jobs(&store)
1521            .await
1522            .into_iter()
1523            .map(|(k, _)| k.name)
1524            .collect();
1525        assert_eq!(names, ["b-clean-120"], "only the well-formed CronJob fired");
1526
1527        let recorded = events.drain();
1528        assert_eq!(recorded.len(), 1, "{recorded:?}");
1529        assert_eq!(recorded[0].involved.name, "a-bad");
1530        assert!(
1531            recorded[0]
1532                .message
1533                .contains("spec.startingDeadlineSeconds is not an integer (found a string)"),
1534            "{}",
1535            recorded[0].message
1536        );
1537    }
1538
1539    /// `null` labels are the empty case: the Job is built and carries the
1540    /// convenience label (before T4.3 it got `labels: null` and no label).
1541    #[test]
1542    fn null_job_template_labels_are_the_empty_label_set() {
1543        let mut cj = cronjob_value("n", "* * * * *", 0);
1544        cj["spec"]["jobTemplate"]["metadata"] = json!({"labels": null});
1545        let (_, job) = CronJobController::build_job(&cj, 60).unwrap().unwrap();
1546        assert_eq!(
1547            job["metadata"]["labels"],
1548            json!({"engenho.io/cronjob": "n"})
1549        );
1550    }
1551
1552    fn job_with_backoff(backoff_limit: Option<i64>) -> Value {
1553        let mut job = json!({
1554            "kind": "Job", "apiVersion": "batch/v1",
1555            "metadata": {"name": "flaky", "namespace": "default", "uid": "flaky-uid"},
1556            "spec": {"template": {"spec": {"containers": [{"image": "alpine"}]}}}
1557        });
1558        if let Some(limit) = backoff_limit {
1559            job["spec"]["backoffLimit"] = json!(limit);
1560        }
1561        job
1562    }
1563
1564    fn pods_in_phase(phase: &str, count: usize) -> Vec<(ResourceKey, Value)> {
1565        (0..count)
1566            .map(|i| {
1567                let name = format!("flaky-{i}");
1568                (
1569                    ResourceKey::namespaced("", "v1", "Pod", "default", &name),
1570                    json!({"metadata": {"name": name}, "status": {"phase": phase}}),
1571                )
1572            })
1573            .collect()
1574    }
1575
1576    #[test]
1577    fn job_backoff_limit_defaults_to_6() {
1578        assert_eq!(BACKOFF_LIMIT.read(&json!({"spec": {}})), Ok(6));
1579    }
1580
1581    #[tokio::test]
1582    async fn a_pod_that_always_fails_stops_at_backoff_limit_plus_one() {
1583        let store = test_store("job-backoff").await;
1584        let c = JobController::new(store, None).with_selector(JobSelector::Off);
1585        let job = job_with_backoff(Some(3));
1586
1587        let retry = c
1588            .reconcile_one(&job, &pods_in_phase("Failed", 3))
1589            .await
1590            .unwrap();
1591        assert_eq!(
1592            retry.commands.len(),
1593            1,
1594            "within the limit a failed pod is replaced"
1595        );
1596
1597        let exhausted = pods_in_phase("Failed", 4);
1598        let stop = c.reconcile_one(&job, &exhausted).await.unwrap();
1599        assert!(
1600            stop.commands.is_empty(),
1601            "backoffLimit + 1 failures create nothing"
1602        );
1603
1604        let status = c.compute_status(&job, &exhausted, 1).unwrap();
1605        assert_eq!(status["failed"], json!(4));
1606        assert_eq!(status["conditions"][0]["type"], json!("Failed"));
1607        assert_eq!(
1608            status["conditions"][0]["reason"],
1609            json!("BackoffLimitExceeded")
1610        );
1611        assert!(job_is_terminal(&json!({"status": status})));
1612    }
1613
1614    #[tokio::test]
1615    async fn an_absent_backoff_limit_stops_after_seven_failures() {
1616        let store = test_store("job-backoff-default").await;
1617        let c = JobController::new(store, None).with_selector(JobSelector::Off);
1618        let job = job_with_backoff(None);
1619        assert_eq!(
1620            c.reconcile_one(&job, &pods_in_phase("Failed", 6))
1621                .await
1622                .unwrap()
1623                .commands
1624                .len(),
1625            1
1626        );
1627        assert!(
1628            c.reconcile_one(&job, &pods_in_phase("Failed", 7))
1629                .await
1630                .unwrap()
1631                .commands
1632                .is_empty()
1633        );
1634    }
1635
1636    #[tokio::test]
1637    async fn a_failed_pod_under_the_limit_leaves_status_without_a_condition() {
1638        let store = test_store("job-backoff-under").await;
1639        let c = JobController::new(store, None).with_selector(JobSelector::Off);
1640        let job = job_with_backoff(Some(3));
1641        let status = c
1642            .compute_status(&job, &pods_in_phase("Failed", 2), 1)
1643            .unwrap();
1644        assert!(status.get("conditions").is_none(), "{status}");
1645    }
1646
1647    fn finished_job(name: &str, created: u64, condition: &str) -> Value {
1648        json!({
1649            "kind": "Job", "apiVersion": "batch/v1",
1650            "metadata": {
1651                "name": name, "namespace": "default",
1652                "creationTimestamp": unix_to_rfc3339(created),
1653                "ownerReferences": [{"uid": "every-uid", "controller": true}]
1654            },
1655            "status": {"conditions": [{"type": condition, "status": "True"}]}
1656        })
1657    }
1658
1659    async fn seed_history(store: &StoreMesh, complete: u64, failed: u64) {
1660        for i in 0..complete {
1661            let name = format!("every-ok-{i}");
1662            put(
1663                store,
1664                ResourceKey::namespaced("batch", "v1", "Job", "default", &name),
1665                finished_job(&name, 1_000 + i, "Complete"),
1666            )
1667            .await;
1668        }
1669        for i in 0..failed {
1670            let name = format!("every-bad-{i}");
1671            put(
1672                store,
1673                ResourceKey::namespaced("batch", "v1", "Job", "default", &name),
1674                finished_job(&name, 2_000 + i, "Failed"),
1675            )
1676            .await;
1677        }
1678    }
1679
1680    async fn job_names(store: &StoreMesh) -> Vec<String> {
1681        let mut names: Vec<String> = list_jobs(store)
1682            .await
1683            .into_iter()
1684            .map(|(k, _)| k.name)
1685            .collect();
1686        names.sort();
1687        names
1688    }
1689
1690    #[tokio::test]
1691    async fn n_plus_three_finished_runs_leave_the_history_limits() {
1692        let store = test_store("cronjob-history").await;
1693        let mut cj = cronjob_value("every", "* * * * *", 100);
1694        cj["spec"]["successfulJobsHistoryLimit"] = json!(3);
1695        cj["spec"]["failedJobsHistoryLimit"] = json!(3);
1696        put(
1697            &store,
1698            ResourceKey::namespaced("batch", "v1", "CronJob", "default", "every"),
1699            cj,
1700        )
1701        .await;
1702        seed_history(&store, 6, 6).await;
1703        put(
1704            &store,
1705            ResourceKey::namespaced("batch", "v1", "Job", "default", "every-running"),
1706            json!({
1707                "kind": "Job", "apiVersion": "batch/v1",
1708                "metadata": {"name": "every-running", "namespace": "default",
1709                    "ownerReferences": [{"uid": "every-uid", "controller": true}]},
1710                "status": {"active": 1}
1711            }),
1712        )
1713        .await;
1714
1715        let c = CronJobController::new(store.clone(), Arc::new(FrozenClock::at(110_000)), None);
1716        let out = c.tick().await.unwrap();
1717        assert_eq!(
1718            out.objects_changed, 1,
1719            "pruning changes the CronJob's history"
1720        );
1721        assert_eq!(
1722            job_names(&store).await,
1723            [
1724                "every-bad-3",
1725                "every-bad-4",
1726                "every-bad-5",
1727                "every-ok-3",
1728                "every-ok-4",
1729                "every-ok-5",
1730                "every-running"
1731            ],
1732            "the newest finished runs are kept and an active Job is never pruned"
1733        );
1734
1735        let again = c.tick().await.unwrap();
1736        assert_eq!(again.objects_changed, 0, "a pruned history is a fixpoint");
1737    }
1738
1739    #[tokio::test]
1740    async fn absent_history_limits_keep_three_successful_and_one_failed() {
1741        let store = test_store("cronjob-history-default").await;
1742        put(
1743            &store,
1744            ResourceKey::namespaced("batch", "v1", "CronJob", "default", "every"),
1745            cronjob_value("every", "* * * * *", 100),
1746        )
1747        .await;
1748        seed_history(&store, 5, 4).await;
1749        let c = CronJobController::new(store.clone(), Arc::new(FrozenClock::at(110_000)), None);
1750        c.tick().await.unwrap();
1751        assert_eq!(
1752            job_names(&store).await,
1753            ["every-bad-3", "every-ok-2", "every-ok-3", "every-ok-4"]
1754        );
1755    }
1756
1757    #[tokio::test]
1758    async fn a_suspended_cronjob_still_prunes_its_history() {
1759        let store = test_store("cronjob-history-suspended").await;
1760        let mut cj = cronjob_value("every", "* * * * *", 0);
1761        cj["spec"]["suspend"] = json!(true);
1762        put(
1763            &store,
1764            ResourceKey::namespaced("batch", "v1", "CronJob", "default", "every"),
1765            cj,
1766        )
1767        .await;
1768        seed_history(&store, 0, 3).await;
1769        let c = CronJobController::new(store.clone(), Arc::new(FrozenClock::at(600_000)), None);
1770        let out = c.tick().await.unwrap();
1771        assert_eq!(out.objects_changed, 1);
1772        assert_eq!(job_names(&store).await, ["every-bad-2"]);
1773    }
1774
1775    fn probe_job() -> Value {
1776        json!({
1777            "kind": "Job", "apiVersion": "batch/v1",
1778            "metadata": {"name": "probe", "namespace": "default", "uid": "probe-uid"},
1779            "spec": {"template": {"spec": {"containers": [{"image": "alpine"}]}}}
1780        })
1781    }
1782
1783    async fn job_pods(store: &StoreMesh) -> Vec<(ResourceKey, Value)> {
1784        store.list("", "v1", "Pod", Some("default")).await
1785    }
1786
1787    #[tokio::test]
1788    async fn a_job_pod_carries_upstreams_job_labels_and_the_job_selects_it() {
1789        let store = test_store("job-labels").await;
1790        let job_key = ResourceKey::namespaced("batch", "v1", "Job", "default", "probe");
1791        put(&store, job_key.clone(), probe_job()).await;
1792        put(
1793            &store,
1794            ResourceKey::namespaced("", "v1", "Pod", "default", "other"),
1795            json!({"kind": "Pod", "apiVersion": "v1", "metadata": {"name": "other", "namespace": "default"}}),
1796        )
1797        .await;
1798        let c = JobController::new(store.clone(), None);
1799        c.tick().await.unwrap();
1800        c.tick().await.unwrap();
1801
1802        let job = store.get(&job_key).await.unwrap();
1803        let want = json!({
1804            "batch.kubernetes.io/controller-uid": "probe-uid",
1805            "batch.kubernetes.io/job-name": "probe",
1806            "controller-uid": "probe-uid",
1807            "job-name": "probe",
1808        });
1809        assert_eq!(
1810            job["spec"]["selector"],
1811            json!({"matchLabels": {"batch.kubernetes.io/controller-uid": "probe-uid"}}),
1812            "{job}"
1813        );
1814        assert_eq!(job["spec"]["template"]["metadata"]["labels"], want, "{job}");
1815        let pods = job_pods(&store).await;
1816        let selected: Vec<&str> = pods
1817            .iter()
1818            .filter(|(_, p)| {
1819                crate::selector::selector_match_labels(&job)
1820                    .is_some_and(|want| crate::selector::matches_labels(p, want))
1821            })
1822            .map(|(k, _)| k.name.as_str())
1823            .collect();
1824        assert_eq!(selected, ["probe-0"], "{pods:?}");
1825        let pod = &pods.iter().find(|(k, _)| k.name == "probe-0").unwrap().1;
1826        assert_eq!(pod["metadata"]["labels"], want, "{pod}");
1827    }
1828
1829    #[tokio::test]
1830    async fn a_manual_selector_job_and_the_off_switch_leave_the_job_unlabelled() {
1831        for (manual, selector) in [(true, JobSelector::Generated), (false, JobSelector::Off)] {
1832            let store = test_store("job-labels-off").await;
1833            let job_key = ResourceKey::namespaced("batch", "v1", "Job", "default", "probe");
1834            let mut job = probe_job();
1835            if manual {
1836                job["spec"]["manualSelector"] = json!(true);
1837            }
1838            put(&store, job_key.clone(), job).await;
1839            let c = JobController::new(store.clone(), None).with_selector(selector);
1840            c.tick().await.unwrap();
1841            let job = store.get(&job_key).await.unwrap();
1842            assert!(job["spec"].get("selector").is_none(), "{job}");
1843            let pods = job_pods(&store).await;
1844            assert_eq!(pods.len(), 1);
1845            assert!(pods[0].1["metadata"].get("labels").is_none(), "{pods:?}");
1846        }
1847    }
1848}