Skip to main content

engenho_controllers/
pod_template.rs

1//! Pod-template identity — upstream's `EqualIgnoreHash`.
2//!
3//! A Deployment finds the `ReplicaSet` that runs its template by COMPARING
4//! the two templates, not by comparing a hash of one against a label on the
5//! other. Upstream (`deploymentutil.FindNewReplicaSet`) does exactly this:
6//! it deep-copies both `PodTemplateSpec`s, deletes the `pod-template-hash`
7//! label from each, and runs `apiequality.Semantic.DeepEqual`. The hash is
8//! only ever used to NAME a new `ReplicaSet`.
9//!
10//! ★ WHY NOT THE HASH. A hash over the raw template bytes changes whenever
11//! the bytes change, including when the template means the same thing: a
12//! `labels: null` the apiserver starts dropping (T4.4), an `env: []` a
13//! client starts omitting, a change to the hash function itself. Each of
14//! those, under a hash matcher, finds no `ReplicaSet` for EVERY Deployment
15//! at once, creates a new one for each, and scales every running one to
16//! zero — a cluster-wide rollout nobody asked for. Under this matcher none
17//! of them can: two templates that decode to the same `PodTemplateSpec`
18//! compare equal, whatever their bytes and whatever their hash.
19//!
20//! ★ WHAT "THE SAME" MEANS HERE — a SUBSET of upstream's equality, never a
21//! superset. Every rule below is one upstream's typed decode + `Semantic`
22//! comparison already applies, so this module never calls two templates
23//! equal that upstream would call different (a missed rollout is worse
24//! than a spurious one):
25//!
26//! * the template's `pod-template-hash` label is ignored (`EqualIgnoreHash`);
27//! * a STRUCT field whose value is `null` is absent — `encoding/json`
28//!   decodes a JSON `null` into a nil pointer/map/slice, or leaves any other
29//!   field at its zero value, which is what absence does;
30//! * a STRUCT field whose value is `[]` is absent — every array in a
31//!   `PodTemplateSpec` decodes to a Go slice, and `Semantic.DeepEqual`
32//!   treats a nil slice and an empty one as equal;
33//! * a MAP field (the closed list [`MAP_FIELDS`]) whose value is `{}` is
34//!   absent — nil and empty maps are equal under the same rule — and so is
35//!   a `metadata` that is `{}`: both `ObjectMeta`s a pod template can carry
36//!   are embedded by value, never by pointer.
37//!
38//! The ENTRIES of a map are kept verbatim: `labels: {"a": null}` decodes to
39//! `{"a": ""}` upstream, which is NOT `{}`. An empty object anywhere else is
40//! kept too: most of those are pointers to a struct (`emptyDir: {}`,
41//! `securityContext: {}`), where `{}` and absent are different values
42//! upstream — `emptyDir: {}` is the volume's whole source.
43//!
44//! Tier, stated plainly: SOUND but INCOMPLETE, and the soundness rests on
45//! one list. Some pairs upstream calls equal still compare unequal here —
46//! `hostNetwork: false` vs absent, a `Quantity` of `"1"` vs `"1000m"`, a
47//! defaulted vs an undefaulted template. Such a pair rolls out, exactly as
48//! it did under the hash, so nothing regresses. The defaulted-vs-undefaulted
49//! case is the one that matters: it is closed only when the `apps/v1`
50//! template-defaulting arm lands AND the same pod-spec defaulter runs inside
51//! [`NormalizedTemplate::of`] on both sides, because a stored `ReplicaSet`
52//! template is never re-defaulted. A map field missing from [`MAP_FIELDS`]
53//! would have its `null` ENTRIES dropped — a false "equal" only for a map
54//! value that is `null`, which T4.4 rejects at the border (422).
55
56use std::fmt;
57use std::io;
58
59use serde_json::{Map, Value};
60
61/// The label a `ReplicaSet` carries naming the hash of the template it was
62/// created for. Upstream's `apps.DefaultDeploymentUniqueLabelKey`.
63pub const POD_TEMPLATE_HASH_LABEL: &str = "pod-template-hash";
64
65/// A pod template reduced to the form two templates are compared in.
66///
67/// The only constructor is [`NormalizedTemplate::of`], so a comparison of
68/// two `NormalizedTemplate`s is always a comparison of normalized forms —
69/// there is no way to hand this type raw template bytes.
70#[derive(Debug, Clone, PartialEq, Eq)]
71pub struct NormalizedTemplate(Value);
72
73impl NormalizedTemplate {
74    /// Normalize `template` (a `PodTemplateSpec`: `spec.template` of a
75    /// Deployment or a `ReplicaSet`). Total: every JSON value has a
76    /// normalized form, and a template that is not an object is compared
77    /// as it stands.
78    #[must_use]
79    pub fn of(template: &Value) -> Self {
80        let mut t = template.clone();
81        if let Some(labels) = t
82            .get_mut("metadata")
83            .and_then(|m| m.get_mut("labels"))
84            .and_then(Value::as_object_mut)
85        {
86            labels.remove(POD_TEMPLATE_HASH_LABEL);
87        }
88        normalize(None, &mut t);
89        Self(t)
90    }
91
92    /// The `spec.template` of `owner` (a Deployment or a `ReplicaSet`),
93    /// normalized. `None` when it declares no template — absent or `null`,
94    /// which are the same thing.
95    #[must_use]
96    pub fn of_spec_template(owner: &Value) -> Option<Self> {
97        owner
98            .get("spec")
99            .and_then(|s| s.get("template"))
100            .filter(|t| !t.is_null())
101            .map(Self::of)
102    }
103
104    /// The hash that NAMES a `ReplicaSet` created for this template (and
105    /// fills its `pod-template-hash` label). It identifies nothing: two
106    /// templates are the same when they compare equal, never because their
107    /// hashes do. Computed over the normalized form, so equal templates
108    /// also get equal names.
109    ///
110    /// `None` only if the normalized value fails to serialize, which a
111    /// `serde_json::Value` with string keys does not do.
112    #[must_use]
113    pub fn naming_hash(&self) -> Option<TemplateHash> {
114        let mut fnv = Fnv1a::new();
115        serde_json::to_writer(&mut fnv, &self.0).ok()?;
116        Some(TemplateHash(fnv.0))
117    }
118}
119
120/// The name-only hash of a template: FNV-1a over the normalized template's
121/// compact JSON, rendered as its top 40 bits in 10 lowercase hex digits.
122#[derive(Debug, Clone, Copy, PartialEq, Eq)]
123pub struct TemplateHash(u64);
124
125impl fmt::Display for TemplateHash {
126    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127        // Top 40 bits = the first 10 of the 16 zero-padded hex digits the
128        // name has always carried.
129        write!(f, "{:010x}", self.0 >> 24)
130    }
131}
132
133/// FNV-1a, 64-bit, fed as a byte sink so the JSON never has to be
134/// materialized to be hashed.
135struct Fnv1a(u64);
136
137impl Fnv1a {
138    const OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
139    const PRIME: u64 = 0x0100_0000_01b3;
140
141    fn new() -> Self {
142        Self(Self::OFFSET)
143    }
144}
145
146impl io::Write for Fnv1a {
147    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
148        for b in buf {
149            self.0 ^= u64::from(*b);
150            self.0 = self.0.wrapping_mul(Self::PRIME);
151        }
152        Ok(buf.len())
153    }
154
155    fn flush(&mut self) -> io::Result<()> {
156        Ok(())
157    }
158}
159
160/// The fields of a `PodTemplateSpec` that are Go MAPS rather than structs,
161/// by name — every name that holds a map anywhere in the tree, and no name
162/// that holds a struct object anywhere in it: `ObjectMeta` (the template's
163/// and an ephemeral volume claim template's) `labels`/`annotations`;
164/// `PodSpec.nodeSelector` and `overhead`; `ResourceRequirements` (a
165/// container's, the pod's, a claim template's) `limits`/`requests`;
166/// `LabelSelector.matchLabels` (affinity terms, spread constraints, claim
167/// selectors); `CSIVolumeSource.volumeAttributes`; `FlexVolumeSource.options`
168/// (`PodDNSConfig.options` is an array, never an object).
169pub const MAP_FIELDS: &[&str] = &[
170    "labels",
171    "annotations",
172    "nodeSelector",
173    "overhead",
174    "limits",
175    "requests",
176    "matchLabels",
177    "volumeAttributes",
178    "options",
179];
180
181fn is_map_field(field: &str) -> bool {
182    MAP_FIELDS.contains(&field)
183}
184
185/// Normalize `v`, the value of `field` (`None` for the template root and
186/// for array elements, which are structs or scalars). A map's entries are
187/// kept verbatim; a struct loses every field [`is_absent_field`] names, at
188/// every depth. Array elements are normalized but never removed: a slice's
189/// length and order are part of its value.
190fn normalize(field: Option<&str>, v: &mut Value) {
191    match v {
192        Value::Object(_) if field.is_some_and(is_map_field) => {}
193        Value::Object(fields) => fields.retain(|name, member| {
194            normalize(Some(name.as_str()), member);
195            !is_absent_field(name, member)
196        }),
197        Value::Array(items) => items.iter_mut().for_each(|item| normalize(None, item)),
198        _ => {}
199    }
200}
201
202/// A struct field whose value decodes to what its absence decodes to, and
203/// compares equal to it under `Semantic.DeepEqual`.
204fn is_absent_field(name: &str, v: &Value) -> bool {
205    v.is_null()
206        || v.as_array().is_some_and(Vec::is_empty)
207        || (v.as_object().is_some_and(Map::is_empty) && (is_map_field(name) || name == "metadata"))
208}
209
210#[cfg(test)]
211mod tests {
212    use super::*;
213    use serde_json::json;
214
215    fn web() -> Value {
216        json!({
217            "metadata": {"labels": {"app": "web"}},
218            "spec": {
219                "containers": [{"name": "c", "image": "web:1"}]
220            }
221        })
222    }
223
224    fn same(a: &Value, b: &Value) -> bool {
225        NormalizedTemplate::of(a) == NormalizedTemplate::of(b)
226    }
227
228    #[test]
229    fn the_pod_template_hash_label_is_ignored() {
230        let mut hashed = web();
231        hashed["metadata"]["labels"]["pod-template-hash"] = json!("0123456789");
232        assert!(same(&web(), &hashed));
233    }
234
235    #[test]
236    fn a_label_set_holding_only_the_hash_is_no_label_set() {
237        let bare = json!({"spec": {"containers": [{"name": "c"}]}});
238        let hashed = json!({
239            "metadata": {"labels": {"pod-template-hash": "0123456789"}},
240            "spec": {"containers": [{"name": "c"}]}
241        });
242        assert!(same(&bare, &hashed));
243    }
244
245    #[test]
246    fn a_null_member_is_an_absent_member_at_any_depth() {
247        let mut nulls = web();
248        nulls["metadata"]["annotations"] = Value::Null;
249        nulls["metadata"]["creationTimestamp"] = Value::Null;
250        nulls["spec"]["nodeSelector"] = Value::Null;
251        nulls["spec"]["containers"][0]["resources"] = Value::Null;
252        assert!(same(&web(), &nulls));
253    }
254
255    #[test]
256    fn an_empty_list_is_an_absent_list_at_any_depth() {
257        let mut empties = web();
258        empties["spec"]["volumes"] = json!([]);
259        empties["spec"]["containers"][0]["env"] = json!([]);
260        empties["spec"]["containers"][0]["args"] = json!([]);
261        assert!(same(&web(), &empties));
262    }
263
264    #[test]
265    fn empty_template_labels_annotations_and_metadata_are_absent() {
266        let bare = json!({"spec": {"containers": [{"name": "c"}]}});
267        let empty_maps = json!({
268            "metadata": {"labels": {}, "annotations": {}},
269            "spec": {"containers": [{"name": "c"}]}
270        });
271        let empty_meta = json!({"metadata": {}, "spec": {"containers": [{"name": "c"}]}});
272        assert!(same(&bare, &empty_maps));
273        assert!(same(&bare, &empty_meta));
274    }
275
276    #[test]
277    fn an_empty_map_field_is_absent_at_any_depth() {
278        let mut empties = web();
279        empties["spec"]["nodeSelector"] = json!({});
280        empties["spec"]["containers"][0]["resources"] = json!({"limits": {}, "requests": {}});
281        let mut bare_resources = web();
282        bare_resources["spec"]["containers"][0]["resources"] = json!({});
283        assert!(same(&bare_resources, &empties));
284    }
285
286    #[test]
287    fn a_null_map_entry_is_an_empty_string_not_an_absent_key() {
288        // `map[string]string` decodes `{"tier": null}` to `{"tier": ""}` —
289        // a label that exists, with an empty value. Dropping it would
290        // call a relabel "no change".
291        let mut null_entry = web();
292        null_entry["metadata"]["labels"]["tier"] = Value::Null;
293        assert!(!same(&web(), &null_entry));
294
295        let mut null_selector = web();
296        null_selector["spec"]["nodeSelector"] = json!({"disk": null});
297        assert!(!same(&web(), &null_selector));
298    }
299
300    #[test]
301    fn a_changed_image_is_a_different_template() {
302        let mut v2 = web();
303        v2["spec"]["containers"][0]["image"] = json!("web:2");
304        assert!(!same(&web(), &v2));
305    }
306
307    #[test]
308    fn a_restart_annotation_is_a_different_template() {
309        // `kubectl rollout restart` works by exactly this edit.
310        let mut restarted = web();
311        restarted["metadata"]["annotations"] =
312            json!({"kubectl.kubernetes.io/restartedAt": "2026-09-19T00:00:00Z"});
313        assert!(!same(&web(), &restarted));
314    }
315
316    #[test]
317    fn a_label_other_than_the_hash_is_part_of_the_template() {
318        let mut relabelled = web();
319        relabelled["metadata"]["labels"]["tier"] = json!("front");
320        assert!(!same(&web(), &relabelled));
321    }
322
323    #[test]
324    fn an_empty_object_that_is_a_pointer_upstream_is_kept() {
325        // `emptyDir: {}` IS the volume's source: without it the volume has
326        // none. Collapsing `{}` to absent here would hide a real edit.
327        let mut with_source = web();
328        with_source["spec"]["volumes"] = json!([{"name": "scratch", "emptyDir": {}}]);
329        let mut without_source = web();
330        without_source["spec"]["volumes"] = json!([{"name": "scratch"}]);
331        assert!(!same(&with_source, &without_source));
332
333        let mut sc = web();
334        sc["spec"]["securityContext"] = json!({});
335        assert!(!same(&web(), &sc));
336    }
337
338    #[test]
339    fn list_order_and_length_are_part_of_the_template() {
340        let two = json!({"spec": {"containers": [{"name": "a"}, {"name": "b"}]}});
341        let swapped = json!({"spec": {"containers": [{"name": "b"}, {"name": "a"}]}});
342        let with_null = json!({"spec": {"containers": [{"name": "a"}, {"name": "b"}, null]}});
343        assert!(!same(&two, &swapped));
344        assert!(!same(&two, &with_null));
345    }
346
347    #[test]
348    fn normalizing_twice_changes_nothing() {
349        let messy = json!({
350            "metadata": {"labels": {"pod-template-hash": "x"}, "annotations": null},
351            "spec": {"containers": [{"name": "c", "env": [], "resources": null}]}
352        });
353        let once = NormalizedTemplate::of(&messy);
354        assert_eq!(NormalizedTemplate::of(&once.0), once);
355    }
356
357    #[test]
358    fn of_spec_template_reads_absent_and_null_as_no_template() {
359        assert!(NormalizedTemplate::of_spec_template(&json!({"spec": {}})).is_none());
360        assert!(
361            NormalizedTemplate::of_spec_template(&json!({"spec": {"template": null}})).is_none()
362        );
363        assert!(
364            NormalizedTemplate::of_spec_template(&json!({"spec": {"template": web()}})).is_some()
365        );
366    }
367
368    #[test]
369    fn the_naming_hash_is_ten_hex_digits_and_follows_the_template() {
370        let h1 = NormalizedTemplate::of(&web())
371            .naming_hash()
372            .map(|h| h.to_string());
373        let mut v2 = web();
374        v2["spec"]["containers"][0]["image"] = json!("web:2");
375        let h2 = NormalizedTemplate::of(&v2)
376            .naming_hash()
377            .map(|h| h.to_string());
378        let h1 = h1.expect("hashable");
379        assert_eq!(h1.len(), 10);
380        assert!(
381            h1.chars()
382                .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase())
383        );
384        assert_ne!(Some(h1), h2);
385    }
386
387    #[test]
388    fn equal_templates_get_equal_names() {
389        let mut nulls = web();
390        nulls["metadata"]["annotations"] = Value::Null;
391        nulls["spec"]["volumes"] = json!([]);
392        assert_eq!(
393            NormalizedTemplate::of(&web()).naming_hash(),
394            NormalizedTemplate::of(&nulls).naming_hash()
395        );
396    }
397
398    #[test]
399    fn the_naming_hash_keeps_the_names_it_always_gave() {
400        // FNV-1a over the compact JSON, top 10 of 16 hex digits — the
401        // rendering the ReplicaSet names have always had, so a template the
402        // normalization leaves untouched keeps its old name.
403        let t = json!({"spec": {}});
404        let bytes = serde_json::to_vec(&t).expect("serializable");
405        let mut h: u64 = 0xcbf2_9ce4_8422_2325;
406        for b in &bytes {
407            h ^= u64::from(*b);
408            h = h.wrapping_mul(0x0100_0000_01b3);
409        }
410        let old: String = format!("{h:016x}").chars().take(10).collect();
411        assert_eq!(
412            NormalizedTemplate::of(&t)
413                .naming_hash()
414                .map(|h| h.to_string()),
415            Some(old)
416        );
417    }
418}