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