Skip to main content

tatara_process/
allocation.rs

1//! `EphemeralAllocation` CRD — a typed request for a pool member.
2//!
3//! Pairs with `EphemeralPool`: an Allocation is the request side;
4//! the pool reconciler answers it by matching one of its free
5//! Process members and stamping the requestor's identity on the
6//! Allocation's status.
7//!
8//! Topology:
9//! - The requestor (GitHub PR webhook, CI runner, operator running
10//!   `feira allocation request …`) creates an `EphemeralAllocation`.
11//! - The pool reconciler watches Allocations; matches `spec.poolRef`
12//!   (or routes via PoolSelector if `poolRef` is omitted) to a pool;
13//!   picks one Free member; transitions the member to Allocated and
14//!   the Allocation to Bound.
15//! - When the requestor is done, it deletes the Allocation. The pool
16//!   reconciler honors the pool's `returnPolicy` (Reset / Replace /
17//!   Keep).
18
19use chrono::{DateTime, Utc};
20use kube::CustomResource;
21use schemars::JsonSchema;
22use serde::{Deserialize, Serialize};
23
24use crate::pool::AllocationRef;
25
26/// `EphemeralAllocation` CRD spec — a typed request for a pool member.
27///
28/// ```yaml
29/// apiVersion: tatara.pleme.io/v1alpha1
30/// kind: EphemeralAllocation
31/// metadata:
32///   name: pr-123-demo-app
33///   namespace: ephemeral-pools
34/// spec:
35///   poolRef:
36///     name: attest-pool
37///     namespace: ephemeral-pools
38///   requestor:
39///     kind: github-pr
40///     repo: "pleme-io/demo-app"
41///     branch: "fix-something"
42///     prNumber: 123
43///     prLabels: ["needs-ephemeral"]
44///   ttl: "1h"
45/// ```
46#[derive(CustomResource, Clone, Debug, Deserialize, Serialize, JsonSchema)]
47#[kube(
48    group = "tatara.pleme.io",
49    version = "v1alpha1",
50    kind = "EphemeralAllocation",
51    plural = "ephemeralallocations",
52    shortname = "ealloc",
53    namespaced,
54    status = "AllocationStatus",
55    printcolumn = r#"{"name":"Pool","type":"string","jsonPath":".spec.poolRef.name"}"#,
56    printcolumn = r#"{"name":"Phase","type":"string","jsonPath":".status.phase"}"#,
57    printcolumn = r#"{"name":"Process","type":"string","jsonPath":".status.assignedProcess.name"}"#,
58    printcolumn = r#"{"name":"Requestor","type":"string","jsonPath":".spec.requestor.kind"}"#,
59    printcolumn = r#"{"name":"Age","type":"date","jsonPath":".metadata.creationTimestamp"}"#
60)]
61#[serde(rename_all = "camelCase")]
62pub struct AllocationSpec {
63    /// Direct pool reference. When set, skip selector-based routing.
64    #[serde(default, skip_serializing_if = "Option::is_none")]
65    pub pool_ref: Option<AllocationRef>,
66
67    /// Who is asking for the env.
68    pub requestor: Requestor,
69
70    /// How long the requestor needs the env (`humantime`). The pool
71    /// reconciler clamps this to `pool.spec.maxAllocationTtl`.
72    /// When unset, falls back to the pool's `template.ttl`.
73    #[serde(default, skip_serializing_if = "Option::is_none")]
74    pub ttl: Option<String>,
75
76    /// Operator-supplied notes — surfaced in `feira allocation list`
77    /// for audit / debugging context.
78    #[serde(default, skip_serializing_if = "Option::is_none")]
79    pub note: Option<String>,
80}
81
82impl AllocationSpec {
83    /// The canonical minimal [`AllocationSpec`] composer — binds only
84    /// the single caller-varying [`Self::requestor`] slot and leaves
85    /// the three-slot default tail (`pool_ref = None`, `ttl = None`,
86    /// `note = None`) at ONE substrate owner. The lift of the 5-line
87    /// `AllocationSpec { pool_ref: None, requestor: <r>, ttl: None,
88    /// note: None }` incantation past the ★★ PRIME-DIRECTIVE ≥ 2
89    /// duplication threshold — pre-lift the SAME requestor-only
90    /// fixture shape recurred at NINE workspace-wide fixture sites
91    /// (five inside [`crate::allocation`]'s own test module — the
92    /// `alloc_with_phase` / `alloc_without_status` observers on the
93    /// phase axis, the `alloc_with_bound_pool` observer on the
94    /// routing axis, the `alloc_with_expires_at` observer on the TTL
95    /// axis, and the `allocation_spec_omits_optional_fields` wire-
96    /// shape pin; three inside [`crate::lib`]'s pin fixtures — the
97    /// `alloc_fixture` + two `empty_alloc_spec` helpers on the
98    /// coordinate / annotation axes; one inside `tatara-pool-
99    /// reconciler::allocation_decide` — the `alloc` fixture seeding
100    /// the pool convergence-decision test battery). All nine sites
101    /// walked the SAME three-slot default tail — differing only in
102    /// the caller-varying [`Requestor`] value.
103    ///
104    /// The three-slot default tail is the SAFE minimal shape: `pool_ref
105    /// = None` triggers selector-based routing (rather than pinning a
106    /// specific pool), `ttl = None` falls back to the pool template's
107    /// TTL, `note = None` leaves the audit slot empty. Every
108    /// [`crate::pool::PoolSelector`] filter sees "no direct pool
109    /// binding" and matches every candidate pool for the requestor's
110    /// kind; post-lift a callsite that legitimately overrides a slot
111    /// lands the override at its own site via struct-update on top
112    /// of `requestor_only`.
113    ///
114    /// A future addition to [`AllocationSpec`] — a new optional slot
115    /// (e.g. a `priority` for admission-control kinds, a `budget`
116    /// for cost-accounting, a `labels` set for per-allocation
117    /// tagging) — lands at ONE primitive body and every fixture /
118    /// default-shape callsite inherits the upgrade mechanically.
119    /// Pre-lift a new field would have broken all NINE callsites
120    /// (each holds an exhaustive struct literal); post-lift only
121    /// sites that legitimately override the new slot need to name it.
122    ///
123    /// Sibling substrate primitives on the same "bind-the-required-
124    /// slot-only" axis: [`Requestor::kind_only`] (Requestor kind-
125    /// only composer; the six-slot Requestor counterpart, one of the
126    /// values this composer stamps into its own `requestor` slot),
127    /// [`crate::intent::AplicacaoIntent::chart_only`] (Aplicacao
128    /// chart-pointer-only composer; the 7-slot Aplicacao counterpart),
129    /// [`crate::pool::PoolSpec::with_template`] (Pool template-only
130    /// composer; the 11-slot Pool counterpart), and
131    /// [`crate::spec::ProcessSpec::gate_compute_defaults`] (Process
132    /// zero-arg-fixture composer; the 12-slot Process counterpart).
133    ///
134    /// Theory anchor: THEORY.md §VI.1 (generation over composition —
135    /// the 3-slot default tail recurred at NINE hand-authored sites
136    /// past the ★★ PRIME-DIRECTIVE ≥ 2 duplication trigger, spanning
137    /// two workspace crates, and is lifted onto the ONE workspace-
138    /// wide substrate owner here). THEORY.md §II.1 invariant 5
139    /// (composition preserves proofs — the pin block below binds the
140    /// primitive at fail-before-pass-after granularity so a
141    /// regression that drifted any of the three default-tail slots
142    /// surfaces at THESE pins rather than as silent fixture skew
143    /// across the nine downstream consumers).
144    #[must_use]
145    pub fn requestor_only(requestor: Requestor) -> Self {
146        Self {
147            pool_ref: None,
148            requestor,
149            ttl: None,
150            note: None,
151        }
152    }
153}
154
155/// Identity + routing context for a request.
156#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)]
157#[serde(rename_all = "camelCase")]
158pub struct Requestor {
159    /// Discriminator: `"github-pr"`, `"manual"`, `"ci-run"`,
160    /// `"scheduled"`, … The wire shape is open by design — operators
161    /// may register their own kinds and the [`crate::pool::PoolSelector`]
162    /// matches on raw string equality. The substrate's own emitters
163    /// stamp one of the four canonical kebab-case kinds enumerated by
164    /// [`RequestorKind::ALL`]; [`Requestor::known_kind`] projects the
165    /// open wire field through that closed-set view at ONE site so
166    /// future kind-keyed consumers (pool dashboards, completion lists,
167    /// audit-trail classifiers) sweep the typed variants without
168    /// re-implementing `match self.kind.as_str()` arm-by-arm. Sibling
169    /// shape to [`crate::receipt::ReceiptEnvelope::known_kind`].
170    pub kind: String,
171
172    /// Optional repo identifier (e.g., `"pleme-io/demo-app"`).
173    /// Matched against `PoolSelector.repos`.
174    #[serde(default, skip_serializing_if = "Option::is_none")]
175    pub repo: Option<String>,
176
177    /// Optional branch name. Matched against `PoolSelector.branches`.
178    #[serde(default, skip_serializing_if = "Option::is_none")]
179    pub branch: Option<String>,
180
181    /// Optional PR number (for `kind: github-pr`). Surfaces in
182    /// printcolumns + audit.
183    #[serde(default, skip_serializing_if = "Option::is_none")]
184    pub pr_number: Option<u64>,
185
186    /// Optional commit SHA (for `kind: github-pr` or `ci-run`).
187    /// Stamped onto the allocated Process for traceability.
188    #[serde(default, skip_serializing_if = "Option::is_none")]
189    pub sha: Option<String>,
190
191    /// PR / commit labels — matched as a subset against
192    /// `PoolSelector.prLabels`.
193    #[serde(default)]
194    pub pr_labels: Vec<String>,
195
196    /// Free-form actor — username, CI runner ID, etc.
197    #[serde(default, skip_serializing_if = "Option::is_none")]
198    pub actor: Option<String>,
199}
200
201impl Requestor {
202    /// Decode [`Self::kind`] into the typed [`RequestorKind`] variant
203    /// when the wire string matches one of the four substrate-emitted
204    /// canonical kebab-case kinds; `None` when the kind is an
205    /// operator-registered open string (the schema is open by design —
206    /// every allocation remains a valid allocation, but only typed
207    /// kinds participate in closed-set dispatch). The (open `String`,
208    /// closed-typed view) split lets future kind-keyed consumers
209    /// (pool-selector classifiers, dashboard completion, audit-trail
210    /// classifiers) sweep the typed variants without touching the
211    /// open-by-design wire shape. Lifted as the canonical decode site
212    /// so no consumer re-implements the `match self.kind.as_str()` arm-
213    /// by-arm — the closed-set sweep happens through
214    /// [`RequestorKind::from_str`] at ONE site. Sibling shape to
215    /// [`crate::receipt::ReceiptEnvelope::known_kind`].
216    #[must_use]
217    pub fn known_kind(&self) -> Option<RequestorKind> {
218        self.kind.parse().ok()
219    }
220
221    /// The canonical minimal [`Requestor`] composer — binds only the
222    /// single caller-varying [`Self::kind`] slot and leaves the
223    /// six-slot default tail (`repo = None`, `branch = None`,
224    /// `pr_number = None`, `sha = None`, `pr_labels = vec![]`,
225    /// `actor = None`) at ONE substrate owner. The lift of the 9-line
226    /// `Requestor { kind: <lit>.into(), repo: None, branch: None,
227    /// pr_number: None, sha: None, pr_labels: vec![], actor: None }`
228    /// incantation past the ★★ PRIME-DIRECTIVE ≥ 2 duplication
229    /// threshold — pre-lift the SAME kind-only fixture shape recurred
230    /// at TEN workspace-wide fixture sites (six inside
231    /// [`crate::allocation`]'s own test module — the
232    /// `known_kind_decodes_built_requestors` sweep, the
233    /// `known_kind_returns_none_for_open_kinds` open-kind pin, the
234    /// `alloc_with_phase` / `alloc_without_status` observers on the
235    /// phase axis, the `bound_pool` observer on the routing axis, the
236    /// `expires_at` observer on the TTL axis, and the
237    /// `allocation_spec_omits_optional_fields` wire-shape pin; three
238    /// inside [`crate::lib`]'s pin fixtures (the `alloc_fixture` +
239    /// two `empty_alloc_spec` helpers on the coordinate / annotation
240    /// axes)).
241    ///
242    /// `impl Into<String>` on the argument accepts every pre-lift
243    /// caller shape verbatim without an argument recast:
244    /// * `Requestor::kind_only("manual")` — the operator-authored
245    ///   default fixture, matching the pre-lift `kind: "manual".into()`.
246    /// * `Requestor::kind_only("github-pr")` — the GitHub-webhook
247    ///   fixture, matching the pre-lift `kind: "github-pr".into()`.
248    /// * `Requestor::kind_only(RequestorKind::GithubPr)` — the
249    ///   typed-round-trip callsite, matching the pre-lift `kind: k
250    ///   .into()` where `k: RequestorKind` composes through the
251    ///   `From<RequestorKind> for String` bridge.
252    /// * `Requestor::kind_only("operator-custom-kind")` — the
253    ///   open-kind pin, matching the pre-lift `kind:
254    ///   "operator-custom-kind".into()`.
255    ///
256    /// The six-slot default tail is the SAFE minimal shape: every
257    /// [`crate::pool::PoolSelector`] filter sees "no repo constraint,
258    /// no branch constraint, no PR labels" and matches every pool
259    /// (post-lift a callsite that legitimately overrides a slot lands
260    /// the override at its own site via struct-update on top of
261    /// `kind_only`). A future addition to [`Requestor`] — a new
262    /// optional slot (e.g. a `run_id` for CI kinds, an `email` for
263    /// scheduled kinds, a `cluster` scoping override) — lands at ONE
264    /// primitive body and every fixture / default-shape callsite
265    /// inherits the upgrade mechanically. Pre-lift a new field would
266    /// have broken all TEN callsites (each holds an exhaustive struct
267    /// literal); post-lift only sites that legitimately override the
268    /// new slot need to name it.
269    ///
270    /// Sibling substrate primitives on the same "bind-the-required-
271    /// slots-only" axis: [`crate::intent::AplicacaoIntent::chart_only`]
272    /// (Aplicacao chart-pointer-only composer; the 7-slot Aplicacao
273    /// counterpart), [`crate::pool::PoolSpec::with_template`] (Pool
274    /// template-only composer; the 11-slot Pool counterpart), and
275    /// [`crate::spec::ProcessSpec::gate_compute_defaults`] (Process
276    /// zero-arg-fixture composer; the 12-slot Process counterpart).
277    #[must_use]
278    pub fn kind_only(kind: impl Into<String>) -> Self {
279        Self {
280            kind: kind.into(),
281            repo: None,
282            branch: None,
283            pr_number: None,
284            sha: None,
285            pr_labels: vec![],
286            actor: None,
287        }
288    }
289}
290
291/// Closed-set view over the substrate-emitted canonical
292/// [`Requestor::kind`] wire strings — the four kebab-case
293/// discriminators every pleme-io requestor stamps onto an
294/// [`EphemeralAllocation`]: `github-pr` (the [`tatara_github_watcher`-
295/// authored](../../tatara-github-watcher/src/allocation_factory.rs)
296/// PR-driven path), `manual` (operator-authored via `feira allocation
297/// request …`), `ci-run` (non-PR CI driver), and `scheduled` (a
298/// cron-style emitter). The wire field stays `pub kind: String` on
299/// [`Requestor`] so operators can register their own kinds without a
300/// schema bump; this enum is the typed view future kind-keyed
301/// consumers (pool dashboards, LSP completion, audit-trail
302/// classifiers) sweep against.
303///
304/// Pre-lift the four canonical kinds existed only as `&'static str`
305/// literals at four scattered sites — the documentation header on
306/// [`Requestor::kind`], the [`crate::pool::PoolSelector::kinds`]
307/// docstring, the `tatara-github-watcher` allocation factory, and the
308/// per-test `kind: "github-pr".into()` fixtures. A rename of one
309/// canonical kind (e.g. `"github-pr"` → `"github-pull-request"`) had
310/// no compile-time link to the others, so the documentation drifted
311/// independently of the emitter, and the [`PoolSelector::matches`]
312/// kind-filter silently kept matching the old spelling forever. Post-
313/// lift the (canonical-name, typed-variant) pairing binds at ONE site
314/// ([`Self::as_str`]); the `From<RequestorKind> for String` bridge
315/// lets emitters compose `Requestor { kind: RequestorKind::GithubPr.into(), … }`
316/// so the four canonical strings stop appearing as bare `&'static str`
317/// literals at author sites.
318///
319/// Adding a fifth kind (e.g. `Slack` → `"slack"`, `Webhook` →
320/// `"webhook"`) lands at one [`Self::ALL`] entry + one [`Self::as_str`]
321/// arm — exhaustively checked by the compiler (the `[Self; 4]` array
322/// literal forces the arity) AND by the per-variant truth-table tests
323/// below.
324///
325/// Sibling closed-set `ALL`-keyed lifts across the crate:
326/// [`crate::receipt::ReceiptKind::ALL`] (the four substrate-emitted
327/// receipt kinds — direct shape peer, same open-wire + closed-view
328/// split), [`AllocationPhase::ALL`], [`crate::phase::ProcessPhase::ALL`],
329/// [`crate::signal::ProcessSignal::ALL`],
330/// [`crate::boundary::ConditionKind::ALL`],
331/// [`crate::lifetime::TeardownPolicy::ALL`],
332/// [`crate::lifetime::LifetimeKind::ALL`],
333/// [`crate::intent::IntentKind::ALL`],
334/// [`crate::lifetime_clock::TerminateReasonKind::ALL`].
335///
336/// Theory anchor: THEORY.md §III — the typescape; the substrate's own
337/// requestor kinds become a TYPE rather than four `&'static str`
338/// literals at every author + docstring + fixture site. THEORY.md
339/// §V.1 — knowable platform; the closed-set view turns "which kinds
340/// does the substrate actually emit" from a grep job into a method
341/// the compiler enforces exhaustively at every dispatch site.
342#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, tatara_closed_set::DeriveClosedSet)]
343#[closed_set(via = "as_str", generate_unknown, display)]
344pub enum RequestorKind {
345    /// GitHub pull-request webhook — `tatara-github-watcher` stamps
346    /// this on every allocation built from a `PullRequestEvent`.
347    GithubPr,
348    /// Operator-authored allocation — `feira allocation request …`
349    /// and any hand-crafted CR.
350    Manual,
351    /// Non-PR CI driver — a pipeline run that wants an ephemeral env
352    /// without an associated pull request.
353    CiRun,
354    /// Cron-style scheduled emitter — periodic allocation creation
355    /// (e.g. nightly drift detection).
356    Scheduled,
357}
358
359impl RequestorKind {
360    /// The closed set of substrate-emitted requestor kinds — single
361    /// source of truth that drives the [`Self::from_str`] decode sweep
362    /// AND any future enumeration consumer (pool-selector classifiers,
363    /// dashboard completion, `tatara-check` kind enumeration). Adding
364    /// a fifth variant (e.g. `Slack` → `"slack"`) lands at one `ALL`
365    /// entry + one `as_str` arm — exhaustively checked by the compiler
366    /// (the `[Self; 4]` array literal forces the arity) AND by the
367    /// per-variant truth-table tests below.
368    pub const ALL: [Self; 4] = [Self::GithubPr, Self::Manual, Self::CiRun, Self::Scheduled];
369
370    /// Canonical kebab-case wire-format kind — the literal that lands
371    /// in [`Requestor::kind`] when this variant authors the request.
372    /// Pinned to four byte-exact strings the substrate has already
373    /// published (the `tatara-github-watcher` factory, the operator
374    /// fixtures in this file, the `PoolSelector.kinds` filter, the
375    /// CRD printcolumns) — renaming any one is a wire-format change,
376    /// not a typed-internal refactor, and the
377    /// `requestor_kind_canonical_names_pinned` truth-table test fails
378    /// first to keep the substrate honest. Used by [`std::fmt::Display`]
379    /// (single source of truth) and as the `String` projection that
380    /// `From<RequestorKind> for String` ([`Self::into`]) composes so
381    /// emitters can spell `Requestor { kind: RequestorKind::GithubPr.into(), … }`
382    /// without re-typing the canonical literal at every author site.
383    #[must_use]
384    pub const fn as_str(self) -> &'static str {
385        match self {
386            Self::GithubPr => "github-pr",
387            Self::Manual => "manual",
388            Self::CiRun => "ci-run",
389            Self::Scheduled => "scheduled",
390        }
391    }
392}
393
394// `impl FromStr for RequestorKind` + `impl tatara_lisp::ClosedSet for
395// RequestorKind` + `impl std::fmt::Display for RequestorKind` are
396// generated by `#[derive(tatara_closed_set::DeriveClosedSet)]` on the enum
397// declaration above. `label` delegates to the inherent
398// `RequestorKind::as_str` via `#[closed_set(via = "as_str")]` so the
399// kebab-case wire-format projection stays load-bearing (matches the
400// `tatara-github-watcher` factory + the CRD printcolumns + the
401// `PoolSelector.kinds` filter verbatim) while generic `T: ClosedSet`
402// consumers reach the STABLE workspace-wide name (`label`). The
403// `display` flag emits the `f.write_str(self.as_str())` delegation
404// block — the substrate-wide closed-set-enum idiom's third piece —
405// at the same proc-macro site rather than a hand-rolled
406// `fmt::Display` block per implementor.
407
408// `pub struct UnknownRequestorKind(pub String)` is generated by
409// `#[derive(tatara_closed_set::DeriveClosedSet)]` + `#[closed_set(generate_unknown)]`
410// on the enum declaration above. The auto-derived label `"requestor kind"`
411// matches the prior hand-rolled `#[error("unknown requestor kind: {0}")]`
412// verbatim — pinned generically by clause (5) of
413// `tatara_closed_set::assert_closed_set_well_formed::<RequestorKind>()` (called
414// from `requestor_kind_is_well_formed_closed_set` in the test module).
415// Symmetric to every sibling `Unknown*` error in this crate (e.g.
416// [`UnknownAllocationPhase`], [`crate::receipt::UnknownReceiptKind`],
417// [`crate::phase::UnknownPhase`], [`crate::lifetime::UnknownTeardownPolicy`]).
418
419impl From<RequestorKind> for String {
420    /// Composes [`RequestorKind::as_str`] into an owned `String` so
421    /// every `impl Into<String>` API surface (the `kind:` field
422    /// initializer on [`Requestor`] most notably) accepts the typed
423    /// variant transparently — the call site stays
424    /// `kind: RequestorKind::GithubPr.into()` and the typed → wire
425    /// bridge runs through ONE place. Sibling shape to
426    /// [`crate::receipt::ReceiptKind`]'s `From for String`.
427    fn from(k: RequestorKind) -> Self {
428        k.as_str().to_owned()
429    }
430}
431
432impl From<RequestorKind> for &'static str {
433    fn from(k: RequestorKind) -> Self {
434        k.as_str()
435    }
436}
437
438/// `EphemeralAllocation.status` — observed allocation state.
439#[derive(Clone, Debug, Default, Deserialize, Serialize, JsonSchema)]
440#[serde(rename_all = "camelCase")]
441pub struct AllocationStatus {
442    /// Current lifecycle phase.
443    #[serde(default)]
444    pub phase: AllocationPhase,
445
446    /// When the phase last changed.
447    #[serde(default, skip_serializing_if = "Option::is_none")]
448    pub phase_since: Option<DateTime<Utc>>,
449
450    /// Pool that owns the matched member. Set as soon as routing
451    /// resolves; not cleared on release (audit trail).
452    #[serde(default, skip_serializing_if = "Option::is_none")]
453    pub bound_pool: Option<AllocationRef>,
454
455    /// The Process backing this allocation, if Bound.
456    #[serde(default, skip_serializing_if = "Option::is_none")]
457    pub assigned_process: Option<AllocationRef>,
458
459    /// When the allocation was matched to a Process.
460    #[serde(default, skip_serializing_if = "Option::is_none")]
461    pub allocated_at: Option<DateTime<Utc>>,
462
463    /// Wall-clock expiry derived from `spec.ttl` + `allocated_at`.
464    /// The pool reconciler force-returns the member at this point.
465    #[serde(default, skip_serializing_if = "Option::is_none")]
466    pub expires_at: Option<DateTime<Utc>>,
467
468    /// Operator-visible message.
469    #[serde(default, skip_serializing_if = "Option::is_none")]
470    pub message: Option<String>,
471
472    /// Standard Conditions.
473    ///
474    /// The empty case is skipped at serialization so a merge-patch
475    /// body built from a caller-supplied [`AllocationStatus`] whose
476    /// `conditions` slot has not been touched does NOT emit
477    /// `"conditions": []` on the wire — under RFC-7396 JSON Merge
478    /// Patch (the shape `Patch::Merge` sends) an empty array
479    /// REPLACES the persisted list rather than merges into it, so a
480    /// controller round-trip that reused a scratch `AllocationStatus`
481    /// as a patch body would silently clobber whatever conditions the
482    /// prior status carried. Peer to `phase_since` /
483    /// `bound_pool` / `assigned_process` / `allocated_at` /
484    /// `expires_at` above, each already skip-serialized on its
485    /// [`Default`]-equivalent variant.
486    #[serde(default, skip_serializing_if = "Vec::is_empty")]
487    pub conditions: Vec<AllocationCondition>,
488}
489
490impl AllocationStatus {
491    /// Substrate composer for a phase-transition [`AllocationStatus`]
492    /// seed: stamps the THREE always-present slots (`phase` +
493    /// `phase_since = Some(now)` + `message = Some(<supplied>)`) and
494    /// defaults every other slot (`bound_pool` / `assigned_process` /
495    /// `allocated_at` / `expires_at` = `None`, `conditions = vec![]`).
496    /// Caller-branches attach the extra slots via struct-update
497    /// syntax onto the seed.
498    ///
499    /// Pre-lift the 4-slot phase-transition seed
500    /// ```rust,ignore
501    /// json!({
502    ///     "status": {
503    ///         "phase": <AllocationPhase-variant>,
504    ///         "phaseSince": Utc::now(),
505    ///         "message": "<transition-reason>",
506    ///         …optional caller-attached slots…
507    ///     }
508    /// })
509    /// ```
510    /// was hand-authored at FOUR sites past the ★★ PRIME-DIRECTIVE
511    /// ≥ 2 duplication threshold in
512    /// `tatara-pool-reconciler::controller_allocation::reconcile_inner`,
513    /// each restating the SAME `phase + phase_since + message` invariant
514    /// triplet on a different [`AllocationPhase`] variant:
515    /// * `AllocationDecision::NoMatchingPool` — the "no Pool selector
516    ///   matched this Requestor" fallthrough
517    ///   ([`AllocationPhase::NoMatchingPool`]).
518    /// * `AllocationDecision::Wait` — the "pool matched; no Free member
519    ///   available" queued path
520    ///   ([`AllocationPhase::Queued`]) with a `bound_pool` addition.
521    /// * `AllocationDecision::Bind` — the "bound to pool member"
522    ///   allocation path ([`AllocationPhase::Bound`]) with
523    ///   `bound_pool` + `assigned_process` + `allocated_at` +
524    ///   `expires_at` additions.
525    /// * `AllocationDecision::Release` — the "released; pool reconciler
526    ///   will return the member" release path
527    ///   ([`AllocationPhase::Released`]) with `bound_pool` +
528    ///   `assigned_process` additions.
529    ///
530    /// All four hand-authored the SAME `phaseSince: Utc::now()` stamp
531    /// alongside the phase transition, and all four spelled the
532    /// invariant triplet as bare JSON keys inside a `json!({...})`
533    /// literal — a fragile shape where any drift in the underlying
534    /// [`AllocationStatus`] field naming (a rename from `phaseSince`
535    /// to `phase_since` at the serde surface, a promotion of `message`
536    /// to a structured envelope) silently stops the JSON keys from
537    /// mapping to the typed struct's fields and the K8s API server
538    /// merges an ill-shaped patch. Post-lift the four callers build a
539    /// typed [`AllocationStatus`] via `AllocationStatus::transition`,
540    /// attach any branch-specific slots via struct-update syntax, and
541    /// wrap the result in `json!({ "status": s })` — the serde
542    /// `rename_all = "camelCase"` derive on [`AllocationStatus`] owns
543    /// the wire-shape composition, so a field rename lands at ONE
544    /// site (the derive) and every emit site inherits the upgrade
545    /// mechanically.
546    ///
547    /// Cross-CRD peer to [`crate::pool::PoolStatus::observed`] on the
548    /// same `<CRD>Status` substrate-composer axis — both primitives
549    /// stamp `phase_since = Some(now)` from a caller-supplied `now`
550    /// timestamp so the composer stays clock-injectable rather than
551    /// implicitly reading wall time, and both close every optional slot
552    /// with its [`Default`]-equivalent variant so a future slot
553    /// addition on either status shape plugs into the composer at ONE
554    /// site and every downstream emit site inherits the new slot
555    /// mechanically.
556    ///
557    /// Cross-CRD peer to the `tatara-reconciler::patch::phase_status_msg`
558    /// primitive on the (CRD × phase-transition-with-message) axis —
559    /// both primitives own the three-slot `phase + phase_since +
560    /// message` invariant on their respective CRDs' status subresource,
561    /// and both accept `impl Into<String>` for the message so the
562    /// callsite carries `&'static str` literal reasons and
563    /// `format!(...)`-owned strings without widening the signature.
564    ///
565    /// Theory anchor: THEORY.md §VI.1 (generation over composition —
566    /// the 4-slot phase-transition status-seed incantation recurred at
567    /// four hand-authored sites past the ★★ PRIME-DIRECTIVE ≥ 2
568    /// duplication trigger, and is lifted to ONE owner here).
569    /// THEORY.md §II.1 invariant 5 (composition preserves proofs —
570    /// the pins bind the three always-present slots + the
571    /// [`Default`]-defaulted rest + byte-identical parity with the
572    /// pre-lift `json!({...})` triplet through serde round-trip, so a
573    /// regression that drifted any surface at
574    /// `tests::allocation_status_transition_*` rather than as silent
575    /// operator-visible skew between the four allocation-decision
576    /// patch sites).
577    #[must_use]
578    pub fn transition(
579        phase: AllocationPhase,
580        message: impl Into<String>,
581        now: DateTime<Utc>,
582    ) -> Self {
583        Self {
584            phase,
585            phase_since: Some(now),
586            message: Some(message.into()),
587            ..Default::default()
588        }
589    }
590
591    /// Substrate composer for a phase-transition [`AllocationStatus`]
592    /// seed whose `bound_pool` + `assigned_process` axis-pair is
593    /// stamped alongside the base [`Self::transition`] triplet
594    /// (`phase` + `phase_since = Some(now)` + `message =
595    /// Some(<supplied>)`). Every other slot lands at its
596    /// [`Default`]-equivalent variant so a caller-branch that attaches
597    /// an optional slot via struct-update syntax (a `Bind` arm's
598    /// `allocated_at` / `expires_at` addenda, say) does not silently
599    /// inherit a pre-populated non-`None` value.
600    ///
601    /// Pre-lift the `bound_pool: Some(pool)` + `assigned_process:
602    /// Some(AllocationRef::new(name, ns))` pair rode struct-update
603    /// syntax onto [`Self::transition`] at TWO sites past the ★★
604    /// PRIME-DIRECTIVE ≥ 2 duplication threshold in
605    /// `tatara-pool-reconciler::controller_allocation::reconcile_inner`
606    /// — the `AllocationDecision::Bind` arm ([`AllocationPhase::Bound`]
607    /// with two extra `allocated_at` / `expires_at` addenda) and the
608    /// `AllocationDecision::Release` arm ([`AllocationPhase::Released`]
609    /// with no addenda). Both restated the SAME pair-of-`Some`-slot
610    /// invariant against the SAME struct-update seed and funneled the
611    /// resulting body through the SAME `patch_status` call on
612    /// `Api<EphemeralAllocation>`. Post-lift both callers reach the
613    /// pair through ONE substrate composer; a future normalization on
614    /// the bound-set axis (a symmetry gate that the assigned_process's
615    /// namespace matches the bound_pool's namespace, a canonicalization
616    /// that closes the pair against a stale audit record, a
617    /// backwards-compatibility rename of either slot at the serde
618    /// surface) lands at ONE substrate site rather than at each
619    /// callsite in the two-arm allocation reconciler.
620    ///
621    /// Composes atop [`Self::transition`] so any future evolution to
622    /// the base three-slot invariant triplet (a `phase_since` rename,
623    /// a `message` promotion to a structured envelope, a fourth
624    /// always-stamped diagnostic slot) reaches this composer through
625    /// ONE substrate site and both consumers inherit the upgrade
626    /// mechanically. Sibling composition discipline to
627    /// [`crate::pool::PoolStatus::observed`]'s `state_count_fanout` +
628    /// `Utc::now()` fold — the compound composer names its axis + calls
629    /// the substrate primitive on the invariant it wraps rather than
630    /// restating the wrapped shape inline.
631    ///
632    /// Theory anchor: THEORY.md §VI.1 (generation over composition —
633    /// the `bound_pool + assigned_process` pair recurred at two hand-
634    /// authored sites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication
635    /// trigger, and is lifted to ONE owner here). THEORY.md §II.1
636    /// invariant 5 (composition preserves proofs — the pins bind the
637    /// pair + the composed base triplet + byte-identical parity with
638    /// the pre-lift struct-update shape through serde round-trip, so a
639    /// regression that drifted any surface at
640    /// `tests::allocation_status_bound_transition_*` rather than as
641    /// silent operator-visible skew between the two Bind / Release
642    /// patch sites).
643    #[must_use]
644    pub fn bound_transition(
645        phase: AllocationPhase,
646        message: impl Into<String>,
647        now: DateTime<Utc>,
648        bound_pool: AllocationRef,
649        assigned_process: AllocationRef,
650    ) -> Self {
651        Self {
652            bound_pool: Some(bound_pool),
653            assigned_process: Some(assigned_process),
654            ..Self::transition(phase, message, now)
655        }
656    }
657}
658
659/// Allocation lifecycle phase.
660///
661/// Sibling closed-set lifts on the same `EphemeralAllocation` /
662/// `EphemeralPool` axis: [`crate::pool::ReplacementPolicy::ALL`],
663/// [`crate::pool::ReturnPolicy::ALL`]. Sibling closed-sets on the
664/// `tatara-process` algebra: [`crate::lifetime::TeardownPolicy::ALL`],
665/// [`crate::lifetime::LifetimeKind::ALL`],
666/// [`crate::boundary::ConditionKind::ALL`],
667/// [`crate::intent::IntentKind::ALL`],
668/// [`crate::phase::ProcessPhase::ALL`],
669/// [`crate::signal::ProcessSignal::ALL`].
670#[derive(
671    Clone,
672    Copy,
673    Debug,
674    PartialEq,
675    Eq,
676    Hash,
677    Serialize,
678    Deserialize,
679    JsonSchema,
680    tatara_closed_set::DeriveClosedSet,
681)]
682#[serde(rename_all = "PascalCase")]
683#[closed_set(via = "as_str", generate_unknown, display)]
684pub enum AllocationPhase {
685    /// Admitted; pool selector matching not yet attempted.
686    Pending,
687    /// Routed to a pool but no `Free` member is available — queued.
688    Queued,
689    /// A pool member has been assigned + transitioned to Allocated.
690    Bound,
691    /// `expires_at` reached or requestor deleted; member is returning.
692    Releasing,
693    /// Released; the allocation is a permanent audit record.
694    Released,
695    /// No pool selector matched. The reconciler will retry on each
696    /// pool spec update; surfaced in status so operators see why.
697    NoMatchingPool,
698    /// Pool refused (e.g., `max_size` reached and no member can be
699    /// freed) — operator intervention needed.
700    Failed,
701}
702
703impl Default for AllocationPhase {
704    fn default() -> Self {
705        Self::Pending
706    }
707}
708
709impl AllocationPhase {
710    /// The closed set of allocation phases — single source of truth
711    /// that drives the `as_str` / Display / `FromStr` triad AND the
712    /// `is_terminal` / `needs_pool_routing` predicate pair the
713    /// allocation reconciler's observe/decide split dispatches on.
714    /// Adding an eighth variant lands at one `ALL` entry + one
715    /// `as_str` arm + one arm per predicate — exhaustively checked by
716    /// the compiler (the `[Self; 7]` array literal forces the arity)
717    /// and by the implication test
718    /// (`allocation_phase_terminal_excludes_routing`) so a new
719    /// variant can't claim to be both terminal AND routing-eligible.
720    pub const ALL: [Self; 7] = [
721        Self::Pending,
722        Self::Queued,
723        Self::Bound,
724        Self::Releasing,
725        Self::Released,
726        Self::NoMatchingPool,
727        Self::Failed,
728    ];
729
730    /// Canonical PascalCase wire-format projection — matches the
731    /// serde `rename_all = "PascalCase"` output verbatim AND the CRD
732    /// `enum:` enumeration the allocation reconciler stamps on the
733    /// `ephemeralallocations.tatara.pleme.io` schema. Pinned by
734    /// `allocation_phase_as_str_matches_serde` so a variant rename
735    /// can't drift between the typed surface, the CRD enum, the YAML
736    /// wire format AND any operator-facing diagnostic composed via
737    /// Display rather than a hard-coded literal that would silently
738    /// rot.
739    pub const fn as_str(self) -> &'static str {
740        match self {
741            Self::Pending => "Pending",
742            Self::Queued => "Queued",
743            Self::Bound => "Bound",
744            Self::Releasing => "Releasing",
745            Self::Released => "Released",
746            Self::NoMatchingPool => "NoMatchingPool",
747            Self::Failed => "Failed",
748        }
749    }
750
751    /// True iff the allocation has reached an absorbing state —
752    /// `Released` (clean audit record) or `Failed` (pool refused;
753    /// operator intervention needed). The allocation reconciler
754    /// short-circuits both phases to `NoOp` rather than re-running
755    /// the routing / heartbeat ladder against a settled record.
756    ///
757    /// Closed-set match (not `matches!`) so a future variant
758    /// triggers the compiler's exhaustiveness check at this site
759    /// rather than silently defaulting to `false` and letting a new
760    /// terminal phase fall through into pool rebinding. Paired with
761    /// `needs_pool_routing` they form the two-axis projection
762    /// `allocation_decide::AllocationConvergence::decide` matches
763    /// against — the impossible bucket `(true, true)` is pinned
764    /// empty by `allocation_phase_terminal_excludes_routing`.
765    pub const fn is_terminal(self) -> bool {
766        match self {
767            Self::Released | Self::Failed => true,
768            Self::Pending | Self::Queued | Self::Bound | Self::Releasing | Self::NoMatchingPool => {
769                false
770            }
771        }
772    }
773
774    /// True iff the allocation is on the routing path — the
775    /// reconciler still needs to resolve a target pool + look up a
776    /// free member. `Pending` (just admitted), `Queued` (matched
777    /// pool was full last tick), and `NoMatchingPool` (no selector
778    /// matched yet; retry on pool spec updates) all live here. The
779    /// settled non-terminal phases `Bound` (already matched) and
780    /// `Releasing` (being torn down) don't — they short-circuit to
781    /// the heartbeat / release ladder without re-resolving the pool.
782    ///
783    /// Closed-set match (not `matches!`) — same exhaustiveness
784    /// discipline as [`Self::is_terminal`]. Lifts the open-coded
785    /// `phase != Released && phase != Bound` gate that
786    /// `allocation_decide::AllocationConvergenceCtx::observe` used
787    /// to predicate pool resolution on, AND closes the latent gap
788    /// where `Failed` / `Releasing` (neither `Released` nor `Bound`)
789    /// would slip through to the routing branch — a `Failed`
790    /// allocation without a deletion timestamp could be silently
791    /// rebound to a fresh pool member, which is the opposite of
792    /// "operator intervention needed."
793    pub const fn needs_pool_routing(self) -> bool {
794        match self {
795            Self::Pending | Self::Queued | Self::NoMatchingPool => true,
796            Self::Bound | Self::Releasing | Self::Released | Self::Failed => false,
797        }
798    }
799}
800
801// `impl FromStr for AllocationPhase` + `impl tatara_lisp::ClosedSet for
802// AllocationPhase` + `impl std::fmt::Display for AllocationPhase` are
803// generated by `#[derive(tatara_closed_set::DeriveClosedSet)]` on the enum
804// declaration above. `label` delegates to the inherent
805// `AllocationPhase::as_str` via `#[closed_set(via = "as_str")]` so the
806// PascalCase wire-format projection stays load-bearing (matches the serde
807// rename + the CRD `enum:` enumeration the allocation reconciler stamps
808// on the `ephemeralallocations.tatara.pleme.io` schema verbatim) while
809// generic `T: ClosedSet` consumers reach the STABLE workspace-wide name
810// (`label`). The `display` flag emits the `f.write_str(self.as_str())`
811// delegation block at the same proc-macro site rather than a
812// hand-rolled `fmt::Display` block per implementor.
813
814// `pub struct UnknownAllocationPhase(pub String)` is generated by
815// `#[derive(tatara_closed_set::DeriveClosedSet)]` + `#[closed_set(generate_unknown)]`
816// on the enum declaration above. The auto-derived label `"allocation phase"`
817// matches the prior hand-rolled `#[error("unknown allocation phase: {0}")]`
818// verbatim — pinned generically by clause (5) of
819// `tatara_closed_set::assert_closed_set_well_formed::<AllocationPhase>()` (called
820// from `allocation_phase_is_well_formed_closed_set` in the test module).
821// Symmetric to [`crate::pool::UnknownReplacementPolicy`],
822// [`crate::pool::UnknownReturnPolicy`],
823// [`crate::lifetime::UnknownTeardownPolicy`],
824// [`crate::boundary::UnknownConditionKind`], and
825// [`crate::phase::UnknownPhase`].
826
827/// Allocation Condition (same shape as PoolCondition for downstream
828/// uniformity).
829#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)]
830#[serde(rename_all = "camelCase")]
831pub struct AllocationCondition {
832    pub type_: String,
833    pub status: String,
834    pub reason: String,
835    pub message: String,
836    pub last_transition_time: DateTime<Utc>,
837}
838
839impl EphemeralAllocation {
840    /// The copy-form status-projection primitive on the phase axis:
841    /// returns the [`AllocationPhase`] the pool reconciler currently
842    /// persists at `status.phase`, wrapped in an `Option` so the
843    /// missing-`status` corner collapses to `None` — the ONE-liner
844    /// collapse of the paired `self.status.as_ref().map(|s| s.phase)`
845    /// incantation the pool reconciler's `AllocationConvergenceCtx::
846    /// observe` restated by hand pre-lift.
847    ///
848    /// Cross-CRD peer to [`crate::prelude::Process::observed_phase`]
849    /// on the (CRD × phase-slot × observed-status) axis pair — both
850    /// primitives walk the identical `.status.as_ref().map(|s| s.
851    /// phase)` shape, differing only in the `Phase` type projected
852    /// ([`AllocationPhase`] vs [`crate::phase::ProcessPhase`]). The
853    /// substrate now owns the borrow-form `.status.as_ref().map(|s|
854    /// s.phase)` chain axis-uniformly across the two `Phase`-having
855    /// CRDs so a future normalization (a generation-filter that
856    /// returns `None` for a phase stamped with a stale
857    /// `metadata.generation`, a staleness gate that drops a phase
858    /// whose observing `phase_since` predates a reconcile deadline,
859    /// a canonicalization pass that maps a phase outside the CRD's
860    /// closed set to `None`) lands at ONE substrate method per CRD
861    /// rather than being restated at every observer.
862    #[must_use]
863    pub fn observed_phase(&self) -> Option<AllocationPhase> {
864        self.status.as_ref().map(|s| s.phase)
865    }
866
867    /// The copy-form status-projection primitive on the phase axis
868    /// with the [`AllocationPhase::Pending`] sink applied — the
869    /// ONE-liner collapse of the paired `self.observed_phase().
870    /// unwrap_or(AllocationPhase::Pending)` incantation the pool
871    /// reconciler's `AllocationConvergenceCtx::observe` restated by
872    /// hand pre-lift as a 5-line `.status.as_ref().map(|s| s.phase).
873    /// unwrap_or(AllocationPhase::Pending)` chain.
874    ///
875    /// Pre-lift the chain sat at [`tatara-pool-reconciler::
876    /// allocation_decide::AllocationConvergenceCtx::observe`]'s
877    /// `phase` seed. Cross-CRD peer to [`crate::prelude::Process::
878    /// observed_phase_or_pending`] on the (CRD × phase-slot × sink)
879    /// axis pair — both primitives close the missing-`status`
880    /// corner with each CRD's respective [`Default`]-equivalent
881    /// `Pending` variant, and both compose on top of their peer
882    /// [`Self::observed_phase`] / [`crate::prelude::Process::
883    /// observed_phase`] borrow-form projections so a future
884    /// normalization at the underlying `observed_phase` primitive
885    /// reaches both the raw-`Option` accessor and the `Pending`-
886    /// sinked composer through the SAME upstream body.
887    ///
888    /// The [`AllocationPhase::Pending`] sink is load-bearing as the
889    /// "not yet observed" default — the pool reconciler's typed
890    /// `AllocationPhase::needs_pool_routing` predicate returns
891    /// `true` for `Pending`, so a freshly-admitted Allocation whose
892    /// pool reconciler has not yet stamped a `.status` slot reads
893    /// as `Pending` and immediately enters the routing ladder,
894    /// matching the pre-lift `AllocationPhase::Pending` fallback
895    /// semantics verbatim.
896    ///
897    /// Theory anchor: THEORY.md §VI.1 (generation over composition
898    /// — the two-link `.status.as_ref().map(|s| s.phase).unwrap_or
899    /// (AllocationPhase::Pending)` chain recurred at both the
900    /// [`crate::prelude::Process`] site (already lifted onto
901    /// [`crate::prelude::Process::observed_phase_or_pending`]) AND
902    /// the [`EphemeralAllocation`] site by hand, i.e. the SHAPE
903    /// itself recurs past the ★★ PRIME-DIRECTIVE ≥ 2 duplication
904    /// trigger, and is lifted to ONE owner per CRD here). THEORY.md
905    /// §II.1 invariant 5 (composition preserves proofs — the pins
906    /// bind the missing-`status` sink to `Pending` + populated-
907    /// status pass-through + every [`AllocationPhase`] variant
908    /// round-trip + byte-identical parity with the pre-lift
909    /// two-link chain + cross-CRD peer coherence with
910    /// [`crate::prelude::Process::observed_phase_or_pending`], so
911    /// a regression that drifted any surface at
912    /// `tests::observed_phase_*` rather than as silent operator-
913    /// facing skew between the allocation observer's routing seed
914    /// and the Process observer's dispatch seed).
915    #[must_use]
916    pub fn observed_phase_or_pending(&self) -> AllocationPhase {
917        self.observed_phase().unwrap_or(AllocationPhase::Pending)
918    }
919
920    /// The borrow-form status-projection primitive on the bound-pool
921    /// axis: returns the [`AllocationRef`] the pool reconciler
922    /// currently persists at `status.bound_pool` (name + namespace of
923    /// the pool that owns the matched member), with the
924    /// missing-`status` corner AND the empty-slot corner BOTH
925    /// collapsed to `None` — the ONE-liner collapse of the paired
926    /// `self.status.as_ref().and_then(|s| s.bound_pool.<clone|as_ref>())`
927    /// incantation the pool reconciler's `AllocationConvergenceCtx::
928    /// observe` restated by hand pre-lift.
929    ///
930    /// Cross-CRD peer to [`crate::prelude::Process::observed_identity`]
931    /// on the (CRD × structured-record-slot × borrow-form) axis pair
932    /// — both primitives walk the identical `.status.as_ref()
933    /// .and_then(|s| s.<slot>.as_ref())` shape, differing only in the
934    /// record projected ([`AllocationRef`] here, [`crate::identity::
935    /// Identity`] on `Process`). The substrate now owns the
936    /// borrow-form `.status.as_ref().and_then(|s| s.<slot>.as_ref())`
937    /// chain on the second `structured-record` slot across the two
938    /// `status`-having CRDs, so a future normalization step (a
939    /// generation-filter that returns `None` for a bound-pool
940    /// reference stamped with a stale `metadata.generation`, a
941    /// canonicalization pass that rejects a malformed
942    /// `(name, namespace)` pair, a cross-cluster reference-rewrite
943    /// gate) lands at ONE substrate method per CRD rather than being
944    /// restated at every observer.
945    ///
946    /// Return-form axis: `Option<&AllocationRef>` mirrors the
947    /// borrow-first discipline of [`crate::prelude::Process::
948    /// observed_identity`]. The lone pre-lift consumer
949    /// ([`tatara-pool-reconciler::allocation_decide::
950    /// AllocationConvergenceCtx::observe`]'s `bound_pool` seed) spelled
951    /// the projection as `.and_then(|s| s.bound_pool.clone())` — an
952    /// eager clone allocated inside every reconcile pass even when the
953    /// downstream branch (the Release-composition arm) needed only the
954    /// borrow for the `.as_ref()` re-projection two lines later.
955    /// Post-lift the consumer reaches the primitive borrow-first
956    /// (`alloc.observed_bound_pool().cloned()`) and the empty-borrow
957    /// corner clones nothing (`Option::cloned` on `None` is `None`);
958    /// the composition point where the owned `AllocationRef` fallback
959    /// is required (the `AllocationConvergenceCtx` snapshot slot,
960    /// still `Option<AllocationRef>`-typed for serde stability) is the
961    /// ONLY site that materializes an owned copy.
962    ///
963    /// The missing-`status` corner AND the populated-status-with-
964    /// `bound_pool=None` corner BOTH collapse to `None` so
965    /// `.is_some()` / `if let Some(_)` / `.cloned()` behave
966    /// identically on an `EphemeralAllocation` whose status field is
967    /// `None` and on one whose status carries an unpopulated
968    /// `bound_pool` slot — matching what the pre-lift `.and_then(...)`
969    /// chain produced. Consumers that need to tell those corners
970    /// apart reach for [`Self::status`] directly, exactly as the
971    /// existing peer accessors [`Self::observed_phase`] +
972    /// [`Self::observed_phase_or_pending`] admit.
973    ///
974    /// Theory anchor: THEORY.md §VI.1 (generation over composition
975    /// — the `.status.as_ref().and_then(|s| s.<structured-record>
976    /// .<clone|as_ref>())` shape recurred as ONE hand-authored
977    /// `.and_then(|s| s.bound_pool.clone())` chain in
978    /// [`tatara-pool-reconciler::allocation_decide::
979    /// AllocationConvergenceCtx::observe`] AND as the peer
980    /// [`crate::prelude::Process::observed_identity`] primitive
981    /// already owned on the `Process` CRD's `status.identity` slot,
982    /// past the ★★ PRIME-DIRECTIVE ≥ 2 duplication trigger at
983    /// substrate-shape level. THEORY.md §II.1 invariant 5
984    /// (composition preserves proofs — the pins bind the missing-
985    /// `status` corner + the empty-`bound_pool`-slot corner + the
986    /// borrow-form `&AllocationRef` lifetime + the zero-copy
987    /// projection contract + byte-identical parity with the pre-lift
988    /// `.and_then(|s| s.bound_pool.clone())` chain across the full
989    /// corner set + cross-CRD peer coherence with
990    /// [`crate::prelude::Process::observed_identity`], so a
991    /// regression that drifted any surface at
992    /// `tests::observed_bound_pool_*` rather than as silent operator-
993    /// facing skew between the allocation observer's Release-
994    /// composition seed and the Process observer's FORK-time
995    /// identity seed on the SAME reconcile tick).
996    #[must_use]
997    pub fn observed_bound_pool(&self) -> Option<&AllocationRef> {
998        self.status.as_ref().and_then(|s| s.bound_pool.as_ref())
999    }
1000
1001    /// The copy-form status-projection primitive on the TTL-expiry axis:
1002    /// returns the wall-clock deadline the pool reconciler currently
1003    /// persists at `status.expires_at` (derived from `spec.ttl` +
1004    /// `allocated_at` at Bind time), wrapped in an `Option` so both the
1005    /// missing-`status` corner AND the populated-status-with-`expires_at
1006    /// =None` corner collapse to `None` — the ONE-liner collapse of the
1007    /// paired `self.status.as_ref().and_then(|s| s.expires_at)`
1008    /// incantation the pool reconciler's `AllocationConvergenceCtx::
1009    /// observe` restated by hand pre-lift.
1010    ///
1011    /// Same-CRD peer to [`Self::observed_phase`] on the (CRD × copy-form
1012    /// × status-slot) axis pair — both primitives walk the identical
1013    /// `.status.as_ref().<map|and_then>(|s| s.<Copy-field>)` shape,
1014    /// differing only in the record projected ([`DateTime<Utc>`] here,
1015    /// [`AllocationPhase`] on the phase axis) and in the outer combinator
1016    /// (`and_then` here because the persisted field is itself an
1017    /// `Option<DateTime<Utc>>`, `map` there because the persisted phase
1018    /// is bare). The substrate now owns the copy-form
1019    /// `.status.as_ref().<map|and_then>(|s| s.<Copy-field>)` chain
1020    /// axis-uniformly across every `Copy`-valued slot on
1021    /// `AllocationStatus`, so a future normalization (a clock-skew
1022    /// guard that drops an `expires_at` stamped before its owning
1023    /// allocation's observed `allocated_at`, a canonicalization pass
1024    /// that clamps a deadline to a monotonic upper bound, a stale-
1025    /// timestamp gate that returns `None` on an `expires_at` older than
1026    /// a controller-configured horizon) lands at ONE substrate method
1027    /// rather than being restated at every observer.
1028    ///
1029    /// Return-form axis: `Option<DateTime<Utc>>` mirrors the copy-first
1030    /// discipline of [`Self::observed_phase`]. The lone pre-lift consumer
1031    /// ([`tatara-pool-reconciler::allocation_decide::
1032    /// AllocationConvergenceCtx::observe`]'s `expires_at` seed) spelled
1033    /// the projection as `.status.as_ref().and_then(|s| s.expires_at)` —
1034    /// a 3-link hand-authored chain the observer walked on every
1035    /// reconcile pass. Post-lift the consumer reaches the primitive
1036    /// once and the whole missing-status + empty-slot corner cross
1037    /// collapses at the substrate rather than at the callsite.
1038    ///
1039    /// The missing-`status` corner AND the populated-status-with-
1040    /// `expires_at=None` corner BOTH collapse to `None` so
1041    /// `.is_some()` / `if let Some(_)` / any `>=` deadline comparison
1042    /// behave identically on an `EphemeralAllocation` whose status
1043    /// field is `None` and on one whose status carries an unpopulated
1044    /// `expires_at` slot — matching what the pre-lift `.and_then(...)`
1045    /// chain produced. Consumers that need to tell those corners apart
1046    /// reach for [`Self::status`] directly, exactly as the existing peer
1047    /// accessors [`Self::observed_phase`] +
1048    /// [`Self::observed_phase_or_pending`] admit.
1049    ///
1050    /// Theory anchor: THEORY.md §VI.1 (generation over composition —
1051    /// the `.status.as_ref().and_then(|s| s.<Copy-field>)` shape
1052    /// recurred as ONE hand-authored chain in
1053    /// [`tatara-pool-reconciler::allocation_decide::
1054    /// AllocationConvergenceCtx::observe`] AND as the copy-form peer
1055    /// [`Self::observed_phase`] primitive already owned on the same
1056    /// CRD's `status.phase` slot, past the substrate-shape recurrence
1057    /// trigger; the substrate now owns the third status-projection
1058    /// primitive on `EphemeralAllocation`, closing the copy-form family
1059    /// alongside the borrow-form [`Self::observed_bound_pool`]).
1060    /// THEORY.md §II.1 invariant 5 (composition preserves proofs — the
1061    /// pins bind the missing-`status` corner + the empty-`expires_at`-
1062    /// slot corner + the copy-form `DateTime<Utc>` return + byte-
1063    /// identical parity with the pre-lift `.and_then(|s| s.expires_at)`
1064    /// chain across the full corner set, so a regression that drifted
1065    /// any surface surfaces at `tests::observed_expires_at_*` rather
1066    /// than as silent operator-facing skew between the allocation
1067    /// observer's Release-composition TTL gate and any future consumer
1068    /// that reaches for the same slot).
1069    #[must_use]
1070    pub fn observed_expires_at(&self) -> Option<DateTime<Utc>> {
1071        self.status.as_ref().and_then(|s| s.expires_at)
1072    }
1073
1074    /// The namespaced-CRD constructor composer on the
1075    /// `EphemeralAllocation` axis: forwards `(name, spec)` to the
1076    /// kube-derived [`Self::new`] constructor + stamps
1077    /// `metadata.namespace` with the caller-supplied slot in ONE
1078    /// step. The ONE-liner collapse of the paired `let mut a =
1079    /// EphemeralAllocation::new(<name>, <spec>); a.meta_mut().
1080    /// namespace = Some(<ns>.into());` incantation every allocation-
1081    /// side emitter restated by hand pre-lift.
1082    ///
1083    /// Pre-lift the 2-line construct-then-set-namespace chain was
1084    /// hand-authored at TWO sites past the ★★ PRIME-DIRECTIVE ≥ 2
1085    /// duplication threshold across TWO workspace crates, composing
1086    /// a namespaced `EphemeralAllocation` fixture / event from a
1087    /// `name` slot and an `AllocationSpec`:
1088    /// * `tatara-github-watcher::allocation_factory::build_allocation`
1089    ///   — the production PR-webhook → `EphemeralAllocation` emitter
1090    ///   at `alloc.meta_mut().namespace = Some(namespace.to_string
1091    ///   ())`; stamps the ephemeral-pools namespace as part of the
1092    ///   canonical opened / reopened / synchronize allocation shape.
1093    /// * `tatara-pool-reconciler::allocation_decide::tests::alloc` —
1094    ///   the allocation-decision test fixture pinned to `"pools"`,
1095    ///   sibling to the peer `pool` fixture in the same module that
1096    ///   composes an `EphemeralPool` via [`crate::pool::EphemeralPool::
1097    ///   new_in`] on the same `ns` slot value.
1098    ///
1099    /// Both sites walked the SAME 2-line chain and both wanted the
1100    /// `EphemeralAllocation` back with `metadata.namespace` stamped as
1101    /// `Some(<ns>.into())`. Post-lift each callsite reads
1102    /// `EphemeralAllocation::new_in(<name>, <ns>, <spec>)` and the
1103    /// produced value feeds the same downstream `Api::create(&pp,
1104    /// &alloc)` chain / test-battery input unchanged.
1105    ///
1106    /// The `impl Into<String>` at the `namespace` slot matches the
1107    /// sibling `impl Into<String>`-widening discipline the workspace's
1108    /// other namespaced-CRD-adjacent composers walk
1109    /// ([`crate::pool::PoolMember::unallocated`] on the
1110    /// `process_name` slot, [`crate::pool::AllocationRef::new`] on the
1111    /// `(name, namespace)` slot pair, [`Requestor::kind_only`] on the
1112    /// `kind` slot) and accepts BOTH `&'static str` (the majority
1113    /// pre-lift caller shape) AND owned `String` at the SAME
1114    /// signature.
1115    ///
1116    /// Peer to [`crate::pool::EphemeralPool::new_in`] on the sister
1117    /// `EphemeralPool` CRD — the two primitives partition the
1118    /// namespaced-CRD-constructor family axis for the two pool-
1119    /// adjacent CRDs the workspace stamps at reconciler fixture /
1120    /// GitHub-webhook-emitter time. A future normalization (a per-
1121    /// fleet virtual-cluster prefix rewrite on the `namespace` slot,
1122    /// a per-cluster canonical case-fold pass, a `generateName`
1123    /// fallback on the `name` slot, an operator-scoped default
1124    /// namespace for cluster-local test rigs, an audit-tag stamped
1125    /// on every fixture-emitted CRD for post-hoc grep discipline)
1126    /// lands at ONE primitive body per CRD and every downstream
1127    /// consumer inherits the upgrade mechanically.
1128    ///
1129    /// `#[must_use]` on the return keeps a caller from composing the
1130    /// namespaced value and dropping it un-passed to a `kube::Api`
1131    /// create call or a `Vec<EphemeralAllocation>` reconciler-input
1132    /// slot.
1133    ///
1134    /// Theory anchor: THEORY.md §VI.1 (generation over composition —
1135    /// the 2-line construct-then-set-namespace chain recurred at
1136    /// TWO hand-authored sites past the ★★ PRIME-DIRECTIVE ≥ 2
1137    /// duplication trigger, spanning two workspace crates, and is
1138    /// lifted to ONE substrate owner here). THEORY.md §II.1
1139    /// invariant 5 (composition preserves proofs — the pins below
1140    /// bind the (name-slot → metadata.name, ns-slot → metadata.
1141    /// namespace, spec-slot → spec) slot-projection triple + the
1142    /// byte-identical parity with the pre-lift 2-line chain across
1143    /// the two representative `impl Into<String>` value shapes
1144    /// (`&'static str` and owned `String`) + the sibling-composer
1145    /// coherence with [`Self::new`]).
1146    #[must_use]
1147    pub fn new_in(name: &str, namespace: impl Into<String>, spec: AllocationSpec) -> Self {
1148        // Routes through the ONE substrate owner of the
1149        // `metadata.namespace` stamp — the [`crate::PlacedInNamespace`]
1150        // blanket-impl trait over `kube::Resource<DynamicType = ()>`.
1151        // Byte-identical to the pre-lift 3-line body
1152        // (`Self::new(name, spec); metadata.namespace = Some(namespace
1153        // .into())`); the trait-forwarding form collapses the mutation
1154        // duplication with the sibling per-CRD composer
1155        // [`crate::pool::EphemeralPool::new_in`] and with the
1156        // render-fixture site on `Process` that has no per-CRD
1157        // `new_in` sibling.
1158        use crate::PlacedInNamespace;
1159        Self::new(name, spec).in_namespace(namespace)
1160    }
1161}
1162
1163#[cfg(test)]
1164mod tests {
1165    // `FromStr` lives in scope at the test surface only — the derive
1166    // emits `impl ::core::str::FromStr` via the full path so the lib
1167    // body no longer reaches `FromStr` directly, but the cross-axis
1168    // sweeps + the verbatim-echo contract tests call
1169    // `AllocationPhase::from_str(bad)` / `bad.parse::<RequestorKind>()`.
1170    use std::str::FromStr;
1171
1172    use super::*;
1173
1174    #[test]
1175    fn requestor_minimum_shape_round_trips() {
1176        let r = Requestor {
1177            kind: "github-pr".into(),
1178            repo: Some("pleme-io/demo-app".into()),
1179            branch: Some("fix-something".into()),
1180            pr_number: Some(123),
1181            sha: Some("abc123def".into()),
1182            pr_labels: vec!["needs-ephemeral".into()],
1183            actor: Some("drzln".into()),
1184        };
1185        let yaml = serde_yaml::to_string(&r).unwrap();
1186        assert!(yaml.contains("kind: github-pr"));
1187        assert!(yaml.contains("prNumber: 123"));
1188        let back: Requestor = serde_yaml::from_str(&yaml).unwrap();
1189        assert_eq!(back.kind, "github-pr");
1190        assert_eq!(back.pr_number, Some(123));
1191    }
1192
1193    #[test]
1194    fn allocation_status_defaults_pending() {
1195        let s = AllocationStatus::default();
1196        assert_eq!(s.phase, AllocationPhase::Pending);
1197        assert!(s.bound_pool.is_none());
1198        assert!(s.assigned_process.is_none());
1199    }
1200
1201    #[test]
1202    fn allocation_phase_round_trips_via_serde() {
1203        for p in [
1204            AllocationPhase::Pending,
1205            AllocationPhase::Queued,
1206            AllocationPhase::Bound,
1207            AllocationPhase::Releasing,
1208            AllocationPhase::Released,
1209            AllocationPhase::NoMatchingPool,
1210            AllocationPhase::Failed,
1211        ] {
1212            let s = serde_yaml::to_string(&p).unwrap();
1213            let back: AllocationPhase = serde_yaml::from_str(&s).unwrap();
1214            assert_eq!(back, p);
1215        }
1216    }
1217
1218    // ── closed-set algebra contracts for AllocationPhase
1219    //    (ALL × as_str × FromStr × predicate-pair) ────────────────────
1220
1221    /// `ALL` is the source of truth — pin its closure so a variant
1222    /// added without an `ALL` entry fails here via the uniqueness
1223    /// check before drifting `FromStr` or the sweep tests below. The
1224    /// arity is asserted by the `[Self; 7]` array type itself.
1225    ///
1226    /// Structural well-formedness of [`AllocationPhase`] as a
1227    /// [`tatara_lisp::ClosedSet`] implementor — the workspace-wide
1228    /// testkit lift that pins all three structural invariants
1229    /// (`ALL` is non-empty, every variant round-trips through
1230    /// `label ↔ parse_label`, labels are pairwise distinct, `""` is
1231    /// outside the closed set) at ONE call site. Replaces the hand-
1232    /// derived `allocation_phase_all_is_unique_and_complete` +
1233    /// `allocation_phase_roundtrip_via_as_str` + the empty-input arm
1234    /// of `unknown_allocation_phase_errors`. `FromStr` delegates to
1235    /// `<Self as tatara_closed_set::ClosedSet>::parse_label`, so this
1236    /// helper exercises the same code path the allocation reconciler
1237    /// hits when parsing a CRD `enum:`-validated value back to the
1238    /// typed phase.
1239    #[test]
1240    fn allocation_phase_is_well_formed_closed_set() {
1241        tatara_closed_set::assert_closed_set_well_formed::<AllocationPhase>();
1242    }
1243
1244    /// CANONICAL-KEY CONTRACT: `as_str` matches serde's PascalCase
1245    /// output verbatim for every variant. A future variant rename
1246    /// (or an `as_str` arm typo) lands here at one site, instead of
1247    /// drifting between the typed surface, the CRD enum, the YAML
1248    /// wire format, and the operator-facing reason strings the
1249    /// reconciler stamps via Display.
1250    #[test]
1251    fn allocation_phase_as_str_matches_serde() {
1252        crate::tagged_union::assert_label_matches_serde_serialization::<AllocationPhase>();
1253    }
1254
1255    /// The Display impl IS `as_str` — pinning this lets future
1256    /// callers reach for either projection without drift.
1257    #[test]
1258    fn allocation_phase_display_matches_as_str() {
1259        crate::tagged_union::assert_display_matches_label::<AllocationPhase>();
1260    }
1261
1262    /// `FromStr` rejects strings that aren't in the canonical
1263    /// projection — lowercased / typo / unrelated — and the error
1264    /// echoes the input verbatim so the operator-facing diagnostic
1265    /// carries the offending value, not a normalized form. The
1266    /// empty-input arm is pinned by
1267    /// [`allocation_phase_is_well_formed_closed_set`] via the
1268    /// `tatara_lisp::ClosedSet` testkit; the cases here pin the
1269    /// verbatim-echo contract on the [`UnknownAllocationPhase`]
1270    /// newtype, which the trait's `make_unknown` can't see.
1271    #[test]
1272    fn unknown_allocation_phase_errors() {
1273        for bad in [
1274            "pending",
1275            "BOUND",
1276            "no-matching-pool",
1277            "release",
1278            "failed_state",
1279            "Reaped",
1280        ] {
1281            let err = AllocationPhase::from_str(bad).unwrap_err();
1282            assert_eq!(err.0, bad, "error payload should echo input verbatim");
1283        }
1284    }
1285
1286    /// TRUTH-TABLE CONTRACT: the predicate pair agrees with the
1287    /// documented per-variant disposition. `Released` + `Failed` are
1288    /// terminal (absorbing); `Pending` / `Queued` / `NoMatchingPool`
1289    /// need pool routing; `Bound` / `Releasing` are settled-but-not-
1290    /// terminal (heartbeat / release ladder).
1291    #[test]
1292    fn allocation_phase_predicate_truth_tables() {
1293        assert!(!AllocationPhase::Pending.is_terminal());
1294        assert!(AllocationPhase::Pending.needs_pool_routing());
1295
1296        assert!(!AllocationPhase::Queued.is_terminal());
1297        assert!(AllocationPhase::Queued.needs_pool_routing());
1298
1299        assert!(!AllocationPhase::Bound.is_terminal());
1300        assert!(!AllocationPhase::Bound.needs_pool_routing());
1301
1302        assert!(!AllocationPhase::Releasing.is_terminal());
1303        assert!(!AllocationPhase::Releasing.needs_pool_routing());
1304
1305        assert!(AllocationPhase::Released.is_terminal());
1306        assert!(!AllocationPhase::Released.needs_pool_routing());
1307
1308        assert!(!AllocationPhase::NoMatchingPool.is_terminal());
1309        assert!(AllocationPhase::NoMatchingPool.needs_pool_routing());
1310
1311        assert!(AllocationPhase::Failed.is_terminal());
1312        assert!(!AllocationPhase::Failed.needs_pool_routing());
1313    }
1314
1315    /// IMPLICATION CONTRACT: `is_terminal → !needs_pool_routing`. A
1316    /// terminal allocation cannot also be routing-eligible — that's
1317    /// the bug the typed projection closes (a `Failed` allocation
1318    /// that's neither `Released` nor `Bound` would otherwise slip
1319    /// through the open-coded gate in `observe` and try to rebind to
1320    /// a pool member). A future variant that flipped both predicates
1321    /// true would fail here, forcing the author to flip one or
1322    /// extend the consumer dispatch site in
1323    /// `tatara-pool-reconciler::allocation_decide` deliberately
1324    /// rather than letting an impossible state slip in.
1325    #[test]
1326    fn allocation_phase_terminal_excludes_routing() {
1327        for phase in AllocationPhase::ALL {
1328            assert!(
1329                !(phase.is_terminal() && phase.needs_pool_routing()),
1330                "{phase:?} is both terminal and routing-eligible",
1331            );
1332        }
1333    }
1334
1335    /// DEFAULT-AGREEMENT CONTRACT: `AllocationPhase::default()` is
1336    /// `Pending` — the entry state, neither terminal nor settled —
1337    /// and it lives on the routing path. A future default-variant
1338    /// rename without flipping the predicates fails here.
1339    #[test]
1340    fn allocation_phase_default_is_pending_and_routes() {
1341        let d = AllocationPhase::default();
1342        assert_eq!(d, AllocationPhase::Pending);
1343        assert!(!d.is_terminal());
1344        assert!(d.needs_pool_routing());
1345    }
1346
1347    // ── RequestorKind closed-set truth-table ─────────────────────────
1348
1349    /// Structural well-formedness of [`RequestorKind`] as a
1350    /// [`tatara_lisp::ClosedSet`] implementor — the workspace-wide
1351    /// testkit lift that pins all three structural invariants
1352    /// (`ALL` is non-empty, every variant round-trips through
1353    /// `label ↔ parse_label`, labels are pairwise distinct, `""` is
1354    /// outside the closed set) at ONE call site. Replaces the hand-
1355    /// derived `requestor_kind_all_enumerates_each_variant_exactly_once`
1356    /// + `requestor_kind_from_str_round_trips_canonical_names` + the
1357    /// empty-input arm of `requestor_kind_from_str_rejects_open_kinds`.
1358    /// `FromStr` delegates to
1359    /// `<Self as tatara_closed_set::ClosedSet>::parse_label`, so this helper
1360    /// exercises the same code path
1361    /// [`Requestor::known_kind`]'s `Option<RequestorKind>` collapse
1362    /// rides on when classifying inbound `Requestor.kind` strings. The
1363    /// arity is asserted by the `[Self; 4]` array type itself.
1364    #[test]
1365    fn requestor_kind_is_well_formed_closed_set() {
1366        tatara_closed_set::assert_closed_set_well_formed::<RequestorKind>();
1367    }
1368
1369    /// Byte-exact wire-format pin — renaming any of these is a wire-
1370    /// format change (the `tatara-github-watcher` emitter, the CRD
1371    /// printcolumns, the `PoolSelector.kinds` filter strings, the
1372    /// per-test `kind: "…".into()` fixtures all depend on these
1373    /// literals), not a typed-internal refactor.
1374    #[test]
1375    fn requestor_kind_canonical_names_pinned() {
1376        assert_eq!(RequestorKind::GithubPr.as_str(), "github-pr");
1377        assert_eq!(RequestorKind::Manual.as_str(), "manual");
1378        assert_eq!(RequestorKind::CiRun.as_str(), "ci-run");
1379        assert_eq!(RequestorKind::Scheduled.as_str(), "scheduled");
1380    }
1381
1382    /// `FromStr` rejects strings that aren't in the canonical
1383    /// projection — lowercased-mismatch / typo / unrelated — and the
1384    /// error echoes the input verbatim so the operator-facing
1385    /// diagnostic carries the offending value, not a normalized form.
1386    /// The schema is open at the wire layer (operators MAY register
1387    /// new kinds and `Requestor::known_kind` collapses them to
1388    /// `None`), but the closed-set view is byte-exact. The empty-input
1389    /// arm is pinned by [`requestor_kind_is_well_formed_closed_set`]
1390    /// via the `tatara_lisp::ClosedSet` testkit; the cases here pin
1391    /// the verbatim-echo contract on the [`UnknownRequestorKind`]
1392    /// newtype, which the trait's `make_unknown` can't see.
1393    #[test]
1394    fn requestor_kind_from_str_rejects_open_kinds() {
1395        for bad in [
1396            "github_pr",
1397            "GithubPr",
1398            "operator-custom-kind",
1399            "ci_run",
1400            "Scheduled",
1401        ] {
1402            let err = bad.parse::<RequestorKind>().unwrap_err();
1403            assert_eq!(err, UnknownRequestorKind(bad.to_string()));
1404        }
1405    }
1406
1407    /// The Display impl IS `as_str` — pinning this lets future
1408    /// callers reach for either projection without drift (Display is
1409    /// what operator-facing diagnostics compose against).
1410    #[test]
1411    fn requestor_kind_display_delegates_to_as_str() {
1412        for k in RequestorKind::ALL {
1413            assert_eq!(format!("{k}"), k.as_str());
1414        }
1415    }
1416
1417    /// The `String` projection that `From<RequestorKind> for String`
1418    /// ([`RequestorKind::into`]) composes is byte-equal to `as_str`.
1419    /// This is the typed → wire bridge — emitters spell
1420    /// `kind: RequestorKind::GithubPr.into()` and the canonical
1421    /// literal is materialized at ONE place.
1422    #[test]
1423    fn requestor_kind_into_string_matches_as_str() {
1424        for k in RequestorKind::ALL {
1425            let s: String = k.into();
1426            assert_eq!(s, k.as_str());
1427        }
1428    }
1429
1430    /// The typed → wire → typed round-trip: composing a `Requestor`
1431    /// with `kind: RequestorKind::X.into()` produces an object whose
1432    /// `known_kind()` decodes back to `X`. Pins the bridge invariant
1433    /// at the `Requestor` boundary, not just at `RequestorKind`.
1434    #[test]
1435    fn known_kind_decodes_built_requestors() {
1436        for k in RequestorKind::ALL {
1437            // Routes through the ONE substrate composer
1438            // `Requestor::kind_only` — one of TEN pre-lift exact-match
1439            // sites past the ★★ PRIME-DIRECTIVE ≥ 2 threshold.
1440            let r = Requestor::kind_only(k);
1441            assert_eq!(r.known_kind(), Some(k), "round-trip failed for {k:?}");
1442        }
1443    }
1444
1445    /// Open-by-design: a custom operator-registered kind still
1446    /// stamps a valid `Requestor` (no schema rejection), it just
1447    /// doesn't project through the closed-set typed view. Mirrors
1448    /// `ReceiptEnvelope::known_kind`'s open-kind posture.
1449    #[test]
1450    fn known_kind_returns_none_for_open_kinds() {
1451        // Routes through the ONE substrate composer
1452        // `Requestor::kind_only` — one of TEN pre-lift exact-match
1453        // sites past the ★★ PRIME-DIRECTIVE ≥ 2 threshold.
1454        let r = Requestor::kind_only("operator-custom-kind");
1455        assert_eq!(r.known_kind(), None);
1456    }
1457
1458    /// The four canonical literals match every previously-published
1459    /// fixture / doc anchor in this crate — pinning the bridge to
1460    /// existing call sites so any drift fails here before the next
1461    /// release ships.
1462    #[test]
1463    fn requestor_kind_matches_existing_fixture_literals() {
1464        // The `requestor_minimum_shape_round_trips` fixture above
1465        // composes `kind: "github-pr".into()` verbatim.
1466        assert_eq!(RequestorKind::GithubPr.as_str(), "github-pr");
1467        // The `allocation_spec_omits_optional_fields` fixture below
1468        // composes `kind: "manual".into()` verbatim.
1469        assert_eq!(RequestorKind::Manual.as_str(), "manual");
1470    }
1471
1472    // ─── Requestor::kind_only substrate pins ────────────────────────
1473    //
1474    // Fail-before-pass-after granularity: `Requestor::kind_only` did
1475    // not exist before this commit. The composer's job is to bind ONE
1476    // caller-varying slot (`kind`) and freeze the six-slot default
1477    // tail so a future addition to `Requestor` lands at ONE primitive
1478    // body rather than at every fixture / default-shape callsite.
1479    // Sibling to the `AplicacaoIntent::chart_only` pin family (the
1480    // 7-slot chart-pointer-only composer) and the `PoolSpec::with_template`
1481    // pin family (the 11-slot pool full-spec composer).
1482
1483    #[test]
1484    fn kind_only_binds_kind_slot_and_defaults_the_other_six() {
1485        // Positional-binding pin: the sole caller slot lands at
1486        // `kind`; every other slot lands at its safe empty default
1487        // (`None` / `vec![]`).
1488        let r = Requestor::kind_only("manual");
1489        assert_eq!(r.kind, "manual");
1490        assert!(r.repo.is_none());
1491        assert!(r.branch.is_none());
1492        assert!(r.pr_number.is_none());
1493        assert!(r.sha.is_none());
1494        assert!(r.pr_labels.is_empty());
1495        assert!(r.actor.is_none());
1496    }
1497
1498    #[test]
1499    fn kind_only_matches_hand_authored_pre_lift_struct_literal_shape() {
1500        // Byte-identity pin: every pre-lift `Requestor { kind: <lit>
1501        // .into(), repo: None, branch: None, pr_number: None, sha:
1502        // None, pr_labels: vec![], actor: None }` shape must
1503        // deserialize back to the same fixture composed via
1504        // `kind_only`. Sweeps the two families every callsite used
1505        // (`"manual"` — the operator-authored fixture at seven
1506        // sites; `"github-pr"` — the github-webhook fixture at three
1507        // sites) plus one open-kind sample (`"operator-custom-kind"` —
1508        // the `known_kind_returns_none_for_open_kinds` open-kind pin)
1509        // so any drift between the primitive and the pre-lift shape
1510        // surfaces at ONE pin rather than as silent fixture skew at
1511        // ten downstream consumers.
1512        for kind in ["manual", "github-pr", "operator-custom-kind"] {
1513            let via_primitive = Requestor::kind_only(kind);
1514            let hand_authored = Requestor {
1515                kind: kind.into(),
1516                repo: None,
1517                branch: None,
1518                pr_number: None,
1519                sha: None,
1520                pr_labels: vec![],
1521                actor: None,
1522            };
1523            let via_yaml = serde_yaml::to_string(&via_primitive).unwrap();
1524            let hand_yaml = serde_yaml::to_string(&hand_authored).unwrap();
1525            assert_eq!(
1526                via_yaml, hand_yaml,
1527                "kind_only({kind:?}) must be YAML-identical to the pre-lift struct literal"
1528            );
1529        }
1530    }
1531
1532    #[test]
1533    fn kind_only_accepts_string_and_str_and_requestor_kind_uniformly() {
1534        // `impl Into<String>` symmetry across the three caller shapes
1535        // pre-lift authors used verbatim: `&'static str` (`"manual"`),
1536        // owned `String` (from a formatted context), and
1537        // [`RequestorKind`] (via the `From<RequestorKind> for String`
1538        // bridge exercised at `known_kind_decodes_built_requestors`).
1539        let from_str_literal = Requestor::kind_only("manual");
1540        let from_owned_string = Requestor::kind_only(String::from("manual"));
1541        let from_typed_variant = Requestor::kind_only(RequestorKind::Manual);
1542        assert_eq!(from_str_literal.kind, "manual");
1543        assert_eq!(from_owned_string.kind, "manual");
1544        assert_eq!(from_typed_variant.kind, "manual");
1545    }
1546
1547    #[test]
1548    fn kind_only_composes_downstream_through_known_kind_projection() {
1549        // Cross-primitive coherence pin: every substrate-emitted
1550        // `RequestorKind` variant round-trips through `kind_only` +
1551        // `known_kind` back to the same typed variant. Byte-identical
1552        // to the `known_kind_decodes_built_requestors` sweep the
1553        // primitive replaced — pins the primitive as the composer the
1554        // typed decoder sees the SAME wire shape from.
1555        for k in RequestorKind::ALL {
1556            let r = Requestor::kind_only(k);
1557            assert_eq!(
1558                r.known_kind(),
1559                Some(k),
1560                "kind_only({k:?}).known_kind() must round-trip to Some({k:?})"
1561            );
1562        }
1563    }
1564
1565    // Per-implementor `unknown_X_message_matches_substrate_convention`
1566    // tests removed — clause (5) of
1567    // `tatara_closed_set::assert_closed_set_well_formed::<T>()` now verifies
1568    // the substrate-wide `"unknown {SET_LABEL}: {input}"` carrier shape
1569    // generically (called above on `RequestorKind` /
1570    // `AllocationPhase` through their `*_is_well_formed_closed_set`
1571    // sites). The `SET_LABEL` projection is pinned independently by
1572    // `tatara_lisp_derive::pascal_to_spaced_lowercase_tests` —
1573    // together the two contracts guarantee the operator-facing
1574    // diagnostic without needing per-enum literal pins.
1575
1576    // ─── EphemeralAllocation::observed_phase* substrate pins ────────
1577    //
1578    // Fail-before-pass-after granularity: neither `observed_phase` nor
1579    // `observed_phase_or_pending` existed before this commit, so each
1580    // pin fails to compile until the corresponding inherent method
1581    // lands. Post-lift the pins bind the missing-`status` corner + the
1582    // populated-status pass-through + byte-identical parity with the
1583    // pre-lift 5-line `.status.as_ref().map(|s| s.phase).unwrap_or
1584    // (AllocationPhase::Pending)` chain the pool reconciler's
1585    // `AllocationConvergenceCtx::observe` walked. Cross-CRD peer
1586    // coherence with `Process::observed_phase_or_pending` is pinned
1587    // by the `_matches_process_peer_shape` sweep at the tail.
1588
1589    fn alloc_with_phase(phase: AllocationPhase) -> EphemeralAllocation {
1590        // AllocationSpec rides through the ONE substrate composer
1591        // `AllocationSpec::requestor_only`; the inner Requestor rides
1592        // through the peer composer `Requestor::kind_only`. Nine pre-
1593        // lift exact-match `AllocationSpec { pool_ref: None,
1594        // requestor: <r>, ttl: None, note: None }` fixture sites past
1595        // the ★★ PRIME-DIRECTIVE ≥ 2 threshold collapse onto this
1596        // ONE substrate owner.
1597        let spec = AllocationSpec::requestor_only(Requestor::kind_only("manual"));
1598        let mut a = EphemeralAllocation::new("obs-alloc", spec);
1599        a.status = Some(AllocationStatus {
1600            phase,
1601            ..AllocationStatus::default()
1602        });
1603        a
1604    }
1605
1606    fn alloc_without_status() -> EphemeralAllocation {
1607        // AllocationSpec rides through `AllocationSpec::requestor_only`
1608        // — sibling to `alloc_with_phase`.
1609        let spec = AllocationSpec::requestor_only(Requestor::kind_only("manual"));
1610        let mut a = EphemeralAllocation::new("no-status-alloc", spec);
1611        a.status = None;
1612        a
1613    }
1614
1615    #[test]
1616    fn observed_phase_returns_none_when_status_is_none() {
1617        let a = alloc_without_status();
1618        assert!(a.observed_phase().is_none());
1619    }
1620
1621    #[test]
1622    fn observed_phase_returns_populated_variant_verbatim() {
1623        for p in AllocationPhase::ALL {
1624            let a = alloc_with_phase(p);
1625            assert_eq!(
1626                a.observed_phase(),
1627                Some(p),
1628                "observed_phase must project the persisted variant verbatim for {p:?}"
1629            );
1630        }
1631    }
1632
1633    #[test]
1634    fn observed_phase_matches_pre_lift_chain_bytewise() {
1635        // Sweep every corner: (status: None) plus every populated
1636        // (status: Some(phase)) variant. The pre-lift chain was
1637        // `alloc.status.as_ref().map(|s| s.phase)` — a 3-link chain
1638        // hand-authored inline at the observer. The primitive must
1639        // return the same `Option<AllocationPhase>` on every corner.
1640        let none_alloc = alloc_without_status();
1641        assert_eq!(
1642            none_alloc.observed_phase(),
1643            none_alloc.status.as_ref().map(|s| s.phase),
1644        );
1645        for p in AllocationPhase::ALL {
1646            let a = alloc_with_phase(p);
1647            assert_eq!(
1648                a.observed_phase(),
1649                a.status.as_ref().map(|s| s.phase),
1650                "primitive must be byte-identical to the pre-lift chain for {p:?}",
1651            );
1652        }
1653    }
1654
1655    #[test]
1656    fn observed_phase_or_pending_defaults_to_pending_when_status_absent() {
1657        let a = alloc_without_status();
1658        assert_eq!(a.observed_phase_or_pending(), AllocationPhase::Pending);
1659    }
1660
1661    #[test]
1662    fn observed_phase_or_pending_returns_populated_phase_verbatim() {
1663        for p in AllocationPhase::ALL {
1664            let a = alloc_with_phase(p);
1665            assert_eq!(
1666                a.observed_phase_or_pending(),
1667                p,
1668                "populated status must pass through verbatim for {p:?}"
1669            );
1670        }
1671    }
1672
1673    #[test]
1674    fn observed_phase_or_pending_defaults_agree_with_allocation_phase_default() {
1675        // The `Pending` sink is load-bearing as the "not yet observed"
1676        // default. `AllocationPhase::default()` returns `Pending`; the
1677        // primitive must return the same variant on the missing-status
1678        // corner. A future default-variant rename that flipped
1679        // `AllocationPhase::default` without flipping the primitive
1680        // (or vice versa) surfaces here as a divergent seed for the
1681        // routing ladder.
1682        let a = alloc_without_status();
1683        assert_eq!(a.observed_phase_or_pending(), AllocationPhase::default());
1684    }
1685
1686    #[test]
1687    fn observed_phase_or_pending_matches_pre_lift_chain_bytewise() {
1688        // The exact pre-lift 5-line chain in
1689        // `tatara-pool-reconciler::allocation_decide::
1690        // AllocationConvergenceCtx::observe` was:
1691        //     let phase = alloc
1692        //         .status
1693        //         .as_ref()
1694        //         .map(|s| s.phase)
1695        //         .unwrap_or(AllocationPhase::Pending);
1696        // Sweep every corner: (status: None) plus every populated
1697        // status variant. The primitive must be byte-identical for
1698        // every corner so the observer's routing decision matches
1699        // bytewise post-lift.
1700        let none_alloc = alloc_without_status();
1701        assert_eq!(
1702            none_alloc.observed_phase_or_pending(),
1703            none_alloc
1704                .status
1705                .as_ref()
1706                .map(|s| s.phase)
1707                .unwrap_or(AllocationPhase::Pending),
1708        );
1709        for p in AllocationPhase::ALL {
1710            let a = alloc_with_phase(p);
1711            assert_eq!(
1712                a.observed_phase_or_pending(),
1713                a.status
1714                    .as_ref()
1715                    .map(|s| s.phase)
1716                    .unwrap_or(AllocationPhase::Pending),
1717                "primitive must be byte-identical to the pre-lift 5-line chain for {p:?}",
1718            );
1719        }
1720    }
1721
1722    #[test]
1723    fn observed_phase_or_pending_composes_from_observed_phase() {
1724        // The composer sits on top of the borrow-form projection —
1725        // `observed_phase_or_pending() == observed_phase().unwrap_or
1726        // (Pending)`. Pinning the composition means a future
1727        // normalization step layered onto `observed_phase` (a
1728        // generation-filter, a staleness gate, a canonicalization
1729        // pass) reaches BOTH the raw-`Option` accessor and the
1730        // `Pending`-sinked composer through the SAME upstream body,
1731        // without needing a per-corner rewrite of the composer.
1732        let none_alloc = alloc_without_status();
1733        assert_eq!(
1734            none_alloc.observed_phase_or_pending(),
1735            none_alloc
1736                .observed_phase()
1737                .unwrap_or(AllocationPhase::Pending),
1738        );
1739        for p in AllocationPhase::ALL {
1740            let a = alloc_with_phase(p);
1741            assert_eq!(
1742                a.observed_phase_or_pending(),
1743                a.observed_phase().unwrap_or(AllocationPhase::Pending),
1744                "composer must ride on top of the borrow-form projection for {p:?}",
1745            );
1746        }
1747    }
1748
1749    #[test]
1750    fn observed_phase_is_a_pure_projection() {
1751        // Reading the phase twice must not mutate the allocation or
1752        // its status slot — pure projection semantics. Also witnesses
1753        // that the accessor doesn't clone / drop the inner `phase`
1754        // (the `Copy` scalar comes out identical on both reads).
1755        let a = alloc_with_phase(AllocationPhase::Bound);
1756        let one = a.observed_phase();
1757        let two = a.observed_phase();
1758        assert_eq!(one, two);
1759        assert!(a.status.is_some(), "projection must not consume the status");
1760    }
1761
1762    #[test]
1763    fn observed_phase_pending_missing_status_and_populated_pending_collapse_to_same_composer_output(
1764    ) {
1765        // A subtle correctness pin: the missing-`status` corner and
1766        // a populated-with-Pending status BOTH read as `Pending`
1767        // through the composer — the observer cannot distinguish the
1768        // two through this accessor. This matches the pre-lift 5-line
1769        // chain's semantics exactly (an operator patching
1770        // `status.phase: Pending` is indistinguishable from a
1771        // freshly-admitted allocation with no status stamped yet).
1772        // The borrow-form `observed_phase` accessor DOES distinguish
1773        // the two, so a caller that needs to tell them apart reaches
1774        // for the raw `Option`.
1775        let none_alloc = alloc_without_status();
1776        let pending_alloc = alloc_with_phase(AllocationPhase::Pending);
1777
1778        assert_eq!(
1779            none_alloc.observed_phase_or_pending(),
1780            pending_alloc.observed_phase_or_pending(),
1781        );
1782        assert_ne!(
1783            none_alloc.observed_phase(),
1784            pending_alloc.observed_phase(),
1785            "borrow-form accessor MUST distinguish missing-status from populated-Pending",
1786        );
1787    }
1788
1789    #[test]
1790    fn observed_phase_or_pending_missing_status_sink_agrees_with_process_peer_shape() {
1791        // Cross-CRD peer-axis coherence with
1792        // `Process::observed_phase_or_pending`. Both primitives walk
1793        // the identical `.status.as_ref().map(|s| s.phase).unwrap_or
1794        // (<Phase>::Pending)` chain differing ONLY in the `Phase`
1795        // type projected. On a missing-status observation, each
1796        // primitive must return its CRD's `Default`-equivalent
1797        // `Pending` variant — for `EphemeralAllocation` that's
1798        // `AllocationPhase::Pending`; for `Process` that's
1799        // `crate::phase::ProcessPhase::Pending`. This pin binds the
1800        // sink-parity structurally so a future rename of either
1801        // default variant surfaces here as a divergent seed for the
1802        // observer's routing / dispatch decision rather than as
1803        // silent drift between the two reconcilers.
1804        let no_status_alloc = alloc_without_status();
1805        assert_eq!(
1806            no_status_alloc.observed_phase_or_pending(),
1807            AllocationPhase::default(),
1808        );
1809        // Peer-axis invariant on the `Process` side — the primitive
1810        // that owns the same shape reads `ProcessPhase::Pending` on
1811        // the missing-status corner via its own inherent method. The
1812        // parity is coordinated at the `Default` seat: both CRDs'
1813        // phase types default to `Pending`, so a rename that broke
1814        // one without the other would fail one of these two
1815        // conjoined assertions.
1816        assert_eq!(AllocationPhase::default(), AllocationPhase::Pending,);
1817        assert_eq!(
1818            crate::phase::ProcessPhase::default(),
1819            crate::phase::ProcessPhase::Pending,
1820        );
1821    }
1822
1823    // ─── EphemeralAllocation::observed_bound_pool substrate pins ────
1824    //
1825    // The borrow-form status-projection primitive on the bound-pool
1826    // axis. Collapses the pre-lift hand-authored `.status.as_ref()
1827    // .and_then(|s| s.bound_pool.clone())` chain in
1828    // `tatara-pool-reconciler::allocation_decide::
1829    // AllocationConvergenceCtx::observe`'s `bound_pool` seed onto the
1830    // ONE substrate primitive. Cross-CRD peer to
1831    // `Process::observed_identity` on the (CRD × structured-record-
1832    // slot × borrow-form) axis pair — both primitives walk the
1833    // identical `.status.as_ref().and_then(|s| s.<slot>.as_ref())`
1834    // shape. Each pin is fail-before-pass-after: `observed_bound_pool`
1835    // did not exist pre-lift, so any test invoking it fails to compile
1836    // pre-lift and passes post-lift.
1837
1838    fn sample_pool_ref(name: &str, ns: &str) -> AllocationRef {
1839        // Fixture ref rides through the ONE substrate composer
1840        // `AllocationRef::new` — the `impl Into<String>` signature
1841        // accepts the borrow-form `&str` slot pair verbatim without
1842        // a per-fixture `.to_string()` promotion.
1843        AllocationRef::new(name, ns)
1844    }
1845
1846    fn alloc_with_bound_pool(bound: Option<AllocationRef>) -> EphemeralAllocation {
1847        // AllocationSpec rides through `AllocationSpec::requestor_only`
1848        // — sibling to `alloc_with_phase`.
1849        let spec = AllocationSpec::requestor_only(Requestor::kind_only("manual"));
1850        let mut a = EphemeralAllocation::new("bp-alloc", spec);
1851        a.status = Some(AllocationStatus {
1852            phase: AllocationPhase::Bound,
1853            bound_pool: bound,
1854            ..AllocationStatus::default()
1855        });
1856        a
1857    }
1858
1859    #[test]
1860    fn observed_bound_pool_returns_none_when_status_is_none() {
1861        // Missing-`status` corner pin: the primitive collapses the
1862        // no-status case to `None` so downstream `.is_some()` /
1863        // `if let Some(_)` / `.cloned().unwrap_or_else(...)` behave
1864        // identically on an `EphemeralAllocation` whose status field
1865        // is `None` and on one whose status carries an unpopulated
1866        // `bound_pool` slot. Matches the pre-lift `.and_then(...)`
1867        // chain's `None` byte-identically at the pool reconciler's
1868        // Release-composition seed.
1869        let a = alloc_without_status();
1870        assert!(a.observed_bound_pool().is_none());
1871    }
1872
1873    #[test]
1874    fn observed_bound_pool_returns_none_when_slot_is_none() {
1875        // Empty-slot-under-populated-status corner pin: the primitive
1876        // returns `None`, matching the missing-`status` corner byte-
1877        // identically. A regression that treated the two corners
1878        // differently would silently promote an internal representation
1879        // detail (whether the pool reconciler has ever written a
1880        // status subresource) into observable behavior at the
1881        // Release-composition branch of the allocation reconciler's
1882        // `decide` transition rule.
1883        let a = alloc_with_bound_pool(None);
1884        assert!(a.observed_bound_pool().is_none());
1885    }
1886
1887    #[test]
1888    fn observed_bound_pool_returns_borrow_when_slot_is_populated() {
1889        // Happy-path pin: with a populated `status.bound_pool` slot,
1890        // the primitive returns a borrowed `&AllocationRef` whose
1891        // (name, namespace) fields match the persisted record. A
1892        // regression that filtered / reshaped / canonicalized the
1893        // record would surface here rather than as silent skew at the
1894        // Release-composition seed's `.cloned()` materialization.
1895        let expected = sample_pool_ref("demo-pool", "pools");
1896        let a = alloc_with_bound_pool(Some(expected.clone()));
1897        let observed = a.observed_bound_pool().expect("populated slot");
1898        assert_eq!(observed, &expected);
1899        assert_eq!(observed.name, "demo-pool");
1900        assert_eq!(observed.namespace, "pools");
1901    }
1902
1903    #[test]
1904    fn observed_bound_pool_is_a_zero_copy_borrow_projection() {
1905        // Borrow-discipline pin: the returned reference points at the
1906        // persisted `AllocationRef` in place — NOT a fresh allocation
1907        // or a clone. A regression that switched the projection to an
1908        // owned `AllocationRef` (via `.clone()`) would defeat the
1909        // zero-copy contract the lift's primary strict-widening
1910        // delivers (the observer's Release-composition arm clones
1911        // once at the composition point where the
1912        // `AllocationConvergenceCtx` snapshot slot requires the owned
1913        // value). Peer to the sibling
1914        // `Process::observed_identity_is_a_zero_copy_borrow_projection`
1915        // pin on the `Process` CRD's `status.identity` slot.
1916        let a = alloc_with_bound_pool(Some(sample_pool_ref("demo-pool", "pools")));
1917        let observed = a.observed_bound_pool().expect("populated slot") as *const _;
1918        let persisted = a.status.as_ref().unwrap().bound_pool.as_ref().unwrap() as *const _;
1919        assert!(std::ptr::eq(observed, persisted));
1920    }
1921
1922    #[test]
1923    fn observed_bound_pool_is_a_pure_projection() {
1924        // Purity pin: calling the projection twice on the same
1925        // `EphemeralAllocation` returns byte-identical borrows (same
1926        // pointer). A regression that introduced state — a lazy-
1927        // cached reference, a normalization step that ran once and
1928        // cached — would surface here rather than as silent drift
1929        // between two dispatches within one reconcile pass.
1930        let a = alloc_with_bound_pool(Some(sample_pool_ref("demo-pool", "pools")));
1931        let one = a.observed_bound_pool().expect("populated slot") as *const _;
1932        let two = a.observed_bound_pool().expect("populated slot") as *const _;
1933        assert!(std::ptr::eq(one, two));
1934    }
1935
1936    #[test]
1937    fn observed_bound_pool_matches_pre_lift_chain_bytewise() {
1938        // Byte-identical parity pin between the borrow-form primitive
1939        // here and the pre-lift `tatara-pool-reconciler`
1940        // `.status.as_ref().and_then(|s| s.bound_pool.clone())` chain.
1941        // Sweeps every corner every callsite plausibly encounters
1942        // (missing status, empty `bound_pool` slot, populated
1943        // `bound_pool` slot). A regression that inserted a
1944        // normalization step at the primitive the pre-lift chain does
1945        // NOT apply — or vice versa — surfaces here rather than as
1946        // silent drift between the pre-lift consumer site and the ONE
1947        // substrate owner it now routes through.
1948        fn pre_lift(a: &EphemeralAllocation) -> Option<AllocationRef> {
1949            a.status.as_ref().and_then(|s| s.bound_pool.clone())
1950        }
1951        // Missing status.
1952        let a = alloc_without_status();
1953        assert_eq!(a.observed_bound_pool().cloned(), pre_lift(&a));
1954        // Populated status, empty `bound_pool` slot.
1955        let a = alloc_with_bound_pool(None);
1956        assert_eq!(a.observed_bound_pool().cloned(), pre_lift(&a));
1957        // Populated status, populated `bound_pool` slot.
1958        let a = alloc_with_bound_pool(Some(sample_pool_ref("demo-pool", "pools")));
1959        assert_eq!(a.observed_bound_pool().cloned(), pre_lift(&a));
1960    }
1961
1962    #[test]
1963    fn observed_bound_pool_missing_status_and_empty_slot_collapse_to_the_same_option_shape() {
1964        // Cross-corner coherence pin: the missing-`status` corner and
1965        // the populated-empty-slot corner return `Option`s whose
1966        // `.is_none()` / `.is_some()` observations are IDENTICAL. A
1967        // regression that promoted the missing-`status` corner to a
1968        // typed error (via a signature change to `Result<_, _>`) — or
1969        // that widened the empty-slot corner to a synthetic
1970        // `Some(AllocationRef::default())` — would surface here rather
1971        // than as silent operator-facing divergence between a never-
1972        // status-written allocation and a bound-pool-cleared
1973        // allocation on the Release-composition branch.
1974        let a_no_status = alloc_without_status();
1975        let a_empty_slot = alloc_with_bound_pool(None);
1976        assert_eq!(
1977            a_no_status.observed_bound_pool().is_none(),
1978            a_empty_slot.observed_bound_pool().is_none(),
1979        );
1980        assert_eq!(
1981            a_no_status.observed_bound_pool().is_some(),
1982            a_empty_slot.observed_bound_pool().is_some(),
1983        );
1984    }
1985
1986    #[test]
1987    fn observed_bound_pool_shape_agrees_with_process_observed_identity_peer_axis() {
1988        // Cross-CRD peer-axis coherence pin binding the SAME
1989        // `.status.as_ref().and_then(|s| s.<slot>.as_ref())` shape
1990        // that both `EphemeralAllocation::observed_bound_pool` (this
1991        // primitive) and `Process::observed_identity` walk, differing
1992        // ONLY in the record projected. Structural test — both
1993        // signatures must resolve as `&Self -> Option<&Record>` fn
1994        // pointers, so a future rename or a signature drift that
1995        // (say) widened one side to `Option<Record>` or narrowed one
1996        // side to `Option<&str>` fails to compile here rather than
1997        // silently drifting the two reconcilers apart at their
1998        // respective observer seeds. The runtime side of the pin
1999        // sweeps the missing-status + empty-slot corners on the
2000        // `EphemeralAllocation` half; the `Process` half is exercised
2001        // by its own `crd.rs::tests::observed_identity_*` pin
2002        // family — this test binds only the peer-axis shape.
2003        let a_no_status = alloc_without_status();
2004        let a_empty_slot = alloc_with_bound_pool(None);
2005        assert!(a_no_status.observed_bound_pool().is_none());
2006        assert!(a_empty_slot.observed_bound_pool().is_none());
2007        // Structural peer-axis coherence: bind both signatures as fn
2008        // pointers at their peer resolution type so the compiler
2009        // refuses to build if either side's shape drifts. The `_`
2010        // let-bindings assert the target type inference.
2011        let _bound_pool_shape: fn(&EphemeralAllocation) -> Option<&AllocationRef> =
2012            EphemeralAllocation::observed_bound_pool;
2013        let _identity_shape: fn(&crate::prelude::Process) -> Option<&crate::identity::Identity> =
2014            crate::prelude::Process::observed_identity;
2015    }
2016
2017    // ─── EphemeralAllocation::observed_expires_at substrate pins ────
2018    //
2019    // The copy-form status-projection primitive on the TTL-expiry axis.
2020    // Collapses the pre-lift hand-authored `.status.as_ref().and_then(
2021    // |s| s.expires_at)` chain in `tatara-pool-reconciler::
2022    // allocation_decide::AllocationConvergenceCtx::observe`'s
2023    // `expires_at` seed onto the ONE substrate primitive. Same-CRD peer
2024    // to `observed_phase` on the (copy-form × status-slot) axis — both
2025    // primitives walk the identical `.status.as_ref().<map|and_then>(
2026    // |s| s.<Copy-field>)` shape. Each pin is fail-before-pass-after:
2027    // `observed_expires_at` did not exist pre-lift, so any test invoking
2028    // it fails to compile pre-lift and passes post-lift.
2029
2030    fn alloc_with_expires_at(expires_at: Option<DateTime<Utc>>) -> EphemeralAllocation {
2031        // AllocationSpec rides through `AllocationSpec::requestor_only`
2032        // — sibling to `alloc_with_phase`.
2033        let spec = AllocationSpec::requestor_only(Requestor::kind_only("manual"));
2034        let mut a = EphemeralAllocation::new("exp-alloc", spec);
2035        a.status = Some(AllocationStatus {
2036            phase: AllocationPhase::Bound,
2037            expires_at,
2038            ..AllocationStatus::default()
2039        });
2040        a
2041    }
2042
2043    #[test]
2044    fn observed_expires_at_returns_none_when_status_is_none() {
2045        // Missing-`status` corner pin: the primitive collapses the
2046        // no-status case to `None` so downstream `.is_some()` / any
2047        // deadline comparison behaves identically on an
2048        // `EphemeralAllocation` whose status field is `None` and on
2049        // one whose status carries an unpopulated `expires_at` slot.
2050        // Matches the pre-lift `.and_then(...)` chain's `None` byte-
2051        // identically at the pool reconciler's Release-composition
2052        // TTL gate.
2053        let a = alloc_without_status();
2054        assert!(a.observed_expires_at().is_none());
2055    }
2056
2057    #[test]
2058    fn observed_expires_at_returns_none_when_slot_is_none() {
2059        // Empty-slot-under-populated-status corner pin: the primitive
2060        // returns `None`, matching the missing-`status` corner byte-
2061        // identically. A regression that treated the two corners
2062        // differently would silently promote an internal representation
2063        // detail (whether the pool reconciler has ever written a
2064        // `status.expires_at` field for a not-yet-Bound allocation)
2065        // into observable behavior at the Release-composition branch
2066        // of the allocation reconciler's `decide` transition rule.
2067        let a = alloc_with_expires_at(None);
2068        assert!(a.observed_expires_at().is_none());
2069    }
2070
2071    #[test]
2072    fn observed_expires_at_returns_populated_timestamp_verbatim() {
2073        // Happy-path pin: with a populated `status.expires_at` slot,
2074        // the primitive returns the persisted `DateTime<Utc>` verbatim.
2075        // A regression that filtered / clamped / canonicalized the
2076        // timestamp would surface here rather than as silent skew at
2077        // the Release-composition TTL gate's `>=` deadline comparison.
2078        let expected = Utc::now();
2079        let a = alloc_with_expires_at(Some(expected));
2080        assert_eq!(a.observed_expires_at(), Some(expected));
2081    }
2082
2083    #[test]
2084    fn observed_expires_at_is_a_pure_projection() {
2085        // Purity pin: calling the projection twice on the same
2086        // `EphemeralAllocation` returns byte-identical `Option`s. A
2087        // regression that introduced state — a lazy-cached value, a
2088        // normalization step that ran once and cached — would surface
2089        // here rather than as silent drift between two dispatches
2090        // within one reconcile pass.
2091        let expected = Utc::now();
2092        let a = alloc_with_expires_at(Some(expected));
2093        assert_eq!(a.observed_expires_at(), a.observed_expires_at());
2094    }
2095
2096    #[test]
2097    fn observed_expires_at_matches_pre_lift_chain_bytewise() {
2098        // Byte-identical parity pin between the copy-form primitive
2099        // here and the pre-lift `tatara-pool-reconciler`
2100        // `.status.as_ref().and_then(|s| s.expires_at)` chain. Sweeps
2101        // every corner every callsite plausibly encounters (missing
2102        // status, empty `expires_at` slot, populated `expires_at`
2103        // slot). A regression that inserted a normalization step at
2104        // the primitive the pre-lift chain does NOT apply — or vice
2105        // versa — surfaces here rather than as silent drift between
2106        // the pre-lift consumer site and the ONE substrate owner it
2107        // now routes through.
2108        fn pre_lift(a: &EphemeralAllocation) -> Option<DateTime<Utc>> {
2109            a.status.as_ref().and_then(|s| s.expires_at)
2110        }
2111        // Missing status.
2112        let a = alloc_without_status();
2113        assert_eq!(a.observed_expires_at(), pre_lift(&a));
2114        // Populated status, empty `expires_at` slot.
2115        let a = alloc_with_expires_at(None);
2116        assert_eq!(a.observed_expires_at(), pre_lift(&a));
2117        // Populated status, populated `expires_at` slot.
2118        let a = alloc_with_expires_at(Some(Utc::now()));
2119        assert_eq!(a.observed_expires_at(), pre_lift(&a));
2120    }
2121
2122    #[test]
2123    fn observed_expires_at_missing_status_and_empty_slot_collapse_to_the_same_option_shape() {
2124        // Cross-corner coherence pin: the missing-`status` corner and
2125        // the populated-empty-slot corner return `Option`s whose
2126        // `.is_none()` / `.is_some()` observations are IDENTICAL. A
2127        // regression that promoted the missing-`status` corner to a
2128        // typed error (via a signature change to `Result<_, _>`) — or
2129        // that widened the empty-slot corner to a synthetic
2130        // `Some(Utc::now())` — would surface here rather than as
2131        // silent operator-facing divergence between a never-status-
2132        // written allocation and a Bind-time-without-TTL allocation on
2133        // the Release-composition branch.
2134        let a_no_status = alloc_without_status();
2135        let a_empty_slot = alloc_with_expires_at(None);
2136        assert_eq!(
2137            a_no_status.observed_expires_at().is_none(),
2138            a_empty_slot.observed_expires_at().is_none(),
2139        );
2140        assert_eq!(
2141            a_no_status.observed_expires_at().is_some(),
2142            a_empty_slot.observed_expires_at().is_some(),
2143        );
2144    }
2145
2146    #[test]
2147    fn observed_expires_at_shape_agrees_with_observed_phase_peer_axis() {
2148        // Same-CRD peer-axis coherence pin binding the SAME
2149        // `.status.as_ref().<map|and_then>(|s| s.<Copy-field>)` shape
2150        // that both `EphemeralAllocation::observed_expires_at` (this
2151        // primitive) and `EphemeralAllocation::observed_phase` walk,
2152        // differing only in the outer combinator (`and_then` here
2153        // because the persisted field is itself `Option<T>`, `map`
2154        // there because the persisted phase is bare) and in the
2155        // projected `Copy` type. Structural test — both signatures
2156        // must resolve as `&Self -> Option<T>` fn pointers with `T`
2157        // `Copy`, so a future rename or a signature drift that (say)
2158        // widened one side to `Option<&T>` or narrowed one side to
2159        // `T` fails to compile here rather than silently drifting
2160        // the family apart. The runtime side of the pin sweeps the
2161        // missing-status + empty-slot corners on the `expires_at`
2162        // half; the `phase` half is exercised by its own
2163        // `tests::observed_phase_*` pin family — this test binds
2164        // only the peer-axis shape.
2165        let a_no_status = alloc_without_status();
2166        let a_empty_slot = alloc_with_expires_at(None);
2167        assert!(a_no_status.observed_expires_at().is_none());
2168        assert!(a_empty_slot.observed_expires_at().is_none());
2169        // Structural peer-axis coherence: bind both signatures as fn
2170        // pointers at their peer resolution type so the compiler
2171        // refuses to build if either side's shape drifts.
2172        let _expires_at_shape: fn(&EphemeralAllocation) -> Option<DateTime<Utc>> =
2173            EphemeralAllocation::observed_expires_at;
2174        let _phase_shape: fn(&EphemeralAllocation) -> Option<AllocationPhase> =
2175            EphemeralAllocation::observed_phase;
2176    }
2177
2178    #[test]
2179    fn allocation_spec_omits_optional_fields() {
2180        // AllocationSpec rides through `AllocationSpec::requestor_only`
2181        // + the inner Requestor through `Requestor::kind_only`; the
2182        // wire-shape pin still holds because BOTH composers produce
2183        // the byte-identical minimal shape whose `skip_serializing_if
2184        // = "Option::is_none"` + default-vec serde attributes elide
2185        // every optional slot from the YAML output.
2186        let s = AllocationSpec::requestor_only(Requestor::kind_only("manual"));
2187        let yaml = serde_yaml::to_string(&s).unwrap();
2188        assert!(!yaml.contains("poolRef"));
2189        assert!(!yaml.contains("ttl"));
2190        assert!(!yaml.contains("note"));
2191    }
2192
2193    // ─── AllocationSpec::requestor_only substrate pins ──────────────
2194    //
2195    // The pre-lift `AllocationSpec { pool_ref: None, requestor: <r>,
2196    // ttl: None, note: None }` incantation recurred at NINE workspace-
2197    // wide fixture sites past the ★★ PRIME-DIRECTIVE ≥ 2 threshold
2198    // (five inside this file's own test module, three inside the
2199    // crate's `tests_owned_coordinates` / `tests_annotated` /
2200    // `tests_deletion_tombstoned` pin modules on `lib.rs`, and one in
2201    // `tatara-pool-reconciler::allocation_decide::alloc`). Every corner
2202    // of the three-slot default tail is pinned here so a future
2203    // normalization at the primitive lands with a fail-before-pass-
2204    // after regression at THIS composer's pins rather than as silent
2205    // fixture skew across the nine callsite arms.
2206
2207    #[test]
2208    fn requestor_only_leaves_the_three_slot_default_tail_at_the_substrate_owner() {
2209        // Every default-tail slot must land at the values the substrate
2210        // owner stamps: `pool_ref = None` (selector-based routing),
2211        // `ttl = None` (fall back to pool template TTL), `note = None`
2212        // (empty audit slot). A regression that drifted ANY of the three
2213        // defaults would silently reshape every downstream fixture
2214        // simultaneously; this pin catches it.
2215        let s = AllocationSpec::requestor_only(Requestor::kind_only("manual"));
2216        assert!(s.pool_ref.is_none(), "pool_ref must default to None");
2217        assert!(s.ttl.is_none(), "ttl must default to None");
2218        assert!(s.note.is_none(), "note must default to None");
2219    }
2220
2221    #[test]
2222    fn requestor_only_stamps_the_caller_requestor_verbatim() {
2223        // The single caller-varying slot MUST pass through untouched —
2224        // a regression that copied only a subset of the Requestor's
2225        // seven slots (e.g. re-authoring `Requestor { kind: r.kind, ..
2226        // Default::default() }` inside the composer) would drop the
2227        // caller's `repo` / `branch` / `pr_number` / `sha` / `pr_labels`
2228        // / `actor` at every downstream fixture. Passes a fully-
2229        // populated `Requestor` through and asserts every slot lands.
2230        let r = Requestor {
2231            kind: "github-pr".into(),
2232            repo: Some("pleme-io/demo".into()),
2233            branch: Some("main".into()),
2234            pr_number: Some(42),
2235            sha: Some("deadbeef".into()),
2236            pr_labels: vec!["needs-review".into()],
2237            actor: Some("dozer".into()),
2238        };
2239        let s = AllocationSpec::requestor_only(r.clone());
2240        assert_eq!(s.requestor.kind, r.kind);
2241        assert_eq!(s.requestor.repo, r.repo);
2242        assert_eq!(s.requestor.branch, r.branch);
2243        assert_eq!(s.requestor.pr_number, r.pr_number);
2244        assert_eq!(s.requestor.sha, r.sha);
2245        assert_eq!(s.requestor.pr_labels, r.pr_labels);
2246        assert_eq!(s.requestor.actor, r.actor);
2247    }
2248
2249    #[test]
2250    fn requestor_only_matches_hand_authored_pre_lift_bytewise() {
2251        // Byte-identical parity with the pre-lift 5-line struct-
2252        // literal every downstream fixture restated verbatim. Swept
2253        // across the two representative requestor shapes: the
2254        // kind-only `"manual"` fixture (the majority of the collapsed
2255        // callsites) and the fully-populated github-pr requestor (the
2256        // `tatara-pool-reconciler::allocation_decide::alloc` shape).
2257        // A regression that reshaped the composer's output would
2258        // diverge from the pre-lift literal HERE rather than at every
2259        // downstream fixture's downstream assertion.
2260        let sample_requestors = [
2261            Requestor::kind_only("manual"),
2262            Requestor::kind_only("github-pr"),
2263            Requestor {
2264                kind: "github-pr".into(),
2265                repo: Some("pleme-io/demo".into()),
2266                branch: Some("main".into()),
2267                pr_number: None,
2268                sha: None,
2269                pr_labels: vec![],
2270                actor: None,
2271            },
2272        ];
2273        for r in sample_requestors {
2274            let via_primitive = AllocationSpec::requestor_only(r.clone());
2275            let hand_authored = AllocationSpec {
2276                pool_ref: None,
2277                requestor: r.clone(),
2278                ttl: None,
2279                note: None,
2280            };
2281            // Sweep every slot rather than round-tripping through
2282            // serde, so a slot rename that keeps the same serde name
2283            // still surfaces as a defect at the primitive's slot-
2284            // level parity.
2285            assert!(via_primitive.pool_ref.is_none() && hand_authored.pool_ref.is_none());
2286            assert_eq!(via_primitive.requestor.kind, hand_authored.requestor.kind);
2287            assert_eq!(via_primitive.ttl, hand_authored.ttl);
2288            assert_eq!(via_primitive.note, hand_authored.note);
2289        }
2290    }
2291
2292    // ─── AllocationStatus::transition substrate pins ────────────────────
2293    //
2294    // Pin the substrate composer at fail-before-pass-after granularity:
2295    // the composer did not exist pre-lift, so any regression against
2296    // the four hand-authored sites in
2297    // `tatara-pool-reconciler::controller_allocation::reconcile_inner`
2298    // surfaces at these pins rather than as silent operator-visible
2299    // status-patch skew.
2300
2301    fn anchor_time() -> DateTime<Utc> {
2302        // A deterministic non-`Utc::now()` anchor so pins that read
2303        // back `phase_since` do not race the wall clock.
2304        DateTime::parse_from_rfc3339("2026-05-01T00:00:00Z")
2305            .unwrap()
2306            .with_timezone(&Utc)
2307    }
2308
2309    #[test]
2310    fn allocation_status_transition_stamps_supplied_phase_verbatim() {
2311        for phase in AllocationPhase::ALL {
2312            let s = AllocationStatus::transition(phase, "irrelevant", anchor_time());
2313            assert_eq!(s.phase, phase, "phase drifted for {phase:?}");
2314        }
2315    }
2316
2317    #[test]
2318    fn allocation_status_transition_stamps_supplied_message_verbatim() {
2319        let s = AllocationStatus::transition(
2320            AllocationPhase::Queued,
2321            "pool matched; no Free member available",
2322            anchor_time(),
2323        );
2324        assert_eq!(
2325            s.message.as_deref(),
2326            Some("pool matched; no Free member available"),
2327        );
2328    }
2329
2330    #[test]
2331    fn allocation_status_transition_sets_phase_since_to_supplied_now() {
2332        let anchor = anchor_time();
2333        let s = AllocationStatus::transition(AllocationPhase::Bound, "bound", anchor);
2334        assert_eq!(
2335            s.phase_since,
2336            Some(anchor),
2337            "phase_since must be the supplied `now`, not a fresh Utc::now()",
2338        );
2339    }
2340
2341    #[test]
2342    fn allocation_status_transition_defaults_every_optional_slot() {
2343        // The composer stamps only the three always-present slots
2344        // (`phase + phase_since + message`); every other slot on
2345        // `AllocationStatus` must land at its `Default`-equivalent
2346        // variant so a caller-branch that attaches an optional slot
2347        // via struct-update syntax does not silently inherit a
2348        // pre-populated non-`None`/non-empty value.
2349        let s = AllocationStatus::transition(AllocationPhase::Released, "released", anchor_time());
2350        assert!(s.bound_pool.is_none(), "bound_pool must default to None");
2351        assert!(
2352            s.assigned_process.is_none(),
2353            "assigned_process must default to None"
2354        );
2355        assert!(
2356            s.allocated_at.is_none(),
2357            "allocated_at must default to None"
2358        );
2359        assert!(s.expires_at.is_none(), "expires_at must default to None");
2360        assert!(
2361            s.conditions.is_empty(),
2362            "conditions must default to an empty Vec"
2363        );
2364    }
2365
2366    #[test]
2367    fn allocation_status_transition_accepts_owned_string_and_static_str() {
2368        // `impl Into<String>` matches every current callsite:
2369        // three of the four hand-authored sites pass `&'static str`
2370        // literal reasons; the fourth ("bound to pool member") also
2371        // passes a `&'static str`. Sibling to
2372        // `tatara-reconciler::patch::phase_status_msg`'s identical
2373        // `impl Into<String>` signature.
2374        let via_static = AllocationStatus::transition(
2375            AllocationPhase::NoMatchingPool,
2376            "no Pool selector matched this Requestor",
2377            anchor_time(),
2378        );
2379        let via_owned = AllocationStatus::transition(
2380            AllocationPhase::NoMatchingPool,
2381            String::from("no Pool selector matched this Requestor"),
2382            anchor_time(),
2383        );
2384        assert_eq!(via_static.message, via_owned.message);
2385    }
2386
2387    #[test]
2388    fn allocation_status_transition_serializes_to_pre_lift_json_shape() {
2389        // Byte-shape pin against the exact `json!({ "status": {
2390        // "phase": <variant>, "phaseSince": <now>, "message": "<msg>"
2391        // } })` incantation every pre-lift callsite restated. A
2392        // regression that reordered a slot, dropped the `phaseSince`
2393        // stamp, or drifted the camelCase key naming here surfaces at
2394        // THIS pin rather than as a subtle patch_status body the K8s
2395        // API server accepts but the pool reconciler's next observe
2396        // pass fails to read back.
2397        let anchor = anchor_time();
2398        let via_composer =
2399            AllocationStatus::transition(AllocationPhase::NoMatchingPool, "no match", anchor);
2400        let composed = serde_json::json!({ "status": via_composer });
2401        let hand_authored = serde_json::json!({
2402            "status": {
2403                "phase": AllocationPhase::NoMatchingPool,
2404                "phaseSince": anchor,
2405                "message": "no match",
2406            }
2407        });
2408        assert_eq!(composed, hand_authored);
2409    }
2410
2411    #[test]
2412    fn allocation_status_transition_composes_with_struct_update_for_bind_seed() {
2413        // Pin the compound shape the `AllocationDecision::Bind`
2414        // callsite composes: the substrate seed carries `phase +
2415        // phase_since + message`, and the branch attaches
2416        // `bound_pool` + `assigned_process` + `allocated_at` +
2417        // `expires_at` via struct-update syntax. Post-lift the four
2418        // extra slots survive the compose intact and the base three
2419        // slots inherit the composer's stamps verbatim.
2420        let anchor = anchor_time();
2421        let ttl = anchor + chrono::Duration::hours(1);
2422        let pool = AllocationRef::new("demo-pool", "pools");
2423        let assigned = AllocationRef::new("demo-abcd", "pools");
2424        let bind_status = AllocationStatus {
2425            bound_pool: Some(pool.clone()),
2426            assigned_process: Some(assigned.clone()),
2427            allocated_at: Some(anchor),
2428            expires_at: Some(ttl),
2429            ..AllocationStatus::transition(AllocationPhase::Bound, "bound to pool member", anchor)
2430        };
2431        // Base-three slots stamped by the composer.
2432        assert_eq!(bind_status.phase, AllocationPhase::Bound);
2433        assert_eq!(bind_status.phase_since, Some(anchor));
2434        assert_eq!(bind_status.message.as_deref(), Some("bound to pool member"));
2435        // Struct-update-attached branch slots.
2436        assert_eq!(
2437            bind_status.bound_pool.as_ref().map(|r| &r.name),
2438            Some(&pool.name)
2439        );
2440        assert_eq!(
2441            bind_status.assigned_process.as_ref().map(|r| &r.name),
2442            Some(&assigned.name)
2443        );
2444        assert_eq!(bind_status.allocated_at, Some(anchor));
2445        assert_eq!(bind_status.expires_at, Some(ttl));
2446    }
2447
2448    // ─── AllocationStatus::bound_transition substrate pins ─────────────
2449    //
2450    // Pin the compound composer at fail-before-pass-after granularity:
2451    // the composer wraps [`AllocationStatus::transition`] with the
2452    // `bound_pool + assigned_process` pair the Bind / Release arms
2453    // both stamped inline pre-lift.
2454
2455    #[test]
2456    fn allocation_status_bound_transition_stamps_supplied_pool_and_process_verbatim() {
2457        let anchor = anchor_time();
2458        let pool = AllocationRef::new("demo-pool", "pools");
2459        let assigned = AllocationRef::new("demo-abcd", "pools");
2460        let s = AllocationStatus::bound_transition(
2461            AllocationPhase::Released,
2462            "released; pool reconciler will return the member",
2463            anchor,
2464            pool.clone(),
2465            assigned.clone(),
2466        );
2467        assert_eq!(s.bound_pool.as_ref(), Some(&pool));
2468        assert_eq!(s.assigned_process.as_ref(), Some(&assigned));
2469    }
2470
2471    #[test]
2472    fn allocation_status_bound_transition_inherits_transition_triplet_verbatim() {
2473        // The compound composer must not stamp its own `phase +
2474        // phase_since + message` triplet — it MUST compose the pair
2475        // atop the substrate `Self::transition` seed so any future
2476        // evolution to the base triplet lands at ONE site and this
2477        // composer inherits the upgrade mechanically. Pin the triplet
2478        // through the same axis-uniform reads the transition tests use.
2479        let anchor = anchor_time();
2480        let via_compound = AllocationStatus::bound_transition(
2481            AllocationPhase::Bound,
2482            "bound to pool member",
2483            anchor,
2484            AllocationRef::new("p", "ns"),
2485            AllocationRef::new("q", "ns"),
2486        );
2487        let via_base =
2488            AllocationStatus::transition(AllocationPhase::Bound, "bound to pool member", anchor);
2489        assert_eq!(via_compound.phase, via_base.phase);
2490        assert_eq!(via_compound.phase_since, via_base.phase_since);
2491        assert_eq!(via_compound.message, via_base.message);
2492    }
2493
2494    #[test]
2495    fn allocation_status_bound_transition_defaults_every_optional_slot_beyond_the_pair() {
2496        // The compound composer stamps only the base triplet + the
2497        // `bound_pool + assigned_process` pair; every other optional
2498        // slot (`allocated_at` / `expires_at` / `conditions`) must
2499        // land at its `Default`-equivalent variant so a caller-branch
2500        // that attaches an addendum via struct-update syntax (a Bind
2501        // arm's `allocated_at` + `expires_at` stamp) does not
2502        // silently inherit a pre-populated non-`None`/non-empty value.
2503        let s = AllocationStatus::bound_transition(
2504            AllocationPhase::Released,
2505            "released",
2506            anchor_time(),
2507            AllocationRef::new("p", "ns"),
2508            AllocationRef::new("q", "ns"),
2509        );
2510        assert!(
2511            s.allocated_at.is_none(),
2512            "allocated_at must default to None"
2513        );
2514        assert!(s.expires_at.is_none(), "expires_at must default to None");
2515        assert!(
2516            s.conditions.is_empty(),
2517            "conditions must default to an empty Vec"
2518        );
2519    }
2520
2521    #[test]
2522    fn allocation_status_bound_transition_composes_with_struct_update_for_bind_seed() {
2523        // Pin the compound shape the `AllocationDecision::Bind`
2524        // callsite post-lift composes: the compound composer seeds
2525        // `phase + phase_since + message + bound_pool +
2526        // assigned_process`, and the Bind branch attaches
2527        // `allocated_at` + `expires_at` via struct-update syntax.
2528        // Post-lift the two extra slots survive the compose intact
2529        // and the base five slots inherit the composer's stamps
2530        // verbatim.
2531        let anchor = anchor_time();
2532        let ttl = anchor + chrono::Duration::hours(1);
2533        let pool = AllocationRef::new("demo-pool", "pools");
2534        let assigned = AllocationRef::new("demo-abcd", "pools");
2535        let bind_status = AllocationStatus {
2536            allocated_at: Some(anchor),
2537            expires_at: Some(ttl),
2538            ..AllocationStatus::bound_transition(
2539                AllocationPhase::Bound,
2540                "bound to pool member",
2541                anchor,
2542                pool.clone(),
2543                assigned.clone(),
2544            )
2545        };
2546        assert_eq!(bind_status.phase, AllocationPhase::Bound);
2547        assert_eq!(bind_status.phase_since, Some(anchor));
2548        assert_eq!(bind_status.message.as_deref(), Some("bound to pool member"));
2549        assert_eq!(bind_status.bound_pool.as_ref(), Some(&pool));
2550        assert_eq!(bind_status.assigned_process.as_ref(), Some(&assigned));
2551        assert_eq!(bind_status.allocated_at, Some(anchor));
2552        assert_eq!(bind_status.expires_at, Some(ttl));
2553    }
2554
2555    #[test]
2556    fn allocation_status_bound_transition_matches_pre_lift_release_arm_verbatim() {
2557        // Byte-shape pin against the exact pre-lift `AllocationStatus
2558        // { bound_pool: Some(pool), assigned_process:
2559        // Some(AllocationRef::new(..)), ..AllocationStatus::transition
2560        // (Released, "…", now) }` composition the
2561        // `AllocationDecision::Release` arm restated inline pre-lift.
2562        // A regression that reordered the pair, dropped a `Some`, or
2563        // drifted the composed base triplet here surfaces at THIS pin
2564        // rather than as a subtle patch_status body the K8s API
2565        // server accepts but the audit record disagrees on.
2566        let anchor = anchor_time();
2567        let pool = AllocationRef::new("demo-pool", "pools");
2568        let assigned = AllocationRef::new("demo-abcd", "pools");
2569        let via_composer = AllocationStatus::bound_transition(
2570            AllocationPhase::Released,
2571            "released; pool reconciler will return the member",
2572            anchor,
2573            pool.clone(),
2574            assigned.clone(),
2575        );
2576        let via_hand_authored = AllocationStatus {
2577            bound_pool: Some(pool),
2578            assigned_process: Some(assigned),
2579            ..AllocationStatus::transition(
2580                AllocationPhase::Released,
2581                "released; pool reconciler will return the member",
2582                anchor,
2583            )
2584        };
2585        assert_eq!(
2586            serde_json::to_value(&via_composer).unwrap(),
2587            serde_json::to_value(&via_hand_authored).unwrap(),
2588        );
2589    }
2590
2591    #[test]
2592    fn allocation_status_transition_shape_agrees_with_pool_status_observed_peer() {
2593        // Cross-CRD peer-axis coherence: both substrate composers
2594        // (`PoolStatus::observed`, `AllocationStatus::transition`)
2595        // accept a caller-supplied `now: DateTime<Utc>` at the SAME
2596        // signature slot, stamp it into `phase_since` uniformly, and
2597        // leave every other slot at its `Default`-equivalent variant.
2598        // Structural pin: if either side's `now` signature drifts to
2599        // `impl Into<DateTime<Utc>>` or a reference form, this bind
2600        // fails to compile here rather than silently drifting the
2601        // family apart.
2602        let _allocation_shape: fn(
2603            AllocationPhase,
2604            &'static str,
2605            DateTime<Utc>,
2606        ) -> AllocationStatus = AllocationStatus::transition;
2607        // (`PoolStatus::observed`'s pinned coherence lives at its own
2608        // peer pin family in `crate::pool`; this pin binds the
2609        // `AllocationStatus::transition` side of the peer pair.)
2610    }
2611
2612    // ─── EphemeralAllocation::new_in substrate pins ────────────────────
2613    //
2614    // The pre-lift 2-line `let mut a = EphemeralAllocation::new(<name>,
2615    // <spec>); a.meta_mut().namespace = Some(<ns>.into());` chain
2616    // recurred at TWO workspace-wide sites past the ★★ PRIME-DIRECTIVE
2617    // ≥ 2 threshold across TWO crates (production PR-webhook emitter
2618    // at `tatara-github-watcher::allocation_factory::build_allocation`
2619    // + allocation-decision test fixture at `tatara-pool-reconciler::
2620    // allocation_decide::tests::alloc`). Post-lift the ONE substrate
2621    // composer stamps a namespaced `EphemeralAllocation` from
2622    // `(name, ns, spec)` in one call. Fail-before-pass-after
2623    // granularity: `new_in` did not exist pre-lift; the compiler
2624    // cannot resolve the name until the impl block above is in place,
2625    // so a rollback of the primitive breaks this whole pin block.
2626
2627    fn sample_spec() -> AllocationSpec {
2628        AllocationSpec::requestor_only(Requestor::kind_only("manual"))
2629    }
2630
2631    #[test]
2632    fn allocation_new_in_stamps_metadata_name_from_the_name_slot() {
2633        // `name` slot → `metadata.name` projection pin. Guards against
2634        // a regression that dropped the `name` slot into a `generate_
2635        // name` slot, an `annotations` seed, or any downstream slot the
2636        // kube-derived [`EphemeralAllocation::new`] does not populate
2637        // at `metadata.name` verbatim.
2638        let a = EphemeralAllocation::new_in("pr-42-demo", "pools", sample_spec());
2639        assert_eq!(a.metadata.name.as_deref(), Some("pr-42-demo"));
2640    }
2641
2642    #[test]
2643    fn allocation_new_in_stamps_metadata_namespace_from_the_ns_slot() {
2644        // `ns` slot → `metadata.namespace` projection pin. Guards
2645        // against a regression that dropped the `ns` slot into a
2646        // `labels` seed, an unrelated annotation, or that stamped
2647        // `namespace = None` even after a caller-supplied value.
2648        let a = EphemeralAllocation::new_in("pr-42-demo", "pools", sample_spec());
2649        assert_eq!(a.metadata.namespace.as_deref(), Some("pools"));
2650    }
2651
2652    #[test]
2653    fn allocation_new_in_stamps_spec_from_the_spec_slot_verbatim() {
2654        // `spec` slot → `spec` projection pin. A regression that
2655        // silently normalized the caller-supplied spec inside the
2656        // composer would diverge from the byte-identical pass-through
2657        // the pre-lift 2-line chain produced.
2658        let spec = AllocationSpec::requestor_only(Requestor::kind_only("github-pr"));
2659        let a = EphemeralAllocation::new_in("pr-42-demo", "pools", spec.clone());
2660        assert_eq!(a.spec.requestor.kind, spec.requestor.kind);
2661        assert!(a.spec.pool_ref.is_none());
2662        assert!(a.spec.ttl.is_none());
2663        assert!(a.spec.note.is_none());
2664    }
2665
2666    #[test]
2667    fn allocation_new_in_accepts_both_owned_and_borrowed_namespace_slot() {
2668        // The `impl Into<String>` ergonomic contract round-trips
2669        // through both `&'static str` (the pre-lift test-fixture caller
2670        // shape) AND owned `String` (the pre-lift production-emitter
2671        // caller shape at `build_allocation`, where `namespace:
2672        // &str` was pushed through a `.to_string()`) at the SAME
2673        // signature. Guards against a regression that narrowed the
2674        // slot to `&str` only or that silently double-`.into()`d an
2675        // already-owned String.
2676        let via_str = EphemeralAllocation::new_in("pr-42-demo", "pools", sample_spec());
2677        let via_string =
2678            EphemeralAllocation::new_in("pr-42-demo", String::from("pools"), sample_spec());
2679        assert_eq!(via_str.metadata.namespace, via_string.metadata.namespace);
2680    }
2681
2682    #[test]
2683    fn allocation_new_in_matches_pre_lift_construct_then_set_namespace_bytewise() {
2684        // Byte-shape parity witness against the pre-lift 2-line chain
2685        // across the two representative namespace shapes the collapsed
2686        // sites used (`"pools"` at `allocation_decide::alloc` +
2687        // production-emitter `"ephemeral-pools"` at `build_allocation`
2688        // + the free-form namespace `build_allocation` accepts). A
2689        // regression that shifted the composer's output would diverge
2690        // from the pre-lift literal HERE rather than at every
2691        // downstream consumer's assertion.
2692        for ns in ["pools", "ephemeral-pools", "custom-ns"] {
2693            let via_primitive = EphemeralAllocation::new_in("pr-42-demo", ns, sample_spec());
2694            let mut hand_authored = EphemeralAllocation::new("pr-42-demo", sample_spec());
2695            hand_authored.metadata.namespace = Some(ns.into());
2696            assert_eq!(via_primitive.metadata.name, hand_authored.metadata.name);
2697            assert_eq!(
2698                via_primitive.metadata.namespace,
2699                hand_authored.metadata.namespace,
2700            );
2701        }
2702    }
2703
2704    #[test]
2705    fn allocation_new_in_defaults_other_metadata_slots_at_kube_derived_new() {
2706        // The composer forwards to the kube-derived
2707        // [`EphemeralAllocation::new`] for every non-namespace metadata
2708        // slot. A regression that stamped finalizers, owner_references,
2709        // labels, or annotations inside the composer's body —
2710        // inheriting the pre-lift chain's undocumented emptiness at
2711        // those slots — would surface here.
2712        let a = EphemeralAllocation::new_in("pr-42-demo", "pools", sample_spec());
2713        assert!(a.metadata.finalizers.is_none());
2714        assert!(a.metadata.owner_references.is_none());
2715        assert!(a.metadata.labels.is_none());
2716        assert!(a.metadata.annotations.is_none());
2717    }
2718
2719    #[test]
2720    fn allocation_new_in_shape_agrees_with_pool_new_in_peer() {
2721        // Cross-CRD peer-axis structural coherence: both substrate
2722        // composers (`EphemeralPool::new_in`, `EphemeralAllocation::
2723        // new_in`) accept `(name: &str, namespace: impl Into<String>,
2724        // spec: <CRD>Spec)` at the SAME positional slot order and
2725        // return the CRD with `metadata.name` + `metadata.namespace`
2726        // stamped uniformly. Structural pin: if either side's slot
2727        // order drifts (e.g. `(ns, name, spec)`), this bind fails to
2728        // compile here rather than silently drifting the family apart.
2729        let _allocation_shape: fn(&str, &'static str, AllocationSpec) -> EphemeralAllocation =
2730            EphemeralAllocation::new_in;
2731        // (`EphemeralPool::new_in`'s pinned coherence lives at its own
2732        // peer pin family in `crate::pool`; this pin binds the
2733        // `EphemeralAllocation::new_in` side of the peer pair.)
2734    }
2735}