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
1075#[cfg(test)]
1076mod tests {
1077    // `FromStr` lives in scope at the test surface only — the derive
1078    // emits `impl ::core::str::FromStr` via the full path so the lib
1079    // body no longer reaches `FromStr` directly, but the cross-axis
1080    // sweeps + the verbatim-echo contract tests call
1081    // `AllocationPhase::from_str(bad)` / `bad.parse::<RequestorKind>()`.
1082    use std::str::FromStr;
1083
1084    use super::*;
1085
1086    #[test]
1087    fn requestor_minimum_shape_round_trips() {
1088        let r = Requestor {
1089            kind: "github-pr".into(),
1090            repo: Some("pleme-io/demo-app".into()),
1091            branch: Some("fix-something".into()),
1092            pr_number: Some(123),
1093            sha: Some("abc123def".into()),
1094            pr_labels: vec!["needs-ephemeral".into()],
1095            actor: Some("drzln".into()),
1096        };
1097        let yaml = serde_yaml::to_string(&r).unwrap();
1098        assert!(yaml.contains("kind: github-pr"));
1099        assert!(yaml.contains("prNumber: 123"));
1100        let back: Requestor = serde_yaml::from_str(&yaml).unwrap();
1101        assert_eq!(back.kind, "github-pr");
1102        assert_eq!(back.pr_number, Some(123));
1103    }
1104
1105    #[test]
1106    fn allocation_status_defaults_pending() {
1107        let s = AllocationStatus::default();
1108        assert_eq!(s.phase, AllocationPhase::Pending);
1109        assert!(s.bound_pool.is_none());
1110        assert!(s.assigned_process.is_none());
1111    }
1112
1113    #[test]
1114    fn allocation_phase_round_trips_via_serde() {
1115        for p in [
1116            AllocationPhase::Pending,
1117            AllocationPhase::Queued,
1118            AllocationPhase::Bound,
1119            AllocationPhase::Releasing,
1120            AllocationPhase::Released,
1121            AllocationPhase::NoMatchingPool,
1122            AllocationPhase::Failed,
1123        ] {
1124            let s = serde_yaml::to_string(&p).unwrap();
1125            let back: AllocationPhase = serde_yaml::from_str(&s).unwrap();
1126            assert_eq!(back, p);
1127        }
1128    }
1129
1130    // ── closed-set algebra contracts for AllocationPhase
1131    //    (ALL × as_str × FromStr × predicate-pair) ────────────────────
1132
1133    /// `ALL` is the source of truth — pin its closure so a variant
1134    /// added without an `ALL` entry fails here via the uniqueness
1135    /// check before drifting `FromStr` or the sweep tests below. The
1136    /// arity is asserted by the `[Self; 7]` array type itself.
1137    ///
1138    /// Structural well-formedness of [`AllocationPhase`] as a
1139    /// [`tatara_lisp::ClosedSet`] implementor — the workspace-wide
1140    /// testkit lift that pins all three structural invariants
1141    /// (`ALL` is non-empty, every variant round-trips through
1142    /// `label ↔ parse_label`, labels are pairwise distinct, `""` is
1143    /// outside the closed set) at ONE call site. Replaces the hand-
1144    /// derived `allocation_phase_all_is_unique_and_complete` +
1145    /// `allocation_phase_roundtrip_via_as_str` + the empty-input arm
1146    /// of `unknown_allocation_phase_errors`. `FromStr` delegates to
1147    /// `<Self as tatara_closed_set::ClosedSet>::parse_label`, so this
1148    /// helper exercises the same code path the allocation reconciler
1149    /// hits when parsing a CRD `enum:`-validated value back to the
1150    /// typed phase.
1151    #[test]
1152    fn allocation_phase_is_well_formed_closed_set() {
1153        tatara_closed_set::assert_closed_set_well_formed::<AllocationPhase>();
1154    }
1155
1156    /// CANONICAL-KEY CONTRACT: `as_str` matches serde's PascalCase
1157    /// output verbatim for every variant. A future variant rename
1158    /// (or an `as_str` arm typo) lands here at one site, instead of
1159    /// drifting between the typed surface, the CRD enum, the YAML
1160    /// wire format, and the operator-facing reason strings the
1161    /// reconciler stamps via Display.
1162    #[test]
1163    fn allocation_phase_as_str_matches_serde() {
1164        crate::tagged_union::assert_label_matches_serde_serialization::<AllocationPhase>();
1165    }
1166
1167    /// The Display impl IS `as_str` — pinning this lets future
1168    /// callers reach for either projection without drift.
1169    #[test]
1170    fn allocation_phase_display_matches_as_str() {
1171        crate::tagged_union::assert_display_matches_label::<AllocationPhase>();
1172    }
1173
1174    /// `FromStr` rejects strings that aren't in the canonical
1175    /// projection — lowercased / typo / unrelated — and the error
1176    /// echoes the input verbatim so the operator-facing diagnostic
1177    /// carries the offending value, not a normalized form. The
1178    /// empty-input arm is pinned by
1179    /// [`allocation_phase_is_well_formed_closed_set`] via the
1180    /// `tatara_lisp::ClosedSet` testkit; the cases here pin the
1181    /// verbatim-echo contract on the [`UnknownAllocationPhase`]
1182    /// newtype, which the trait's `make_unknown` can't see.
1183    #[test]
1184    fn unknown_allocation_phase_errors() {
1185        for bad in [
1186            "pending",
1187            "BOUND",
1188            "no-matching-pool",
1189            "release",
1190            "failed_state",
1191            "Reaped",
1192        ] {
1193            let err = AllocationPhase::from_str(bad).unwrap_err();
1194            assert_eq!(err.0, bad, "error payload should echo input verbatim");
1195        }
1196    }
1197
1198    /// TRUTH-TABLE CONTRACT: the predicate pair agrees with the
1199    /// documented per-variant disposition. `Released` + `Failed` are
1200    /// terminal (absorbing); `Pending` / `Queued` / `NoMatchingPool`
1201    /// need pool routing; `Bound` / `Releasing` are settled-but-not-
1202    /// terminal (heartbeat / release ladder).
1203    #[test]
1204    fn allocation_phase_predicate_truth_tables() {
1205        assert!(!AllocationPhase::Pending.is_terminal());
1206        assert!(AllocationPhase::Pending.needs_pool_routing());
1207
1208        assert!(!AllocationPhase::Queued.is_terminal());
1209        assert!(AllocationPhase::Queued.needs_pool_routing());
1210
1211        assert!(!AllocationPhase::Bound.is_terminal());
1212        assert!(!AllocationPhase::Bound.needs_pool_routing());
1213
1214        assert!(!AllocationPhase::Releasing.is_terminal());
1215        assert!(!AllocationPhase::Releasing.needs_pool_routing());
1216
1217        assert!(AllocationPhase::Released.is_terminal());
1218        assert!(!AllocationPhase::Released.needs_pool_routing());
1219
1220        assert!(!AllocationPhase::NoMatchingPool.is_terminal());
1221        assert!(AllocationPhase::NoMatchingPool.needs_pool_routing());
1222
1223        assert!(AllocationPhase::Failed.is_terminal());
1224        assert!(!AllocationPhase::Failed.needs_pool_routing());
1225    }
1226
1227    /// IMPLICATION CONTRACT: `is_terminal → !needs_pool_routing`. A
1228    /// terminal allocation cannot also be routing-eligible — that's
1229    /// the bug the typed projection closes (a `Failed` allocation
1230    /// that's neither `Released` nor `Bound` would otherwise slip
1231    /// through the open-coded gate in `observe` and try to rebind to
1232    /// a pool member). A future variant that flipped both predicates
1233    /// true would fail here, forcing the author to flip one or
1234    /// extend the consumer dispatch site in
1235    /// `tatara-pool-reconciler::allocation_decide` deliberately
1236    /// rather than letting an impossible state slip in.
1237    #[test]
1238    fn allocation_phase_terminal_excludes_routing() {
1239        for phase in AllocationPhase::ALL {
1240            assert!(
1241                !(phase.is_terminal() && phase.needs_pool_routing()),
1242                "{phase:?} is both terminal and routing-eligible",
1243            );
1244        }
1245    }
1246
1247    /// DEFAULT-AGREEMENT CONTRACT: `AllocationPhase::default()` is
1248    /// `Pending` — the entry state, neither terminal nor settled —
1249    /// and it lives on the routing path. A future default-variant
1250    /// rename without flipping the predicates fails here.
1251    #[test]
1252    fn allocation_phase_default_is_pending_and_routes() {
1253        let d = AllocationPhase::default();
1254        assert_eq!(d, AllocationPhase::Pending);
1255        assert!(!d.is_terminal());
1256        assert!(d.needs_pool_routing());
1257    }
1258
1259    // ── RequestorKind closed-set truth-table ─────────────────────────
1260
1261    /// Structural well-formedness of [`RequestorKind`] as a
1262    /// [`tatara_lisp::ClosedSet`] implementor — the workspace-wide
1263    /// testkit lift that pins all three structural invariants
1264    /// (`ALL` is non-empty, every variant round-trips through
1265    /// `label ↔ parse_label`, labels are pairwise distinct, `""` is
1266    /// outside the closed set) at ONE call site. Replaces the hand-
1267    /// derived `requestor_kind_all_enumerates_each_variant_exactly_once`
1268    /// + `requestor_kind_from_str_round_trips_canonical_names` + the
1269    /// empty-input arm of `requestor_kind_from_str_rejects_open_kinds`.
1270    /// `FromStr` delegates to
1271    /// `<Self as tatara_closed_set::ClosedSet>::parse_label`, so this helper
1272    /// exercises the same code path
1273    /// [`Requestor::known_kind`]'s `Option<RequestorKind>` collapse
1274    /// rides on when classifying inbound `Requestor.kind` strings. The
1275    /// arity is asserted by the `[Self; 4]` array type itself.
1276    #[test]
1277    fn requestor_kind_is_well_formed_closed_set() {
1278        tatara_closed_set::assert_closed_set_well_formed::<RequestorKind>();
1279    }
1280
1281    /// Byte-exact wire-format pin — renaming any of these is a wire-
1282    /// format change (the `tatara-github-watcher` emitter, the CRD
1283    /// printcolumns, the `PoolSelector.kinds` filter strings, the
1284    /// per-test `kind: "…".into()` fixtures all depend on these
1285    /// literals), not a typed-internal refactor.
1286    #[test]
1287    fn requestor_kind_canonical_names_pinned() {
1288        assert_eq!(RequestorKind::GithubPr.as_str(), "github-pr");
1289        assert_eq!(RequestorKind::Manual.as_str(), "manual");
1290        assert_eq!(RequestorKind::CiRun.as_str(), "ci-run");
1291        assert_eq!(RequestorKind::Scheduled.as_str(), "scheduled");
1292    }
1293
1294    /// `FromStr` rejects strings that aren't in the canonical
1295    /// projection — lowercased-mismatch / typo / unrelated — and the
1296    /// error echoes the input verbatim so the operator-facing
1297    /// diagnostic carries the offending value, not a normalized form.
1298    /// The schema is open at the wire layer (operators MAY register
1299    /// new kinds and `Requestor::known_kind` collapses them to
1300    /// `None`), but the closed-set view is byte-exact. The empty-input
1301    /// arm is pinned by [`requestor_kind_is_well_formed_closed_set`]
1302    /// via the `tatara_lisp::ClosedSet` testkit; the cases here pin
1303    /// the verbatim-echo contract on the [`UnknownRequestorKind`]
1304    /// newtype, which the trait's `make_unknown` can't see.
1305    #[test]
1306    fn requestor_kind_from_str_rejects_open_kinds() {
1307        for bad in [
1308            "github_pr",
1309            "GithubPr",
1310            "operator-custom-kind",
1311            "ci_run",
1312            "Scheduled",
1313        ] {
1314            let err = bad.parse::<RequestorKind>().unwrap_err();
1315            assert_eq!(err, UnknownRequestorKind(bad.to_string()));
1316        }
1317    }
1318
1319    /// The Display impl IS `as_str` — pinning this lets future
1320    /// callers reach for either projection without drift (Display is
1321    /// what operator-facing diagnostics compose against).
1322    #[test]
1323    fn requestor_kind_display_delegates_to_as_str() {
1324        for k in RequestorKind::ALL {
1325            assert_eq!(format!("{k}"), k.as_str());
1326        }
1327    }
1328
1329    /// The `String` projection that `From<RequestorKind> for String`
1330    /// ([`RequestorKind::into`]) composes is byte-equal to `as_str`.
1331    /// This is the typed → wire bridge — emitters spell
1332    /// `kind: RequestorKind::GithubPr.into()` and the canonical
1333    /// literal is materialized at ONE place.
1334    #[test]
1335    fn requestor_kind_into_string_matches_as_str() {
1336        for k in RequestorKind::ALL {
1337            let s: String = k.into();
1338            assert_eq!(s, k.as_str());
1339        }
1340    }
1341
1342    /// The typed → wire → typed round-trip: composing a `Requestor`
1343    /// with `kind: RequestorKind::X.into()` produces an object whose
1344    /// `known_kind()` decodes back to `X`. Pins the bridge invariant
1345    /// at the `Requestor` boundary, not just at `RequestorKind`.
1346    #[test]
1347    fn known_kind_decodes_built_requestors() {
1348        for k in RequestorKind::ALL {
1349            // Routes through the ONE substrate composer
1350            // `Requestor::kind_only` — one of TEN pre-lift exact-match
1351            // sites past the ★★ PRIME-DIRECTIVE ≥ 2 threshold.
1352            let r = Requestor::kind_only(k);
1353            assert_eq!(r.known_kind(), Some(k), "round-trip failed for {k:?}");
1354        }
1355    }
1356
1357    /// Open-by-design: a custom operator-registered kind still
1358    /// stamps a valid `Requestor` (no schema rejection), it just
1359    /// doesn't project through the closed-set typed view. Mirrors
1360    /// `ReceiptEnvelope::known_kind`'s open-kind posture.
1361    #[test]
1362    fn known_kind_returns_none_for_open_kinds() {
1363        // Routes through the ONE substrate composer
1364        // `Requestor::kind_only` — one of TEN pre-lift exact-match
1365        // sites past the ★★ PRIME-DIRECTIVE ≥ 2 threshold.
1366        let r = Requestor::kind_only("operator-custom-kind");
1367        assert_eq!(r.known_kind(), None);
1368    }
1369
1370    /// The four canonical literals match every previously-published
1371    /// fixture / doc anchor in this crate — pinning the bridge to
1372    /// existing call sites so any drift fails here before the next
1373    /// release ships.
1374    #[test]
1375    fn requestor_kind_matches_existing_fixture_literals() {
1376        // The `requestor_minimum_shape_round_trips` fixture above
1377        // composes `kind: "github-pr".into()` verbatim.
1378        assert_eq!(RequestorKind::GithubPr.as_str(), "github-pr");
1379        // The `allocation_spec_omits_optional_fields` fixture below
1380        // composes `kind: "manual".into()` verbatim.
1381        assert_eq!(RequestorKind::Manual.as_str(), "manual");
1382    }
1383
1384    // ─── Requestor::kind_only substrate pins ────────────────────────
1385    //
1386    // Fail-before-pass-after granularity: `Requestor::kind_only` did
1387    // not exist before this commit. The composer's job is to bind ONE
1388    // caller-varying slot (`kind`) and freeze the six-slot default
1389    // tail so a future addition to `Requestor` lands at ONE primitive
1390    // body rather than at every fixture / default-shape callsite.
1391    // Sibling to the `AplicacaoIntent::chart_only` pin family (the
1392    // 7-slot chart-pointer-only composer) and the `PoolSpec::with_template`
1393    // pin family (the 11-slot pool full-spec composer).
1394
1395    #[test]
1396    fn kind_only_binds_kind_slot_and_defaults_the_other_six() {
1397        // Positional-binding pin: the sole caller slot lands at
1398        // `kind`; every other slot lands at its safe empty default
1399        // (`None` / `vec![]`).
1400        let r = Requestor::kind_only("manual");
1401        assert_eq!(r.kind, "manual");
1402        assert!(r.repo.is_none());
1403        assert!(r.branch.is_none());
1404        assert!(r.pr_number.is_none());
1405        assert!(r.sha.is_none());
1406        assert!(r.pr_labels.is_empty());
1407        assert!(r.actor.is_none());
1408    }
1409
1410    #[test]
1411    fn kind_only_matches_hand_authored_pre_lift_struct_literal_shape() {
1412        // Byte-identity pin: every pre-lift `Requestor { kind: <lit>
1413        // .into(), repo: None, branch: None, pr_number: None, sha:
1414        // None, pr_labels: vec![], actor: None }` shape must
1415        // deserialize back to the same fixture composed via
1416        // `kind_only`. Sweeps the two families every callsite used
1417        // (`"manual"` — the operator-authored fixture at seven
1418        // sites; `"github-pr"` — the github-webhook fixture at three
1419        // sites) plus one open-kind sample (`"operator-custom-kind"` —
1420        // the `known_kind_returns_none_for_open_kinds` open-kind pin)
1421        // so any drift between the primitive and the pre-lift shape
1422        // surfaces at ONE pin rather than as silent fixture skew at
1423        // ten downstream consumers.
1424        for kind in ["manual", "github-pr", "operator-custom-kind"] {
1425            let via_primitive = Requestor::kind_only(kind);
1426            let hand_authored = Requestor {
1427                kind: kind.into(),
1428                repo: None,
1429                branch: None,
1430                pr_number: None,
1431                sha: None,
1432                pr_labels: vec![],
1433                actor: None,
1434            };
1435            let via_yaml = serde_yaml::to_string(&via_primitive).unwrap();
1436            let hand_yaml = serde_yaml::to_string(&hand_authored).unwrap();
1437            assert_eq!(
1438                via_yaml, hand_yaml,
1439                "kind_only({kind:?}) must be YAML-identical to the pre-lift struct literal"
1440            );
1441        }
1442    }
1443
1444    #[test]
1445    fn kind_only_accepts_string_and_str_and_requestor_kind_uniformly() {
1446        // `impl Into<String>` symmetry across the three caller shapes
1447        // pre-lift authors used verbatim: `&'static str` (`"manual"`),
1448        // owned `String` (from a formatted context), and
1449        // [`RequestorKind`] (via the `From<RequestorKind> for String`
1450        // bridge exercised at `known_kind_decodes_built_requestors`).
1451        let from_str_literal = Requestor::kind_only("manual");
1452        let from_owned_string = Requestor::kind_only(String::from("manual"));
1453        let from_typed_variant = Requestor::kind_only(RequestorKind::Manual);
1454        assert_eq!(from_str_literal.kind, "manual");
1455        assert_eq!(from_owned_string.kind, "manual");
1456        assert_eq!(from_typed_variant.kind, "manual");
1457    }
1458
1459    #[test]
1460    fn kind_only_composes_downstream_through_known_kind_projection() {
1461        // Cross-primitive coherence pin: every substrate-emitted
1462        // `RequestorKind` variant round-trips through `kind_only` +
1463        // `known_kind` back to the same typed variant. Byte-identical
1464        // to the `known_kind_decodes_built_requestors` sweep the
1465        // primitive replaced — pins the primitive as the composer the
1466        // typed decoder sees the SAME wire shape from.
1467        for k in RequestorKind::ALL {
1468            let r = Requestor::kind_only(k);
1469            assert_eq!(
1470                r.known_kind(),
1471                Some(k),
1472                "kind_only({k:?}).known_kind() must round-trip to Some({k:?})"
1473            );
1474        }
1475    }
1476
1477    // Per-implementor `unknown_X_message_matches_substrate_convention`
1478    // tests removed — clause (5) of
1479    // `tatara_closed_set::assert_closed_set_well_formed::<T>()` now verifies
1480    // the substrate-wide `"unknown {SET_LABEL}: {input}"` carrier shape
1481    // generically (called above on `RequestorKind` /
1482    // `AllocationPhase` through their `*_is_well_formed_closed_set`
1483    // sites). The `SET_LABEL` projection is pinned independently by
1484    // `tatara_lisp_derive::pascal_to_spaced_lowercase_tests` —
1485    // together the two contracts guarantee the operator-facing
1486    // diagnostic without needing per-enum literal pins.
1487
1488    // ─── EphemeralAllocation::observed_phase* substrate pins ────────
1489    //
1490    // Fail-before-pass-after granularity: neither `observed_phase` nor
1491    // `observed_phase_or_pending` existed before this commit, so each
1492    // pin fails to compile until the corresponding inherent method
1493    // lands. Post-lift the pins bind the missing-`status` corner + the
1494    // populated-status pass-through + byte-identical parity with the
1495    // pre-lift 5-line `.status.as_ref().map(|s| s.phase).unwrap_or
1496    // (AllocationPhase::Pending)` chain the pool reconciler's
1497    // `AllocationConvergenceCtx::observe` walked. Cross-CRD peer
1498    // coherence with `Process::observed_phase_or_pending` is pinned
1499    // by the `_matches_process_peer_shape` sweep at the tail.
1500
1501    fn alloc_with_phase(phase: AllocationPhase) -> EphemeralAllocation {
1502        // AllocationSpec rides through the ONE substrate composer
1503        // `AllocationSpec::requestor_only`; the inner Requestor rides
1504        // through the peer composer `Requestor::kind_only`. Nine pre-
1505        // lift exact-match `AllocationSpec { pool_ref: None,
1506        // requestor: <r>, ttl: None, note: None }` fixture sites past
1507        // the ★★ PRIME-DIRECTIVE ≥ 2 threshold collapse onto this
1508        // ONE substrate owner.
1509        let spec = AllocationSpec::requestor_only(Requestor::kind_only("manual"));
1510        let mut a = EphemeralAllocation::new("obs-alloc", spec);
1511        a.status = Some(AllocationStatus {
1512            phase,
1513            ..AllocationStatus::default()
1514        });
1515        a
1516    }
1517
1518    fn alloc_without_status() -> EphemeralAllocation {
1519        // AllocationSpec rides through `AllocationSpec::requestor_only`
1520        // — sibling to `alloc_with_phase`.
1521        let spec = AllocationSpec::requestor_only(Requestor::kind_only("manual"));
1522        let mut a = EphemeralAllocation::new("no-status-alloc", spec);
1523        a.status = None;
1524        a
1525    }
1526
1527    #[test]
1528    fn observed_phase_returns_none_when_status_is_none() {
1529        let a = alloc_without_status();
1530        assert!(a.observed_phase().is_none());
1531    }
1532
1533    #[test]
1534    fn observed_phase_returns_populated_variant_verbatim() {
1535        for p in AllocationPhase::ALL {
1536            let a = alloc_with_phase(p);
1537            assert_eq!(
1538                a.observed_phase(),
1539                Some(p),
1540                "observed_phase must project the persisted variant verbatim for {p:?}"
1541            );
1542        }
1543    }
1544
1545    #[test]
1546    fn observed_phase_matches_pre_lift_chain_bytewise() {
1547        // Sweep every corner: (status: None) plus every populated
1548        // (status: Some(phase)) variant. The pre-lift chain was
1549        // `alloc.status.as_ref().map(|s| s.phase)` — a 3-link chain
1550        // hand-authored inline at the observer. The primitive must
1551        // return the same `Option<AllocationPhase>` on every corner.
1552        let none_alloc = alloc_without_status();
1553        assert_eq!(
1554            none_alloc.observed_phase(),
1555            none_alloc.status.as_ref().map(|s| s.phase),
1556        );
1557        for p in AllocationPhase::ALL {
1558            let a = alloc_with_phase(p);
1559            assert_eq!(
1560                a.observed_phase(),
1561                a.status.as_ref().map(|s| s.phase),
1562                "primitive must be byte-identical to the pre-lift chain for {p:?}",
1563            );
1564        }
1565    }
1566
1567    #[test]
1568    fn observed_phase_or_pending_defaults_to_pending_when_status_absent() {
1569        let a = alloc_without_status();
1570        assert_eq!(a.observed_phase_or_pending(), AllocationPhase::Pending);
1571    }
1572
1573    #[test]
1574    fn observed_phase_or_pending_returns_populated_phase_verbatim() {
1575        for p in AllocationPhase::ALL {
1576            let a = alloc_with_phase(p);
1577            assert_eq!(
1578                a.observed_phase_or_pending(),
1579                p,
1580                "populated status must pass through verbatim for {p:?}"
1581            );
1582        }
1583    }
1584
1585    #[test]
1586    fn observed_phase_or_pending_defaults_agree_with_allocation_phase_default() {
1587        // The `Pending` sink is load-bearing as the "not yet observed"
1588        // default. `AllocationPhase::default()` returns `Pending`; the
1589        // primitive must return the same variant on the missing-status
1590        // corner. A future default-variant rename that flipped
1591        // `AllocationPhase::default` without flipping the primitive
1592        // (or vice versa) surfaces here as a divergent seed for the
1593        // routing ladder.
1594        let a = alloc_without_status();
1595        assert_eq!(a.observed_phase_or_pending(), AllocationPhase::default());
1596    }
1597
1598    #[test]
1599    fn observed_phase_or_pending_matches_pre_lift_chain_bytewise() {
1600        // The exact pre-lift 5-line chain in
1601        // `tatara-pool-reconciler::allocation_decide::
1602        // AllocationConvergenceCtx::observe` was:
1603        //     let phase = alloc
1604        //         .status
1605        //         .as_ref()
1606        //         .map(|s| s.phase)
1607        //         .unwrap_or(AllocationPhase::Pending);
1608        // Sweep every corner: (status: None) plus every populated
1609        // status variant. The primitive must be byte-identical for
1610        // every corner so the observer's routing decision matches
1611        // bytewise post-lift.
1612        let none_alloc = alloc_without_status();
1613        assert_eq!(
1614            none_alloc.observed_phase_or_pending(),
1615            none_alloc
1616                .status
1617                .as_ref()
1618                .map(|s| s.phase)
1619                .unwrap_or(AllocationPhase::Pending),
1620        );
1621        for p in AllocationPhase::ALL {
1622            let a = alloc_with_phase(p);
1623            assert_eq!(
1624                a.observed_phase_or_pending(),
1625                a.status
1626                    .as_ref()
1627                    .map(|s| s.phase)
1628                    .unwrap_or(AllocationPhase::Pending),
1629                "primitive must be byte-identical to the pre-lift 5-line chain for {p:?}",
1630            );
1631        }
1632    }
1633
1634    #[test]
1635    fn observed_phase_or_pending_composes_from_observed_phase() {
1636        // The composer sits on top of the borrow-form projection —
1637        // `observed_phase_or_pending() == observed_phase().unwrap_or
1638        // (Pending)`. Pinning the composition means a future
1639        // normalization step layered onto `observed_phase` (a
1640        // generation-filter, a staleness gate, a canonicalization
1641        // pass) reaches BOTH the raw-`Option` accessor and the
1642        // `Pending`-sinked composer through the SAME upstream body,
1643        // without needing a per-corner rewrite of the composer.
1644        let none_alloc = alloc_without_status();
1645        assert_eq!(
1646            none_alloc.observed_phase_or_pending(),
1647            none_alloc
1648                .observed_phase()
1649                .unwrap_or(AllocationPhase::Pending),
1650        );
1651        for p in AllocationPhase::ALL {
1652            let a = alloc_with_phase(p);
1653            assert_eq!(
1654                a.observed_phase_or_pending(),
1655                a.observed_phase().unwrap_or(AllocationPhase::Pending),
1656                "composer must ride on top of the borrow-form projection for {p:?}",
1657            );
1658        }
1659    }
1660
1661    #[test]
1662    fn observed_phase_is_a_pure_projection() {
1663        // Reading the phase twice must not mutate the allocation or
1664        // its status slot — pure projection semantics. Also witnesses
1665        // that the accessor doesn't clone / drop the inner `phase`
1666        // (the `Copy` scalar comes out identical on both reads).
1667        let a = alloc_with_phase(AllocationPhase::Bound);
1668        let one = a.observed_phase();
1669        let two = a.observed_phase();
1670        assert_eq!(one, two);
1671        assert!(a.status.is_some(), "projection must not consume the status");
1672    }
1673
1674    #[test]
1675    fn observed_phase_pending_missing_status_and_populated_pending_collapse_to_same_composer_output(
1676    ) {
1677        // A subtle correctness pin: the missing-`status` corner and
1678        // a populated-with-Pending status BOTH read as `Pending`
1679        // through the composer — the observer cannot distinguish the
1680        // two through this accessor. This matches the pre-lift 5-line
1681        // chain's semantics exactly (an operator patching
1682        // `status.phase: Pending` is indistinguishable from a
1683        // freshly-admitted allocation with no status stamped yet).
1684        // The borrow-form `observed_phase` accessor DOES distinguish
1685        // the two, so a caller that needs to tell them apart reaches
1686        // for the raw `Option`.
1687        let none_alloc = alloc_without_status();
1688        let pending_alloc = alloc_with_phase(AllocationPhase::Pending);
1689
1690        assert_eq!(
1691            none_alloc.observed_phase_or_pending(),
1692            pending_alloc.observed_phase_or_pending(),
1693        );
1694        assert_ne!(
1695            none_alloc.observed_phase(),
1696            pending_alloc.observed_phase(),
1697            "borrow-form accessor MUST distinguish missing-status from populated-Pending",
1698        );
1699    }
1700
1701    #[test]
1702    fn observed_phase_or_pending_missing_status_sink_agrees_with_process_peer_shape() {
1703        // Cross-CRD peer-axis coherence with
1704        // `Process::observed_phase_or_pending`. Both primitives walk
1705        // the identical `.status.as_ref().map(|s| s.phase).unwrap_or
1706        // (<Phase>::Pending)` chain differing ONLY in the `Phase`
1707        // type projected. On a missing-status observation, each
1708        // primitive must return its CRD's `Default`-equivalent
1709        // `Pending` variant — for `EphemeralAllocation` that's
1710        // `AllocationPhase::Pending`; for `Process` that's
1711        // `crate::phase::ProcessPhase::Pending`. This pin binds the
1712        // sink-parity structurally so a future rename of either
1713        // default variant surfaces here as a divergent seed for the
1714        // observer's routing / dispatch decision rather than as
1715        // silent drift between the two reconcilers.
1716        let no_status_alloc = alloc_without_status();
1717        assert_eq!(
1718            no_status_alloc.observed_phase_or_pending(),
1719            AllocationPhase::default(),
1720        );
1721        // Peer-axis invariant on the `Process` side — the primitive
1722        // that owns the same shape reads `ProcessPhase::Pending` on
1723        // the missing-status corner via its own inherent method. The
1724        // parity is coordinated at the `Default` seat: both CRDs'
1725        // phase types default to `Pending`, so a rename that broke
1726        // one without the other would fail one of these two
1727        // conjoined assertions.
1728        assert_eq!(AllocationPhase::default(), AllocationPhase::Pending,);
1729        assert_eq!(
1730            crate::phase::ProcessPhase::default(),
1731            crate::phase::ProcessPhase::Pending,
1732        );
1733    }
1734
1735    // ─── EphemeralAllocation::observed_bound_pool substrate pins ────
1736    //
1737    // The borrow-form status-projection primitive on the bound-pool
1738    // axis. Collapses the pre-lift hand-authored `.status.as_ref()
1739    // .and_then(|s| s.bound_pool.clone())` chain in
1740    // `tatara-pool-reconciler::allocation_decide::
1741    // AllocationConvergenceCtx::observe`'s `bound_pool` seed onto the
1742    // ONE substrate primitive. Cross-CRD peer to
1743    // `Process::observed_identity` on the (CRD × structured-record-
1744    // slot × borrow-form) axis pair — both primitives walk the
1745    // identical `.status.as_ref().and_then(|s| s.<slot>.as_ref())`
1746    // shape. Each pin is fail-before-pass-after: `observed_bound_pool`
1747    // did not exist pre-lift, so any test invoking it fails to compile
1748    // pre-lift and passes post-lift.
1749
1750    fn sample_pool_ref(name: &str, ns: &str) -> AllocationRef {
1751        // Fixture ref rides through the ONE substrate composer
1752        // `AllocationRef::new` — the `impl Into<String>` signature
1753        // accepts the borrow-form `&str` slot pair verbatim without
1754        // a per-fixture `.to_string()` promotion.
1755        AllocationRef::new(name, ns)
1756    }
1757
1758    fn alloc_with_bound_pool(bound: Option<AllocationRef>) -> EphemeralAllocation {
1759        // AllocationSpec rides through `AllocationSpec::requestor_only`
1760        // — sibling to `alloc_with_phase`.
1761        let spec = AllocationSpec::requestor_only(Requestor::kind_only("manual"));
1762        let mut a = EphemeralAllocation::new("bp-alloc", spec);
1763        a.status = Some(AllocationStatus {
1764            phase: AllocationPhase::Bound,
1765            bound_pool: bound,
1766            ..AllocationStatus::default()
1767        });
1768        a
1769    }
1770
1771    #[test]
1772    fn observed_bound_pool_returns_none_when_status_is_none() {
1773        // Missing-`status` corner pin: the primitive collapses the
1774        // no-status case to `None` so downstream `.is_some()` /
1775        // `if let Some(_)` / `.cloned().unwrap_or_else(...)` behave
1776        // identically on an `EphemeralAllocation` whose status field
1777        // is `None` and on one whose status carries an unpopulated
1778        // `bound_pool` slot. Matches the pre-lift `.and_then(...)`
1779        // chain's `None` byte-identically at the pool reconciler's
1780        // Release-composition seed.
1781        let a = alloc_without_status();
1782        assert!(a.observed_bound_pool().is_none());
1783    }
1784
1785    #[test]
1786    fn observed_bound_pool_returns_none_when_slot_is_none() {
1787        // Empty-slot-under-populated-status corner pin: the primitive
1788        // returns `None`, matching the missing-`status` corner byte-
1789        // identically. A regression that treated the two corners
1790        // differently would silently promote an internal representation
1791        // detail (whether the pool reconciler has ever written a
1792        // status subresource) into observable behavior at the
1793        // Release-composition branch of the allocation reconciler's
1794        // `decide` transition rule.
1795        let a = alloc_with_bound_pool(None);
1796        assert!(a.observed_bound_pool().is_none());
1797    }
1798
1799    #[test]
1800    fn observed_bound_pool_returns_borrow_when_slot_is_populated() {
1801        // Happy-path pin: with a populated `status.bound_pool` slot,
1802        // the primitive returns a borrowed `&AllocationRef` whose
1803        // (name, namespace) fields match the persisted record. A
1804        // regression that filtered / reshaped / canonicalized the
1805        // record would surface here rather than as silent skew at the
1806        // Release-composition seed's `.cloned()` materialization.
1807        let expected = sample_pool_ref("demo-pool", "pools");
1808        let a = alloc_with_bound_pool(Some(expected.clone()));
1809        let observed = a.observed_bound_pool().expect("populated slot");
1810        assert_eq!(observed, &expected);
1811        assert_eq!(observed.name, "demo-pool");
1812        assert_eq!(observed.namespace, "pools");
1813    }
1814
1815    #[test]
1816    fn observed_bound_pool_is_a_zero_copy_borrow_projection() {
1817        // Borrow-discipline pin: the returned reference points at the
1818        // persisted `AllocationRef` in place — NOT a fresh allocation
1819        // or a clone. A regression that switched the projection to an
1820        // owned `AllocationRef` (via `.clone()`) would defeat the
1821        // zero-copy contract the lift's primary strict-widening
1822        // delivers (the observer's Release-composition arm clones
1823        // once at the composition point where the
1824        // `AllocationConvergenceCtx` snapshot slot requires the owned
1825        // value). Peer to the sibling
1826        // `Process::observed_identity_is_a_zero_copy_borrow_projection`
1827        // pin on the `Process` CRD's `status.identity` slot.
1828        let a = alloc_with_bound_pool(Some(sample_pool_ref("demo-pool", "pools")));
1829        let observed = a.observed_bound_pool().expect("populated slot") as *const _;
1830        let persisted = a.status.as_ref().unwrap().bound_pool.as_ref().unwrap() as *const _;
1831        assert!(std::ptr::eq(observed, persisted));
1832    }
1833
1834    #[test]
1835    fn observed_bound_pool_is_a_pure_projection() {
1836        // Purity pin: calling the projection twice on the same
1837        // `EphemeralAllocation` returns byte-identical borrows (same
1838        // pointer). A regression that introduced state — a lazy-
1839        // cached reference, a normalization step that ran once and
1840        // cached — would surface here rather than as silent drift
1841        // between two dispatches within one reconcile pass.
1842        let a = alloc_with_bound_pool(Some(sample_pool_ref("demo-pool", "pools")));
1843        let one = a.observed_bound_pool().expect("populated slot") as *const _;
1844        let two = a.observed_bound_pool().expect("populated slot") as *const _;
1845        assert!(std::ptr::eq(one, two));
1846    }
1847
1848    #[test]
1849    fn observed_bound_pool_matches_pre_lift_chain_bytewise() {
1850        // Byte-identical parity pin between the borrow-form primitive
1851        // here and the pre-lift `tatara-pool-reconciler`
1852        // `.status.as_ref().and_then(|s| s.bound_pool.clone())` chain.
1853        // Sweeps every corner every callsite plausibly encounters
1854        // (missing status, empty `bound_pool` slot, populated
1855        // `bound_pool` slot). A regression that inserted a
1856        // normalization step at the primitive the pre-lift chain does
1857        // NOT apply — or vice versa — surfaces here rather than as
1858        // silent drift between the pre-lift consumer site and the ONE
1859        // substrate owner it now routes through.
1860        fn pre_lift(a: &EphemeralAllocation) -> Option<AllocationRef> {
1861            a.status.as_ref().and_then(|s| s.bound_pool.clone())
1862        }
1863        // Missing status.
1864        let a = alloc_without_status();
1865        assert_eq!(a.observed_bound_pool().cloned(), pre_lift(&a));
1866        // Populated status, empty `bound_pool` slot.
1867        let a = alloc_with_bound_pool(None);
1868        assert_eq!(a.observed_bound_pool().cloned(), pre_lift(&a));
1869        // Populated status, populated `bound_pool` slot.
1870        let a = alloc_with_bound_pool(Some(sample_pool_ref("demo-pool", "pools")));
1871        assert_eq!(a.observed_bound_pool().cloned(), pre_lift(&a));
1872    }
1873
1874    #[test]
1875    fn observed_bound_pool_missing_status_and_empty_slot_collapse_to_the_same_option_shape() {
1876        // Cross-corner coherence pin: the missing-`status` corner and
1877        // the populated-empty-slot corner return `Option`s whose
1878        // `.is_none()` / `.is_some()` observations are IDENTICAL. A
1879        // regression that promoted the missing-`status` corner to a
1880        // typed error (via a signature change to `Result<_, _>`) — or
1881        // that widened the empty-slot corner to a synthetic
1882        // `Some(AllocationRef::default())` — would surface here rather
1883        // than as silent operator-facing divergence between a never-
1884        // status-written allocation and a bound-pool-cleared
1885        // allocation on the Release-composition branch.
1886        let a_no_status = alloc_without_status();
1887        let a_empty_slot = alloc_with_bound_pool(None);
1888        assert_eq!(
1889            a_no_status.observed_bound_pool().is_none(),
1890            a_empty_slot.observed_bound_pool().is_none(),
1891        );
1892        assert_eq!(
1893            a_no_status.observed_bound_pool().is_some(),
1894            a_empty_slot.observed_bound_pool().is_some(),
1895        );
1896    }
1897
1898    #[test]
1899    fn observed_bound_pool_shape_agrees_with_process_observed_identity_peer_axis() {
1900        // Cross-CRD peer-axis coherence pin binding the SAME
1901        // `.status.as_ref().and_then(|s| s.<slot>.as_ref())` shape
1902        // that both `EphemeralAllocation::observed_bound_pool` (this
1903        // primitive) and `Process::observed_identity` walk, differing
1904        // ONLY in the record projected. Structural test — both
1905        // signatures must resolve as `&Self -> Option<&Record>` fn
1906        // pointers, so a future rename or a signature drift that
1907        // (say) widened one side to `Option<Record>` or narrowed one
1908        // side to `Option<&str>` fails to compile here rather than
1909        // silently drifting the two reconcilers apart at their
1910        // respective observer seeds. The runtime side of the pin
1911        // sweeps the missing-status + empty-slot corners on the
1912        // `EphemeralAllocation` half; the `Process` half is exercised
1913        // by its own `crd.rs::tests::observed_identity_*` pin
1914        // family — this test binds only the peer-axis shape.
1915        let a_no_status = alloc_without_status();
1916        let a_empty_slot = alloc_with_bound_pool(None);
1917        assert!(a_no_status.observed_bound_pool().is_none());
1918        assert!(a_empty_slot.observed_bound_pool().is_none());
1919        // Structural peer-axis coherence: bind both signatures as fn
1920        // pointers at their peer resolution type so the compiler
1921        // refuses to build if either side's shape drifts. The `_`
1922        // let-bindings assert the target type inference.
1923        let _bound_pool_shape: fn(&EphemeralAllocation) -> Option<&AllocationRef> =
1924            EphemeralAllocation::observed_bound_pool;
1925        let _identity_shape: fn(&crate::prelude::Process) -> Option<&crate::identity::Identity> =
1926            crate::prelude::Process::observed_identity;
1927    }
1928
1929    // ─── EphemeralAllocation::observed_expires_at substrate pins ────
1930    //
1931    // The copy-form status-projection primitive on the TTL-expiry axis.
1932    // Collapses the pre-lift hand-authored `.status.as_ref().and_then(
1933    // |s| s.expires_at)` chain in `tatara-pool-reconciler::
1934    // allocation_decide::AllocationConvergenceCtx::observe`'s
1935    // `expires_at` seed onto the ONE substrate primitive. Same-CRD peer
1936    // to `observed_phase` on the (copy-form × status-slot) axis — both
1937    // primitives walk the identical `.status.as_ref().<map|and_then>(
1938    // |s| s.<Copy-field>)` shape. Each pin is fail-before-pass-after:
1939    // `observed_expires_at` did not exist pre-lift, so any test invoking
1940    // it fails to compile pre-lift and passes post-lift.
1941
1942    fn alloc_with_expires_at(expires_at: Option<DateTime<Utc>>) -> EphemeralAllocation {
1943        // AllocationSpec rides through `AllocationSpec::requestor_only`
1944        // — sibling to `alloc_with_phase`.
1945        let spec = AllocationSpec::requestor_only(Requestor::kind_only("manual"));
1946        let mut a = EphemeralAllocation::new("exp-alloc", spec);
1947        a.status = Some(AllocationStatus {
1948            phase: AllocationPhase::Bound,
1949            expires_at,
1950            ..AllocationStatus::default()
1951        });
1952        a
1953    }
1954
1955    #[test]
1956    fn observed_expires_at_returns_none_when_status_is_none() {
1957        // Missing-`status` corner pin: the primitive collapses the
1958        // no-status case to `None` so downstream `.is_some()` / any
1959        // deadline comparison behaves identically on an
1960        // `EphemeralAllocation` whose status field is `None` and on
1961        // one whose status carries an unpopulated `expires_at` slot.
1962        // Matches the pre-lift `.and_then(...)` chain's `None` byte-
1963        // identically at the pool reconciler's Release-composition
1964        // TTL gate.
1965        let a = alloc_without_status();
1966        assert!(a.observed_expires_at().is_none());
1967    }
1968
1969    #[test]
1970    fn observed_expires_at_returns_none_when_slot_is_none() {
1971        // Empty-slot-under-populated-status corner pin: the primitive
1972        // returns `None`, matching the missing-`status` corner byte-
1973        // identically. A regression that treated the two corners
1974        // differently would silently promote an internal representation
1975        // detail (whether the pool reconciler has ever written a
1976        // `status.expires_at` field for a not-yet-Bound allocation)
1977        // into observable behavior at the Release-composition branch
1978        // of the allocation reconciler's `decide` transition rule.
1979        let a = alloc_with_expires_at(None);
1980        assert!(a.observed_expires_at().is_none());
1981    }
1982
1983    #[test]
1984    fn observed_expires_at_returns_populated_timestamp_verbatim() {
1985        // Happy-path pin: with a populated `status.expires_at` slot,
1986        // the primitive returns the persisted `DateTime<Utc>` verbatim.
1987        // A regression that filtered / clamped / canonicalized the
1988        // timestamp would surface here rather than as silent skew at
1989        // the Release-composition TTL gate's `>=` deadline comparison.
1990        let expected = Utc::now();
1991        let a = alloc_with_expires_at(Some(expected));
1992        assert_eq!(a.observed_expires_at(), Some(expected));
1993    }
1994
1995    #[test]
1996    fn observed_expires_at_is_a_pure_projection() {
1997        // Purity pin: calling the projection twice on the same
1998        // `EphemeralAllocation` returns byte-identical `Option`s. A
1999        // regression that introduced state — a lazy-cached value, a
2000        // normalization step that ran once and cached — would surface
2001        // here rather than as silent drift between two dispatches
2002        // within one reconcile pass.
2003        let expected = Utc::now();
2004        let a = alloc_with_expires_at(Some(expected));
2005        assert_eq!(a.observed_expires_at(), a.observed_expires_at());
2006    }
2007
2008    #[test]
2009    fn observed_expires_at_matches_pre_lift_chain_bytewise() {
2010        // Byte-identical parity pin between the copy-form primitive
2011        // here and the pre-lift `tatara-pool-reconciler`
2012        // `.status.as_ref().and_then(|s| s.expires_at)` chain. Sweeps
2013        // every corner every callsite plausibly encounters (missing
2014        // status, empty `expires_at` slot, populated `expires_at`
2015        // slot). A regression that inserted a normalization step at
2016        // the primitive the pre-lift chain does NOT apply — or vice
2017        // versa — surfaces here rather than as silent drift between
2018        // the pre-lift consumer site and the ONE substrate owner it
2019        // now routes through.
2020        fn pre_lift(a: &EphemeralAllocation) -> Option<DateTime<Utc>> {
2021            a.status.as_ref().and_then(|s| s.expires_at)
2022        }
2023        // Missing status.
2024        let a = alloc_without_status();
2025        assert_eq!(a.observed_expires_at(), pre_lift(&a));
2026        // Populated status, empty `expires_at` slot.
2027        let a = alloc_with_expires_at(None);
2028        assert_eq!(a.observed_expires_at(), pre_lift(&a));
2029        // Populated status, populated `expires_at` slot.
2030        let a = alloc_with_expires_at(Some(Utc::now()));
2031        assert_eq!(a.observed_expires_at(), pre_lift(&a));
2032    }
2033
2034    #[test]
2035    fn observed_expires_at_missing_status_and_empty_slot_collapse_to_the_same_option_shape() {
2036        // Cross-corner coherence pin: the missing-`status` corner and
2037        // the populated-empty-slot corner return `Option`s whose
2038        // `.is_none()` / `.is_some()` observations are IDENTICAL. A
2039        // regression that promoted the missing-`status` corner to a
2040        // typed error (via a signature change to `Result<_, _>`) — or
2041        // that widened the empty-slot corner to a synthetic
2042        // `Some(Utc::now())` — would surface here rather than as
2043        // silent operator-facing divergence between a never-status-
2044        // written allocation and a Bind-time-without-TTL allocation on
2045        // the Release-composition branch.
2046        let a_no_status = alloc_without_status();
2047        let a_empty_slot = alloc_with_expires_at(None);
2048        assert_eq!(
2049            a_no_status.observed_expires_at().is_none(),
2050            a_empty_slot.observed_expires_at().is_none(),
2051        );
2052        assert_eq!(
2053            a_no_status.observed_expires_at().is_some(),
2054            a_empty_slot.observed_expires_at().is_some(),
2055        );
2056    }
2057
2058    #[test]
2059    fn observed_expires_at_shape_agrees_with_observed_phase_peer_axis() {
2060        // Same-CRD peer-axis coherence pin binding the SAME
2061        // `.status.as_ref().<map|and_then>(|s| s.<Copy-field>)` shape
2062        // that both `EphemeralAllocation::observed_expires_at` (this
2063        // primitive) and `EphemeralAllocation::observed_phase` walk,
2064        // differing only in the outer combinator (`and_then` here
2065        // because the persisted field is itself `Option<T>`, `map`
2066        // there because the persisted phase is bare) and in the
2067        // projected `Copy` type. Structural test — both signatures
2068        // must resolve as `&Self -> Option<T>` fn pointers with `T`
2069        // `Copy`, so a future rename or a signature drift that (say)
2070        // widened one side to `Option<&T>` or narrowed one side to
2071        // `T` fails to compile here rather than silently drifting
2072        // the family apart. The runtime side of the pin sweeps the
2073        // missing-status + empty-slot corners on the `expires_at`
2074        // half; the `phase` half is exercised by its own
2075        // `tests::observed_phase_*` pin family — this test binds
2076        // only the peer-axis shape.
2077        let a_no_status = alloc_without_status();
2078        let a_empty_slot = alloc_with_expires_at(None);
2079        assert!(a_no_status.observed_expires_at().is_none());
2080        assert!(a_empty_slot.observed_expires_at().is_none());
2081        // Structural peer-axis coherence: bind both signatures as fn
2082        // pointers at their peer resolution type so the compiler
2083        // refuses to build if either side's shape drifts.
2084        let _expires_at_shape: fn(&EphemeralAllocation) -> Option<DateTime<Utc>> =
2085            EphemeralAllocation::observed_expires_at;
2086        let _phase_shape: fn(&EphemeralAllocation) -> Option<AllocationPhase> =
2087            EphemeralAllocation::observed_phase;
2088    }
2089
2090    #[test]
2091    fn allocation_spec_omits_optional_fields() {
2092        // AllocationSpec rides through `AllocationSpec::requestor_only`
2093        // + the inner Requestor through `Requestor::kind_only`; the
2094        // wire-shape pin still holds because BOTH composers produce
2095        // the byte-identical minimal shape whose `skip_serializing_if
2096        // = "Option::is_none"` + default-vec serde attributes elide
2097        // every optional slot from the YAML output.
2098        let s = AllocationSpec::requestor_only(Requestor::kind_only("manual"));
2099        let yaml = serde_yaml::to_string(&s).unwrap();
2100        assert!(!yaml.contains("poolRef"));
2101        assert!(!yaml.contains("ttl"));
2102        assert!(!yaml.contains("note"));
2103    }
2104
2105    // ─── AllocationSpec::requestor_only substrate pins ──────────────
2106    //
2107    // The pre-lift `AllocationSpec { pool_ref: None, requestor: <r>,
2108    // ttl: None, note: None }` incantation recurred at NINE workspace-
2109    // wide fixture sites past the ★★ PRIME-DIRECTIVE ≥ 2 threshold
2110    // (five inside this file's own test module, three inside the
2111    // crate's `tests_owned_coordinates` / `tests_annotated` /
2112    // `tests_deletion_tombstoned` pin modules on `lib.rs`, and one in
2113    // `tatara-pool-reconciler::allocation_decide::alloc`). Every corner
2114    // of the three-slot default tail is pinned here so a future
2115    // normalization at the primitive lands with a fail-before-pass-
2116    // after regression at THIS composer's pins rather than as silent
2117    // fixture skew across the nine callsite arms.
2118
2119    #[test]
2120    fn requestor_only_leaves_the_three_slot_default_tail_at_the_substrate_owner() {
2121        // Every default-tail slot must land at the values the substrate
2122        // owner stamps: `pool_ref = None` (selector-based routing),
2123        // `ttl = None` (fall back to pool template TTL), `note = None`
2124        // (empty audit slot). A regression that drifted ANY of the three
2125        // defaults would silently reshape every downstream fixture
2126        // simultaneously; this pin catches it.
2127        let s = AllocationSpec::requestor_only(Requestor::kind_only("manual"));
2128        assert!(s.pool_ref.is_none(), "pool_ref must default to None");
2129        assert!(s.ttl.is_none(), "ttl must default to None");
2130        assert!(s.note.is_none(), "note must default to None");
2131    }
2132
2133    #[test]
2134    fn requestor_only_stamps_the_caller_requestor_verbatim() {
2135        // The single caller-varying slot MUST pass through untouched —
2136        // a regression that copied only a subset of the Requestor's
2137        // seven slots (e.g. re-authoring `Requestor { kind: r.kind, ..
2138        // Default::default() }` inside the composer) would drop the
2139        // caller's `repo` / `branch` / `pr_number` / `sha` / `pr_labels`
2140        // / `actor` at every downstream fixture. Passes a fully-
2141        // populated `Requestor` through and asserts every slot lands.
2142        let r = Requestor {
2143            kind: "github-pr".into(),
2144            repo: Some("pleme-io/demo".into()),
2145            branch: Some("main".into()),
2146            pr_number: Some(42),
2147            sha: Some("deadbeef".into()),
2148            pr_labels: vec!["needs-review".into()],
2149            actor: Some("dozer".into()),
2150        };
2151        let s = AllocationSpec::requestor_only(r.clone());
2152        assert_eq!(s.requestor.kind, r.kind);
2153        assert_eq!(s.requestor.repo, r.repo);
2154        assert_eq!(s.requestor.branch, r.branch);
2155        assert_eq!(s.requestor.pr_number, r.pr_number);
2156        assert_eq!(s.requestor.sha, r.sha);
2157        assert_eq!(s.requestor.pr_labels, r.pr_labels);
2158        assert_eq!(s.requestor.actor, r.actor);
2159    }
2160
2161    #[test]
2162    fn requestor_only_matches_hand_authored_pre_lift_bytewise() {
2163        // Byte-identical parity with the pre-lift 5-line struct-
2164        // literal every downstream fixture restated verbatim. Swept
2165        // across the two representative requestor shapes: the
2166        // kind-only `"manual"` fixture (the majority of the collapsed
2167        // callsites) and the fully-populated github-pr requestor (the
2168        // `tatara-pool-reconciler::allocation_decide::alloc` shape).
2169        // A regression that reshaped the composer's output would
2170        // diverge from the pre-lift literal HERE rather than at every
2171        // downstream fixture's downstream assertion.
2172        let sample_requestors = [
2173            Requestor::kind_only("manual"),
2174            Requestor::kind_only("github-pr"),
2175            Requestor {
2176                kind: "github-pr".into(),
2177                repo: Some("pleme-io/demo".into()),
2178                branch: Some("main".into()),
2179                pr_number: None,
2180                sha: None,
2181                pr_labels: vec![],
2182                actor: None,
2183            },
2184        ];
2185        for r in sample_requestors {
2186            let via_primitive = AllocationSpec::requestor_only(r.clone());
2187            let hand_authored = AllocationSpec {
2188                pool_ref: None,
2189                requestor: r.clone(),
2190                ttl: None,
2191                note: None,
2192            };
2193            // Sweep every slot rather than round-tripping through
2194            // serde, so a slot rename that keeps the same serde name
2195            // still surfaces as a defect at the primitive's slot-
2196            // level parity.
2197            assert!(via_primitive.pool_ref.is_none() && hand_authored.pool_ref.is_none());
2198            assert_eq!(via_primitive.requestor.kind, hand_authored.requestor.kind);
2199            assert_eq!(via_primitive.ttl, hand_authored.ttl);
2200            assert_eq!(via_primitive.note, hand_authored.note);
2201        }
2202    }
2203
2204    // ─── AllocationStatus::transition substrate pins ────────────────────
2205    //
2206    // Pin the substrate composer at fail-before-pass-after granularity:
2207    // the composer did not exist pre-lift, so any regression against
2208    // the four hand-authored sites in
2209    // `tatara-pool-reconciler::controller_allocation::reconcile_inner`
2210    // surfaces at these pins rather than as silent operator-visible
2211    // status-patch skew.
2212
2213    fn anchor_time() -> DateTime<Utc> {
2214        // A deterministic non-`Utc::now()` anchor so pins that read
2215        // back `phase_since` do not race the wall clock.
2216        DateTime::parse_from_rfc3339("2026-05-01T00:00:00Z")
2217            .unwrap()
2218            .with_timezone(&Utc)
2219    }
2220
2221    #[test]
2222    fn allocation_status_transition_stamps_supplied_phase_verbatim() {
2223        for phase in AllocationPhase::ALL {
2224            let s = AllocationStatus::transition(phase, "irrelevant", anchor_time());
2225            assert_eq!(s.phase, phase, "phase drifted for {phase:?}");
2226        }
2227    }
2228
2229    #[test]
2230    fn allocation_status_transition_stamps_supplied_message_verbatim() {
2231        let s = AllocationStatus::transition(
2232            AllocationPhase::Queued,
2233            "pool matched; no Free member available",
2234            anchor_time(),
2235        );
2236        assert_eq!(
2237            s.message.as_deref(),
2238            Some("pool matched; no Free member available"),
2239        );
2240    }
2241
2242    #[test]
2243    fn allocation_status_transition_sets_phase_since_to_supplied_now() {
2244        let anchor = anchor_time();
2245        let s = AllocationStatus::transition(AllocationPhase::Bound, "bound", anchor);
2246        assert_eq!(
2247            s.phase_since,
2248            Some(anchor),
2249            "phase_since must be the supplied `now`, not a fresh Utc::now()",
2250        );
2251    }
2252
2253    #[test]
2254    fn allocation_status_transition_defaults_every_optional_slot() {
2255        // The composer stamps only the three always-present slots
2256        // (`phase + phase_since + message`); every other slot on
2257        // `AllocationStatus` must land at its `Default`-equivalent
2258        // variant so a caller-branch that attaches an optional slot
2259        // via struct-update syntax does not silently inherit a
2260        // pre-populated non-`None`/non-empty value.
2261        let s = AllocationStatus::transition(AllocationPhase::Released, "released", anchor_time());
2262        assert!(s.bound_pool.is_none(), "bound_pool must default to None");
2263        assert!(
2264            s.assigned_process.is_none(),
2265            "assigned_process must default to None"
2266        );
2267        assert!(
2268            s.allocated_at.is_none(),
2269            "allocated_at must default to None"
2270        );
2271        assert!(s.expires_at.is_none(), "expires_at must default to None");
2272        assert!(
2273            s.conditions.is_empty(),
2274            "conditions must default to an empty Vec"
2275        );
2276    }
2277
2278    #[test]
2279    fn allocation_status_transition_accepts_owned_string_and_static_str() {
2280        // `impl Into<String>` matches every current callsite:
2281        // three of the four hand-authored sites pass `&'static str`
2282        // literal reasons; the fourth ("bound to pool member") also
2283        // passes a `&'static str`. Sibling to
2284        // `tatara-reconciler::patch::phase_status_msg`'s identical
2285        // `impl Into<String>` signature.
2286        let via_static = AllocationStatus::transition(
2287            AllocationPhase::NoMatchingPool,
2288            "no Pool selector matched this Requestor",
2289            anchor_time(),
2290        );
2291        let via_owned = AllocationStatus::transition(
2292            AllocationPhase::NoMatchingPool,
2293            String::from("no Pool selector matched this Requestor"),
2294            anchor_time(),
2295        );
2296        assert_eq!(via_static.message, via_owned.message);
2297    }
2298
2299    #[test]
2300    fn allocation_status_transition_serializes_to_pre_lift_json_shape() {
2301        // Byte-shape pin against the exact `json!({ "status": {
2302        // "phase": <variant>, "phaseSince": <now>, "message": "<msg>"
2303        // } })` incantation every pre-lift callsite restated. A
2304        // regression that reordered a slot, dropped the `phaseSince`
2305        // stamp, or drifted the camelCase key naming here surfaces at
2306        // THIS pin rather than as a subtle patch_status body the K8s
2307        // API server accepts but the pool reconciler's next observe
2308        // pass fails to read back.
2309        let anchor = anchor_time();
2310        let via_composer =
2311            AllocationStatus::transition(AllocationPhase::NoMatchingPool, "no match", anchor);
2312        let composed = serde_json::json!({ "status": via_composer });
2313        let hand_authored = serde_json::json!({
2314            "status": {
2315                "phase": AllocationPhase::NoMatchingPool,
2316                "phaseSince": anchor,
2317                "message": "no match",
2318            }
2319        });
2320        assert_eq!(composed, hand_authored);
2321    }
2322
2323    #[test]
2324    fn allocation_status_transition_composes_with_struct_update_for_bind_seed() {
2325        // Pin the compound shape the `AllocationDecision::Bind`
2326        // callsite composes: the substrate seed carries `phase +
2327        // phase_since + message`, and the branch attaches
2328        // `bound_pool` + `assigned_process` + `allocated_at` +
2329        // `expires_at` via struct-update syntax. Post-lift the four
2330        // extra slots survive the compose intact and the base three
2331        // slots inherit the composer's stamps verbatim.
2332        let anchor = anchor_time();
2333        let ttl = anchor + chrono::Duration::hours(1);
2334        let pool = AllocationRef::new("demo-pool", "pools");
2335        let assigned = AllocationRef::new("demo-abcd", "pools");
2336        let bind_status = AllocationStatus {
2337            bound_pool: Some(pool.clone()),
2338            assigned_process: Some(assigned.clone()),
2339            allocated_at: Some(anchor),
2340            expires_at: Some(ttl),
2341            ..AllocationStatus::transition(AllocationPhase::Bound, "bound to pool member", anchor)
2342        };
2343        // Base-three slots stamped by the composer.
2344        assert_eq!(bind_status.phase, AllocationPhase::Bound);
2345        assert_eq!(bind_status.phase_since, Some(anchor));
2346        assert_eq!(bind_status.message.as_deref(), Some("bound to pool member"));
2347        // Struct-update-attached branch slots.
2348        assert_eq!(
2349            bind_status.bound_pool.as_ref().map(|r| &r.name),
2350            Some(&pool.name)
2351        );
2352        assert_eq!(
2353            bind_status.assigned_process.as_ref().map(|r| &r.name),
2354            Some(&assigned.name)
2355        );
2356        assert_eq!(bind_status.allocated_at, Some(anchor));
2357        assert_eq!(bind_status.expires_at, Some(ttl));
2358    }
2359
2360    // ─── AllocationStatus::bound_transition substrate pins ─────────────
2361    //
2362    // Pin the compound composer at fail-before-pass-after granularity:
2363    // the composer wraps [`AllocationStatus::transition`] with the
2364    // `bound_pool + assigned_process` pair the Bind / Release arms
2365    // both stamped inline pre-lift.
2366
2367    #[test]
2368    fn allocation_status_bound_transition_stamps_supplied_pool_and_process_verbatim() {
2369        let anchor = anchor_time();
2370        let pool = AllocationRef::new("demo-pool", "pools");
2371        let assigned = AllocationRef::new("demo-abcd", "pools");
2372        let s = AllocationStatus::bound_transition(
2373            AllocationPhase::Released,
2374            "released; pool reconciler will return the member",
2375            anchor,
2376            pool.clone(),
2377            assigned.clone(),
2378        );
2379        assert_eq!(s.bound_pool.as_ref(), Some(&pool));
2380        assert_eq!(s.assigned_process.as_ref(), Some(&assigned));
2381    }
2382
2383    #[test]
2384    fn allocation_status_bound_transition_inherits_transition_triplet_verbatim() {
2385        // The compound composer must not stamp its own `phase +
2386        // phase_since + message` triplet — it MUST compose the pair
2387        // atop the substrate `Self::transition` seed so any future
2388        // evolution to the base triplet lands at ONE site and this
2389        // composer inherits the upgrade mechanically. Pin the triplet
2390        // through the same axis-uniform reads the transition tests use.
2391        let anchor = anchor_time();
2392        let via_compound = AllocationStatus::bound_transition(
2393            AllocationPhase::Bound,
2394            "bound to pool member",
2395            anchor,
2396            AllocationRef::new("p", "ns"),
2397            AllocationRef::new("q", "ns"),
2398        );
2399        let via_base =
2400            AllocationStatus::transition(AllocationPhase::Bound, "bound to pool member", anchor);
2401        assert_eq!(via_compound.phase, via_base.phase);
2402        assert_eq!(via_compound.phase_since, via_base.phase_since);
2403        assert_eq!(via_compound.message, via_base.message);
2404    }
2405
2406    #[test]
2407    fn allocation_status_bound_transition_defaults_every_optional_slot_beyond_the_pair() {
2408        // The compound composer stamps only the base triplet + the
2409        // `bound_pool + assigned_process` pair; every other optional
2410        // slot (`allocated_at` / `expires_at` / `conditions`) must
2411        // land at its `Default`-equivalent variant so a caller-branch
2412        // that attaches an addendum via struct-update syntax (a Bind
2413        // arm's `allocated_at` + `expires_at` stamp) does not
2414        // silently inherit a pre-populated non-`None`/non-empty value.
2415        let s = AllocationStatus::bound_transition(
2416            AllocationPhase::Released,
2417            "released",
2418            anchor_time(),
2419            AllocationRef::new("p", "ns"),
2420            AllocationRef::new("q", "ns"),
2421        );
2422        assert!(
2423            s.allocated_at.is_none(),
2424            "allocated_at must default to None"
2425        );
2426        assert!(s.expires_at.is_none(), "expires_at must default to None");
2427        assert!(
2428            s.conditions.is_empty(),
2429            "conditions must default to an empty Vec"
2430        );
2431    }
2432
2433    #[test]
2434    fn allocation_status_bound_transition_composes_with_struct_update_for_bind_seed() {
2435        // Pin the compound shape the `AllocationDecision::Bind`
2436        // callsite post-lift composes: the compound composer seeds
2437        // `phase + phase_since + message + bound_pool +
2438        // assigned_process`, and the Bind branch attaches
2439        // `allocated_at` + `expires_at` via struct-update syntax.
2440        // Post-lift the two extra slots survive the compose intact
2441        // and the base five slots inherit the composer's stamps
2442        // verbatim.
2443        let anchor = anchor_time();
2444        let ttl = anchor + chrono::Duration::hours(1);
2445        let pool = AllocationRef::new("demo-pool", "pools");
2446        let assigned = AllocationRef::new("demo-abcd", "pools");
2447        let bind_status = AllocationStatus {
2448            allocated_at: Some(anchor),
2449            expires_at: Some(ttl),
2450            ..AllocationStatus::bound_transition(
2451                AllocationPhase::Bound,
2452                "bound to pool member",
2453                anchor,
2454                pool.clone(),
2455                assigned.clone(),
2456            )
2457        };
2458        assert_eq!(bind_status.phase, AllocationPhase::Bound);
2459        assert_eq!(bind_status.phase_since, Some(anchor));
2460        assert_eq!(bind_status.message.as_deref(), Some("bound to pool member"));
2461        assert_eq!(bind_status.bound_pool.as_ref(), Some(&pool));
2462        assert_eq!(bind_status.assigned_process.as_ref(), Some(&assigned));
2463        assert_eq!(bind_status.allocated_at, Some(anchor));
2464        assert_eq!(bind_status.expires_at, Some(ttl));
2465    }
2466
2467    #[test]
2468    fn allocation_status_bound_transition_matches_pre_lift_release_arm_verbatim() {
2469        // Byte-shape pin against the exact pre-lift `AllocationStatus
2470        // { bound_pool: Some(pool), assigned_process:
2471        // Some(AllocationRef::new(..)), ..AllocationStatus::transition
2472        // (Released, "…", now) }` composition the
2473        // `AllocationDecision::Release` arm restated inline pre-lift.
2474        // A regression that reordered the pair, dropped a `Some`, or
2475        // drifted the composed base triplet here surfaces at THIS pin
2476        // rather than as a subtle patch_status body the K8s API
2477        // server accepts but the audit record disagrees on.
2478        let anchor = anchor_time();
2479        let pool = AllocationRef::new("demo-pool", "pools");
2480        let assigned = AllocationRef::new("demo-abcd", "pools");
2481        let via_composer = AllocationStatus::bound_transition(
2482            AllocationPhase::Released,
2483            "released; pool reconciler will return the member",
2484            anchor,
2485            pool.clone(),
2486            assigned.clone(),
2487        );
2488        let via_hand_authored = AllocationStatus {
2489            bound_pool: Some(pool),
2490            assigned_process: Some(assigned),
2491            ..AllocationStatus::transition(
2492                AllocationPhase::Released,
2493                "released; pool reconciler will return the member",
2494                anchor,
2495            )
2496        };
2497        assert_eq!(
2498            serde_json::to_value(&via_composer).unwrap(),
2499            serde_json::to_value(&via_hand_authored).unwrap(),
2500        );
2501    }
2502
2503    #[test]
2504    fn allocation_status_transition_shape_agrees_with_pool_status_observed_peer() {
2505        // Cross-CRD peer-axis coherence: both substrate composers
2506        // (`PoolStatus::observed`, `AllocationStatus::transition`)
2507        // accept a caller-supplied `now: DateTime<Utc>` at the SAME
2508        // signature slot, stamp it into `phase_since` uniformly, and
2509        // leave every other slot at its `Default`-equivalent variant.
2510        // Structural pin: if either side's `now` signature drifts to
2511        // `impl Into<DateTime<Utc>>` or a reference form, this bind
2512        // fails to compile here rather than silently drifting the
2513        // family apart.
2514        let _allocation_shape: fn(
2515            AllocationPhase,
2516            &'static str,
2517            DateTime<Utc>,
2518        ) -> AllocationStatus = AllocationStatus::transition;
2519        // (`PoolStatus::observed`'s pinned coherence lives at its own
2520        // peer pin family in `crate::pool`; this pin binds the
2521        // `AllocationStatus::transition` side of the peer pair.)
2522    }
2523}