Skip to main content

engenho_controllers/
gc.rs

1//! `GcController` — orphan-reference garbage collector.
2//!
3//! K8s rule: a dependent is deleted when NONE of its
4//! `metadata.ownerReferences` names a solid owner (kube-controller-manager's
5//! garbage collector). References to owners that are gone are removed from a
6//! dependent that still has a live one.
7//!
8//! ## The owner is resolved from the ownerReference, never from a list
9//!
10//! This controller used to build a set of live UIDs by listing TWO
11//! hardcoded kinds — Deployment and `ReplicaSet` — and delete any Pod whose
12//! controller UID was not in it. A `StatefulSet`'s Pod is therefore an
13//! "orphan" on every single tick.
14//!
15//! Measured on ryn 2026-09-18: `pitr-lab/mysql-0` (owned by the
16//! `StatefulSet` `pitr-lab/mysql`) was deleted ~10 times per SECOND for
17//! days. The statefulset controller recreated it, the scheduler bound it,
18//! gc deleted it, forever — three controllers at full tilt, `changed=1`
19//! on every tick of each, and 14,306 log lines about one pod. The churn
20//! was also the event storm that overflowed the kubelet's watch buffer,
21//! which is what exposed the driver defect fixed in `watch_driver.rs`.
22//!
23//! The old doc comment called the fix "more entries in the scan list".
24//! That is the wrong destination: the next owner kind would have re-armed
25//! the same trap. Upstream does not keep a list — `garbagecollector`
26//! resolves an ownerReference through the `RESTMapper` and does a live GET
27//! of THAT owner, and it deletes only against a confirmed-absent owner
28//! (`absentOwnerCache`). So do we, and the hardcoded enumeration is gone
29//! rather than extended.
30//!
31//! **Fail closed.** Not knowing an owner's kind is not evidence the owner
32//! is missing. A dependent is deleted only when a positive observation
33//! says so: the owner is absent at its own coordinates, or an object with
34//! that name exists under a DIFFERENT uid (the owner was recreated, so
35//! this dependent belongs to a dead generation).
36//!
37//! ## Every owner reference, classified (I19 GC oracle)
38//!
39//! Checked row by row against upstream's garbage collector (v1.34.0,
40//! `tests/oracle_gc.rs`). Three things the controlling-owner-only reading
41//! got wrong, each a way to delete a dependent upstream keeps:
42//!
43//! - **Only the controller was consulted.** Upstream classifies EVERY
44//!   ownerReference and deletes only when none is solid; with some solid
45//!   and some dangling it patches the dangling ones out and keeps the
46//!   object. A pod whose controller is gone but whose other owner lives is
47//!   kept now, and the dead reference is removed.
48//! - **An unserved apiVersion read as Absent.** `extensions/v1beta1`
49//!   Deployment for an owner stored as `apps/v1` was looked up at a key
50//!   nothing is written under, found missing, and the pod deleted.
51//!   Resolution goes through the served catalog ([`ServedKinds`]), pinned
52//!   to the reference's exact group/version; a miss is [`Unresolvable`] and
53//!   the dependent is left alone.
54//! - **The foreground finalizer was ignored.** An owner being deleted with
55//!   `foregroundDeletion` waits for its dependents; it is not solid.
56//!
57//! The DEPENDENT side is still a scan of two kinds (Pods, `ReplicaSets`).
58//! Widening it to every served kind is refused (`IMPROVEMENT-PLAN` §9): it
59//! would put every kind's objects through this path on every tick.
60
61mod collect;
62mod served;
63
64use std::sync::Arc;
65
66use async_trait::async_trait;
67use engenho_store::{
68    ResourceKey, StoreMesh,
69    command::{Reason, ResourceCommand},
70    revision::Revision,
71};
72use serde_json::{Value, json};
73use tracing::debug;
74
75pub use collect::{
76    Candidate, Classification, Classified, Collected, Decision, FOREGROUND_DELETION, GcEnv,
77    OwnerState, classify, collect, owner_references, owner_state,
78};
79pub use served::{ServedKind, ServedKinds, Unresolvable};
80
81use crate::controller::{Controller, ReconcileOutcome, ReconcileReport};
82use crate::effect::Effect;
83use crate::error::ControllerError;
84use crate::event_retention::{EventRetention, expire_events};
85use crate::reads::{DeclaresReads, Reads};
86
87/// The dependent kinds gc scans. Owners are resolved from each reference
88/// through the served catalog, so this list does not bound which OWNERS
89/// are recognised; it bounds which DEPENDENTS are collected.
90const DEPENDENT_KINDS: [(&str, &str, &str); 2] = [("", "v1", "Pod"), ("apps", "v1", "ReplicaSet")];
91
92pub struct GcController {
93    store: Arc<StoreMesh>,
94    namespace: Option<String>,
95}
96
97impl GcController {
98    #[must_use]
99    pub fn new(store: Arc<StoreMesh>, namespace: Option<String>) -> Self {
100        Self { store, namespace }
101    }
102
103    /// Every kind served right now: the compiled-in catalog plus each
104    /// stored CRD's served versions.
105    async fn served(&self) -> ServedKinds {
106        let crds = self
107            .store
108            .list(
109                "apiextensions.k8s.io",
110                "v1",
111                "CustomResourceDefinition",
112                None,
113            )
114            .await;
115        ServedKinds::builtin().with_crds(crds.iter().map(|(_, crd)| crd))
116    }
117}
118
119/// [`GcEnv`] over the store. Every write carries the revision it is pinned
120/// to, and a delete carries its clock (T3.6).
121struct StoreEnv<'a> {
122    store: &'a StoreMesh,
123}
124
125#[async_trait]
126impl GcEnv for StoreEnv<'_> {
127    async fn get(&self, key: &ResourceKey) -> Option<Value> {
128        self.store.get(key).await
129    }
130
131    async fn delete(&self, key: &ResourceKey, pinned: Revision) -> Result<Effect, ControllerError> {
132        let applied = self
133            .store
134            .propose(ResourceCommand::delete_at(
135                key.clone(),
136                Some(pinned),
137                Reason::GarbageCollector,
138                Some(engenho_types::time::now_rfc3339_utc()),
139            ))
140            .await?;
141        Ok(Effect::of(applied.op))
142    }
143
144    async fn replace_owner_references(
145        &self,
146        key: &ResourceKey,
147        references: Vec<Value>,
148        pinned: Revision,
149    ) -> Result<Effect, ControllerError> {
150        // An RFC 7396 merge of a list replaces the list: upstream's JSON
151        // merge-patch form of this write, with its resourceVersion
152        // precondition.
153        let applied = self
154            .store
155            .propose(ResourceCommand::patch_cas(
156                key.clone(),
157                json!({"metadata": {"ownerReferences": references}}),
158                Some(pinned),
159                Reason::GarbageCollector,
160            ))
161            .await?;
162        Ok(Effect::of(applied.op))
163    }
164}
165
166/// Every kind: it looks an owner up by whatever kind the dependent's
167/// owner reference names, which it cannot know ahead of time, so any event
168/// may be the deletion that orphans something.
169impl DeclaresReads for GcController {
170    fn reads(&self) -> Reads {
171        Reads::every()
172    }
173}
174
175#[async_trait]
176impl Controller for GcController {
177    fn name(&self) -> &'static str {
178        "gc"
179    }
180
181    async fn tick(&self) -> Result<ReconcileOutcome, ControllerError> {
182        let mut report = ReconcileReport::default();
183        let ns = self.namespace.as_deref();
184        let served = self.served().await;
185        let env = StoreEnv { store: &self.store };
186        expire_events(&self.store, ns, EventRetention::default(), &mut report).await?;
187
188        for (group, version, kind) in DEPENDENT_KINDS {
189            let dependents = self.store.list(group, version, kind, ns).await;
190            report.objects_examined += dependents.len();
191            for (key, value) in dependents {
192                let Some(candidate) = Candidate::listed(key, &value) else {
193                    continue;
194                };
195                match collect(&env, &served, &candidate).await? {
196                    Collected::Deleted(effect) => {
197                        debug!(dependent = %candidate.key.label(), "deleted: no owner is solid");
198                        report.record(effect);
199                    }
200                    Collected::ReferencesRemoved { uids, effect } => {
201                        debug!(
202                            dependent = %candidate.key.label(),
203                            removed = ?uids,
204                            "removed owner references that are not solid"
205                        );
206                        report.record(effect);
207                    }
208                    Collected::Unresolvable(why) => {
209                        debug!(dependent = %candidate.key.label(), %why, "left alone");
210                    }
211                    Collected::BeingDeleted
212                    | Collected::ItemGone
213                    | Collected::NoOwners
214                    | Collected::Unpinned
215                    | Collected::Kept => {}
216                }
217            }
218        }
219        Ok(report.into())
220    }
221}
222
223#[cfg(test)]
224mod tests {
225    use serde_json::json;
226
227    use crate::owner::{OwnerReference, controlling_owner, set_owner_reference};
228
229    fn owner_ref(uid: &str) -> OwnerReference {
230        OwnerReference {
231            api_version: "apps/v1".into(),
232            kind: "ReplicaSet".into(),
233            name: "n".into(),
234            uid: uid.into(),
235            controller: true,
236            block_owner_deletion: true,
237        }
238    }
239
240    #[test]
241    fn owner_uid_returns_controller_uid() {
242        let mut pod = json!({"metadata": {"name": "p"}});
243        set_owner_reference(&mut pod, owner_ref("uid-123")).unwrap();
244        assert_eq!(
245            controlling_owner(&pod).map(|o| o.uid),
246            Some("uid-123".into())
247        );
248    }
249
250    #[test]
251    fn owner_uid_none_without_owner_ref() {
252        let pod = json!({"metadata": {"name": "p"}});
253        assert!(controlling_owner(&pod).map(|o| o.uid).is_none());
254    }
255}