Skip to main content

engenho_controllers/
sweep.rs

1//! PER-OBJECT ISOLATION — one object's failure costs only that object.
2//!
3//! ★ THE DEFECT. A controller's tick is a sweep: list every object of a
4//! kind, reconcile each. Before this module the only way out of an
5//! object's work was `?`, and `?` left the whole tick. The pv-binder is
6//! the worked case: a PVC whose local-path directory could not be created
7//! returned `Err` from `tick`, so every PVC after it in the list stayed
8//! Pending — on that tick, the retry, and every tick after, for as long as
9//! the one directory failed. Nothing about the other claims was wrong.
10//!
11//! ★ THE SHAPE. [`Sweep::run`] walks the objects and calls a per-object
12//! closure whose future resolves to `Result<ObjectOutcome, SweepAbort>`:
13//!
14//!   * A [`ControllerError`] cannot be `?`-ed out of that closure: there is
15//!     no `From<ControllerError> for SweepAbort`, so it does not compile
16//!     (the `compile_fail` example on [`Sweep`] pins it). The error
17//!     has to pass through [`ControllerError::triage`] (or
18//!     [`ObjectOutcome::settle`], which calls it), and triage reads
19//!     [`ControllerError::scope`]: an `Item` error becomes
20//!     [`ObjectOutcome::Failed`] and the sweep moves to the next object; only
21//!     a `Sweep` error (the store) becomes the [`SweepAbort`] that ends it.
22//!   * [`ItemFailure`] and [`SweepAbort`] have private fields and are built
23//!     only by triage, so a `Failed` always holds an Item-scoped error and
24//!     an abort always holds a Sweep-scoped one.
25//!   * The [`SweepReport`] is folded from the outcomes, one per object, and
26//!     stores no `examined` count of its own: `examined` is the sum of
27//!     changed + unchanged + skipped + failed, so the identity holds by
28//!     construction rather than by every call site counting right.
29//!
30//! ★ A FAILURE IS STILL ANSWERED. Isolating a failure must not make it
31//! quieter than aborting did.
32//!
33//!   * Every failed object is logged with its key and error.
34//!   * A Transient failure still earns a targeted retry: each failing
35//!     object keeps its own [`Streak`] on [`TRANSIENT_RETRY`], and the
36//!     sweep's outcome asks for a requeue at the earliest delay any of
37//!     them is owed. Without this a tick that isolated a failure would
38//!     return `Ok`, and the driver would wait for the fallback timer.
39//!   * A Declarative failure emits an Event on the object itself, so
40//!     `kubectl describe` says why it is stuck. It is emitted once per
41//!     (object, resourceVersion): a declaration that is still broken on
42//!     the next sweep is the same failure, and an Event per sweep would be
43//!     a Raft write per fallback tick, forever.
44//!
45//! ★ WHY `FnMut -> Future` AND NOT AN ASYNC CLOSURE. An `AsyncFnMut` bound
46//! reads better and lets the closure mutate captured state directly, but a
47//! tick is an `#[async_trait]` future that must be `Send`, and rustc cannot
48//! prove that for a generic `AsyncFnMut` today ("implementation of `Send`
49//! is not general enough"). So the closure returns a future that owns its
50//! borrows (`async move` over copied references), and state shared across
51//! objects goes through a lock held for one object's reconcile — the
52//! pv-binder's list of PVs claimed this pass is the worked example.
53//!
54//! Tier-honest: the scope decision is a type (a closure cannot `?` a
55//! [`ControllerError`] out; it must be triaged). Whether a controller USES
56//! the helper is not — a controller that still loops by hand can still `?`
57//! out of its sweep, and only review catches that.
58
59use std::collections::{BTreeMap, BTreeSet};
60use std::sync::Arc;
61use std::time::Duration;
62
63use engenho_store::{ResourceKey, ResourceValue};
64use serde_json::Value;
65use shigoto_types::failure::FailureKind;
66
67use crate::controller::{ReconcileOutcome, ReconcileReport, ReconcileResult};
68use crate::curve::Streak;
69use crate::effect::{Effect, Landed};
70use crate::error::{ControllerError, ErrorScope};
71use crate::event_recorder::{EventRecord, EventSink, InvolvedObject, NullEventSink, Reason};
72use crate::watch_driver::TRANSIENT_RETRY;
73
74/// What reconciling one object did. A sweep records exactly one per object.
75#[derive(Debug)]
76pub enum ObjectOutcome {
77    /// A write made for this object landed. The [`Landed`] comes only from
78    /// an [`Effect`] that observed it, so an object cannot be reported
79    /// changed on the strength of a write having been attempted.
80    Changed(Landed),
81    /// Examined and already converged: nothing to write.
82    Unchanged,
83    /// Deliberately not acted on this pass — waiting on something outside
84    /// the object, or outside this controller's reach. `note`, when given,
85    /// becomes the report's note.
86    Skipped { note: Option<&'static str> },
87    /// This object's reconcile failed with an Item-scoped error. Built only
88    /// by [`ControllerError::triage`].
89    Failed(ItemFailure),
90}
91
92/// A per-object outcome from what its write did: landed is Changed, a
93/// write that changed nothing is Unchanged, and a write the store refused
94/// is a Skip carrying the refusal as its note. The object is left as it
95/// was, and the next tick re-reads it.
96impl From<Effect> for ObjectOutcome {
97    fn from(effect: Effect) -> Self {
98        match effect {
99            Effect::Written(landed) => Self::Changed(landed),
100            Effect::Unchanged => Self::Unchanged,
101            Effect::Rejected(refusal) => Self::skipped_because(refusal.note()),
102        }
103    }
104}
105
106impl ObjectOutcome {
107    /// Skipped, with nothing further to say.
108    pub const SKIPPED: Self = Self::Skipped { note: None };
109
110    /// Skipped, with a note for the report.
111    #[must_use]
112    pub const fn skipped_because(note: &'static str) -> Self {
113        Self::Skipped { note: Some(note) }
114    }
115
116    /// Settle a per-object result written with ordinary `?`: an `Item`
117    /// error becomes [`ObjectOutcome::Failed`], a `Sweep` error the
118    /// [`SweepAbort`] that ends the sweep.
119    ///
120    /// This is how a per-object method returning `ControllerError` joins a
121    /// sweep: `?` inside the method leaves only the method, and this call
122    /// decides — by scope, never by the call site — whether that is the
123    /// end of the object or of the sweep.
124    ///
125    /// # Errors
126    ///
127    /// [`SweepAbort`] when the error's scope is [`ErrorScope::Sweep`].
128    pub fn settle(result: Result<Self, ControllerError>) -> Result<Self, SweepAbort> {
129        match result {
130            Ok(outcome) => Ok(outcome),
131            Err(e) => e.triage().map(Self::Failed),
132        }
133    }
134}
135
136/// An Item-scoped error, recorded against the one object it belongs to.
137///
138/// The field is private and the only constructor is
139/// [`ControllerError::triage`], so an `ItemFailure` never holds a
140/// Sweep-scoped error.
141#[derive(Debug)]
142pub struct ItemFailure(ControllerError);
143
144impl ItemFailure {
145    /// The underlying error.
146    #[must_use]
147    pub const fn error(&self) -> &ControllerError {
148        &self.0
149    }
150
151    /// Its retry class.
152    #[must_use]
153    pub const fn class(&self) -> FailureKind {
154        self.0.classify()
155    }
156}
157
158/// A Sweep-scoped error: the sweep stops here and the tick fails with it.
159///
160/// Built only by [`ControllerError::triage`]; turns back into the
161/// [`ControllerError`] it holds, so a tick can `?` it. Displays as that
162/// error, unchanged.
163#[derive(Debug, thiserror::Error)]
164#[error(transparent)]
165pub struct SweepAbort(ControllerError);
166
167impl From<SweepAbort> for ControllerError {
168    fn from(abort: SweepAbort) -> Self {
169        abort.0
170    }
171}
172
173impl ControllerError {
174    /// Split this error by [`scope`](Self::scope): an Item error is kept
175    /// for its object, a Sweep error ends the sweep.
176    ///
177    /// # Errors
178    ///
179    /// [`SweepAbort`] when the scope is [`ErrorScope::Sweep`].
180    pub fn triage(self) -> Result<ItemFailure, SweepAbort> {
181        match self.scope() {
182            ErrorScope::Item => Ok(ItemFailure(self)),
183            ErrorScope::Sweep => Err(SweepAbort(self)),
184        }
185    }
186}
187
188/// The tally of one sweep, folded from its per-object outcomes.
189///
190/// There is no stored `examined`: [`examined`](Self::examined) is the sum of
191/// the four outcome counts, so `examined = changed + unchanged + skipped +
192/// failed` cannot be broken. The counts are private and only
193/// [`Sweep::run`] adds to them.
194#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
195pub struct SweepReport {
196    changed: usize,
197    unchanged: usize,
198    skipped: usize,
199    failed: usize,
200    note: Option<&'static str>,
201    /// The earliest targeted retry any Transient failure in this sweep is
202    /// owed, read off that object's own streak.
203    retry_after: Option<Duration>,
204}
205
206impl SweepReport {
207    /// Objects the sweep reached: the sum of the four outcomes.
208    #[must_use]
209    pub const fn examined(&self) -> usize {
210        self.changed + self.unchanged + self.skipped + self.failed
211    }
212
213    #[must_use]
214    pub const fn changed(&self) -> usize {
215        self.changed
216    }
217
218    #[must_use]
219    pub const fn unchanged(&self) -> usize {
220        self.unchanged
221    }
222
223    #[must_use]
224    pub const fn skipped(&self) -> usize {
225        self.skipped
226    }
227
228    #[must_use]
229    pub const fn failed(&self) -> usize {
230        self.failed
231    }
232
233    /// The last note a skipped object gave, if any.
234    #[must_use]
235    pub const fn note(&self) -> Option<&'static str> {
236        self.note
237    }
238
239    /// When the sweep wants to run again because of a Transient failure.
240    #[must_use]
241    pub const fn retry_after(&self) -> Option<Duration> {
242        self.retry_after
243    }
244
245    fn record(&mut self, outcome: &ObjectOutcome) {
246        match outcome {
247            ObjectOutcome::Changed(_) => self.changed += 1,
248            ObjectOutcome::Unchanged => self.unchanged += 1,
249            ObjectOutcome::Skipped { note } => {
250                self.skipped += 1;
251                if note.is_some() {
252                    self.note = *note;
253                }
254            }
255            ObjectOutcome::Failed(_) => self.failed += 1,
256        }
257    }
258
259    fn owe(&mut self, after: Duration) {
260        self.retry_after = Some(self.retry_after.map_or(after, |d| d.min(after)));
261    }
262
263    /// One tally for a tick that ran two sweeps, this one first: the counts
264    /// add, the retry owed is the earlier of the two, and the note is the
265    /// later sweep's when it gave one.
266    ///
267    /// A controller whose tick walks two kinds keeps a [`Sweep`] per kind,
268    /// because a sweep forgets every object it did not see fail; one sweep
269    /// over both would forget the other kind's failures each time.
270    #[must_use]
271    pub fn then(self, later: Self) -> Self {
272        Self {
273            changed: self.changed + later.changed,
274            unchanged: self.unchanged + later.unchanged,
275            skipped: self.skipped + later.skipped,
276            failed: self.failed + later.failed,
277            note: later.note.or(self.note),
278            retry_after: match (self.retry_after, later.retry_after) {
279                (Some(a), Some(b)) => Some(a.min(b)),
280                (a, b) => a.or(b),
281            },
282        }
283    }
284
285    /// Log this tally for `controller`, at WARN when anything failed.
286    pub fn log(&self, controller: &str) {
287        let note = self.note.unwrap_or("");
288        if self.failed > 0 {
289            tracing::warn!(
290                controller,
291                examined = self.examined(),
292                changed = self.changed,
293                unchanged = self.unchanged,
294                skipped = self.skipped,
295                failed = self.failed,
296                note,
297                "reconcile tick (objects failed; the rest were reconciled)"
298            );
299        } else if self.changed > 0 || self.skipped > 0 {
300            tracing::info!(
301                controller,
302                examined = self.examined(),
303                changed = self.changed,
304                unchanged = self.unchanged,
305                skipped = self.skipped,
306                note,
307                "reconcile tick"
308            );
309        } else {
310            tracing::debug!(
311                controller,
312                examined = self.examined(),
313                "reconcile tick (no-op)"
314            );
315        }
316    }
317}
318
319/// The legacy counters, derived. `objects_skipped` is skips only; the
320/// failed and unchanged counts live on the [`SweepReport`] the outcome
321/// carries alongside.
322impl From<SweepReport> for ReconcileReport {
323    fn from(s: SweepReport) -> Self {
324        Self {
325            objects_examined: s.examined(),
326            objects_changed: s.changed,
327            objects_skipped: s.skipped,
328            note: s.note.map(str::to_string),
329        }
330    }
331}
332
333/// A tick's outcome from its sweep: the derived report, the tally itself,
334/// and a requeue at the earliest owed retry when a Transient failure was
335/// isolated (otherwise `Done`).
336impl From<SweepReport> for ReconcileOutcome {
337    fn from(s: SweepReport) -> Self {
338        let result = s
339            .retry_after
340            .map_or(ReconcileResult::Done, ReconcileResult::Requeue);
341        let mut outcome = Self::new(ReconcileReport::from(s), result);
342        outcome.sweep = Some(s);
343        outcome
344    }
345}
346
347/// What a sweep remembers about an object that failed, until it stops
348/// failing or disappears.
349#[derive(Debug)]
350struct Remembered {
351    /// Consecutive failed sweeps, read against [`TRANSIENT_RETRY`].
352    streak: Streak,
353    /// The resourceVersion a Declarative failure was last announced at.
354    announced: Announced,
355}
356
357#[derive(Debug, PartialEq, Eq)]
358enum Announced {
359    Never,
360    /// An Event was emitted while the object stood at this version
361    /// (`None` when the object carried none).
362    AtVersion(Option<String>),
363}
364
365/// The per-object isolation runner a controller owns, one per controller.
366///
367/// It holds the controller's failure vocabulary (the component name that
368/// signs its Events and the upstream reason a Declarative failure is
369/// reported under) and a small memory of objects that are currently
370/// failing, bounded by that set: an object leaves it on its first
371/// non-failed outcome, or when it is no longer listed.
372///
373/// The per-object work is written with ordinary `?` against
374/// [`ControllerError`], and joins the sweep through
375/// [`ObjectOutcome::settle`]:
376///
377/// ```
378/// use engenho_controllers::event_recorder::Reason;
379/// use engenho_controllers::{ControllerError, ObjectOutcome, Sweep};
380/// use engenho_store::{ResourceKey, ResourceValue};
381///
382/// fn reconcile(_key: &ResourceKey) -> Result<ObjectOutcome, ControllerError> {
383///     Err(ControllerError::Internal("this object's directory".into()))
384/// }
385///
386/// async fn tick(
387///     sweep: &Sweep,
388///     objects: &[(ResourceKey, ResourceValue)],
389/// ) -> Result<usize, ControllerError> {
390///     let report = sweep
391///         .run(objects, |key, _value| async move {
392///             ObjectOutcome::settle(reconcile(key))
393///         })
394///         .await?;
395///     Ok(report.failed())
396/// }
397/// # let _ = Sweep::new("example", Reason::ProvisioningFailed);
398/// ```
399///
400/// `?`-ing the error straight out of the closure does not compile — there
401/// is no way to turn a [`ControllerError`] into a [`SweepAbort`] except by
402/// triaging it. This differs from the example above only in that line:
403///
404/// ```compile_fail
405/// use engenho_controllers::event_recorder::Reason;
406/// use engenho_controllers::{ControllerError, ObjectOutcome, Sweep};
407/// use engenho_store::{ResourceKey, ResourceValue};
408///
409/// fn reconcile(_key: &ResourceKey) -> Result<ObjectOutcome, ControllerError> {
410///     Err(ControllerError::Internal("this object's directory".into()))
411/// }
412///
413/// async fn tick(
414///     sweep: &Sweep,
415///     objects: &[(ResourceKey, ResourceValue)],
416/// ) -> Result<usize, ControllerError> {
417///     let report = sweep
418///         .run(objects, |key, _value| async move {
419///             let outcome = reconcile(key)?;
420///             Ok(outcome)
421///         })
422///         .await?;
423///     Ok(report.failed())
424/// }
425/// # let _ = Sweep::new("example", Reason::ProvisioningFailed);
426/// ```
427pub struct Sweep {
428    component: &'static str,
429    failure_reason: Reason,
430    events: Arc<dyn EventSink>,
431    memory: tokio::sync::Mutex<BTreeMap<ResourceKey, Remembered>>,
432}
433
434impl Sweep {
435    /// A runner for `component` (upstream's `source.component`, e.g.
436    /// `persistentvolume-controller`), announcing Declarative failures
437    /// under `failure_reason`. Events go nowhere until
438    /// [`with_event_sink`](Self::with_event_sink) wires a sink.
439    #[must_use]
440    pub fn new(component: &'static str, failure_reason: Reason) -> Self {
441        Self {
442            component,
443            failure_reason,
444            events: Arc::new(NullEventSink),
445            memory: tokio::sync::Mutex::new(BTreeMap::new()),
446        }
447    }
448
449    /// Builder: the sink Declarative failures are announced through.
450    #[must_use]
451    pub fn with_event_sink(mut self, events: Arc<dyn EventSink>) -> Self {
452        self.events = events;
453        self
454    }
455
456    /// Reconcile each of `objects` with `per_object`, isolating failures.
457    ///
458    /// `per_object` is called once per object, in order, and its future is
459    /// awaited before the next call — objects are never reconciled
460    /// concurrently, so state shared through a lock is never contended.
461    /// Every object is visited in order. An `Ok` outcome is tallied; a
462    /// [`ObjectOutcome::Failed`] is tallied, logged, and — by its class —
463    /// owed a retry or announced as an Event on the object; the sweep then
464    /// continues. Only an `Err(SweepAbort)` stops it, and that error is
465    /// returned as-is.
466    ///
467    /// # Errors
468    ///
469    /// The first [`SweepAbort`] a per-object call returns.
470    pub async fn run<'a, F, Fut>(
471        &self,
472        objects: &'a [(ResourceKey, ResourceValue)],
473        mut per_object: F,
474    ) -> Result<SweepReport, SweepAbort>
475    where
476        F: FnMut(&'a ResourceKey, &'a ResourceValue) -> Fut,
477        Fut: Future<Output = Result<ObjectOutcome, SweepAbort>>,
478    {
479        let mut memory = self.memory.lock().await;
480        let mut report = SweepReport::default();
481        let mut failing: BTreeSet<&ResourceKey> = BTreeSet::new();
482        let mut now: Option<String> = None;
483
484        for (key, value) in objects {
485            let outcome = per_object(key, value).await?;
486            if let ObjectOutcome::Failed(failure) = &outcome {
487                failing.insert(key);
488                let seen = memory.entry(key.clone()).or_insert_with(|| Remembered {
489                    streak: Streak::new(TRANSIENT_RETRY),
490                    announced: Announced::Never,
491                });
492                let owed = seen.streak.miss();
493                match failure.class() {
494                    // No targeted retry, the same rule the driver applies
495                    // to a Declarative tick: re-trying an unusable
496                    // declaration does not fix it. The Event is the answer,
497                    // and it and the WARN are given once per version; a
498                    // later sweep meeting the same declaration says so at
499                    // DEBUG only.
500                    FailureKind::Declarative => {
501                        let version = Announced::AtVersion(resource_version(value));
502                        if seen.announced == version {
503                            tracing::debug!(
504                                controller = self.component,
505                                object = %key.label(),
506                                error = %failure.error(),
507                                "object still fails (declarative, already announced)"
508                            );
509                        } else {
510                            tracing::warn!(
511                                controller = self.component,
512                                object = %key.label(),
513                                error = %failure.error(),
514                                "object reconcile failed (declarative: not retried until it \
515                                 changes); the sweep continues with the next object"
516                            );
517                            let stamp = now
518                                .get_or_insert_with(engenho_types::time::now_rfc3339_utc)
519                                .clone();
520                            self.events
521                                .record(EventRecord {
522                                    involved: involved_object(key, value),
523                                    reason: self.failure_reason,
524                                    message: failure.error().to_string(),
525                                    component: self.component.to_string(),
526                                    timestamp: stamp,
527                                })
528                                .await;
529                            seen.announced = version;
530                        }
531                    }
532                    // Transient, and any class shigoto adds later (the enum
533                    // is non_exhaustive): retried on this object's curve,
534                    // never faster than a Transient.
535                    class => {
536                        tracing::warn!(
537                            controller = self.component,
538                            object = %key.label(),
539                            class = ?class,
540                            error = %failure.error(),
541                            retry_after_ms = u64::try_from(owed.as_millis()).unwrap_or(u64::MAX),
542                            "object reconcile failed; retrying it on its own curve, and the \
543                             sweep continues with the next object"
544                        );
545                        report.owe(owed);
546                    }
547                }
548            } else {
549                memory.remove(key);
550            }
551            report.record(&outcome);
552        }
553
554        // Every object was reached: forget any that are not failing now —
555        // recovered ones were removed above, and this drops the ones that
556        // were deleted. The memory is bounded by the failing set.
557        memory.retain(|k, _| failing.contains(k));
558        Ok(report)
559    }
560}
561
562/// Give a controller that owns a `sweep: Sweep` field its event-sink
563/// builder. Invoked in the controller's own module (the field is private
564/// there), once per controller, so the builder is written once:
565///
566/// ```ignore
567/// crate::sweep::impl_sweep_event_sink!(ReplicaSetController);
568/// ```
569macro_rules! impl_sweep_event_sink {
570    ($controller:ty) => {
571        $crate::sweep::impl_sweep_event_sink!($controller: sweep);
572    };
573    // A controller that keeps one sweep per kind it walks names each field.
574    ($controller:ty: $($field:ident),+ $(,)?) => {
575        impl $controller {
576            /// Builder: wire the sink this controller announces a failed
577            /// object through — a Warning Event on that object, once per
578            /// resourceVersion (see [`crate::sweep::Sweep`]).
579            #[must_use]
580            pub fn with_event_sink(
581                mut self,
582                events: ::std::sync::Arc<dyn $crate::event_recorder::EventSink>,
583            ) -> Self {
584                $(self.$field = self.$field.with_event_sink(::std::sync::Arc::clone(&events));)+
585                self
586            }
587        }
588    };
589}
590pub(crate) use impl_sweep_event_sink;
591
592/// `metadata.resourceVersion`, if the object carries one.
593fn resource_version(value: &ResourceValue) -> Option<String> {
594    value
595        .get("metadata")
596        .and_then(|m| m.get("resourceVersion"))
597        .and_then(Value::as_str)
598        .map(str::to_string)
599}
600
601/// The Event subject for a listed object, from its key and its own uid.
602fn involved_object(key: &ResourceKey, value: &ResourceValue) -> InvolvedObject {
603    let api_version = if key.group.is_empty() {
604        key.version.clone()
605    } else {
606        [key.group.as_str(), "/", key.version.as_str()].concat()
607    };
608    InvolvedObject {
609        api_version,
610        kind: key.kind.clone(),
611        namespace: key.namespace.clone(),
612        name: key.name.clone(),
613        uid: value
614            .get("metadata")
615            .and_then(|m| m.get("uid"))
616            .and_then(Value::as_str)
617            .map(str::to_string),
618    }
619}
620
621#[cfg(test)]
622mod tests {
623    use super::*;
624    use crate::event_recorder::CollectingEventSink;
625    use engenho_store::StoreError;
626    use engenho_store::command::ResourceOp;
627    use serde_json::json;
628
629    fn obj(name: &str, rv: &str) -> (ResourceKey, ResourceValue) {
630        (
631            ResourceKey::namespaced("", "v1", "PersistentVolumeClaim", "ns", name),
632            json!({ "metadata": { "name": name, "namespace": "ns",
633                                  "uid": (["uid-", name].concat()), "resourceVersion": rv } }),
634        )
635    }
636
637    fn objs(names: &[&str]) -> Vec<(ResourceKey, ResourceValue)> {
638        names.iter().map(|n| obj(n, "1")).collect()
639    }
640
641    /// Per-object answers keyed by name; anything unnamed is Changed.
642    fn answer(name: &str) -> Result<ObjectOutcome, ControllerError> {
643        match name {
644            "broken" => Err(ControllerError::InvalidResource(
645                "no storage request".into(),
646            )),
647            "flaky" => Err(ControllerError::Internal("mkdir: permission denied".into())),
648            "store-down" => Err(ControllerError::Store(StoreError::ClientWriteFailed(
649                "no leader".into(),
650            ))),
651            "settled" => Ok(ObjectOutcome::Unchanged),
652            "waiting" => Ok(ObjectOutcome::skipped_because("waiting on a driver")),
653            _ => Ok(ObjectOutcome::from(Effect::of(ResourceOp::Created))),
654        }
655    }
656
657    fn sweep_with(events: Arc<CollectingEventSink>) -> Sweep {
658        Sweep::new("test-controller", Reason::ProvisioningFailed).with_event_sink(events)
659    }
660
661    /// Two sweeps in one tick fold into one tally: counts add, the earlier
662    /// retry wins, and a later sweep with nothing to say keeps the earlier
663    /// note.
664    #[test]
665    fn two_sweeps_fold_into_one_tally() {
666        let mut first = SweepReport::default();
667        first.record(&answer("new").unwrap());
668        first.record(&ObjectOutcome::skipped_because("first"));
669        first.owe(Duration::from_secs(4));
670        let mut later = SweepReport::default();
671        later.record(&ObjectOutcome::Unchanged);
672        later.owe(Duration::from_secs(2));
673
674        let both = first.then(later);
675
676        assert_eq!(
677            (
678                both.changed(),
679                both.unchanged(),
680                both.skipped(),
681                both.failed()
682            ),
683            (1, 1, 1, 0)
684        );
685        assert_eq!(both.examined(), 3);
686        assert_eq!(both.note(), Some("first"));
687        assert_eq!(both.retry_after(), Some(Duration::from_secs(2)));
688        let mut noted = SweepReport::default();
689        noted.record(&ObjectOutcome::skipped_because("later"));
690        assert_eq!(both.then(noted).note(), Some("later"));
691    }
692
693    async fn run(
694        sweep: &Sweep,
695        objects: &[(ResourceKey, ResourceValue)],
696    ) -> Result<SweepReport, SweepAbort> {
697        sweep
698            .run(objects, |key, _value| {
699                std::future::ready(ObjectOutcome::settle(answer(&key.name)))
700            })
701            .await
702    }
703
704    #[tokio::test]
705    async fn one_poisoned_object_does_not_stop_the_others() {
706        let events = Arc::new(CollectingEventSink::new());
707        let sweep = sweep_with(events.clone());
708        let objects = objs(&["a", "broken", "b", "flaky", "c"]);
709        let mut visited = Vec::new();
710        let report = sweep
711            .run(&objects, |key, _value| {
712                visited.push(key.name.clone());
713                std::future::ready(ObjectOutcome::settle(answer(&key.name)))
714            })
715            .await
716            .expect("item failures never abort the sweep");
717        assert_eq!(
718            visited,
719            ["a", "broken", "b", "flaky", "c"],
720            "every object was reached"
721        );
722        assert_eq!(
723            report.changed(),
724            3,
725            "the three healthy objects were reconciled"
726        );
727        assert_eq!(report.failed(), 2);
728    }
729
730    #[tokio::test]
731    async fn the_report_identity_holds_for_every_mix_of_outcomes() {
732        let names = [
733            "a", "broken", "settled", "waiting", "flaky", "b", "settled2",
734        ];
735        // Every prefix of the list, so each outcome kind is tallied alone
736        // and in combination.
737        for n in 0..=names.len() {
738            let sweep = sweep_with(Arc::new(CollectingEventSink::new()));
739            let objects = objs(&names[..n]);
740            let report = run(&sweep, &objects).await.unwrap();
741            assert_eq!(report.examined(), n, "examined is every object reached");
742            assert_eq!(
743                report.examined(),
744                report.changed() + report.unchanged() + report.skipped() + report.failed(),
745            );
746            let legacy = ReconcileReport::from(report);
747            assert_eq!(legacy.objects_examined, n);
748            assert_eq!(legacy.objects_changed, report.changed());
749            assert_eq!(legacy.objects_skipped, report.skipped());
750        }
751    }
752
753    /// An object is changed only if its write landed: a `NoOp` is unchanged
754    /// and a refused write is a skip naming the refusal, and neither is
755    /// tallied as a change.
756    #[tokio::test]
757    async fn an_object_is_changed_only_when_its_write_landed() {
758        let sweep = sweep_with(Arc::new(CollectingEventSink::new()));
759        let objects = objs(&["created", "noop", "conflict"]);
760        let report = sweep
761            .run(&objects, |key, _value| {
762                let op = match key.name.as_str() {
763                    "created" => ResourceOp::Created,
764                    "noop" => ResourceOp::NoOp,
765                    _ => ResourceOp::Conflict,
766                };
767                std::future::ready(Ok(ObjectOutcome::from(Effect::of(op))))
768            })
769            .await
770            .unwrap();
771        assert_eq!(
772            (report.changed(), report.unchanged(), report.skipped()),
773            (1, 1, 1)
774        );
775        assert_eq!(
776            report.note(),
777            Some(crate::effect::Refusal::Conflict.note()),
778            "the skip says the store refused the write"
779        );
780    }
781
782    #[tokio::test]
783    async fn a_store_error_stops_the_sweep_at_that_object() {
784        let sweep = sweep_with(Arc::new(CollectingEventSink::new()));
785        let objects = objs(&["a", "store-down", "b"]);
786        let mut visited = Vec::new();
787        let err = sweep
788            .run(&objects, |key, _value| {
789                visited.push(key.name.clone());
790                std::future::ready(ObjectOutcome::settle(answer(&key.name)))
791            })
792            .await
793            .expect_err("a store error is sweep-scoped");
794        assert_eq!(
795            visited,
796            ["a", "store-down"],
797            "nothing after the store error ran"
798        );
799        assert!(matches!(
800            ControllerError::from(err),
801            ControllerError::Store(StoreError::ClientWriteFailed(_))
802        ));
803    }
804
805    #[test]
806    fn triage_splits_by_scope_and_keeps_the_error() {
807        let item = ControllerError::Internal("x".into()).triage().unwrap();
808        assert!(matches!(item.error(), ControllerError::Internal(_)));
809        let abort = ControllerError::Store(StoreError::Fatal("y".into()))
810            .triage()
811            .unwrap_err();
812        // One Display: the abort renders exactly as the error it holds.
813        assert_eq!(
814            abort.to_string(),
815            ControllerError::Store(StoreError::Fatal("y".into())).to_string()
816        );
817    }
818
819    #[tokio::test]
820    async fn a_declarative_failure_is_announced_on_its_object_once_per_version() {
821        let events = Arc::new(CollectingEventSink::new());
822        let sweep = sweep_with(events.clone());
823        let objects = objs(&["a", "broken", "flaky"]);
824        run(&sweep, &objects).await.unwrap();
825        let first = events.drain();
826        assert_eq!(first.len(), 1, "only the Declarative failure is announced");
827        let e = &first[0];
828        assert_eq!(e.reason, Reason::ProvisioningFailed);
829        assert_eq!(e.involved.kind, "PersistentVolumeClaim");
830        assert_eq!(e.involved.api_version, "v1");
831        assert_eq!(e.involved.namespace.as_deref(), Some("ns"));
832        assert_eq!(e.involved.name, "broken");
833        assert_eq!(e.involved.uid.as_deref(), Some("uid-broken"));
834        assert_eq!(e.component, "test-controller");
835        assert!(e.message.contains("no storage request"), "{}", e.message);
836
837        // The same declaration on the next sweep is the same failure.
838        run(&sweep, &objects).await.unwrap();
839        assert!(
840            events.drain().is_empty(),
841            "no Event per sweep for an unchanged object"
842        );
843
844        // An edited object that still fails is a new failure.
845        let edited = vec![obj("broken", "2")];
846        run(&sweep, &edited).await.unwrap();
847        assert_eq!(events.drain().len(), 1, "a new version is announced again");
848    }
849
850    #[tokio::test]
851    async fn a_recovered_object_is_announced_again_if_it_breaks_again() {
852        let events = Arc::new(CollectingEventSink::new());
853        let sweep = sweep_with(events.clone());
854        let broken = objs(&["broken"]);
855        run(&sweep, &broken).await.unwrap();
856        assert_eq!(events.drain().len(), 1);
857        // Gone from the list: forgotten.
858        run(&sweep, &[]).await.unwrap();
859        run(&sweep, &broken).await.unwrap();
860        assert_eq!(
861            events.drain().len(),
862            1,
863            "a failure after the object left is new"
864        );
865    }
866
867    #[tokio::test]
868    async fn a_transient_failure_owes_a_retry_that_grows_per_object() {
869        let sweep = sweep_with(Arc::new(CollectingEventSink::new()));
870        let objects = objs(&["a", "flaky"]);
871        let mut owed = Vec::new();
872        for _ in 0..4 {
873            let report = run(&sweep, &objects).await.unwrap();
874            owed.push(
875                report
876                    .retry_after()
877                    .expect("a transient failure asks for a retry"),
878            );
879        }
880        assert_eq!(
881            owed,
882            (0..4).map(|n| TRANSIENT_RETRY.delay(n)).collect::<Vec<_>>(),
883            "the object's own streak, on the shared curve"
884        );
885        let outcome = ReconcileOutcome::from(run(&sweep, &objects).await.unwrap());
886        assert_eq!(
887            outcome.result,
888            ReconcileResult::Requeue(TRANSIENT_RETRY.delay(4))
889        );
890
891        // The same object succeeding resets its streak: it is forgotten,
892        // and the sweep owes nothing.
893        let report = sweep
894            .run(&objects, |_key, _value| {
895                std::future::ready(Ok(ObjectOutcome::from(Effect::of(ResourceOp::Replaced))))
896            })
897            .await
898            .unwrap();
899        assert_eq!(report.retry_after(), None);
900        assert_eq!(ReconcileOutcome::from(report).result, ReconcileResult::Done);
901        // ...so its next failure starts from the curve's base again.
902        let report = run(&sweep, &objects).await.unwrap();
903        assert_eq!(report.retry_after(), Some(TRANSIENT_RETRY.base()));
904    }
905
906    #[tokio::test]
907    async fn a_declarative_failure_owes_no_targeted_retry() {
908        let sweep = sweep_with(Arc::new(CollectingEventSink::new()));
909        let report = run(&sweep, &objs(&["broken"])).await.unwrap();
910        assert_eq!(report.failed(), 1);
911        assert_eq!(report.retry_after(), None);
912    }
913}