Skip to main content

engenho_controllers/
event_recorder.rs

1//! EVENT RECORDING — how the cluster explains itself.
2//!
3//! ★ WHY THIS EXISTS. `Event` has always been in the catalog: storable,
4//! listable, watchable like any other kind. Nothing ever WROTE one. The
5//! consequence is not cosmetic — `kubectl describe pod` shows an empty
6//! Events section, `kubectl get events` is empty, and every "why did this
7//! fail" question has no in-cluster answer at all.
8//!
9//! Measured on cid 2026-08-29: diagnosing a pod that had restarted 160
10//! times required reading podman's container list and the daemon's own log
11//! file directly, because the cluster could say *that* it had restarted and
12//! never *why*. A distribution whose failures are only legible by sshing to
13//! the node is not substitutable for one whose are not.
14//!
15//! ★ THE REASON VOCABULARY IS UPSTREAM'S, NOT OURS. Every string in
16//! [`Reason`] is one kubectl, operators, alerting rules and a decade of
17//! runbooks already recognise. Inventing `PodDidNotStart` where upstream
18//! says `Failed` would produce events that are technically present and
19//! practically useless — worse than none, because they look right.
20//!
21//! ★ ONE TYPE, NOT FREE STRINGS. An event is emitted from the kubelet, the
22//! scheduler and several controllers; a `&str` reason at each site drifts
23//! within a release. The closed [`Reason`] enum makes a typo a compile
24//! error and lets the vocabulary be diffed against upstream in one place.
25
26use engenho_store::{ResourceKey, ResourceValue};
27use serde_json::json;
28
29/// Event severity — upstream's `type` field, which has exactly two values.
30///
31/// Not a bool: `Normal`/`Warning` are what appears on the wire and in
32/// `kubectl get events --field-selector type=Warning`, and a bool would
33/// have to be translated at every boundary.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum Severity {
36    Normal,
37    Warning,
38}
39
40impl Severity {
41    #[must_use]
42    pub fn as_str(self) -> &'static str {
43        match self {
44            Self::Normal => "Normal",
45            Self::Warning => "Warning",
46        }
47    }
48}
49
50/// The upstream reason vocabulary, closed.
51///
52/// Only reasons engenho can actually emit are listed. A reason with no
53/// emitting site would be a promise the cluster does not keep — the same
54/// "advertised with zero behaviour" pattern this codebase otherwise avoids.
55/// The two exceptions, [`Reason::ProbeBlind`] and [`Reason::WouldReject`],
56/// say on their variant which emitter they are waiting for.
57///
58/// Four reasons are engenho's own, each for a state upstream does not
59/// have: [`Reason::NetworkPolicyNotEnforced`],
60/// [`Reason::ResourcesNotEnforced`], [`Reason::ProbeBlind`] and
61/// [`Reason::WouldReject`]. Each is `Warning`. The last two share their
62/// word with what an operator searches for beside them — the kubelet's
63/// `ProbeBlind` pod condition, the `engenho_would_reject_total` metric — so
64/// each pair is found together.
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub enum Reason {
67    // ── kubelet, pod lifecycle ──
68    /// The image was pulled successfully.
69    Pulled,
70    /// A container was created from the image.
71    Created,
72    /// A container was started.
73    Started,
74    /// A container terminated unexpectedly, or could not be started.
75    Failed,
76    /// A container was killed (delete, probe failure, restart).
77    Killing,
78    /// A liveness/readiness/startup probe failed.
79    Unhealthy,
80    /// A probe could not observe the container at all: the pod has no
81    /// address to dial, the runtime could not run the exec, or the prober
82    /// could not form the request. Nothing was asked, so nothing failed —
83    /// and a blind probe never restarts a container.
84    ///
85    /// Not upstream's: upstream's prober reports an errored probe as
86    /// `Unhealthy`, which makes "the prober cannot see" read as "the
87    /// workload is failing" to every rule that matches `Unhealthy`. Named
88    /// after the kubelet's `ProbeBlind` pod condition, raised once the
89    /// blindness is sustained.
90    ///
91    /// Emitter: the kubelet's blind report, once per blind streak, on the
92    /// pod — which at this commit still records `Unhealthy` (T1.1).
93    ProbeBlind,
94    /// The container is in a crash-restart backoff.
95    BackOff,
96    // ── scheduler ──
97    /// The pod was assigned to a node.
98    Scheduled,
99    /// No node satisfied the pod's requirements.
100    FailedScheduling,
101    // ── workload controllers ──
102    /// A `ReplicaSet` was scaled up or down.
103    ScalingReplicaSet,
104    /// A `ReplicaSet` created a pod.
105    SuccessfulCreate,
106    /// A `ReplicaSet` deleted a pod.
107    SuccessfulDelete,
108    /// A workload controller could not create a child from its parent's
109    /// template (`ReplicaSet`, `StatefulSet`, `DaemonSet` and `Job` pods;
110    /// `CronJob` jobs). Upstream's `FailedCreatePodReason`. Emitted by the
111    /// owned-children sweep and the `CronJob` sweep, on the parent.
112    FailedCreate,
113    /// A controller could not update an object it maintains. Upstream's
114    /// `StatefulSet` `Failed<Verb>` string for `update`. Emitted by the
115    /// `NetworkPolicy` controller when a policy's enforcement annotation
116    /// cannot be written, and by the pvc-protection controller's sweep on a
117    /// claim whose finalizers it cannot write.
118    FailedUpdate,
119    /// The Deployment controller could not create a `ReplicaSet`. Upstream's
120    /// `deploymentutil.FailedRSCreateReason`.
121    ReplicaSetCreateError,
122    /// The Endpoints controller could not write a Service's `Endpoints` or
123    /// `EndpointSlice`. Upstream's `FailedToUpdateEndpoint`.
124    FailedToUpdateEndpoint,
125    /// A `PersistentVolumeClaim` was bound.
126    ProvisioningSucceeded,
127    /// A `PersistentVolumeClaim` could not be provisioned, for a reason that
128    /// retrying will not clear (its declaration is unusable). Emitted by the
129    /// pv-binder's sweep on the claim itself.
130    ProvisioningFailed,
131    /// A Released `PersistentVolume` could not be reclaimed under its
132    /// policy: engenho knows no deleter for it, its policy is one engenho
133    /// does not run, or its directory is not the one the local-path
134    /// provisioner derived. Upstream's `VolumeFailedDelete`. Emitted by the
135    /// pv-binder's volume sweep on the volume, once, as it goes `Failed`.
136    VolumeFailedDelete,
137    // ── networking ──
138    /// A `NetworkPolicy` was accepted and its rules computed, but no packet
139    /// filter was installed — so the traffic it claims to restrict is
140    /// unrestricted. The one case where silence would be a SECURITY claim
141    /// rather than a missing feature, which is why it is a `Warning` and
142    /// why it is surfaced where `kubectl describe` shows it.
143    NetworkPolicyNotEnforced,
144    ResourcesNotEnforced,
145    ConfinementNotEnforced,
146    // ── rollout gates ──
147    /// A gate in Shadow allowed what Enforce would refuse. The string is
148    /// [`engenho_substrate::WouldReject::EVENT_REASON`], owned by the
149    /// rollout gate and shared with the `engenho_would_reject_total` metric,
150    /// so it is read from there rather than restated here.
151    ///
152    /// Emitter: none yet. A gate's ledger hook logs and counts; no gate
153    /// records an Event until one is handed a sink (T0.11).
154    WouldReject,
155}
156
157impl Reason {
158    /// The exact wire string — upstream's, or for engenho's own reasons the
159    /// one their owner defines. Diffed in one place, not per call site.
160    #[must_use]
161    pub fn as_str(self) -> &'static str {
162        match self {
163            Self::Pulled => "Pulled",
164            Self::Created => "Created",
165            Self::Started => "Started",
166            Self::Failed => "Failed",
167            Self::Killing => "Killing",
168            Self::Unhealthy => "Unhealthy",
169            Self::ProbeBlind => "ProbeBlind",
170            Self::BackOff => "BackOff",
171            Self::Scheduled => "Scheduled",
172            Self::FailedScheduling => "FailedScheduling",
173            Self::ScalingReplicaSet => "ScalingReplicaSet",
174            Self::SuccessfulCreate => "SuccessfulCreate",
175            Self::SuccessfulDelete => "SuccessfulDelete",
176            Self::FailedCreate => "FailedCreate",
177            Self::FailedUpdate => "FailedUpdate",
178            Self::ReplicaSetCreateError => "ReplicaSetCreateError",
179            Self::FailedToUpdateEndpoint => "FailedToUpdateEndpoint",
180            Self::ProvisioningSucceeded => "ProvisioningSucceeded",
181            Self::ProvisioningFailed => "ProvisioningFailed",
182            Self::VolumeFailedDelete => "VolumeFailedDelete",
183            Self::NetworkPolicyNotEnforced => "NetworkPolicyNotEnforced",
184            Self::ResourcesNotEnforced => "ResourcesNotEnforced",
185            Self::ConfinementNotEnforced => "ConfinementNotEnforced",
186            Self::WouldReject => engenho_substrate::WouldReject::EVENT_REASON,
187        }
188    }
189
190    /// The severity upstream pairs with this reason.
191    ///
192    /// Derived rather than passed in: a `Warning`/`Normal` argument at each
193    /// call site is exactly where drift appears, and upstream's pairing is
194    /// fixed per reason.
195    ///
196    /// Exhaustive, with no wildcard arm: a new reason does not compile until
197    /// it is given a severity, so it cannot fall silently into `Normal`.
198    #[must_use]
199    pub fn severity(self) -> Severity {
200        match self {
201            Self::Failed
202            | Self::Unhealthy
203            | Self::ProbeBlind
204            | Self::BackOff
205            | Self::FailedScheduling
206            | Self::ProvisioningFailed
207            | Self::VolumeFailedDelete
208            | Self::FailedCreate
209            | Self::FailedUpdate
210            | Self::ReplicaSetCreateError
211            | Self::FailedToUpdateEndpoint
212            | Self::NetworkPolicyNotEnforced
213            | Self::ResourcesNotEnforced
214            | Self::ConfinementNotEnforced
215            | Self::WouldReject => Severity::Warning,
216            Self::Pulled
217            | Self::Created
218            | Self::Started
219            | Self::Killing
220            | Self::Scheduled
221            | Self::ScalingReplicaSet
222            | Self::SuccessfulCreate
223            | Self::SuccessfulDelete
224            | Self::ProvisioningSucceeded => Severity::Normal,
225        }
226    }
227}
228
229/// What the event is about.
230#[derive(Debug, Clone, PartialEq, Eq)]
231pub struct InvolvedObject {
232    pub api_version: String,
233    pub kind: String,
234    pub namespace: Option<String>,
235    pub name: String,
236    pub uid: Option<String>,
237}
238
239/// A single recorded event, ready to be written.
240#[derive(Debug, Clone)]
241pub struct EventRecord {
242    pub involved: InvolvedObject,
243    pub reason: Reason,
244    pub message: String,
245    /// The component that observed it (`kubelet`, `default-scheduler`,
246    /// `replicaset-controller`) — upstream's `source.component`.
247    pub component: String,
248    /// Frozen at the boundary by the caller. The clock is not a replicated
249    /// input, the same law `deletion_timestamp` obeys.
250    pub timestamp: String,
251}
252
253impl EventRecord {
254    /// The object's name in the events namespace.
255    ///
256    /// Upstream appends a nanosecond-ish suffix so repeated events about
257    /// one object do not collide. engenho derives the suffix from the
258    /// frozen timestamp instead of reading a clock here, keeping the name
259    /// deterministic for a given (object, reason, timestamp) — which is
260    /// what makes an event write replay-safe on a Raft follower.
261    #[must_use]
262    pub fn event_name(&self) -> String {
263        let stamp: String = self
264            .timestamp
265            .chars()
266            .filter(char::is_ascii_alphanumeric)
267            .collect();
268        format!("{}.{}.{}", self.involved.name, self.reason.as_str(), stamp)
269    }
270
271    /// The store key this event is written at.
272    #[must_use]
273    pub fn key(&self) -> ResourceKey {
274        let ns = self.involved.namespace.as_deref().unwrap_or("default");
275        ResourceKey::namespaced("", "v1", "Event", ns, self.event_name())
276    }
277
278    /// The `v1.Event` object.
279    #[must_use]
280    pub fn to_value(&self) -> ResourceValue {
281        let ns = self.involved.namespace.as_deref().unwrap_or("default");
282        json!({
283            "apiVersion": "v1",
284            "kind": "Event",
285            "metadata": { "name": self.event_name(), "namespace": ns },
286            "involvedObject": {
287                "apiVersion": self.involved.api_version,
288                "kind": self.involved.kind,
289                "namespace": self.involved.namespace,
290                "name": self.involved.name,
291                "uid": self.involved.uid,
292            },
293            "reason": self.reason.as_str(),
294            "message": self.message,
295            "type": self.reason.severity().as_str(),
296            "source": { "component": self.component },
297            "firstTimestamp": self.timestamp,
298            "lastTimestamp": self.timestamp,
299            "eventTime": self.timestamp,
300            "count": 1,
301            "reportingComponent": self.component,
302            "reportingInstance": "",
303        })
304    }
305}
306
307#[cfg(test)]
308mod tests {
309    use super::*;
310
311    fn rec(reason: Reason) -> EventRecord {
312        EventRecord {
313            involved: InvolvedObject {
314                api_version: "v1".into(),
315                kind: "Pod".into(),
316                namespace: Some("default".into()),
317                name: "nginx".into(),
318                uid: Some("abc".into()),
319            },
320            reason,
321            message: "because".into(),
322            component: "kubelet".into(),
323            timestamp: "2026-08-29T21:00:00Z".into(),
324        }
325    }
326
327    #[test]
328    fn the_reason_vocabulary_is_upstreams_exact_strings() {
329        // kubectl, alerting rules and a decade of runbooks match on these.
330        // A near-miss is worse than nothing: it looks right and matches
331        // nothing.
332        assert_eq!(Reason::Pulled.as_str(), "Pulled");
333        assert_eq!(Reason::BackOff.as_str(), "BackOff");
334        assert_eq!(Reason::FailedScheduling.as_str(), "FailedScheduling");
335        assert_eq!(Reason::ScalingReplicaSet.as_str(), "ScalingReplicaSet");
336        assert_eq!(Reason::SuccessfulCreate.as_str(), "SuccessfulCreate");
337        // k8s.io/kubernetes pkg/controller/volume/events.ProvisioningFailed.
338        assert_eq!(Reason::ProvisioningFailed.as_str(), "ProvisioningFailed");
339        // k8s.io/kubernetes pkg/controller/volume/events.VolumeFailedDelete.
340        assert_eq!(Reason::VolumeFailedDelete.as_str(), "VolumeFailedDelete");
341        // pkg/controller/controller_utils.go FailedCreatePodReason.
342        assert_eq!(Reason::FailedCreate.as_str(), "FailedCreate");
343        // pkg/controller/statefulset recordPodEvent("update").
344        assert_eq!(Reason::FailedUpdate.as_str(), "FailedUpdate");
345        // pkg/controller/deployment/util FailedRSCreateReason.
346        assert_eq!(
347            Reason::ReplicaSetCreateError.as_str(),
348            "ReplicaSetCreateError"
349        );
350        // pkg/controller/endpoint FailedToUpdateEndpoint.
351        assert_eq!(
352            Reason::FailedToUpdateEndpoint.as_str(),
353            "FailedToUpdateEndpoint"
354        );
355    }
356
357    #[test]
358    fn severity_is_derived_from_the_reason_never_passed_in() {
359        // A per-call-site Normal/Warning is exactly where drift appears.
360        for r in [
361            Reason::Failed,
362            Reason::Unhealthy,
363            Reason::BackOff,
364            Reason::FailedScheduling,
365            Reason::ProvisioningFailed,
366            Reason::VolumeFailedDelete,
367            Reason::FailedCreate,
368            Reason::FailedUpdate,
369            Reason::ReplicaSetCreateError,
370            Reason::FailedToUpdateEndpoint,
371            Reason::NetworkPolicyNotEnforced,
372            Reason::ResourcesNotEnforced,
373            Reason::ConfinementNotEnforced,
374            Reason::ProbeBlind,
375            Reason::WouldReject,
376        ] {
377            assert_eq!(r.severity(), Severity::Warning, "{} must warn", r.as_str());
378        }
379        for r in [Reason::Pulled, Reason::Started, Reason::Scheduled] {
380            assert_eq!(r.severity(), Severity::Normal, "{}", r.as_str());
381        }
382    }
383
384    #[test]
385    fn a_shadow_gates_would_reject_is_a_warning_under_the_gates_own_reason() {
386        // The rollout gate owns the string, and the event shares it with
387        // engenho_would_reject_total so one search finds both. A second
388        // spelling here would split them.
389        assert_eq!(
390            Reason::WouldReject.as_str(),
391            engenho_substrate::WouldReject::EVENT_REASON
392        );
393        assert_eq!(Reason::WouldReject.as_str(), "WouldReject");
394        // Something Enforce would refuse is going through: that is a
395        // Warning, never routine.
396        let v = rec(Reason::WouldReject).to_value();
397        assert_eq!(v["reason"], "WouldReject");
398        assert_eq!(v["type"], "Warning");
399    }
400
401    #[test]
402    fn a_blind_probe_is_a_warning_that_does_not_read_as_a_failed_one() {
403        // A probe that observed nothing did not observe a failure. Under
404        // `Unhealthy` it would count toward every rule that means "the
405        // workload is failing its probe".
406        assert_eq!(Reason::ProbeBlind.as_str(), "ProbeBlind");
407        assert_ne!(
408            Reason::ProbeBlind.as_str(),
409            Reason::Unhealthy.as_str(),
410            "blind and failed must be told apart on the wire"
411        );
412        let v = rec(Reason::ProbeBlind).to_value();
413        assert_eq!(v["reason"], "ProbeBlind");
414        assert_eq!(v["type"], "Warning");
415        // A blind event and a failure event at the same instant are two
416        // objects, not one overwriting the other.
417        assert_ne!(
418            rec(Reason::ProbeBlind).event_name(),
419            rec(Reason::Unhealthy).event_name()
420        );
421    }
422
423    #[test]
424    fn the_event_object_carries_every_field_kubectl_describe_reads() {
425        let v = rec(Reason::Started).to_value();
426        assert_eq!(v["kind"], "Event");
427        assert_eq!(v["reason"], "Started");
428        assert_eq!(v["type"], "Normal");
429        assert_eq!(v["message"], "because");
430        assert_eq!(v["source"]["component"], "kubelet");
431        assert_eq!(v["involvedObject"]["kind"], "Pod");
432        assert_eq!(v["involvedObject"]["name"], "nginx");
433        assert_eq!(v["involvedObject"]["uid"], "abc");
434        // kubectl sorts by these; an absent timestamp renders as <unknown>.
435        assert_eq!(v["firstTimestamp"], "2026-08-29T21:00:00Z");
436        assert_eq!(v["lastTimestamp"], "2026-08-29T21:00:00Z");
437    }
438
439    #[test]
440    fn the_event_name_is_deterministic_for_a_frozen_timestamp() {
441        // Replay-safety: a Raft follower re-applying the write must derive
442        // the identical name, so the name cannot read a clock.
443        let a = rec(Reason::Started).event_name();
444        let b = rec(Reason::Started).event_name();
445        assert_eq!(a, b);
446        // And distinct events about one object do not collide.
447        assert_ne!(a, rec(Reason::Killing).event_name());
448    }
449
450    #[test]
451    fn events_are_written_into_the_involved_objects_namespace() {
452        // kubectl -n <ns> get events must find it; a cluster-scoped
453        // fallback would hide every event for a namespaced object.
454        let k = rec(Reason::Started).key();
455        assert_eq!(k.namespace.as_deref(), Some("default"));
456        assert_eq!(k.kind, "Event");
457    }
458}
459
460// ─────────────────────────────────────────────────────────────────────
461// THE SINK — the seam between "an event happened" and "it is in the store".
462//
463// ★ WHY A TRAIT AND NOT A DIRECT STORE WRITE. Events are emitted from the
464// kubelet, the scheduler and a dozen controllers, none of which should
465// take a store dependency just to say what they observed. More
466// importantly, event recording MUST NOT be able to fail a reconcile: if
467// writing an event errored upward, a full event store would stop the
468// cluster from working. The sink's contract is therefore infallible from
469// the caller's view — it records or it drops, and it never propagates.
470//
471// ★ DROPPING IS A REAL POLICY, NOT AN OVERSIGHT. Upstream's recorder is
472// lossy under pressure for exactly this reason. A dropped event costs
473// visibility; a failed reconcile costs the workload.
474// ─────────────────────────────────────────────────────────────────────
475
476/// Where recorded events go.
477#[async_trait::async_trait]
478pub trait EventSink: Send + Sync + 'static {
479    /// Record one event. Never returns an error: see the block above.
480    async fn record(&self, event: EventRecord);
481}
482
483/// A sink that discards everything.
484///
485/// The honest default for a component with no store wired, and what makes
486/// event emission safe to add to a code path before the plumbing exists —
487/// the alternative being an `Option<Sink>` check at every call site.
488pub struct NullEventSink;
489
490#[async_trait::async_trait]
491impl EventSink for NullEventSink {
492    async fn record(&self, _event: EventRecord) {}
493}
494
495/// The sink that writes events into the store, so `kubectl describe` and
496/// `kubectl get events` can see them.
497///
498/// ★ THIS IS THE PRODUCER THE VOCABULARY WAS MISSING. `Reason`, `Severity`,
499/// `EventRecord` and `EventSink` all shipped and were fully tested against
500/// `CollectingEventSink`, and no event ever reached a cluster — which is
501/// why diagnosing a pod stuck at 149 restarts had to bypass the cluster
502/// entirely and read the container runtime directly. A cluster that cannot
503/// explain itself makes every operator an engenho developer.
504///
505/// ★ A FAILED WRITE IS DROPPED, NOT PROPAGATED, and that is the design
506/// stated in this module's header rather than an oversight here: upstream's
507/// recorder is deliberately lossy under pressure. A dropped event costs
508/// visibility; a failed reconcile costs the workload.
509pub struct StoreEventSink<S: EventStore> {
510    store: std::sync::Arc<S>,
511}
512
513impl<S: EventStore> StoreEventSink<S> {
514    #[must_use]
515    pub fn new(store: std::sync::Arc<S>) -> Self {
516        Self { store }
517    }
518}
519
520/// The one store capability an event sink needs.
521///
522/// A narrow trait rather than a dependency on the concrete mesh: this crate
523/// already sits below the assembly layer, and a sink that could do anything
524/// to the store is a sink that will eventually be asked to.
525#[async_trait::async_trait]
526pub trait EventStore: Send + Sync + 'static {
527    /// Write one event object. Errors are the sink's to swallow.
528    async fn put_event(&self, key: ResourceKey, value: ResourceValue) -> Result<(), String>;
529}
530
531#[async_trait::async_trait]
532impl<S: EventStore> EventSink for StoreEventSink<S> {
533    async fn record(&self, event: EventRecord) {
534        if let Err(e) = self.store.put_event(event.key(), event.to_value()).await {
535            // Logged, never returned: see above.
536            tracing::debug!(
537                reason = event.reason.as_str(),
538                object = %event.involved.name,
539                error = %e,
540                "event write dropped"
541            );
542        }
543    }
544}
545
546/// A sink that collects into memory, for tests.
547#[derive(Default)]
548pub struct CollectingEventSink {
549    events: std::sync::Mutex<Vec<EventRecord>>,
550}
551
552impl CollectingEventSink {
553    #[must_use]
554    pub fn new() -> Self {
555        Self::default()
556    }
557
558    /// Every event recorded so far, in order.
559    #[must_use]
560    pub fn drain(&self) -> Vec<EventRecord> {
561        std::mem::take(&mut *self.events.lock().expect("event sink poisoned"))
562    }
563
564    /// The reasons recorded so far — the assertion most tests actually want.
565    #[must_use]
566    pub fn reasons(&self) -> Vec<Reason> {
567        self.events
568            .lock()
569            .expect("event sink poisoned")
570            .iter()
571            .map(|e| e.reason)
572            .collect()
573    }
574}
575
576#[async_trait::async_trait]
577impl EventSink for CollectingEventSink {
578    async fn record(&self, event: EventRecord) {
579        self.events.lock().expect("event sink poisoned").push(event);
580    }
581}
582
583/// Helper: record an event about a pod.
584///
585/// Exists so a call site names only what it observed — the object, the
586/// reason, the message — and cannot get the involvedObject shape wrong.
587pub async fn record_pod_event(
588    sink: &dyn EventSink,
589    namespace: &str,
590    pod: &str,
591    uid: Option<&str>,
592    reason: Reason,
593    message: impl Into<String>,
594    component: &str,
595    timestamp: &str,
596) {
597    sink.record(EventRecord {
598        involved: InvolvedObject {
599            api_version: "v1".to_string(),
600            kind: "Pod".to_string(),
601            namespace: Some(namespace.to_string()),
602            name: pod.to_string(),
603            uid: uid.map(ToString::to_string),
604        },
605        reason,
606        message: message.into(),
607        component: component.to_string(),
608        timestamp: timestamp.to_string(),
609    })
610    .await;
611}
612
613#[cfg(test)]
614mod sink_tests {
615    use super::*;
616
617    #[tokio::test]
618    async fn the_collecting_sink_preserves_order() {
619        let sink = CollectingEventSink::new();
620        for r in [Reason::Pulled, Reason::Created, Reason::Started] {
621            record_pod_event(
622                &sink,
623                "default",
624                "nginx",
625                Some("u"),
626                r,
627                "m",
628                "kubelet",
629                "2026-08-29T21:00:00Z",
630            )
631            .await;
632        }
633        // Order matters: kubectl describe renders events chronologically,
634        // and a reordered lifecycle reads as a different failure.
635        assert_eq!(
636            sink.reasons(),
637            vec![Reason::Pulled, Reason::Created, Reason::Started]
638        );
639    }
640
641    #[tokio::test]
642    async fn the_null_sink_makes_emission_safe_before_the_plumbing_exists() {
643        // The alternative is an Option<Sink> check at every call site,
644        // which is where a forgotten branch silently stops recording.
645        let sink = NullEventSink;
646        record_pod_event(
647            &sink,
648            "default",
649            "nginx",
650            None,
651            Reason::Failed,
652            "m",
653            "kubelet",
654            "2026-08-29T21:00:00Z",
655        )
656        .await;
657        // Nothing to assert but the absence of a panic — which IS the
658        // contract: recording must never be able to fail a reconcile.
659    }
660
661    #[tokio::test]
662    async fn the_helper_cannot_get_the_involved_object_shape_wrong() {
663        let sink = CollectingEventSink::new();
664        record_pod_event(
665            &sink,
666            "kube-system",
667            "coredns",
668            Some("abc"),
669            Reason::Unhealthy,
670            "probe failed",
671            "kubelet",
672            "2026-08-29T21:00:00Z",
673        )
674        .await;
675        let e = &sink.drain()[0];
676        assert_eq!(e.involved.kind, "Pod");
677        assert_eq!(e.involved.api_version, "v1");
678        assert_eq!(e.involved.namespace.as_deref(), Some("kube-system"));
679        assert_eq!(e.involved.name, "coredns");
680        assert_eq!(e.involved.uid.as_deref(), Some("abc"));
681        // And the severity still derives from the reason, not the caller.
682        assert_eq!(e.reason.severity(), Severity::Warning);
683    }
684}