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