Skip to main content

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 EphemeralPool {
148    /// Borrow-form metadata-projection primitive on the `metadata.name`
149    /// axis of `EphemeralPool`: returns the K8s object name slice with
150    /// the missing-name corner collapsed to the load-bearing empty-string
151    /// sentinel — the ONE-liner collapse of the paired
152    /// `self.metadata.name.as_deref().unwrap_or("")` incantation every
153    /// pool-side consumer restated by hand pre-lift.
154    ///
155    /// Pre-lift the `.metadata.name.as_deref().unwrap_or("")` chain
156    /// was hand-authored at TWO sites past the ★★ PRIME-DIRECTIVE ≥ 2
157    /// duplication threshold in `tatara-pool-reconciler`, both keyed
158    /// by the pool's own name slot:
159    /// * `router::pool_name` — the tie-break comparator inside
160    ///   `best_match`; a deterministic lexicographic-min-name arbiter
161    ///   across two pool candidates whose specificity scores tie.
162    /// * `controller_allocation::reconcile_inner` — the `HashMap<
163    ///   pool-name, Vec<PoolMember>>` lookup closure fed into
164    ///   `decide_allocation_reconcile`; keys the "which pool members
165    ///   back this allocation candidate?" projection at every
166    ///   allocation-reconcile pass.
167    ///
168    /// Both sites walked the SAME `.as_deref().unwrap_or("")` chain
169    /// and both wanted the `&str` form the primitive returns — as a
170    /// borrow suitable for lexicographic `str::cmp` in the tie-break
171    /// AND for the `HashMap<String, _>::get(&str)` lookup. Post-lift
172    /// each caller reaches for `pool.name_or_empty()` and the produced
173    /// slice feeds the same downstream comparator / lookup unchanged.
174    ///
175    /// The empty-string fallback is the SAME sentinel the sibling
176    /// borrow-form primitive [`crate::crd::Process::uid_or_empty`]
177    /// returns AND the SAME sentinel the owned-form sibling
178    /// [`crate::crd::Process::owned_name_or_empty`] returns on the
179    /// `metadata.name` axis of the sister CRD — the three primitives
180    /// partition the (borrow-form × owned-form) × (uid × name) corner
181    /// of the metadata-slot family on identical fallback semantics
182    /// (empty string means "the slot is unset"), so a consumer that
183    /// switches between the CRD surfaces based on downstream keying
184    /// requirements never sees a different missing-slot spelling as
185    /// a side effect.
186    ///
187    /// Return-form axis: `&str` mirrors the borrow-first discipline
188    /// of the peer metadata primitives on `Process`
189    /// ([`crate::crd::Process::namespace_or_default`],
190    /// [`crate::crd::Process::name_or_placeholder`],
191    /// [`crate::crd::Process::uid_or_empty`]). The one missing-slot
192    /// corner the chain swallowed pre-lift (missing `metadata.name`)
193    /// collapses to the empty-string sentinel so `str::is_empty` /
194    /// `HashMap::get` on an unnamed pool behaves identically to what
195    /// the pre-lift `.as_deref().unwrap_or("")` chain produced.
196    ///
197    /// A future normalization step (a name-canonicalization pass, a
198    /// case-fold key builder, a per-cluster prefix stripper for
199    /// cross-cluster pool-name aliasing) lands at ONE substrate
200    /// method here and both downstream consumers pick up the upgrade
201    /// mechanically — no per-callsite hand-edit at `pool_name` /
202    /// `reconcile_inner`.
203    ///
204    /// Theory anchor: THEORY.md §VI.1 (generation over composition —
205    /// the `.metadata.name.as_deref().unwrap_or("")` chain recurred
206    /// at two hand-authored sites past the ★★ PRIME-DIRECTIVE ≥ 2
207    /// duplication trigger, and is lifted to ONE owner here).
208    /// THEORY.md §II.1 invariant 5 (composition preserves proofs —
209    /// the pins bind the missing-name corner + the empty-string
210    /// sentinel byte-shape + the borrow-form `&str` lifetime + the
211    /// byte-identical parity with the pre-lift chain + the fallback-
212    /// value coherence with `Process::uid_or_empty` /
213    /// `Process::owned_name_or_empty` on the metadata-slot × empty-
214    /// sentinel axis, so a regression that drifted any surface at
215    /// `tests::name_or_empty_*` here rather than as silent operator-
216    /// facing skew between the router tie-break and the allocation
217    /// member-lookup on the SAME pool candidate).
218    pub fn name_or_empty(&self) -> &str {
219        self.metadata.name.as_deref().unwrap_or("")
220    }
221
222    /// Owned-form metadata-projection primitive on the `metadata.name`
223    /// axis of `EphemeralPool`: returns an owned `String` copy of the K8s
224    /// object name with the missing-name corner collapsed to the load-
225    /// bearing empty-string sentinel — the ONE-liner collapse of the
226    /// paired `self.metadata.name.clone().unwrap_or_default()` incantation
227    /// every pool-side consumer restated by hand pre-lift.
228    ///
229    /// Pre-lift the `.metadata.name.clone().unwrap_or_default()` chain
230    /// was hand-authored at TWO sites past the ★★ PRIME-DIRECTIVE ≥ 2
231    /// duplication threshold in `tatara-pool-reconciler`, both keyed by
232    /// the pool's own name slot in an `owned String` context:
233    /// * `controller_allocation::reconcile_inner` — the
234    ///   `HashMap<String, Vec<PoolMember>>` key seed inside a
235    ///   `pools.iter().map(|p| ...).collect()` fanout; the map key is
236    ///   the owned `String` form because the produced `HashMap<String, _>`
237    ///   outlives the pool-list borrow that generated it and the
238    ///   downstream `pool_members.get(pool.name_or_empty())` closure
239    ///   consumes it as `&str`.
240    /// * `allocation_decide::AllocationConvergenceCtx::observe` — the
241    ///   `AllocationRef::name` slot seed stamped on the matched-pool
242    ///   handle; the struct literal is `AllocationRef { name: String,
243    ///   namespace: String }` and the produced value is threaded through
244    ///   the `Decision::decide` transition rule downstream.
245    ///
246    /// Both sites walked the SAME `.clone().unwrap_or_default()` chain
247    /// and both wanted the `String` form the primitive returns — as the
248    /// owned key of a `HashMap<String, _>` and as the `String` slot of
249    /// an `AllocationRef` struct literal. Post-lift each callsite reads
250    /// `pool.owned_name_or_empty()` and the produced value feeds the
251    /// same downstream key / struct-literal slot unchanged.
252    ///
253    /// The empty-string fallback is the SAME sentinel the sibling
254    /// borrow-form primitive [`Self::name_or_empty`] returns AND the
255    /// SAME sentinel the sibling owned-form primitive
256    /// [`crate::crd::Process::owned_name_or_empty`] returns on the
257    /// `metadata.name` axis of the sister CRD — the three primitives
258    /// partition the (borrow-form × owned-form) corner of the metadata-
259    /// name family across BOTH tatara-process CRDs on identical missing-
260    /// slot semantics (empty string means "the slot is unset"), so a
261    /// consumer that switches between the CRD surfaces based on
262    /// downstream ownership requirements never sees a different
263    /// missing-slot spelling as a side effect.
264    ///
265    /// Peer to [`Self::name_or_empty`] on the (return-form × ownership)
266    /// axis pair — closes the corner the pool-side family previously
267    /// left open:
268    ///
269    /// * borrow + empty sentinel → [`Self::name_or_empty`] (router tie-
270    ///   break comparator, `HashMap<String, _>::get(&str)` lookup —
271    ///   consumers whose downstream keys by `&str` and allocates
272    ///   nothing);
273    /// * owned + empty sentinel → **this method** (HashMap-key seed in
274    ///   an outliving-borrow context, `AllocationRef::name` struct-
275    ///   literal slot — consumers whose downstream requires the owned
276    ///   `String` form because the produced value outlives the source-
277    ///   pool borrow).
278    ///
279    /// A future normalization step (a name-canonicalization pass, a
280    /// case-fold key builder, a per-cluster prefix stripper for cross-
281    /// cluster pool-name aliasing) lands at ONE substrate method here
282    /// and both downstream consumers pick up the upgrade mechanically —
283    /// no per-callsite hand-edit at `reconcile_inner` /
284    /// `AllocationConvergenceCtx::observe`.
285    ///
286    /// Theory anchor: THEORY.md §VI.1 (generation over composition —
287    /// the `.metadata.name.clone().unwrap_or_default()` chain recurred
288    /// at two hand-authored sites past the ★★ PRIME-DIRECTIVE ≥ 2
289    /// duplication trigger, and is lifted to ONE owner here).
290    /// THEORY.md §II.1 invariant 5 (composition preserves proofs —
291    /// the pins bind the missing-name corner + the empty-string
292    /// sentinel byte-shape + the owned-form `String` return type + the
293    /// byte-identical parity with the pre-lift chain + the fallback-
294    /// value coherence with [`Self::name_or_empty`] +
295    /// [`crate::crd::Process::owned_name_or_empty`] on the metadata-
296    /// slot × empty-sentinel axis, so a regression that drifted any
297    /// surface at `tests::owned_name_or_empty_*` here rather than as
298    /// silent operator-facing skew between the pool-members lookup key
299    /// and the AllocationRef seed on the SAME pool candidate).
300    pub fn owned_name_or_empty(&self) -> String {
301        self.metadata.name.clone().unwrap_or_default()
302    }
303
304    /// Copy-form metadata-projection primitive on the deletion-tombstone
305    /// axis of `EphemeralPool`: returns `true` iff the K8s API server
306    /// has stamped a `metadata.deletionTimestamp` on this pool (the
307    /// moment the object entered the "being deleted" corner of its
308    /// lifecycle, after which further mutating writes are refused and
309    /// finalizers are drained before the object is actually removed) —
310    /// the ONE-liner collapse of the paired
311    /// `self.metadata.deletion_timestamp.is_some()` incantation every
312    /// pool-side consumer restated by hand pre-lift.
313    ///
314    /// Pre-lift the `.metadata.deletion_timestamp.is_some()` chain was
315    /// hand-authored at TWO sites past the ★★ PRIME-DIRECTIVE ≥ 2
316    /// duplication threshold in `tatara-pool-reconciler`, both
317    /// projecting the SAME tombstone-presence predicate on an
318    /// `EphemeralPool` value:
319    /// * `pool_decide::decide_pool_reconcile` — the pure decision
320    ///   function's deletion-preempt gate that forces
321    ///   [`PoolDecision::Drain`] as soon as the API server stamps
322    ///   the tombstone, before the (desired vs actual) supply-arithmetic
323    ///   branches get a chance to run. Wired at the very top of the
324    ///   decision so a draining pool never spawns / reaps / expires
325    ///   through the normal replenishment arithmetic while the
326    ///   deletion is in flight.
327    /// * `controller_pool::pool_phase_from_members` — the observed-
328    ///   phase composer's tombstone-first arm that returns
329    ///   [`PoolPhase::Draining`] regardless of the supply / demand
330    ///   arithmetic that would otherwise pick `Ready` / `Scaling` /
331    ///   `Degraded`. Keeps the reported phase honest during the
332    ///   finalizer drain so operators reading `kubectl get
333    ///   ephemeralpools` see the tombstone-present state as
334    ///   `Draining`, not as a stale `Ready`.
335    ///
336    /// Both sites walked the SAME `.metadata.deletion_timestamp
337    /// .is_some()` chain and both wanted the `bool` form the primitive
338    /// returns — the `decide_pool_reconcile` site to gate the
339    /// `→ Drain` short-circuit and the `pool_phase_from_members` site
340    /// to gate the `→ Draining` short-circuit. Post-lift each callsite
341    /// reads `pool.is_being_deleted()` and the produced `bool` feeds
342    /// the same downstream short-circuit unchanged.
343    ///
344    /// Sibling to [`crate::crd::Process::is_being_deleted`] on the
345    /// deletion-tombstone axis of the sister CRD — the two primitives
346    /// now partition the tombstone-presence probe across BOTH
347    /// tatara-process CRDs on identical missing-slot semantics
348    /// (present timestamp means "the API server has begun deletion"),
349    /// so an operator or reconciler that switches between the CRD
350    /// surfaces never sees a different tombstone-detection spelling
351    /// as a side effect.
352    ///
353    /// Return-form axis: `bool` matches the copy-form discipline of
354    /// the sibling [`crate::crd::Process::is_being_deleted`] and of
355    /// the pool-side [`crate::phase::ProcessPhase::is_alive`] +
356    /// [`Self::name_or_empty`]-family primitives — the underlying
357    /// slot is a wire-format `Option<Time>` that carries only
358    /// presence information at this axis (the RFC-3339 timestamp
359    /// payload itself is not what the two consumers read; both only
360    /// probe presence to detect the tombstone-stamped state).
361    /// Returning the raw `Option<&Time>` would push the `.is_some()`
362    /// probe back to every callsite, restating the pre-lift chain
363    /// one link shorter without collapsing the primitive.
364    ///
365    /// Peer to [`Self::name_or_empty`] and [`Self::owned_name_or_empty`]
366    /// on the metadata-projection axis for `EphemeralPool`; this method
367    /// opens the presence-probe corner for the tombstone slot. Future
368    /// metadata-presence projections on the pool CRD (an
369    /// `is_being_finalized` projection on
370    /// `metadata.finalizers.is_empty()`'s negation, a `has_owner`
371    /// projection on `metadata.owner_references.is_empty()`'s
372    /// negation) land as peer methods on this same axis.
373    ///
374    /// A future normalization step (a per-tombstone staleness gate
375    /// that returns `false` for a tombstone older than the reconciler's
376    /// grace-period budget, a canonicalization pass that treats a
377    /// tombstone from a paused controller as absent, a cross-cluster
378    /// tombstone-observation clock skew guard) lands at ONE substrate
379    /// method here and both downstream consumers pick up the upgrade
380    /// mechanically — no per-callsite hand-edit at
381    /// `decide_pool_reconcile` / `pool_phase_from_members`.
382    ///
383    /// Theory anchor: THEORY.md §VI.1 (generation over composition —
384    /// the `.metadata.deletion_timestamp.is_some()` chain recurred at
385    /// two hand-authored sites past the ★★ PRIME-DIRECTIVE ≥ 2
386    /// duplication trigger, and is lifted to ONE owner here).
387    /// THEORY.md §II.1 invariant 5 (composition preserves proofs —
388    /// the pins bind the missing-tombstone corner + the present-
389    /// tombstone corner + the copy-form `bool` return + the byte-
390    /// identical parity with the pre-lift `.is_some()` chain + the
391    /// cross-CRD coherence with `crate::crd::Process::is_being_deleted`
392    /// on the tombstone axis, so a regression that drifted any surface
393    /// at `tests::is_being_deleted_*` rather than as silent operator-
394    /// facing skew between the pool-reconciler's `→ Drain` decision
395    /// and the observed-phase composer's `→ Draining` report on the
396    /// SAME `EphemeralPool` within one reconcile pass).
397    pub fn is_being_deleted(&self) -> bool {
398        self.metadata.deletion_timestamp.is_some()
399    }
400
401    /// Owned-form metadata-projection primitive on the `metadata.namespace`
402    /// axis of `EphemeralPool`: returns an owned `String` copy of the K8s
403    /// namespace with the missing-namespace corner collapsed to the load-
404    /// bearing empty-string sentinel — the ONE-liner collapse of the
405    /// paired `self.metadata.namespace.clone().unwrap_or_default()`
406    /// incantation every pool-side consumer restated by hand pre-lift.
407    ///
408    /// Pre-lift the `.metadata.namespace.clone().unwrap_or_default()`
409    /// chain was hand-authored at TWO sites past the ★★ PRIME-DIRECTIVE
410    /// ≥ 2 duplication threshold, both stamping the `AllocationRef
411    /// { namespace: String, .. }` slot inside an owned-`String` context:
412    /// * `tatara-pool-reconciler::allocation_decide::AllocationConvergenceCtx
413    ///   ::observe` — the matched-pool seed's `AllocationRef.namespace`
414    ///   slot, right beside the peer [`Self::owned_name_or_empty`] call
415    ///   that owns the paired name half. This is the exact site the
416    ///   pre-existing peer-primitive doc-comment forecast (`"a future
417    ///   run may lift owned_namespace_or_empty as the sibling axis
418    ///   peer"`).
419    /// * `crate::pool::tests::allocation_ref_new_composes_with_owned_name_or_empty_pool_projection`
420    ///   — the composition pin that seeded an `AllocationRef` from the
421    ///   same paired-primitive-half construction the production consumer
422    ///   in `allocation_decide::observe` performs. Post-lift the pin
423    ///   composes two peer primitives (`owned_name_or_empty` +
424    ///   `owned_namespace_or_empty`) rather than one primitive plus the
425    ///   pre-lift chain, sharpening it from a mixed-form composition
426    ///   check into a paired-primitive-family composition check.
427    ///
428    /// Both sites walked the SAME `.clone().unwrap_or_default()` chain
429    /// and both wanted the `String` form the primitive returns — as the
430    /// `String` slot of an `AllocationRef` struct literal built through
431    /// [`crate::pool::AllocationRef::new`]. Post-lift each callsite reads
432    /// `pool.owned_namespace_or_empty()` and the produced value feeds
433    /// the same downstream `AllocationRef` slot unchanged.
434    ///
435    /// The empty-string fallback is the SAME sentinel the sibling owned-
436    /// form primitive [`Self::owned_name_or_empty`] returns on the
437    /// `metadata.name` axis of the same CRD — the two primitives now
438    /// partition the (owned `String` × `metadata.<slot>`) corner of the
439    /// pool CRD's metadata family across BOTH object-coordinate slots
440    /// on identical missing-slot semantics (empty string means "the
441    /// slot is unset"), so the [`crate::pool::AllocationRef::new`]
442    /// composer sees a coherent owned-empty pair regardless of which
443    /// slot is absent on the source pool. Coherent with the workspace-
444    /// wide owned-empty sentinel that the peer primitives
445    /// [`crate::crd::Process::uid_or_empty`],
446    /// [`crate::crd::Process::owned_name_or_empty`],
447    /// [`Self::name_or_empty`], and [`Self::owned_name_or_empty`]
448    /// already share on the metadata-slot × empty-sentinel axis.
449    ///
450    /// Peer to [`Self::owned_name_or_empty`] on the
451    /// (`metadata.name` × `metadata.namespace`) axis of the owned-form
452    /// projection family — closes the corner the pool-side family
453    /// previously left open:
454    ///
455    /// * owned + name + empty sentinel → [`Self::owned_name_or_empty`]
456    ///   (`AllocationRef.name` seed, `HashMap<String, _>` key seed);
457    /// * owned + namespace + empty sentinel → **this method**
458    ///   (`AllocationRef.namespace` seed — the paired half the same
459    ///   `AllocationRef::new(name, namespace)` constructor consumes);
460    /// * copy + deletion + tombstone probe → [`Self::is_being_deleted`]
461    ///   (the presence-probe corner of the same metadata axis, already
462    ///   opened).
463    ///
464    /// A future normalization step (a namespace-canonicalization pass,
465    /// a case-fold key builder, a per-cluster prefix stripper, or the
466    /// canonical-namespace default lift that would substitute
467    /// [`crate::crd::Process::DEFAULT_NAMESPACE`] on the missing-slot
468    /// corner rather than the empty-string sentinel) lands at ONE
469    /// substrate method here and both downstream consumers pick up the
470    /// upgrade mechanically — no per-callsite hand-edit at
471    /// `AllocationConvergenceCtx::observe` / the composition pin.
472    ///
473    /// The empty-string fallback (rather than
474    /// [`crate::crd::Process::DEFAULT_NAMESPACE`]) is DELIBERATELY
475    /// pinned: the sole downstream consumer
476    /// (`AllocationConvergenceCtx::observe`'s matched-pool seed) feeds
477    /// the produced value into `AllocationRef.namespace`, which is then
478    /// matched byte-identically against `spec.pool_ref.namespace` at
479    /// [`crate::pool::allocation_decide::resolve_pool`]-style comparators.
480    /// A silent substitution of `"default"` at this primitive would
481    /// alias every namespace-absent pool to the `"default"` bucket at
482    /// the matcher, hiding the missing-slot corner from an operator
483    /// who explicitly authored an allocation against a namespace-
484    /// unset pool. The load-bearing empty-string sentinel keeps the
485    /// pre-lift `.clone().unwrap_or_default()` shape verbatim so the
486    /// downstream matcher's byte-comparison stays honest.
487    ///
488    /// Theory anchor: THEORY.md §VI.1 (generation over composition —
489    /// the `.metadata.namespace.clone().unwrap_or_default()` chain
490    /// recurred at two hand-authored sites past the ★★ PRIME-DIRECTIVE
491    /// ≥ 2 duplication trigger, and is lifted to ONE owner here).
492    /// THEORY.md §II.1 invariant 5 (composition preserves proofs —
493    /// the pins bind the missing-namespace corner + the empty-string
494    /// sentinel byte-shape + the owned-form `String` return type + the
495    /// byte-identical parity with the pre-lift chain + the fallback-
496    /// value coherence with [`Self::owned_name_or_empty`] on the
497    /// paired-slot axis, so a regression that drifted any surface at
498    /// `tests::owned_namespace_or_empty_*` rather than as silent
499    /// operator-facing skew between the paired name / namespace halves
500    /// of the SAME `AllocationRef` seed).
501    pub fn owned_namespace_or_empty(&self) -> String {
502        self.metadata.namespace.clone().unwrap_or_default()
503    }
504
505    /// Copy-form metadata-projection primitive on the `metadata.name`
506    /// axis of `EphemeralPool` in its `presence-and-equal` corner:
507    /// returns `true` iff the K8s object name slot is BOTH `Some(_)`
508    /// AND byte-identical to the supplied candidate — the ONE-liner
509    /// collapse of the paired
510    /// `self.metadata.name.as_deref() == Some(candidate)` incantation
511    /// every pool-side lookup consumer restated by hand pre-lift.
512    ///
513    /// Pre-lift the `.metadata.name.as_deref() == Some(<candidate>)`
514    /// chain was hand-authored at TWO production sites past the ★★
515    /// PRIME-DIRECTIVE ≥ 2 duplication threshold in
516    /// `tatara-pool-reconciler`, both keyed by the `EphemeralPool`'s
517    /// own name slot inside a `candidate_pools.iter().find(|p| ...)`
518    /// closure that resolves a pool from an `AllocationRef.name` half:
519    /// * `allocation_decide::resolve_pool` — the explicit-`pool_ref`
520    ///   half of the pool-resolution ladder, one of two conjuncts in
521    ///   the `(name == X && namespace == Y)` byte-comparison against
522    ///   `AllocationSpec::pool_ref`. Pairs with the sibling namespace
523    ///   comparison (a future run may lift `has_namespace` as the
524    ///   paired-axis peer once a second namespace-probe site opens).
525    /// * `controller_allocation::reconcile_inner` — the TTL-inheritance
526    ///   fallback path's pool-lookup by `AllocationDecision::Bind::pool
527    ///   .name`, feeding the matched pool's `spec.template.ttl` into
528    ///   the just-bound member Process's lifetime overlay.
529    ///
530    /// Both sites walked the SAME `.as_deref() == Some(<x>.as_str())`
531    /// chain against a `&str` candidate held by an [`AllocationRef`]
532    /// or a similar owned-name handle, and both wanted the `bool`
533    /// form the primitive returns — the transition rule's discriminant
534    /// on either the `find(|p| p.has_name(&pool_ref.name))` closure
535    /// (which either matches ONE candidate pool or none) or the
536    /// TTL-inheritance closure's short-circuit through
537    /// `.map(...).unwrap_or_else(...)`. Post-lift each callsite reads
538    /// `p.has_name(&candidate)` and the produced `bool` feeds the same
539    /// downstream `find` / `map` closure unchanged.
540    ///
541    /// Distinct in semantics from the sibling primitive
542    /// [`Self::name_or_empty`] on the SAME `metadata.name` axis: the
543    /// `_or_empty` family folds the missing-slot corner to the load-
544    /// bearing empty-string sentinel (so `None` and `Some("")` both
545    /// project to `""`), whereas this primitive keeps `None` distinct
546    /// from `Some("")` at the `==` operator — a `None` slot returns
547    /// `false` even when the candidate is the empty string. That
548    /// discipline is load-bearing at both consumer sites: pre-lift
549    /// they compared `Option<&str>` against `Some(<candidate>)`, so a
550    /// substitution through `Self::name_or_empty` would silently
551    /// promote a namespace-absent pool with a `""` candidate into a
552    /// spurious match at the `find` closure, aliasing every unnamed
553    /// pool to the same lookup bucket at the resolver. Preserving the
554    /// `None ⇒ false` corner keeps the resolver's byte-comparison
555    /// honest.
556    ///
557    /// Peer to the sibling substrate primitives already opened on the
558    /// pool-side (`metadata.name` × return-form) axis:
559    /// * borrow-form + empty sentinel → [`Self::name_or_empty`] (`&str`
560    ///   projection with a `""` fallback for missing / explicitly-empty
561    ///   name slots; router tie-break comparator);
562    /// * owned-form + empty sentinel → [`Self::owned_name_or_empty`]
563    ///   (`String` projection with a `""` fallback; `AllocationRef.name`
564    ///   seed);
565    /// * **presence-and-equal probe → this method** (`bool` projection
566    ///   with `None`-preserving semantics; pool-lookup closure
567    ///   discriminant).
568    ///
569    /// A future normalization step (a name-canonicalization pass, a
570    /// case-fold key builder, a per-cluster prefix stripper for cross-
571    /// cluster pool-name aliasing, or a canonical-namespace default
572    /// lift) lands at ONE substrate method here and both downstream
573    /// consumers pick up the upgrade mechanically — no per-callsite
574    /// hand-edit at `resolve_pool` / `controller_allocation
575    /// ::reconcile_inner`.
576    ///
577    /// Theory anchor: THEORY.md §VI.1 (generation over composition —
578    /// the `.metadata.name.as_deref() == Some(<candidate>)` chain
579    /// recurred at two hand-authored sites past the ★★ PRIME-
580    /// DIRECTIVE ≥ 2 duplication trigger, and is lifted to ONE owner
581    /// here). THEORY.md §II.1 invariant 5 (composition preserves
582    /// proofs — the pins bind the missing-slot corner (`None ⇒
583    /// false`, even against a `""` candidate) + the populated-slot
584    /// equal corner + the populated-slot unequal corner + the
585    /// byte-identical parity with the pre-lift `.as_deref() == Some
586    /// (<candidate>)` chain + the disjoint semantics vs. the
587    /// `_or_empty` sibling family, so a regression that drifted any
588    /// surface at `tests::has_name_*` here rather than as silent
589    /// operator-facing skew between the two `find` closures the
590    /// primitive owns).
591    #[must_use]
592    pub fn has_name(&self, candidate: &str) -> bool {
593        self.metadata.name.as_deref() == Some(candidate)
594    }
595}
596
597/// What the pool reconciler does when a member reaches `Failed`.
598///
599/// Sibling closed-set lifts on the same `tatara-process` axis:
600/// [`crate::compliance::VerificationPhase::ALL`],
601/// [`crate::signal::SighupStrategy::ALL`],
602/// [`crate::spec::MustReachPhase::ALL`],
603/// [`crate::intent::WorkloadKind::ALL`],
604/// [`crate::export::ReportFormat::ALL`],
605/// [`crate::encapsulates::EncapsulationMode::ALL`],
606/// [`crate::export::ExportTrigger::ALL`],
607/// [`crate::lifetime::TeardownPolicy::ALL`],
608/// [`crate::boundary::ConditionKind::ALL`],
609/// [`crate::lifetime::LifetimeKind::ALL`],
610/// [`crate::intent::IntentKind::ALL`],
611/// [`crate::phase::ProcessPhase::ALL`],
612/// [`crate::signal::ProcessSignal::ALL`].
613#[derive(
614    Clone,
615    Copy,
616    Debug,
617    Default,
618    Serialize,
619    Deserialize,
620    JsonSchema,
621    PartialEq,
622    Eq,
623    Hash,
624    tatara_closed_set::DeriveClosedSet,
625)]
626#[serde(rename_all = "PascalCase")]
627#[closed_set(via = "as_str", generate_unknown, display)]
628pub enum ReplacementPolicy {
629    /// **Default** — Failed member is reaped + replaced immediately
630    /// (pool stays at `desired` count). Most production-like.
631    #[default]
632    ReplaceImmediate,
633    /// Failed member stays for inspection; pool runs short until the
634    /// operator manually reaps it. Useful for debugging.
635    HoldFailed,
636    /// Failed member triggers pool-wide pause: `desired` is
637    /// effectively 0 until the operator manually resumes via a
638    /// pool-status patch. Used for "halt on any failure" workflows.
639    PausePool,
640}
641
642impl ReplacementPolicy {
643    /// The closed set of replacement policies — single source of truth
644    /// that drives the `as_str` / Display / `FromStr` triad and the
645    /// `replaces_failed` / `pauses_on_failure` predicate pair. Adding a
646    /// fourth variant lands at one `ALL` entry + one `as_str` arm + one
647    /// predicate arm per projection — exhaustively checked by the
648    /// compiler (the `[Self; 3]` array literal forces the arity) and by
649    /// the predicate-pair injectivity test below (a new variant must
650    /// land in its own (replaces_failed, pauses_on_failure) bucket or
651    /// the author has to extend the consumer dispatch in
652    /// `tatara-pool-reconciler::desired::PoolConvergence::decide`).
653    pub const ALL: [Self; 3] = [Self::ReplaceImmediate, Self::HoldFailed, Self::PausePool];
654
655    /// Canonical PascalCase wire-format projection — matches the serde
656    /// `rename_all = "PascalCase"` output verbatim AND the CRD `enum:`
657    /// enumeration the pool reconciler stamps on the
658    /// `ephemeralpools.tatara.pleme.io` schema. Pinned by
659    /// `replacement_policy_as_str_matches_serde` so a variant rename
660    /// can't drift between the typed surface, the CRD enum, the YAML
661    /// wire format AND the operator-facing diagnostic (the
662    /// `desired.rs` Pause reason composes `policy={policy}` via
663    /// Display, not a hard-coded `"PausePool"` literal that would
664    /// silently rot).
665    pub const fn as_str(self) -> &'static str {
666        match self {
667            Self::ReplaceImmediate => "ReplaceImmediate",
668            Self::HoldFailed => "HoldFailed",
669            Self::PausePool => "PausePool",
670        }
671    }
672
673    /// Should the pool auto-spawn a replacement for a Failed member?
674    /// Closed-set match (not `matches!`) so a future variant triggers
675    /// the compiler's exhaustiveness check at this site rather than
676    /// silently defaulting to `false`. Paired with
677    /// `pauses_on_failure` they form the two-axis projection
678    /// consumers in `tatara-pool-reconciler::desired::PoolConvergence`
679    /// pattern-match against — `replaces_failed` true ⇒ emit
680    /// `ReapFailed` per failure; `pauses_on_failure` true with any
681    /// failure ⇒ emit `Pause` and short-circuit. The pair is
682    /// `(true, false) | (false, false) | (false, true)` — pinned
683    /// injective by `replacement_policy_predicate_pair_is_injective`.
684    pub const fn replaces_failed(self) -> bool {
685        match self {
686            Self::ReplaceImmediate => true,
687            Self::HoldFailed | Self::PausePool => false,
688        }
689    }
690
691    /// Should reaching Failed on any member pause the whole pool?
692    /// See `replaces_failed` for the closed-match rationale + the
693    /// predicate-pair contract.
694    pub const fn pauses_on_failure(self) -> bool {
695        match self {
696            Self::PausePool => true,
697            Self::ReplaceImmediate | Self::HoldFailed => false,
698        }
699    }
700}
701
702// `impl FromStr for ReplacementPolicy` + `impl tatara_lisp::ClosedSet for
703// ReplacementPolicy` + `impl fmt::Display for ReplacementPolicy` are
704// generated by `#[derive(tatara_closed_set::DeriveClosedSet)]` on the enum
705// declaration above. `label` delegates to the inherent
706// `ReplacementPolicy::as_str` via `#[closed_set(via = "as_str")]` so the
707// PascalCase wire-format projection stays load-bearing (matches the
708// serde `rename_all = "PascalCase"` output AND the
709// `tatara-pool-reconciler::desired::PoolConvergence` Pause reason
710// emission verbatim) while generic `T: ClosedSet` consumers reach the
711// STABLE workspace-wide name (`label`); Display delegates to the same
712// inherent projection via `#[closed_set(display)]` so the
713// `Pause` reason emitter's `policy={policy}` composition stays
714// pinned on the closed-set algebra rather than on a hand-rolled
715// `fmt::Display` block per implementor.
716
717// `pub struct UnknownReplacementPolicy(pub String)` is generated by
718// `#[derive(tatara_closed_set::DeriveClosedSet)]` + `#[closed_set(generate_unknown)]`
719// on the enum declaration above. The auto-derived label
720// `"replacement policy"` matches the prior hand-rolled
721// `#[error("unknown replacement policy: {0}")]` verbatim. Symmetric to
722// [`UnknownMemberState`], [`UnknownPoolPhase`], [`UnknownReturnPolicy`],
723// [`crate::export::UnknownReportFormat`],
724// [`crate::export::UnknownChannelKind`],
725// [`crate::export::UnknownExportTrigger`],
726// [`crate::lifetime::UnknownTeardownPolicy`],
727// [`crate::boundary::UnknownConditionKind`], and
728// [`crate::phase::UnknownPhase`].
729
730fn default_free_ttl() -> String {
731    "24h".to_string()
732}
733fn default_max_allocation_ttl() -> String {
734    "4h".to_string()
735}
736
737/// `EphemeralPool.status` — observed pool population state.
738#[derive(Clone, Debug, Default, Deserialize, Serialize, JsonSchema)]
739#[serde(rename_all = "camelCase")]
740pub struct PoolStatus {
741    /// Pool lifecycle phase.
742    #[serde(default)]
743    pub phase: PoolPhase,
744
745    /// When the pool entered the current phase.
746    #[serde(default, skip_serializing_if = "Option::is_none")]
747    pub phase_since: Option<DateTime<Utc>>,
748
749    /// Number of members currently in `Free` state (ready for allocation).
750    #[serde(default)]
751    pub ready_count: u32,
752
753    /// Number of members currently `Allocated`.
754    #[serde(default)]
755    pub allocated_count: u32,
756
757    /// Number of members currently `Spawning` (not yet Attested).
758    #[serde(default)]
759    pub spawning_count: u32,
760
761    /// Number of members currently `Returning` (reset or replace
762    /// in progress).
763    #[serde(default)]
764    pub returning_count: u32,
765
766    /// Member ledger — one entry per pool slot.
767    #[serde(default)]
768    pub members: Vec<PoolMember>,
769
770    /// Operator-visible message (e.g., "scaled down to floor").
771    #[serde(default, skip_serializing_if = "Option::is_none")]
772    pub message: Option<String>,
773
774    /// Standard Kubernetes Conditions.
775    #[serde(default)]
776    pub conditions: Vec<PoolCondition>,
777}
778
779/// One pool slot's state.
780#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)]
781#[serde(rename_all = "camelCase")]
782pub struct PoolMember {
783    /// `metadata.name` of the backing Process.
784    pub process_name: String,
785    /// Pool member's current slot state.
786    pub state: MemberState,
787    /// When the member entered the current state.
788    pub entered_state_at: DateTime<Utc>,
789    /// If allocated: the AllocationRef holding this slot.
790    #[serde(default, skip_serializing_if = "Option::is_none")]
791    pub allocation_ref: Option<AllocationRef>,
792}
793
794impl PoolStatus {
795    /// Substrate constructor for the observed [`PoolStatus`] seed:
796    /// composes the `(phase, phase_since, ready/allocated/spawning
797    /// /returning counts, members, message, conditions)` 9-slot record
798    /// every pool-reconciler status-patch site restated by hand pre-
799    /// lift. The four counters ride a SINGLE closed-set-driven fold
800    /// over the members list (one pass rather than four independent
801    /// filter-and-count passes); the `message` + `conditions` slots
802    /// stay at their invariant `None` / `vec![]` defaults every pre-
803    /// lift caller stamped verbatim, and `phase_since` is derived from
804    /// the caller-supplied `now` timestamp so the constructor stays
805    /// clock-injectable rather than implicitly reading wall time.
806    ///
807    /// Pre-lift the 11-line
808    /// ```rust,ignore
809    /// PoolStatus {
810    ///     phase,
811    ///     phase_since: Some(Utc::now()),
812    ///     ready_count: count_state(&members, MemberState::Free),
813    ///     allocated_count: count_state(&members, MemberState::Allocated),
814    ///     spawning_count: count_state(&members, MemberState::Spawning),
815    ///     returning_count: count_state(&members, MemberState::Returning),
816    ///     members: members.clone(),
817    ///     message: None,
818    ///     conditions: vec![],
819    /// }
820    /// ```
821    /// incantation was hand-authored at TWO sites past the ★★ PRIME-
822    /// DIRECTIVE ≥ 2 duplication threshold in
823    /// `tatara-pool-reconciler::controller_pool::reconcile_inner`,
824    /// both restating the same 4-slot count fanout + defaults:
825    /// * The `desired > 0` path — status patch after the
826    ///   convergence-action loop when the operator drives the pool
827    ///   through the R11 desired-count invariant.
828    /// * The legacy allocation-driven path (`desired == 0`) — status
829    ///   patch after the [`crate::pool::PoolDecision`] apply loop.
830    ///
831    /// Both sites walked the SAME 4-slot count fanout on the SAME
832    /// four `MemberState` variants (Free/Allocated/Spawning/Returning)
833    /// and stamped the SAME defaults (`message: None`, `conditions:
834    /// vec![]`), even though the four counters walked the members list
835    /// four independent times pre-lift when a single pass suffices.
836    /// Post-lift both callers write
837    /// `PoolStatus::observed(phase, members, Utc::now())` and share
838    /// ONE substrate owner; a future counter slot (e.g., a
839    /// `warming_count` for a `MemberState::Warming` variant between
840    /// Spawning and Free) plugs into the fold at ONE match arm and
841    /// both status-patch sites inherit the new slot mechanically.
842    ///
843    /// The `Failed` variant is deliberately absent from the fold — no
844    /// `PoolStatus` slot counts failed members (they surface via
845    /// `pool_phase_from_members`'s `PoolPhase::Degraded` transition
846    /// instead), and the closed-set match on
847    /// [`MemberState`] pins that a future variant which SHOULD count
848    /// toward one of the four buckets triggers the compiler's
849    /// exhaustiveness check at this fold rather than silently sinking
850    /// into `Failed`'s no-op arm.
851    ///
852    /// Theory anchor: THEORY.md §VI.1 (generation over composition —
853    /// the 11-line status-seed incantation recurred at two hand-
854    /// authored sites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication
855    /// trigger, and is lifted to ONE owner here). THEORY.md §II.1
856    /// invariant 5 (composition preserves proofs — the pins bind the
857    /// 4-slot count fanout + the closed-set exhaustiveness on
858    /// `MemberState` + the invariant defaults, so a regression that
859    /// dropped a counter slot or swapped a variant surfaces at
860    /// `tests::pool_status_observed_*` rather than as silent operator-
861    /// facing skew between the two status-patch sites on the SAME
862    /// pool).
863    #[must_use]
864    pub fn observed(phase: PoolPhase, members: Vec<PoolMember>, now: DateTime<Utc>) -> Self {
865        let (ready_count, allocated_count, spawning_count, returning_count) =
866            PoolMember::state_count_fanout(&members);
867        Self {
868            phase,
869            phase_since: Some(now),
870            ready_count,
871            allocated_count,
872            spawning_count,
873            returning_count,
874            members,
875            message: None,
876            conditions: vec![],
877        }
878    }
879}
880
881impl PoolMember {
882    /// Substrate primitive: single-pass closed-set fold over a
883    /// `[PoolMember]` slice producing the `(ready, allocated,
884    /// spawning, returning)` 4-tuple every `PoolStatus` seed stamps at
885    /// its four counter slots. The `Failed` arm is a no-op (no
886    /// `PoolStatus` counter tracks failed members — they surface via
887    /// [`PoolPhase::Degraded`] instead), pinned by the closed-set
888    /// match so a future variant that SHOULD count toward one of the
889    /// four buckets triggers the compiler's exhaustiveness check here
890    /// rather than silently falling through.
891    ///
892    /// Consumed by [`PoolStatus::observed`]. A caller that needs a
893    /// single per-variant count outside the status-seed fanout should
894    /// keep spelling `members.iter().filter(...).count()` rather than
895    /// walking this 4-tuple — the fanout is shaped for the
896    /// `PoolStatus` fill, not for arbitrary per-variant queries.
897    #[must_use]
898    pub fn state_count_fanout(members: &[Self]) -> (u32, u32, u32, u32) {
899        let mut ready = 0u32;
900        let mut allocated = 0u32;
901        let mut spawning = 0u32;
902        let mut returning = 0u32;
903        for m in members {
904            match m.state {
905                MemberState::Free => ready += 1,
906                MemberState::Allocated => allocated += 1,
907                MemberState::Spawning => spawning += 1,
908                MemberState::Returning => returning += 1,
909                MemberState::Failed => {}
910            }
911        }
912        (ready, allocated, spawning, returning)
913    }
914}
915
916/// Light reference to an `EphemeralAllocation`.
917#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema, PartialEq, Eq)]
918#[serde(rename_all = "camelCase")]
919pub struct AllocationRef {
920    pub name: String,
921    pub namespace: String,
922}
923
924impl AllocationRef {
925    /// Substrate constructor for [`AllocationRef`]: composes the
926    /// `(name, namespace)` pair through ONE `impl Into<String>`-gated
927    /// entry point — the ONE-liner collapse of the paired
928    /// `AllocationRef { name: n.into(), namespace: ns.into() }`
929    /// struct-literal incantation every downstream consumer restated
930    /// by hand pre-lift.
931    ///
932    /// Pre-lift the `AllocationRef { name, namespace }` struct-literal
933    /// was hand-authored at FOUR production sites past the ★★ PRIME-
934    /// DIRECTIVE ≥ 2 duplication threshold across the workspace, all
935    /// composing an owned `(name: String, namespace: String)` pair
936    /// under one of two roles:
937    /// * `tatara-pool-reconciler::controller_allocation::reconcile_inner`
938    ///   Bind path — the `assignedProcess` status slot's ref, pairing
939    ///   the just-bound member Process name with the allocation's
940    ///   containing namespace.
941    /// * `tatara-pool-reconciler::controller_allocation::reconcile_inner`
942    ///   Release path — the same `assignedProcess` slot shape, stamped
943    ///   at the release-side status patch alongside the (unchanged)
944    ///   `boundPool` ref.
945    /// * `tatara-pool-reconciler::allocation_decide::AllocationConvergenceCtx::observe`
946    ///   pool-matched handle — the `matched_pool` slot's ref, pairing
947    ///   [`EphemeralPool::owned_name_or_empty`] with the pool's
948    ///   containing namespace.
949    /// * `tatara-github-watcher::allocation_factory::allocation_from_pr`
950    ///   — the `pool_ref` slot on the `AllocationSpec` emitted from a
951    ///   PullRequestEvent, pairing the operator-configured pool name
952    ///   with the watcher's target namespace.
953    ///
954    /// All FOUR sites walked the SAME two-field struct-literal shape
955    /// — an owned name half, an owned namespace half — differing only
956    /// in provenance. Post-lift each callsite reads
957    /// `AllocationRef::new(name, ns)` and the produced value feeds the
958    /// same downstream slot (`assignedProcess` / `bound_pool` /
959    /// `matched_pool` / `spec.pool_ref`) unchanged. The `impl Into<String>`
960    /// signature accepts every provenance the pre-lift sites carried —
961    /// owned `String` (the reconciler's owned-form projections), `&str`
962    /// (the factory's `n.to_string()` / `namespace.to_string()`
963    /// borrow-to-owned promotions), `Cow<str>`, and every other
964    /// `Into<String>` implementor — so no callsite has to change its
965    /// upstream provenance to route through the primitive.
966    ///
967    /// Return-form axis: owned [`AllocationRef`] — the wire-format
968    /// shape [`crate::pool::AllocationRef`]'s serde `rename_all =
969    /// "camelCase"` produces on both spec (`poolRef`) and status
970    /// (`boundPool` / `assignedProcess`) slots. The primitive owns
971    /// the axis-order `(name, namespace)` — the same order the four
972    /// consumers spelled — so a slot swap surfaces at the
973    /// `allocation_ref_new_positional_axis_order` pin below rather
974    /// than as silent `<namespace>/<name>` inversion downstream.
975    ///
976    /// Peer to the sibling substrate primitives already opened on the
977    /// pool-side (name, namespace) axis pair:
978    /// [`EphemeralPool::name_or_empty`] (borrow-form name),
979    /// [`EphemeralPool::owned_name_or_empty`] (owned-form name); this
980    /// constructor is the composer that folds the owned-form projections
981    /// into the wire-format ref shape.
982    ///
983    /// A future refactor of [`AllocationRef`]'s field set (a
984    /// `resource_kind: String` field for cross-CRD refs, an
985    /// `api_version: String` field for FQN references, a
986    /// canonicalization pass over the namespace half, a non-empty-name
987    /// gate) lands at ONE substrate constructor site here and every
988    /// downstream consumer inherits the upgrade mechanically — no per-
989    /// callsite hand-edit at the FOUR reconciler + factory sites.
990    ///
991    /// Theory anchor: THEORY.md §VI.1 (generation over composition —
992    /// the `AllocationRef { name, namespace }` struct-literal shape
993    /// recurred at four hand-authored sites past the ★★ PRIME-
994    /// DIRECTIVE ≥ 2 duplication trigger, and is lifted to ONE owner
995    /// here). THEORY.md §II.1 invariant 5 (composition preserves
996    /// proofs — the pins bind the positional axis-order + the
997    /// `Into<String>` provenance closure + byte-identical parity with
998    /// the pre-lift struct-literal + `PartialEq` coherence with the
999    /// hand-authored form, so a regression that reshaped any surface
1000    /// at `tests::allocation_ref_new_*` rather than as silent
1001    /// operator-facing skew between the assignedProcess / bound_pool
1002    /// / matched_pool / spec.pool_ref slots on the SAME allocation).
1003    #[must_use]
1004    pub fn new(name: impl Into<String>, namespace: impl Into<String>) -> Self {
1005        Self {
1006            name: name.into(),
1007            namespace: namespace.into(),
1008        }
1009    }
1010}
1011
1012/// Per-slot state in the pool's free list.
1013///
1014/// Sibling closed-sets on the `EphemeralPool` axis: [`ReplacementPolicy::ALL`]
1015/// (the on-failure policy that the pool reconciler dispatches against
1016/// the [`Self::is_failed`] projection), [`ReturnPolicy::ALL`] (the
1017/// release-time disposition that transitions an [`Self::Allocated`]
1018/// member into [`Self::Returning`] before it either re-enters
1019/// [`Self::Free`] or gets [`Self::Spawning`]'d as a fresh slot).
1020#[derive(
1021    Clone,
1022    Copy,
1023    Debug,
1024    PartialEq,
1025    Eq,
1026    Hash,
1027    Serialize,
1028    Deserialize,
1029    JsonSchema,
1030    tatara_closed_set::DeriveClosedSet,
1031)]
1032#[serde(rename_all = "PascalCase")]
1033#[closed_set(via = "as_str", generate_unknown, display)]
1034pub enum MemberState {
1035    /// Pool reconciler is creating/converging the backing Process.
1036    Spawning,
1037    /// Process is `Attested`; ready for allocation.
1038    Free,
1039    /// Held by an `EphemeralAllocation`.
1040    Allocated,
1041    /// Return policy is being applied (Reset → reset Job; Replace →
1042    /// Process is being torn down and recreated).
1043    Returning,
1044    /// Permanent failure — the member needs operator attention.
1045    Failed,
1046}
1047
1048impl MemberState {
1049    /// The closed set of member states — single source of truth that
1050    /// drives the `as_str` / Display / `FromStr` triad AND the
1051    /// `is_failed` / `counts_toward_supply` predicate pair. Adding a
1052    /// sixth variant lands at one `ALL` entry + one `as_str` arm + one
1053    /// arm per predicate — exhaustively checked by the compiler (the
1054    /// `[Self; 5]` array literal forces the arity) and by the
1055    /// per-variant truth-table contract test (a new variant must
1056    /// declare its own `(is_failed, counts_toward_supply)` projection
1057    /// or the consumer dispatch in
1058    /// `tatara-pool-reconciler::controller_pool::pool_phase_from_members`
1059    /// and `tatara-pool-reconciler::pool_decide::decide_pool_reconcile`
1060    /// will silently bucket it into the wrong lifecycle column).
1061    pub const ALL: [Self; 5] = [
1062        Self::Spawning,
1063        Self::Free,
1064        Self::Allocated,
1065        Self::Returning,
1066        Self::Failed,
1067    ];
1068
1069    /// Canonical PascalCase wire-format projection — matches the serde
1070    /// `rename_all = "PascalCase"` output verbatim AND the CRD `enum:`
1071    /// enumeration that `ephemeralpools.tatara.pleme.io` stamps on
1072    /// `status.members[].state`. Pinned by
1073    /// `member_state_as_str_matches_serde` so a variant rename can't
1074    /// drift between the typed surface, the CRD enum, the YAML wire
1075    /// format AND any future operator-facing diagnostic that composes
1076    /// `state={state}` via Display rather than a hard-coded literal
1077    /// that would silently rot.
1078    pub const fn as_str(self) -> &'static str {
1079        match self {
1080            Self::Spawning => "Spawning",
1081            Self::Free => "Free",
1082            Self::Allocated => "Allocated",
1083            Self::Returning => "Returning",
1084            Self::Failed => "Failed",
1085        }
1086    }
1087
1088    /// Is this member in a permanent-failure state — needs operator
1089    /// attention? Closed-set match (not `matches!`) so a future variant
1090    /// triggers the compiler's exhaustiveness check at this site rather
1091    /// than silently defaulting to `false`. Consumed by
1092    /// `tatara-pool-reconciler::pool_decide::decide_pool_reconcile` to
1093    /// gate the highest-priority `ReplaceMembers` decision branch — a
1094    /// future variant that should also trigger replacement (e.g.
1095    /// `MemberState::Quarantined`) flips this predicate at one site
1096    /// and inherits the priority-1 dispatch without touching the
1097    /// consumer match arm.
1098    pub const fn is_failed(self) -> bool {
1099        match self {
1100            Self::Failed => true,
1101            Self::Spawning | Self::Free | Self::Allocated | Self::Returning => false,
1102        }
1103    }
1104
1105    /// Does this member contribute to the pool's *available supply*
1106    /// (current ready slots + slots coming online)? Closed-set match so
1107    /// a future variant triggers the compiler's exhaustiveness check.
1108    /// Consumed by
1109    /// `tatara-pool-reconciler::controller_pool::pool_phase_from_members`
1110    /// — the `(free + spawning)` supply calc collapses into one
1111    /// predicate-driven filter, so a future "warming-up" state
1112    /// (`MemberState::Warming` between Spawning and Free) plugs into
1113    /// the supply count at one site rather than three. Disjoint with
1114    /// `is_failed` — pinned by `member_state_failed_implies_no_supply`
1115    /// (a Failed member can never count toward supply; the pool
1116    /// reconciler would otherwise double-count failures as available
1117    /// capacity).
1118    pub const fn counts_toward_supply(self) -> bool {
1119        match self {
1120            Self::Free | Self::Spawning => true,
1121            Self::Allocated | Self::Returning | Self::Failed => false,
1122        }
1123    }
1124}
1125
1126// `impl FromStr for MemberState` + `impl tatara_lisp::ClosedSet for
1127// MemberState` + `impl fmt::Display for MemberState` are generated by
1128// `#[derive(tatara_closed_set::DeriveClosedSet)]` on the enum declaration
1129// above. `label` delegates to the inherent `MemberState::as_str` via
1130// `#[closed_set(via = "as_str")]` so the
1131// `pool_phase_from_members` supply calc can keep keying on
1132// `counts_toward_supply` against the typed variant while a generic
1133// `T: ClosedSet` consumer reaches the STABLE workspace-wide name
1134// (`label`) without knowing this enum lives in `tatara-process::pool`;
1135// Display delegates to the same inherent projection via
1136// `#[closed_set(display)]` so the diagnostic emitter's
1137// `state={state}` composition stays pinned on the closed-set algebra.
1138
1139// `pub struct UnknownMemberState(pub String)` is generated by
1140// `#[derive(tatara_closed_set::DeriveClosedSet)]` + `#[closed_set(generate_unknown)]`
1141// on the enum declaration above. The auto-derived label `"member state"`
1142// matches the prior hand-rolled `#[error("unknown member state: {0}")]`
1143// verbatim. Symmetric to [`UnknownReplacementPolicy`],
1144// [`UnknownPoolPhase`], [`UnknownReturnPolicy`],
1145// [`crate::lifetime::UnknownTeardownPolicy`],
1146// [`crate::boundary::UnknownConditionKind`], and
1147// [`crate::phase::UnknownPhase`].
1148
1149/// Pool lifecycle phase (observed across the whole pool population).
1150///
1151/// Sibling closed-set on the same `EphemeralPool` axis as
1152/// [`MemberState::ALL`] (the per-slot lifecycle this phase aggregates
1153/// over via [`MemberState::counts_toward_supply`]),
1154/// [`ReplacementPolicy::ALL`] (on-failure policy) and
1155/// [`ReturnPolicy::ALL`] (release-time disposition). Together with
1156/// `MemberState`, this closes the pool reconciler's
1157/// `(slot-state, pool-phase)` two-tier observation algebra on the
1158/// same closed-set discipline as the rest of `tatara-process`.
1159#[derive(
1160    Clone,
1161    Copy,
1162    Debug,
1163    PartialEq,
1164    Eq,
1165    Hash,
1166    Serialize,
1167    Deserialize,
1168    JsonSchema,
1169    tatara_closed_set::DeriveClosedSet,
1170)]
1171#[serde(rename_all = "PascalCase")]
1172#[closed_set(via = "as_str", generate_unknown, display)]
1173pub enum PoolPhase {
1174    /// Just admitted; no members yet.
1175    Initializing,
1176    /// `ready_count == desired_size`.
1177    Steady,
1178    /// `ready_count + spawning_count < desired_size` and reconciler
1179    /// is creating new members.
1180    ScalingUp,
1181    /// `ready_count > desired_size` and reconciler is reaping excess.
1182    ScalingDown,
1183    /// `min_size` constraint violated.
1184    Degraded,
1185    /// Pool is being deleted; reconciler is reaping all members.
1186    Draining,
1187}
1188
1189impl Default for PoolPhase {
1190    fn default() -> Self {
1191        Self::Initializing
1192    }
1193}
1194
1195impl PoolPhase {
1196    /// The closed set of pool phases — single source of truth that
1197    /// drives the `as_str` / Display / `FromStr` triad AND the
1198    /// `is_steady` / `is_terminal` predicate pair. Adding a seventh
1199    /// variant lands at one `ALL` entry + one `as_str` arm + one arm
1200    /// per predicate — exhaustively checked by the compiler (the
1201    /// `[Self; 6]` array literal forces the arity) AND by the
1202    /// per-variant truth-table contract test (a new variant must
1203    /// declare its own `(is_steady, is_terminal)` projection or any
1204    /// future status-aggregator surface — `feira pool list
1205    /// --healthy`, the operator-facing condition aggregator, the
1206    /// desired-loop heartbeat short-circuit — will silently bucket
1207    /// it into the wrong lifecycle column).
1208    pub const ALL: [Self; 6] = [
1209        Self::Initializing,
1210        Self::Steady,
1211        Self::ScalingUp,
1212        Self::ScalingDown,
1213        Self::Degraded,
1214        Self::Draining,
1215    ];
1216
1217    /// Canonical PascalCase wire-format projection — matches the
1218    /// serde `rename_all = "PascalCase"` output verbatim AND the CRD
1219    /// `enum:` enumeration that `ephemeralpools.tatara.pleme.io`
1220    /// stamps on `status.phase`. Pinned by
1221    /// `pool_phase_as_str_matches_serde` so a variant rename can't
1222    /// drift between the typed surface, the CRD enum, the YAML wire
1223    /// format AND any future operator-facing diagnostic that
1224    /// composes `phase={phase}` via Display rather than a hard-coded
1225    /// literal that would silently rot. Display + FromStr triad
1226    /// over `ALL` mirrors `MemberState` / `ReplacementPolicy` /
1227    /// `ReturnPolicy` / `AllocationPhase` / `TeardownPolicy` /
1228    /// `ConditionKind` / `ProcessPhase` / `ProcessSignal`.
1229    pub const fn as_str(self) -> &'static str {
1230        match self {
1231            Self::Initializing => "Initializing",
1232            Self::Steady => "Steady",
1233            Self::ScalingUp => "ScalingUp",
1234            Self::ScalingDown => "ScalingDown",
1235            Self::Degraded => "Degraded",
1236            Self::Draining => "Draining",
1237        }
1238    }
1239
1240    /// Is the pool fully converged — supply matches desired, no
1241    /// reconciler-driven population change pending? Closed-set match
1242    /// (not `matches!`) so a future variant triggers the compiler's
1243    /// exhaustiveness check at this site rather than silently
1244    /// defaulting to `false`. Paired with `is_terminal` they form
1245    /// the two-axis projection that future status aggregators
1246    /// (operator-facing fleet health, `feira pool list --healthy`,
1247    /// the SSE filter "show non-steady pools") dispatch against —
1248    /// `is_steady && !is_terminal` ⇒ converged (goal state);
1249    /// `!is_steady && is_terminal` ⇒ being deleted (no future
1250    /// spawn); `!is_steady && !is_terminal` ⇒ transient
1251    /// (Initializing | ScalingUp | ScalingDown | Degraded — pool
1252    /// is in motion toward desired). The impossible bucket
1253    /// `(true, true)` — a draining pool that's somehow also steady
1254    /// — is pinned empty by `pool_phase_steady_excludes_terminal`.
1255    pub const fn is_steady(self) -> bool {
1256        match self {
1257            Self::Steady => true,
1258            Self::Initializing
1259            | Self::ScalingUp
1260            | Self::ScalingDown
1261            | Self::Degraded
1262            | Self::Draining => false,
1263        }
1264    }
1265
1266    /// Is the pool in its absorbing exit state — deletion-stamped,
1267    /// reconciler is reaping every member, no spawn will ever
1268    /// happen again? Closed-set match so a future variant triggers
1269    /// the compiler's exhaustiveness check. See `is_steady` for the
1270    /// predicate-pair contract + bucket definitions.
1271    pub const fn is_terminal(self) -> bool {
1272        match self {
1273            Self::Draining => true,
1274            Self::Initializing
1275            | Self::Steady
1276            | Self::ScalingUp
1277            | Self::ScalingDown
1278            | Self::Degraded => false,
1279        }
1280    }
1281}
1282
1283// `impl FromStr for PoolPhase` + `impl tatara_lisp::ClosedSet for PoolPhase`
1284// + `impl fmt::Display for PoolPhase` are generated by
1285// `#[derive(tatara_closed_set::DeriveClosedSet)]` on the enum declaration above.
1286// `label` delegates to the inherent `PoolPhase::as_str` via
1287// `#[closed_set(via = "as_str")]` so the operator-facing
1288// `phase={phase}` Display composition keeps reading the same canonical
1289// PascalCase projection while a generic `T: ClosedSet` consumer (a
1290// status-aggregator filter, the `feira pool list --healthy` predicate, a
1291// future SSE event router) can walk every variant without knowing the
1292// closed set lives in `tatara-process::pool`; Display delegates to the
1293// same inherent projection via `#[closed_set(display)]` so the
1294// `phase={phase}` composition stays pinned on the closed-set algebra
1295// rather than a hand-rolled `fmt::Display` block.
1296
1297// `pub struct UnknownPoolPhase(pub String)` is generated by
1298// `#[derive(tatara_closed_set::DeriveClosedSet)]` + `#[closed_set(generate_unknown)]`
1299// on the enum declaration above. The auto-derived label `"pool phase"`
1300// matches the prior hand-rolled `#[error("unknown pool phase: {0}")]`
1301// verbatim. Symmetric to [`UnknownMemberState`],
1302// [`UnknownReplacementPolicy`], [`UnknownReturnPolicy`],
1303// [`crate::lifetime::UnknownTeardownPolicy`],
1304// [`crate::boundary::UnknownConditionKind`], and
1305// [`crate::phase::UnknownPhase`].
1306
1307/// Standard K8s Condition shape (kept local so tatara-process doesn't
1308/// depend on k8s_openapi types in its public schema).
1309#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)]
1310#[serde(rename_all = "camelCase")]
1311pub struct PoolCondition {
1312    pub type_: String,
1313    pub status: String,
1314    pub reason: String,
1315    pub message: String,
1316    pub last_transition_time: DateTime<Utc>,
1317}
1318
1319/// What the pool does when an allocation releases a member.
1320///
1321/// Sibling closed-set on the `EphemeralPool` axis:
1322/// [`ReplacementPolicy::ALL`]. Sibling closed-sets on the
1323/// `tatara-process` algebra: [`crate::lifetime::TeardownPolicy::ALL`]
1324/// (the *release*-time counterpart for non-pooled ephemeral envs),
1325/// [`crate::boundary::ConditionKind::ALL`],
1326/// [`crate::lifetime::LifetimeKind::ALL`],
1327/// [`crate::intent::IntentKind::ALL`],
1328/// [`crate::phase::ProcessPhase::ALL`],
1329/// [`crate::signal::ProcessSignal::ALL`].
1330#[derive(
1331    Clone,
1332    Copy,
1333    Debug,
1334    Hash,
1335    PartialEq,
1336    Eq,
1337    Serialize,
1338    Deserialize,
1339    JsonSchema,
1340    Default,
1341    tatara_closed_set::DeriveClosedSet,
1342)]
1343#[serde(rename_all = "PascalCase")]
1344#[closed_set(via = "as_str", generate_unknown, display)]
1345pub enum ReturnPolicy {
1346    /// Tear down the Process + create a fresh one. Safe but slow
1347    /// (1-2 min spin-up before the slot is Free again).
1348    #[default]
1349    Replace,
1350    /// Keep the Process running; run a typed `:reset` Job that wipes
1351    /// state (DB drop, secrets rotate). Fast (~5-10s) but depends on
1352    /// the reset Job being correct for the workload. API-authoritative
1353    /// systems are natural fits because the control API owns all state.
1354    Reset,
1355    /// Keep the Process indefinitely after release (debugging aid;
1356    /// operator must `feira pool reap NAME` to clean up). Useful for
1357    /// post-mortem of a flaky test.
1358    Keep,
1359}
1360
1361impl ReturnPolicy {
1362    /// The closed set of return policies — single source of truth that
1363    /// drives the `as_str` / Display / `FromStr` triad and the
1364    /// `keeps_process` / `runs_reset_job` predicate pair. Adding a
1365    /// fourth variant lands at one `ALL` entry + one `as_str` arm +
1366    /// one arm per predicate — exhaustively checked by the compiler
1367    /// (the `[Self; 3]` array literal forces the arity) and by the
1368    /// predicate-pair injectivity test (a new variant must land in
1369    /// its own (keeps_process, runs_reset_job) bucket or the author
1370    /// has to extend the consumer dispatch in
1371    /// `tatara-pool-reconciler::return_policy::plan_return`).
1372    pub const ALL: [Self; 3] = [Self::Replace, Self::Reset, Self::Keep];
1373
1374    /// Canonical PascalCase wire-format projection — matches the
1375    /// serde `rename_all = "PascalCase"` output verbatim AND the CRD
1376    /// `enum:` enumeration the pool reconciler stamps on the
1377    /// `ephemeralpools.tatara.pleme.io` schema. Pinned by
1378    /// `return_policy_as_str_matches_serde` so a variant rename can't
1379    /// drift between the typed surface, the CRD enum, the YAML wire
1380    /// format AND any future operator-facing diagnostic that composes
1381    /// `policy={policy}` via Display rather than a hard-coded literal.
1382    pub const fn as_str(self) -> &'static str {
1383        match self {
1384            Self::Replace => "Replace",
1385            Self::Reset => "Reset",
1386            Self::Keep => "Keep",
1387        }
1388    }
1389
1390    /// Does the pool keep the backing Process alive across release?
1391    /// Closed-set match (not `matches!`) so a future variant triggers
1392    /// the compiler's exhaustiveness check at this site rather than
1393    /// silently defaulting to `false`. Paired with `runs_reset_job`
1394    /// they form the two-axis projection that the consumer in
1395    /// `tatara-pool-reconciler::return_policy::plan_return` matches
1396    /// against — `keeps_process` false ⇒ `DeleteAndRespawn`;
1397    /// `keeps_process && runs_reset_job` ⇒ `ResetThenFree`;
1398    /// `keeps_process && !runs_reset_job` ⇒ `KeepForInspection`. The
1399    /// pair is `(false, false) | (true, true) | (true, false)` —
1400    /// pinned injective by
1401    /// `return_policy_predicate_pair_is_injective`.
1402    pub const fn keeps_process(self) -> bool {
1403        match self {
1404            Self::Replace => false,
1405            Self::Reset | Self::Keep => true,
1406        }
1407    }
1408
1409    /// Does the policy run a typed `:reset` Job to wipe state in
1410    /// place? See `keeps_process` for the closed-match rationale +
1411    /// the predicate-pair contract.
1412    pub const fn runs_reset_job(self) -> bool {
1413        match self {
1414            Self::Reset => true,
1415            Self::Replace | Self::Keep => false,
1416        }
1417    }
1418}
1419
1420// `impl FromStr for ReturnPolicy` + `impl tatara_lisp::ClosedSet for
1421// ReturnPolicy` + `impl fmt::Display for ReturnPolicy` are generated by
1422// `#[derive(tatara_closed_set::DeriveClosedSet)]` on the enum declaration
1423// above. `label` delegates to the inherent `ReturnPolicy::as_str` via
1424// `#[closed_set(via = "as_str")]` so the
1425// `tatara-pool-reconciler::return_policy::plan_return` dispatch keeps
1426// reading the canonical PascalCase projection that matches the CRD
1427// `enum:` literal verbatim, while a generic `T: ClosedSet` consumer
1428// plugs in without knowing the enum lives in `tatara-process::pool`;
1429// Display delegates to the same inherent projection via
1430// `#[closed_set(display)]` so the `policy={policy}` diagnostic
1431// composition stays pinned on the closed-set algebra.
1432
1433// `pub struct UnknownReturnPolicy(pub String)` is generated by
1434// `#[derive(tatara_closed_set::DeriveClosedSet)]` + `#[closed_set(generate_unknown)]`
1435// on the enum declaration above. The auto-derived label `"return policy"`
1436// matches the prior hand-rolled `#[error("unknown return policy: {0}")]`
1437// verbatim. Symmetric to [`UnknownReplacementPolicy`],
1438// [`UnknownMemberState`], [`UnknownPoolPhase`],
1439// [`crate::lifetime::UnknownTeardownPolicy`],
1440// [`crate::boundary::UnknownConditionKind`], and
1441// [`crate::phase::UnknownPhase`].
1442
1443/// Routing selector — matches an `EphemeralAllocation`'s requestor
1444/// against pool-eligibility predicates.
1445#[derive(Clone, Debug, Default, Deserialize, Serialize, JsonSchema)]
1446#[serde(rename_all = "camelCase")]
1447pub struct PoolSelector {
1448    /// Glob-matched against `EphemeralAllocation.spec.requestor.repo`.
1449    /// Empty = match every repo.
1450    #[serde(default)]
1451    pub repos: Vec<String>,
1452
1453    /// Glob-matched against `EphemeralAllocation.spec.requestor.branch`.
1454    /// Empty = match every branch.
1455    #[serde(default)]
1456    pub branches: Vec<String>,
1457
1458    /// PR labels (all-must-match, AND semantics). Empty = no label
1459    /// requirement.
1460    #[serde(default)]
1461    pub pr_labels: Vec<String>,
1462
1463    /// Allocation `kind` strings this pool can serve (e.g., "github-pr",
1464    /// "manual", "ci-run"). Empty = any kind.
1465    #[serde(default)]
1466    pub kinds: Vec<String>,
1467}
1468
1469impl PoolSelector {
1470    /// Does this selector match the given allocation routing key?
1471    /// Pure: no side effects.
1472    pub fn matches(&self, key: &MatchKey<'_>) -> bool {
1473        glob_any(&self.repos, key.repo)
1474            && glob_any(&self.branches, key.branch)
1475            && labels_subset(&self.pr_labels, key.pr_labels)
1476            && kind_any(&self.kinds, key.kind)
1477    }
1478
1479    /// Specificity score — higher = more specific. Used by the
1480    /// reconciler to break ties between selectors that all match.
1481    pub fn specificity(&self) -> u32 {
1482        let mut score = 0;
1483        if !self.repos.is_empty() {
1484            score += 8;
1485        }
1486        if !self.branches.is_empty() {
1487            score += 4;
1488        }
1489        score += (self.pr_labels.len() as u32) * 2;
1490        if !self.kinds.is_empty() {
1491            score += 1;
1492        }
1493        score
1494    }
1495}
1496
1497/// Allocation routing key — what the reconciler matches against pool selectors.
1498#[derive(Clone, Copy, Debug)]
1499pub struct MatchKey<'a> {
1500    pub repo: &'a str,
1501    pub branch: &'a str,
1502    pub pr_labels: &'a [String],
1503    pub kind: &'a str,
1504}
1505
1506fn glob_any(patterns: &[String], value: &str) -> bool {
1507    if patterns.is_empty() {
1508        return true;
1509    }
1510    patterns.iter().any(|p| glob_match(p, value))
1511}
1512
1513fn kind_any(kinds: &[String], value: &str) -> bool {
1514    if kinds.is_empty() {
1515        return true;
1516    }
1517    kinds.iter().any(|k| k == value)
1518}
1519
1520fn labels_subset(required: &[String], present: &[String]) -> bool {
1521    required.iter().all(|r| present.iter().any(|p| p == r))
1522}
1523
1524/// Minimal glob: supports trailing `*` only (e.g., `"pleme-io/*"`,
1525/// `"release-*"`). Sufficient for repo/branch routing. Empty pattern
1526/// matches anything.
1527fn glob_match(pattern: &str, value: &str) -> bool {
1528    if pattern.is_empty() {
1529        return true;
1530    }
1531    if let Some(prefix) = pattern.strip_suffix('*') {
1532        value.starts_with(prefix)
1533    } else {
1534        pattern == value
1535    }
1536}
1537
1538#[cfg(test)]
1539mod tests {
1540    use super::*;
1541    // The closed-set tests below call `T::from_str(bad)` via the
1542    // derive-generated `FromStr` impls — bring the trait into scope at
1543    // the test module so the lib body doesn't carry an otherwise-unused
1544    // `use std::str::FromStr;` at the file head.
1545    use std::str::FromStr;
1546
1547    #[test]
1548    fn glob_trailing_star_matches_prefix() {
1549        assert!(glob_match("pleme-io/*", "pleme-io/demo-app"));
1550        assert!(!glob_match("pleme-io/*", "drzln/dotfiles"));
1551        assert!(glob_match("release-*", "release-2026-05"));
1552        assert!(!glob_match("release-*", "main"));
1553        assert!(glob_match("main", "main"));
1554        assert!(!glob_match("main", "develop"));
1555    }
1556
1557    #[test]
1558    fn empty_selector_matches_anything() {
1559        let s = PoolSelector::default();
1560        assert!(s.matches(&MatchKey {
1561            repo: "any/repo",
1562            branch: "any-branch",
1563            pr_labels: &[],
1564            kind: "any",
1565        }));
1566    }
1567
1568    #[test]
1569    fn repo_glob_filters_match_key() {
1570        let s = PoolSelector {
1571            repos: vec!["pleme-io/demo-*".into()],
1572            ..Default::default()
1573        };
1574        assert!(s.matches(&MatchKey {
1575            repo: "pleme-io/demo-app",
1576            branch: "x",
1577            pr_labels: &[],
1578            kind: "y",
1579        }));
1580        assert!(!s.matches(&MatchKey {
1581            repo: "pleme-io/other-repo",
1582            branch: "x",
1583            pr_labels: &[],
1584            kind: "y",
1585        }));
1586    }
1587
1588    #[test]
1589    fn pr_labels_require_all() {
1590        let s = PoolSelector {
1591            pr_labels: vec!["needs-ephemeral".into(), "integration".into()],
1592            ..Default::default()
1593        };
1594        // Both labels present → match.
1595        assert!(s.matches(&MatchKey {
1596            repo: "x",
1597            branch: "y",
1598            pr_labels: &[
1599                "needs-ephemeral".into(),
1600                "integration".into(),
1601                "extra".into()
1602            ],
1603            kind: "z",
1604        }));
1605        // One label missing → no match.
1606        assert!(!s.matches(&MatchKey {
1607            repo: "x",
1608            branch: "y",
1609            pr_labels: &["needs-ephemeral".into()],
1610            kind: "z",
1611        }));
1612    }
1613
1614    #[test]
1615    fn specificity_ranks_more_constrained_higher() {
1616        let general = PoolSelector::default();
1617        let specific = PoolSelector {
1618            repos: vec!["pleme-io/*".into()],
1619            branches: vec!["main".into()],
1620            pr_labels: vec!["needs-ephemeral".into()],
1621            kinds: vec!["github-pr".into()],
1622        };
1623        assert!(specific.specificity() > general.specificity());
1624    }
1625
1626    #[test]
1627    fn return_policy_defaults_to_replace() {
1628        assert_eq!(ReturnPolicy::default(), ReturnPolicy::Replace);
1629    }
1630
1631    #[test]
1632    fn pool_phase_defaults_to_initializing() {
1633        assert_eq!(PoolPhase::default(), PoolPhase::Initializing);
1634    }
1635
1636    // ── closed-set algebra contracts for ReplacementPolicy
1637    //    (ALL × as_str × FromStr × predicate-pair) ────────────────────
1638
1639    /// Structural well-formedness of [`ReplacementPolicy`] as a
1640    /// [`tatara_lisp::ClosedSet`] implementor — the workspace-wide
1641    /// testkit lift that pins all three structural invariants (`ALL`
1642    /// is non-empty, every variant round-trips through
1643    /// `label ↔ parse_label`, labels are pairwise distinct, `""` is
1644    /// outside the closed set) at ONE call site. Replaces the hand-
1645    /// derived `replacement_policy_all_is_unique_and_complete` +
1646    /// `replacement_policy_roundtrip_via_as_str` + the empty-input arm
1647    /// of `unknown_replacement_policy_errors`. `FromStr` delegates to
1648    /// `<Self as tatara_closed_set::ClosedSet>::parse_label`, so this helper
1649    /// exercises the same code path the pool reconciler hits when
1650    /// parsing a CRD `enum:`-validated value back to the typed policy.
1651    #[test]
1652    fn replacement_policy_is_well_formed_closed_set() {
1653        tatara_closed_set::assert_closed_set_well_formed::<ReplacementPolicy>();
1654    }
1655
1656    /// CANONICAL-KEY CONTRACT: `as_str` matches serde's PascalCase
1657    /// output verbatim for every variant. A future variant rename (or
1658    /// an `as_str` arm typo) lands here at one site, instead of
1659    /// drifting between the typed surface, the CRD enum, and the
1660    /// YAML wire format.
1661    #[test]
1662    fn replacement_policy_as_str_matches_serde() {
1663        crate::tagged_union::assert_label_matches_serde_serialization::<ReplacementPolicy>();
1664    }
1665
1666    /// The Display impl IS `as_str` — pinning this lets future callers
1667    /// reach for either projection without drift. The operator-facing
1668    /// "policy={policy}" diagnostic in `tatara-pool-reconciler::desired`
1669    /// composes through Display rather than through a hard-coded
1670    /// variant string.
1671    #[test]
1672    fn replacement_policy_display_matches_as_str() {
1673        crate::tagged_union::assert_display_matches_label::<ReplacementPolicy>();
1674    }
1675
1676    /// `FromStr` rejects strings that aren't in the canonical
1677    /// projection — lowercased / typo / cross-axis-leaked — and the
1678    /// error echoes the input verbatim so the operator-facing
1679    /// diagnostic carries the offending value, not a normalized form.
1680    /// The empty-input arm is pinned by
1681    /// [`replacement_policy_is_well_formed_closed_set`] via the
1682    /// `tatara_lisp::ClosedSet` testkit; the cases here pin the
1683    /// verbatim-echo contract on the [`UnknownReplacementPolicy`]
1684    /// newtype, which the trait's `make_unknown` can't see.
1685    #[test]
1686    fn unknown_replacement_policy_errors() {
1687        for bad in [
1688            "replaceimmediate",
1689            "PAUSEPOOL",
1690            "Replace-Immediate",
1691            "hold_failed",
1692            "Pause",
1693            "Reset",
1694        ] {
1695            let err = ReplacementPolicy::from_str(bad).unwrap_err();
1696            assert_eq!(err.0, bad, "error payload should echo input verbatim");
1697        }
1698    }
1699
1700    /// TRUTH-TABLE CONTRACT: the predicate pair agrees with the
1701    /// documented per-variant on-failure behavior.
1702    #[test]
1703    fn replacement_policy_predicate_truth_tables() {
1704        assert!(ReplacementPolicy::ReplaceImmediate.replaces_failed());
1705        assert!(!ReplacementPolicy::ReplaceImmediate.pauses_on_failure());
1706
1707        assert!(!ReplacementPolicy::HoldFailed.replaces_failed());
1708        assert!(!ReplacementPolicy::HoldFailed.pauses_on_failure());
1709
1710        assert!(!ReplacementPolicy::PausePool.replaces_failed());
1711        assert!(ReplacementPolicy::PausePool.pauses_on_failure());
1712    }
1713
1714    /// DISJOINTNESS CONTRACT: no variant returns true from BOTH
1715    /// predicates simultaneously — the two on-failure actions
1716    /// (reap-each-failed vs pause-whole-pool) are mutually exclusive.
1717    /// A future `ReplacementPolicy::PauseAndReap` that returned true
1718    /// from both would FAIL here, forcing the author to either pick
1719    /// one bucket or extend the consumer dispatch site in
1720    /// `tatara-pool-reconciler::desired::PoolConvergence::decide`
1721    /// deliberately rather than silently double-firing both branches.
1722    #[test]
1723    fn replacement_policy_predicates_are_disjoint() {
1724        for policy in ReplacementPolicy::ALL {
1725            assert!(
1726                !(policy.replaces_failed() && policy.pauses_on_failure()),
1727                "{policy:?} returns true from both replaces_failed and pauses_on_failure",
1728            );
1729        }
1730    }
1731
1732    /// INJECTIVITY CONTRACT: the pair `(replaces_failed,
1733    /// pauses_on_failure)` is injective across `ALL`. Each variant
1734    /// projects to its own `(bool, bool)` bucket: `(true, false)` =
1735    /// reap; `(false, false)` = hold; `(false, true)` = pause. Pairing
1736    /// this with the disjointness contract above forces a future
1737    /// variant to land in a fresh `(replaces_failed,
1738    /// pauses_on_failure)` bucket — or the author extends the consumer
1739    /// dispatch in `tatara-pool-reconciler::desired::PoolConvergence`
1740    /// to recognize the new projection bucket.
1741    #[test]
1742    fn replacement_policy_predicate_pair_is_injective() {
1743        let projections: Vec<(bool, bool)> = ReplacementPolicy::ALL
1744            .into_iter()
1745            .map(|p| (p.replaces_failed(), p.pauses_on_failure()))
1746            .collect();
1747        let unique: std::collections::HashSet<_> = projections.iter().copied().collect();
1748        assert_eq!(
1749            projections.len(),
1750            unique.len(),
1751            "predicate pair projection is not injective: {projections:?}",
1752        );
1753    }
1754
1755    /// DEFAULT-AGREEMENT CONTRACT: `ReplacementPolicy::default()`
1756    /// returns the variant tagged `#[default]` in the enum, AND that
1757    /// variant reaps (the production-safe behavior). A future #[default]
1758    /// rename without flipping the predicates fails here.
1759    #[test]
1760    fn replacement_policy_default_replaces_failed() {
1761        let d = ReplacementPolicy::default();
1762        assert_eq!(d, ReplacementPolicy::ReplaceImmediate);
1763        assert!(d.replaces_failed());
1764        assert!(!d.pauses_on_failure());
1765    }
1766
1767    #[test]
1768    fn kinds_filter_to_known_set() {
1769        let s = PoolSelector {
1770            kinds: vec!["github-pr".into(), "manual".into()],
1771            ..Default::default()
1772        };
1773        assert!(s.matches(&MatchKey {
1774            repo: "x",
1775            branch: "y",
1776            pr_labels: &[],
1777            kind: "github-pr",
1778        }));
1779        assert!(!s.matches(&MatchKey {
1780            repo: "x",
1781            branch: "y",
1782            pr_labels: &[],
1783            kind: "scheduled",
1784        }));
1785    }
1786
1787    // ── closed-set algebra contracts for ReturnPolicy
1788    //    (ALL × as_str × FromStr × predicate-pair) ────────────────────
1789
1790    /// Structural well-formedness of [`ReturnPolicy`] as a
1791    /// [`tatara_lisp::ClosedSet`] implementor — testkit lift
1792    /// symmetric to [`replacement_policy_is_well_formed_closed_set`]
1793    /// above.
1794    #[test]
1795    fn return_policy_is_well_formed_closed_set() {
1796        tatara_closed_set::assert_closed_set_well_formed::<ReturnPolicy>();
1797    }
1798
1799    /// CANONICAL-KEY CONTRACT: `as_str` matches serde's PascalCase
1800    /// output verbatim for every variant. A future variant rename (or
1801    /// an `as_str` arm typo) lands here at one site, instead of
1802    /// drifting between the typed surface, the CRD enum, and the
1803    /// YAML wire format.
1804    #[test]
1805    fn return_policy_as_str_matches_serde() {
1806        crate::tagged_union::assert_label_matches_serde_serialization::<ReturnPolicy>();
1807    }
1808
1809    /// The Display impl IS `as_str` — pinning this lets future callers
1810    /// reach for either projection without drift, mirroring the
1811    /// `ReplacementPolicy` discipline.
1812    #[test]
1813    fn return_policy_display_matches_as_str() {
1814        crate::tagged_union::assert_display_matches_label::<ReturnPolicy>();
1815    }
1816
1817    /// `FromStr` rejects strings that aren't in the canonical
1818    /// projection — lowercased / typo / cross-axis-leaked — and the
1819    /// error echoes the input verbatim so the operator-facing
1820    /// diagnostic carries the offending value, not a normalized form.
1821    /// The empty-input arm is pinned by
1822    /// [`return_policy_is_well_formed_closed_set`] via the
1823    /// `tatara_lisp::ClosedSet` testkit.
1824    #[test]
1825    fn unknown_return_policy_errors() {
1826        for bad in [
1827            "replace",
1828            "RESET",
1829            "Re-place",
1830            "keep_for_inspection",
1831            "DeleteAndRespawn",
1832            "ReplaceImmediate",
1833        ] {
1834            let err = ReturnPolicy::from_str(bad).unwrap_err();
1835            assert_eq!(err.0, bad, "error payload should echo input verbatim");
1836        }
1837    }
1838
1839    /// TRUTH-TABLE CONTRACT: the predicate pair agrees with the
1840    /// documented per-variant on-release behavior.
1841    #[test]
1842    fn return_policy_predicate_truth_tables() {
1843        assert!(!ReturnPolicy::Replace.keeps_process());
1844        assert!(!ReturnPolicy::Replace.runs_reset_job());
1845
1846        assert!(ReturnPolicy::Reset.keeps_process());
1847        assert!(ReturnPolicy::Reset.runs_reset_job());
1848
1849        assert!(ReturnPolicy::Keep.keeps_process());
1850        assert!(!ReturnPolicy::Keep.runs_reset_job());
1851    }
1852
1853    /// IMPLICATION CONTRACT: `runs_reset_job` implies `keeps_process`.
1854    /// You cannot run a typed `:reset` Job against a Process you've
1855    /// just deleted; the impossible bucket `(false, true)` must stay
1856    /// empty. A future variant returning true from `runs_reset_job`
1857    /// while returning false from `keeps_process` fails here, which
1858    /// forces the author to either flip `keeps_process` to true or
1859    /// extend the consumer dispatch site in
1860    /// `tatara-pool-reconciler::return_policy::plan_return`
1861    /// deliberately rather than letting an impossible state slip in.
1862    #[test]
1863    fn return_policy_reset_implies_keeps_process() {
1864        for policy in ReturnPolicy::ALL {
1865            if policy.runs_reset_job() {
1866                assert!(
1867                    policy.keeps_process(),
1868                    "{policy:?} runs a reset job but does not keep the process",
1869                );
1870            }
1871        }
1872    }
1873
1874    /// INJECTIVITY CONTRACT: the pair `(keeps_process, runs_reset_job)`
1875    /// is injective across `ALL`. Each variant projects to its own
1876    /// `(bool, bool)` bucket: `(false, false)` = delete + respawn;
1877    /// `(true, true)` = reset-in-place; `(true, false)` = keep for
1878    /// inspection. Pairing this with the implication contract above
1879    /// forces a future variant to land in a fresh
1880    /// `(keeps_process, runs_reset_job)` bucket — or the author
1881    /// extends the consumer dispatch in
1882    /// `tatara-pool-reconciler::return_policy::plan_return` to
1883    /// recognize the new projection bucket.
1884    #[test]
1885    fn return_policy_predicate_pair_is_injective() {
1886        let projections: Vec<(bool, bool)> = ReturnPolicy::ALL
1887            .into_iter()
1888            .map(|p| (p.keeps_process(), p.runs_reset_job()))
1889            .collect();
1890        let unique: std::collections::HashSet<_> = projections.iter().copied().collect();
1891        assert_eq!(
1892            projections.len(),
1893            unique.len(),
1894            "predicate pair projection is not injective: {projections:?}",
1895        );
1896    }
1897
1898    /// DEFAULT-AGREEMENT CONTRACT: `ReturnPolicy::default()` returns
1899    /// the variant tagged `#[default]` in the enum, AND that variant
1900    /// is the safe "tear down + respawn" behavior — neither keeps the
1901    /// process nor runs a reset Job. A future `#[default]` rename
1902    /// without flipping the predicates fails here.
1903    #[test]
1904    fn return_policy_default_is_replace_and_neither_predicate_fires() {
1905        let d = ReturnPolicy::default();
1906        assert_eq!(d, ReturnPolicy::Replace);
1907        assert!(!d.keeps_process());
1908        assert!(!d.runs_reset_job());
1909    }
1910
1911    // ── closed-set algebra contracts for MemberState
1912    //    (ALL × as_str × FromStr × predicate pair) ────────────────────
1913
1914    /// Structural well-formedness of [`MemberState`] as a
1915    /// [`tatara_lisp::ClosedSet`] implementor — testkit lift
1916    /// symmetric to [`replacement_policy_is_well_formed_closed_set`]
1917    /// and [`return_policy_is_well_formed_closed_set`] above.
1918    #[test]
1919    fn member_state_is_well_formed_closed_set() {
1920        tatara_closed_set::assert_closed_set_well_formed::<MemberState>();
1921    }
1922
1923    /// CANONICAL-KEY CONTRACT: `as_str` matches serde's PascalCase
1924    /// output verbatim for every variant. A future variant rename (or
1925    /// an `as_str` arm typo) lands here at one site, instead of
1926    /// drifting between the typed surface, the CRD enum, and the YAML
1927    /// wire format the pool reconciler stamps on
1928    /// `status.members[].state`.
1929    #[test]
1930    fn member_state_as_str_matches_serde() {
1931        crate::tagged_union::assert_label_matches_serde_serialization::<MemberState>();
1932    }
1933
1934    /// The Display impl IS `as_str` — pinning this lets future callers
1935    /// reach for either projection without drift. Any operator-facing
1936    /// "state={state}" diagnostic that composes through Display
1937    /// inherits the canonical wire-format string automatically.
1938    #[test]
1939    fn member_state_display_matches_as_str() {
1940        crate::tagged_union::assert_display_matches_label::<MemberState>();
1941    }
1942
1943    /// `FromStr` rejects strings that aren't in the canonical
1944    /// projection — lowercased / typo / cross-axis-leaked — and
1945    /// the error echoes the input verbatim so the operator-facing
1946    /// diagnostic carries the offending value, not a normalized form.
1947    /// The empty-input arm is pinned by
1948    /// [`member_state_is_well_formed_closed_set`] via the
1949    /// `tatara_lisp::ClosedSet` testkit. The cross-axis leak cases
1950    /// pin the closed-set REJECTION contract that the trait can't see:
1951    /// `"ReplaceImmediate"`, `"Reset"`, and `"Attested"` are valid
1952    /// labels for sibling enums (`ReplacementPolicy`, `ReturnPolicy`,
1953    /// `ProcessPhase`) but MUST reject here, because the codomains
1954    /// are disjoint.
1955    #[test]
1956    fn unknown_member_state_errors() {
1957        for bad in [
1958            "free",
1959            "SPAWNING",
1960            "Free-State",
1961            "allocated_now",
1962            "ReplaceImmediate", // ReplacementPolicy-axis leak
1963            "Reset",            // ReturnPolicy-axis leak
1964            "Attested",         // ProcessPhase-axis leak
1965        ] {
1966            let err = MemberState::from_str(bad).unwrap_err();
1967            assert_eq!(err.0, bad, "error payload should echo input verbatim");
1968        }
1969    }
1970
1971    /// TRUTH-TABLE CONTRACT: the predicate pair agrees with the
1972    /// documented per-variant lifecycle role. The pool reconciler's
1973    /// `pool_phase_from_members` supply calc collapses
1974    /// `count_state(Free) + count_state(Spawning)` into one
1975    /// `counts_toward_supply` filter; this table pins the per-variant
1976    /// projection that consumer depends on.
1977    #[test]
1978    fn member_state_predicate_truth_tables() {
1979        assert!(!MemberState::Spawning.is_failed());
1980        assert!(MemberState::Spawning.counts_toward_supply());
1981
1982        assert!(!MemberState::Free.is_failed());
1983        assert!(MemberState::Free.counts_toward_supply());
1984
1985        assert!(!MemberState::Allocated.is_failed());
1986        assert!(!MemberState::Allocated.counts_toward_supply());
1987
1988        assert!(!MemberState::Returning.is_failed());
1989        assert!(!MemberState::Returning.counts_toward_supply());
1990
1991        assert!(MemberState::Failed.is_failed());
1992        assert!(!MemberState::Failed.counts_toward_supply());
1993    }
1994
1995    /// DISJOINTNESS CONTRACT: no variant returns true from BOTH
1996    /// `is_failed` and `counts_toward_supply` simultaneously — a
1997    /// failed member can never be counted as available capacity. A
1998    /// future variant that returned true from both would FAIL here,
1999    /// forcing the author to either drop it from supply, or extend
2000    /// the consumer's bucketing in
2001    /// `tatara-pool-reconciler::controller_pool::pool_phase_from_members`
2002    /// deliberately rather than silently inflating the pool's supply
2003    /// count with failed slots.
2004    #[test]
2005    fn member_state_failed_implies_no_supply() {
2006        for state in MemberState::ALL {
2007            assert!(
2008                !(state.is_failed() && state.counts_toward_supply()),
2009                "{state:?} returns true from both is_failed and counts_toward_supply — \
2010                 a failed member can never be counted as available pool capacity",
2011            );
2012        }
2013    }
2014
2015    /// COVERAGE CONTRACT: every variant lands somewhere — either
2016    /// in supply, or as a failed slot, or as an in-use bucket
2017    /// (`Allocated | Returning`). A future variant that returns
2018    /// `false` from `counts_toward_supply` AND `false` from
2019    /// `is_failed` is fine *iff* it represents an in-use slot; this
2020    /// test pins the existing variants in their declared buckets so
2021    /// the consumer-side dispatch in
2022    /// `tatara-pool-reconciler::pool_decide::decide_pool_reconcile`
2023    /// stays grounded.
2024    #[test]
2025    fn member_state_buckets_cover_every_variant() {
2026        let mut supply = 0u32;
2027        let mut failed = 0u32;
2028        let mut in_use = 0u32;
2029        for state in MemberState::ALL {
2030            match (state.is_failed(), state.counts_toward_supply()) {
2031                (true, false) => failed += 1,
2032                (false, true) => supply += 1,
2033                (false, false) => in_use += 1,
2034                (true, true) => panic!("disjointness already pins this empty for {state:?}"),
2035            }
2036        }
2037        assert_eq!(supply, 2, "supply bucket: Free + Spawning");
2038        assert_eq!(failed, 1, "failed bucket: Failed");
2039        assert_eq!(in_use, 2, "in-use bucket: Allocated + Returning");
2040        assert_eq!(supply + failed + in_use, MemberState::ALL.len() as u32);
2041    }
2042
2043    // ── closed-set algebra contracts for PoolPhase
2044    //    (ALL × as_str × FromStr × predicate pair) ────────────────────
2045
2046    /// Structural well-formedness of [`PoolPhase`] as a
2047    /// [`tatara_lisp::ClosedSet`] implementor — testkit lift
2048    /// symmetric to [`member_state_is_well_formed_closed_set`] above.
2049    #[test]
2050    fn pool_phase_is_well_formed_closed_set() {
2051        tatara_closed_set::assert_closed_set_well_formed::<PoolPhase>();
2052    }
2053
2054    /// CANONICAL-KEY CONTRACT: `as_str` matches serde's PascalCase
2055    /// output verbatim for every variant. A future variant rename (or
2056    /// an `as_str` arm typo) lands here at one site, instead of
2057    /// drifting between the typed surface, the CRD enum, and the YAML
2058    /// wire format the pool reconciler stamps on `status.phase`.
2059    #[test]
2060    fn pool_phase_as_str_matches_serde() {
2061        crate::tagged_union::assert_label_matches_serde_serialization::<PoolPhase>();
2062    }
2063
2064    /// The Display impl IS `as_str` — pinning this lets future callers
2065    /// reach for either projection without drift. Any operator-facing
2066    /// "phase={phase}" diagnostic that composes through Display
2067    /// inherits the canonical wire-format string automatically.
2068    #[test]
2069    fn pool_phase_display_matches_as_str() {
2070        crate::tagged_union::assert_display_matches_label::<PoolPhase>();
2071    }
2072
2073    /// `FromStr` rejects strings that aren't in the canonical
2074    /// projection — lowercased / typo / cross-axis-leaked — and
2075    /// the error echoes the input verbatim so the operator-facing
2076    /// diagnostic carries the offending value, not a normalized form.
2077    /// The empty-input arm is pinned by
2078    /// [`pool_phase_is_well_formed_closed_set`] via the
2079    /// `tatara_lisp::ClosedSet` testkit. The cross-axis leak cases
2080    /// (`"Free"`, `"Replace"`, `"Attested"`, `"HoldFailed"`) pin the
2081    /// closed-set REJECTION contract that the trait can't see — those
2082    /// are valid sibling-axis labels but MUST reject here.
2083    #[test]
2084    fn unknown_pool_phase_errors() {
2085        for bad in [
2086            "steady",
2087            "SCALINGUP",
2088            "Scaling-Up",
2089            "scaling_down",
2090            "Free",       // MemberState-axis leak
2091            "Replace",    // ReturnPolicy-axis leak
2092            "Attested",   // ProcessPhase-axis leak
2093            "HoldFailed", // ReplacementPolicy-axis leak
2094        ] {
2095            let err = PoolPhase::from_str(bad).unwrap_err();
2096            assert_eq!(err.0, bad, "error payload should echo input verbatim");
2097        }
2098    }
2099
2100    /// TRUTH-TABLE CONTRACT: the predicate pair agrees with the
2101    /// documented per-variant lifecycle role. Pinning this table at
2102    /// one site means any future status-aggregator surface
2103    /// (`feira pool list --healthy`, the SSE filter, the desired-loop
2104    /// heartbeat short-circuit) reads the same projection that the
2105    /// reconciler writes.
2106    #[test]
2107    fn pool_phase_predicate_truth_tables() {
2108        assert!(!PoolPhase::Initializing.is_steady());
2109        assert!(!PoolPhase::Initializing.is_terminal());
2110
2111        assert!(PoolPhase::Steady.is_steady());
2112        assert!(!PoolPhase::Steady.is_terminal());
2113
2114        assert!(!PoolPhase::ScalingUp.is_steady());
2115        assert!(!PoolPhase::ScalingUp.is_terminal());
2116
2117        assert!(!PoolPhase::ScalingDown.is_steady());
2118        assert!(!PoolPhase::ScalingDown.is_terminal());
2119
2120        assert!(!PoolPhase::Degraded.is_steady());
2121        assert!(!PoolPhase::Degraded.is_terminal());
2122
2123        assert!(!PoolPhase::Draining.is_steady());
2124        assert!(PoolPhase::Draining.is_terminal());
2125    }
2126
2127    /// DISJOINTNESS CONTRACT: no variant returns true from BOTH
2128    /// `is_steady` and `is_terminal` simultaneously — a draining pool
2129    /// is by definition transitioning OUT, not the goal converged
2130    /// state. A future variant that returned true from both would
2131    /// FAIL here, forcing the author to either pick one bucket or
2132    /// extend the consumer dispatch sites (status aggregators,
2133    /// heartbeat short-circuit) deliberately rather than silently
2134    /// double-firing both branches.
2135    #[test]
2136    fn pool_phase_steady_excludes_terminal() {
2137        for phase in PoolPhase::ALL {
2138            assert!(
2139                !(phase.is_steady() && phase.is_terminal()),
2140                "{phase:?} returns true from both is_steady and is_terminal — \
2141                 a draining pool is by definition not the converged goal state",
2142            );
2143        }
2144    }
2145
2146    /// COVERAGE CONTRACT: every variant lands somewhere — either the
2147    /// converged goal (`Steady`), the absorbing exit (`Draining`),
2148    /// or the transient bucket (`Initializing | ScalingUp |
2149    /// ScalingDown | Degraded` — pool is in motion toward desired).
2150    /// A future variant that returns `false` from BOTH predicates is
2151    /// fine *iff* it represents an in-motion state; this test pins
2152    /// the existing variants in their declared buckets so the
2153    /// projection consumers stay grounded.
2154    #[test]
2155    fn pool_phase_buckets_cover_every_variant() {
2156        let mut converged = 0u32;
2157        let mut terminal = 0u32;
2158        let mut transient = 0u32;
2159        for phase in PoolPhase::ALL {
2160            match (phase.is_steady(), phase.is_terminal()) {
2161                (true, false) => converged += 1,
2162                (false, true) => terminal += 1,
2163                (false, false) => transient += 1,
2164                (true, true) => panic!("disjointness already pins this empty for {phase:?}"),
2165            }
2166        }
2167        assert_eq!(converged, 1, "converged bucket: Steady");
2168        assert_eq!(terminal, 1, "terminal bucket: Draining");
2169        assert_eq!(
2170            transient, 4,
2171            "transient bucket: Initializing + ScalingUp + ScalingDown + Degraded"
2172        );
2173        assert_eq!(
2174            converged + terminal + transient,
2175            PoolPhase::ALL.len() as u32
2176        );
2177    }
2178
2179    /// DEFAULT-AGREEMENT CONTRACT: `PoolPhase::default()` returns the
2180    /// variant a freshly-admitted pool should land in — `Initializing`
2181    /// — AND that variant is neither steady (no members yet) nor
2182    /// terminal (not deletion-stamped). A future `Default` rename
2183    /// without flipping the predicates fails here.
2184    #[test]
2185    fn pool_phase_default_is_initializing_in_transient_bucket() {
2186        let d = PoolPhase::default();
2187        assert_eq!(d, PoolPhase::Initializing);
2188        assert!(!d.is_steady());
2189        assert!(!d.is_terminal());
2190    }
2191
2192    // ─────────────────────────────────────────────────────────────────
2193    // `EphemeralPool::name_or_empty` — borrow-form metadata-projection
2194    // primitive on the `metadata.name` axis. Pins the missing-slot
2195    // corner, the populated-slot corner, the pre-lift chain-shape
2196    // parity, and the pure-projection discipline that the two
2197    // `tatara-pool-reconciler` consumers routed onto the primitive
2198    // depend on. See the primitive's doc-comment for the full
2199    // migration rationale.
2200    // ─────────────────────────────────────────────────────────────────
2201
2202    fn empty_template() -> EphemeralSpec {
2203        EphemeralSpec {
2204            aplicacao: crate::intent::AplicacaoIntent {
2205                chart_ref: "oci://x".into(),
2206                version: "1".into(),
2207                profile: String::new(),
2208                values_overlay: serde_json::Value::Null,
2209                release_name: None,
2210                target_namespace: None,
2211                install_timeout: None,
2212            },
2213            ttl: "1h".into(),
2214            teardown: crate::lifetime::TeardownPolicy::Always,
2215            max_concurrent: 0,
2216            postconditions: vec![],
2217            preconditions: vec![],
2218            verify_timeout: None,
2219            classification: None,
2220            parent: None,
2221            exports: vec![],
2222            routing: None,
2223        }
2224    }
2225
2226    fn pool_spec() -> PoolSpec {
2227        PoolSpec {
2228            desired_size: 1,
2229            min_size: 0,
2230            max_size: 0,
2231            return_policy: ReturnPolicy::Replace,
2232            selector: PoolSelector::default(),
2233            template: empty_template(),
2234            free_ttl: "24h".into(),
2235            max_allocation_ttl: "4h".into(),
2236            desired: 0,
2237            replacement_policy: ReplacementPolicy::default(),
2238            stable_name_claim: false,
2239        }
2240    }
2241
2242    fn pool_named(name: &str) -> EphemeralPool {
2243        EphemeralPool::new(name, pool_spec())
2244    }
2245
2246    fn pool_unnamed() -> EphemeralPool {
2247        let mut p = EphemeralPool::new("scratch", pool_spec());
2248        p.metadata.name = None;
2249        p
2250    }
2251
2252    #[test]
2253    fn name_or_empty_returns_empty_string_when_metadata_name_is_none() {
2254        let p = pool_unnamed();
2255        assert!(p.metadata.name.is_none(), "fixture invariant");
2256        assert_eq!(p.name_or_empty(), "");
2257    }
2258
2259    #[test]
2260    fn name_or_empty_returns_populated_slot_verbatim() {
2261        let p = pool_named("attest-pool");
2262        assert_eq!(p.name_or_empty(), "attest-pool");
2263    }
2264
2265    #[test]
2266    fn name_or_empty_returns_empty_string_when_slot_is_explicitly_empty_string() {
2267        // Corner between `None` (missing slot) and `Some(String::new())`
2268        // (populated slot containing the empty string): the primitive
2269        // MUST fold both to the same `""` byte-shape so a downstream
2270        // `HashMap<String,_>::get(name)` / `str::cmp` sees ONE
2271        // "unnamed pool" bucket regardless of which shape the K8s API
2272        // server materialized. This is byte-identical to what the
2273        // pre-lift `.as_deref().unwrap_or("")` chain produced.
2274        let mut p = pool_named("scratch");
2275        p.metadata.name = Some(String::new());
2276        assert_eq!(p.name_or_empty(), "");
2277    }
2278
2279    #[test]
2280    fn name_or_empty_is_a_pure_projection() {
2281        // Consecutive calls return byte-identical slices — no cached
2282        // state, no mutation on the `EphemeralPool` between calls.
2283        // Guards against a future refactor that plants a cache field
2284        // and drifts one caller from another silently.
2285        let p = pool_named("router-pool");
2286        assert_eq!(p.name_or_empty(), p.name_or_empty());
2287        assert_eq!(p.name_or_empty(), "router-pool");
2288        assert_eq!(p.name_or_empty(), "router-pool");
2289    }
2290
2291    #[test]
2292    fn name_or_empty_matches_pre_lift_chain_verbatim() {
2293        // Byte-identical parity with the two hand-authored
2294        // `.metadata.name.as_deref().unwrap_or("")` chains the
2295        // primitive replaces in `tatara-pool-reconciler::router` and
2296        // `tatara-pool-reconciler::controller_allocation`. Runs across
2297        // the FULL corner set of the metadata.name slot: absent,
2298        // present-with-value, present-with-empty-string.
2299        let cases: [(Option<String>, &str); 3] = [
2300            (None, ""),
2301            (Some("attest-pool".into()), "attest-pool"),
2302            (Some(String::new()), ""),
2303        ];
2304        for (slot, expected) in cases {
2305            let mut p = pool_named("scratch");
2306            p.metadata.name = slot.clone();
2307            let pre_lift = p.metadata.name.as_deref().unwrap_or("");
2308            assert_eq!(pre_lift, expected, "pre-lift chain sanity");
2309            assert_eq!(p.name_or_empty(), pre_lift);
2310            assert_eq!(p.name_or_empty(), expected);
2311        }
2312    }
2313
2314    #[test]
2315    fn name_or_empty_borrows_from_metadata_name_slot() {
2316        // The returned `&str` is tied to the `EphemeralPool`'s
2317        // lifetime — the caller can compare / hash / index without
2318        // allocating. This is the load-bearing property that lets
2319        // the `HashMap<String, _>::get(pool.name_or_empty())` closure
2320        // in `controller_allocation::reconcile_inner` skip cloning.
2321        let p = pool_named("attest-pool");
2322        let s: &str = p.name_or_empty();
2323        assert_eq!(s.as_ptr(), p.metadata.name.as_deref().unwrap().as_ptr());
2324    }
2325
2326    // ─── EphemeralPool::owned_name_or_empty substrate pins ────────────
2327    //
2328    // The owned-form peer of the borrow-form `name_or_empty` primitive
2329    // above. Sibling to the sister-CRD primitive
2330    // `crate::crd::Process::owned_name_or_empty` (owned + empty sentinel
2331    // on `Process::metadata.name`) — the four primitives now partition
2332    // the (borrow × owned) × (name × uid) corner of the metadata-slot
2333    // family on identical missing-slot semantics across BOTH tatara-
2334    // process CRDs (`Process::uid_or_empty` + `Process::owned_name_or_empty`
2335    // + `EphemeralPool::name_or_empty` + this method). Fail-before-pass-
2336    // after granularity: `owned_name_or_empty` did not exist on the pool
2337    // CRD pre-lift; the compiler cannot resolve the name until the impl
2338    // block above is in place, so a rollback of the primitive breaks
2339    // this whole module.
2340    #[test]
2341    fn owned_name_or_empty_returns_empty_string_when_metadata_name_is_none() {
2342        let p = pool_unnamed();
2343        assert!(p.metadata.name.is_none(), "fixture invariant");
2344        assert_eq!(p.owned_name_or_empty(), String::new());
2345    }
2346
2347    #[test]
2348    fn owned_name_or_empty_returns_owned_string_when_slot_is_populated() {
2349        let p = pool_named("attest-pool");
2350        assert_eq!(p.owned_name_or_empty(), "attest-pool");
2351    }
2352
2353    #[test]
2354    fn owned_name_or_empty_returns_empty_string_when_slot_is_explicitly_empty_string() {
2355        // Corner between `None` (missing slot) and `Some(String::new())`
2356        // (populated slot containing the empty string): the primitive
2357        // MUST fold both to the same `""` byte-shape so a downstream
2358        // `HashMap<String,_>::get(name)` sees ONE "unnamed pool" bucket
2359        // regardless of which shape the K8s API server materialized.
2360        // Byte-identical to what the pre-lift `.clone().unwrap_or_default()`
2361        // chain produced.
2362        let mut p = pool_named("scratch");
2363        p.metadata.name = Some(String::new());
2364        assert_eq!(p.owned_name_or_empty(), String::new());
2365        assert!(p.owned_name_or_empty().is_empty());
2366    }
2367
2368    #[test]
2369    fn owned_name_or_empty_is_a_pure_projection() {
2370        // Consecutive calls return byte-identical Strings — no cached
2371        // state, no mutation on the `EphemeralPool` between calls.
2372        // Guards against a future refactor that plants a cache field
2373        // and drifts one caller from another silently.
2374        let p = pool_named("router-pool");
2375        assert_eq!(p.owned_name_or_empty(), p.owned_name_or_empty());
2376        assert_eq!(p.owned_name_or_empty(), "router-pool");
2377        assert_eq!(p.owned_name_or_empty(), "router-pool");
2378    }
2379
2380    #[test]
2381    fn owned_name_or_empty_matches_pre_lift_chain_verbatim() {
2382        // Byte-identical parity with the two hand-authored
2383        // `.metadata.name.clone().unwrap_or_default()` chains the
2384        // primitive replaces in `tatara-pool-reconciler::
2385        // controller_allocation::reconcile_inner` (HashMap key seed)
2386        // and `tatara-pool-reconciler::allocation_decide::
2387        // AllocationConvergenceCtx::observe` (AllocationRef.name slot
2388        // seed). Runs across the FULL corner set of the metadata.name
2389        // slot: absent, present-with-value, present-with-empty-string.
2390        // A regression that inserted a normalization step at the
2391        // primitive the pre-lift chain does NOT apply — or vice versa —
2392        // surfaces here rather than as silent drift between the two
2393        // owned-form callsites and the ONE substrate owner they now
2394        // route through.
2395        let cases: [(Option<String>, &str); 3] = [
2396            (None, ""),
2397            (Some("attest-pool".into()), "attest-pool"),
2398            (Some(String::new()), ""),
2399        ];
2400        for (slot, expected) in cases {
2401            let mut p = pool_named("scratch");
2402            p.metadata.name = slot.clone();
2403            let pre_lift = p.metadata.name.clone().unwrap_or_default();
2404            assert_eq!(pre_lift.as_str(), expected, "pre-lift chain sanity");
2405            assert_eq!(p.owned_name_or_empty(), pre_lift);
2406            assert_eq!(p.owned_name_or_empty().as_str(), expected);
2407        }
2408    }
2409
2410    #[test]
2411    fn owned_name_or_empty_matches_borrow_form_peer_on_populated_slot() {
2412        // Cross-primitive coherence pin at the sibling corner: when the
2413        // slot is present, the borrow-form (`name_or_empty`) and owned-
2414        // form (`owned_name_or_empty`) primitives return the SAME byte
2415        // sequence and differ only in ownership. A regression that
2416        // skewed one form's fallback would surface here rather than as
2417        // silent drift between the router tie-break comparator and the
2418        // AllocationRef seed on the SAME pool.
2419        let p = pool_named("attest-pool");
2420        assert_eq!(p.name_or_empty(), p.owned_name_or_empty().as_str());
2421    }
2422
2423    #[test]
2424    fn owned_name_or_empty_matches_borrow_form_peer_on_missing_slot() {
2425        // Sibling corner of the coherence pin above: when the slot is
2426        // absent (or explicitly empty), BOTH primitives fold to the
2427        // same empty-string byte-shape. The load-bearing property is
2428        // that a caller who switches between the two return-forms
2429        // based on downstream ownership requirements never sees a
2430        // different missing-slot spelling as a side effect.
2431        let p = pool_unnamed();
2432        assert_eq!(p.name_or_empty(), p.owned_name_or_empty().as_str());
2433        assert_eq!(p.name_or_empty(), "");
2434        assert_eq!(p.owned_name_or_empty(), String::new());
2435    }
2436
2437    // ─── EphemeralPool::is_being_deleted substrate pins ───────────────
2438    //
2439    // Pins the copy-form metadata-projection primitive on the deletion-
2440    // tombstone axis of the pool CRD. Peer to the borrow-form + owned-
2441    // form metadata-fallback family (`name_or_empty`,
2442    // `owned_name_or_empty`); this one opens the presence-probe corner
2443    // for the tombstone slot. Sibling to the sister-CRD primitive
2444    // `crate::crd::Process::is_being_deleted` — the two primitives
2445    // now partition the tombstone-presence probe across BOTH tatara-
2446    // process CRDs on identical missing-slot semantics. Fail-before-
2447    // pass-after granularity: `is_being_deleted` did not exist on the
2448    // pool CRD pre-lift; the compiler cannot resolve the name until
2449    // the impl block above is in place, so a rollback of the primitive
2450    // breaks this whole module.
2451
2452    fn tombstoned_pool() -> EphemeralPool {
2453        let mut p = pool_named("attest-pool");
2454        p.metadata.namespace = Some("ephemeral-pools".into());
2455        p.metadata.deletion_timestamp = Some(k8s_openapi::apimachinery::pkg::apis::meta::v1::Time(
2456            Utc::now(),
2457        ));
2458        p
2459    }
2460
2461    #[test]
2462    fn is_being_deleted_returns_false_when_deletion_timestamp_is_absent() {
2463        // Missing-tombstone corner pin: the primitive collapses the
2464        // no-tombstone case to `false` so the `→ Drain` short-circuit
2465        // at `decide_pool_reconcile` is NOT taken and the observed-
2466        // phase composer at `pool_phase_from_members` proceeds to its
2467        // normal (free / spawning / allocated) arithmetic branches
2468        // instead of short-circuiting to `PoolPhase::Draining`.
2469        // Matches the pre-lift `.is_some()` chain's `false` byte-
2470        // identically at every consumer's downstream gate.
2471        let mut p = pool_named("attest-pool");
2472        p.metadata.deletion_timestamp = None;
2473        assert!(!p.is_being_deleted());
2474    }
2475
2476    #[test]
2477    fn is_being_deleted_returns_true_when_deletion_timestamp_is_present() {
2478        // Present-tombstone corner pin: the primitive returns `true`
2479        // on any populated `metadata.deletionTimestamp` slot regardless
2480        // of the timestamp payload — the two consumers only read the
2481        // tombstone's PRESENCE, never its RFC-3339 timestamp value.
2482        // A regression that gated the `true` return on the timestamp
2483        // being non-epoch, or parsed the timestamp before returning,
2484        // would surface here rather than as silent skew at the
2485        // `→ Drain` decision or the `→ Draining` phase report on the
2486        // SAME `EphemeralPool`.
2487        let p = tombstoned_pool();
2488        assert!(p.is_being_deleted());
2489    }
2490
2491    #[test]
2492    fn is_being_deleted_is_a_pure_projection() {
2493        // Purity pin: two consecutive calls return byte-identical
2494        // `bool` values (no lazy materialization, no interior
2495        // mutation of `self`). Peer to the sibling
2496        // `name_or_empty_is_a_pure_projection` +
2497        // `owned_name_or_empty_is_a_pure_projection` pins in this
2498        // module and to `is_being_deleted_is_a_pure_projection` on
2499        // the sister-CRD `Process`; all four bind the pure-projection
2500        // discipline on the ONE substrate accessor per metadata slot.
2501        let p = tombstoned_pool();
2502        let a = p.is_being_deleted();
2503        let b = p.is_being_deleted();
2504        assert_eq!(a, b);
2505        assert!(a);
2506    }
2507
2508    #[test]
2509    fn is_being_deleted_matches_pre_lift_pool_reconciler_chain_shape() {
2510        // Parity pin: sweeps the two corners every pre-lift consumer
2511        // plausibly encountered (missing tombstone, present tombstone)
2512        // and compares the substrate call against a hand-authored pre-
2513        // lift chain byte-identically. A regression that reshaped
2514        // either corner would surface here rather than as silent
2515        // operator-facing skew between the pool-reconciler's `→ Drain`
2516        // decision and the observed-phase composer's `→ Draining`
2517        // report on the SAME `EphemeralPool` within one reconcile
2518        // pass.
2519        fn pre_lift(p: &EphemeralPool) -> bool {
2520            p.metadata.deletion_timestamp.is_some()
2521        }
2522        // Missing slot.
2523        let mut p = pool_named("attest-pool");
2524        p.metadata.deletion_timestamp = None;
2525        assert_eq!(p.is_being_deleted(), pre_lift(&p));
2526        // Populated slot.
2527        let p = tombstoned_pool();
2528        assert_eq!(p.is_being_deleted(), pre_lift(&p));
2529    }
2530
2531    #[test]
2532    fn is_being_deleted_composes_with_pool_phase_draining_at_reconcile_preempt() {
2533        // Call-site-shape pin: the `pool_phase_from_members`
2534        // deletion-preempt returns `PoolPhase::Draining` as soon as
2535        // `pool.is_being_deleted()` holds, regardless of the (free +
2536        // spawning) supply arithmetic that would otherwise pick
2537        // `Ready` / `Scaling` / `Degraded`. The `→ Drain` decision at
2538        // `decide_pool_reconcile` composes with the same probe on the
2539        // same tombstone-presence slot. A regression that broadened
2540        // the tombstone probe implicitly (returning `false` on a
2541        // present but zero-timestamp) or narrowed it (requiring an
2542        // additional `.finalizers.is_empty()` conjunct that the two
2543        // consumers never spelled) would surface here rather than as
2544        // silent operator-facing skew between the pool reconciler's
2545        // decision and the observed-phase composer on the SAME
2546        // `EphemeralPool` within one reconcile pass.
2547        let alive = pool_named("attest-pool");
2548        assert!(!alive.is_being_deleted());
2549        let dying = tombstoned_pool();
2550        assert!(dying.is_being_deleted());
2551    }
2552
2553    // ─── EphemeralPool::owned_namespace_or_empty substrate pins ───────
2554    //
2555    // The owned-form peer of the `owned_name_or_empty` primitive on the
2556    // sibling `metadata.namespace` axis — the paired half of the
2557    // `AllocationRef { name, namespace }` struct literal both
2558    // `AllocationConvergenceCtx::observe` and the composition pin
2559    // consume through the SAME `AllocationRef::new(name, namespace)`
2560    // constructor. Fail-before-pass-after granularity:
2561    // `owned_namespace_or_empty` did not exist on the pool CRD pre-
2562    // lift; the compiler cannot resolve the name until the impl block
2563    // above is in place, so a rollback of the primitive breaks this
2564    // whole module.
2565    #[test]
2566    fn owned_namespace_or_empty_returns_empty_string_when_metadata_namespace_is_none() {
2567        // Missing-slot corner pin: the primitive collapses the no-
2568        // namespace case to the load-bearing empty-string sentinel so
2569        // the downstream `AllocationRef.namespace` slot carries `""`
2570        // rather than a defaulted `"default"` string. See the doc-
2571        // comment's DELIBERATE-EMPTY-SENTINEL rationale for why the
2572        // fallback matches `.clone().unwrap_or_default()` byte-for-
2573        // byte rather than substituting `Process::DEFAULT_NAMESPACE`
2574        // at the primitive.
2575        let mut p = pool_named("attest-pool");
2576        p.metadata.namespace = None;
2577        assert!(p.metadata.namespace.is_none(), "fixture invariant");
2578        assert_eq!(p.owned_namespace_or_empty(), String::new());
2579    }
2580
2581    #[test]
2582    fn owned_namespace_or_empty_returns_owned_string_when_slot_is_populated() {
2583        let mut p = pool_named("attest-pool");
2584        p.metadata.namespace = Some("ephemeral-pools".into());
2585        assert_eq!(p.owned_namespace_or_empty(), "ephemeral-pools");
2586    }
2587
2588    #[test]
2589    fn owned_namespace_or_empty_returns_empty_string_when_slot_is_explicitly_empty_string() {
2590        // Corner between `None` (missing slot) and `Some(String::new())`
2591        // (populated slot containing the empty string): the primitive
2592        // MUST fold both to the same `""` byte-shape so a downstream
2593        // `AllocationRef.namespace ==` comparator at
2594        // `resolve_pool` sees ONE "unset namespace" bucket regardless
2595        // of which shape the K8s API server materialized. Byte-
2596        // identical to what the pre-lift `.clone().unwrap_or_default()`
2597        // chain produced.
2598        let mut p = pool_named("attest-pool");
2599        p.metadata.namespace = Some(String::new());
2600        assert_eq!(p.owned_namespace_or_empty(), String::new());
2601        assert!(p.owned_namespace_or_empty().is_empty());
2602    }
2603
2604    #[test]
2605    fn owned_namespace_or_empty_is_a_pure_projection() {
2606        // Consecutive calls return byte-identical Strings — no cached
2607        // state, no mutation on the `EphemeralPool` between calls.
2608        // Peer to the sibling `owned_name_or_empty_is_a_pure_projection`
2609        // pin in this module and to `is_being_deleted_is_a_pure_projection`
2610        // on the same CRD; all three bind the pure-projection
2611        // discipline on the ONE substrate accessor per metadata slot.
2612        let mut p = pool_named("attest-pool");
2613        p.metadata.namespace = Some("ephemeral-pools".into());
2614        assert_eq!(p.owned_namespace_or_empty(), p.owned_namespace_or_empty());
2615        assert_eq!(p.owned_namespace_or_empty(), "ephemeral-pools");
2616        assert_eq!(p.owned_namespace_or_empty(), "ephemeral-pools");
2617    }
2618
2619    #[test]
2620    fn owned_namespace_or_empty_matches_pre_lift_chain_verbatim() {
2621        // Byte-identical parity with the two hand-authored
2622        // `.metadata.namespace.clone().unwrap_or_default()` chains
2623        // the primitive replaces in `tatara-pool-reconciler::
2624        // allocation_decide::AllocationConvergenceCtx::observe`
2625        // (matched-pool `AllocationRef.namespace` seed) and in the
2626        // sibling composition pin
2627        // `allocation_ref_new_composes_with_owned_name_or_empty_pool_projection`.
2628        // Runs across the FULL corner set of the metadata.namespace
2629        // slot: absent, present-with-value, present-with-empty-string.
2630        // A regression that inserted a normalization step at the
2631        // primitive the pre-lift chain does NOT apply — or vice versa —
2632        // surfaces here rather than as silent drift between the two
2633        // owned-form callsites and the ONE substrate owner they now
2634        // route through.
2635        let cases: [(Option<String>, &str); 3] = [
2636            (None, ""),
2637            (Some("ephemeral-pools".into()), "ephemeral-pools"),
2638            (Some(String::new()), ""),
2639        ];
2640        for (slot, expected) in cases {
2641            let mut p = pool_named("attest-pool");
2642            p.metadata.namespace = slot.clone();
2643            let pre_lift = p.metadata.namespace.clone().unwrap_or_default();
2644            assert_eq!(pre_lift.as_str(), expected, "pre-lift chain sanity");
2645            assert_eq!(p.owned_namespace_or_empty(), pre_lift);
2646            assert_eq!(p.owned_namespace_or_empty().as_str(), expected);
2647        }
2648    }
2649
2650    #[test]
2651    fn owned_namespace_or_empty_composes_with_owned_name_or_empty_on_paired_slot_axis() {
2652        // Paired-axis coherence pin: the two owned-form primitives on
2653        // the pool CRD's `metadata.name` + `metadata.namespace` slots
2654        // share the SAME empty-string sentinel on the missing corner,
2655        // so a caller that composes both halves into an
2656        // `AllocationRef` (as `AllocationConvergenceCtx::observe`
2657        // does) never sees a mixed-fallback pair (one `""`, the
2658        // other `"default"`) as a side effect of one slot being
2659        // absent. A regression that skewed either primitive's
2660        // fallback would surface here rather than as silent operator-
2661        // facing skew between the paired halves of the SAME
2662        // `AllocationRef` seed.
2663        let mut p = pool_named("attest-pool");
2664        p.metadata.namespace = None;
2665        p.metadata.name = None;
2666        assert_eq!(p.owned_name_or_empty(), p.owned_namespace_or_empty());
2667        assert_eq!(p.owned_name_or_empty(), String::new());
2668        assert_eq!(p.owned_namespace_or_empty(), String::new());
2669    }
2670
2671    #[test]
2672    fn owned_namespace_or_empty_does_not_default_to_process_default_namespace() {
2673        // Deliberate-empty-sentinel pin: the primitive's fallback is
2674        // `""`, NOT `crate::crd::Process::DEFAULT_NAMESPACE`. The
2675        // sole downstream consumer (`AllocationConvergenceCtx::observe`)
2676        // feeds the produced value into `AllocationRef.namespace`,
2677        // which is then matched byte-identically against
2678        // `spec.pool_ref.namespace` at `resolve_pool`. A silent
2679        // substitution of `"default"` at this primitive would alias
2680        // every namespace-absent pool to the `"default"` bucket at
2681        // the matcher, hiding the missing-slot corner from an
2682        // operator who explicitly authored an allocation against a
2683        // namespace-unset pool. Pinned so a future "helpful"
2684        // canonicalization step lands as a compiler-visible failure
2685        // here rather than as silent operator-facing skew at the
2686        // matched-pool seed.
2687        let mut p = pool_named("attest-pool");
2688        p.metadata.namespace = None;
2689        assert_ne!(
2690            p.owned_namespace_or_empty(),
2691            crate::crd::Process::DEFAULT_NAMESPACE
2692        );
2693        assert_eq!(p.owned_namespace_or_empty(), "");
2694    }
2695
2696    // ─── AllocationRef::new substrate pins ────────────────────────────
2697    //
2698    // Pins the substrate constructor for [`AllocationRef`] — the
2699    // ONE-liner composer that lifts the paired
2700    // `AllocationRef { name, namespace }` struct-literal every
2701    // downstream consumer restated by hand pre-lift at FOUR production
2702    // sites (2 × controller_allocation.rs assignedProcess seeds, 1 ×
2703    // allocation_decide.rs pool_ref seed, 1 × allocation_factory.rs
2704    // pool_ref seed) onto ONE substrate owner on `AllocationRef`.
2705    // Fail-before-pass-after granularity: `AllocationRef::new` did not
2706    // exist pre-lift; the compiler cannot resolve the name until the
2707    // impl block above is in place, so a rollback of the primitive
2708    // breaks this whole module.
2709
2710    #[test]
2711    fn allocation_ref_new_composes_owned_string_pair_verbatim() {
2712        // Happy-path pin: the constructor materializes an
2713        // `AllocationRef { name: <name>, namespace: <namespace> }`
2714        // byte-identical to the pre-lift struct literal every consumer
2715        // spelled. A regression that dropped either slot (e.g. an
2716        // erroneous `..Default::default()` on a shape that never had
2717        // a Default derive) surfaces here rather than as silent slot
2718        // loss downstream at the assignedProcess / bound_pool /
2719        // matched_pool / spec.pool_ref sinks.
2720        let r = AllocationRef::new(String::from("pr-42-demo"), String::from("ephemeral-pools"));
2721        assert_eq!(r.name, "pr-42-demo");
2722        assert_eq!(r.namespace, "ephemeral-pools");
2723    }
2724
2725    #[test]
2726    fn allocation_ref_new_matches_pre_lift_struct_literal_verbatim() {
2727        // Byte-identical parity pin: the substrate constructor and the
2728        // hand-authored struct literal produce equal `AllocationRef`
2729        // values on every provenance the FOUR pre-lift sites carried
2730        // (owned `String` from an owned-form projection; `&str`
2731        // promoted through `.to_string()`). A regression that inserted
2732        // a normalization step at the primitive the pre-lift literal
2733        // does NOT apply — or vice versa — surfaces here rather than
2734        // as silent drift between the four consumers and the ONE
2735        // substrate owner they now route through.
2736        let owned_name = String::from("pr-42-demo");
2737        let owned_ns = String::from("ephemeral-pools");
2738        let lifted = AllocationRef::new(owned_name.clone(), owned_ns.clone());
2739        let pre_lift = AllocationRef {
2740            name: owned_name,
2741            namespace: owned_ns,
2742        };
2743        assert_eq!(lifted, pre_lift);
2744    }
2745
2746    #[test]
2747    fn allocation_ref_new_accepts_str_provenance_via_into_string() {
2748        // `Into<String>` provenance-closure pin: the primitive accepts
2749        // every provenance the pre-lift sites carried. The
2750        // controller_allocation.rs assignedProcess seeds passed owned
2751        // `String` values (a moved `member_process_name` +
2752        // `ns.clone()`); the allocation_factory.rs pool_ref seed
2753        // passed `&str` (`n.to_string()` / `namespace.to_string()`).
2754        // Both provenances produce byte-identical output. A future
2755        // refactor of the constructor signature that demanded owned
2756        // `String` at author sites (dropping `impl Into<String>`)
2757        // would force `.to_string()` back at the FOUR call sites — the
2758        // pin fences that regression at ONE place.
2759        let from_str = AllocationRef::new("pr-42-demo", "ephemeral-pools");
2760        let from_string =
2761            AllocationRef::new(String::from("pr-42-demo"), String::from("ephemeral-pools"));
2762        assert_eq!(from_str, from_string);
2763        // Mixed provenance is also load-bearing: the allocation_decide.rs
2764        // matched_pool seed pairs an owned `String` (from
2765        // `EphemeralPool::owned_name_or_empty()`) with a hand-authored
2766        // `.clone().unwrap_or_default()` — also `String`. The
2767        // controller_allocation.rs paths pair a moved `String` name
2768        // with a `.clone()`-ed `ns: String`. Verify (owned, borrow)
2769        // and (borrow, owned) both compose to the same shape as
2770        // (owned, owned) / (borrow, borrow).
2771        let mixed_a = AllocationRef::new(String::from("pr-42-demo"), "ephemeral-pools");
2772        let mixed_b = AllocationRef::new("pr-42-demo", String::from("ephemeral-pools"));
2773        assert_eq!(from_str, mixed_a);
2774        assert_eq!(from_str, mixed_b);
2775    }
2776
2777    #[test]
2778    fn allocation_ref_new_positional_axis_order_pinned_name_first_namespace_second() {
2779        // Axis-order pin: name is the FIRST positional argument;
2780        // namespace is the SECOND. Reversing the pair at the
2781        // constructor is the exact regression this pin fences — the
2782        // FOUR pre-lift sites all spelled `name` before `namespace`
2783        // (matching the struct definition's field order in
2784        // `pub struct AllocationRef { pub name, pub namespace }`)
2785        // and the wire-format serde output `{ "name": "...",
2786        // "namespace": "..." }` reflects that order. A slot swap at
2787        // the primitive would surface here rather than as silent
2788        // `<namespace>/<name>` inversion at every downstream
2789        // qualified-ref composer that reads `{ref.name}/{ref.namespace}`
2790        // as an audit-log key.
2791        let r = AllocationRef::new("alpha-name", "beta-namespace");
2792        assert_eq!(r.name, "alpha-name");
2793        assert_eq!(r.namespace, "beta-namespace");
2794        assert_ne!(r.name, "beta-namespace");
2795        assert_ne!(r.namespace, "alpha-name");
2796    }
2797
2798    #[test]
2799    fn allocation_ref_new_preserves_empty_string_verbatim() {
2800        // Empty-string sentinel pin: the constructor is pure — it does
2801        // NOT canonicalize empty inputs (does NOT default an empty
2802        // namespace to `"default"`; does NOT reject an empty name).
2803        // Preserves the pre-lift shape the allocation_decide.rs
2804        // matched_pool seed relied on: when the pool's metadata.namespace
2805        // is absent, `.clone().unwrap_or_default()` yields the empty
2806        // string, and the AllocationRef's namespace slot carries that
2807        // empty string verbatim to the downstream `bound_pool` sink.
2808        // A future canonicalization pass (e.g. defaulting to
2809        // `Process::DEFAULT_NAMESPACE`) MUST land here, not at the
2810        // primitive body silently, so the pre-lift consumers' empty-
2811        // sentinel semantics are the visible contract of the new
2812        // constructor.
2813        let r = AllocationRef::new("", "");
2814        assert_eq!(r.name, "");
2815        assert_eq!(r.namespace, "");
2816        let mixed = AllocationRef::new("pr-42-demo", "");
2817        assert_eq!(mixed.name, "pr-42-demo");
2818        assert_eq!(mixed.namespace, "");
2819    }
2820
2821    #[test]
2822    fn allocation_ref_new_composes_with_owned_name_or_empty_pool_projection() {
2823        // Composition pin: the constructor composes with the paired
2824        // substrate primitives [`EphemeralPool::owned_name_or_empty`]
2825        // + [`EphemeralPool::owned_namespace_or_empty`] at the
2826        // allocation_decide.rs pool_ref seed — the same primitive
2827        // family the pool CRD opened for both halves of the
2828        // `AllocationRef { name, namespace }` struct literal. The
2829        // composed pair carries an owned `String` name half (from
2830        // `pool.owned_name_or_empty()`) and an owned `String`
2831        // namespace half (from `pool.owned_namespace_or_empty()`) —
2832        // no pre-lift chain remains. A regression that broke the
2833        // primitive family's `impl Into<String>` acceptance of an
2834        // owned `String` return type would surface here rather than
2835        // as silent build failure at the pool-reconciler matched_pool
2836        // seed.
2837        let pool = pool_named("attest-pool");
2838        let r = AllocationRef::new(pool.owned_name_or_empty(), pool.owned_namespace_or_empty());
2839        assert_eq!(r.name, "attest-pool");
2840        assert_eq!(r.namespace, pool.owned_namespace_or_empty());
2841    }
2842
2843    #[test]
2844    fn allocation_ref_new_returns_wire_format_serialization_verbatim() {
2845        // Wire-format pin: the constructor produces an
2846        // [`AllocationRef`] whose serde `rename_all = "camelCase"`
2847        // serialization is byte-identical to the pre-lift struct
2848        // literal's serialization. The `bound_pool` and
2849        // `assignedProcess` slots on `AllocationStatus` (and the
2850        // `poolRef` slot on `AllocationSpec`) all round-trip through
2851        // this shape — the pin fences a regression that added a
2852        // private field or a `#[serde(skip)]` accidentally.
2853        let r = AllocationRef::new("pr-42-demo", "ephemeral-pools");
2854        let yaml = serde_yaml::to_string(&r).expect("AllocationRef serializes to yaml");
2855        assert!(yaml.contains("name: pr-42-demo"), "{yaml}");
2856        assert!(yaml.contains("namespace: ephemeral-pools"), "{yaml}");
2857        let back: AllocationRef =
2858            serde_yaml::from_str(&yaml).expect("AllocationRef round-trips through yaml");
2859        assert_eq!(back, r);
2860    }
2861
2862    fn member(state: MemberState) -> PoolMember {
2863        PoolMember {
2864            process_name: "m".into(),
2865            state,
2866            entered_state_at: DateTime::<Utc>::from_timestamp(0, 0).unwrap(),
2867            allocation_ref: None,
2868        }
2869    }
2870
2871    #[test]
2872    fn state_count_fanout_returns_all_zeros_on_empty_slice() {
2873        // Zero-length pin: the empty-members corner produces a
2874        // 4-tuple of zero counters, matching the pre-lift
2875        // `count_state` fanout's four `.iter().filter(...).count()`
2876        // calls each returning 0 on an empty iterator.
2877        assert_eq!(PoolMember::state_count_fanout(&[]), (0, 0, 0, 0));
2878    }
2879
2880    #[test]
2881    fn state_count_fanout_partitions_variants_into_correct_slots() {
2882        // Positional-axis pin: the returned 4-tuple's slot order
2883        // matches the four `PoolStatus` counter slots in declaration
2884        // order — `(ready, allocated, spawning, returning)`. A
2885        // regression that swapped two slots (e.g., `ready` ↔
2886        // `spawning`) surfaces here rather than as an operator-facing
2887        // scale-out oscillation at the pool reconciler.
2888        let members = vec![
2889            member(MemberState::Free),
2890            member(MemberState::Free),
2891            member(MemberState::Allocated),
2892            member(MemberState::Spawning),
2893            member(MemberState::Spawning),
2894            member(MemberState::Spawning),
2895            member(MemberState::Returning),
2896        ];
2897        assert_eq!(PoolMember::state_count_fanout(&members), (2, 1, 3, 1));
2898    }
2899
2900    #[test]
2901    fn state_count_fanout_excludes_failed_from_every_counter() {
2902        // Closed-set pin: no `PoolStatus` slot counts `Failed` members
2903        // (they surface via `PoolPhase::Degraded` instead of a status
2904        // counter). This test fences a regression that let a `Failed`
2905        // member drift into one of the four counters and inflate the
2906        // operator-visible ready/allocated/spawning/returning fanout.
2907        let members = vec![
2908            member(MemberState::Failed),
2909            member(MemberState::Failed),
2910            member(MemberState::Failed),
2911        ];
2912        assert_eq!(PoolMember::state_count_fanout(&members), (0, 0, 0, 0));
2913
2914        // Mixed with a Free member: the Free member is counted, the
2915        // Failed members are not.
2916        let mixed = vec![
2917            member(MemberState::Free),
2918            member(MemberState::Failed),
2919            member(MemberState::Failed),
2920        ];
2921        assert_eq!(PoolMember::state_count_fanout(&mixed), (1, 0, 0, 0));
2922    }
2923
2924    #[test]
2925    fn state_count_fanout_matches_pre_lift_count_state_helper_verbatim() {
2926        // Parity pin: for every possible members list, the 4-tuple
2927        // returned by the substrate primitive matches the pre-lift
2928        // `count_state(&members, MemberState::<slot>)` fanout that
2929        // pool-reconciler restated at both status-patch sites. The
2930        // pre-lift helper was
2931        // ```rust,ignore
2932        // fn count_state(members: &[PoolMember], target: MemberState) -> u32 {
2933        //     members.iter().filter(|m| m.state == target).count() as u32
2934        // }
2935        // ```
2936        // — re-implemented inline here as an oracle.
2937        fn count_state(members: &[PoolMember], target: MemberState) -> u32 {
2938            members.iter().filter(|m| m.state == target).count() as u32
2939        }
2940        let members = vec![
2941            member(MemberState::Free),
2942            member(MemberState::Allocated),
2943            member(MemberState::Allocated),
2944            member(MemberState::Spawning),
2945            member(MemberState::Returning),
2946            member(MemberState::Returning),
2947            member(MemberState::Failed),
2948        ];
2949        let (ready, allocated, spawning, returning) = PoolMember::state_count_fanout(&members);
2950        assert_eq!(ready, count_state(&members, MemberState::Free));
2951        assert_eq!(allocated, count_state(&members, MemberState::Allocated));
2952        assert_eq!(spawning, count_state(&members, MemberState::Spawning));
2953        assert_eq!(returning, count_state(&members, MemberState::Returning));
2954    }
2955
2956    #[test]
2957    fn pool_status_observed_composes_pre_lift_status_seed_verbatim() {
2958        // Composition pin: the substrate constructor produces a
2959        // `PoolStatus` structurally equal to the pre-lift 11-line
2960        // struct literal both pool-reconciler status-patch sites
2961        // stamped by hand. Any drift in the defaults (`message`,
2962        // `conditions`) or in the counter fanout surfaces here.
2963        let now = DateTime::<Utc>::from_timestamp(1_700_000_000, 0).unwrap();
2964        let members = vec![
2965            member(MemberState::Free),
2966            member(MemberState::Allocated),
2967            member(MemberState::Spawning),
2968            member(MemberState::Returning),
2969            member(MemberState::Failed),
2970        ];
2971        let member_count = members.len();
2972        let observed = PoolStatus::observed(PoolPhase::Steady, members, now);
2973        assert_eq!(observed.phase, PoolPhase::Steady);
2974        assert_eq!(observed.phase_since, Some(now));
2975        assert_eq!(observed.ready_count, 1);
2976        assert_eq!(observed.allocated_count, 1);
2977        assert_eq!(observed.spawning_count, 1);
2978        assert_eq!(observed.returning_count, 1);
2979        assert_eq!(observed.members.len(), member_count);
2980        assert!(observed.message.is_none());
2981        assert!(observed.conditions.is_empty());
2982    }
2983
2984    #[test]
2985    fn pool_status_observed_moves_members_by_value_without_extra_clone() {
2986        // Ownership pin: the constructor consumes the members Vec by
2987        // value rather than borrowing + cloning internally. Both pre-
2988        // lift sites called `.clone()` on their `members` binding for
2989        // the struct-literal `members:` slot; the substrate lift keeps
2990        // the same one-clone bound at the caller (or a straight move
2991        // if the caller no longer needs the local `members` binding
2992        // after the seed) rather than accidentally cloning twice.
2993        let members = vec![member(MemberState::Free), member(MemberState::Spawning)];
2994        let now = DateTime::<Utc>::from_timestamp(0, 0).unwrap();
2995        let observed = PoolStatus::observed(PoolPhase::Steady, members, now);
2996        assert_eq!(observed.members.len(), 2);
2997    }
2998
2999    // ─── EphemeralPool::has_name substrate pins ───────────────────────
3000    //
3001    // Pins the copy-form metadata-projection primitive on the
3002    // `metadata.name` axis's presence-and-equal corner — the
3003    // discriminant every `candidate_pools.iter().find(|p| ...)`
3004    // closure that resolves a pool from an owned-name handle
3005    // (`AllocationRef.name` / `AllocationDecision::Bind.pool.name`)
3006    // routes through. Sibling to the `_or_empty` family on the SAME
3007    // slot ([`EphemeralPool::name_or_empty`] +
3008    // [`EphemeralPool::owned_name_or_empty`]) — this primitive owns
3009    // the `None`-preserving corner the `_or_empty` family folds away.
3010    // Fail-before-pass-after granularity: `has_name` did not exist
3011    // pre-lift; the compiler cannot resolve the name until the impl
3012    // block above is in place, so a rollback of the primitive breaks
3013    // this whole module.
3014    #[test]
3015    fn has_name_returns_true_when_slot_is_populated_and_equal() {
3016        // Happy-path pin: the slot is set AND byte-identical to the
3017        // candidate. Both pre-lift `find` closures — `resolve_pool`'s
3018        // explicit-`pool_ref` half and `controller_allocation`'s TTL-
3019        // inheritance fallback — resolve their target pool exactly in
3020        // this corner, and the primitive returns `true` here to
3021        // authorize the resolution.
3022        let p = pool_named("attest-pool");
3023        assert!(p.has_name("attest-pool"));
3024    }
3025
3026    #[test]
3027    fn has_name_returns_false_when_slot_is_populated_and_different() {
3028        // Populated-slot inequality pin: the primitive returns `false`
3029        // for every candidate that is NOT byte-identical to the slot,
3030        // including strict subsequences (`"attest"` vs. `"attest-pool"`),
3031        // strict superstrings (`"attest-pool-2"` vs. `"attest-pool"`),
3032        // and case-differ variants. This is the load-bearing property
3033        // that lets `find(|p| p.has_name(&candidate))` reject
3034        // non-matching pools rather than aliasing them together.
3035        let p = pool_named("attest-pool");
3036        assert!(!p.has_name("other-pool"));
3037        assert!(!p.has_name("attest"));
3038        assert!(!p.has_name("attest-pool-2"));
3039        assert!(!p.has_name("ATTEST-POOL"));
3040    }
3041
3042    #[test]
3043    fn has_name_returns_false_when_slot_is_none_even_against_empty_candidate() {
3044        // The `None`-preserving discipline pin: an unset `metadata.name`
3045        // slot returns `false` even when the candidate is the empty
3046        // string. Distinguishes `has_name` from a naïve substitution
3047        // through the sibling `name_or_empty` primitive, which would
3048        // fold both `None` and `Some("")` to `""` and silently promote
3049        // an unnamed pool with an empty candidate into a spurious
3050        // match at the resolver's `find` closure. Byte-identical to
3051        // what the pre-lift `.as_deref() == Some(<candidate>)` chain
3052        // produced (`None == Some("")` is `false`), which is what
3053        // both consumer sites relied on.
3054        let p = pool_unnamed();
3055        assert!(p.metadata.name.is_none(), "fixture invariant");
3056        assert!(!p.has_name(""));
3057        assert!(!p.has_name("attest-pool"));
3058    }
3059
3060    #[test]
3061    fn has_name_returns_true_only_when_populated_slot_and_candidate_are_both_empty() {
3062        // Populated-empty-slot corner pin: `Some(String::new())` is a
3063        // populated slot with an empty payload. `has_name("")` returns
3064        // `true` here (byte-identical `""` on both sides), while
3065        // `has_name("<anything else>")` returns `false`. This is the
3066        // corner where `has_name` DIVERGES from `name_or_empty`
3067        // observably: the `_or_empty` family folds this corner into
3068        // the same bucket as `None`, but `has_name` keeps the
3069        // presence bit visible — `Some("") == Some("")` is `true`
3070        // while `None == Some("")` is `false`.
3071        let mut p = pool_named("scratch");
3072        p.metadata.name = Some(String::new());
3073        assert!(p.has_name(""));
3074        assert!(!p.has_name("attest-pool"));
3075    }
3076
3077    #[test]
3078    fn has_name_matches_pre_lift_chain_verbatim_across_full_corner_set() {
3079        // Byte-identical parity pin: the primitive returns the same
3080        // `bool` as the pre-lift `.metadata.name.as_deref() == Some
3081        // (candidate)` chain across the FULL cross product of
3082        // (slot ∈ {None, Some("attest-pool"), Some("")}) × (candidate
3083        // ∈ {"attest-pool", "", "other"}). A regression that inserted
3084        // a normalization step at the primitive the pre-lift chain
3085        // does NOT apply — or vice versa — surfaces here rather than
3086        // as silent drift between the two `find` closures the primitive
3087        // owns.
3088        let slots: [Option<String>; 3] =
3089            [None, Some(String::from("attest-pool")), Some(String::new())];
3090        let candidates: [&str; 3] = ["attest-pool", "", "other"];
3091        for slot in slots {
3092            let mut p = pool_named("scratch");
3093            p.metadata.name = slot.clone();
3094            for candidate in candidates {
3095                let pre_lift = p.metadata.name.as_deref() == Some(candidate);
3096                assert_eq!(
3097                    p.has_name(candidate),
3098                    pre_lift,
3099                    "slot = {slot:?}, candidate = {candidate:?}"
3100                );
3101            }
3102        }
3103    }
3104
3105    #[test]
3106    fn has_name_diverges_from_name_or_empty_on_the_missing_slot_corner() {
3107        // Cross-primitive discipline pin: `has_name("")` and
3108        // `name_or_empty() == ""` MUST disagree on the `None`-slot
3109        // corner. `name_or_empty` returns `""` (its load-bearing
3110        // sentinel), so a naïve `name_or_empty() == ""` probe would
3111        // return `true` here — aliasing every unnamed pool to the
3112        // empty-candidate bucket at the resolver. `has_name`
3113        // preserves `Option::as_deref() == Some(_)`'s `None ⇒ false`
3114        // semantics, so it returns `false` and rejects the spurious
3115        // match. This test fences the WHOLE reason `has_name` exists
3116        // as a distinct primitive from the `_or_empty` family: a
3117        // future refactor that collapsed `has_name` into
3118        // `name_or_empty() == candidate` would break this pin and
3119        // silently regress the resolver's byte-comparison honesty.
3120        let p = pool_unnamed();
3121        assert_eq!(p.name_or_empty(), "");
3122        assert!(!p.has_name(""));
3123    }
3124
3125    #[test]
3126    fn has_name_is_a_pure_projection() {
3127        // Consecutive calls with the same candidate return the same
3128        // `bool` — no cached state, no mutation on the `EphemeralPool`
3129        // between calls. Guards against a future refactor that plants
3130        // a cache field on `EphemeralPool` and drifts one caller from
3131        // another silently.
3132        let p = pool_named("router-pool");
3133        assert_eq!(p.has_name("router-pool"), p.has_name("router-pool"));
3134        assert_eq!(p.has_name("other"), p.has_name("other"));
3135        assert!(p.has_name("router-pool"));
3136        assert!(!p.has_name("other"));
3137    }
3138}