Skip to main content

engenho_controllers/
pdb.rs

1//! R19 — `PodDisruptionBudget` controller.
2//!
3//! Tracks per-pod-set disruption budgets. The substrate's
4//! voluntary-eviction path (the `/eviction` subresource — a SEPARATE
5//! later brick) consults the budget's `status.disruptionsAllowed`
6//! before allowing a voluntary pod delete; this controller maintains
7//! that status (the number it reads) so the gate has live state.
8//!
9//! ## Reconcile rule
10//!
11//! For each `policy/v1 PodDisruptionBudget`:
12//!   * Find pods in the PDB's namespace matching `spec.selector`
13//!     (reuses [`crate::selector::matches_labels`] +
14//!     [`crate::selector::selector_match_labels`] — the same
15//!     selector logic the `EndpointsController` uses; no fork).
16//!   * `expectedPods` = matched pods.
17//!   * `currentHealthy` = matched pods that are Ready (status.conditions
18//!     `Ready=True`).
19//!   * `desiredHealthy` is resolved from the `minAvailable` / `maxUnavailable`
20//!     [`IntOrString`](engenho_types::primitives::int_or_string::IntOrString) (mutually exclusive; int → that number, `"N%"` →
21//!     `ceil(N/100 × expectedPods)`):
22//!       - `minAvailable` set ⇒ `desiredHealthy = resolve(minAvailable)`.
23//!       - `maxUnavailable` set ⇒ `desiredHealthy = expectedPods − resolve(maxUnavailable)`.
24//!       - neither set ⇒ default `minAvailable` semantics (`desiredHealthy = 0`).
25//!   * `disruptionsAllowed = max(0, currentHealthy − desiredHealthy)`.
26//!   * `observedGeneration = metadata.generation`.
27//!
28//! Decisions stay idempotent — the status patch only fires when one of
29//! the five computed numbers changes (no churn on a steady re-tick).
30
31use std::sync::Arc;
32
33use async_trait::async_trait;
34use engenho_store::{
35    StoreMesh,
36    command::{Reason, ResourceCommand},
37};
38use serde_json::{Value, json};
39
40use crate::controller::{Controller, ReconcileOutcome, ReconcileReport};
41use crate::effect::Effect;
42use crate::error::ControllerError;
43use crate::meta::warn_unreadable;
44use crate::reads::{DeclaresReads, Reads, gvk};
45use crate::selector::{matches_labels, selector_match_labels};
46use crate::status::{generation_of, pod_is_ready};
47
48/// How long an eviction's `status.disruptedPods` entry keeps its pod out of
49/// the healthy count — upstream's `DeletionTimeout`.
50pub const DISRUPTED_POD_TTL: std::time::Duration = std::time::Duration::from_secs(120);
51
52/// Whether `pdb` budgets `pod`: same namespace is the caller's to ensure;
53/// this is the selector test the controller counts with, so the eviction
54/// subresource and the controller can never disagree about which pods a
55/// budget covers. A PDB with no selector covers nothing.
56#[must_use]
57pub fn pdb_selects(pdb: &Value, pod: &Value) -> bool {
58    selector_match_labels(pdb).is_some_and(|sel| matches_labels(pod, sel))
59}
60
61/// Whether `pod` counts as healthy for a budget: Ready, not being deleted,
62/// and not named in the budget's `status.disruptedPods` within the last
63/// [`DISRUPTED_POD_TTL`] (evicted, not gone yet). Upstream's disruption
64/// controller counts the same way, so a pod an eviction just took is not
65/// counted back before it disappears, and a later pod reusing its name is.
66#[must_use]
67pub fn counts_healthy(pdb: &Value, pod: &Value) -> bool {
68    let name = pod.pointer("/metadata/name").and_then(Value::as_str);
69    let disrupted = name.is_some_and(|n| {
70        pdb.pointer("/status/disruptedPods")
71            .and_then(|m| m.get(n))
72            .and_then(Value::as_str)
73            .and_then(engenho_types::time::age_since_rfc3339)
74            .is_some_and(|age| age < DISRUPTED_POD_TTL)
75    });
76    pod_is_ready(pod) && pod.pointer("/metadata/deletionTimestamp").is_none() && !disrupted
77}
78
79/// The five status numbers a PDB reconcile computes. Carrying them in
80/// one typed struct keeps the "compute" step (pure, unit-testable) and
81/// the "did anything change?" comparison (idempotency) honest — a new
82/// status field can't be silently dropped from the comparison.
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub struct PdbStatus {
85    /// `status.currentHealthy` — matched pods that are Ready.
86    pub current_healthy: i64,
87    /// `status.desiredHealthy` — minimum healthy pods the budget wants.
88    pub desired_healthy: i64,
89    /// `status.expectedPods` — matched pods (selector total).
90    pub expected_pods: i64,
91    /// `status.disruptionsAllowed` — `max(0, currentHealthy − desiredHealthy)`.
92    pub disruptions_allowed: i64,
93    /// `status.observedGeneration` — the PDB's `metadata.generation`.
94    pub observed_generation: i64,
95}
96
97/// `PodDisruptionBudget` controller.
98pub struct PodDisruptionBudgetController {
99    store: Arc<StoreMesh>,
100    namespace: Option<String>,
101}
102
103impl PodDisruptionBudgetController {
104    /// New controller.
105    #[must_use]
106    pub fn new(store: Arc<StoreMesh>, namespace: Option<String>) -> Self {
107        Self { store, namespace }
108    }
109
110    fn min_available(pdb: &Value) -> Option<&Value> {
111        pdb.get("spec").and_then(|s| s.get("minAvailable"))
112    }
113
114    fn max_unavailable(pdb: &Value) -> Option<&Value> {
115        pdb.get("spec").and_then(|s| s.get("maxUnavailable"))
116    }
117
118    /// Resolve a `minAvailable` / `maxUnavailable` `IntOrString` against a
119    /// pod total. A bare integer JSON value resolves to itself; a string of
120    /// the form `"N%"` resolves to `ceil(N/100 × total)` (K8s rounds the
121    /// percentage UP for `minAvailable`/`maxUnavailable`); any other shape
122    /// (malformed string, null, object) resolves to `None`.
123    ///
124    /// Exposed for tests — this is the int-or-percent parse the whole
125    /// `desiredHealthy` computation rests on.
126    #[must_use]
127    pub fn resolve_int_or_percent(value: &Value, total: i64) -> Option<i64> {
128        if let Some(n) = value.as_i64() {
129            return Some(n);
130        }
131        let s = value.as_str()?;
132        let pct_str = s.strip_suffix('%')?;
133        let pct: i64 = pct_str.trim().parse().ok()?;
134        // ceil(pct × total / 100) with non-negative inputs.
135        let numer = pct.saturating_mul(total);
136        Some(numer.div_euclid(100) + i64::from(numer.rem_euclid(100) != 0))
137    }
138
139    /// Pure: compute the five status numbers from the PDB's
140    /// `minAvailable`/`maxUnavailable` (int-or-percent), the healthy +
141    /// total matched-pod counts, and the PDB generation. Exposed for tests.
142    ///
143    /// `desiredHealthy`:
144    ///   * `minAvailable` set ⇒ `resolve(minAvailable, total)`.
145    ///   * else `maxUnavailable` set ⇒ `total − resolve(maxUnavailable, total)`.
146    ///   * else (neither) ⇒ 0 (default `minAvailable` semantics).
147    ///
148    /// `disruptionsAllowed = max(0, currentHealthy − desiredHealthy)`
149    /// (clamped ≥ 0). `desiredHealthy` is itself clamped ≥ 0 so a
150    /// `maxUnavailable` larger than `total` can't drive it negative.
151    #[must_use]
152    pub fn compute_status(
153        min_available: Option<&Value>,
154        max_unavailable: Option<&Value>,
155        healthy: i64,
156        total: i64,
157        generation: i64,
158    ) -> PdbStatus {
159        let desired_healthy = if let Some(min) = min_available {
160            Self::resolve_int_or_percent(min, total).unwrap_or(0)
161        } else if let Some(max) = max_unavailable {
162            let allowed_unavailable = Self::resolve_int_or_percent(max, total).unwrap_or(0);
163            total - allowed_unavailable
164        } else {
165            // Neither set — default minAvailable semantics (nothing required).
166            0
167        }
168        .max(0);
169
170        let disruptions_allowed = (healthy - desired_healthy).max(0);
171
172        PdbStatus {
173            current_healthy: healthy,
174            desired_healthy,
175            expected_pods: total,
176            disruptions_allowed,
177            observed_generation: generation,
178        }
179    }
180
181    /// Read the five status numbers already on the stored PDB (for the
182    /// idempotency comparison). A field absent → that arm of the compared
183    /// `Option` is `None`, so the very first reconcile (no status yet)
184    /// always differs and writes.
185    fn current_status(pdb: &Value) -> Option<PdbStatus> {
186        let status = pdb.get("status")?;
187        let read = |k: &str| status.get(k).and_then(serde_json::Value::as_i64);
188        Some(PdbStatus {
189            current_healthy: read("currentHealthy")?,
190            desired_healthy: read("desiredHealthy")?,
191            expected_pods: read("expectedPods")?,
192            disruptions_allowed: read("disruptionsAllowed")?,
193            observed_generation: read("observedGeneration")?,
194        })
195    }
196}
197
198/// The budgets, and the Pods their selectors count.
199impl DeclaresReads for PodDisruptionBudgetController {
200    fn reads(&self) -> Reads {
201        Reads::of(&[
202            gvk("policy", "v1", "PodDisruptionBudget"),
203            gvk("", "v1", "Pod"),
204        ])
205    }
206}
207
208#[async_trait]
209impl Controller for PodDisruptionBudgetController {
210    fn name(&self) -> &'static str {
211        "pdb"
212    }
213
214    async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
215        let pdbs = self
216            .store
217            .list(
218                "policy",
219                "v1",
220                "PodDisruptionBudget",
221                self.namespace.as_deref(),
222            )
223            .await;
224        let mut report = ReconcileReport::default();
225        report.objects_examined = pdbs.len();
226
227        for (pdb_key, pdb_value) in &pdbs {
228            // A null selector matches no pods (K8s convention); our
229            // `selector_match_labels` returns None for an absent selector,
230            // which we treat as "nothing to budget" and skip.
231            if selector_match_labels(pdb_value).is_none() {
232                report.objects_skipped += 1;
233                continue;
234            }
235            // A generation that is not an integer leaves this PDB's status
236            // alone: `observedGeneration` would name a revision nobody can.
237            let generation = match generation_of(pdb_value) {
238                Ok(generation) => generation,
239                Err(e) => {
240                    warn_unreadable("pdb", &pdb_key.label(), &e);
241                    report.objects_skipped += 1;
242                    continue;
243                }
244            };
245            let ns = pdb_key.namespace.as_deref();
246            let pods = self.store.list("", "v1", "Pod", ns).await;
247            let matching: Vec<&Value> = pods
248                .iter()
249                .filter_map(|(_, p)| pdb_selects(pdb_value, p).then_some(p))
250                .collect();
251            let total = matching.len() as i64;
252            let healthy = matching
253                .iter()
254                .filter(|p| counts_healthy(pdb_value, p))
255                .count() as i64;
256
257            let desired = Self::compute_status(
258                Self::min_available(pdb_value),
259                Self::max_unavailable(pdb_value),
260                healthy,
261                total,
262                generation,
263            );
264
265            // Idempotent: skip the patch when the live status already
266            // matches all five computed numbers.
267            if Self::current_status(pdb_value) == Some(desired) {
268                continue;
269            }
270
271            let applied = self
272                .store
273                .propose(ResourceCommand::patch(
274                    pdb_key.clone(),
275                    json!({
276                        "status": {
277                            "currentHealthy": desired.current_healthy,
278                            "desiredHealthy": desired.desired_healthy,
279                            "expectedPods": desired.expected_pods,
280                            "disruptionsAllowed": desired.disruptions_allowed,
281                            "observedGeneration": desired.observed_generation,
282                        }
283                    }),
284                    Reason::Controller,
285                ))
286                .await?;
287            report.record(Effect::of(applied.op));
288        }
289        Ok(report.into())
290    }
291}
292
293#[cfg(test)]
294mod tests {
295    use super::*;
296    use engenho_store::resource::ResourceKey;
297    use serde_json::json;
298
299    // ── pure helpers ──────────────────────────────────────────────────
300
301    #[test]
302    fn min_available_reads_spec_field() {
303        let pdb = json!({"spec": {"minAvailable": 2}});
304        assert_eq!(
305            PodDisruptionBudgetController::min_available(&pdb).and_then(serde_json::Value::as_i64),
306            Some(2)
307        );
308    }
309
310    #[test]
311    fn max_unavailable_reads_spec_field() {
312        let pdb = json!({"spec": {"maxUnavailable": 1}});
313        assert_eq!(
314            PodDisruptionBudgetController::max_unavailable(&pdb)
315                .and_then(serde_json::Value::as_i64),
316            Some(1)
317        );
318    }
319
320    #[test]
321    fn pod_is_ready_true_when_condition_true() {
322        let p = json!({"status": {"conditions": [{"type": "Ready", "status": "True"}]}});
323        assert!(crate::status::pod_is_ready(&p));
324    }
325
326    #[test]
327    fn pod_is_ready_false_when_condition_false() {
328        let p = json!({"status": {"conditions": [{"type": "Ready", "status": "False"}]}});
329        assert!(!crate::status::pod_is_ready(&p));
330    }
331
332    #[test]
333    fn pod_is_ready_false_when_no_status() {
334        let p = json!({"metadata": {"name": "x"}});
335        assert!(!crate::status::pod_is_ready(&p));
336    }
337
338    // ── int-or-percent IntOrString parse ──────────────────────────────
339
340    #[test]
341    fn resolve_int_or_percent_bare_int() {
342        assert_eq!(
343            PodDisruptionBudgetController::resolve_int_or_percent(&json!(2), 10),
344            Some(2)
345        );
346    }
347
348    #[test]
349    fn resolve_int_or_percent_percent_ceils() {
350        // 50% of 4 → ceil(2.0) = 2.
351        assert_eq!(
352            PodDisruptionBudgetController::resolve_int_or_percent(&json!("50%"), 4),
353            Some(2)
354        );
355        // 50% of 3 → ceil(1.5) = 2.
356        assert_eq!(
357            PodDisruptionBudgetController::resolve_int_or_percent(&json!("50%"), 3),
358            Some(2)
359        );
360        // 30% of 10 → ceil(3.0) = 3.
361        assert_eq!(
362            PodDisruptionBudgetController::resolve_int_or_percent(&json!("30%"), 10),
363            Some(3)
364        );
365        // 100% of 5 → 5.
366        assert_eq!(
367            PodDisruptionBudgetController::resolve_int_or_percent(&json!("100%"), 5),
368            Some(5)
369        );
370    }
371
372    #[test]
373    fn resolve_int_or_percent_malformed_is_none() {
374        assert_eq!(
375            PodDisruptionBudgetController::resolve_int_or_percent(&json!("abc"), 4),
376            None
377        );
378        assert_eq!(
379            PodDisruptionBudgetController::resolve_int_or_percent(&json!("50"), 4),
380            None
381        );
382        assert_eq!(
383            PodDisruptionBudgetController::resolve_int_or_percent(&json!(null), 4),
384            None
385        );
386    }
387
388    // ── compute_status (the brick's core math) ────────────────────────
389
390    #[test]
391    fn compute_status_min_available_int() {
392        // minAvailable=2, 3 ready / 3 total → desired=2, allowed=1.
393        let s = PodDisruptionBudgetController::compute_status(Some(&json!(2)), None, 3, 3, 7);
394        assert_eq!(s.expected_pods, 3);
395        assert_eq!(s.current_healthy, 3);
396        assert_eq!(s.desired_healthy, 2);
397        assert_eq!(s.disruptions_allowed, 1);
398        assert_eq!(s.observed_generation, 7);
399    }
400
401    #[test]
402    fn compute_status_min_available_percent() {
403        // minAvailable="50%", 3 ready / 4 total → desired=ceil(2.0)=2, allowed=1.
404        let s = PodDisruptionBudgetController::compute_status(Some(&json!("50%")), None, 3, 4, 1);
405        assert_eq!(s.expected_pods, 4);
406        assert_eq!(s.current_healthy, 3);
407        assert_eq!(s.desired_healthy, 2);
408        assert_eq!(s.disruptions_allowed, 1);
409    }
410
411    #[test]
412    fn compute_status_max_unavailable_int() {
413        // maxUnavailable=1, 3 ready / 3 total → desired = 3-1 = 2, allowed=1.
414        let s = PodDisruptionBudgetController::compute_status(None, Some(&json!(1)), 3, 3, 1);
415        assert_eq!(s.desired_healthy, 2);
416        assert_eq!(s.disruptions_allowed, 1);
417    }
418
419    #[test]
420    fn compute_status_max_unavailable_percent() {
421        // maxUnavailable="25%" of 4 → ceil(1.0)=1; desired = 4-1 = 3.
422        // 4 ready / 4 total → allowed = 4-3 = 1.
423        let s = PodDisruptionBudgetController::compute_status(None, Some(&json!("25%")), 4, 4, 1);
424        assert_eq!(s.desired_healthy, 3);
425        assert_eq!(s.disruptions_allowed, 1);
426    }
427
428    #[test]
429    fn compute_status_clamps_disruptions_allowed_at_zero() {
430        // minAvailable=3, only 2 healthy → desired=3, allowed=max(0,2-3)=0.
431        let s = PodDisruptionBudgetController::compute_status(Some(&json!(3)), None, 2, 3, 1);
432        assert_eq!(s.desired_healthy, 3);
433        assert_eq!(s.disruptions_allowed, 0);
434        // currentHealthy == desiredHealthy → also 0.
435        let s = PodDisruptionBudgetController::compute_status(Some(&json!(2)), None, 2, 2, 1);
436        assert_eq!(s.disruptions_allowed, 0);
437    }
438
439    #[test]
440    fn compute_status_max_unavailable_cannot_drive_desired_negative() {
441        // maxUnavailable=5 but only 3 pods → desired = max(0, 3-5) = 0.
442        let s = PodDisruptionBudgetController::compute_status(None, Some(&json!(5)), 3, 3, 1);
443        assert_eq!(s.desired_healthy, 0);
444        assert_eq!(s.disruptions_allowed, 3);
445    }
446
447    #[test]
448    fn compute_status_neither_defaults_to_zero_desired() {
449        let s = PodDisruptionBudgetController::compute_status(None, None, 5, 5, 1);
450        assert_eq!(s.desired_healthy, 0);
451        assert_eq!(s.disruptions_allowed, 5);
452    }
453
454    #[test]
455    fn controller_name_is_stable() {
456        struct F;
457        #[async_trait]
458        impl Controller for F {
459            fn name(&self) -> &'static str {
460                "pdb"
461            }
462            async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
463                Ok(ReconcileReport::default().into())
464            }
465        }
466        assert_eq!(F.name(), "pdb");
467    }
468
469    // ── live-store reconcile (mockable, no real cluster) ──────────────
470
471    async fn live_store() -> Arc<StoreMesh> {
472        use engenho_store::{InProcessRouter, default_config};
473        use std::time::Duration;
474        let router = InProcessRouter::new();
475        let cfg = default_config("controllers-pdb").unwrap();
476        let store = Arc::new(
477            StoreMesh::start(1, "in-process://1".into(), router, cfg)
478                .await
479                .unwrap(),
480        );
481        store.initialize_singleton().await.unwrap();
482        assert!(store.wait_for_leadership(Duration::from_secs(3)).await);
483        store
484    }
485
486    /// Seed a Pod with the given labels + readiness.
487    async fn put_pod(store: &Arc<StoreMesh>, ns: &str, name: &str, labels: Value, ready: bool) {
488        let conditions = if ready {
489            json!([{"type": "Ready", "status": "True"}])
490        } else {
491            json!([{"type": "Ready", "status": "False"}])
492        };
493        store
494            .propose(ResourceCommand::put(
495                ResourceKey::namespaced("", "v1", "Pod", ns, name),
496                json!({
497                    "kind": "Pod", "apiVersion": "v1",
498                    "metadata": {"name": name, "namespace": ns, "labels": labels},
499                    "status": {"conditions": conditions}
500                }),
501                Reason::Operator,
502            ))
503            .await
504            .unwrap();
505    }
506
507    /// Seed a PDB; returns its key.
508    async fn put_pdb(store: &Arc<StoreMesh>, ns: &str, name: &str, spec: Value) -> ResourceKey {
509        let key = ResourceKey::namespaced("policy", "v1", "PodDisruptionBudget", ns, name);
510        store
511            .propose(ResourceCommand::put(
512                key.clone(),
513                json!({
514                    "kind": "PodDisruptionBudget", "apiVersion": "policy/v1",
515                    "metadata": {"name": name, "namespace": ns},
516                    "spec": spec
517                }),
518                Reason::Operator,
519            ))
520            .await
521            .unwrap();
522        key
523    }
524
525    fn status_of(pdb: &Value) -> (i64, i64, i64, i64) {
526        let s = pdb.get("status").expect("status patched");
527        (
528            s["currentHealthy"].as_i64().unwrap(),
529            s["desiredHealthy"].as_i64().unwrap(),
530            s["expectedPods"].as_i64().unwrap(),
531            s["disruptionsAllowed"].as_i64().unwrap(),
532        )
533    }
534
535    #[tokio::test]
536    async fn min_available_two_three_ready_pods() {
537        let store = live_store().await;
538        let key = put_pdb(
539            &store,
540            "ns1",
541            "pdb",
542            json!({"minAvailable": 2, "selector": {"matchLabels": {"app": "x"}}}),
543        )
544        .await;
545        for n in ["p1", "p2", "p3"] {
546            put_pod(&store, "ns1", n, json!({"app": "x"}), true).await;
547        }
548
549        let c = PodDisruptionBudgetController::new(store.clone(), None);
550        let out = c.tick().await.unwrap();
551        assert_eq!(out.objects_changed, 1);
552
553        let pdb = store.get(&key).await.unwrap();
554        // currentHealthy=3, desiredHealthy=2, expectedPods=3, disruptionsAllowed=1.
555        assert_eq!(status_of(&pdb), (3, 2, 3, 1));
556        // observedGeneration tracks metadata.generation (store-stamped).
557        let generation = pdb["metadata"]["generation"].as_i64().unwrap();
558        assert_eq!(
559            pdb["status"]["observedGeneration"].as_i64().unwrap(),
560            generation
561        );
562    }
563
564    #[tokio::test]
565    async fn min_available_percent_50_of_four() {
566        let store = live_store().await;
567        let key = put_pdb(
568            &store,
569            "ns1",
570            "pdb",
571            json!({"minAvailable": "50%", "selector": {"matchLabels": {"app": "x"}}}),
572        )
573        .await;
574        // 4 matching pods, 3 ready.
575        put_pod(&store, "ns1", "p1", json!({"app": "x"}), true).await;
576        put_pod(&store, "ns1", "p2", json!({"app": "x"}), true).await;
577        put_pod(&store, "ns1", "p3", json!({"app": "x"}), true).await;
578        put_pod(&store, "ns1", "p4", json!({"app": "x"}), false).await;
579
580        PodDisruptionBudgetController::new(store.clone(), None)
581            .tick()
582            .await
583            .unwrap();
584
585        let pdb = store.get(&key).await.unwrap();
586        // desiredHealthy=ceil(0.5×4)=2, currentHealthy=3, expected=4, allowed=1.
587        assert_eq!(status_of(&pdb), (3, 2, 4, 1));
588    }
589
590    #[tokio::test]
591    async fn max_unavailable_one_three_ready_pods() {
592        let store = live_store().await;
593        let key = put_pdb(
594            &store,
595            "ns1",
596            "pdb",
597            json!({"maxUnavailable": 1, "selector": {"matchLabels": {"app": "x"}}}),
598        )
599        .await;
600        for n in ["p1", "p2", "p3"] {
601            put_pod(&store, "ns1", n, json!({"app": "x"}), true).await;
602        }
603
604        PodDisruptionBudgetController::new(store.clone(), None)
605            .tick()
606            .await
607            .unwrap();
608
609        let pdb = store.get(&key).await.unwrap();
610        // desiredHealthy=3-1=2, currentHealthy=3, expected=3, allowed=1.
611        assert_eq!(status_of(&pdb), (3, 2, 3, 1));
612    }
613
614    #[tokio::test]
615    async fn disruptions_allowed_clamped_to_zero() {
616        let store = live_store().await;
617        // minAvailable=3 but only 2 ready → desired=3, currentHealthy=2,
618        // disruptionsAllowed=max(0, 2-3)=0.
619        let key = put_pdb(
620            &store,
621            "ns1",
622            "pdb",
623            json!({"minAvailable": 3, "selector": {"matchLabels": {"app": "x"}}}),
624        )
625        .await;
626        put_pod(&store, "ns1", "p1", json!({"app": "x"}), true).await;
627        put_pod(&store, "ns1", "p2", json!({"app": "x"}), true).await;
628        put_pod(&store, "ns1", "p3", json!({"app": "x"}), false).await;
629
630        PodDisruptionBudgetController::new(store.clone(), None)
631            .tick()
632            .await
633            .unwrap();
634
635        let pdb = store.get(&key).await.unwrap();
636        // currentHealthy=2 (one unready), desired=3, expected=3, allowed=0.
637        assert_eq!(status_of(&pdb), (2, 3, 3, 0));
638    }
639
640    #[tokio::test]
641    async fn unready_pods_do_not_count_toward_current_healthy() {
642        let store = live_store().await;
643        let key = put_pdb(
644            &store,
645            "ns1",
646            "pdb",
647            json!({"minAvailable": 1, "selector": {"matchLabels": {"app": "x"}}}),
648        )
649        .await;
650        // 3 matching, only 1 ready.
651        put_pod(&store, "ns1", "p1", json!({"app": "x"}), true).await;
652        put_pod(&store, "ns1", "p2", json!({"app": "x"}), false).await;
653        put_pod(&store, "ns1", "p3", json!({"app": "x"}), false).await;
654
655        PodDisruptionBudgetController::new(store.clone(), None)
656            .tick()
657            .await
658            .unwrap();
659
660        let pdb = store.get(&key).await.unwrap();
661        // expected=3 (all match), currentHealthy=1 (only one ready).
662        assert_eq!(status_of(&pdb), (1, 1, 3, 0));
663    }
664
665    #[tokio::test]
666    async fn selector_only_counts_matching_pods() {
667        let store = live_store().await;
668        let key = put_pdb(
669            &store,
670            "ns1",
671            "pdb",
672            json!({"minAvailable": 1, "selector": {"matchLabels": {"app": "x"}}}),
673        )
674        .await;
675        // 2 matching ready + 1 non-matching ready pod.
676        put_pod(&store, "ns1", "p1", json!({"app": "x"}), true).await;
677        put_pod(&store, "ns1", "p2", json!({"app": "x"}), true).await;
678        put_pod(&store, "ns1", "other", json!({"app": "y"}), true).await;
679
680        PodDisruptionBudgetController::new(store.clone(), None)
681            .tick()
682            .await
683            .unwrap();
684
685        let pdb = store.get(&key).await.unwrap();
686        // expected=2 (only app=x), currentHealthy=2, desired=1, allowed=1.
687        assert_eq!(status_of(&pdb), (2, 1, 2, 1));
688    }
689
690    #[tokio::test]
691    async fn re_tick_is_idempotent_no_change() {
692        let store = live_store().await;
693        let key = put_pdb(
694            &store,
695            "ns1",
696            "pdb",
697            json!({"minAvailable": 2, "selector": {"matchLabels": {"app": "x"}}}),
698        )
699        .await;
700        for n in ["p1", "p2", "p3"] {
701            put_pod(&store, "ns1", n, json!({"app": "x"}), true).await;
702        }
703
704        let c = PodDisruptionBudgetController::new(store.clone(), None);
705        let first = c.tick().await.unwrap();
706        assert_eq!(first.objects_changed, 1);
707        let rv_after_first = store.get(&key).await.unwrap()["metadata"]["resourceVersion"].clone();
708
709        // Re-tick with no pod change: status already matches → NoChange.
710        let second = c.tick().await.unwrap();
711        assert_eq!(
712            second.objects_changed, 0,
713            "idempotent re-tick writes nothing"
714        );
715        let rv_after_second = store.get(&key).await.unwrap()["metadata"]["resourceVersion"].clone();
716        assert_eq!(
717            rv_after_first, rv_after_second,
718            "no status churn on a steady re-tick"
719        );
720    }
721}