tatara_process/pool.rs
1//! `EphemeralPool` CRD — a population of warm, pre-attested ephemeral
2//! Processes that get *allocated* to requestors (e.g., a GitHub PR
3//! flow) on demand and *returned* (per a typed policy) when the
4//! requestor releases them.
5//!
6//! Compounding move: the pool is a population manager **over the
7//! existing Process algebra**, not a parallel runtime. A pool member
8//! is just a `Process` with `Lifetime::Permanent` while in the free
9//! list; allocation is "the operator (the pool reconciler) flips
10//! that Process's lifetime slot to Ephemeral with the requestor's
11//! TTL." Zero new compute primitive.
12//!
13//! Topology:
14//!
15//! ```text
16//! EphemeralPool (this CRD)
17//! ├── PoolSpec (desired_size, template (EphemeralSpec), return_policy, selector)
18//! ├── PoolStatus (phase, free / allocated / spawning / returning counts, members)
19//! └── owns N Processes via ownerReferences (one per pool slot)
20//!
21//! EphemeralAllocation (see allocation.rs)
22//! ├── AllocationSpec (pool_ref, requestor, requested_at, lifetime override)
23//! └── AllocationStatus (phase, assigned_process_ref, allocated_at, expires_at)
24//! ```
25
26use chrono::{DateTime, Utc};
27use kube::CustomResource;
28use schemars::JsonSchema;
29use serde::{Deserialize, Serialize};
30
31use crate::ephemeral::EphemeralSpec;
32
33/// `EphemeralPool` CRD spec — typed pool of warm Processes.
34///
35/// ```yaml
36/// apiVersion: tatara.pleme.io/v1alpha1
37/// kind: EphemeralPool
38/// metadata:
39/// name: attest-pool
40/// namespace: ephemeral-pools
41/// spec:
42/// desiredSize: 3
43/// minSize: 1
44/// maxSize: 5
45/// returnPolicy: Reset
46/// selector:
47/// repos: ["pleme-io/demo-*"]
48/// branches: ["main", "release-*"]
49/// prLabels: ["needs-ephemeral"]
50/// template:
51/// aplicacao:
52/// chartRef: "oci://ghcr.io/pleme-io/charts/lareira-demo-app"
53/// version: "0.5.5"
54/// profile: "all-in-one"
55/// …
56/// ttl: "2h"
57/// teardown: OnAttested
58/// postconditions: [ … ]
59/// ```
60#[derive(CustomResource, Clone, Debug, Deserialize, Serialize, JsonSchema)]
61#[kube(
62 group = "tatara.pleme.io",
63 version = "v1alpha1",
64 kind = "EphemeralPool",
65 plural = "ephemeralpools",
66 shortname = "epool",
67 namespaced,
68 status = "PoolStatus",
69 printcolumn = r#"{"name":"Desired","type":"integer","jsonPath":".spec.desiredSize"}"#,
70 printcolumn = r#"{"name":"Ready","type":"integer","jsonPath":".status.readyCount"}"#,
71 printcolumn = r#"{"name":"Allocated","type":"integer","jsonPath":".status.allocatedCount"}"#,
72 printcolumn = r#"{"name":"Phase","type":"string","jsonPath":".status.phase"}"#,
73 printcolumn = r#"{"name":"Age","type":"date","jsonPath":".metadata.creationTimestamp"}"#
74)]
75#[serde(rename_all = "camelCase")]
76pub struct PoolSpec {
77 /// Target number of warm Processes the pool maintains in `Free`
78 /// state (sum of Free + Spawning targets `desired_size`).
79 pub desired_size: u32,
80
81 /// Hard floor on the free count. The reconciler refuses to scale
82 /// below this even on cost-pressure signals. Default = 0.
83 #[serde(default)]
84 pub min_size: u32,
85
86 /// Hard ceiling on total pool members (free + allocated + spawning).
87 /// `0` = no cap. Default = 0.
88 #[serde(default)]
89 pub max_size: u32,
90
91 /// What to do when an allocation releases.
92 #[serde(default)]
93 pub return_policy: ReturnPolicy,
94
95 /// Routing selector — which allocation requests this pool serves.
96 /// The reconciler matches incoming `EphemeralAllocation` CRs
97 /// against this selector (most-specific wins across pools sharing
98 /// a namespace).
99 #[serde(default)]
100 pub selector: PoolSelector,
101
102 /// Template for each pool member — a typed `EphemeralSpec` that
103 /// the reconciler lowers to `ProcessSpec` and instantiates.
104 /// While in the free list each member's lifetime is overridden
105 /// to `Permanent`; allocation flips it back to `Ephemeral` with
106 /// the requestor's TTL.
107 pub template: EphemeralSpec,
108
109 /// How long a pool member may sit in `Free` before the reconciler
110 /// recycles it (humantime). Defends against drift / stale state.
111 /// Default `"24h"`.
112 #[serde(default = "default_free_ttl")]
113 pub free_ttl: String,
114
115 /// Max time the reconciler allows a single allocation to hold a
116 /// member before forcibly returning it (humantime). Hard cap
117 /// independent of the allocation's own TTL. Default `"4h"`.
118 #[serde(default = "default_max_allocation_ttl")]
119 pub max_allocation_ttl: String,
120
121 /// **R5 desired-count loop** — when set non-zero, the pool
122 /// reconciler maintains exactly this many *healthy* (Running or
123 /// Attested) Processes regardless of allocation pressure. Drives
124 /// the "always seeking stability" property: failed members are
125 /// replaced per `replacement_policy`. `0` keeps the legacy
126 /// allocation-driven sizing (desired = floor of free + allocated).
127 ///
128 /// Operator usage: `desired: 5` means "always have 5 of these
129 /// running"; failures auto-replace.
130 #[serde(default)]
131 pub desired: u32,
132
133 /// **R5** — what the pool reconciler does when a member reaches
134 /// `Failed` phase.
135 #[serde(default)]
136 pub replacement_policy: ReplacementPolicy,
137
138 /// **R5** — when true, exactly one healthy member of the pool
139 /// holds the unprefixed-form DNS hostnames declared in
140 /// `template.routing` at any moment. The claim arbiter (see
141 /// `tatara-reconciler::claim`) transfers atomically when the
142 /// holder fails.
143 #[serde(default)]
144 pub stable_name_claim: bool,
145}
146
147impl PoolSpec {
148 /// Humantime-parsed [`std::time::Duration`] projection of the
149 /// [`Self::free_ttl`] slot — the ONE-line collapse of the paired
150 /// `humantime::parse_duration(&<pool>.spec.free_ttl).ok()`
151 /// incantation the pool reconciler's stale-free bucket loop
152 /// hand-authored pre-lift, sibling to
153 /// [`crate::lifetime::EphemeralLifetime::ttl_duration`] on the
154 /// SAME `(humantime string field × Option<Duration>) → Option<
155 /// Duration>` substrate axis.
156 ///
157 /// Pre-lift the `humantime::parse_duration(&<field>).ok()` shape
158 /// was owned at ONE substrate primitive on
159 /// [`crate::lifetime::EphemeralLifetime`] (the `spec.lifetime
160 /// .ephemeral.ttl` axis, feeding
161 /// [`crate::lifetime_clock::evaluate`]'s TTL-expiry gate + the
162 /// `requeue_with_ttl` sleep-budget picker) AND hand-authored at
163 /// ONE peer consumer site — `tatara-pool-reconciler::pool_decide
164 /// ::decide_pool`, which parses `pool.spec.free_ttl` with the
165 /// byte-identical shape (`humantime::parse_duration(&spec
166 /// .free_ttl).unwrap_or_default()`) and gates the stale-free
167 /// bucket loop on the result. That's ONE substrate owner + ONE
168 /// hand-authored chain on a peer humantime field of a peer spec
169 /// type past the ★★ PRIME-DIRECTIVE ≥ 2 duplication trigger —
170 /// two surfaces spelling the SAME projection with the SAME drift
171 /// risk (a per-fleet minimum TTL floor before the humantime cast,
172 /// a canonical unit-normalization pass, a warn-log on
173 /// unparseable strings would have had to land at every surface
174 /// plus stay coherent between them).
175 ///
176 /// Post-lift both peer humantime fields
177 /// ([`crate::lifetime::EphemeralLifetime::ttl`] +
178 /// [`Self::free_ttl`]) publish the SAME shape at TWO peer
179 /// inherent methods on peer spec types — the tatara-pool-
180 /// reconciler's stale-free bucket loop reads `pool.spec.free_ttl
181 /// _duration().unwrap_or_default()` and the produced [`std::time
182 /// ::Duration`] feeds the same `!free_ttl.is_zero()` guard +
183 /// `elapsed > free_ttl` comparator unchanged. A future
184 /// normalization (per-fleet minimum floor, canonical unit
185 /// normalization, warn-log on unparseable strings) lands at TWO
186 /// substrate methods here + on
187 /// [`crate::lifetime::EphemeralLifetime::ttl_duration`], reachable
188 /// via ONE workspace-wide sweep across the peer axis rather than
189 /// as a per-callsite hand-edit at every downstream humantime-ttl
190 /// consumer.
191 ///
192 /// Return-form axis: `Option<std::time::Duration>` matches the
193 /// peer primitive on
194 /// [`crate::lifetime::EphemeralLifetime::ttl_duration`] and the
195 /// downstream comparator's type. The peer projection
196 /// [`crate::time::elapsed_since`] returns the SAME `Option<std
197 /// ::time::Duration>` shape, so the stale-free gate's `elapsed >
198 /// free_ttl` comparator lands with both operands on the same
199 /// axis without a per-consumer conversion step.
200 ///
201 /// The `None` arm is the "operator's `free_ttl` string doesn't
202 /// parse" corner — a typo (`"1our"`), an unsupported unit, a
203 /// non-humantime literal that reached the field. The pool
204 /// reconciler's stale-free bucket loop collapses the corner via
205 /// `.unwrap_or_default()`, yielding the `Duration::ZERO` value
206 /// that already gates its follow-on `!free_ttl.is_zero()` check
207 /// — post-lift semantics is byte-identical to the pre-lift
208 /// hand-authored `humantime::parse_duration(&spec.free_ttl)
209 /// .unwrap_or_default()` shape.
210 ///
211 /// Theory anchor: THEORY.md §VI.1 (generation over composition —
212 /// the `humantime::parse_duration(&<field>).ok()` shape recurred
213 /// at ONE substrate owner + ONE hand-authored peer site past the
214 /// ★★ PRIME-DIRECTIVE ≥ 2 duplication trigger, and is lifted onto
215 /// TWO peer inherent methods on peer spec types here + on
216 /// [`crate::lifetime::EphemeralLifetime::ttl_duration`]).
217 /// THEORY.md §II.1 invariant 5 (composition preserves proofs —
218 /// the pins below bind the parse-failure corner, the empty-ttl
219 /// corner, the humantime edge shapes, the return-form parity with
220 /// [`crate::lifetime::EphemeralLifetime::ttl_duration`], and the
221 /// byte-identical parity with the pre-lift `.ok()` chain on the
222 /// SAME `spec.free_ttl` value, so a regression that drifts any
223 /// surface fails at `tests::pool_spec_free_ttl_duration_*` here
224 /// rather than as silent operator-facing skew between the pool
225 /// stale-free bucket loop and the ephemeral TTL-expiry gate on
226 /// the two peer humantime-string fields).
227 #[must_use]
228 pub fn free_ttl_duration(&self) -> Option<std::time::Duration> {
229 humantime::parse_duration(&self.free_ttl).ok()
230 }
231
232 /// Compose a [`PoolSpec`] for the given member `template`, stamping
233 /// every non-template slot at the `#[serde(default …)]` value the
234 /// wire-schema publishes above — the ONE substrate composer that
235 /// closes the 11-slot `PoolSpec { desired_size: 1, min_size: 0,
236 /// max_size: 0, return_policy: ReturnPolicy::Replace, selector:
237 /// PoolSelector::default(), template, free_ttl: "24h".into(),
238 /// max_allocation_ttl: "4h".into(), desired: 0, replacement_policy:
239 /// Default::default(), stable_name_claim: false }` struct-literal
240 /// every test-side + reconciler-side seed hand-authored pre-lift.
241 ///
242 /// Sibling to [`crate::crd::ProcessSpec::gate_compute_defaults`] on
243 /// the (spec-type × full-baseline-composer) axis — that primitive
244 /// owns the 11-slot [`crate::crd::ProcessSpec`] baseline composer;
245 /// this one owns the peer 11-slot [`PoolSpec`] baseline composer.
246 /// Both take a caller-supplied slot (there: the classification
247 /// baseline via `Classification::gate_compute()`; here: the
248 /// `template` [`EphemeralSpec`], which has no natural default) and
249 /// fill every other slot at its wire-published default so a caller
250 /// composes with struct-update syntax (`PoolSpec { desired_size: 1,
251 /// ..PoolSpec::with_template(empty_template()) }`) rather than
252 /// re-spelling the 10 defaulted slots at every seed. A future
253 /// promotion of a defaulted slot to a non-default (a per-fleet
254 /// minimum `min_size` floor, a shifted `default_free_ttl`,
255 /// a widened `ReturnPolicy` default) lands at ONE substrate
256 /// composer here and every downstream seed inherits the upgrade
257 /// mechanically.
258 ///
259 /// Pre-lift the 11-slot struct-literal was hand-authored at EIGHT
260 /// sites across TWO crates past the ★★ PRIME-DIRECTIVE ≥ 2
261 /// duplication trigger:
262 /// * `tatara-process::lib::tests::pool_fixture` — the
263 /// `qualified_process_ref` + trait-pin fixture seed;
264 /// * `tatara-process::lib::tests::empty_pool_spec` (×2) — the two
265 /// sibling fixtures inside separate pin modules;
266 /// * `tatara-process::pool::tests::pool_spec` — the `name_or_empty`
267 /// / `namespace_or_empty` pin fixture;
268 /// * `tatara-pool-reconciler::router::tests::pool` — the router-
269 /// candidate-arbiter pin fixture (overrides `selector`);
270 /// * `tatara-pool-reconciler::desired::tests::pool_with_desired` —
271 /// the desired-count-loop pin fixture (overrides `desired` +
272 /// `replacement_policy`);
273 /// * `tatara-pool-reconciler::pool_decide::tests::pool` — the
274 /// pure-decision pin fixture (overrides sizes);
275 /// * `tatara-pool-reconciler::allocation_decide::tests::pool` —
276 /// the allocation-router pin fixture (overrides `selector`).
277 ///
278 /// The three fields the wire-schema does NOT default (`desired_size`
279 /// carries no `#[serde(default)]` above; `template` is the caller-
280 /// supplied slot) are stamped at their operator-friendly seed
281 /// values here — `desired_size = 0` matches every other reset
282 /// slot's `0` / `false` / `Default` stamp, so a caller can compose
283 /// `PoolSpec { desired_size: 1, ..PoolSpec::with_template(t) }` for
284 /// the single-slot pool the majority of pre-lift seeds spelled, or
285 /// `PoolSpec { desired_size: 0, desired: 5, ..with_template(t) }`
286 /// for the desired-count-loop shape one seed spelled.
287 ///
288 /// Theory anchor: THEORY.md §VI.1 (generation over composition — the
289 /// 11-slot [`PoolSpec`] struct-literal recurred at EIGHT hand-
290 /// authored sites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication
291 /// trigger and is lifted onto ONE workspace-wide owner here).
292 /// THEORY.md §II.1 invariant 5 (composition preserves proofs — a
293 /// regression that drifted a wire-published default at only one
294 /// consumer, or that broke the sibling-default correspondence with
295 /// [`crate::crd::ProcessSpec::gate_compute_defaults`], surfaces at
296 /// this primitive's tests rather than as silent operator-visible
297 /// skew across the eight fixtures whose assertions key on the
298 /// shape).
299 #[must_use]
300 pub fn with_template(template: EphemeralSpec) -> Self {
301 Self {
302 desired_size: 0,
303 min_size: 0,
304 max_size: 0,
305 return_policy: ReturnPolicy::default(),
306 selector: PoolSelector::default(),
307 template,
308 free_ttl: default_free_ttl(),
309 max_allocation_ttl: default_max_allocation_ttl(),
310 desired: 0,
311 replacement_policy: ReplacementPolicy::default(),
312 stable_name_claim: false,
313 }
314 }
315}
316
317impl EphemeralPool {
318 /// Borrow-form metadata-projection primitive on the `metadata.name`
319 /// axis of `EphemeralPool`: returns the K8s object name slice with
320 /// the missing-name corner collapsed to the load-bearing empty-string
321 /// sentinel — the ONE-liner collapse of the paired
322 /// `self.metadata.name.as_deref().unwrap_or("")` incantation every
323 /// pool-side consumer restated by hand pre-lift.
324 ///
325 /// Pre-lift the `.metadata.name.as_deref().unwrap_or("")` chain
326 /// was hand-authored at TWO sites past the ★★ PRIME-DIRECTIVE ≥ 2
327 /// duplication threshold in `tatara-pool-reconciler`, both keyed
328 /// by the pool's own name slot:
329 /// * `router::pool_name` — the tie-break comparator inside
330 /// `best_match`; a deterministic lexicographic-min-name arbiter
331 /// across two pool candidates whose specificity scores tie.
332 /// * `controller_allocation::reconcile_inner` — the `HashMap<
333 /// pool-name, Vec<PoolMember>>` lookup closure fed into
334 /// `decide_allocation_reconcile`; keys the "which pool members
335 /// back this allocation candidate?" projection at every
336 /// allocation-reconcile pass.
337 ///
338 /// Both sites walked the SAME `.as_deref().unwrap_or("")` chain
339 /// and both wanted the `&str` form the primitive returns — as a
340 /// borrow suitable for lexicographic `str::cmp` in the tie-break
341 /// AND for the `HashMap<String, _>::get(&str)` lookup. Post-lift
342 /// each caller reaches for `pool.name_or_empty()` and the produced
343 /// slice feeds the same downstream comparator / lookup unchanged.
344 ///
345 /// The empty-string fallback is the SAME sentinel the sibling
346 /// borrow-form primitive [`crate::crd::Process::uid_or_empty`]
347 /// returns AND the SAME sentinel the owned-form sibling
348 /// [`crate::crd::Process::owned_name_or_empty`] returns on the
349 /// `metadata.name` axis of the sister CRD — the three primitives
350 /// partition the (borrow-form × owned-form) × (uid × name) corner
351 /// of the metadata-slot family on identical fallback semantics
352 /// (empty string means "the slot is unset"), so a consumer that
353 /// switches between the CRD surfaces based on downstream keying
354 /// requirements never sees a different missing-slot spelling as
355 /// a side effect.
356 ///
357 /// Return-form axis: `&str` mirrors the borrow-first discipline
358 /// of the peer metadata primitives on `Process`
359 /// ([`crate::crd::Process::namespace_or_default`],
360 /// [`crate::crd::Process::name_or_placeholder`],
361 /// [`crate::crd::Process::uid_or_empty`]). The one missing-slot
362 /// corner the chain swallowed pre-lift (missing `metadata.name`)
363 /// collapses to the empty-string sentinel so `str::is_empty` /
364 /// `HashMap::get` on an unnamed pool behaves identically to what
365 /// the pre-lift `.as_deref().unwrap_or("")` chain produced.
366 ///
367 /// A future normalization step (a name-canonicalization pass, a
368 /// case-fold key builder, a per-cluster prefix stripper for
369 /// cross-cluster pool-name aliasing) lands at ONE substrate
370 /// method here and both downstream consumers pick up the upgrade
371 /// mechanically — no per-callsite hand-edit at `pool_name` /
372 /// `reconcile_inner`.
373 ///
374 /// Theory anchor: THEORY.md §VI.1 (generation over composition —
375 /// the `.metadata.name.as_deref().unwrap_or("")` chain recurred
376 /// at two hand-authored sites past the ★★ PRIME-DIRECTIVE ≥ 2
377 /// duplication trigger, and is lifted to ONE owner here).
378 /// THEORY.md §II.1 invariant 5 (composition preserves proofs —
379 /// the pins bind the missing-name corner + the empty-string
380 /// sentinel byte-shape + the borrow-form `&str` lifetime + the
381 /// byte-identical parity with the pre-lift chain + the fallback-
382 /// value coherence with `Process::uid_or_empty` /
383 /// `Process::owned_name_or_empty` on the metadata-slot × empty-
384 /// sentinel axis, so a regression that drifted any surface at
385 /// `tests::name_or_empty_*` here rather than as silent operator-
386 /// facing skew between the router tie-break and the allocation
387 /// member-lookup on the SAME pool candidate).
388 pub fn name_or_empty(&self) -> &str {
389 self.metadata.name.as_deref().unwrap_or("")
390 }
391
392 /// Owned-form metadata-projection primitive on the `metadata.name`
393 /// axis of `EphemeralPool`: returns an owned `String` copy of the K8s
394 /// object name with the missing-name corner collapsed to the load-
395 /// bearing empty-string sentinel — the ONE-liner collapse of the
396 /// paired `self.metadata.name.clone().unwrap_or_default()` incantation
397 /// every pool-side consumer restated by hand pre-lift.
398 ///
399 /// Pre-lift the `.metadata.name.clone().unwrap_or_default()` chain
400 /// was hand-authored at TWO sites past the ★★ PRIME-DIRECTIVE ≥ 2
401 /// duplication threshold in `tatara-pool-reconciler`, both keyed by
402 /// the pool's own name slot in an `owned String` context:
403 /// * `controller_allocation::reconcile_inner` — the
404 /// `HashMap<String, Vec<PoolMember>>` key seed inside a
405 /// `pools.iter().map(|p| ...).collect()` fanout; the map key is
406 /// the owned `String` form because the produced `HashMap<String, _>`
407 /// outlives the pool-list borrow that generated it and the
408 /// downstream `pool_members.get(pool.name_or_empty())` closure
409 /// consumes it as `&str`.
410 /// * `allocation_decide::AllocationConvergenceCtx::observe` — the
411 /// `AllocationRef::name` slot seed stamped on the matched-pool
412 /// handle; the struct literal is `AllocationRef { name: String,
413 /// namespace: String }` and the produced value is threaded through
414 /// the `Decision::decide` transition rule downstream.
415 ///
416 /// Both sites walked the SAME `.clone().unwrap_or_default()` chain
417 /// and both wanted the `String` form the primitive returns — as the
418 /// owned key of a `HashMap<String, _>` and as the `String` slot of
419 /// an `AllocationRef` struct literal. Post-lift each callsite reads
420 /// `pool.owned_name_or_empty()` and the produced value feeds the
421 /// same downstream key / struct-literal slot unchanged.
422 ///
423 /// The empty-string fallback is the SAME sentinel the sibling
424 /// borrow-form primitive [`Self::name_or_empty`] returns AND the
425 /// SAME sentinel the sibling owned-form primitive
426 /// [`crate::crd::Process::owned_name_or_empty`] returns on the
427 /// `metadata.name` axis of the sister CRD — the three primitives
428 /// partition the (borrow-form × owned-form) corner of the metadata-
429 /// name family across BOTH tatara-process CRDs on identical missing-
430 /// slot semantics (empty string means "the slot is unset"), so a
431 /// consumer that switches between the CRD surfaces based on
432 /// downstream ownership requirements never sees a different
433 /// missing-slot spelling as a side effect.
434 ///
435 /// Peer to [`Self::name_or_empty`] on the (return-form × ownership)
436 /// axis pair — closes the corner the pool-side family previously
437 /// left open:
438 ///
439 /// * borrow + empty sentinel → [`Self::name_or_empty`] (router tie-
440 /// break comparator, `HashMap<String, _>::get(&str)` lookup —
441 /// consumers whose downstream keys by `&str` and allocates
442 /// nothing);
443 /// * owned + empty sentinel → **this method** (HashMap-key seed in
444 /// an outliving-borrow context, `AllocationRef::name` struct-
445 /// literal slot — consumers whose downstream requires the owned
446 /// `String` form because the produced value outlives the source-
447 /// pool borrow).
448 ///
449 /// A future normalization step (a name-canonicalization pass, a
450 /// case-fold key builder, a per-cluster prefix stripper for cross-
451 /// cluster pool-name aliasing) lands at ONE substrate method here
452 /// and both downstream consumers pick up the upgrade mechanically —
453 /// no per-callsite hand-edit at `reconcile_inner` /
454 /// `AllocationConvergenceCtx::observe`.
455 ///
456 /// Theory anchor: THEORY.md §VI.1 (generation over composition —
457 /// the `.metadata.name.clone().unwrap_or_default()` chain recurred
458 /// at two hand-authored sites past the ★★ PRIME-DIRECTIVE ≥ 2
459 /// duplication trigger, and is lifted to ONE owner here).
460 /// THEORY.md §II.1 invariant 5 (composition preserves proofs —
461 /// the pins bind the missing-name corner + the empty-string
462 /// sentinel byte-shape + the owned-form `String` return type + the
463 /// byte-identical parity with the pre-lift chain + the fallback-
464 /// value coherence with [`Self::name_or_empty`] +
465 /// [`crate::crd::Process::owned_name_or_empty`] on the metadata-
466 /// slot × empty-sentinel axis, so a regression that drifted any
467 /// surface at `tests::owned_name_or_empty_*` here rather than as
468 /// silent operator-facing skew between the pool-members lookup key
469 /// and the AllocationRef seed on the SAME pool candidate).
470 pub fn owned_name_or_empty(&self) -> String {
471 self.metadata.name.clone().unwrap_or_default()
472 }
473
474 /// Copy-form metadata-projection primitive on the deletion-tombstone
475 /// axis of `EphemeralPool`: returns `true` iff the K8s API server
476 /// has stamped a `metadata.deletionTimestamp` on this pool (the
477 /// moment the object entered the "being deleted" corner of its
478 /// lifecycle, after which further mutating writes are refused and
479 /// finalizers are drained before the object is actually removed) —
480 /// the ONE-liner collapse of the paired
481 /// `self.metadata.deletion_timestamp.is_some()` incantation every
482 /// pool-side consumer restated by hand pre-lift.
483 ///
484 /// Pre-lift the `.metadata.deletion_timestamp.is_some()` chain was
485 /// hand-authored at TWO sites past the ★★ PRIME-DIRECTIVE ≥ 2
486 /// duplication threshold in `tatara-pool-reconciler`, both
487 /// projecting the SAME tombstone-presence predicate on an
488 /// `EphemeralPool` value:
489 /// * `pool_decide::decide_pool_reconcile` — the pure decision
490 /// function's deletion-preempt gate that forces
491 /// [`PoolDecision::Drain`] as soon as the API server stamps
492 /// the tombstone, before the (desired vs actual) supply-arithmetic
493 /// branches get a chance to run. Wired at the very top of the
494 /// decision so a draining pool never spawns / reaps / expires
495 /// through the normal replenishment arithmetic while the
496 /// deletion is in flight.
497 /// * `controller_pool::pool_phase_from_members` — the observed-
498 /// phase composer's tombstone-first arm that returns
499 /// [`PoolPhase::Draining`] regardless of the supply / demand
500 /// arithmetic that would otherwise pick `Ready` / `Scaling` /
501 /// `Degraded`. Keeps the reported phase honest during the
502 /// finalizer drain so operators reading `kubectl get
503 /// ephemeralpools` see the tombstone-present state as
504 /// `Draining`, not as a stale `Ready`.
505 ///
506 /// Both sites walked the SAME `.metadata.deletion_timestamp
507 /// .is_some()` chain and both wanted the `bool` form the primitive
508 /// returns — the `decide_pool_reconcile` site to gate the
509 /// `→ Drain` short-circuit and the `pool_phase_from_members` site
510 /// to gate the `→ Draining` short-circuit. Post-lift each callsite
511 /// reads `pool.is_being_deleted()` and the produced `bool` feeds
512 /// the same downstream short-circuit unchanged.
513 ///
514 /// Sibling to [`crate::crd::Process::is_being_deleted`] on the
515 /// deletion-tombstone axis of the sister CRD — the two primitives
516 /// now partition the tombstone-presence probe across BOTH
517 /// tatara-process CRDs on identical missing-slot semantics
518 /// (present timestamp means "the API server has begun deletion"),
519 /// so an operator or reconciler that switches between the CRD
520 /// surfaces never sees a different tombstone-detection spelling
521 /// as a side effect.
522 ///
523 /// Return-form axis: `bool` matches the copy-form discipline of
524 /// the sibling [`crate::crd::Process::is_being_deleted`] and of
525 /// the pool-side [`crate::phase::ProcessPhase::is_alive`] +
526 /// [`Self::name_or_empty`]-family primitives — the underlying
527 /// slot is a wire-format `Option<Time>` that carries only
528 /// presence information at this axis (the RFC-3339 timestamp
529 /// payload itself is not what the two consumers read; both only
530 /// probe presence to detect the tombstone-stamped state).
531 /// Returning the raw `Option<&Time>` would push the `.is_some()`
532 /// probe back to every callsite, restating the pre-lift chain
533 /// one link shorter without collapsing the primitive.
534 ///
535 /// Peer to [`Self::name_or_empty`] and [`Self::owned_name_or_empty`]
536 /// on the metadata-projection axis for `EphemeralPool`; this method
537 /// opens the presence-probe corner for the tombstone slot. Future
538 /// metadata-presence projections on the pool CRD (an
539 /// `is_being_finalized` projection on
540 /// `metadata.finalizers.is_empty()`'s negation, a `has_owner`
541 /// projection on `metadata.owner_references.is_empty()`'s
542 /// negation) land as peer methods on this same axis.
543 ///
544 /// A future normalization step (a per-tombstone staleness gate
545 /// that returns `false` for a tombstone older than the reconciler's
546 /// grace-period budget, a canonicalization pass that treats a
547 /// tombstone from a paused controller as absent, a cross-cluster
548 /// tombstone-observation clock skew guard) lands at ONE substrate
549 /// method here and both downstream consumers pick up the upgrade
550 /// mechanically — no per-callsite hand-edit at
551 /// `decide_pool_reconcile` / `pool_phase_from_members`.
552 ///
553 /// Theory anchor: THEORY.md §VI.1 (generation over composition —
554 /// the `.metadata.deletion_timestamp.is_some()` chain recurred at
555 /// two hand-authored sites past the ★★ PRIME-DIRECTIVE ≥ 2
556 /// duplication trigger, and is lifted to ONE owner here).
557 /// THEORY.md §II.1 invariant 5 (composition preserves proofs —
558 /// the pins bind the missing-tombstone corner + the present-
559 /// tombstone corner + the copy-form `bool` return + the byte-
560 /// identical parity with the pre-lift `.is_some()` chain + the
561 /// cross-CRD coherence with `crate::crd::Process::is_being_deleted`
562 /// on the tombstone axis, so a regression that drifted any surface
563 /// at `tests::is_being_deleted_*` rather than as silent operator-
564 /// facing skew between the pool-reconciler's `→ Drain` decision
565 /// and the observed-phase composer's `→ Draining` report on the
566 /// SAME `EphemeralPool` within one reconcile pass).
567 pub fn is_being_deleted(&self) -> bool {
568 self.metadata.deletion_timestamp.is_some()
569 }
570
571 /// Owned-form metadata-projection primitive on the `metadata.namespace`
572 /// axis of `EphemeralPool`: returns an owned `String` copy of the K8s
573 /// namespace with the missing-namespace corner collapsed to the load-
574 /// bearing empty-string sentinel — the ONE-liner collapse of the
575 /// paired `self.metadata.namespace.clone().unwrap_or_default()`
576 /// incantation every pool-side consumer restated by hand pre-lift.
577 ///
578 /// Pre-lift the `.metadata.namespace.clone().unwrap_or_default()`
579 /// chain was hand-authored at TWO sites past the ★★ PRIME-DIRECTIVE
580 /// ≥ 2 duplication threshold, both stamping the `AllocationRef
581 /// { namespace: String, .. }` slot inside an owned-`String` context:
582 /// * `tatara-pool-reconciler::allocation_decide::AllocationConvergenceCtx
583 /// ::observe` — the matched-pool seed's `AllocationRef.namespace`
584 /// slot, right beside the peer [`Self::owned_name_or_empty`] call
585 /// that owns the paired name half. This is the exact site the
586 /// pre-existing peer-primitive doc-comment forecast (`"a future
587 /// run may lift owned_namespace_or_empty as the sibling axis
588 /// peer"`).
589 /// * `crate::pool::tests::allocation_ref_new_composes_with_owned_name_or_empty_pool_projection`
590 /// — the composition pin that seeded an `AllocationRef` from the
591 /// same paired-primitive-half construction the production consumer
592 /// in `allocation_decide::observe` performs. Post-lift the pin
593 /// composes two peer primitives (`owned_name_or_empty` +
594 /// `owned_namespace_or_empty`) rather than one primitive plus the
595 /// pre-lift chain, sharpening it from a mixed-form composition
596 /// check into a paired-primitive-family composition check.
597 ///
598 /// Both sites walked the SAME `.clone().unwrap_or_default()` chain
599 /// and both wanted the `String` form the primitive returns — as the
600 /// `String` slot of an `AllocationRef` struct literal built through
601 /// [`crate::pool::AllocationRef::new`]. Post-lift each callsite reads
602 /// `pool.owned_namespace_or_empty()` and the produced value feeds
603 /// the same downstream `AllocationRef` slot unchanged.
604 ///
605 /// The empty-string fallback is the SAME sentinel the sibling owned-
606 /// form primitive [`Self::owned_name_or_empty`] returns on the
607 /// `metadata.name` axis of the same CRD — the two primitives now
608 /// partition the (owned `String` × `metadata.<slot>`) corner of the
609 /// pool CRD's metadata family across BOTH object-coordinate slots
610 /// on identical missing-slot semantics (empty string means "the
611 /// slot is unset"), so the [`crate::pool::AllocationRef::new`]
612 /// composer sees a coherent owned-empty pair regardless of which
613 /// slot is absent on the source pool. Coherent with the workspace-
614 /// wide owned-empty sentinel that the peer primitives
615 /// [`crate::crd::Process::uid_or_empty`],
616 /// [`crate::crd::Process::owned_name_or_empty`],
617 /// [`Self::name_or_empty`], and [`Self::owned_name_or_empty`]
618 /// already share on the metadata-slot × empty-sentinel axis.
619 ///
620 /// Peer to [`Self::owned_name_or_empty`] on the
621 /// (`metadata.name` × `metadata.namespace`) axis of the owned-form
622 /// projection family — closes the corner the pool-side family
623 /// previously left open:
624 ///
625 /// * owned + name + empty sentinel → [`Self::owned_name_or_empty`]
626 /// (`AllocationRef.name` seed, `HashMap<String, _>` key seed);
627 /// * owned + namespace + empty sentinel → **this method**
628 /// (`AllocationRef.namespace` seed — the paired half the same
629 /// `AllocationRef::new(name, namespace)` constructor consumes);
630 /// * copy + deletion + tombstone probe → [`Self::is_being_deleted`]
631 /// (the presence-probe corner of the same metadata axis, already
632 /// opened).
633 ///
634 /// A future normalization step (a namespace-canonicalization pass,
635 /// a case-fold key builder, a per-cluster prefix stripper, or the
636 /// canonical-namespace default lift that would substitute
637 /// [`crate::crd::Process::DEFAULT_NAMESPACE`] on the missing-slot
638 /// corner rather than the empty-string sentinel) lands at ONE
639 /// substrate method here and both downstream consumers pick up the
640 /// upgrade mechanically — no per-callsite hand-edit at
641 /// `AllocationConvergenceCtx::observe` / the composition pin.
642 ///
643 /// The empty-string fallback (rather than
644 /// [`crate::crd::Process::DEFAULT_NAMESPACE`]) is DELIBERATELY
645 /// pinned: the sole downstream consumer
646 /// (`AllocationConvergenceCtx::observe`'s matched-pool seed) feeds
647 /// the produced value into `AllocationRef.namespace`, which is then
648 /// matched byte-identically against `spec.pool_ref.namespace` at
649 /// [`crate::pool::allocation_decide::resolve_pool`]-style comparators.
650 /// A silent substitution of `"default"` at this primitive would
651 /// alias every namespace-absent pool to the `"default"` bucket at
652 /// the matcher, hiding the missing-slot corner from an operator
653 /// who explicitly authored an allocation against a namespace-
654 /// unset pool. The load-bearing empty-string sentinel keeps the
655 /// pre-lift `.clone().unwrap_or_default()` shape verbatim so the
656 /// downstream matcher's byte-comparison stays honest.
657 ///
658 /// Theory anchor: THEORY.md §VI.1 (generation over composition —
659 /// the `.metadata.namespace.clone().unwrap_or_default()` chain
660 /// recurred at two hand-authored sites past the ★★ PRIME-DIRECTIVE
661 /// ≥ 2 duplication trigger, and is lifted to ONE owner here).
662 /// THEORY.md §II.1 invariant 5 (composition preserves proofs —
663 /// the pins bind the missing-namespace corner + the empty-string
664 /// sentinel byte-shape + the owned-form `String` return type + the
665 /// byte-identical parity with the pre-lift chain + the fallback-
666 /// value coherence with [`Self::owned_name_or_empty`] on the
667 /// paired-slot axis, so a regression that drifted any surface at
668 /// `tests::owned_namespace_or_empty_*` rather than as silent
669 /// operator-facing skew between the paired name / namespace halves
670 /// of the SAME `AllocationRef` seed).
671 pub fn owned_namespace_or_empty(&self) -> String {
672 self.metadata.namespace.clone().unwrap_or_default()
673 }
674
675 /// Compound owned-form metadata-projection primitive on the paired
676 /// `(metadata.uid, metadata.name)` axis of `EphemeralPool`: returns
677 /// a stable owned `String` seed for slot-slug derivation, PREFERRING
678 /// the K8s-assigned uid, FALLING BACK to the pool's own name, then
679 /// SINKING to the load-bearing empty-string sentinel when both slots
680 /// are absent — the ONE-liner collapse of the paired
681 /// `pool.metadata.uid.clone().unwrap_or_else(|| name.<into>())`
682 /// incantation every pool-slot-name-composing consumer restated by
683 /// hand pre-lift.
684 ///
685 /// Pre-lift the `.metadata.uid.clone().unwrap_or_else(|| name.<into>())`
686 /// chain was hand-authored at TWO production sites past the ★★
687 /// PRIME-DIRECTIVE ≥ 2 duplication threshold in
688 /// `tatara-pool-reconciler::controller_pool`, both feeding the SAME
689 /// `member_process_name(&pool_name, &pool_uid_or_name_fallback, slot)`
690 /// composer:
691 /// * `reconcile_inner` — the desired-count `PoolDecision::Spawn`
692 /// arm's spawn-loop slot-slug seed (fallback bound as
693 /// `|| name.clone()` from the extracted-earlier owned `name`
694 /// half of `owned_coordinates_required()`).
695 /// * `apply_convergence_actions` — the legacy allocation-driven
696 /// `ConvergenceAction::CreateMember` arm's slot-slug seed
697 /// (fallback bound as `|| name.to_string()` from the borrowed
698 /// `name: &str` parameter that the same
699 /// `owned_coordinates_required()`-extracted `String` was passed
700 /// through by reference).
701 ///
702 /// Both sites computed the SAME "prefer the k8s uid; fall back to
703 /// the pool's own name" projection on the SAME `EphemeralPool`
704 /// value, differing only in the surface syntax of the fallback
705 /// (`.clone()` vs `.to_string()`) — a per-callsite typing artefact
706 /// of the enclosing scope's `name` binding rather than a semantic
707 /// distinction. Post-lift each callsite reads
708 /// `pool.owned_uid_or_name_or_empty()` and the produced owned
709 /// `String` feeds the same `member_process_name(&name, &_, slot)`
710 /// composer verbatim; the caller no longer threads its own local
711 /// `name` handle through as the fallback, since the primitive
712 /// reaches through the same `self.metadata.name` slot the caller
713 /// extracted from earlier — coherent by construction with the
714 /// sibling primitive [`Self::owned_name_or_empty`] on the missing-
715 /// name corner.
716 ///
717 /// The compound (uid-preferred, name-fallback, empty-sentinel)
718 /// precedence is DELIBERATELY pinned: the K8s API server stamps
719 /// `metadata.uid` on every persisted object at admission time, so
720 /// the reachable state at both callsites (each already gated by
721 /// `owned_coordinates_required()?`) has `uid = Some(_)`. The name
722 /// fallback is a load-bearing safety net for the vanishingly rare
723 /// pre-admission-uid corner + the unit-test path that constructs
724 /// an `EphemeralPool` value in-memory without stamping a uid; the
725 /// empty-string sink is the sentinel-coherent complement of the
726 /// missing-both corner (both slots `None`) so a regression that
727 /// dropped either fallback surfaces as a compiler-visible test
728 /// failure rather than as an operator-facing skew between spawn
729 /// slots derived from mixed-fallback seeds within one reconcile
730 /// pass. Coherent with the workspace-wide owned-empty sentinel
731 /// that the peer primitives [`Self::owned_name_or_empty`],
732 /// [`Self::owned_namespace_or_empty`],
733 /// [`crate::crd::Process::owned_name_or_empty`], and
734 /// [`crate::crd::Process::uid_or_empty`] already share on the
735 /// metadata-slot × empty-sentinel axis.
736 ///
737 /// A future normalization step (a per-cluster uid-prefix stripper,
738 /// a case-fold key builder, canonicalization of a suspiciously-
739 /// empty uid to the name fallback, a namespace-scoped hashing pass
740 /// that mixes cluster identity into the seed) lands at ONE
741 /// substrate method here and both downstream `spawn` /
742 /// `apply_convergence_actions` consumers pick up the upgrade
743 /// mechanically — no per-callsite hand-edit at `controller_pool`.
744 ///
745 /// Theory anchor: THEORY.md §VI.1 (generation over composition —
746 /// the `.metadata.uid.clone().unwrap_or_else(|| name.<into>())`
747 /// chain recurred at two hand-authored sites past the ★★ PRIME-
748 /// DIRECTIVE ≥ 2 duplication trigger, and is lifted to ONE owner
749 /// here). THEORY.md §II.1 invariant 5 (composition preserves
750 /// proofs — the pins bind the uid-present corner + the uid-absent
751 /// name-fallback corner + the both-absent empty-sentinel corner +
752 /// the owned-form `String` return type + the byte-identical parity
753 /// with each pre-lift callsite's fallback surface, so a regression
754 /// that drifted any surface at `tests::owned_uid_or_name_or_empty_*`
755 /// rather than as silent operator-facing skew between the two
756 /// slot-slug seeds within ONE reconcile pass).
757 pub fn owned_uid_or_name_or_empty(&self) -> String {
758 self.metadata
759 .uid
760 .clone()
761 .unwrap_or_else(|| self.owned_name_or_empty())
762 }
763
764 /// Copy-form metadata-projection primitive on the `metadata.name`
765 /// axis of `EphemeralPool` in its `presence-and-equal` corner:
766 /// returns `true` iff the K8s object name slot is BOTH `Some(_)`
767 /// AND byte-identical to the supplied candidate — the ONE-liner
768 /// collapse of the paired
769 /// `self.metadata.name.as_deref() == Some(candidate)` incantation
770 /// every pool-side lookup consumer restated by hand pre-lift.
771 ///
772 /// Pre-lift the `.metadata.name.as_deref() == Some(<candidate>)`
773 /// chain was hand-authored at TWO production sites past the ★★
774 /// PRIME-DIRECTIVE ≥ 2 duplication threshold in
775 /// `tatara-pool-reconciler`, both keyed by the `EphemeralPool`'s
776 /// own name slot inside a `candidate_pools.iter().find(|p| ...)`
777 /// closure that resolves a pool from an `AllocationRef.name` half:
778 /// * `allocation_decide::resolve_pool` — the explicit-`pool_ref`
779 /// half of the pool-resolution ladder, one of two conjuncts in
780 /// the `(name == X && namespace == Y)` byte-comparison against
781 /// `AllocationSpec::pool_ref`. Pairs with the sibling namespace
782 /// comparison (a future run may lift `has_namespace` as the
783 /// paired-axis peer once a second namespace-probe site opens).
784 /// * `controller_allocation::reconcile_inner` — the TTL-inheritance
785 /// fallback path's pool-lookup by `AllocationDecision::Bind::pool
786 /// .name`, feeding the matched pool's `spec.template.ttl` into
787 /// the just-bound member Process's lifetime overlay.
788 ///
789 /// Both sites walked the SAME `.as_deref() == Some(<x>.as_str())`
790 /// chain against a `&str` candidate held by an [`AllocationRef`]
791 /// or a similar owned-name handle, and both wanted the `bool`
792 /// form the primitive returns — the transition rule's discriminant
793 /// on either the `find(|p| p.has_name(&pool_ref.name))` closure
794 /// (which either matches ONE candidate pool or none) or the
795 /// TTL-inheritance closure's short-circuit through
796 /// `.map(...).unwrap_or_else(...)`. Post-lift each callsite reads
797 /// `p.has_name(&candidate)` and the produced `bool` feeds the same
798 /// downstream `find` / `map` closure unchanged.
799 ///
800 /// Distinct in semantics from the sibling primitive
801 /// [`Self::name_or_empty`] on the SAME `metadata.name` axis: the
802 /// `_or_empty` family folds the missing-slot corner to the load-
803 /// bearing empty-string sentinel (so `None` and `Some("")` both
804 /// project to `""`), whereas this primitive keeps `None` distinct
805 /// from `Some("")` at the `==` operator — a `None` slot returns
806 /// `false` even when the candidate is the empty string. That
807 /// discipline is load-bearing at both consumer sites: pre-lift
808 /// they compared `Option<&str>` against `Some(<candidate>)`, so a
809 /// substitution through `Self::name_or_empty` would silently
810 /// promote a namespace-absent pool with a `""` candidate into a
811 /// spurious match at the `find` closure, aliasing every unnamed
812 /// pool to the same lookup bucket at the resolver. Preserving the
813 /// `None ⇒ false` corner keeps the resolver's byte-comparison
814 /// honest.
815 ///
816 /// Peer to the sibling substrate primitives already opened on the
817 /// pool-side (`metadata.name` × return-form) axis:
818 /// * borrow-form + empty sentinel → [`Self::name_or_empty`] (`&str`
819 /// projection with a `""` fallback for missing / explicitly-empty
820 /// name slots; router tie-break comparator);
821 /// * owned-form + empty sentinel → [`Self::owned_name_or_empty`]
822 /// (`String` projection with a `""` fallback; `AllocationRef.name`
823 /// seed);
824 /// * **presence-and-equal probe → this method** (`bool` projection
825 /// with `None`-preserving semantics; pool-lookup closure
826 /// discriminant).
827 ///
828 /// A future normalization step (a name-canonicalization pass, a
829 /// case-fold key builder, a per-cluster prefix stripper for cross-
830 /// cluster pool-name aliasing, or a canonical-namespace default
831 /// lift) lands at ONE substrate method here and both downstream
832 /// consumers pick up the upgrade mechanically — no per-callsite
833 /// hand-edit at `resolve_pool` / `controller_allocation
834 /// ::reconcile_inner`.
835 ///
836 /// Theory anchor: THEORY.md §VI.1 (generation over composition —
837 /// the `.metadata.name.as_deref() == Some(<candidate>)` chain
838 /// recurred at two hand-authored sites past the ★★ PRIME-
839 /// DIRECTIVE ≥ 2 duplication trigger, and is lifted to ONE owner
840 /// here). THEORY.md §II.1 invariant 5 (composition preserves
841 /// proofs — the pins bind the missing-slot corner (`None ⇒
842 /// false`, even against a `""` candidate) + the populated-slot
843 /// equal corner + the populated-slot unequal corner + the
844 /// byte-identical parity with the pre-lift `.as_deref() == Some
845 /// (<candidate>)` chain + the disjoint semantics vs. the
846 /// `_or_empty` sibling family, so a regression that drifted any
847 /// surface at `tests::has_name_*` here rather than as silent
848 /// operator-facing skew between the two `find` closures the
849 /// primitive owns).
850 #[must_use]
851 pub fn has_name(&self, candidate: &str) -> bool {
852 self.metadata.name.as_deref() == Some(candidate)
853 }
854
855 /// The namespaced-CRD constructor composer on the `EphemeralPool`
856 /// axis: forwards `(name, spec)` to the kube-derived
857 /// [`Self::new`] constructor + stamps `metadata.namespace` with
858 /// the caller-supplied slot in ONE step. The ONE-liner collapse
859 /// of the paired `let mut p = EphemeralPool::new(<name>, <spec>);
860 /// p.meta_mut().namespace = Some(<ns>.into());` incantation every
861 /// pool-side test fixture restated by hand pre-lift.
862 ///
863 /// Pre-lift the 2-line construct-then-set-namespace chain was
864 /// hand-authored at FOUR sites past the ★★ PRIME-DIRECTIVE ≥ 2
865 /// duplication threshold in `tatara-pool-reconciler`, all
866 /// composing a namespaced `EphemeralPool` fixture from a `name`
867 /// slot and a `PoolSpec`:
868 /// * `router::pool` — the selector-routing test fixture pinned
869 /// to `"ephemeral-pools"`.
870 /// * `pool_decide::pool` — the desired-count-loop test fixture
871 /// pinned to `"pools"`.
872 /// * `desired::pool` — the replacement-policy test fixture
873 /// pinned to `"pools"`.
874 /// * `allocation_decide::pool` — the allocation-decision test
875 /// fixture pinned to the caller-supplied `ns` slot.
876 ///
877 /// All four sites walked the SAME 2-line chain and all four
878 /// wanted the `EphemeralPool` back with `metadata.namespace`
879 /// stamped as `Some(<ns>.into())`. Post-lift each callsite reads
880 /// `EphemeralPool::new_in(<name>, <ns>, <spec>)` and the produced
881 /// value feeds the same downstream reconciler-input `Vec<
882 /// EphemeralPool>` unchanged.
883 ///
884 /// The `impl Into<String>` at the `namespace` slot matches the
885 /// sibling `impl Into<String>`-widening discipline the workspace's
886 /// other namespaced-CRD-adjacent composers walk
887 /// ([`crate::pool::PoolMember::unallocated`] on the
888 /// `process_name` slot, [`crate::pool::AllocationRef::new`] on the
889 /// `(name, namespace)` slot pair, [`crate::allocation::
890 /// Requestor::kind_only`] on the `kind` slot) and accepts BOTH
891 /// `&'static str` (the majority pre-lift caller shape) AND owned
892 /// `String` at the SAME signature.
893 ///
894 /// Peer to [`crate::allocation::EphemeralAllocation::new_in`] on
895 /// the sister `EphemeralAllocation` CRD — the two primitives
896 /// partition the namespaced-CRD-constructor family axis for the
897 /// two pool-adjacent CRDs the workspace stamps at reconciler
898 /// fixture / GitHub-webhook-emitter time. A future normalization
899 /// (a per-fleet virtual-cluster prefix rewrite on the `namespace`
900 /// slot, a per-cluster canonical case-fold pass, a
901 /// `generateName` fallback on the `name` slot, an operator-scoped
902 /// default namespace for cluster-local test rigs, an audit-tag
903 /// stamped on every fixture-emitted CRD for post-hoc grep
904 /// discipline) lands at ONE primitive body per CRD and every
905 /// downstream fixture consumer inherits the upgrade mechanically.
906 ///
907 /// `#[must_use]` on the return keeps a caller from composing the
908 /// namespaced value and dropping it un-passed to a reconciler-
909 /// input slot or an assertion helper.
910 ///
911 /// Theory anchor: THEORY.md §VI.1 (generation over composition —
912 /// the 2-line construct-then-set-namespace chain recurred at
913 /// FOUR hand-authored sites past the ★★ PRIME-DIRECTIVE ≥ 2
914 /// duplication trigger, spanning one crate but four modules, and
915 /// is lifted to ONE substrate owner here). THEORY.md §II.1
916 /// invariant 5 (composition preserves proofs — the pins below
917 /// bind the (name-slot → metadata.name, ns-slot → metadata.
918 /// namespace, spec-slot → spec) slot-projection triple + the
919 /// byte-identical parity with the pre-lift 2-line chain across
920 /// the two representative `impl Into<String>` value shapes
921 /// (`&'static str` and owned `String`) + the sibling-composer
922 /// coherence with [`Self::new`]).
923 #[must_use]
924 pub fn new_in(name: &str, namespace: impl Into<String>, spec: PoolSpec) -> Self {
925 // Routes through the ONE substrate owner of the
926 // `metadata.namespace` stamp — the [`crate::PlacedInNamespace`]
927 // blanket-impl trait over `kube::Resource<DynamicType = ()>`.
928 // Byte-identical to the pre-lift 3-line body
929 // (`Self::new(name, spec); metadata.namespace = Some(namespace
930 // .into())`); the trait-forwarding form collapses the mutation
931 // duplication with the sibling per-CRD composer
932 // [`crate::allocation::EphemeralAllocation::new_in`] and with
933 // the render-fixture site on `Process` that has no per-CRD
934 // `new_in` sibling.
935 use crate::PlacedInNamespace;
936 Self::new(name, spec).in_namespace(namespace)
937 }
938}
939
940/// What the pool reconciler does when a member reaches `Failed`.
941///
942/// Sibling closed-set lifts on the same `tatara-process` axis:
943/// [`crate::compliance::VerificationPhase::ALL`],
944/// [`crate::signal::SighupStrategy::ALL`],
945/// [`crate::spec::MustReachPhase::ALL`],
946/// [`crate::intent::WorkloadKind::ALL`],
947/// [`crate::export::ReportFormat::ALL`],
948/// [`crate::encapsulates::EncapsulationMode::ALL`],
949/// [`crate::export::ExportTrigger::ALL`],
950/// [`crate::lifetime::TeardownPolicy::ALL`],
951/// [`crate::boundary::ConditionKind::ALL`],
952/// [`crate::lifetime::LifetimeKind::ALL`],
953/// [`crate::intent::IntentKind::ALL`],
954/// [`crate::phase::ProcessPhase::ALL`],
955/// [`crate::signal::ProcessSignal::ALL`].
956#[derive(
957 Clone,
958 Copy,
959 Debug,
960 Default,
961 Serialize,
962 Deserialize,
963 JsonSchema,
964 PartialEq,
965 Eq,
966 Hash,
967 tatara_closed_set::DeriveClosedSet,
968)]
969#[serde(rename_all = "PascalCase")]
970#[closed_set(via = "as_str", generate_unknown, display)]
971pub enum ReplacementPolicy {
972 /// **Default** — Failed member is reaped + replaced immediately
973 /// (pool stays at `desired` count). Most production-like.
974 #[default]
975 ReplaceImmediate,
976 /// Failed member stays for inspection; pool runs short until the
977 /// operator manually reaps it. Useful for debugging.
978 HoldFailed,
979 /// Failed member triggers pool-wide pause: `desired` is
980 /// effectively 0 until the operator manually resumes via a
981 /// pool-status patch. Used for "halt on any failure" workflows.
982 PausePool,
983}
984
985impl ReplacementPolicy {
986 /// The closed set of replacement policies — single source of truth
987 /// that drives the `as_str` / Display / `FromStr` triad and the
988 /// `replaces_failed` / `pauses_on_failure` predicate pair. Adding a
989 /// fourth variant lands at one `ALL` entry + one `as_str` arm + one
990 /// predicate arm per projection — exhaustively checked by the
991 /// compiler (the `[Self; 3]` array literal forces the arity) and by
992 /// the predicate-pair injectivity test below (a new variant must
993 /// land in its own (replaces_failed, pauses_on_failure) bucket or
994 /// the author has to extend the consumer dispatch in
995 /// `tatara-pool-reconciler::desired::PoolConvergence::decide`).
996 pub const ALL: [Self; 3] = [Self::ReplaceImmediate, Self::HoldFailed, Self::PausePool];
997
998 /// Canonical PascalCase wire-format projection — matches the serde
999 /// `rename_all = "PascalCase"` output verbatim AND the CRD `enum:`
1000 /// enumeration the pool reconciler stamps on the
1001 /// `ephemeralpools.tatara.pleme.io` schema. Pinned by
1002 /// `replacement_policy_as_str_matches_serde` so a variant rename
1003 /// can't drift between the typed surface, the CRD enum, the YAML
1004 /// wire format AND the operator-facing diagnostic (the
1005 /// `desired.rs` Pause reason composes `policy={policy}` via
1006 /// Display, not a hard-coded `"PausePool"` literal that would
1007 /// silently rot).
1008 pub const fn as_str(self) -> &'static str {
1009 match self {
1010 Self::ReplaceImmediate => "ReplaceImmediate",
1011 Self::HoldFailed => "HoldFailed",
1012 Self::PausePool => "PausePool",
1013 }
1014 }
1015
1016 /// Should the pool auto-spawn a replacement for a Failed member?
1017 /// Closed-set match (not `matches!`) so a future variant triggers
1018 /// the compiler's exhaustiveness check at this site rather than
1019 /// silently defaulting to `false`. Paired with
1020 /// `pauses_on_failure` they form the two-axis projection
1021 /// consumers in `tatara-pool-reconciler::desired::PoolConvergence`
1022 /// pattern-match against — `replaces_failed` true ⇒ emit
1023 /// `ReapFailed` per failure; `pauses_on_failure` true with any
1024 /// failure ⇒ emit `Pause` and short-circuit. The pair is
1025 /// `(true, false) | (false, false) | (false, true)` — pinned
1026 /// injective by `replacement_policy_predicate_pair_is_injective`.
1027 pub const fn replaces_failed(self) -> bool {
1028 match self {
1029 Self::ReplaceImmediate => true,
1030 Self::HoldFailed | Self::PausePool => false,
1031 }
1032 }
1033
1034 /// Should reaching Failed on any member pause the whole pool?
1035 /// See `replaces_failed` for the closed-match rationale + the
1036 /// predicate-pair contract.
1037 pub const fn pauses_on_failure(self) -> bool {
1038 match self {
1039 Self::PausePool => true,
1040 Self::ReplaceImmediate | Self::HoldFailed => false,
1041 }
1042 }
1043}
1044
1045// `impl FromStr for ReplacementPolicy` + `impl tatara_lisp::ClosedSet for
1046// ReplacementPolicy` + `impl fmt::Display for ReplacementPolicy` are
1047// generated by `#[derive(tatara_closed_set::DeriveClosedSet)]` on the enum
1048// declaration above. `label` delegates to the inherent
1049// `ReplacementPolicy::as_str` via `#[closed_set(via = "as_str")]` so the
1050// PascalCase wire-format projection stays load-bearing (matches the
1051// serde `rename_all = "PascalCase"` output AND the
1052// `tatara-pool-reconciler::desired::PoolConvergence` Pause reason
1053// emission verbatim) while generic `T: ClosedSet` consumers reach the
1054// STABLE workspace-wide name (`label`); Display delegates to the same
1055// inherent projection via `#[closed_set(display)]` so the
1056// `Pause` reason emitter's `policy={policy}` composition stays
1057// pinned on the closed-set algebra rather than on a hand-rolled
1058// `fmt::Display` block per implementor.
1059
1060// `pub struct UnknownReplacementPolicy(pub String)` is generated by
1061// `#[derive(tatara_closed_set::DeriveClosedSet)]` + `#[closed_set(generate_unknown)]`
1062// on the enum declaration above. The auto-derived label
1063// `"replacement policy"` matches the prior hand-rolled
1064// `#[error("unknown replacement policy: {0}")]` verbatim. Symmetric to
1065// [`UnknownMemberState`], [`UnknownPoolPhase`], [`UnknownReturnPolicy`],
1066// [`crate::export::UnknownReportFormat`],
1067// [`crate::export::UnknownChannelKind`],
1068// [`crate::export::UnknownExportTrigger`],
1069// [`crate::lifetime::UnknownTeardownPolicy`],
1070// [`crate::boundary::UnknownConditionKind`], and
1071// [`crate::phase::UnknownPhase`].
1072
1073fn default_free_ttl() -> String {
1074 "24h".to_string()
1075}
1076fn default_max_allocation_ttl() -> String {
1077 "4h".to_string()
1078}
1079
1080/// `EphemeralPool.status` — observed pool population state.
1081#[derive(Clone, Debug, Default, Deserialize, Serialize, JsonSchema)]
1082#[serde(rename_all = "camelCase")]
1083pub struct PoolStatus {
1084 /// Pool lifecycle phase.
1085 #[serde(default)]
1086 pub phase: PoolPhase,
1087
1088 /// When the pool entered the current phase.
1089 #[serde(default, skip_serializing_if = "Option::is_none")]
1090 pub phase_since: Option<DateTime<Utc>>,
1091
1092 /// Number of members currently in `Free` state (ready for allocation).
1093 #[serde(default)]
1094 pub ready_count: u32,
1095
1096 /// Number of members currently `Allocated`.
1097 #[serde(default)]
1098 pub allocated_count: u32,
1099
1100 /// Number of members currently `Spawning` (not yet Attested).
1101 #[serde(default)]
1102 pub spawning_count: u32,
1103
1104 /// Number of members currently `Returning` (reset or replace
1105 /// in progress).
1106 #[serde(default)]
1107 pub returning_count: u32,
1108
1109 /// Member ledger — one entry per pool slot.
1110 #[serde(default)]
1111 pub members: Vec<PoolMember>,
1112
1113 /// Operator-visible message (e.g., "scaled down to floor").
1114 #[serde(default, skip_serializing_if = "Option::is_none")]
1115 pub message: Option<String>,
1116
1117 /// Standard Kubernetes Conditions.
1118 #[serde(default)]
1119 pub conditions: Vec<PoolCondition>,
1120}
1121
1122/// One pool slot's state.
1123#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)]
1124#[serde(rename_all = "camelCase")]
1125pub struct PoolMember {
1126 /// `metadata.name` of the backing Process.
1127 pub process_name: String,
1128 /// Pool member's current slot state.
1129 pub state: MemberState,
1130 /// When the member entered the current state.
1131 pub entered_state_at: DateTime<Utc>,
1132 /// If allocated: the AllocationRef holding this slot.
1133 #[serde(default, skip_serializing_if = "Option::is_none")]
1134 pub allocation_ref: Option<AllocationRef>,
1135}
1136
1137impl PoolStatus {
1138 /// Substrate constructor for the observed [`PoolStatus`] seed:
1139 /// composes the `(phase, phase_since, ready/allocated/spawning
1140 /// /returning counts, members, message, conditions)` 9-slot record
1141 /// every pool-reconciler status-patch site restated by hand pre-
1142 /// lift. The four counters ride a SINGLE closed-set-driven fold
1143 /// over the members list (one pass rather than four independent
1144 /// filter-and-count passes); the `message` + `conditions` slots
1145 /// stay at their invariant `None` / `vec![]` defaults every pre-
1146 /// lift caller stamped verbatim, and `phase_since` is derived from
1147 /// the caller-supplied `now` timestamp so the constructor stays
1148 /// clock-injectable rather than implicitly reading wall time.
1149 ///
1150 /// Pre-lift the 11-line
1151 /// ```rust,ignore
1152 /// PoolStatus {
1153 /// phase,
1154 /// phase_since: Some(Utc::now()),
1155 /// ready_count: count_state(&members, MemberState::Free),
1156 /// allocated_count: count_state(&members, MemberState::Allocated),
1157 /// spawning_count: count_state(&members, MemberState::Spawning),
1158 /// returning_count: count_state(&members, MemberState::Returning),
1159 /// members: members.clone(),
1160 /// message: None,
1161 /// conditions: vec![],
1162 /// }
1163 /// ```
1164 /// incantation was hand-authored at TWO sites past the ★★ PRIME-
1165 /// DIRECTIVE ≥ 2 duplication threshold in
1166 /// `tatara-pool-reconciler::controller_pool::reconcile_inner`,
1167 /// both restating the same 4-slot count fanout + defaults:
1168 /// * The `desired > 0` path — status patch after the
1169 /// convergence-action loop when the operator drives the pool
1170 /// through the R11 desired-count invariant.
1171 /// * The legacy allocation-driven path (`desired == 0`) — status
1172 /// patch after the [`crate::pool::PoolDecision`] apply loop.
1173 ///
1174 /// Both sites walked the SAME 4-slot count fanout on the SAME
1175 /// four `MemberState` variants (Free/Allocated/Spawning/Returning)
1176 /// and stamped the SAME defaults (`message: None`, `conditions:
1177 /// vec![]`), even though the four counters walked the members list
1178 /// four independent times pre-lift when a single pass suffices.
1179 /// Post-lift both callers write
1180 /// `PoolStatus::observed(phase, members, Utc::now())` and share
1181 /// ONE substrate owner; a future counter slot (e.g., a
1182 /// `warming_count` for a `MemberState::Warming` variant between
1183 /// Spawning and Free) plugs into the fold at ONE match arm and
1184 /// both status-patch sites inherit the new slot mechanically.
1185 ///
1186 /// The `Failed` variant is deliberately absent from the fold — no
1187 /// `PoolStatus` slot counts failed members (they surface via
1188 /// `pool_phase_from_members`'s `PoolPhase::Degraded` transition
1189 /// instead), and the closed-set match on
1190 /// [`MemberState`] pins that a future variant which SHOULD count
1191 /// toward one of the four buckets triggers the compiler's
1192 /// exhaustiveness check at this fold rather than silently sinking
1193 /// into `Failed`'s no-op arm.
1194 ///
1195 /// Theory anchor: THEORY.md §VI.1 (generation over composition —
1196 /// the 11-line status-seed incantation recurred at two hand-
1197 /// authored sites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication
1198 /// trigger, and is lifted to ONE owner here). THEORY.md §II.1
1199 /// invariant 5 (composition preserves proofs — the pins bind the
1200 /// 4-slot count fanout + the closed-set exhaustiveness on
1201 /// `MemberState` + the invariant defaults, so a regression that
1202 /// dropped a counter slot or swapped a variant surfaces at
1203 /// `tests::pool_status_observed_*` rather than as silent operator-
1204 /// facing skew between the two status-patch sites on the SAME
1205 /// pool).
1206 #[must_use]
1207 pub fn observed(phase: PoolPhase, members: Vec<PoolMember>, now: DateTime<Utc>) -> Self {
1208 let (ready_count, allocated_count, spawning_count, returning_count) =
1209 PoolMember::state_count_fanout(&members);
1210 Self {
1211 phase,
1212 phase_since: Some(now),
1213 ready_count,
1214 allocated_count,
1215 spawning_count,
1216 returning_count,
1217 members,
1218 message: None,
1219 conditions: vec![],
1220 }
1221 }
1222
1223 /// Wall-clock-anchored peer of [`Self::observed`] — the ONE
1224 /// substrate owner of the 4-arg `PoolStatus::observed(phase,
1225 /// members, Utc::now())` composition every pool-reconciler
1226 /// status-patch site that reads the wall clock at tick-time
1227 /// hand-authored pre-lift.
1228 ///
1229 /// # Why it exists
1230 ///
1231 /// Pre-lift the 4-arg `PoolStatus::observed(phase, members.clone(),
1232 /// chrono::Utc::now())` chain was hand-authored at TWO sites past the
1233 /// ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold in
1234 /// `tatara-pool-reconciler::controller_pool::reconcile_inner`, each
1235 /// pairing the 3-arg [`Self::observed`] composer with a
1236 /// `chrono::Utc::now()` third argument at the status-patch stamp:
1237 ///
1238 /// * The `desired > 0` path — status patch after the
1239 /// convergence-action loop when the operator drives the pool
1240 /// through the R11 desired-count invariant.
1241 /// * The legacy allocation-driven path (`desired == 0`) — status
1242 /// patch after the [`crate::pool::PoolDecision`] apply loop.
1243 ///
1244 /// Both sites walked the SAME 4-arg call with the SAME
1245 /// `chrono::Utc::now()` third argument — the wall-clock projection
1246 /// had no per-callsite variation. Post-lift both consumers share ONE
1247 /// substrate owner for the wall-clock-at-tick projection; a future
1248 /// clock swap (a monotonic clock cross-check, a per-reconciler
1249 /// injected time source, a test-only override at the production
1250 /// callsite via feature flag) lands at ONE substrate function and
1251 /// every pool-reconciler status-patch site inherits the upgrade
1252 /// mechanically.
1253 ///
1254 /// The 3-arg [`Self::observed`] peer stays load-bearing for test
1255 /// callers — the injected-`now` shape is what unit tests use to
1256 /// drive the clock deterministically (every
1257 /// `PoolStatus::observed(phase, members, seeded_now)` in this
1258 /// module's own test suite reads that surface). This peer is
1259 /// production-only: pinning the wall-clock at the substrate site
1260 /// means no test can accidentally consume it without the
1261 /// deterministic-clock injection that makes the test meaningful.
1262 ///
1263 /// Sibling of
1264 /// [`crate::lifetime_clock::evaluate_now`] on the (typed
1265 /// pure-fn, wall-clock-anchored peer) axis — both primitives own
1266 /// the "read the wall clock at tick-time" projection on a peer
1267 /// clock-injectable primitive so the workspace's timed-decision
1268 /// family stays uniform across `EphemeralLifetime` TTL expiry and
1269 /// `PoolStatus` observed-state stamp.
1270 ///
1271 /// # Invariants
1272 ///
1273 /// - **Same shape:** returns the SAME [`PoolStatus`] the 3-arg
1274 /// [`Self::observed`] returns when passed `chrono::Utc::now()` as
1275 /// the third argument. This is a delegation, not a
1276 /// re-implementation.
1277 /// - **Wall-clock read once:** `Utc::now()` is called exactly ONCE
1278 /// per invocation, at the primitive's body, so a future consumer
1279 /// that chains two `observed_now` calls back-to-back still sees
1280 /// monotonic `now` reads (each call reads a fresh instant, not a
1281 /// cached one) — matches the pre-lift shape where each of the two
1282 /// status-patch sites computed its own `chrono::Utc::now()` at its
1283 /// own line.
1284 ///
1285 /// # `#[must_use]`
1286 ///
1287 /// Every consumer feeds the returned [`PoolStatus`] into
1288 /// `tatara_process::patch::merge_status(&pool_api, &name, &<status>)`
1289 /// or a peer status-patch call. Dropping the return means the
1290 /// observation composed for no observable reason — the attribute
1291 /// surfaces that as a warning at every call site.
1292 ///
1293 /// Theory anchor: THEORY.md §VI.1 (generation over composition —
1294 /// the 4-arg call with `chrono::Utc::now()` as the third argument
1295 /// recurred at 2 hand-authored sites past the ★★ PRIME-DIRECTIVE
1296 /// ≥ 2 duplication trigger, lifted onto the ONE workspace-wide
1297 /// substrate owner here). THEORY.md §II.1 invariant 5 (composition
1298 /// preserves proofs — the wall-clock projection lives at ONE site
1299 /// so a future clock swap reaches both consumers through one edit).
1300 #[must_use]
1301 pub fn observed_now(phase: PoolPhase, members: Vec<PoolMember>) -> Self {
1302 Self::observed(phase, members, Utc::now())
1303 }
1304}
1305
1306impl PoolMember {
1307 /// Substrate primitive: single-pass closed-set fold over a
1308 /// `[PoolMember]` slice producing the `(ready, allocated,
1309 /// spawning, returning)` 4-tuple every `PoolStatus` seed stamps at
1310 /// its four counter slots. The `Failed` arm is a no-op (no
1311 /// `PoolStatus` counter tracks failed members — they surface via
1312 /// [`PoolPhase::Degraded`] instead), pinned by the closed-set
1313 /// match so a future variant that SHOULD count toward one of the
1314 /// four buckets triggers the compiler's exhaustiveness check here
1315 /// rather than silently falling through.
1316 ///
1317 /// Consumed by [`PoolStatus::observed`]. A caller that needs a
1318 /// single per-variant count outside the status-seed fanout should
1319 /// keep spelling `members.iter().filter(...).count()` rather than
1320 /// walking this 4-tuple — the fanout is shaped for the
1321 /// `PoolStatus` fill, not for arbitrary per-variant queries.
1322 #[must_use]
1323 pub fn state_count_fanout(members: &[Self]) -> (u32, u32, u32, u32) {
1324 let mut ready = 0u32;
1325 let mut allocated = 0u32;
1326 let mut spawning = 0u32;
1327 let mut returning = 0u32;
1328 for m in members {
1329 match m.state {
1330 MemberState::Free => ready += 1,
1331 MemberState::Allocated => allocated += 1,
1332 MemberState::Spawning => spawning += 1,
1333 MemberState::Returning => returning += 1,
1334 MemberState::Failed => {}
1335 }
1336 }
1337 (ready, allocated, spawning, returning)
1338 }
1339
1340 /// Substrate primitive: single-pass closed-set collection of the
1341 /// `process_name` axis over a `[PoolMember]` slice into an owned
1342 /// `HashSet<String>` — the O(1)-lookup shape every spawn-arm on
1343 /// the workspace builds pre-collision-check against a candidate
1344 /// [`crate::pool::PoolMember::process_name`] produced by
1345 /// [`tatara-pool-reconciler::naming::member_process_name`].
1346 ///
1347 /// Pre-lift the 2-line
1348 /// `members.iter().map(|m| m.process_name.clone()).collect()`
1349 /// chain was hand-authored at TWO sites past the ★★ PRIME-
1350 /// DIRECTIVE ≥ 2 duplication threshold in
1351 /// `tatara-pool-reconciler::controller_pool`, both restating the
1352 /// SAME `process_name` projection through the SAME
1353 /// `iter → map → collect` shape and both feeding a `.contains
1354 /// (&candidate)` probe:
1355 /// * `reconcile_inner`'s legacy allocation-driven
1356 /// `PoolDecision::Spawn` arm (`desired == 0` path) —
1357 /// collision-set for
1358 /// `member_process_name(&pool_name, &pool_uid, slot)` per spawn
1359 /// slot.
1360 /// * `apply_convergence_actions` — collision-set for the SAME
1361 /// composer inside the R11 desired-count
1362 /// `ConvergenceAction::CreateMember` loop.
1363 ///
1364 /// Post-lift both consumers share ONE substrate owner; the
1365 /// composed `HashSet<String>` still feeds the same
1366 /// `HashSet::<String>::contains(&candidate)` probe at each
1367 /// callsite unchanged. A future normalization step on the
1368 /// occupied-name axis (case-fold before insertion, a per-cluster
1369 /// prefix strip, deduplication against a sibling stale-name
1370 /// registry, exclusion of `Returning`/`Failed` members that no
1371 /// longer own their slot) lands at ONE substrate method rather
1372 /// than being restated at each callsite.
1373 ///
1374 /// Sibling to [`Self::state_count_fanout`] on the `(collection
1375 /// shape × slice-owned fold)` axis: both primitives fold a
1376 /// `[PoolMember]` slice into one caller-shaped aggregate in a
1377 /// single pass, both are `#[must_use]`, both take the slice by
1378 /// reference so no caller has to reshape its `Vec<PoolMember>` or
1379 /// `Vec<PoolMember>` slice upstream.
1380 ///
1381 /// Theory anchor: THEORY.md §VI.1 (generation over composition —
1382 /// the `HashSet<String>` collision-set shape recurred at TWO
1383 /// hand-authored sites past the ★★ PRIME-DIRECTIVE ≥ 2
1384 /// duplication trigger, and is lifted to ONE owner here).
1385 /// THEORY.md §II.1 invariant 5 (composition preserves proofs —
1386 /// the pins bind the axis (`process_name`), the aggregate shape
1387 /// (`HashSet<String>`), the empty-slice corner, and the
1388 /// duplicate-name deduplication semantics `HashSet` provides
1389 /// implicitly, so a regression at any of those surfaces at
1390 /// `tests::process_names_set_*` rather than as silent occupied-
1391 /// slot skew at either spawn arm).
1392 #[must_use]
1393 pub fn process_names_set(members: &[Self]) -> std::collections::HashSet<String> {
1394 members.iter().map(|m| m.process_name.clone()).collect()
1395 }
1396
1397 /// Substrate composer for the unallocated `PoolMember` seed: the
1398 /// 4-slot `{ process_name, state, entered_state_at, allocation_ref:
1399 /// None }` fixture literal every non-`Allocated`-role callsite
1400 /// stamped by hand pre-lift.
1401 ///
1402 /// Pre-lift the 4-slot struct literal `PoolMember { process_name,
1403 /// state, entered_state_at, allocation_ref: None }` was hand-authored
1404 /// at FIVE workspace-wide sites past the ★★ PRIME-DIRECTIVE ≥ 2
1405 /// duplication threshold across TWO crates:
1406 /// * `tatara-pool-reconciler::controller_pool::reconcile_inner` —
1407 /// the production per-owned-Process seed built inside the
1408 /// `for p in all_processes.items` walk; `entered_state_at` rides
1409 /// in from [`crate::prelude::Process::observed_phase_since`] with
1410 /// the `Utc::now` fallback at the callsite.
1411 /// * `tatara-pool-reconciler::pool_decide::tests::member` — test
1412 /// helper for the pool decision suite; `entered_state_at` rides
1413 /// in from [`crate::time::seconds_ago`].
1414 /// * `tatara-pool-reconciler::allocation_decide::tests::member` —
1415 /// test helper for the allocation decision suite;
1416 /// `entered_state_at` rides in from `Utc::now`.
1417 /// * `tatara-process::pool::tests::member` — test helper for the
1418 /// fanout / status suite; `entered_state_at` rides in from the
1419 /// epoch anchor `DateTime::<Utc>::from_timestamp(0, 0)`.
1420 /// * `tatara-process::pool::tests::named_member` — test helper for
1421 /// the `process_names_set` suite; same epoch anchor.
1422 ///
1423 /// Every one of those FIVE sites pinned `allocation_ref: None`
1424 /// verbatim — no `PoolMember` construction site in the workspace
1425 /// pairs `allocation_ref: Some(<ref>)` with a hand-authored 4-slot
1426 /// struct literal, so this composer's `None` slot is safe by
1427 /// construction (the compiler exhaustiveness check on the struct's
1428 /// four fields catches a future 5th slot addition here rather than
1429 /// at any of the callsites).
1430 ///
1431 /// Post-lift every consumer writes
1432 /// `PoolMember::unallocated(<name>, <state>, <anchor>)` and shares
1433 /// ONE substrate owner; a future promotion of the unallocated shape
1434 /// (a per-cluster clock-skew guard on the `entered_state_at`
1435 /// anchor, a canonical rename of the None-slot to a typed
1436 /// `Unallocated` marker, a lint-friendly closed-set restriction to
1437 /// the four `MemberState` variants that legitimately carry no
1438 /// `allocation_ref`) lands at ONE substrate site and every downstream
1439 /// consumer inherits the upgrade mechanically.
1440 ///
1441 /// `impl Into<String>` accepts both `&str` literals (every test
1442 /// helper site) and owned `String` produced by
1443 /// [`crate::prelude::Process::owned_name_or_empty`] (the production
1444 /// controller-pool site) without widening the signature.
1445 ///
1446 /// Sibling to [`AllocationRef::new`] on the substrate-composer
1447 /// axis: both take `impl Into<String>`-gated identity slots and
1448 /// return their owner-type by value; [`AllocationRef::new`] owns
1449 /// the (name, namespace) pair, this composer owns the four-slot
1450 /// unallocated-member seed.
1451 ///
1452 /// Theory anchor: THEORY.md §VI.1 (generation over composition —
1453 /// the 4-slot unallocated-`PoolMember` seed recurred at FIVE hand-
1454 /// authored sites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication
1455 /// trigger, and is lifted to ONE owner here). THEORY.md §II.1
1456 /// invariant 5 (composition preserves proofs — the pins bind the
1457 /// four-slot fill AND the `allocation_ref: None` invariant AND the
1458 /// caller-clock-injectability of `entered_state_at`, so a
1459 /// regression that drifts any surface fails at
1460 /// `tests::pool_member_unallocated_*` rather than as silent
1461 /// operator-facing skew between the production controller-pool seed
1462 /// and the three test-suite helpers on the SAME `PoolMember`
1463 /// shape).
1464 #[must_use]
1465 pub fn unallocated(
1466 process_name: impl Into<String>,
1467 state: MemberState,
1468 entered_state_at: DateTime<Utc>,
1469 ) -> Self {
1470 Self {
1471 process_name: process_name.into(),
1472 state,
1473 entered_state_at,
1474 allocation_ref: None,
1475 }
1476 }
1477}
1478
1479/// Light reference to an `EphemeralAllocation`.
1480#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema, PartialEq, Eq)]
1481#[serde(rename_all = "camelCase")]
1482pub struct AllocationRef {
1483 pub name: String,
1484 pub namespace: String,
1485}
1486
1487impl AllocationRef {
1488 /// Substrate constructor for [`AllocationRef`]: composes the
1489 /// `(name, namespace)` pair through ONE `impl Into<String>`-gated
1490 /// entry point — the ONE-liner collapse of the paired
1491 /// `AllocationRef { name: n.into(), namespace: ns.into() }`
1492 /// struct-literal incantation every downstream consumer restated
1493 /// by hand pre-lift.
1494 ///
1495 /// Pre-lift the `AllocationRef { name, namespace }` struct-literal
1496 /// was hand-authored at FOUR production sites past the ★★ PRIME-
1497 /// DIRECTIVE ≥ 2 duplication threshold across the workspace, all
1498 /// composing an owned `(name: String, namespace: String)` pair
1499 /// under one of two roles:
1500 /// * `tatara-pool-reconciler::controller_allocation::reconcile_inner`
1501 /// Bind path — the `assignedProcess` status slot's ref, pairing
1502 /// the just-bound member Process name with the allocation's
1503 /// containing namespace.
1504 /// * `tatara-pool-reconciler::controller_allocation::reconcile_inner`
1505 /// Release path — the same `assignedProcess` slot shape, stamped
1506 /// at the release-side status patch alongside the (unchanged)
1507 /// `boundPool` ref.
1508 /// * `tatara-pool-reconciler::allocation_decide::AllocationConvergenceCtx::observe`
1509 /// pool-matched handle — the `matched_pool` slot's ref, pairing
1510 /// [`EphemeralPool::owned_name_or_empty`] with the pool's
1511 /// containing namespace.
1512 /// * `tatara-github-watcher::allocation_factory::allocation_from_pr`
1513 /// — the `pool_ref` slot on the `AllocationSpec` emitted from a
1514 /// PullRequestEvent, pairing the operator-configured pool name
1515 /// with the watcher's target namespace.
1516 ///
1517 /// All FOUR sites walked the SAME two-field struct-literal shape
1518 /// — an owned name half, an owned namespace half — differing only
1519 /// in provenance. Post-lift each callsite reads
1520 /// `AllocationRef::new(name, ns)` and the produced value feeds the
1521 /// same downstream slot (`assignedProcess` / `bound_pool` /
1522 /// `matched_pool` / `spec.pool_ref`) unchanged. The `impl Into<String>`
1523 /// signature accepts every provenance the pre-lift sites carried —
1524 /// owned `String` (the reconciler's owned-form projections), `&str`
1525 /// (the factory's `n.to_string()` / `namespace.to_string()`
1526 /// borrow-to-owned promotions), `Cow<str>`, and every other
1527 /// `Into<String>` implementor — so no callsite has to change its
1528 /// upstream provenance to route through the primitive.
1529 ///
1530 /// Return-form axis: owned [`AllocationRef`] — the wire-format
1531 /// shape [`crate::pool::AllocationRef`]'s serde `rename_all =
1532 /// "camelCase"` produces on both spec (`poolRef`) and status
1533 /// (`boundPool` / `assignedProcess`) slots. The primitive owns
1534 /// the axis-order `(name, namespace)` — the same order the four
1535 /// consumers spelled — so a slot swap surfaces at the
1536 /// `allocation_ref_new_positional_axis_order` pin below rather
1537 /// than as silent `<namespace>/<name>` inversion downstream.
1538 ///
1539 /// Peer to the sibling substrate primitives already opened on the
1540 /// pool-side (name, namespace) axis pair:
1541 /// [`EphemeralPool::name_or_empty`] (borrow-form name),
1542 /// [`EphemeralPool::owned_name_or_empty`] (owned-form name); this
1543 /// constructor is the composer that folds the owned-form projections
1544 /// into the wire-format ref shape.
1545 ///
1546 /// A future refactor of [`AllocationRef`]'s field set (a
1547 /// `resource_kind: String` field for cross-CRD refs, an
1548 /// `api_version: String` field for FQN references, a
1549 /// canonicalization pass over the namespace half, a non-empty-name
1550 /// gate) lands at ONE substrate constructor site here and every
1551 /// downstream consumer inherits the upgrade mechanically — no per-
1552 /// callsite hand-edit at the FOUR reconciler + factory sites.
1553 ///
1554 /// Theory anchor: THEORY.md §VI.1 (generation over composition —
1555 /// the `AllocationRef { name, namespace }` struct-literal shape
1556 /// recurred at four hand-authored sites past the ★★ PRIME-
1557 /// DIRECTIVE ≥ 2 duplication trigger, and is lifted to ONE owner
1558 /// here). THEORY.md §II.1 invariant 5 (composition preserves
1559 /// proofs — the pins bind the positional axis-order + the
1560 /// `Into<String>` provenance closure + byte-identical parity with
1561 /// the pre-lift struct-literal + `PartialEq` coherence with the
1562 /// hand-authored form, so a regression that reshaped any surface
1563 /// at `tests::allocation_ref_new_*` rather than as silent
1564 /// operator-facing skew between the assignedProcess / bound_pool
1565 /// / matched_pool / spec.pool_ref slots on the SAME allocation).
1566 #[must_use]
1567 pub fn new(name: impl Into<String>, namespace: impl Into<String>) -> Self {
1568 Self {
1569 name: name.into(),
1570 namespace: namespace.into(),
1571 }
1572 }
1573}
1574
1575/// Per-slot state in the pool's free list.
1576///
1577/// Sibling closed-sets on the `EphemeralPool` axis: [`ReplacementPolicy::ALL`]
1578/// (the on-failure policy that the pool reconciler dispatches against
1579/// the [`Self::is_failed`] projection), [`ReturnPolicy::ALL`] (the
1580/// release-time disposition that transitions an [`Self::Allocated`]
1581/// member into [`Self::Returning`] before it either re-enters
1582/// [`Self::Free`] or gets [`Self::Spawning`]'d as a fresh slot).
1583#[derive(
1584 Clone,
1585 Copy,
1586 Debug,
1587 PartialEq,
1588 Eq,
1589 Hash,
1590 Serialize,
1591 Deserialize,
1592 JsonSchema,
1593 tatara_closed_set::DeriveClosedSet,
1594)]
1595#[serde(rename_all = "PascalCase")]
1596#[closed_set(via = "as_str", generate_unknown, display)]
1597pub enum MemberState {
1598 /// Pool reconciler is creating/converging the backing Process.
1599 Spawning,
1600 /// Process is `Attested`; ready for allocation.
1601 Free,
1602 /// Held by an `EphemeralAllocation`.
1603 Allocated,
1604 /// Return policy is being applied (Reset → reset Job; Replace →
1605 /// Process is being torn down and recreated).
1606 Returning,
1607 /// Permanent failure — the member needs operator attention.
1608 Failed,
1609}
1610
1611impl MemberState {
1612 /// The closed set of member states — single source of truth that
1613 /// drives the `as_str` / Display / `FromStr` triad AND the
1614 /// `is_failed` / `counts_toward_supply` predicate pair. Adding a
1615 /// sixth variant lands at one `ALL` entry + one `as_str` arm + one
1616 /// arm per predicate — exhaustively checked by the compiler (the
1617 /// `[Self; 5]` array literal forces the arity) and by the
1618 /// per-variant truth-table contract test (a new variant must
1619 /// declare its own `(is_failed, counts_toward_supply)` projection
1620 /// or the consumer dispatch in
1621 /// `tatara-pool-reconciler::controller_pool::pool_phase_from_members`
1622 /// and `tatara-pool-reconciler::pool_decide::decide_pool_reconcile`
1623 /// will silently bucket it into the wrong lifecycle column).
1624 pub const ALL: [Self; 5] = [
1625 Self::Spawning,
1626 Self::Free,
1627 Self::Allocated,
1628 Self::Returning,
1629 Self::Failed,
1630 ];
1631
1632 /// Canonical PascalCase wire-format projection — matches the serde
1633 /// `rename_all = "PascalCase"` output verbatim AND the CRD `enum:`
1634 /// enumeration that `ephemeralpools.tatara.pleme.io` stamps on
1635 /// `status.members[].state`. Pinned by
1636 /// `member_state_as_str_matches_serde` so a variant rename can't
1637 /// drift between the typed surface, the CRD enum, the YAML wire
1638 /// format AND any future operator-facing diagnostic that composes
1639 /// `state={state}` via Display rather than a hard-coded literal
1640 /// that would silently rot.
1641 pub const fn as_str(self) -> &'static str {
1642 match self {
1643 Self::Spawning => "Spawning",
1644 Self::Free => "Free",
1645 Self::Allocated => "Allocated",
1646 Self::Returning => "Returning",
1647 Self::Failed => "Failed",
1648 }
1649 }
1650
1651 /// Is this member in a permanent-failure state — needs operator
1652 /// attention? Closed-set match (not `matches!`) so a future variant
1653 /// triggers the compiler's exhaustiveness check at this site rather
1654 /// than silently defaulting to `false`. Consumed by
1655 /// `tatara-pool-reconciler::pool_decide::decide_pool_reconcile` to
1656 /// gate the highest-priority `ReplaceMembers` decision branch — a
1657 /// future variant that should also trigger replacement (e.g.
1658 /// `MemberState::Quarantined`) flips this predicate at one site
1659 /// and inherits the priority-1 dispatch without touching the
1660 /// consumer match arm.
1661 pub const fn is_failed(self) -> bool {
1662 match self {
1663 Self::Failed => true,
1664 Self::Spawning | Self::Free | Self::Allocated | Self::Returning => false,
1665 }
1666 }
1667
1668 /// Does this member contribute to the pool's *available supply*
1669 /// (current ready slots + slots coming online)? Closed-set match so
1670 /// a future variant triggers the compiler's exhaustiveness check.
1671 /// Consumed by
1672 /// `tatara-pool-reconciler::controller_pool::pool_phase_from_members`
1673 /// — the `(free + spawning)` supply calc collapses into one
1674 /// predicate-driven filter, so a future "warming-up" state
1675 /// (`MemberState::Warming` between Spawning and Free) plugs into
1676 /// the supply count at one site rather than three. Disjoint with
1677 /// `is_failed` — pinned by `member_state_failed_implies_no_supply`
1678 /// (a Failed member can never count toward supply; the pool
1679 /// reconciler would otherwise double-count failures as available
1680 /// capacity).
1681 pub const fn counts_toward_supply(self) -> bool {
1682 match self {
1683 Self::Free | Self::Spawning => true,
1684 Self::Allocated | Self::Returning | Self::Failed => false,
1685 }
1686 }
1687}
1688
1689// `impl FromStr for MemberState` + `impl tatara_lisp::ClosedSet for
1690// MemberState` + `impl fmt::Display for MemberState` are generated by
1691// `#[derive(tatara_closed_set::DeriveClosedSet)]` on the enum declaration
1692// above. `label` delegates to the inherent `MemberState::as_str` via
1693// `#[closed_set(via = "as_str")]` so the
1694// `pool_phase_from_members` supply calc can keep keying on
1695// `counts_toward_supply` against the typed variant while a generic
1696// `T: ClosedSet` consumer reaches the STABLE workspace-wide name
1697// (`label`) without knowing this enum lives in `tatara-process::pool`;
1698// Display delegates to the same inherent projection via
1699// `#[closed_set(display)]` so the diagnostic emitter's
1700// `state={state}` composition stays pinned on the closed-set algebra.
1701
1702// `pub struct UnknownMemberState(pub String)` is generated by
1703// `#[derive(tatara_closed_set::DeriveClosedSet)]` + `#[closed_set(generate_unknown)]`
1704// on the enum declaration above. The auto-derived label `"member state"`
1705// matches the prior hand-rolled `#[error("unknown member state: {0}")]`
1706// verbatim. Symmetric to [`UnknownReplacementPolicy`],
1707// [`UnknownPoolPhase`], [`UnknownReturnPolicy`],
1708// [`crate::lifetime::UnknownTeardownPolicy`],
1709// [`crate::boundary::UnknownConditionKind`], and
1710// [`crate::phase::UnknownPhase`].
1711
1712/// Pool lifecycle phase (observed across the whole pool population).
1713///
1714/// Sibling closed-set on the same `EphemeralPool` axis as
1715/// [`MemberState::ALL`] (the per-slot lifecycle this phase aggregates
1716/// over via [`MemberState::counts_toward_supply`]),
1717/// [`ReplacementPolicy::ALL`] (on-failure policy) and
1718/// [`ReturnPolicy::ALL`] (release-time disposition). Together with
1719/// `MemberState`, this closes the pool reconciler's
1720/// `(slot-state, pool-phase)` two-tier observation algebra on the
1721/// same closed-set discipline as the rest of `tatara-process`.
1722#[derive(
1723 Clone,
1724 Copy,
1725 Debug,
1726 PartialEq,
1727 Eq,
1728 Hash,
1729 Serialize,
1730 Deserialize,
1731 JsonSchema,
1732 tatara_closed_set::DeriveClosedSet,
1733)]
1734#[serde(rename_all = "PascalCase")]
1735#[closed_set(via = "as_str", generate_unknown, display)]
1736pub enum PoolPhase {
1737 /// Just admitted; no members yet.
1738 Initializing,
1739 /// `ready_count == desired_size`.
1740 Steady,
1741 /// `ready_count + spawning_count < desired_size` and reconciler
1742 /// is creating new members.
1743 ScalingUp,
1744 /// `ready_count > desired_size` and reconciler is reaping excess.
1745 ScalingDown,
1746 /// `min_size` constraint violated.
1747 Degraded,
1748 /// Pool is being deleted; reconciler is reaping all members.
1749 Draining,
1750}
1751
1752impl Default for PoolPhase {
1753 fn default() -> Self {
1754 Self::Initializing
1755 }
1756}
1757
1758impl PoolPhase {
1759 /// The closed set of pool phases — single source of truth that
1760 /// drives the `as_str` / Display / `FromStr` triad AND the
1761 /// `is_steady` / `is_terminal` predicate pair. Adding a seventh
1762 /// variant lands at one `ALL` entry + one `as_str` arm + one arm
1763 /// per predicate — exhaustively checked by the compiler (the
1764 /// `[Self; 6]` array literal forces the arity) AND by the
1765 /// per-variant truth-table contract test (a new variant must
1766 /// declare its own `(is_steady, is_terminal)` projection or any
1767 /// future status-aggregator surface — `feira pool list
1768 /// --healthy`, the operator-facing condition aggregator, the
1769 /// desired-loop heartbeat short-circuit — will silently bucket
1770 /// it into the wrong lifecycle column).
1771 pub const ALL: [Self; 6] = [
1772 Self::Initializing,
1773 Self::Steady,
1774 Self::ScalingUp,
1775 Self::ScalingDown,
1776 Self::Degraded,
1777 Self::Draining,
1778 ];
1779
1780 /// Canonical PascalCase wire-format projection — matches the
1781 /// serde `rename_all = "PascalCase"` output verbatim AND the CRD
1782 /// `enum:` enumeration that `ephemeralpools.tatara.pleme.io`
1783 /// stamps on `status.phase`. Pinned by
1784 /// `pool_phase_as_str_matches_serde` so a variant rename can't
1785 /// drift between the typed surface, the CRD enum, the YAML wire
1786 /// format AND any future operator-facing diagnostic that
1787 /// composes `phase={phase}` via Display rather than a hard-coded
1788 /// literal that would silently rot. Display + FromStr triad
1789 /// over `ALL` mirrors `MemberState` / `ReplacementPolicy` /
1790 /// `ReturnPolicy` / `AllocationPhase` / `TeardownPolicy` /
1791 /// `ConditionKind` / `ProcessPhase` / `ProcessSignal`.
1792 pub const fn as_str(self) -> &'static str {
1793 match self {
1794 Self::Initializing => "Initializing",
1795 Self::Steady => "Steady",
1796 Self::ScalingUp => "ScalingUp",
1797 Self::ScalingDown => "ScalingDown",
1798 Self::Degraded => "Degraded",
1799 Self::Draining => "Draining",
1800 }
1801 }
1802
1803 /// Is the pool fully converged — supply matches desired, no
1804 /// reconciler-driven population change pending? Closed-set match
1805 /// (not `matches!`) so a future variant triggers the compiler's
1806 /// exhaustiveness check at this site rather than silently
1807 /// defaulting to `false`. Paired with `is_terminal` they form
1808 /// the two-axis projection that future status aggregators
1809 /// (operator-facing fleet health, `feira pool list --healthy`,
1810 /// the SSE filter "show non-steady pools") dispatch against —
1811 /// `is_steady && !is_terminal` ⇒ converged (goal state);
1812 /// `!is_steady && is_terminal` ⇒ being deleted (no future
1813 /// spawn); `!is_steady && !is_terminal` ⇒ transient
1814 /// (Initializing | ScalingUp | ScalingDown | Degraded — pool
1815 /// is in motion toward desired). The impossible bucket
1816 /// `(true, true)` — a draining pool that's somehow also steady
1817 /// — is pinned empty by `pool_phase_steady_excludes_terminal`.
1818 pub const fn is_steady(self) -> bool {
1819 match self {
1820 Self::Steady => true,
1821 Self::Initializing
1822 | Self::ScalingUp
1823 | Self::ScalingDown
1824 | Self::Degraded
1825 | Self::Draining => false,
1826 }
1827 }
1828
1829 /// Is the pool in its absorbing exit state — deletion-stamped,
1830 /// reconciler is reaping every member, no spawn will ever
1831 /// happen again? Closed-set match so a future variant triggers
1832 /// the compiler's exhaustiveness check. See `is_steady` for the
1833 /// predicate-pair contract + bucket definitions.
1834 pub const fn is_terminal(self) -> bool {
1835 match self {
1836 Self::Draining => true,
1837 Self::Initializing
1838 | Self::Steady
1839 | Self::ScalingUp
1840 | Self::ScalingDown
1841 | Self::Degraded => false,
1842 }
1843 }
1844}
1845
1846// `impl FromStr for PoolPhase` + `impl tatara_lisp::ClosedSet for PoolPhase`
1847// + `impl fmt::Display for PoolPhase` are generated by
1848// `#[derive(tatara_closed_set::DeriveClosedSet)]` on the enum declaration above.
1849// `label` delegates to the inherent `PoolPhase::as_str` via
1850// `#[closed_set(via = "as_str")]` so the operator-facing
1851// `phase={phase}` Display composition keeps reading the same canonical
1852// PascalCase projection while a generic `T: ClosedSet` consumer (a
1853// status-aggregator filter, the `feira pool list --healthy` predicate, a
1854// future SSE event router) can walk every variant without knowing the
1855// closed set lives in `tatara-process::pool`; Display delegates to the
1856// same inherent projection via `#[closed_set(display)]` so the
1857// `phase={phase}` composition stays pinned on the closed-set algebra
1858// rather than a hand-rolled `fmt::Display` block.
1859
1860// `pub struct UnknownPoolPhase(pub String)` is generated by
1861// `#[derive(tatara_closed_set::DeriveClosedSet)]` + `#[closed_set(generate_unknown)]`
1862// on the enum declaration above. The auto-derived label `"pool phase"`
1863// matches the prior hand-rolled `#[error("unknown pool phase: {0}")]`
1864// verbatim. Symmetric to [`UnknownMemberState`],
1865// [`UnknownReplacementPolicy`], [`UnknownReturnPolicy`],
1866// [`crate::lifetime::UnknownTeardownPolicy`],
1867// [`crate::boundary::UnknownConditionKind`], and
1868// [`crate::phase::UnknownPhase`].
1869
1870/// Standard K8s Condition shape (kept local so tatara-process doesn't
1871/// depend on k8s_openapi types in its public schema).
1872#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)]
1873#[serde(rename_all = "camelCase")]
1874pub struct PoolCondition {
1875 pub type_: String,
1876 pub status: String,
1877 pub reason: String,
1878 pub message: String,
1879 pub last_transition_time: DateTime<Utc>,
1880}
1881
1882/// What the pool does when an allocation releases a member.
1883///
1884/// Sibling closed-set on the `EphemeralPool` axis:
1885/// [`ReplacementPolicy::ALL`]. Sibling closed-sets on the
1886/// `tatara-process` algebra: [`crate::lifetime::TeardownPolicy::ALL`]
1887/// (the *release*-time counterpart for non-pooled ephemeral envs),
1888/// [`crate::boundary::ConditionKind::ALL`],
1889/// [`crate::lifetime::LifetimeKind::ALL`],
1890/// [`crate::intent::IntentKind::ALL`],
1891/// [`crate::phase::ProcessPhase::ALL`],
1892/// [`crate::signal::ProcessSignal::ALL`].
1893#[derive(
1894 Clone,
1895 Copy,
1896 Debug,
1897 Hash,
1898 PartialEq,
1899 Eq,
1900 Serialize,
1901 Deserialize,
1902 JsonSchema,
1903 Default,
1904 tatara_closed_set::DeriveClosedSet,
1905)]
1906#[serde(rename_all = "PascalCase")]
1907#[closed_set(via = "as_str", generate_unknown, display)]
1908pub enum ReturnPolicy {
1909 /// Tear down the Process + create a fresh one. Safe but slow
1910 /// (1-2 min spin-up before the slot is Free again).
1911 #[default]
1912 Replace,
1913 /// Keep the Process running; run a typed `:reset` Job that wipes
1914 /// state (DB drop, secrets rotate). Fast (~5-10s) but depends on
1915 /// the reset Job being correct for the workload. API-authoritative
1916 /// systems are natural fits because the control API owns all state.
1917 Reset,
1918 /// Keep the Process indefinitely after release (debugging aid;
1919 /// operator must `feira pool reap NAME` to clean up). Useful for
1920 /// post-mortem of a flaky test.
1921 Keep,
1922}
1923
1924impl ReturnPolicy {
1925 /// The closed set of return policies — single source of truth that
1926 /// drives the `as_str` / Display / `FromStr` triad and the
1927 /// `keeps_process` / `runs_reset_job` predicate pair. Adding a
1928 /// fourth variant lands at one `ALL` entry + one `as_str` arm +
1929 /// one arm per predicate — exhaustively checked by the compiler
1930 /// (the `[Self; 3]` array literal forces the arity) and by the
1931 /// predicate-pair injectivity test (a new variant must land in
1932 /// its own (keeps_process, runs_reset_job) bucket or the author
1933 /// has to extend the consumer dispatch in
1934 /// `tatara-pool-reconciler::return_policy::plan_return`).
1935 pub const ALL: [Self; 3] = [Self::Replace, Self::Reset, Self::Keep];
1936
1937 /// Canonical PascalCase wire-format projection — matches the
1938 /// serde `rename_all = "PascalCase"` output verbatim AND the CRD
1939 /// `enum:` enumeration the pool reconciler stamps on the
1940 /// `ephemeralpools.tatara.pleme.io` schema. Pinned by
1941 /// `return_policy_as_str_matches_serde` so a variant rename can't
1942 /// drift between the typed surface, the CRD enum, the YAML wire
1943 /// format AND any future operator-facing diagnostic that composes
1944 /// `policy={policy}` via Display rather than a hard-coded literal.
1945 pub const fn as_str(self) -> &'static str {
1946 match self {
1947 Self::Replace => "Replace",
1948 Self::Reset => "Reset",
1949 Self::Keep => "Keep",
1950 }
1951 }
1952
1953 /// Does the pool keep the backing Process alive across release?
1954 /// Closed-set match (not `matches!`) so a future variant triggers
1955 /// the compiler's exhaustiveness check at this site rather than
1956 /// silently defaulting to `false`. Paired with `runs_reset_job`
1957 /// they form the two-axis projection that the consumer in
1958 /// `tatara-pool-reconciler::return_policy::plan_return` matches
1959 /// against — `keeps_process` false ⇒ `DeleteAndRespawn`;
1960 /// `keeps_process && runs_reset_job` ⇒ `ResetThenFree`;
1961 /// `keeps_process && !runs_reset_job` ⇒ `KeepForInspection`. The
1962 /// pair is `(false, false) | (true, true) | (true, false)` —
1963 /// pinned injective by
1964 /// `return_policy_predicate_pair_is_injective`.
1965 pub const fn keeps_process(self) -> bool {
1966 match self {
1967 Self::Replace => false,
1968 Self::Reset | Self::Keep => true,
1969 }
1970 }
1971
1972 /// Does the policy run a typed `:reset` Job to wipe state in
1973 /// place? See `keeps_process` for the closed-match rationale +
1974 /// the predicate-pair contract.
1975 pub const fn runs_reset_job(self) -> bool {
1976 match self {
1977 Self::Reset => true,
1978 Self::Replace | Self::Keep => false,
1979 }
1980 }
1981}
1982
1983// `impl FromStr for ReturnPolicy` + `impl tatara_lisp::ClosedSet for
1984// ReturnPolicy` + `impl fmt::Display for ReturnPolicy` are generated by
1985// `#[derive(tatara_closed_set::DeriveClosedSet)]` on the enum declaration
1986// above. `label` delegates to the inherent `ReturnPolicy::as_str` via
1987// `#[closed_set(via = "as_str")]` so the
1988// `tatara-pool-reconciler::return_policy::plan_return` dispatch keeps
1989// reading the canonical PascalCase projection that matches the CRD
1990// `enum:` literal verbatim, while a generic `T: ClosedSet` consumer
1991// plugs in without knowing the enum lives in `tatara-process::pool`;
1992// Display delegates to the same inherent projection via
1993// `#[closed_set(display)]` so the `policy={policy}` diagnostic
1994// composition stays pinned on the closed-set algebra.
1995
1996// `pub struct UnknownReturnPolicy(pub String)` is generated by
1997// `#[derive(tatara_closed_set::DeriveClosedSet)]` + `#[closed_set(generate_unknown)]`
1998// on the enum declaration above. The auto-derived label `"return policy"`
1999// matches the prior hand-rolled `#[error("unknown return policy: {0}")]`
2000// verbatim. Symmetric to [`UnknownReplacementPolicy`],
2001// [`UnknownMemberState`], [`UnknownPoolPhase`],
2002// [`crate::lifetime::UnknownTeardownPolicy`],
2003// [`crate::boundary::UnknownConditionKind`], and
2004// [`crate::phase::UnknownPhase`].
2005
2006/// Routing selector — matches an `EphemeralAllocation`'s requestor
2007/// against pool-eligibility predicates.
2008#[derive(Clone, Debug, Default, Deserialize, Serialize, JsonSchema)]
2009#[serde(rename_all = "camelCase")]
2010pub struct PoolSelector {
2011 /// Glob-matched against `EphemeralAllocation.spec.requestor.repo`.
2012 /// Empty = match every repo.
2013 #[serde(default)]
2014 pub repos: Vec<String>,
2015
2016 /// Glob-matched against `EphemeralAllocation.spec.requestor.branch`.
2017 /// Empty = match every branch.
2018 #[serde(default)]
2019 pub branches: Vec<String>,
2020
2021 /// PR labels (all-must-match, AND semantics). Empty = no label
2022 /// requirement.
2023 #[serde(default)]
2024 pub pr_labels: Vec<String>,
2025
2026 /// Allocation `kind` strings this pool can serve (e.g., "github-pr",
2027 /// "manual", "ci-run"). Empty = any kind.
2028 #[serde(default)]
2029 pub kinds: Vec<String>,
2030}
2031
2032impl PoolSelector {
2033 /// Does this selector match the given allocation routing key?
2034 /// Pure: no side effects.
2035 pub fn matches(&self, key: &MatchKey<'_>) -> bool {
2036 glob_any(&self.repos, key.repo)
2037 && glob_any(&self.branches, key.branch)
2038 && labels_subset(&self.pr_labels, key.pr_labels)
2039 && kind_any(&self.kinds, key.kind)
2040 }
2041
2042 /// Specificity score — higher = more specific. Used by the
2043 /// reconciler to break ties between selectors that all match.
2044 pub fn specificity(&self) -> u32 {
2045 let mut score = 0;
2046 if !self.repos.is_empty() {
2047 score += 8;
2048 }
2049 if !self.branches.is_empty() {
2050 score += 4;
2051 }
2052 score += (self.pr_labels.len() as u32) * 2;
2053 if !self.kinds.is_empty() {
2054 score += 1;
2055 }
2056 score
2057 }
2058}
2059
2060/// Allocation routing key — what the reconciler matches against pool selectors.
2061#[derive(Clone, Copy, Debug)]
2062pub struct MatchKey<'a> {
2063 pub repo: &'a str,
2064 pub branch: &'a str,
2065 pub pr_labels: &'a [String],
2066 pub kind: &'a str,
2067}
2068
2069fn glob_any(patterns: &[String], value: &str) -> bool {
2070 if patterns.is_empty() {
2071 return true;
2072 }
2073 patterns.iter().any(|p| glob_match(p, value))
2074}
2075
2076fn kind_any(kinds: &[String], value: &str) -> bool {
2077 if kinds.is_empty() {
2078 return true;
2079 }
2080 kinds.iter().any(|k| k == value)
2081}
2082
2083fn labels_subset(required: &[String], present: &[String]) -> bool {
2084 required.iter().all(|r| present.iter().any(|p| p == r))
2085}
2086
2087/// Minimal glob: supports trailing `*` only (e.g., `"pleme-io/*"`,
2088/// `"release-*"`). Sufficient for repo/branch routing. Empty pattern
2089/// matches anything.
2090fn glob_match(pattern: &str, value: &str) -> bool {
2091 if pattern.is_empty() {
2092 return true;
2093 }
2094 if let Some(prefix) = pattern.strip_suffix('*') {
2095 value.starts_with(prefix)
2096 } else {
2097 pattern == value
2098 }
2099}
2100
2101#[cfg(test)]
2102mod tests {
2103 use super::*;
2104 // The closed-set tests below call `T::from_str(bad)` via the
2105 // derive-generated `FromStr` impls — bring the trait into scope at
2106 // the test module so the lib body doesn't carry an otherwise-unused
2107 // `use std::str::FromStr;` at the file head.
2108 use std::str::FromStr;
2109
2110 #[test]
2111 fn glob_trailing_star_matches_prefix() {
2112 assert!(glob_match("pleme-io/*", "pleme-io/demo-app"));
2113 assert!(!glob_match("pleme-io/*", "drzln/dotfiles"));
2114 assert!(glob_match("release-*", "release-2026-05"));
2115 assert!(!glob_match("release-*", "main"));
2116 assert!(glob_match("main", "main"));
2117 assert!(!glob_match("main", "develop"));
2118 }
2119
2120 #[test]
2121 fn empty_selector_matches_anything() {
2122 let s = PoolSelector::default();
2123 assert!(s.matches(&MatchKey {
2124 repo: "any/repo",
2125 branch: "any-branch",
2126 pr_labels: &[],
2127 kind: "any",
2128 }));
2129 }
2130
2131 #[test]
2132 fn repo_glob_filters_match_key() {
2133 let s = PoolSelector {
2134 repos: vec!["pleme-io/demo-*".into()],
2135 ..Default::default()
2136 };
2137 assert!(s.matches(&MatchKey {
2138 repo: "pleme-io/demo-app",
2139 branch: "x",
2140 pr_labels: &[],
2141 kind: "y",
2142 }));
2143 assert!(!s.matches(&MatchKey {
2144 repo: "pleme-io/other-repo",
2145 branch: "x",
2146 pr_labels: &[],
2147 kind: "y",
2148 }));
2149 }
2150
2151 #[test]
2152 fn pr_labels_require_all() {
2153 let s = PoolSelector {
2154 pr_labels: vec!["needs-ephemeral".into(), "integration".into()],
2155 ..Default::default()
2156 };
2157 // Both labels present → match.
2158 assert!(s.matches(&MatchKey {
2159 repo: "x",
2160 branch: "y",
2161 pr_labels: &[
2162 "needs-ephemeral".into(),
2163 "integration".into(),
2164 "extra".into()
2165 ],
2166 kind: "z",
2167 }));
2168 // One label missing → no match.
2169 assert!(!s.matches(&MatchKey {
2170 repo: "x",
2171 branch: "y",
2172 pr_labels: &["needs-ephemeral".into()],
2173 kind: "z",
2174 }));
2175 }
2176
2177 #[test]
2178 fn specificity_ranks_more_constrained_higher() {
2179 let general = PoolSelector::default();
2180 let specific = PoolSelector {
2181 repos: vec!["pleme-io/*".into()],
2182 branches: vec!["main".into()],
2183 pr_labels: vec!["needs-ephemeral".into()],
2184 kinds: vec!["github-pr".into()],
2185 };
2186 assert!(specific.specificity() > general.specificity());
2187 }
2188
2189 #[test]
2190 fn return_policy_defaults_to_replace() {
2191 assert_eq!(ReturnPolicy::default(), ReturnPolicy::Replace);
2192 }
2193
2194 #[test]
2195 fn pool_phase_defaults_to_initializing() {
2196 assert_eq!(PoolPhase::default(), PoolPhase::Initializing);
2197 }
2198
2199 // ── closed-set algebra contracts for ReplacementPolicy
2200 // (ALL × as_str × FromStr × predicate-pair) ────────────────────
2201
2202 /// Structural well-formedness of [`ReplacementPolicy`] as a
2203 /// [`tatara_lisp::ClosedSet`] implementor — the workspace-wide
2204 /// testkit lift that pins all three structural invariants (`ALL`
2205 /// is non-empty, every variant round-trips through
2206 /// `label ↔ parse_label`, labels are pairwise distinct, `""` is
2207 /// outside the closed set) at ONE call site. Replaces the hand-
2208 /// derived `replacement_policy_all_is_unique_and_complete` +
2209 /// `replacement_policy_roundtrip_via_as_str` + the empty-input arm
2210 /// of `unknown_replacement_policy_errors`. `FromStr` delegates to
2211 /// `<Self as tatara_closed_set::ClosedSet>::parse_label`, so this helper
2212 /// exercises the same code path the pool reconciler hits when
2213 /// parsing a CRD `enum:`-validated value back to the typed policy.
2214 #[test]
2215 fn replacement_policy_is_well_formed_closed_set() {
2216 tatara_closed_set::assert_closed_set_well_formed::<ReplacementPolicy>();
2217 }
2218
2219 /// CANONICAL-KEY CONTRACT: `as_str` matches serde's PascalCase
2220 /// output verbatim for every variant. A future variant rename (or
2221 /// an `as_str` arm typo) lands here at one site, instead of
2222 /// drifting between the typed surface, the CRD enum, and the
2223 /// YAML wire format.
2224 #[test]
2225 fn replacement_policy_as_str_matches_serde() {
2226 crate::tagged_union::assert_label_matches_serde_serialization::<ReplacementPolicy>();
2227 }
2228
2229 /// The Display impl IS `as_str` — pinning this lets future callers
2230 /// reach for either projection without drift. The operator-facing
2231 /// "policy={policy}" diagnostic in `tatara-pool-reconciler::desired`
2232 /// composes through Display rather than through a hard-coded
2233 /// variant string.
2234 #[test]
2235 fn replacement_policy_display_matches_as_str() {
2236 crate::tagged_union::assert_display_matches_label::<ReplacementPolicy>();
2237 }
2238
2239 /// `FromStr` rejects strings that aren't in the canonical
2240 /// projection — lowercased / typo / cross-axis-leaked — and the
2241 /// error echoes the input verbatim so the operator-facing
2242 /// diagnostic carries the offending value, not a normalized form.
2243 /// The empty-input arm is pinned by
2244 /// [`replacement_policy_is_well_formed_closed_set`] via the
2245 /// `tatara_lisp::ClosedSet` testkit; the cases here pin the
2246 /// verbatim-echo contract on the [`UnknownReplacementPolicy`]
2247 /// newtype, which the trait's `make_unknown` can't see.
2248 #[test]
2249 fn unknown_replacement_policy_errors() {
2250 for bad in [
2251 "replaceimmediate",
2252 "PAUSEPOOL",
2253 "Replace-Immediate",
2254 "hold_failed",
2255 "Pause",
2256 "Reset",
2257 ] {
2258 let err = ReplacementPolicy::from_str(bad).unwrap_err();
2259 assert_eq!(err.0, bad, "error payload should echo input verbatim");
2260 }
2261 }
2262
2263 /// TRUTH-TABLE CONTRACT: the predicate pair agrees with the
2264 /// documented per-variant on-failure behavior.
2265 #[test]
2266 fn replacement_policy_predicate_truth_tables() {
2267 assert!(ReplacementPolicy::ReplaceImmediate.replaces_failed());
2268 assert!(!ReplacementPolicy::ReplaceImmediate.pauses_on_failure());
2269
2270 assert!(!ReplacementPolicy::HoldFailed.replaces_failed());
2271 assert!(!ReplacementPolicy::HoldFailed.pauses_on_failure());
2272
2273 assert!(!ReplacementPolicy::PausePool.replaces_failed());
2274 assert!(ReplacementPolicy::PausePool.pauses_on_failure());
2275 }
2276
2277 /// DISJOINTNESS CONTRACT: no variant returns true from BOTH
2278 /// predicates simultaneously — the two on-failure actions
2279 /// (reap-each-failed vs pause-whole-pool) are mutually exclusive.
2280 /// A future `ReplacementPolicy::PauseAndReap` that returned true
2281 /// from both would FAIL here, forcing the author to either pick
2282 /// one bucket or extend the consumer dispatch site in
2283 /// `tatara-pool-reconciler::desired::PoolConvergence::decide`
2284 /// deliberately rather than silently double-firing both branches.
2285 #[test]
2286 fn replacement_policy_predicates_are_disjoint() {
2287 for policy in ReplacementPolicy::ALL {
2288 assert!(
2289 !(policy.replaces_failed() && policy.pauses_on_failure()),
2290 "{policy:?} returns true from both replaces_failed and pauses_on_failure",
2291 );
2292 }
2293 }
2294
2295 /// INJECTIVITY CONTRACT: the pair `(replaces_failed,
2296 /// pauses_on_failure)` is injective across `ALL`. Each variant
2297 /// projects to its own `(bool, bool)` bucket: `(true, false)` =
2298 /// reap; `(false, false)` = hold; `(false, true)` = pause. Pairing
2299 /// this with the disjointness contract above forces a future
2300 /// variant to land in a fresh `(replaces_failed,
2301 /// pauses_on_failure)` bucket — or the author extends the consumer
2302 /// dispatch in `tatara-pool-reconciler::desired::PoolConvergence`
2303 /// to recognize the new projection bucket.
2304 #[test]
2305 fn replacement_policy_predicate_pair_is_injective() {
2306 let projections: Vec<(bool, bool)> = ReplacementPolicy::ALL
2307 .into_iter()
2308 .map(|p| (p.replaces_failed(), p.pauses_on_failure()))
2309 .collect();
2310 let unique: std::collections::HashSet<_> = projections.iter().copied().collect();
2311 assert_eq!(
2312 projections.len(),
2313 unique.len(),
2314 "predicate pair projection is not injective: {projections:?}",
2315 );
2316 }
2317
2318 /// DEFAULT-AGREEMENT CONTRACT: `ReplacementPolicy::default()`
2319 /// returns the variant tagged `#[default]` in the enum, AND that
2320 /// variant reaps (the production-safe behavior). A future #[default]
2321 /// rename without flipping the predicates fails here.
2322 #[test]
2323 fn replacement_policy_default_replaces_failed() {
2324 let d = ReplacementPolicy::default();
2325 assert_eq!(d, ReplacementPolicy::ReplaceImmediate);
2326 assert!(d.replaces_failed());
2327 assert!(!d.pauses_on_failure());
2328 }
2329
2330 #[test]
2331 fn kinds_filter_to_known_set() {
2332 let s = PoolSelector {
2333 kinds: vec!["github-pr".into(), "manual".into()],
2334 ..Default::default()
2335 };
2336 assert!(s.matches(&MatchKey {
2337 repo: "x",
2338 branch: "y",
2339 pr_labels: &[],
2340 kind: "github-pr",
2341 }));
2342 assert!(!s.matches(&MatchKey {
2343 repo: "x",
2344 branch: "y",
2345 pr_labels: &[],
2346 kind: "scheduled",
2347 }));
2348 }
2349
2350 // ── closed-set algebra contracts for ReturnPolicy
2351 // (ALL × as_str × FromStr × predicate-pair) ────────────────────
2352
2353 /// Structural well-formedness of [`ReturnPolicy`] as a
2354 /// [`tatara_lisp::ClosedSet`] implementor — testkit lift
2355 /// symmetric to [`replacement_policy_is_well_formed_closed_set`]
2356 /// above.
2357 #[test]
2358 fn return_policy_is_well_formed_closed_set() {
2359 tatara_closed_set::assert_closed_set_well_formed::<ReturnPolicy>();
2360 }
2361
2362 /// CANONICAL-KEY CONTRACT: `as_str` matches serde's PascalCase
2363 /// output verbatim for every variant. A future variant rename (or
2364 /// an `as_str` arm typo) lands here at one site, instead of
2365 /// drifting between the typed surface, the CRD enum, and the
2366 /// YAML wire format.
2367 #[test]
2368 fn return_policy_as_str_matches_serde() {
2369 crate::tagged_union::assert_label_matches_serde_serialization::<ReturnPolicy>();
2370 }
2371
2372 /// The Display impl IS `as_str` — pinning this lets future callers
2373 /// reach for either projection without drift, mirroring the
2374 /// `ReplacementPolicy` discipline.
2375 #[test]
2376 fn return_policy_display_matches_as_str() {
2377 crate::tagged_union::assert_display_matches_label::<ReturnPolicy>();
2378 }
2379
2380 /// `FromStr` rejects strings that aren't in the canonical
2381 /// projection — lowercased / typo / cross-axis-leaked — and the
2382 /// error echoes the input verbatim so the operator-facing
2383 /// diagnostic carries the offending value, not a normalized form.
2384 /// The empty-input arm is pinned by
2385 /// [`return_policy_is_well_formed_closed_set`] via the
2386 /// `tatara_lisp::ClosedSet` testkit.
2387 #[test]
2388 fn unknown_return_policy_errors() {
2389 for bad in [
2390 "replace",
2391 "RESET",
2392 "Re-place",
2393 "keep_for_inspection",
2394 "DeleteAndRespawn",
2395 "ReplaceImmediate",
2396 ] {
2397 let err = ReturnPolicy::from_str(bad).unwrap_err();
2398 assert_eq!(err.0, bad, "error payload should echo input verbatim");
2399 }
2400 }
2401
2402 /// TRUTH-TABLE CONTRACT: the predicate pair agrees with the
2403 /// documented per-variant on-release behavior.
2404 #[test]
2405 fn return_policy_predicate_truth_tables() {
2406 assert!(!ReturnPolicy::Replace.keeps_process());
2407 assert!(!ReturnPolicy::Replace.runs_reset_job());
2408
2409 assert!(ReturnPolicy::Reset.keeps_process());
2410 assert!(ReturnPolicy::Reset.runs_reset_job());
2411
2412 assert!(ReturnPolicy::Keep.keeps_process());
2413 assert!(!ReturnPolicy::Keep.runs_reset_job());
2414 }
2415
2416 /// IMPLICATION CONTRACT: `runs_reset_job` implies `keeps_process`.
2417 /// You cannot run a typed `:reset` Job against a Process you've
2418 /// just deleted; the impossible bucket `(false, true)` must stay
2419 /// empty. A future variant returning true from `runs_reset_job`
2420 /// while returning false from `keeps_process` fails here, which
2421 /// forces the author to either flip `keeps_process` to true or
2422 /// extend the consumer dispatch site in
2423 /// `tatara-pool-reconciler::return_policy::plan_return`
2424 /// deliberately rather than letting an impossible state slip in.
2425 #[test]
2426 fn return_policy_reset_implies_keeps_process() {
2427 for policy in ReturnPolicy::ALL {
2428 if policy.runs_reset_job() {
2429 assert!(
2430 policy.keeps_process(),
2431 "{policy:?} runs a reset job but does not keep the process",
2432 );
2433 }
2434 }
2435 }
2436
2437 /// INJECTIVITY CONTRACT: the pair `(keeps_process, runs_reset_job)`
2438 /// is injective across `ALL`. Each variant projects to its own
2439 /// `(bool, bool)` bucket: `(false, false)` = delete + respawn;
2440 /// `(true, true)` = reset-in-place; `(true, false)` = keep for
2441 /// inspection. Pairing this with the implication contract above
2442 /// forces a future variant to land in a fresh
2443 /// `(keeps_process, runs_reset_job)` bucket — or the author
2444 /// extends the consumer dispatch in
2445 /// `tatara-pool-reconciler::return_policy::plan_return` to
2446 /// recognize the new projection bucket.
2447 #[test]
2448 fn return_policy_predicate_pair_is_injective() {
2449 let projections: Vec<(bool, bool)> = ReturnPolicy::ALL
2450 .into_iter()
2451 .map(|p| (p.keeps_process(), p.runs_reset_job()))
2452 .collect();
2453 let unique: std::collections::HashSet<_> = projections.iter().copied().collect();
2454 assert_eq!(
2455 projections.len(),
2456 unique.len(),
2457 "predicate pair projection is not injective: {projections:?}",
2458 );
2459 }
2460
2461 /// DEFAULT-AGREEMENT CONTRACT: `ReturnPolicy::default()` returns
2462 /// the variant tagged `#[default]` in the enum, AND that variant
2463 /// is the safe "tear down + respawn" behavior — neither keeps the
2464 /// process nor runs a reset Job. A future `#[default]` rename
2465 /// without flipping the predicates fails here.
2466 #[test]
2467 fn return_policy_default_is_replace_and_neither_predicate_fires() {
2468 let d = ReturnPolicy::default();
2469 assert_eq!(d, ReturnPolicy::Replace);
2470 assert!(!d.keeps_process());
2471 assert!(!d.runs_reset_job());
2472 }
2473
2474 // ── closed-set algebra contracts for MemberState
2475 // (ALL × as_str × FromStr × predicate pair) ────────────────────
2476
2477 /// Structural well-formedness of [`MemberState`] as a
2478 /// [`tatara_lisp::ClosedSet`] implementor — testkit lift
2479 /// symmetric to [`replacement_policy_is_well_formed_closed_set`]
2480 /// and [`return_policy_is_well_formed_closed_set`] above.
2481 #[test]
2482 fn member_state_is_well_formed_closed_set() {
2483 tatara_closed_set::assert_closed_set_well_formed::<MemberState>();
2484 }
2485
2486 /// CANONICAL-KEY CONTRACT: `as_str` matches serde's PascalCase
2487 /// output verbatim for every variant. A future variant rename (or
2488 /// an `as_str` arm typo) lands here at one site, instead of
2489 /// drifting between the typed surface, the CRD enum, and the YAML
2490 /// wire format the pool reconciler stamps on
2491 /// `status.members[].state`.
2492 #[test]
2493 fn member_state_as_str_matches_serde() {
2494 crate::tagged_union::assert_label_matches_serde_serialization::<MemberState>();
2495 }
2496
2497 /// The Display impl IS `as_str` — pinning this lets future callers
2498 /// reach for either projection without drift. Any operator-facing
2499 /// "state={state}" diagnostic that composes through Display
2500 /// inherits the canonical wire-format string automatically.
2501 #[test]
2502 fn member_state_display_matches_as_str() {
2503 crate::tagged_union::assert_display_matches_label::<MemberState>();
2504 }
2505
2506 /// `FromStr` rejects strings that aren't in the canonical
2507 /// projection — lowercased / typo / cross-axis-leaked — and
2508 /// the error echoes the input verbatim so the operator-facing
2509 /// diagnostic carries the offending value, not a normalized form.
2510 /// The empty-input arm is pinned by
2511 /// [`member_state_is_well_formed_closed_set`] via the
2512 /// `tatara_lisp::ClosedSet` testkit. The cross-axis leak cases
2513 /// pin the closed-set REJECTION contract that the trait can't see:
2514 /// `"ReplaceImmediate"`, `"Reset"`, and `"Attested"` are valid
2515 /// labels for sibling enums (`ReplacementPolicy`, `ReturnPolicy`,
2516 /// `ProcessPhase`) but MUST reject here, because the codomains
2517 /// are disjoint.
2518 #[test]
2519 fn unknown_member_state_errors() {
2520 for bad in [
2521 "free",
2522 "SPAWNING",
2523 "Free-State",
2524 "allocated_now",
2525 "ReplaceImmediate", // ReplacementPolicy-axis leak
2526 "Reset", // ReturnPolicy-axis leak
2527 "Attested", // ProcessPhase-axis leak
2528 ] {
2529 let err = MemberState::from_str(bad).unwrap_err();
2530 assert_eq!(err.0, bad, "error payload should echo input verbatim");
2531 }
2532 }
2533
2534 /// TRUTH-TABLE CONTRACT: the predicate pair agrees with the
2535 /// documented per-variant lifecycle role. The pool reconciler's
2536 /// `pool_phase_from_members` supply calc collapses
2537 /// `count_state(Free) + count_state(Spawning)` into one
2538 /// `counts_toward_supply` filter; this table pins the per-variant
2539 /// projection that consumer depends on.
2540 #[test]
2541 fn member_state_predicate_truth_tables() {
2542 assert!(!MemberState::Spawning.is_failed());
2543 assert!(MemberState::Spawning.counts_toward_supply());
2544
2545 assert!(!MemberState::Free.is_failed());
2546 assert!(MemberState::Free.counts_toward_supply());
2547
2548 assert!(!MemberState::Allocated.is_failed());
2549 assert!(!MemberState::Allocated.counts_toward_supply());
2550
2551 assert!(!MemberState::Returning.is_failed());
2552 assert!(!MemberState::Returning.counts_toward_supply());
2553
2554 assert!(MemberState::Failed.is_failed());
2555 assert!(!MemberState::Failed.counts_toward_supply());
2556 }
2557
2558 /// DISJOINTNESS CONTRACT: no variant returns true from BOTH
2559 /// `is_failed` and `counts_toward_supply` simultaneously — a
2560 /// failed member can never be counted as available capacity. A
2561 /// future variant that returned true from both would FAIL here,
2562 /// forcing the author to either drop it from supply, or extend
2563 /// the consumer's bucketing in
2564 /// `tatara-pool-reconciler::controller_pool::pool_phase_from_members`
2565 /// deliberately rather than silently inflating the pool's supply
2566 /// count with failed slots.
2567 #[test]
2568 fn member_state_failed_implies_no_supply() {
2569 for state in MemberState::ALL {
2570 assert!(
2571 !(state.is_failed() && state.counts_toward_supply()),
2572 "{state:?} returns true from both is_failed and counts_toward_supply — \
2573 a failed member can never be counted as available pool capacity",
2574 );
2575 }
2576 }
2577
2578 /// COVERAGE CONTRACT: every variant lands somewhere — either
2579 /// in supply, or as a failed slot, or as an in-use bucket
2580 /// (`Allocated | Returning`). A future variant that returns
2581 /// `false` from `counts_toward_supply` AND `false` from
2582 /// `is_failed` is fine *iff* it represents an in-use slot; this
2583 /// test pins the existing variants in their declared buckets so
2584 /// the consumer-side dispatch in
2585 /// `tatara-pool-reconciler::pool_decide::decide_pool_reconcile`
2586 /// stays grounded.
2587 #[test]
2588 fn member_state_buckets_cover_every_variant() {
2589 let mut supply = 0u32;
2590 let mut failed = 0u32;
2591 let mut in_use = 0u32;
2592 for state in MemberState::ALL {
2593 match (state.is_failed(), state.counts_toward_supply()) {
2594 (true, false) => failed += 1,
2595 (false, true) => supply += 1,
2596 (false, false) => in_use += 1,
2597 (true, true) => panic!("disjointness already pins this empty for {state:?}"),
2598 }
2599 }
2600 assert_eq!(supply, 2, "supply bucket: Free + Spawning");
2601 assert_eq!(failed, 1, "failed bucket: Failed");
2602 assert_eq!(in_use, 2, "in-use bucket: Allocated + Returning");
2603 assert_eq!(supply + failed + in_use, MemberState::ALL.len() as u32);
2604 }
2605
2606 // ── closed-set algebra contracts for PoolPhase
2607 // (ALL × as_str × FromStr × predicate pair) ────────────────────
2608
2609 /// Structural well-formedness of [`PoolPhase`] as a
2610 /// [`tatara_lisp::ClosedSet`] implementor — testkit lift
2611 /// symmetric to [`member_state_is_well_formed_closed_set`] above.
2612 #[test]
2613 fn pool_phase_is_well_formed_closed_set() {
2614 tatara_closed_set::assert_closed_set_well_formed::<PoolPhase>();
2615 }
2616
2617 /// CANONICAL-KEY CONTRACT: `as_str` matches serde's PascalCase
2618 /// output verbatim for every variant. A future variant rename (or
2619 /// an `as_str` arm typo) lands here at one site, instead of
2620 /// drifting between the typed surface, the CRD enum, and the YAML
2621 /// wire format the pool reconciler stamps on `status.phase`.
2622 #[test]
2623 fn pool_phase_as_str_matches_serde() {
2624 crate::tagged_union::assert_label_matches_serde_serialization::<PoolPhase>();
2625 }
2626
2627 /// The Display impl IS `as_str` — pinning this lets future callers
2628 /// reach for either projection without drift. Any operator-facing
2629 /// "phase={phase}" diagnostic that composes through Display
2630 /// inherits the canonical wire-format string automatically.
2631 #[test]
2632 fn pool_phase_display_matches_as_str() {
2633 crate::tagged_union::assert_display_matches_label::<PoolPhase>();
2634 }
2635
2636 /// `FromStr` rejects strings that aren't in the canonical
2637 /// projection — lowercased / typo / cross-axis-leaked — and
2638 /// the error echoes the input verbatim so the operator-facing
2639 /// diagnostic carries the offending value, not a normalized form.
2640 /// The empty-input arm is pinned by
2641 /// [`pool_phase_is_well_formed_closed_set`] via the
2642 /// `tatara_lisp::ClosedSet` testkit. The cross-axis leak cases
2643 /// (`"Free"`, `"Replace"`, `"Attested"`, `"HoldFailed"`) pin the
2644 /// closed-set REJECTION contract that the trait can't see — those
2645 /// are valid sibling-axis labels but MUST reject here.
2646 #[test]
2647 fn unknown_pool_phase_errors() {
2648 for bad in [
2649 "steady",
2650 "SCALINGUP",
2651 "Scaling-Up",
2652 "scaling_down",
2653 "Free", // MemberState-axis leak
2654 "Replace", // ReturnPolicy-axis leak
2655 "Attested", // ProcessPhase-axis leak
2656 "HoldFailed", // ReplacementPolicy-axis leak
2657 ] {
2658 let err = PoolPhase::from_str(bad).unwrap_err();
2659 assert_eq!(err.0, bad, "error payload should echo input verbatim");
2660 }
2661 }
2662
2663 /// TRUTH-TABLE CONTRACT: the predicate pair agrees with the
2664 /// documented per-variant lifecycle role. Pinning this table at
2665 /// one site means any future status-aggregator surface
2666 /// (`feira pool list --healthy`, the SSE filter, the desired-loop
2667 /// heartbeat short-circuit) reads the same projection that the
2668 /// reconciler writes.
2669 #[test]
2670 fn pool_phase_predicate_truth_tables() {
2671 assert!(!PoolPhase::Initializing.is_steady());
2672 assert!(!PoolPhase::Initializing.is_terminal());
2673
2674 assert!(PoolPhase::Steady.is_steady());
2675 assert!(!PoolPhase::Steady.is_terminal());
2676
2677 assert!(!PoolPhase::ScalingUp.is_steady());
2678 assert!(!PoolPhase::ScalingUp.is_terminal());
2679
2680 assert!(!PoolPhase::ScalingDown.is_steady());
2681 assert!(!PoolPhase::ScalingDown.is_terminal());
2682
2683 assert!(!PoolPhase::Degraded.is_steady());
2684 assert!(!PoolPhase::Degraded.is_terminal());
2685
2686 assert!(!PoolPhase::Draining.is_steady());
2687 assert!(PoolPhase::Draining.is_terminal());
2688 }
2689
2690 /// DISJOINTNESS CONTRACT: no variant returns true from BOTH
2691 /// `is_steady` and `is_terminal` simultaneously — a draining pool
2692 /// is by definition transitioning OUT, not the goal converged
2693 /// state. A future variant that returned true from both would
2694 /// FAIL here, forcing the author to either pick one bucket or
2695 /// extend the consumer dispatch sites (status aggregators,
2696 /// heartbeat short-circuit) deliberately rather than silently
2697 /// double-firing both branches.
2698 #[test]
2699 fn pool_phase_steady_excludes_terminal() {
2700 for phase in PoolPhase::ALL {
2701 assert!(
2702 !(phase.is_steady() && phase.is_terminal()),
2703 "{phase:?} returns true from both is_steady and is_terminal — \
2704 a draining pool is by definition not the converged goal state",
2705 );
2706 }
2707 }
2708
2709 /// COVERAGE CONTRACT: every variant lands somewhere — either the
2710 /// converged goal (`Steady`), the absorbing exit (`Draining`),
2711 /// or the transient bucket (`Initializing | ScalingUp |
2712 /// ScalingDown | Degraded` — pool is in motion toward desired).
2713 /// A future variant that returns `false` from BOTH predicates is
2714 /// fine *iff* it represents an in-motion state; this test pins
2715 /// the existing variants in their declared buckets so the
2716 /// projection consumers stay grounded.
2717 #[test]
2718 fn pool_phase_buckets_cover_every_variant() {
2719 let mut converged = 0u32;
2720 let mut terminal = 0u32;
2721 let mut transient = 0u32;
2722 for phase in PoolPhase::ALL {
2723 match (phase.is_steady(), phase.is_terminal()) {
2724 (true, false) => converged += 1,
2725 (false, true) => terminal += 1,
2726 (false, false) => transient += 1,
2727 (true, true) => panic!("disjointness already pins this empty for {phase:?}"),
2728 }
2729 }
2730 assert_eq!(converged, 1, "converged bucket: Steady");
2731 assert_eq!(terminal, 1, "terminal bucket: Draining");
2732 assert_eq!(
2733 transient, 4,
2734 "transient bucket: Initializing + ScalingUp + ScalingDown + Degraded"
2735 );
2736 assert_eq!(
2737 converged + terminal + transient,
2738 PoolPhase::ALL.len() as u32
2739 );
2740 }
2741
2742 /// DEFAULT-AGREEMENT CONTRACT: `PoolPhase::default()` returns the
2743 /// variant a freshly-admitted pool should land in — `Initializing`
2744 /// — AND that variant is neither steady (no members yet) nor
2745 /// terminal (not deletion-stamped). A future `Default` rename
2746 /// without flipping the predicates fails here.
2747 #[test]
2748 fn pool_phase_default_is_initializing_in_transient_bucket() {
2749 let d = PoolPhase::default();
2750 assert_eq!(d, PoolPhase::Initializing);
2751 assert!(!d.is_steady());
2752 assert!(!d.is_terminal());
2753 }
2754
2755 // ─────────────────────────────────────────────────────────────────
2756 // `EphemeralPool::name_or_empty` — borrow-form metadata-projection
2757 // primitive on the `metadata.name` axis. Pins the missing-slot
2758 // corner, the populated-slot corner, the pre-lift chain-shape
2759 // parity, and the pure-projection discipline that the two
2760 // `tatara-pool-reconciler` consumers routed onto the primitive
2761 // depend on. See the primitive's doc-comment for the full
2762 // migration rationale.
2763 // ─────────────────────────────────────────────────────────────────
2764
2765 fn empty_template() -> EphemeralSpec {
2766 EphemeralSpec {
2767 aplicacao: crate::intent::AplicacaoIntent::chart_only("oci://x", "1"),
2768 ttl: "1h".into(),
2769 teardown: crate::lifetime::TeardownPolicy::Always,
2770 max_concurrent: 0,
2771 postconditions: vec![],
2772 preconditions: vec![],
2773 verify_timeout: None,
2774 classification: None,
2775 parent: None,
2776 exports: vec![],
2777 routing: None,
2778 }
2779 }
2780
2781 fn pool_spec() -> PoolSpec {
2782 // Every non-template slot rides the ONE substrate composer
2783 // [`PoolSpec::with_template`] at its wire-published default;
2784 // pre-lift this fixture spelled the full 11-slot struct-literal
2785 // verbatim as one of eight cross-crate hand-authored copies past
2786 // the ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold. See the
2787 // primitive's doc-comment for the full migration rationale.
2788 PoolSpec {
2789 desired_size: 1,
2790 ..PoolSpec::with_template(empty_template())
2791 }
2792 }
2793
2794 fn pool_named(name: &str) -> EphemeralPool {
2795 EphemeralPool::new(name, pool_spec())
2796 }
2797
2798 fn pool_unnamed() -> EphemeralPool {
2799 let mut p = EphemeralPool::new("scratch", pool_spec());
2800 p.metadata.name = None;
2801 p
2802 }
2803
2804 #[test]
2805 fn name_or_empty_returns_empty_string_when_metadata_name_is_none() {
2806 let p = pool_unnamed();
2807 assert!(p.metadata.name.is_none(), "fixture invariant");
2808 assert_eq!(p.name_or_empty(), "");
2809 }
2810
2811 #[test]
2812 fn name_or_empty_returns_populated_slot_verbatim() {
2813 let p = pool_named("attest-pool");
2814 assert_eq!(p.name_or_empty(), "attest-pool");
2815 }
2816
2817 #[test]
2818 fn name_or_empty_returns_empty_string_when_slot_is_explicitly_empty_string() {
2819 // Corner between `None` (missing slot) and `Some(String::new())`
2820 // (populated slot containing the empty string): the primitive
2821 // MUST fold both to the same `""` byte-shape so a downstream
2822 // `HashMap<String,_>::get(name)` / `str::cmp` sees ONE
2823 // "unnamed pool" bucket regardless of which shape the K8s API
2824 // server materialized. This is byte-identical to what the
2825 // pre-lift `.as_deref().unwrap_or("")` chain produced.
2826 let mut p = pool_named("scratch");
2827 p.metadata.name = Some(String::new());
2828 assert_eq!(p.name_or_empty(), "");
2829 }
2830
2831 #[test]
2832 fn name_or_empty_is_a_pure_projection() {
2833 // Consecutive calls return byte-identical slices — no cached
2834 // state, no mutation on the `EphemeralPool` between calls.
2835 // Guards against a future refactor that plants a cache field
2836 // and drifts one caller from another silently.
2837 let p = pool_named("router-pool");
2838 assert_eq!(p.name_or_empty(), p.name_or_empty());
2839 assert_eq!(p.name_or_empty(), "router-pool");
2840 assert_eq!(p.name_or_empty(), "router-pool");
2841 }
2842
2843 #[test]
2844 fn name_or_empty_matches_pre_lift_chain_verbatim() {
2845 // Byte-identical parity with the two hand-authored
2846 // `.metadata.name.as_deref().unwrap_or("")` chains the
2847 // primitive replaces in `tatara-pool-reconciler::router` and
2848 // `tatara-pool-reconciler::controller_allocation`. Runs across
2849 // the FULL corner set of the metadata.name slot: absent,
2850 // present-with-value, present-with-empty-string.
2851 let cases: [(Option<String>, &str); 3] = [
2852 (None, ""),
2853 (Some("attest-pool".into()), "attest-pool"),
2854 (Some(String::new()), ""),
2855 ];
2856 for (slot, expected) in cases {
2857 let mut p = pool_named("scratch");
2858 p.metadata.name = slot.clone();
2859 let pre_lift = p.metadata.name.as_deref().unwrap_or("");
2860 assert_eq!(pre_lift, expected, "pre-lift chain sanity");
2861 assert_eq!(p.name_or_empty(), pre_lift);
2862 assert_eq!(p.name_or_empty(), expected);
2863 }
2864 }
2865
2866 #[test]
2867 fn name_or_empty_borrows_from_metadata_name_slot() {
2868 // The returned `&str` is tied to the `EphemeralPool`'s
2869 // lifetime — the caller can compare / hash / index without
2870 // allocating. This is the load-bearing property that lets
2871 // the `HashMap<String, _>::get(pool.name_or_empty())` closure
2872 // in `controller_allocation::reconcile_inner` skip cloning.
2873 let p = pool_named("attest-pool");
2874 let s: &str = p.name_or_empty();
2875 assert_eq!(s.as_ptr(), p.metadata.name.as_deref().unwrap().as_ptr());
2876 }
2877
2878 // ─── EphemeralPool::owned_name_or_empty substrate pins ────────────
2879 //
2880 // The owned-form peer of the borrow-form `name_or_empty` primitive
2881 // above. Sibling to the sister-CRD primitive
2882 // `crate::crd::Process::owned_name_or_empty` (owned + empty sentinel
2883 // on `Process::metadata.name`) — the four primitives now partition
2884 // the (borrow × owned) × (name × uid) corner of the metadata-slot
2885 // family on identical missing-slot semantics across BOTH tatara-
2886 // process CRDs (`Process::uid_or_empty` + `Process::owned_name_or_empty`
2887 // + `EphemeralPool::name_or_empty` + this method). Fail-before-pass-
2888 // after granularity: `owned_name_or_empty` did not exist on the pool
2889 // CRD pre-lift; the compiler cannot resolve the name until the impl
2890 // block above is in place, so a rollback of the primitive breaks
2891 // this whole module.
2892 #[test]
2893 fn owned_name_or_empty_returns_empty_string_when_metadata_name_is_none() {
2894 let p = pool_unnamed();
2895 assert!(p.metadata.name.is_none(), "fixture invariant");
2896 assert_eq!(p.owned_name_or_empty(), String::new());
2897 }
2898
2899 #[test]
2900 fn owned_name_or_empty_returns_owned_string_when_slot_is_populated() {
2901 let p = pool_named("attest-pool");
2902 assert_eq!(p.owned_name_or_empty(), "attest-pool");
2903 }
2904
2905 #[test]
2906 fn owned_name_or_empty_returns_empty_string_when_slot_is_explicitly_empty_string() {
2907 // Corner between `None` (missing slot) and `Some(String::new())`
2908 // (populated slot containing the empty string): the primitive
2909 // MUST fold both to the same `""` byte-shape so a downstream
2910 // `HashMap<String,_>::get(name)` sees ONE "unnamed pool" bucket
2911 // regardless of which shape the K8s API server materialized.
2912 // Byte-identical to what the pre-lift `.clone().unwrap_or_default()`
2913 // chain produced.
2914 let mut p = pool_named("scratch");
2915 p.metadata.name = Some(String::new());
2916 assert_eq!(p.owned_name_or_empty(), String::new());
2917 assert!(p.owned_name_or_empty().is_empty());
2918 }
2919
2920 #[test]
2921 fn owned_name_or_empty_is_a_pure_projection() {
2922 // Consecutive calls return byte-identical Strings — no cached
2923 // state, no mutation on the `EphemeralPool` between calls.
2924 // Guards against a future refactor that plants a cache field
2925 // and drifts one caller from another silently.
2926 let p = pool_named("router-pool");
2927 assert_eq!(p.owned_name_or_empty(), p.owned_name_or_empty());
2928 assert_eq!(p.owned_name_or_empty(), "router-pool");
2929 assert_eq!(p.owned_name_or_empty(), "router-pool");
2930 }
2931
2932 #[test]
2933 fn owned_name_or_empty_matches_pre_lift_chain_verbatim() {
2934 // Byte-identical parity with the two hand-authored
2935 // `.metadata.name.clone().unwrap_or_default()` chains the
2936 // primitive replaces in `tatara-pool-reconciler::
2937 // controller_allocation::reconcile_inner` (HashMap key seed)
2938 // and `tatara-pool-reconciler::allocation_decide::
2939 // AllocationConvergenceCtx::observe` (AllocationRef.name slot
2940 // seed). Runs across the FULL corner set of the metadata.name
2941 // slot: absent, present-with-value, present-with-empty-string.
2942 // A regression that inserted a normalization step at the
2943 // primitive the pre-lift chain does NOT apply — or vice versa —
2944 // surfaces here rather than as silent drift between the two
2945 // owned-form callsites and the ONE substrate owner they now
2946 // route through.
2947 let cases: [(Option<String>, &str); 3] = [
2948 (None, ""),
2949 (Some("attest-pool".into()), "attest-pool"),
2950 (Some(String::new()), ""),
2951 ];
2952 for (slot, expected) in cases {
2953 let mut p = pool_named("scratch");
2954 p.metadata.name = slot.clone();
2955 let pre_lift = p.metadata.name.clone().unwrap_or_default();
2956 assert_eq!(pre_lift.as_str(), expected, "pre-lift chain sanity");
2957 assert_eq!(p.owned_name_or_empty(), pre_lift);
2958 assert_eq!(p.owned_name_or_empty().as_str(), expected);
2959 }
2960 }
2961
2962 #[test]
2963 fn owned_name_or_empty_matches_borrow_form_peer_on_populated_slot() {
2964 // Cross-primitive coherence pin at the sibling corner: when the
2965 // slot is present, the borrow-form (`name_or_empty`) and owned-
2966 // form (`owned_name_or_empty`) primitives return the SAME byte
2967 // sequence and differ only in ownership. A regression that
2968 // skewed one form's fallback would surface here rather than as
2969 // silent drift between the router tie-break comparator and the
2970 // AllocationRef seed on the SAME pool.
2971 let p = pool_named("attest-pool");
2972 assert_eq!(p.name_or_empty(), p.owned_name_or_empty().as_str());
2973 }
2974
2975 #[test]
2976 fn owned_name_or_empty_matches_borrow_form_peer_on_missing_slot() {
2977 // Sibling corner of the coherence pin above: when the slot is
2978 // absent (or explicitly empty), BOTH primitives fold to the
2979 // same empty-string byte-shape. The load-bearing property is
2980 // that a caller who switches between the two return-forms
2981 // based on downstream ownership requirements never sees a
2982 // different missing-slot spelling as a side effect.
2983 let p = pool_unnamed();
2984 assert_eq!(p.name_or_empty(), p.owned_name_or_empty().as_str());
2985 assert_eq!(p.name_or_empty(), "");
2986 assert_eq!(p.owned_name_or_empty(), String::new());
2987 }
2988
2989 // ─── EphemeralPool::is_being_deleted substrate pins ───────────────
2990 //
2991 // Pins the copy-form metadata-projection primitive on the deletion-
2992 // tombstone axis of the pool CRD. Peer to the borrow-form + owned-
2993 // form metadata-fallback family (`name_or_empty`,
2994 // `owned_name_or_empty`); this one opens the presence-probe corner
2995 // for the tombstone slot. Sibling to the sister-CRD primitive
2996 // `crate::crd::Process::is_being_deleted` — the two primitives
2997 // now partition the tombstone-presence probe across BOTH tatara-
2998 // process CRDs on identical missing-slot semantics. Fail-before-
2999 // pass-after granularity: `is_being_deleted` did not exist on the
3000 // pool CRD pre-lift; the compiler cannot resolve the name until
3001 // the impl block above is in place, so a rollback of the primitive
3002 // breaks this whole module.
3003
3004 fn tombstoned_pool() -> EphemeralPool {
3005 let mut p = pool_named("attest-pool");
3006 p.metadata.namespace = Some("ephemeral-pools".into());
3007 // Routes through the ONE substrate composer
3008 // `tatara_process::time::tombstone_now` — see the peer
3009 // `tombstoned_process` doc-comment in `crd.rs` for the full
3010 // migration rationale.
3011 p.metadata.deletion_timestamp = crate::time::tombstone_now();
3012 p
3013 }
3014
3015 #[test]
3016 fn is_being_deleted_returns_false_when_deletion_timestamp_is_absent() {
3017 // Missing-tombstone corner pin: the primitive collapses the
3018 // no-tombstone case to `false` so the `→ Drain` short-circuit
3019 // at `decide_pool_reconcile` is NOT taken and the observed-
3020 // phase composer at `pool_phase_from_members` proceeds to its
3021 // normal (free / spawning / allocated) arithmetic branches
3022 // instead of short-circuiting to `PoolPhase::Draining`.
3023 // Matches the pre-lift `.is_some()` chain's `false` byte-
3024 // identically at every consumer's downstream gate.
3025 let mut p = pool_named("attest-pool");
3026 p.metadata.deletion_timestamp = None;
3027 assert!(!p.is_being_deleted());
3028 }
3029
3030 #[test]
3031 fn is_being_deleted_returns_true_when_deletion_timestamp_is_present() {
3032 // Present-tombstone corner pin: the primitive returns `true`
3033 // on any populated `metadata.deletionTimestamp` slot regardless
3034 // of the timestamp payload — the two consumers only read the
3035 // tombstone's PRESENCE, never its RFC-3339 timestamp value.
3036 // A regression that gated the `true` return on the timestamp
3037 // being non-epoch, or parsed the timestamp before returning,
3038 // would surface here rather than as silent skew at the
3039 // `→ Drain` decision or the `→ Draining` phase report on the
3040 // SAME `EphemeralPool`.
3041 let p = tombstoned_pool();
3042 assert!(p.is_being_deleted());
3043 }
3044
3045 #[test]
3046 fn is_being_deleted_is_a_pure_projection() {
3047 // Purity pin: two consecutive calls return byte-identical
3048 // `bool` values (no lazy materialization, no interior
3049 // mutation of `self`). Peer to the sibling
3050 // `name_or_empty_is_a_pure_projection` +
3051 // `owned_name_or_empty_is_a_pure_projection` pins in this
3052 // module and to `is_being_deleted_is_a_pure_projection` on
3053 // the sister-CRD `Process`; all four bind the pure-projection
3054 // discipline on the ONE substrate accessor per metadata slot.
3055 let p = tombstoned_pool();
3056 let a = p.is_being_deleted();
3057 let b = p.is_being_deleted();
3058 assert_eq!(a, b);
3059 assert!(a);
3060 }
3061
3062 #[test]
3063 fn is_being_deleted_matches_pre_lift_pool_reconciler_chain_shape() {
3064 // Parity pin: sweeps the two corners every pre-lift consumer
3065 // plausibly encountered (missing tombstone, present tombstone)
3066 // and compares the substrate call against a hand-authored pre-
3067 // lift chain byte-identically. A regression that reshaped
3068 // either corner would surface here rather than as silent
3069 // operator-facing skew between the pool-reconciler's `→ Drain`
3070 // decision and the observed-phase composer's `→ Draining`
3071 // report on the SAME `EphemeralPool` within one reconcile
3072 // pass.
3073 fn pre_lift(p: &EphemeralPool) -> bool {
3074 p.metadata.deletion_timestamp.is_some()
3075 }
3076 // Missing slot.
3077 let mut p = pool_named("attest-pool");
3078 p.metadata.deletion_timestamp = None;
3079 assert_eq!(p.is_being_deleted(), pre_lift(&p));
3080 // Populated slot.
3081 let p = tombstoned_pool();
3082 assert_eq!(p.is_being_deleted(), pre_lift(&p));
3083 }
3084
3085 #[test]
3086 fn is_being_deleted_composes_with_pool_phase_draining_at_reconcile_preempt() {
3087 // Call-site-shape pin: the `pool_phase_from_members`
3088 // deletion-preempt returns `PoolPhase::Draining` as soon as
3089 // `pool.is_being_deleted()` holds, regardless of the (free +
3090 // spawning) supply arithmetic that would otherwise pick
3091 // `Ready` / `Scaling` / `Degraded`. The `→ Drain` decision at
3092 // `decide_pool_reconcile` composes with the same probe on the
3093 // same tombstone-presence slot. A regression that broadened
3094 // the tombstone probe implicitly (returning `false` on a
3095 // present but zero-timestamp) or narrowed it (requiring an
3096 // additional `.finalizers.is_empty()` conjunct that the two
3097 // consumers never spelled) would surface here rather than as
3098 // silent operator-facing skew between the pool reconciler's
3099 // decision and the observed-phase composer on the SAME
3100 // `EphemeralPool` within one reconcile pass.
3101 let alive = pool_named("attest-pool");
3102 assert!(!alive.is_being_deleted());
3103 let dying = tombstoned_pool();
3104 assert!(dying.is_being_deleted());
3105 }
3106
3107 // ─── EphemeralPool::owned_namespace_or_empty substrate pins ───────
3108 //
3109 // The owned-form peer of the `owned_name_or_empty` primitive on the
3110 // sibling `metadata.namespace` axis — the paired half of the
3111 // `AllocationRef { name, namespace }` struct literal both
3112 // `AllocationConvergenceCtx::observe` and the composition pin
3113 // consume through the SAME `AllocationRef::new(name, namespace)`
3114 // constructor. Fail-before-pass-after granularity:
3115 // `owned_namespace_or_empty` did not exist on the pool CRD pre-
3116 // lift; the compiler cannot resolve the name until the impl block
3117 // above is in place, so a rollback of the primitive breaks this
3118 // whole module.
3119 #[test]
3120 fn owned_namespace_or_empty_returns_empty_string_when_metadata_namespace_is_none() {
3121 // Missing-slot corner pin: the primitive collapses the no-
3122 // namespace case to the load-bearing empty-string sentinel so
3123 // the downstream `AllocationRef.namespace` slot carries `""`
3124 // rather than a defaulted `"default"` string. See the doc-
3125 // comment's DELIBERATE-EMPTY-SENTINEL rationale for why the
3126 // fallback matches `.clone().unwrap_or_default()` byte-for-
3127 // byte rather than substituting `Process::DEFAULT_NAMESPACE`
3128 // at the primitive.
3129 let mut p = pool_named("attest-pool");
3130 p.metadata.namespace = None;
3131 assert!(p.metadata.namespace.is_none(), "fixture invariant");
3132 assert_eq!(p.owned_namespace_or_empty(), String::new());
3133 }
3134
3135 #[test]
3136 fn owned_namespace_or_empty_returns_owned_string_when_slot_is_populated() {
3137 let mut p = pool_named("attest-pool");
3138 p.metadata.namespace = Some("ephemeral-pools".into());
3139 assert_eq!(p.owned_namespace_or_empty(), "ephemeral-pools");
3140 }
3141
3142 #[test]
3143 fn owned_namespace_or_empty_returns_empty_string_when_slot_is_explicitly_empty_string() {
3144 // Corner between `None` (missing slot) and `Some(String::new())`
3145 // (populated slot containing the empty string): the primitive
3146 // MUST fold both to the same `""` byte-shape so a downstream
3147 // `AllocationRef.namespace ==` comparator at
3148 // `resolve_pool` sees ONE "unset namespace" bucket regardless
3149 // of which shape the K8s API server materialized. Byte-
3150 // identical to what the pre-lift `.clone().unwrap_or_default()`
3151 // chain produced.
3152 let mut p = pool_named("attest-pool");
3153 p.metadata.namespace = Some(String::new());
3154 assert_eq!(p.owned_namespace_or_empty(), String::new());
3155 assert!(p.owned_namespace_or_empty().is_empty());
3156 }
3157
3158 #[test]
3159 fn owned_namespace_or_empty_is_a_pure_projection() {
3160 // Consecutive calls return byte-identical Strings — no cached
3161 // state, no mutation on the `EphemeralPool` between calls.
3162 // Peer to the sibling `owned_name_or_empty_is_a_pure_projection`
3163 // pin in this module and to `is_being_deleted_is_a_pure_projection`
3164 // on the same CRD; all three bind the pure-projection
3165 // discipline on the ONE substrate accessor per metadata slot.
3166 let mut p = pool_named("attest-pool");
3167 p.metadata.namespace = Some("ephemeral-pools".into());
3168 assert_eq!(p.owned_namespace_or_empty(), p.owned_namespace_or_empty());
3169 assert_eq!(p.owned_namespace_or_empty(), "ephemeral-pools");
3170 assert_eq!(p.owned_namespace_or_empty(), "ephemeral-pools");
3171 }
3172
3173 #[test]
3174 fn owned_namespace_or_empty_matches_pre_lift_chain_verbatim() {
3175 // Byte-identical parity with the two hand-authored
3176 // `.metadata.namespace.clone().unwrap_or_default()` chains
3177 // the primitive replaces in `tatara-pool-reconciler::
3178 // allocation_decide::AllocationConvergenceCtx::observe`
3179 // (matched-pool `AllocationRef.namespace` seed) and in the
3180 // sibling composition pin
3181 // `allocation_ref_new_composes_with_owned_name_or_empty_pool_projection`.
3182 // Runs across the FULL corner set of the metadata.namespace
3183 // slot: absent, present-with-value, present-with-empty-string.
3184 // A regression that inserted a normalization step at the
3185 // primitive the pre-lift chain does NOT apply — or vice versa —
3186 // surfaces here rather than as silent drift between the two
3187 // owned-form callsites and the ONE substrate owner they now
3188 // route through.
3189 let cases: [(Option<String>, &str); 3] = [
3190 (None, ""),
3191 (Some("ephemeral-pools".into()), "ephemeral-pools"),
3192 (Some(String::new()), ""),
3193 ];
3194 for (slot, expected) in cases {
3195 let mut p = pool_named("attest-pool");
3196 p.metadata.namespace = slot.clone();
3197 let pre_lift = p.metadata.namespace.clone().unwrap_or_default();
3198 assert_eq!(pre_lift.as_str(), expected, "pre-lift chain sanity");
3199 assert_eq!(p.owned_namespace_or_empty(), pre_lift);
3200 assert_eq!(p.owned_namespace_or_empty().as_str(), expected);
3201 }
3202 }
3203
3204 #[test]
3205 fn owned_namespace_or_empty_composes_with_owned_name_or_empty_on_paired_slot_axis() {
3206 // Paired-axis coherence pin: the two owned-form primitives on
3207 // the pool CRD's `metadata.name` + `metadata.namespace` slots
3208 // share the SAME empty-string sentinel on the missing corner,
3209 // so a caller that composes both halves into an
3210 // `AllocationRef` (as `AllocationConvergenceCtx::observe`
3211 // does) never sees a mixed-fallback pair (one `""`, the
3212 // other `"default"`) as a side effect of one slot being
3213 // absent. A regression that skewed either primitive's
3214 // fallback would surface here rather than as silent operator-
3215 // facing skew between the paired halves of the SAME
3216 // `AllocationRef` seed.
3217 let mut p = pool_named("attest-pool");
3218 p.metadata.namespace = None;
3219 p.metadata.name = None;
3220 assert_eq!(p.owned_name_or_empty(), p.owned_namespace_or_empty());
3221 assert_eq!(p.owned_name_or_empty(), String::new());
3222 assert_eq!(p.owned_namespace_or_empty(), String::new());
3223 }
3224
3225 #[test]
3226 fn owned_namespace_or_empty_does_not_default_to_process_default_namespace() {
3227 // Deliberate-empty-sentinel pin: the primitive's fallback is
3228 // `""`, NOT `crate::crd::Process::DEFAULT_NAMESPACE`. The
3229 // sole downstream consumer (`AllocationConvergenceCtx::observe`)
3230 // feeds the produced value into `AllocationRef.namespace`,
3231 // which is then matched byte-identically against
3232 // `spec.pool_ref.namespace` at `resolve_pool`. A silent
3233 // substitution of `"default"` at this primitive would alias
3234 // every namespace-absent pool to the `"default"` bucket at
3235 // the matcher, hiding the missing-slot corner from an
3236 // operator who explicitly authored an allocation against a
3237 // namespace-unset pool. Pinned so a future "helpful"
3238 // canonicalization step lands as a compiler-visible failure
3239 // here rather than as silent operator-facing skew at the
3240 // matched-pool seed.
3241 let mut p = pool_named("attest-pool");
3242 p.metadata.namespace = None;
3243 assert_ne!(
3244 p.owned_namespace_or_empty(),
3245 crate::crd::Process::DEFAULT_NAMESPACE
3246 );
3247 assert_eq!(p.owned_namespace_or_empty(), "");
3248 }
3249
3250 // ─── EphemeralPool::owned_uid_or_name_or_empty substrate pins ─────
3251 //
3252 // Pins the compound owned-form projection on the paired
3253 // `(metadata.uid, metadata.name)` axis of the pool CRD — the
3254 // ONE-liner collapse of the paired `.metadata.uid.clone()
3255 // .unwrap_or_else(|| name.<into>())` chain every pool-slot-name
3256 // consumer restated by hand pre-lift at TWO production sites in
3257 // `tatara-pool-reconciler::controller_pool` (spawn arm +
3258 // apply_convergence_actions arm), both feeding the SAME
3259 // `member_process_name(&pool_name, &pool_uid_or_name_fallback,
3260 // slot)` composer. Fail-before-pass-after granularity:
3261 // `owned_uid_or_name_or_empty` did not exist on the pool CRD pre-
3262 // lift; the compiler cannot resolve the name until the impl block
3263 // above is in place, so a rollback of the primitive breaks this
3264 // whole module.
3265 #[test]
3266 fn owned_uid_or_name_or_empty_returns_uid_when_uid_is_present() {
3267 // Preferred-slot pin: uid populated → uid wins, regardless of
3268 // whether the name-fallback slot is populated. Byte-identical
3269 // to what each pre-lift `.metadata.uid.clone().unwrap_or_else
3270 // (|| name.<into>())` chain returned in the reachable-state
3271 // corner where the K8s API server has stamped a uid (the
3272 // common case at both callsites, which are already gated by
3273 // `owned_coordinates_required()?`).
3274 let mut p = pool_named("attest-pool");
3275 p.metadata.uid = Some("uid-42".into());
3276 assert_eq!(p.owned_uid_or_name_or_empty(), "uid-42");
3277 }
3278
3279 #[test]
3280 fn owned_uid_or_name_or_empty_falls_back_to_name_when_uid_is_missing() {
3281 // Fallback-slot pin: uid absent → name wins. Byte-identical
3282 // to what each pre-lift chain returned in the corner where
3283 // the K8s API server has NOT yet stamped a uid (pre-admission
3284 // / unit-test in-memory pool). The pre-lift chain reached
3285 // the fallback via a locally-bound `name` string derived from
3286 // the same `.metadata.name` slot the primitive reaches via
3287 // `owned_name_or_empty()`.
3288 let mut p = pool_named("attest-pool");
3289 p.metadata.uid = None;
3290 assert_eq!(p.owned_uid_or_name_or_empty(), "attest-pool");
3291 }
3292
3293 #[test]
3294 fn owned_uid_or_name_or_empty_sinks_to_empty_when_both_slots_are_missing() {
3295 // Missing-both corner pin: uid absent AND name absent → the
3296 // load-bearing empty-string sentinel. Coherent with the
3297 // sibling primitives `owned_name_or_empty` +
3298 // `owned_namespace_or_empty` on the SAME empty-sentinel axis.
3299 // A regression that dropped either fallback surfaces here
3300 // rather than as a runtime panic on `.unwrap()` at a spawn
3301 // callsite that assumed both slots were populated.
3302 let mut p = pool_named("attest-pool");
3303 p.metadata.uid = None;
3304 p.metadata.name = None;
3305 assert_eq!(p.owned_uid_or_name_or_empty(), String::new());
3306 assert!(p.owned_uid_or_name_or_empty().is_empty());
3307 }
3308
3309 #[test]
3310 fn owned_uid_or_name_or_empty_prefers_uid_when_both_slots_are_present() {
3311 // Precedence pin: both slots populated → uid wins. The pre-
3312 // lift `.unwrap_or_else(|| name.<into>())` chain's short-
3313 // circuit on the `Some(u)` arm skipped the fallback entirely;
3314 // the primitive matches that byte-for-byte via `.clone()
3315 // .unwrap_or_else(|| self.owned_name_or_empty())`, so the
3316 // name-fallback slot is not read when uid is populated.
3317 let mut p = pool_named("attest-pool");
3318 p.metadata.uid = Some("uid-preferred".into());
3319 p.metadata.name = Some("attest-pool".into());
3320 assert_eq!(p.owned_uid_or_name_or_empty(), "uid-preferred");
3321 assert_ne!(p.owned_uid_or_name_or_empty(), "attest-pool");
3322 }
3323
3324 #[test]
3325 fn owned_uid_or_name_or_empty_returns_uid_even_when_uid_is_explicitly_empty_string() {
3326 // Corner between `None` (missing slot) and `Some(String::new())`
3327 // (populated slot containing the empty string): the primitive
3328 // MUST return the populated-empty-string uid rather than
3329 // falling back to the name half — byte-identical to what the
3330 // pre-lift `.metadata.uid.clone().unwrap_or_else(|| name...)`
3331 // chain produced, whose `unwrap_or_else` short-circuits on
3332 // `Some(_)` regardless of the wrapped value. Pinned so a
3333 // future "helpful" canonicalization that treats
3334 // `Some(String::new())` as `None` at the primitive lands as
3335 // a compiler-visible failure here rather than as silent
3336 // operator-facing skew between the two spawn-slot-slug seeds.
3337 let mut p = pool_named("attest-pool");
3338 p.metadata.uid = Some(String::new());
3339 p.metadata.name = Some("attest-pool".into());
3340 assert_eq!(p.owned_uid_or_name_or_empty(), String::new());
3341 assert_ne!(p.owned_uid_or_name_or_empty(), "attest-pool");
3342 }
3343
3344 #[test]
3345 fn owned_uid_or_name_or_empty_is_a_pure_projection() {
3346 // Consecutive calls return byte-identical Strings across the
3347 // FULL corner set (uid-present, uid-absent name-fallback,
3348 // both-absent empty-sentinel) — no cached state, no mutation
3349 // on the `EphemeralPool` between calls. Peer to the sibling
3350 // `owned_name_or_empty_is_a_pure_projection` +
3351 // `owned_namespace_or_empty_is_a_pure_projection` pins in
3352 // this module; all three bind the pure-projection discipline
3353 // on the ONE substrate accessor per metadata-derived slot.
3354 let mut p = pool_named("attest-pool");
3355 p.metadata.uid = Some("uid-42".into());
3356 assert_eq!(
3357 p.owned_uid_or_name_or_empty(),
3358 p.owned_uid_or_name_or_empty()
3359 );
3360 p.metadata.uid = None;
3361 assert_eq!(
3362 p.owned_uid_or_name_or_empty(),
3363 p.owned_uid_or_name_or_empty()
3364 );
3365 p.metadata.name = None;
3366 assert_eq!(
3367 p.owned_uid_or_name_or_empty(),
3368 p.owned_uid_or_name_or_empty()
3369 );
3370 }
3371
3372 #[test]
3373 fn owned_uid_or_name_or_empty_matches_pre_lift_chain_verbatim() {
3374 // Byte-identical parity with the two hand-authored
3375 // `.metadata.uid.clone().unwrap_or_else(|| name.<into>())`
3376 // chains the primitive replaces in
3377 // `tatara-pool-reconciler::controller_pool` (spawn arm +
3378 // apply_convergence_actions arm). Runs across the FULL
3379 // corner set of the paired (metadata.uid, metadata.name)
3380 // slots. A regression that inserted a normalization step at
3381 // the primitive the pre-lift chain does NOT apply — or vice
3382 // versa — surfaces here rather than as silent drift between
3383 // the two owned-form callsites and the ONE substrate owner
3384 // they now route through.
3385 let cases: [(Option<String>, Option<String>, &str); 6] = [
3386 (Some("uid-42".into()), Some("attest-pool".into()), "uid-42"),
3387 (Some("uid-42".into()), None, "uid-42"),
3388 (Some(String::new()), Some("attest-pool".into()), ""),
3389 (None, Some("attest-pool".into()), "attest-pool"),
3390 (None, Some(String::new()), ""),
3391 (None, None, ""),
3392 ];
3393 for (uid_slot, name_slot, expected) in cases {
3394 let mut p = pool_named("attest-pool");
3395 p.metadata.uid = uid_slot.clone();
3396 p.metadata.name = name_slot.clone();
3397 // Reproduce the pre-lift chain shape at the spawn arm
3398 // (fallback `|| name.clone()` on an extracted-earlier
3399 // `String` name) — semantically equivalent to
3400 // `.metadata.name.clone().unwrap_or_default()` at the
3401 // point of call because `owned_coordinates_required()?`
3402 // gate guarantees the caller's `name` binding matches
3403 // the pool's own `metadata.name` slot.
3404 let pre_lift = p
3405 .metadata
3406 .uid
3407 .clone()
3408 .unwrap_or_else(|| p.metadata.name.clone().unwrap_or_default());
3409 assert_eq!(pre_lift.as_str(), expected, "pre-lift chain sanity");
3410 assert_eq!(p.owned_uid_or_name_or_empty(), pre_lift);
3411 assert_eq!(p.owned_uid_or_name_or_empty().as_str(), expected);
3412 }
3413 }
3414
3415 #[test]
3416 fn owned_uid_or_name_or_empty_composes_with_member_process_name_seed_shape() {
3417 // Composition pin: the produced owned `String` feeds the
3418 // downstream `member_process_name(&pool_name, &pool_uid_or_
3419 // name_fallback, slot)` composer at both callsites, so the
3420 // seed's `String` shape must survive being borrowed as
3421 // `&str` for the composer without any owned/borrow-form
3422 // adaptation at the callsite. Binds the primitive's return
3423 // type + the borrow-form availability that the pre-lift
3424 // chain also produced (a locally-owned `String` from
3425 // `.clone().unwrap_or_else(|| name.<into>())`).
3426 let mut p = pool_named("attest-pool");
3427 p.metadata.uid = Some("uid-42".into());
3428 let seed: String = p.owned_uid_or_name_or_empty();
3429 let _borrowed: &str = &seed;
3430 assert_eq!(seed, "uid-42");
3431 p.metadata.uid = None;
3432 let seed_fallback: String = p.owned_uid_or_name_or_empty();
3433 let _borrowed_fallback: &str = &seed_fallback;
3434 assert_eq!(seed_fallback, "attest-pool");
3435 }
3436
3437 // ─── AllocationRef::new substrate pins ────────────────────────────
3438 //
3439 // Pins the substrate constructor for [`AllocationRef`] — the
3440 // ONE-liner composer that lifts the paired
3441 // `AllocationRef { name, namespace }` struct-literal every
3442 // downstream consumer restated by hand pre-lift at FOUR production
3443 // sites (2 × controller_allocation.rs assignedProcess seeds, 1 ×
3444 // allocation_decide.rs pool_ref seed, 1 × allocation_factory.rs
3445 // pool_ref seed) onto ONE substrate owner on `AllocationRef`.
3446 // Fail-before-pass-after granularity: `AllocationRef::new` did not
3447 // exist pre-lift; the compiler cannot resolve the name until the
3448 // impl block above is in place, so a rollback of the primitive
3449 // breaks this whole module.
3450
3451 #[test]
3452 fn allocation_ref_new_composes_owned_string_pair_verbatim() {
3453 // Happy-path pin: the constructor materializes an
3454 // `AllocationRef { name: <name>, namespace: <namespace> }`
3455 // byte-identical to the pre-lift struct literal every consumer
3456 // spelled. A regression that dropped either slot (e.g. an
3457 // erroneous `..Default::default()` on a shape that never had
3458 // a Default derive) surfaces here rather than as silent slot
3459 // loss downstream at the assignedProcess / bound_pool /
3460 // matched_pool / spec.pool_ref sinks.
3461 let r = AllocationRef::new(String::from("pr-42-demo"), String::from("ephemeral-pools"));
3462 assert_eq!(r.name, "pr-42-demo");
3463 assert_eq!(r.namespace, "ephemeral-pools");
3464 }
3465
3466 #[test]
3467 fn allocation_ref_new_matches_pre_lift_struct_literal_verbatim() {
3468 // Byte-identical parity pin: the substrate constructor and the
3469 // hand-authored struct literal produce equal `AllocationRef`
3470 // values on every provenance the FOUR pre-lift sites carried
3471 // (owned `String` from an owned-form projection; `&str`
3472 // promoted through `.to_string()`). A regression that inserted
3473 // a normalization step at the primitive the pre-lift literal
3474 // does NOT apply — or vice versa — surfaces here rather than
3475 // as silent drift between the four consumers and the ONE
3476 // substrate owner they now route through.
3477 let owned_name = String::from("pr-42-demo");
3478 let owned_ns = String::from("ephemeral-pools");
3479 let lifted = AllocationRef::new(owned_name.clone(), owned_ns.clone());
3480 let pre_lift = AllocationRef {
3481 name: owned_name,
3482 namespace: owned_ns,
3483 };
3484 assert_eq!(lifted, pre_lift);
3485 }
3486
3487 #[test]
3488 fn allocation_ref_new_accepts_str_provenance_via_into_string() {
3489 // `Into<String>` provenance-closure pin: the primitive accepts
3490 // every provenance the pre-lift sites carried. The
3491 // controller_allocation.rs assignedProcess seeds passed owned
3492 // `String` values (a moved `member_process_name` +
3493 // `ns.clone()`); the allocation_factory.rs pool_ref seed
3494 // passed `&str` (`n.to_string()` / `namespace.to_string()`).
3495 // Both provenances produce byte-identical output. A future
3496 // refactor of the constructor signature that demanded owned
3497 // `String` at author sites (dropping `impl Into<String>`)
3498 // would force `.to_string()` back at the FOUR call sites — the
3499 // pin fences that regression at ONE place.
3500 let from_str = AllocationRef::new("pr-42-demo", "ephemeral-pools");
3501 let from_string =
3502 AllocationRef::new(String::from("pr-42-demo"), String::from("ephemeral-pools"));
3503 assert_eq!(from_str, from_string);
3504 // Mixed provenance is also load-bearing: the allocation_decide.rs
3505 // matched_pool seed pairs an owned `String` (from
3506 // `EphemeralPool::owned_name_or_empty()`) with a hand-authored
3507 // `.clone().unwrap_or_default()` — also `String`. The
3508 // controller_allocation.rs paths pair a moved `String` name
3509 // with a `.clone()`-ed `ns: String`. Verify (owned, borrow)
3510 // and (borrow, owned) both compose to the same shape as
3511 // (owned, owned) / (borrow, borrow).
3512 let mixed_a = AllocationRef::new(String::from("pr-42-demo"), "ephemeral-pools");
3513 let mixed_b = AllocationRef::new("pr-42-demo", String::from("ephemeral-pools"));
3514 assert_eq!(from_str, mixed_a);
3515 assert_eq!(from_str, mixed_b);
3516 }
3517
3518 #[test]
3519 fn allocation_ref_new_positional_axis_order_pinned_name_first_namespace_second() {
3520 // Axis-order pin: name is the FIRST positional argument;
3521 // namespace is the SECOND. Reversing the pair at the
3522 // constructor is the exact regression this pin fences — the
3523 // FOUR pre-lift sites all spelled `name` before `namespace`
3524 // (matching the struct definition's field order in
3525 // `pub struct AllocationRef { pub name, pub namespace }`)
3526 // and the wire-format serde output `{ "name": "...",
3527 // "namespace": "..." }` reflects that order. A slot swap at
3528 // the primitive would surface here rather than as silent
3529 // `<namespace>/<name>` inversion at every downstream
3530 // qualified-ref composer that reads `{ref.name}/{ref.namespace}`
3531 // as an audit-log key.
3532 let r = AllocationRef::new("alpha-name", "beta-namespace");
3533 assert_eq!(r.name, "alpha-name");
3534 assert_eq!(r.namespace, "beta-namespace");
3535 assert_ne!(r.name, "beta-namespace");
3536 assert_ne!(r.namespace, "alpha-name");
3537 }
3538
3539 #[test]
3540 fn allocation_ref_new_preserves_empty_string_verbatim() {
3541 // Empty-string sentinel pin: the constructor is pure — it does
3542 // NOT canonicalize empty inputs (does NOT default an empty
3543 // namespace to `"default"`; does NOT reject an empty name).
3544 // Preserves the pre-lift shape the allocation_decide.rs
3545 // matched_pool seed relied on: when the pool's metadata.namespace
3546 // is absent, `.clone().unwrap_or_default()` yields the empty
3547 // string, and the AllocationRef's namespace slot carries that
3548 // empty string verbatim to the downstream `bound_pool` sink.
3549 // A future canonicalization pass (e.g. defaulting to
3550 // `Process::DEFAULT_NAMESPACE`) MUST land here, not at the
3551 // primitive body silently, so the pre-lift consumers' empty-
3552 // sentinel semantics are the visible contract of the new
3553 // constructor.
3554 let r = AllocationRef::new("", "");
3555 assert_eq!(r.name, "");
3556 assert_eq!(r.namespace, "");
3557 let mixed = AllocationRef::new("pr-42-demo", "");
3558 assert_eq!(mixed.name, "pr-42-demo");
3559 assert_eq!(mixed.namespace, "");
3560 }
3561
3562 #[test]
3563 fn allocation_ref_new_composes_with_owned_name_or_empty_pool_projection() {
3564 // Composition pin: the constructor composes with the paired
3565 // substrate primitives [`EphemeralPool::owned_name_or_empty`]
3566 // + [`EphemeralPool::owned_namespace_or_empty`] at the
3567 // allocation_decide.rs pool_ref seed — the same primitive
3568 // family the pool CRD opened for both halves of the
3569 // `AllocationRef { name, namespace }` struct literal. The
3570 // composed pair carries an owned `String` name half (from
3571 // `pool.owned_name_or_empty()`) and an owned `String`
3572 // namespace half (from `pool.owned_namespace_or_empty()`) —
3573 // no pre-lift chain remains. A regression that broke the
3574 // primitive family's `impl Into<String>` acceptance of an
3575 // owned `String` return type would surface here rather than
3576 // as silent build failure at the pool-reconciler matched_pool
3577 // seed.
3578 let pool = pool_named("attest-pool");
3579 let r = AllocationRef::new(pool.owned_name_or_empty(), pool.owned_namespace_or_empty());
3580 assert_eq!(r.name, "attest-pool");
3581 assert_eq!(r.namespace, pool.owned_namespace_or_empty());
3582 }
3583
3584 #[test]
3585 fn allocation_ref_new_returns_wire_format_serialization_verbatim() {
3586 // Wire-format pin: the constructor produces an
3587 // [`AllocationRef`] whose serde `rename_all = "camelCase"`
3588 // serialization is byte-identical to the pre-lift struct
3589 // literal's serialization. The `bound_pool` and
3590 // `assignedProcess` slots on `AllocationStatus` (and the
3591 // `poolRef` slot on `AllocationSpec`) all round-trip through
3592 // this shape — the pin fences a regression that added a
3593 // private field or a `#[serde(skip)]` accidentally.
3594 let r = AllocationRef::new("pr-42-demo", "ephemeral-pools");
3595 let yaml = serde_yaml::to_string(&r).expect("AllocationRef serializes to yaml");
3596 assert!(yaml.contains("name: pr-42-demo"), "{yaml}");
3597 assert!(yaml.contains("namespace: ephemeral-pools"), "{yaml}");
3598 let back: AllocationRef =
3599 serde_yaml::from_str(&yaml).expect("AllocationRef round-trips through yaml");
3600 assert_eq!(back, r);
3601 }
3602
3603 fn member(state: MemberState) -> PoolMember {
3604 // 4-slot unallocated seed rides through the ONE substrate
3605 // owner `PoolMember::unallocated` (peer of the four workspace-
3606 // wide restatements of the SAME `PoolMember { process_name,
3607 // state, entered_state_at, allocation_ref: None }` fixture
3608 // literal that pre-lift lived at the production `controller_
3609 // pool::reconcile_inner` walk + the two `pool_decide::tests::
3610 // member` / `allocation_decide::tests::member` helpers + the
3611 // sibling `named_member` helper in this file).
3612 PoolMember::unallocated("m", state, crate::time::at_epoch_second(0))
3613 }
3614
3615 #[test]
3616 fn state_count_fanout_returns_all_zeros_on_empty_slice() {
3617 // Zero-length pin: the empty-members corner produces a
3618 // 4-tuple of zero counters, matching the pre-lift
3619 // `count_state` fanout's four `.iter().filter(...).count()`
3620 // calls each returning 0 on an empty iterator.
3621 assert_eq!(PoolMember::state_count_fanout(&[]), (0, 0, 0, 0));
3622 }
3623
3624 #[test]
3625 fn state_count_fanout_partitions_variants_into_correct_slots() {
3626 // Positional-axis pin: the returned 4-tuple's slot order
3627 // matches the four `PoolStatus` counter slots in declaration
3628 // order — `(ready, allocated, spawning, returning)`. A
3629 // regression that swapped two slots (e.g., `ready` ↔
3630 // `spawning`) surfaces here rather than as an operator-facing
3631 // scale-out oscillation at the pool reconciler.
3632 let members = vec![
3633 member(MemberState::Free),
3634 member(MemberState::Free),
3635 member(MemberState::Allocated),
3636 member(MemberState::Spawning),
3637 member(MemberState::Spawning),
3638 member(MemberState::Spawning),
3639 member(MemberState::Returning),
3640 ];
3641 assert_eq!(PoolMember::state_count_fanout(&members), (2, 1, 3, 1));
3642 }
3643
3644 #[test]
3645 fn state_count_fanout_excludes_failed_from_every_counter() {
3646 // Closed-set pin: no `PoolStatus` slot counts `Failed` members
3647 // (they surface via `PoolPhase::Degraded` instead of a status
3648 // counter). This test fences a regression that let a `Failed`
3649 // member drift into one of the four counters and inflate the
3650 // operator-visible ready/allocated/spawning/returning fanout.
3651 let members = vec![
3652 member(MemberState::Failed),
3653 member(MemberState::Failed),
3654 member(MemberState::Failed),
3655 ];
3656 assert_eq!(PoolMember::state_count_fanout(&members), (0, 0, 0, 0));
3657
3658 // Mixed with a Free member: the Free member is counted, the
3659 // Failed members are not.
3660 let mixed = vec![
3661 member(MemberState::Free),
3662 member(MemberState::Failed),
3663 member(MemberState::Failed),
3664 ];
3665 assert_eq!(PoolMember::state_count_fanout(&mixed), (1, 0, 0, 0));
3666 }
3667
3668 #[test]
3669 fn state_count_fanout_matches_pre_lift_count_state_helper_verbatim() {
3670 // Parity pin: for every possible members list, the 4-tuple
3671 // returned by the substrate primitive matches the pre-lift
3672 // `count_state(&members, MemberState::<slot>)` fanout that
3673 // pool-reconciler restated at both status-patch sites. The
3674 // pre-lift helper was
3675 // ```rust,ignore
3676 // fn count_state(members: &[PoolMember], target: MemberState) -> u32 {
3677 // members.iter().filter(|m| m.state == target).count() as u32
3678 // }
3679 // ```
3680 // — re-implemented inline here as an oracle.
3681 fn count_state(members: &[PoolMember], target: MemberState) -> u32 {
3682 members.iter().filter(|m| m.state == target).count() as u32
3683 }
3684 let members = vec![
3685 member(MemberState::Free),
3686 member(MemberState::Allocated),
3687 member(MemberState::Allocated),
3688 member(MemberState::Spawning),
3689 member(MemberState::Returning),
3690 member(MemberState::Returning),
3691 member(MemberState::Failed),
3692 ];
3693 let (ready, allocated, spawning, returning) = PoolMember::state_count_fanout(&members);
3694 assert_eq!(ready, count_state(&members, MemberState::Free));
3695 assert_eq!(allocated, count_state(&members, MemberState::Allocated));
3696 assert_eq!(spawning, count_state(&members, MemberState::Spawning));
3697 assert_eq!(returning, count_state(&members, MemberState::Returning));
3698 }
3699
3700 // ─── PoolMember::process_names_set substrate pins ─────────────────
3701 //
3702 // Pins the closed-set slice-owned collection primitive on the
3703 // `process_name` axis into a `HashSet<String>` — the O(1)-lookup
3704 // shape both spawn arms in
3705 // `tatara-pool-reconciler::controller_pool` build pre-collision-
3706 // check against a candidate `member_process_name(&pool_name,
3707 // &pool_uid, slot)`. Sibling to `state_count_fanout` on the
3708 // `(collection shape × slice-owned fold)` axis; the fanout owns
3709 // the state-counter tuple corner, this primitive owns the
3710 // process-name-lookup corner. Fail-before-pass-after granularity:
3711 // `process_names_set` did not exist pre-lift; the compiler cannot
3712 // resolve the name until the impl block above is in place, so a
3713 // rollback of the primitive breaks this whole test group.
3714
3715 fn named_member(process_name: &str, state: MemberState) -> PoolMember {
3716 // 4-slot unallocated seed rides through the ONE substrate
3717 // owner `PoolMember::unallocated` — sibling to the `member`
3718 // helper in this file on the same epoch-anchored axis.
3719 PoolMember::unallocated(process_name, state, crate::time::at_epoch_second(0))
3720 }
3721
3722 #[test]
3723 fn process_names_set_returns_empty_hashset_on_empty_slice() {
3724 // Zero-length pin: the empty-members corner produces an
3725 // empty `HashSet<String>`, matching the pre-lift
3726 // `.iter().map(...).collect()` chain's empty-iterator
3727 // behavior. A regression that started producing a sentinel
3728 // entry (a `""` placeholder, a static seed) on the empty-
3729 // slice corner would silently reject the first spawn slot
3730 // downstream — the pin closes that failure mode.
3731 let empty: Vec<PoolMember> = vec![];
3732 assert!(PoolMember::process_names_set(&empty).is_empty());
3733 }
3734
3735 #[test]
3736 fn process_names_set_collects_every_process_name_from_populated_slice() {
3737 // Positive pin: every `PoolMember`'s `process_name` slot
3738 // lands in the returned `HashSet<String>` verbatim. Cross-
3739 // state (Free / Allocated / Spawning / Returning / Failed)
3740 // to prove the primitive is state-agnostic — the spawn arms
3741 // check occupancy on the name axis, NOT the state axis, so a
3742 // future refactor that filtered by state would silently
3743 // leave a returned/failed slot open to a duplicate spawn.
3744 let members = vec![
3745 named_member("pool-a-0", MemberState::Free),
3746 named_member("pool-a-1", MemberState::Allocated),
3747 named_member("pool-a-2", MemberState::Spawning),
3748 named_member("pool-a-3", MemberState::Returning),
3749 named_member("pool-a-4", MemberState::Failed),
3750 ];
3751 let set = PoolMember::process_names_set(&members);
3752 assert_eq!(set.len(), 5);
3753 for slot in 0..5 {
3754 let want = format!("pool-a-{slot}");
3755 assert!(set.contains(&want), "missing {want}; set = {set:?}");
3756 }
3757 }
3758
3759 #[test]
3760 fn process_names_set_deduplicates_duplicate_process_names() {
3761 // Deduplication pin: two `PoolMember` entries with the same
3762 // `process_name` (a race between the two spawn arms, an
3763 // adopted foreign Process the reconciler picked up twice)
3764 // collapse to ONE entry in the `HashSet<String>`. Pins the
3765 // `HashSet` deduplication semantics the pre-lift `.iter()
3766 // .map(...).collect()` chain already inherited from the
3767 // `FromIterator` impl — a regression that swapped the
3768 // aggregate to a `Vec<String>` or `BTreeSet<String>` still
3769 // matches the shape but changes the operator-visible count
3770 // at the `.len()` probe here.
3771 let members = vec![
3772 named_member("pool-b-0", MemberState::Free),
3773 named_member("pool-b-0", MemberState::Spawning),
3774 named_member("pool-b-1", MemberState::Free),
3775 ];
3776 let set = PoolMember::process_names_set(&members);
3777 assert_eq!(set.len(), 2);
3778 assert!(set.contains("pool-b-0"));
3779 assert!(set.contains("pool-b-1"));
3780 }
3781
3782 #[test]
3783 fn process_names_set_membership_probe_matches_pre_lift_chain_verbatim() {
3784 // Byte-identical parity pin: the `.contains(&candidate)`
3785 // probe on the substrate's `HashSet<String>` return returns
3786 // the same `bool` as the pre-lift `members.iter().map(|m|
3787 // m.process_name.clone()).collect::<HashSet<_>>().contains
3788 // (&candidate)` chain across the FULL cross product of
3789 // (candidate ∈ {an existing name, a novel name, the empty
3790 // string}). A regression that inserted a normalization step
3791 // at the primitive the pre-lift chain does NOT apply — or
3792 // vice versa — surfaces here rather than as silent drift
3793 // between the two spawn arms the primitive owns.
3794 let members = vec![
3795 named_member("pool-c-0", MemberState::Free),
3796 named_member("pool-c-1", MemberState::Allocated),
3797 ];
3798 let candidates: [&str; 4] = ["pool-c-0", "pool-c-1", "pool-c-2", ""];
3799 let via_primitive = PoolMember::process_names_set(&members);
3800 for candidate in candidates {
3801 let pre_lift: std::collections::HashSet<String> =
3802 members.iter().map(|m| m.process_name.clone()).collect();
3803 assert_eq!(
3804 via_primitive.contains(candidate),
3805 pre_lift.contains(candidate),
3806 "candidate = {candidate:?}"
3807 );
3808 }
3809 }
3810
3811 #[test]
3812 fn process_names_set_is_a_pure_projection() {
3813 // Consecutive calls on the same slice return equal sets —
3814 // no cached state, no mutation on the input. Guards against
3815 // a future refactor that plants a cache field somewhere and
3816 // drifts one caller from another silently.
3817 let members = vec![
3818 named_member("pool-d-0", MemberState::Free),
3819 named_member("pool-d-1", MemberState::Spawning),
3820 ];
3821 let first = PoolMember::process_names_set(&members);
3822 let second = PoolMember::process_names_set(&members);
3823 assert_eq!(first, second);
3824 }
3825
3826 #[test]
3827 fn pool_status_observed_composes_pre_lift_status_seed_verbatim() {
3828 // Composition pin: the substrate constructor produces a
3829 // `PoolStatus` structurally equal to the pre-lift 11-line
3830 // struct literal both pool-reconciler status-patch sites
3831 // stamped by hand. Any drift in the defaults (`message`,
3832 // `conditions`) or in the counter fanout surfaces here.
3833 let now = crate::time::at_epoch_second(1_700_000_000);
3834 let members = vec![
3835 member(MemberState::Free),
3836 member(MemberState::Allocated),
3837 member(MemberState::Spawning),
3838 member(MemberState::Returning),
3839 member(MemberState::Failed),
3840 ];
3841 let member_count = members.len();
3842 let observed = PoolStatus::observed(PoolPhase::Steady, members, now);
3843 assert_eq!(observed.phase, PoolPhase::Steady);
3844 assert_eq!(observed.phase_since, Some(now));
3845 assert_eq!(observed.ready_count, 1);
3846 assert_eq!(observed.allocated_count, 1);
3847 assert_eq!(observed.spawning_count, 1);
3848 assert_eq!(observed.returning_count, 1);
3849 assert_eq!(observed.members.len(), member_count);
3850 assert!(observed.message.is_none());
3851 assert!(observed.conditions.is_empty());
3852 }
3853
3854 #[test]
3855 fn pool_status_observed_moves_members_by_value_without_extra_clone() {
3856 // Ownership pin: the constructor consumes the members Vec by
3857 // value rather than borrowing + cloning internally. Both pre-
3858 // lift sites called `.clone()` on their `members` binding for
3859 // the struct-literal `members:` slot; the substrate lift keeps
3860 // the same one-clone bound at the caller (or a straight move
3861 // if the caller no longer needs the local `members` binding
3862 // after the seed) rather than accidentally cloning twice.
3863 let members = vec![member(MemberState::Free), member(MemberState::Spawning)];
3864 let now = crate::time::at_epoch_second(0);
3865 let observed = PoolStatus::observed(PoolPhase::Steady, members, now);
3866 assert_eq!(observed.members.len(), 2);
3867 }
3868
3869 // ─── PoolStatus::observed_now substrate pins ─────────────────────
3870 //
3871 // Bind [`PoolStatus::observed_now`] at fail-before-pass-after
3872 // granularity so a regression that dropped the wall-clock read
3873 // (yielding a `phase_since` of `Some(DateTime::default())`),
3874 // reshaped the delegation target (a peer 4-arg composer that
3875 // stamped different defaults), or diverged the peer from the 3-arg
3876 // [`PoolStatus::observed`] on any observable slot surfaces HERE
3877 // rather than as silent operator-facing drift at the two
3878 // controller_pool status-patch sites.
3879 //
3880 // Each pin is fail-before-pass-after: the primitive did not exist
3881 // pre-lift, so any test that invokes it fails to compile pre-lift
3882 // and passes post-lift; the byte-identity pins below then bind the
3883 // specific shape choice.
3884
3885 #[test]
3886 fn pool_status_observed_now_composes_through_observed_with_wall_clock() {
3887 // Composition pin: `observed_now` MUST agree with the 3-arg
3888 // `observed(phase, members, Utc::now())` peer at every slot
3889 // other than `phase_since` (which reads the wall clock at
3890 // different instants and diverges by scheduler jitter). A
3891 // regression that specialized either composer (a stray
3892 // canonicalization at `observed_now`, a swapped default at the
3893 // 3-arg peer) would surface HERE rather than as silent skew at
3894 // the two controller_pool sites the primitive owns.
3895 let members = vec![
3896 member(MemberState::Free),
3897 member(MemberState::Allocated),
3898 member(MemberState::Spawning),
3899 member(MemberState::Returning),
3900 ];
3901 let via_now = PoolStatus::observed_now(PoolPhase::Steady, members.clone());
3902 let via_injected =
3903 PoolStatus::observed(PoolPhase::Steady, members.clone(), chrono::Utc::now());
3904 assert_eq!(via_now.phase, via_injected.phase);
3905 assert_eq!(via_now.ready_count, via_injected.ready_count);
3906 assert_eq!(via_now.allocated_count, via_injected.allocated_count);
3907 assert_eq!(via_now.spawning_count, via_injected.spawning_count);
3908 assert_eq!(via_now.returning_count, via_injected.returning_count);
3909 assert_eq!(via_now.members.len(), via_injected.members.len());
3910 assert_eq!(via_now.message, via_injected.message);
3911 assert_eq!(via_now.conditions.len(), via_injected.conditions.len());
3912 }
3913
3914 #[test]
3915 fn pool_status_observed_now_reads_wall_clock_into_phase_since() {
3916 // Wall-clock pin: `phase_since` MUST fall between `Utc::now()`
3917 // reads bracketed around the call. A regression that dropped
3918 // the wall-clock read to a module-load constant (`Utc::now()`
3919 // captured at `static` init), a `DateTime::default()` (epoch),
3920 // or a stale `None` would fail this bracket check.
3921 let before = chrono::Utc::now();
3922 let observed = PoolStatus::observed_now(PoolPhase::Steady, vec![]);
3923 let after = chrono::Utc::now();
3924 let phase_since = observed
3925 .phase_since
3926 .expect("observed_now must stamp phase_since with the wall clock");
3927 assert!(
3928 phase_since >= before && phase_since <= after,
3929 "phase_since {phase_since} must fall in [{before}, {after}]"
3930 );
3931 }
3932
3933 #[test]
3934 fn pool_status_observed_now_stamps_the_same_defaults_as_the_injected_peer() {
3935 // Defaults pin: `message: None` + `conditions: vec![]` MUST
3936 // agree with the 3-arg [`PoolStatus::observed`] peer verbatim.
3937 // A regression that stamped a per-caller message default at
3938 // `observed_now` (a "wall-clock-stamped observation" prefix,
3939 // say) or seeded a "just-observed" Condition row would surface
3940 // HERE rather than as silent operator-facing drift at either
3941 // status-patch site.
3942 let observed = PoolStatus::observed_now(PoolPhase::Steady, vec![]);
3943 assert!(observed.message.is_none());
3944 assert!(observed.conditions.is_empty());
3945 }
3946
3947 #[test]
3948 fn pool_status_observed_now_wall_clock_is_read_per_invocation_not_cached() {
3949 // Monotonic-read pin: two back-to-back `observed_now` calls
3950 // MUST read `Utc::now()` twice — the second `phase_since` MUST
3951 // be `>=` the first. A regression that cached a wall-clock read
3952 // into a `OnceLock` / lazy `static` would fire the SAME
3953 // `phase_since` for every caller on the reconciler's process
3954 // and every status-patch would carry the module-load instant
3955 // rather than the tick instant. Both instants may coincide on
3956 // a fast machine; use `>=` (not `>`) to keep the pin robust
3957 // against subsecond scheduler granularity while still catching
3958 // a cached-constant regression (where the second read would
3959 // be < the wall clock).
3960 let first = PoolStatus::observed_now(PoolPhase::Steady, vec![])
3961 .phase_since
3962 .expect("first observed_now stamps phase_since");
3963 let second = PoolStatus::observed_now(PoolPhase::Steady, vec![])
3964 .phase_since
3965 .expect("second observed_now stamps phase_since");
3966 assert!(
3967 second >= first,
3968 "second phase_since {second} must be >= first phase_since {first}"
3969 );
3970 // AND the second read MUST NOT precede the wall clock reads
3971 // bracketing the call — a cached-past constant would fail
3972 // this bound.
3973 let after = chrono::Utc::now();
3974 assert!(
3975 second <= after,
3976 "second phase_since {second} must be <= {after}"
3977 );
3978 }
3979
3980 #[test]
3981 fn pool_status_observed_now_matches_pre_lift_utc_now_composition_shape() {
3982 // Byte-identical parity with the pre-lift
3983 // `PoolStatus::observed(phase, members.clone(), Utc::now())`
3984 // block both hand-authored callsites restated at their status-
3985 // patch sites, swept across representative pool-phase variants.
3986 // Both blocks read the wall clock at DIFFERENT instants so the
3987 // two anchors CAN differ by the wall-clock delta between calls
3988 // — bound the divergence at 100ms scheduler jitter, matching
3989 // the peer `seconds_ago_matches_hand_authored_pre_lift_chain_shape`
3990 // pin's tolerance on the sibling `crate::time` module.
3991 let members = vec![member(MemberState::Free), member(MemberState::Spawning)];
3992 for phase in [PoolPhase::Steady, PoolPhase::ScalingUp, PoolPhase::Degraded] {
3993 let composed = PoolStatus::observed_now(phase, members.clone())
3994 .phase_since
3995 .expect("observed_now stamps phase_since");
3996 let hand_authored = PoolStatus::observed(phase, members.clone(), chrono::Utc::now())
3997 .phase_since
3998 .expect("observed stamps phase_since");
3999 let delta = (hand_authored - composed).abs();
4000 assert!(
4001 delta <= chrono::Duration::milliseconds(100),
4002 "composed {composed} and hand-authored {hand_authored} must agree within 100ms scheduler jitter for phase={phase:?}"
4003 );
4004 }
4005 }
4006
4007 // ─── PoolMember::unallocated substrate pins ───────────────────────
4008 //
4009 // Pins the 4-slot `{ process_name, state, entered_state_at,
4010 // allocation_ref: None }` composer's fill at fail-before-pass-after
4011 // granularity: `unallocated` did not exist pre-lift; the compiler
4012 // cannot resolve the name until the impl block above is in place,
4013 // so a rollback of the primitive breaks this whole test group. The
4014 // primitive owns FIVE workspace-wide seed sites (one production
4015 // walk in `tatara-pool-reconciler::controller_pool::reconcile_inner`
4016 // and four test helpers across `pool.rs`, `pool_decide.rs`, and
4017 // `allocation_decide.rs`) so a regression that drifts any of the
4018 // four slots (a mistyped `allocation_ref: Some(<sentinel>)`, a
4019 // reversed positional order at the composer entry, an accidental
4020 // canonicalization of the `entered_state_at` anchor) surfaces here
4021 // rather than as silent operator-facing skew between the production
4022 // seed and the three test-suite helpers on the SAME `PoolMember`
4023 // shape.
4024
4025 #[test]
4026 fn pool_member_unallocated_fills_every_slot_verbatim() {
4027 // Positional-axis pin: the composer's four inputs land at the
4028 // four struct slots in declaration order. A regression that
4029 // swapped `process_name` and `entered_state_at` at the composer
4030 // entry (or that renamed the `allocation_ref` invariant slot to
4031 // a different `None`-preserving field) surfaces here.
4032 let anchor = crate::time::at_epoch_second(1_700_000_000);
4033 let m = PoolMember::unallocated("pool-x-0", MemberState::Free, anchor);
4034 assert_eq!(m.process_name, "pool-x-0");
4035 assert_eq!(m.state, MemberState::Free);
4036 assert_eq!(m.entered_state_at, anchor);
4037 assert!(m.allocation_ref.is_none());
4038 }
4039
4040 #[test]
4041 fn pool_member_unallocated_accepts_owned_string_and_str_at_the_same_signature() {
4042 // `impl Into<String>` axis pin: both the `&'static str` shape
4043 // (every test-helper site) and the `String` shape (produced by
4044 // `Process::owned_name_or_empty` at the production
4045 // `controller_pool::reconcile_inner` site) reach the same
4046 // composer entry without a per-caller conversion. A regression
4047 // that narrowed the signature to `&str` alone would break the
4048 // production site's `owned_name_or_empty` handoff; a regression
4049 // that narrowed to `String` alone would force every test helper
4050 // to `.into()` at the callsite. This pin fences both corners.
4051 let anchor = crate::time::at_epoch_second(0);
4052 let via_str = PoolMember::unallocated("pool-y-0", MemberState::Spawning, anchor);
4053 let owned: String = "pool-y-0".to_string();
4054 let via_string = PoolMember::unallocated(owned, MemberState::Spawning, anchor);
4055 assert_eq!(via_str.process_name, via_string.process_name);
4056 assert_eq!(via_str.state, via_string.state);
4057 assert_eq!(via_str.entered_state_at, via_string.entered_state_at);
4058 assert_eq!(via_str.allocation_ref, via_string.allocation_ref);
4059 }
4060
4061 #[test]
4062 fn pool_member_unallocated_matches_pre_lift_struct_literal_bytewise() {
4063 // Byte-shape parity pin: the composer output is structurally
4064 // equal to the pre-lift 4-slot struct literal every hand-
4065 // authored site stamped. Sweeps every `MemberState` variant so
4066 // a regression that special-cased one variant (e.g., pinned
4067 // `Allocated` to a bogus `Some(<placeholder>)` at the composer)
4068 // surfaces here rather than at the four downstream helpers'
4069 // callsites.
4070 let anchor = crate::time::at_epoch_second(1_700_000_000);
4071 for state in [
4072 MemberState::Free,
4073 MemberState::Allocated,
4074 MemberState::Spawning,
4075 MemberState::Returning,
4076 MemberState::Failed,
4077 ] {
4078 let via_primitive = PoolMember::unallocated("m", state, anchor);
4079 let hand_authored = PoolMember {
4080 process_name: "m".into(),
4081 state,
4082 entered_state_at: anchor,
4083 allocation_ref: None,
4084 };
4085 assert_eq!(via_primitive.process_name, hand_authored.process_name);
4086 assert_eq!(via_primitive.state, hand_authored.state);
4087 assert_eq!(
4088 via_primitive.entered_state_at,
4089 hand_authored.entered_state_at
4090 );
4091 assert_eq!(via_primitive.allocation_ref, hand_authored.allocation_ref);
4092 }
4093 }
4094
4095 #[test]
4096 fn pool_member_unallocated_preserves_caller_clock_anchor() {
4097 // Clock-injectability pin: the composer does NOT read wall
4098 // time on its own — every consumer supplies its own
4099 // `entered_state_at` anchor (the production site from
4100 // `Process::observed_phase_since`, the `pool_decide` helper
4101 // from `crate::time::seconds_ago`, the `allocation_decide` and
4102 // `pool.rs` helpers from `Utc::now` / the epoch anchor). A
4103 // regression that started stamping the composer's own
4104 // `Utc::now()` would silently reset every downstream anchor
4105 // and break the fanout tests' epoch-based expectations.
4106 let epoch = crate::time::at_epoch_second(0);
4107 let future = crate::time::at_epoch_second(2_000_000_000);
4108 let anchored_at_epoch = PoolMember::unallocated("a", MemberState::Free, epoch);
4109 let anchored_at_future = PoolMember::unallocated("b", MemberState::Free, future);
4110 assert_eq!(anchored_at_epoch.entered_state_at, epoch);
4111 assert_eq!(anchored_at_future.entered_state_at, future);
4112 assert_ne!(
4113 anchored_at_epoch.entered_state_at, anchored_at_future.entered_state_at,
4114 "composer must preserve the caller-supplied anchor verbatim",
4115 );
4116 }
4117
4118 // ─── EphemeralPool::has_name substrate pins ───────────────────────
4119 //
4120 // Pins the copy-form metadata-projection primitive on the
4121 // `metadata.name` axis's presence-and-equal corner — the
4122 // discriminant every `candidate_pools.iter().find(|p| ...)`
4123 // closure that resolves a pool from an owned-name handle
4124 // (`AllocationRef.name` / `AllocationDecision::Bind.pool.name`)
4125 // routes through. Sibling to the `_or_empty` family on the SAME
4126 // slot ([`EphemeralPool::name_or_empty`] +
4127 // [`EphemeralPool::owned_name_or_empty`]) — this primitive owns
4128 // the `None`-preserving corner the `_or_empty` family folds away.
4129 // Fail-before-pass-after granularity: `has_name` did not exist
4130 // pre-lift; the compiler cannot resolve the name until the impl
4131 // block above is in place, so a rollback of the primitive breaks
4132 // this whole module.
4133 #[test]
4134 fn has_name_returns_true_when_slot_is_populated_and_equal() {
4135 // Happy-path pin: the slot is set AND byte-identical to the
4136 // candidate. Both pre-lift `find` closures — `resolve_pool`'s
4137 // explicit-`pool_ref` half and `controller_allocation`'s TTL-
4138 // inheritance fallback — resolve their target pool exactly in
4139 // this corner, and the primitive returns `true` here to
4140 // authorize the resolution.
4141 let p = pool_named("attest-pool");
4142 assert!(p.has_name("attest-pool"));
4143 }
4144
4145 #[test]
4146 fn has_name_returns_false_when_slot_is_populated_and_different() {
4147 // Populated-slot inequality pin: the primitive returns `false`
4148 // for every candidate that is NOT byte-identical to the slot,
4149 // including strict subsequences (`"attest"` vs. `"attest-pool"`),
4150 // strict superstrings (`"attest-pool-2"` vs. `"attest-pool"`),
4151 // and case-differ variants. This is the load-bearing property
4152 // that lets `find(|p| p.has_name(&candidate))` reject
4153 // non-matching pools rather than aliasing them together.
4154 let p = pool_named("attest-pool");
4155 assert!(!p.has_name("other-pool"));
4156 assert!(!p.has_name("attest"));
4157 assert!(!p.has_name("attest-pool-2"));
4158 assert!(!p.has_name("ATTEST-POOL"));
4159 }
4160
4161 #[test]
4162 fn has_name_returns_false_when_slot_is_none_even_against_empty_candidate() {
4163 // The `None`-preserving discipline pin: an unset `metadata.name`
4164 // slot returns `false` even when the candidate is the empty
4165 // string. Distinguishes `has_name` from a naïve substitution
4166 // through the sibling `name_or_empty` primitive, which would
4167 // fold both `None` and `Some("")` to `""` and silently promote
4168 // an unnamed pool with an empty candidate into a spurious
4169 // match at the resolver's `find` closure. Byte-identical to
4170 // what the pre-lift `.as_deref() == Some(<candidate>)` chain
4171 // produced (`None == Some("")` is `false`), which is what
4172 // both consumer sites relied on.
4173 let p = pool_unnamed();
4174 assert!(p.metadata.name.is_none(), "fixture invariant");
4175 assert!(!p.has_name(""));
4176 assert!(!p.has_name("attest-pool"));
4177 }
4178
4179 #[test]
4180 fn has_name_returns_true_only_when_populated_slot_and_candidate_are_both_empty() {
4181 // Populated-empty-slot corner pin: `Some(String::new())` is a
4182 // populated slot with an empty payload. `has_name("")` returns
4183 // `true` here (byte-identical `""` on both sides), while
4184 // `has_name("<anything else>")` returns `false`. This is the
4185 // corner where `has_name` DIVERGES from `name_or_empty`
4186 // observably: the `_or_empty` family folds this corner into
4187 // the same bucket as `None`, but `has_name` keeps the
4188 // presence bit visible — `Some("") == Some("")` is `true`
4189 // while `None == Some("")` is `false`.
4190 let mut p = pool_named("scratch");
4191 p.metadata.name = Some(String::new());
4192 assert!(p.has_name(""));
4193 assert!(!p.has_name("attest-pool"));
4194 }
4195
4196 #[test]
4197 fn has_name_matches_pre_lift_chain_verbatim_across_full_corner_set() {
4198 // Byte-identical parity pin: the primitive returns the same
4199 // `bool` as the pre-lift `.metadata.name.as_deref() == Some
4200 // (candidate)` chain across the FULL cross product of
4201 // (slot ∈ {None, Some("attest-pool"), Some("")}) × (candidate
4202 // ∈ {"attest-pool", "", "other"}). A regression that inserted
4203 // a normalization step at the primitive the pre-lift chain
4204 // does NOT apply — or vice versa — surfaces here rather than
4205 // as silent drift between the two `find` closures the primitive
4206 // owns.
4207 let slots: [Option<String>; 3] =
4208 [None, Some(String::from("attest-pool")), Some(String::new())];
4209 let candidates: [&str; 3] = ["attest-pool", "", "other"];
4210 for slot in slots {
4211 let mut p = pool_named("scratch");
4212 p.metadata.name = slot.clone();
4213 for candidate in candidates {
4214 let pre_lift = p.metadata.name.as_deref() == Some(candidate);
4215 assert_eq!(
4216 p.has_name(candidate),
4217 pre_lift,
4218 "slot = {slot:?}, candidate = {candidate:?}"
4219 );
4220 }
4221 }
4222 }
4223
4224 #[test]
4225 fn has_name_diverges_from_name_or_empty_on_the_missing_slot_corner() {
4226 // Cross-primitive discipline pin: `has_name("")` and
4227 // `name_or_empty() == ""` MUST disagree on the `None`-slot
4228 // corner. `name_or_empty` returns `""` (its load-bearing
4229 // sentinel), so a naïve `name_or_empty() == ""` probe would
4230 // return `true` here — aliasing every unnamed pool to the
4231 // empty-candidate bucket at the resolver. `has_name`
4232 // preserves `Option::as_deref() == Some(_)`'s `None ⇒ false`
4233 // semantics, so it returns `false` and rejects the spurious
4234 // match. This test fences the WHOLE reason `has_name` exists
4235 // as a distinct primitive from the `_or_empty` family: a
4236 // future refactor that collapsed `has_name` into
4237 // `name_or_empty() == candidate` would break this pin and
4238 // silently regress the resolver's byte-comparison honesty.
4239 let p = pool_unnamed();
4240 assert_eq!(p.name_or_empty(), "");
4241 assert!(!p.has_name(""));
4242 }
4243
4244 #[test]
4245 fn has_name_is_a_pure_projection() {
4246 // Consecutive calls with the same candidate return the same
4247 // `bool` — no cached state, no mutation on the `EphemeralPool`
4248 // between calls. Guards against a future refactor that plants
4249 // a cache field on `EphemeralPool` and drifts one caller from
4250 // another silently.
4251 let p = pool_named("router-pool");
4252 assert_eq!(p.has_name("router-pool"), p.has_name("router-pool"));
4253 assert_eq!(p.has_name("other"), p.has_name("other"));
4254 assert!(p.has_name("router-pool"));
4255 assert!(!p.has_name("other"));
4256 }
4257
4258 // ─── PoolSpec::free_ttl_duration substrate pins ─────────────────
4259 //
4260 // The `humantime::parse_duration(&<field>).ok()` shape rides
4261 // through TWO peer inherent methods on peer spec types post-lift:
4262 // [`crate::lifetime::EphemeralLifetime::ttl_duration`] on the
4263 // `spec.lifetime.ephemeral.ttl` axis + [`PoolSpec::free_ttl_
4264 // duration`] on the `pool.spec.free_ttl` axis. These pins bind the
4265 // pool-spec-side primitive at fail-before-pass-after granularity
4266 // so a regression that drifts either surface (a per-fleet minimum
4267 // floor added at only one primitive, a canonical unit-normalization
4268 // pass, a warn-log on unparseable strings) fails here rather than
4269 // as silent operator-facing skew between the pool stale-free
4270 // bucket loop in `tatara-pool-reconciler::pool_decide::decide_pool`
4271 // and the ephemeral TTL-expiry gate in
4272 // `tatara-process::lifetime_clock::evaluate`.
4273
4274 fn pool_spec_with_free_ttl(free_ttl: &str) -> PoolSpec {
4275 PoolSpec {
4276 free_ttl: free_ttl.into(),
4277 ..pool_spec()
4278 }
4279 }
4280
4281 #[test]
4282 fn pool_spec_free_ttl_duration_parseable_humantime_projects_to_some() {
4283 for (ttl, expected_secs) in [
4284 ("30s", 30u64),
4285 ("5m", 300),
4286 ("1h", 3600),
4287 ("24h", 86_400),
4288 ("1d", 86_400),
4289 ] {
4290 let spec = pool_spec_with_free_ttl(ttl);
4291 assert_eq!(
4292 spec.free_ttl_duration(),
4293 Some(std::time::Duration::from_secs(expected_secs)),
4294 "free_ttl_duration drift for {ttl:?}",
4295 );
4296 }
4297 }
4298
4299 #[test]
4300 fn pool_spec_free_ttl_duration_unparseable_returns_none() {
4301 // A typo (`"1our"`), an unsupported unit (`"1w"` — humantime
4302 // supports `w`, but `"forever"` doesn't), a non-humantime
4303 // literal that reached the field via API-server acceptance
4304 // ALL collapse to `None`. The `pool_decide::decide_pool`
4305 // caller collapses the corner via `.unwrap_or_default()`,
4306 // yielding `Duration::ZERO` — byte-identical to the pre-lift
4307 // hand-authored `humantime::parse_duration(&spec.free_ttl)
4308 // .unwrap_or_default()` semantics.
4309 for bad in ["", "1our", "forever", "not-a-duration", "1", "-1s"] {
4310 let spec = pool_spec_with_free_ttl(bad);
4311 assert_eq!(
4312 spec.free_ttl_duration(),
4313 None,
4314 "free_ttl_duration should be None for {bad:?}",
4315 );
4316 }
4317 }
4318
4319 #[test]
4320 fn pool_spec_free_ttl_duration_zero_seconds_returns_some_zero() {
4321 // `"0s"` is a parseable-but-zero humantime literal — the
4322 // primitive returns `Some(Duration::ZERO)`, distinguishable
4323 // from the parse-failure `None` corner. Downstream consumers
4324 // that gate on `!free_ttl.is_zero()` collapse this back
4325 // together with the `None`-via-`unwrap_or_default()` corner,
4326 // but the primitive itself keeps the two shapes distinct so
4327 // a future consumer needing that distinction can reach for
4328 // it without a re-parse.
4329 let spec = pool_spec_with_free_ttl("0s");
4330 assert_eq!(
4331 spec.free_ttl_duration(),
4332 Some(std::time::Duration::ZERO),
4333 "0s should project to Some(Duration::ZERO), not None",
4334 );
4335 }
4336
4337 #[test]
4338 fn pool_spec_free_ttl_duration_default_free_ttl_matches_24h() {
4339 // The default `free_ttl` is `"24h"` (via [`default_free_ttl`]).
4340 // The primitive on a `PoolSpec` carrying the default must
4341 // agree with a manually-parsed `"24h"` — a future
4342 // `default_free_ttl` change (a shorter recycling window, a
4343 // per-fleet override) reaches BOTH surfaces at once (this
4344 // pin + the `default_free_ttl` fn) without silent skew.
4345 let spec = pool_spec_with_free_ttl(&default_free_ttl());
4346 assert_eq!(
4347 spec.free_ttl_duration(),
4348 Some(std::time::Duration::from_secs(24 * 3600)),
4349 );
4350 }
4351
4352 #[test]
4353 fn pool_spec_free_ttl_duration_matches_pre_lift_hand_authored_chain_bytewise() {
4354 // Byte-shape parity with the pre-lift hand-authored chain the
4355 // `pool_decide::decide_pool` stale-free bucket loop restated
4356 // (`humantime::parse_duration(&spec.free_ttl).ok()` — the
4357 // `.ok()` tail and the caller's `.unwrap_or_default()` compose
4358 // to the same `Duration::ZERO`-on-failure semantics). Sweeps
4359 // every callsite corner the pool reconciler plausibly
4360 // encounters: the default `"24h"` free-recycling window, a
4361 // short-window test override (`"10s"`), a parse-failure typo,
4362 // an empty string.
4363 for ttl in ["24h", "10s", "1our", ""] {
4364 let spec = pool_spec_with_free_ttl(ttl);
4365 let via_primitive = spec.free_ttl_duration();
4366 let hand_authored = humantime::parse_duration(&spec.free_ttl).ok();
4367 assert_eq!(
4368 via_primitive, hand_authored,
4369 "free_ttl_duration must be byte-identical to `humantime::\
4370 parse_duration(&spec.free_ttl).ok()` for {ttl:?}",
4371 );
4372 }
4373 }
4374
4375 #[test]
4376 fn pool_spec_free_ttl_duration_matches_peer_ephemeral_lifetime_ttl_duration_shape() {
4377 // Return-shape parity with the peer primitive
4378 // [`crate::lifetime::EphemeralLifetime::ttl_duration`]: given
4379 // the SAME humantime string on both peer fields (the pool
4380 // `free_ttl` slot AND the ephemeral `ttl` slot), the two
4381 // primitives return byte-identical `Option<Duration>` values.
4382 // A regression that inserted a per-primitive normalization
4383 // step at only one surface — a per-fleet minimum floor, a
4384 // canonical unit-normalization pass — surfaces here rather
4385 // than as silent operator-facing skew between the pool
4386 // stale-free bucket loop and the ephemeral TTL-expiry gate
4387 // on the SAME humantime literal.
4388 for ttl in ["30s", "1h", "24h", "1our", ""] {
4389 let pool_spec = pool_spec_with_free_ttl(ttl);
4390 let eph = crate::lifetime::EphemeralLifetime {
4391 ttl: ttl.into(),
4392 ..Default::default()
4393 };
4394 assert_eq!(
4395 pool_spec.free_ttl_duration(),
4396 eph.ttl_duration(),
4397 "peer-primitive shape drift for {ttl:?}",
4398 );
4399 }
4400 }
4401
4402 // ── PoolSpec::with_template substrate pins ──────────────────────
4403 //
4404 // The 11-slot `PoolSpec { desired_size: <N>, min_size: 0, max_size:
4405 // 0, return_policy: ReturnPolicy::Replace, selector: <PoolSelector
4406 // ::default() or override>, template: <EphemeralSpec>, free_ttl:
4407 // "24h".into(), max_allocation_ttl: "4h".into(), desired: 0,
4408 // replacement_policy: Default::default(), stable_name_claim: false
4409 // }` struct-literal was open-coded verbatim at EIGHT hand-authored
4410 // callsites across two crates before this primitive closed it.
4411 // These pins bind the composed shape at fail-before-pass-after
4412 // granularity so a regression that drifted the wire-published
4413 // default at only one slot — a shorter `default_free_ttl`, a
4414 // widened `ReturnPolicy` default, a promoted `stable_name_claim`
4415 // seed — surfaces HERE rather than as silent operator-visible drift
4416 // across every fixture that keys assertions on the shape.
4417 fn hand_authored_pre_lift_with_template() -> PoolSpec {
4418 PoolSpec {
4419 desired_size: 0,
4420 min_size: 0,
4421 max_size: 0,
4422 return_policy: ReturnPolicy::Replace,
4423 selector: PoolSelector::default(),
4424 template: empty_template(),
4425 free_ttl: "24h".into(),
4426 max_allocation_ttl: "4h".into(),
4427 desired: 0,
4428 replacement_policy: ReplacementPolicy::default(),
4429 stable_name_claim: false,
4430 }
4431 }
4432
4433 #[test]
4434 fn with_template_stamps_caller_supplied_template_verbatim() {
4435 // The caller-supplied slot is the ONE the substrate does not
4436 // default. A regression that reshaped the primitive's
4437 // pass-through — a hidden re-encode through
4438 // `serde_json::to_value` and back, a per-primitive
4439 // normalization that flipped a defaulted-inner slot — would
4440 // surface HERE rather than at every downstream seed whose
4441 // assertions key on the template shape.
4442 let t = empty_template();
4443 let s = PoolSpec::with_template(t.clone());
4444 assert_eq!(
4445 serde_json::to_value(&s.template).unwrap(),
4446 serde_json::to_value(&t).unwrap(),
4447 );
4448 }
4449
4450 #[test]
4451 fn with_template_defaulted_slots_ride_wire_schema_defaults() {
4452 // Pins the sibling-default correspondence the doc-comment
4453 // names — every non-template slot rides its own
4454 // `#[serde(default = "…")]` value from the `pub struct
4455 // PoolSpec` schema above. A regression that promoted any
4456 // defaulted slot to a non-default (a shorter
4457 // `default_free_ttl`, a widened `ReturnPolicy` default, a
4458 // `stable_name_claim: true` seed) would move the baseline
4459 // HERE rather than at every downstream fixture.
4460 let s = PoolSpec::with_template(empty_template());
4461 assert_eq!(s.desired_size, 0);
4462 assert_eq!(s.min_size, 0);
4463 assert_eq!(s.max_size, 0);
4464 assert_eq!(s.return_policy, ReturnPolicy::default());
4465 assert_eq!(
4466 serde_json::to_value(&s.selector).unwrap(),
4467 serde_json::to_value(PoolSelector::default()).unwrap(),
4468 );
4469 assert_eq!(s.free_ttl, default_free_ttl());
4470 assert_eq!(s.max_allocation_ttl, default_max_allocation_ttl());
4471 assert_eq!(s.desired, 0);
4472 assert_eq!(s.replacement_policy, ReplacementPolicy::default());
4473 assert!(!s.stable_name_claim);
4474 }
4475
4476 #[test]
4477 fn with_template_matches_hand_authored_pre_lift_bytewise() {
4478 // Byte-identical parity pin between the substrate primitive
4479 // and the pre-lift 11-slot struct-literal that recurred at
4480 // eight hand-authored sites (compared with `desired_size:
4481 // 0` to match the primitive's baseline — the five hand-
4482 // authored `desired_size: 1` sites compose the baseline via
4483 // struct-update and the pin below binds THAT axis
4484 // separately). Compares via `serde_json` value equality —
4485 // `PoolSpec` does not derive `PartialEq` (the typed fields
4486 // it composes over do not uniformly derive it), so a
4487 // serialize round-trip is the shape-equality currency the
4488 // pin family already uses.
4489 let composed = PoolSpec::with_template(empty_template());
4490 let hand = hand_authored_pre_lift_with_template();
4491 assert_eq!(
4492 serde_json::to_value(&composed).unwrap(),
4493 serde_json::to_value(&hand).unwrap(),
4494 );
4495 }
4496
4497 #[test]
4498 fn with_template_supports_struct_update_override_at_each_pre_lift_axis() {
4499 // Sweeps every override axis the eight pre-lift seeds
4500 // exercised via struct-update syntax:
4501 // * `desired_size: 1` — six sites (the majority of pre-lift
4502 // fixtures use a single-slot pool).
4503 // * `selector: <custom>` — two sites (router.rs +
4504 // allocation_decide.rs).
4505 // * `desired: N` + `replacement_policy: <policy>` — one
4506 // site (desired.rs's desired-count-loop fixture).
4507 // * `desired_size: N, min_size: N, max_size: N` — one site
4508 // (pool_decide.rs's pure-decision fixture).
4509 // A regression that broke the struct-update path (e.g. a
4510 // `#[non_exhaustive]` attribute added to `PoolSpec` that
4511 // would refuse struct-update syntax across crate boundaries)
4512 // surfaces at compile time HERE rather than as an eight-site
4513 // downstream break.
4514 let base = PoolSpec::with_template(empty_template());
4515 let size_1 = PoolSpec {
4516 desired_size: 1,
4517 ..PoolSpec::with_template(empty_template())
4518 };
4519 assert_eq!(base.desired_size, 0);
4520 assert_eq!(size_1.desired_size, 1);
4521 // Every other slot rides the base composition.
4522 assert_eq!(size_1.free_ttl, base.free_ttl);
4523 assert_eq!(size_1.max_allocation_ttl, base.max_allocation_ttl);
4524
4525 let custom_selector = PoolSelector::default();
4526 let with_selector = PoolSpec {
4527 desired_size: 1,
4528 selector: custom_selector,
4529 ..PoolSpec::with_template(empty_template())
4530 };
4531 assert_eq!(with_selector.desired_size, 1);
4532 assert_eq!(with_selector.free_ttl, base.free_ttl);
4533
4534 let with_desired = PoolSpec {
4535 desired: 5,
4536 replacement_policy: ReplacementPolicy::HoldFailed,
4537 ..PoolSpec::with_template(empty_template())
4538 };
4539 assert_eq!(with_desired.desired, 5);
4540 assert_eq!(
4541 with_desired.replacement_policy,
4542 ReplacementPolicy::HoldFailed
4543 );
4544 assert_eq!(with_desired.desired_size, 0);
4545
4546 let with_sizes = PoolSpec {
4547 desired_size: 3,
4548 min_size: 1,
4549 max_size: 5,
4550 ..PoolSpec::with_template(empty_template())
4551 };
4552 assert_eq!(with_sizes.desired_size, 3);
4553 assert_eq!(with_sizes.min_size, 1);
4554 assert_eq!(with_sizes.max_size, 5);
4555 assert_eq!(with_sizes.replacement_policy, base.replacement_policy);
4556 }
4557
4558 #[test]
4559 fn with_template_is_call_time_construction_not_a_shared_singleton() {
4560 // Two independent calls produce structurally-equal but
4561 // distinct values — pins that the primitive is a plain
4562 // constructor rather than a `lazy_static` clone whose in-
4563 // place mutation at one consumer would silently mutate the
4564 // shape at every other consumer. Mirrors the sibling
4565 // `gate_compute_defaults_is_call_time_construction_not_a_
4566 // shared_singleton` pin on `ProcessSpec::gate_compute_defaults`.
4567 let a = PoolSpec::with_template(empty_template());
4568 let b = PoolSpec::with_template(empty_template());
4569 assert_eq!(
4570 serde_json::to_value(&a).unwrap(),
4571 serde_json::to_value(&b).unwrap(),
4572 );
4573 assert!(!std::ptr::eq(&a, &b));
4574 }
4575
4576 #[test]
4577 fn with_template_free_ttl_composes_with_free_ttl_duration_at_default_window() {
4578 // The primitive's `free_ttl` slot rides `default_free_ttl()`;
4579 // the sibling `free_ttl_duration` primitive parses that
4580 // literal into the same 24h `Duration` every pre-lift
4581 // reconciler-side seed produced. Pins the round-trip so a
4582 // regression that shifted `default_free_ttl` without
4583 // updating this baseline (or vice versa) surfaces HERE
4584 // rather than as silent skew between the composer and the
4585 // ttl-parse gate that consumes it.
4586 let s = PoolSpec::with_template(empty_template());
4587 assert_eq!(
4588 s.free_ttl_duration(),
4589 Some(std::time::Duration::from_secs(24 * 3600)),
4590 );
4591 }
4592
4593 // ─── EphemeralPool::new_in substrate pins ─────────────────────────
4594 //
4595 // The pre-lift 2-line `let mut p = EphemeralPool::new(<name>,
4596 // <spec>); p.meta_mut().namespace = Some(<ns>.into());` chain
4597 // recurred at FOUR workspace-wide fixture sites in
4598 // `tatara-pool-reconciler` past the ★★ PRIME-DIRECTIVE ≥ 2
4599 // threshold. Post-lift the ONE substrate composer stamps a
4600 // namespaced `EphemeralPool` from `(name, ns, spec)` in one call.
4601 // Fail-before-pass-after granularity: `new_in` did not exist pre-
4602 // lift; the compiler cannot resolve the name until the impl block
4603 // above is in place, so a rollback of the primitive breaks this
4604 // whole pin block.
4605
4606 #[test]
4607 fn new_in_stamps_metadata_name_from_the_name_slot() {
4608 // `name` slot → `metadata.name` projection pin. Guards against
4609 // a regression that dropped the `name` slot into a `generate_
4610 // name` slot, an `annotations` seed, or any downstream slot the
4611 // kube-derived [`Self::new`] does not populate at
4612 // `metadata.name` verbatim.
4613 let s = pool_spec();
4614 let p = EphemeralPool::new_in("attest-pool", "pools", s);
4615 assert_eq!(p.metadata.name.as_deref(), Some("attest-pool"));
4616 }
4617
4618 #[test]
4619 fn new_in_stamps_metadata_namespace_from_the_ns_slot() {
4620 // `ns` slot → `metadata.namespace` projection pin. Guards
4621 // against a regression that dropped the `ns` slot into a
4622 // `labels` seed, an unrelated annotation, or that stamped
4623 // `namespace = None` even after a caller-supplied value.
4624 let s = pool_spec();
4625 let p = EphemeralPool::new_in("attest-pool", "pools", s);
4626 assert_eq!(p.metadata.namespace.as_deref(), Some("pools"));
4627 }
4628
4629 #[test]
4630 fn new_in_stamps_spec_from_the_spec_slot_verbatim() {
4631 // `spec` slot → `spec` projection pin. A regression that
4632 // silently normalized the caller-supplied spec inside the
4633 // composer (a defaulted-slot reset, a per-fleet override) would
4634 // diverge from the byte-identical pass-through the pre-lift
4635 // 2-line chain produced.
4636 let mut s = pool_spec();
4637 s.desired_size = 7;
4638 let p = EphemeralPool::new_in("attest-pool", "pools", s.clone());
4639 assert_eq!(p.spec.desired_size, s.desired_size);
4640 assert_eq!(p.spec.min_size, s.min_size);
4641 assert_eq!(p.spec.max_size, s.max_size);
4642 }
4643
4644 #[test]
4645 fn new_in_accepts_both_owned_and_borrowed_namespace_slot() {
4646 // The `impl Into<String>` ergonomic contract round-trips
4647 // through both `&'static str` (majority pre-lift caller shape)
4648 // AND owned `String` at the SAME signature. Guards against a
4649 // regression that narrowed the slot to `&str` only or that
4650 // silently double-`.into()`d an already-owned String.
4651 let s = pool_spec();
4652 let via_str = EphemeralPool::new_in("attest-pool", "pools", s.clone());
4653 let via_string = EphemeralPool::new_in("attest-pool", String::from("pools"), s.clone());
4654 assert_eq!(via_str.metadata.namespace, via_string.metadata.namespace);
4655 }
4656
4657 #[test]
4658 fn new_in_matches_pre_lift_construct_then_set_namespace_bytewise() {
4659 // Byte-shape parity witness against the pre-lift 2-line chain
4660 // across the two representative namespace shapes the collapsed
4661 // sites used (`"ephemeral-pools"` at `router::pool`, `"pools"`
4662 // at `pool_decide::pool` + `desired::pool` +
4663 // `allocation_decide::pool`). A regression that shifted the
4664 // composer's output would diverge from the pre-lift literal
4665 // HERE rather than at every downstream fixture's downstream
4666 // assertion.
4667 for ns in ["ephemeral-pools", "pools"] {
4668 let via_primitive = EphemeralPool::new_in("attest-pool", ns, pool_spec());
4669 let mut hand_authored = EphemeralPool::new("attest-pool", pool_spec());
4670 hand_authored.metadata.namespace = Some(ns.into());
4671 assert_eq!(via_primitive.metadata.name, hand_authored.metadata.name);
4672 assert_eq!(
4673 via_primitive.metadata.namespace,
4674 hand_authored.metadata.namespace,
4675 );
4676 }
4677 }
4678
4679 #[test]
4680 fn new_in_defaults_other_metadata_slots_at_kube_derived_new() {
4681 // The composer forwards to the kube-derived [`Self::new`] for
4682 // every non-namespace metadata slot. A regression that stamped
4683 // finalizers, owner_references, labels, or annotations inside
4684 // the composer's body — inheriting the pre-lift chain's
4685 // undocumented emptiness at those slots — would surface here.
4686 let p = EphemeralPool::new_in("attest-pool", "pools", pool_spec());
4687 assert!(p.metadata.finalizers.is_none());
4688 assert!(p.metadata.owner_references.is_none());
4689 assert!(p.metadata.labels.is_none());
4690 assert!(p.metadata.annotations.is_none());
4691 }
4692}