Skip to main content

tatara_process/
lib.rs

1//! Process CRD — the K8s-as-Unix-processes wire format.
2//!
3//! A `Process` is one element of the tatara convergence lattice.
4//! Clusters, HelmReleases, migrations, tests — all are Processes.
5//! The reconciliation loop *is* Unix: fork → exec → wait → exit → reap.
6
7pub mod allocation;
8pub mod anyhow_flatten;
9pub mod attestation;
10pub mod boundary;
11pub mod classification;
12pub mod compliance;
13pub mod configmap;
14pub mod crd;
15pub mod create;
16pub mod delete;
17pub mod encapsulates;
18pub mod env;
19pub mod ephemeral;
20pub mod err_ctx;
21pub mod export;
22pub mod flux_resource;
23pub mod hash;
24pub mod hostname;
25pub mod identity;
26pub mod intent;
27pub mod json_object;
28pub mod k8s_builtin_resource;
29pub mod k8s_object_ref;
30pub mod k8s_wire_identity;
31pub mod kube_error;
32pub mod lifetime;
33pub mod lifetime_clock;
34pub mod list;
35pub mod matrix;
36pub mod patch;
37pub mod phase;
38pub mod pool;
39pub mod process_api;
40pub mod receipt;
41pub mod requeue;
42pub mod routing;
43pub mod routing_edge_resource;
44pub mod signal;
45pub mod spec;
46pub mod status;
47pub mod table;
48pub mod tagged_union;
49pub mod three_pillar;
50pub mod time;
51
52pub mod prelude {
53    pub use crate::allocation::{
54        AllocationCondition, AllocationPhase, AllocationSpec, AllocationStatus,
55        EphemeralAllocation, Requestor,
56    };
57    pub use crate::anyhow_flatten::FlattenCtxExt;
58    pub use crate::attestation::ProcessAttestation;
59    pub use crate::boundary::{Boundary, Condition, ConditionKind, UnknownConditionKind};
60    pub use crate::classification::{
61        Arity, CalmClassification, Classification, ConvergencePointType, DataClassification,
62        Horizon, HorizonKind, OptimizationDirection, SubstrateType, UnknownCalmClassification,
63        UnknownConvergencePointType, UnknownDataClassification, UnknownHorizonKind,
64        UnknownOptimizationDirection, UnknownSubstrateType,
65    };
66    pub use crate::compliance::{
67        ComplianceBinding, ComplianceSpec, UnknownVerificationPhase, VerificationPhase,
68    };
69    pub use crate::crd::{Process, ProcessSpec, ProcessStatus};
70    pub use crate::encapsulates::{
71        BareWorkload, EncapsulatesSpec, EncapsulationKind, EncapsulationKindError,
72        EncapsulationKindVariant, EncapsulationMode, EncapsulationTarget, ExistingHelmRelease,
73        ExistingKustomization, UnknownEncapsulationMode, UnknownEncapsulationTarget,
74    };
75    pub use crate::ephemeral::{compile_ephemeral_source, EphemeralSpec};
76    pub use crate::err_ctx::ErrCtxExt;
77    pub use crate::export::{
78        ArtifactError, ArtifactKind, ArtifactSource, ArtifactVariant, ChannelError, ChannelKind,
79        ChannelVariant, ExportSpec, ExportTrigger, HttpEventChannel, NatsSubjectChannel,
80        ProcessSnapshotSource, ReceiptsSource, ReportFormat, ReportPayloadShape, RunMarkerSource,
81        StdoutChannel, TestReportSource, UnknownArtifactKind, UnknownChannelKind,
82        UnknownExportTrigger, UnknownReportFormat, VectorChannel, DEFAULT_NATS_URL,
83        DEFAULT_VECTOR_INGEST,
84    };
85    pub use crate::flux_resource::FluxResource;
86    pub use crate::hash::hex_blake3;
87    pub use crate::hostname::{
88        ephemeral_id_from_spec, fmt_fqdn, fmt_fqdn_stable, resolve_ephemeral_id, HostnameError,
89        HostnameResultExt, EPHEMERAL_ID_HASH_LEN,
90    };
91    pub use crate::identity::{content_hash, derive_identity, format_process_address, Identity};
92    pub use crate::intent::{
93        AplicacaoIntent, ContainerIntent, FluxIntent, GuestIntent, HelmLifecyclePolicy,
94        HelmRemediationPolicy, Intent, IntentError, IntentKind, IntentVariant, LispIntent,
95        NixIntent, UnknownWorkloadKind, WorkloadKind, FLUX_HELM_DEFAULT_INTERVAL,
96        HELM_LIFECYCLE_DEFAULT_RETRIES, HELM_LIFECYCLE_DEFAULT_TIMEOUT,
97    };
98    pub use crate::k8s_builtin_resource::K8sBuiltinResource;
99    pub use crate::k8s_object_ref::K8sObjectRef;
100    pub use crate::k8s_wire_identity::K8sWireIdentity;
101    pub use crate::lifetime::{
102        EphemeralLifetime, Lifetime, LifetimeError, LifetimeKind, LifetimeVariant,
103        PermanentLifetime, TeardownPolicy, UnknownTeardownPolicy,
104    };
105    pub use crate::lifetime_clock::{
106        evaluate as lifetime_clock_evaluate, AutoTerminate, AutoTerminateKind, TerminateReason,
107        TerminateReasonKind, UnknownAutoTerminateKind, UnknownTerminateReasonKind,
108    };
109    pub use crate::matrix::{
110        compile_env_matrix_source, EnvMatrixSpec, MatrixAxis, MatrixBudget, NamedEphemeral,
111        SelectStrategy, SelectStrategyKind, UnknownSelectStrategyKind,
112    };
113    pub use crate::phase::{ProcessPhase, UnknownPhase};
114    pub use crate::pool::{
115        AllocationRef, EphemeralPool, MatchKey, MemberState, PoolCondition, PoolMember, PoolPhase,
116        PoolSelector, PoolSpec, PoolStatus, ReplacementPolicy, ReturnPolicy, UnknownMemberState,
117        UnknownPoolPhase, UnknownReplacementPolicy,
118    };
119    pub use crate::qualified_process_ref;
120    pub use crate::receipt::{
121        default_receipt_config_map_name, extract_receipt_payload_json, ReceiptEnvelope,
122        ReceiptError, ReceiptKind, RECEIPT_CM_KEYS, RECEIPT_CM_MISSING_KEY_MSG, RECEIPT_CM_SUFFIX,
123        RECEIPT_JSON_KEY, RECEIPT_VERSION, RECEIPT_YAML_KEY,
124    };
125    pub use crate::requeue::after_secs as requeue_after_secs;
126    pub use crate::routing::{RoutingBackend, RoutingForm, RoutingHostname, RoutingSpec};
127    pub use crate::routing_edge_resource::RoutingEdgeResource;
128    pub use crate::signal::{ProcessSignal, SighupStrategy, UnknownSighupStrategy};
129    pub use crate::spec::{
130        DependsOn, IdentitySpec, MustReachPhase, SignalPolicy, UnknownMustReachPhase,
131    };
132    pub use crate::status::{
133        BoundaryStatus, CheckedCondition, ComplianceStatus, FluxResourceRef, ProcessCondition,
134        RenderedResourceCoords,
135    };
136    pub use crate::table::{
137        ClaimRecord, ProcessEntry, ProcessTable, ProcessTableSpec, ProcessTableStatus,
138    };
139    pub use crate::time::{elapsed_since, seconds_ago, tombstone_at, tombstone_now};
140    pub use crate::{Annotated, DeletionTombstoned, NamespacedApiCoordinates, PlacedInNamespace};
141}
142
143/// CRD API group for every tatara CRD.
144pub const GROUP: &str = "tatara.pleme.io";
145/// CRD version for this module.
146pub const VERSION: &str = "v1alpha1";
147/// Kind spelling of the tatara Process CRD as it appears in a K8s
148/// [`OwnerReference.kind`][ownref] field. Peer to [`GROUP`] +
149/// [`VERSION`] — centralizes the ONE literal every SSA-time
150/// re-injection helper pre-lift restated by hand across
151/// `tatara-reconciler` (`render.rs`, `edges.rs`, `ssapply.rs`).
152///
153/// [ownref]: https://kubernetes.io/docs/concepts/overview/working-with-objects/owners-dependents/
154pub const PROCESS_KIND: &str = "Process";
155
156/// Canonical `<GROUP>/<VERSION>` as an owned `String` — the ONE
157/// K8s `apiVersion` shape every tatara CRD stamps. Composed from
158/// [`GROUP`] + [`VERSION`] so a bump of either constant lands here
159/// exactly once; pre-lift, two `tatara-reconciler` sites hand-wrote
160/// `format!("{}/{}", tatara_process::GROUP, tatara_process::VERSION)`
161/// while a third inlined the literal `"tatara.pleme.io/v1alpha1"`,
162/// opening a silent drift path if `VERSION` ever advances past
163/// `v1alpha1`.
164pub fn api_version() -> String {
165    format!("{GROUP}/{VERSION}")
166}
167
168/// Substrate-primitive composer for the canonical
169/// **namespace-qualified process reference** — the `<ns>/<name>`
170/// string every consumer that grepped, keyed, or annotated a
171/// Process by "which cluster location owns it" hand-authored as
172/// `format!("{ns}/{name}")` at scattered sites across the workspace.
173/// Lifted onto `tatara-process` (from its prior home at
174/// `tatara_reconciler::ssapply::qualified_process_ref`) so callers
175/// BELOW the reconciler layer — `tatara-export-worker` (which does
176/// NOT depend on `tatara-reconciler`) and `tatara-pool-reconciler` —
177/// reach the SAME composer the reconciler-side sites do, closing
178/// the previously-open substrate corner where a downstream consumer
179/// re-authored the shape by hand rather than routing through the
180/// ONE primitive.
181///
182/// The `<ns>/<name>` shape is the workspace-wide convention for
183/// "how to name a namespaced K8s resource in a single string" — the
184/// same shape the K8s API server itself uses in
185/// [`OwnerReference`][ownref] pretty-printing, in the `holder` slot of
186/// [`crate::table::ClaimRecord`], and in the `tatara.pleme.io/process`
187/// annotation every reconciler-emitted resource carries. Callers
188/// with a live [`crate::prelude::Process`] compose through
189/// [`crate::prelude::Process::coordinates_or_defaults`] +
190/// [`Self`] (this function); callers with bare
191/// `(ns: &str, name: &str)` params (CLI-arg driven binaries,
192/// `metadata`-agnostic composers) call this directly.
193///
194/// The 2-arg signature encodes the invariant "the qualified
195/// reference is EXACTLY `<ns>/<name>`, in that order, joined by a
196/// single `/` separator" at the type level — a caller cannot
197/// accidentally swap the two axes (which would produce `<name>/<ns>`
198/// and silently break every downstream grep) nor omit either half,
199/// the way a pre-lift hand-authored `format!("{name}/{ns}")` or
200/// `format!("{ns}-{name}")` typo would.
201///
202/// A future change to the reference shape — a `<ns>/<name>@<gen>`
203/// multi-generation variant for attestation grepping, a
204/// `<cluster>/<ns>/<name>` cross-cluster form, a normalization
205/// (case-fold, unicode-safe collation) that must apply everywhere —
206/// lands at ONE substrate function here and every downstream
207/// composer (annotation seed, ProcessTable claim key, label
208/// selector, owner metadata, export-worker run-id fallback,
209/// receipt-owner filter) inherits the upgrade mechanically.
210///
211/// Theory anchor: THEORY.md §VI.1 (generation over composition —
212/// the `<ns>/<name>` shape recurred at hand-authored sites past the
213/// ★★ PRIME-DIRECTIVE ≥ 2 duplication trigger, and is lifted onto
214/// the ONE workspace-wide owner here). THEORY.md §II.1 invariant 5
215/// (composition preserves proofs — a regression that swapped the
216/// two axes or the separator at ONE site surfaces at
217/// [`qualified_process_ref_tests::qualified_process_ref_joins_ns_and_name_with_slash`]
218/// rather than as silent drift at every downstream annotation seed
219/// / claim key / label selector / run-id / receipt-owner filter).
220///
221/// [ownref]: https://kubernetes.io/docs/concepts/overview/working-with-objects/owners-dependents/
222#[must_use]
223pub fn qualified_process_ref(ns: &str, name: &str) -> String {
224    format!("{ns}/{name}")
225}
226
227/// Build a Kubernetes [`OwnerReference`][ownref] JSON blob pointing
228/// at a Process (`kind = `[`PROCESS_KIND`], `apiVersion = `
229/// [`api_version`]) with `controller: true` +
230/// `blockOwnerDeletion: true` — the exact 6-slot shape every SSA
231/// re-injection site pre-lift restated three times across
232/// `tatara-reconciler` (`render.rs::owner_refs` for export-Job
233/// owners, `edges.rs::build_owner_refs` for Ingress + DNSEndpoint
234/// owners, `ssapply.rs::build_owner_reference` for the injected
235/// owner-ref stamped on every applied `DynamicObject`). Callers
236/// with a live `Process` value read `metadata.{name,uid}` and pass
237/// them through as `&str`.
238///
239/// The 6-slot shape is fixed (`controller` + `blockOwnerDeletion`
240/// both `true`); a Process-owned resource that wants a non-
241/// controller reference doesn't belong on this owner and can build
242/// its own `json!` inline — this primitive is the composer for the
243/// canonical "Process controls this resource, cascade-delete on
244/// GC" shape, not a general OwnerReference builder.
245///
246/// [ownref]: https://kubernetes.io/docs/concepts/overview/working-with-objects/owners-dependents/
247pub fn owner_reference_json(name: &str, uid: &str) -> serde_json::Value {
248    serde_json::json!({
249        "apiVersion": api_version(),
250        "kind": PROCESS_KIND,
251        "name": name,
252        "uid": uid,
253        "controller": true,
254        "blockOwnerDeletion": true,
255    })
256}
257
258/// Substrate-primitive builder for a Process-owned resource's
259/// **`metadata.ownerReferences` array** — the empty-uid-gated,
260/// single-entry `Vec<Value>` every emit site that lacks a fully
261/// materialized [`crate::prelude::Process`] (i.e. every site that
262/// works from a bare `(name, uid)` pair rather than routing through
263/// [`ssapply::build_owner_reference`](../tatara_reconciler/ssapply/fn.build_owner_reference.html)'s
264/// anyhow-guarded unwrap) hand-composed by wrapping
265/// [`owner_reference_json`] in a `Vec::new()` + `is_empty` gate on
266/// the `uid` slot.
267///
268/// The `uid.is_empty()` gate encodes the invariant every caller
269/// already enforced: a Process pre-metadata (fixtured in tests, or
270/// caught mid-Forking before the API server has stamped a `uid`) has
271/// no admissible owner reference to point at, so the emit site
272/// stamps `metadata.ownerReferences: []` rather than an
273/// owner-referenceless resource pointing at a placeholder uid the K8s
274/// GC would silently ignore. Post-lift the gate lives at ONE
275/// primitive so a regression that inlined an owner reference for
276/// an empty uid — which the API server accepts and quietly detaches
277/// from cascade-delete — surfaces at THIS primitive's pin rather
278/// than as an operator-visible ownerless resource after apply.
279///
280/// Pre-lift the 3-line `let mut owner_refs = vec![]; if
281/// !uid.is_empty() { owner_refs.push(owner_reference_json(name,
282/// uid)); }` incantation was hand-authored at TWO sites past the
283/// ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold in
284/// `tatara-reconciler`, each restating the same gated composition:
285/// * `edges::build_owner_refs` — the shared owner-refs builder both
286///   `IngressEdge` + `DnsEndpointEdge` route through, sourcing
287///   `(process_name, process_uid)` from the [`crate::edges::EdgeContext`].
288/// * `render::one_export_job` — the export Job's owner-refs seed,
289///   sourcing `(name, uid)` from the [`crate::prelude::Process`]
290///   `render_export_jobs` threaded in.
291///
292/// Post-lift both callsites read `owner_references_json(name, uid)`.
293/// A future addition — e.g. a second owner-reference slot naming a
294/// controlling ProcessTable entry, a policy that stamps a stale-uid
295/// warning annotation before returning empty, or a normalization
296/// that strips a cluster-prefix off the uid — lands at ONE
297/// substrate function here and every emit site inherits the upgrade
298/// mechanically. The [`ssapply::build_owner_reference`] path (which
299/// works from a materialized [`crate::prelude::Process`] and errors
300/// on absent `metadata.uid`) is a peer, not a lift candidate: its
301/// contract is "the K8s API server assigned a uid, so refuse to
302/// SSA-apply resources whose owner cannot be materialized", while
303/// this primitive's contract is "the caller has an optional-uid
304/// posture; emit `[]` when the uid is absent". The two shapes
305/// partition the input space at the "is the enclosing scope
306/// obligated to produce a materialized Process reference" axis.
307///
308/// The 2-arg `(&str, &str)` signature accepts both the
309/// `EdgeContext`-sourced `(&str, &str)` slice shape and the
310/// `render_export_jobs`-owned `(name: &str, uid: &str)` local shape
311/// without widening — matches every current callsite.
312pub fn owner_references_json(name: &str, uid: &str) -> Vec<serde_json::Value> {
313    if uid.is_empty() {
314        vec![]
315    } else {
316        vec![owner_reference_json(name, uid)]
317    }
318}
319
320/// Substrate-primitive trait for the **`Api::namespaced`-shaped
321/// coordinate extraction** every tatara-CRD reconciler restated by
322/// hand at its top-level `reconcile` dispatcher: pull owned `String`
323/// forms of `metadata.namespace` and `metadata.name` and refuse to
324/// substitute a workspace-wide default for either slot, because the
325/// caller is about to feed the pair positionally into
326/// `Api::namespaced(client, &ns)` + `Api::patch(&name, …)` and the
327/// K8s API server refuses an empty-string name / namespace path
328/// segment.
329///
330/// Pre-lift the 5-line `.metadata.<slot>.clone().ok_or_else(||
331/// anyhow!("<Kind> has no metadata.<slot>"))?` chain (paired at both
332/// slots inside every controller's `reconcile_inner`) was hand-
333/// authored at TWO sites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication
334/// threshold in `tatara-pool-reconciler`, each restating the SAME
335/// (`namespace` errors, then `name` errors, both owned `String`)
336/// contract on a different CRD:
337/// * `controller_pool::reconcile_inner` — the pool reconciler's
338///   top-level `Pool has no metadata.{namespace,name}` gate,
339///   funneling every subsequent `Api::namespaced` + `Api::patch` call
340///   through the extracted `(ns, name)` pair.
341/// * `controller_allocation::reconcile_inner` — the allocation
342///   reconciler's peer gate on `EphemeralAllocation`, funneling the
343///   `Api::namespaced` + `Api::patch_status` calls that follow.
344///
345/// Both sites walked the SAME 5-line paired chain and both wanted the
346/// `(String, String)` form the primitive returns — because the
347/// produced `ns` outlives the source-object borrow (it feeds
348/// `Api::namespaced(client, &ns)` and later log-line interpolations
349/// across a stretch of `.await` points) and the `name` similarly
350/// threads through `Api::patch(&name, …)` calls downstream. Post-lift
351/// each callsite reads `pool.owned_coordinates_required()?` /
352/// `alloc.owned_coordinates_required()?` and the produced tuple
353/// destructures into the same downstream slots unchanged.
354///
355/// The blanket impl over `kube::Resource<DynamicType = ()>` (which
356/// every `#[derive(CustomResource)]`-generated tatara CRD satisfies)
357/// closes the substrate corner ONCE for the entire workspace: adding
358/// a third or fourth CRD in a peer crate — a routing-edge object, a
359/// receipt registry — inherits the extractor for free at its own
360/// `reconcile_inner` dispatcher with zero per-CRD lift work. This is
361/// the direction the CSE Compounding Directive names by
362/// "solve once, load-bearing fixes only": the primitive lands once
363/// and every downstream controller pattern-matches into it without
364/// re-authoring the chain.
365///
366/// Peer to [`crate::prelude::Process::owned_coordinates_or_err`] on
367/// the (`Process`-specific × namespace-required) axis pair — the two
368/// primitives partition the workspace's owned-form coordinate
369/// extraction on the `namespace-required` axis and cover the
370/// per-CRD needs they were opened for:
371///
372/// * ns-defaulted, name-required, `Process`-inherent →
373///   [`crate::prelude::Process::owned_coordinates_or_err`]
374///   (`tatara-reconciler`'s `phase_machine` / `signals` callers —
375///   consumers whose downstream tolerates the workspace's
376///   [`crate::prelude::Process::DEFAULT_NAMESPACE`] substitute for a
377///   `Process` fixtured pre-namespace-defaulting).
378/// * ns-required + name-required, blanket over every CRD → **this
379///   method** (`tatara-pool-reconciler`'s pool + allocation reconciler
380///   callers — consumers whose downstream refuses BOTH substitutions
381///   because the `Api::namespaced` dispatcher expects a real path
382///   segment on each axis and the enclosing controller is not
383///   authored to run against a namespace-less pool / allocation).
384///
385/// The error strings are shaped as `"{Kind} has no metadata.{slot}"`
386/// with `{Kind}` pulled positionally from `Self::kind(&())` (the
387/// kube-rs canonical CRD kind — `"EphemeralPool"` / `"EphemeralAllocation"`
388/// — which matches `kubectl get ephemeralpools|ephemeralallocations`
389/// output verbatim rather than the pre-lift `"Pool"` / `"Allocation"`
390/// short-forms every callsite hard-coded by hand). Routing the type
391/// name through `Self::kind` closes the drift path where a future
392/// CRD rename or a copy-paste consumer inherited the wrong short-
393/// form; the K8s-kind spelling is the ONE canonical name every
394/// operator-facing surface (kubectl output, RBAC subject strings,
395/// audit-log entries) already uses, so a log-line consumer greppping
396/// for either kind hits the primitive's canonical spelling directly.
397///
398/// A future normalization step (a per-CRD namespace canonicalization
399/// pass — case-fold, unicode-safe path-segment validation, a shared
400/// [`crate::prelude::Process::DEFAULT_NAMESPACE`]-aware fallback
401/// mode gated by an argument) lands at ONE substrate trait method
402/// here and every downstream reconciler picks up the upgrade
403/// mechanically — no per-callsite hand-edit at `controller_pool` /
404/// `controller_allocation` / any future CRD's `reconcile_inner`.
405///
406/// Theory anchor: THEORY.md §VI.1 (generation over composition —
407/// the paired 5-line `.metadata.<slot>.clone().ok_or_else` chain
408/// recurred at two hand-authored sites past the ★★ PRIME-DIRECTIVE
409/// ≥ 2 duplication trigger, and is lifted onto ONE trait method
410/// here). THEORY.md §II.1 invariant 5 (composition preserves
411/// proofs — the pins bind the missing-namespace corner, the
412/// missing-name corner, the missing-both corner (namespace error
413/// wins), the both-slots-present happy path, AND the
414/// `Self::kind`-driven error-string spelling per CRD, so a
415/// regression that reordered the two `ok_or_else` gates or drifted
416/// the error prefix surfaces at `tests::owned_coordinates_required_*`
417/// rather than as silent operator-facing skew between the two
418/// reconcilers' top-level error-message shapes).
419pub trait NamespacedApiCoordinates: kube::Resource<DynamicType = ()> {
420    /// Extract the K8s API path coordinates as owned `String`s,
421    /// erroring with a `Self::kind`-prefixed message when either
422    /// slot is absent. See the trait-level docs for the axis-family
423    /// context, peer primitives, and future-normalization anchor.
424    fn owned_coordinates_required(&self) -> anyhow::Result<(String, String)> {
425        let meta = self.meta();
426        let ns = meta
427            .namespace
428            .clone()
429            .ok_or_else(|| anyhow::anyhow!("{} has no metadata.namespace", Self::kind(&())))?;
430        let name = meta
431            .name
432            .clone()
433            .ok_or_else(|| anyhow::anyhow!("{} has no metadata.name", Self::kind(&())))?;
434        Ok((ns, name))
435    }
436}
437
438impl<T> NamespacedApiCoordinates for T where T: kube::Resource<DynamicType = ()> {}
439
440/// Substrate-primitive trait for the **deletion-tombstone presence
441/// probe** every tatara CRD reconciler restated as
442/// `.metadata.deletion_timestamp.is_some()` on the K8s-API-server-
443/// stamped `metadata.deletionTimestamp` slot: a `true` reading means
444/// the API server has accepted a DELETE and finalizers are draining
445/// (the object is still live but the controller must move into its
446/// SIGTERM cascade / DELETE-skip branch), while a `false` reading
447/// means no delete is in flight.
448///
449/// Pre-lift the ONE-line `.metadata.deletion_timestamp.is_some()`
450/// chain was hand-authored across every tatara-process CRD in
451/// consumer crates and independently re-authored as byte-identical
452/// inherent methods on [`crate::prelude::Process`] +
453/// [`crate::prelude::EphemeralPool`], with the sister CRD
454/// [`crate::prelude::EphemeralAllocation`] still on the raw chain in
455/// `tatara-pool-reconciler::allocation_decide::AllocationConvergenceCtx::observe`.
456/// That's TWO byte-identical inherent implementations past the ★★
457/// PRIME-DIRECTIVE ≥ 2 duplication threshold on the substrate side
458/// PLUS the hand-authored chain on the third CRD — three surfaces
459/// spelling the SAME projection, each with the same drift risk (a
460/// stale-tombstone grace-period gate, a paused-controller
461/// canonicalization, a cross-cluster clock-skew guard would have to
462/// land at every surface plus stay coherent).
463///
464/// Post-lift the substrate owns the probe at ONE trait method with a
465/// blanket impl over every `kube::Resource<DynamicType = ()>`, so:
466/// * [`crate::prelude::EphemeralAllocation`] inherits the probe for
467///   free — its `allocation_decide.rs` hand-authored chain routes
468///   through `alloc.is_being_deleted()` post-lift, closing the
469///   third-CRD gap noted in the [`crate::prelude::EphemeralPool::is_being_deleted`]
470///   commit body (`7f8f104`).
471/// * Any future tatara CRD (a routing-edge object, a receipt
472///   registry, a fleet-wide claim registry) inherits the probe at
473///   its own `reconcile_inner` dispatcher with zero per-CRD lift
474///   work — the same solve-once discipline
475///   [`NamespacedApiCoordinates`] established for the paired
476///   coordinate extractor.
477///
478/// The two existing inherent methods
479/// ([`crate::prelude::Process::is_being_deleted`] +
480/// [`crate::prelude::EphemeralPool::is_being_deleted`]) are peers
481/// rather than lift casualties: Rust method resolution prefers the
482/// inherent over the trait's blanket, so every existing callsite
483/// keeps hitting the same code path. The trait's blanket impl
484/// closes the substrate corner for CRDs WITHOUT the inherent — the
485/// coherence tests pin that the trait and the two inherents produce
486/// byte-identical results across every corner of the (missing,
487/// present) input matrix, so a future rewrite that consolidates
488/// onto the trait doesn't skew any consumer.
489///
490/// Return-form axis: `bool` matches the copy-form discipline of the
491/// two inherent peers and of [`crate::prelude::Process::observed_phase`]
492/// — the underlying wire-format slot is an `Option<Time>` carrying
493/// only presence information at this axis (the RFC-3339 timestamp
494/// payload itself is not what the callers read; all just probe
495/// presence to detect the tombstone-stamped state).
496///
497/// A future normalization step (a per-tombstone staleness gate
498/// returning `false` for a tombstone older than the reconciler's
499/// grace-period budget, a paused-controller tombstone
500/// canonicalization, a cross-cluster tombstone-observation clock
501/// skew guard) lands at ONE substrate trait method here — the two
502/// inherent forwarders inherit the upgrade mechanically if they are
503/// rewired to `<Self as DeletionTombstoned>::is_being_deleted(self)`
504/// as a follow-up sweep, and every downstream consumer that already
505/// routes through this trait picks it up without a per-callsite
506/// hand-edit.
507///
508/// Theory anchor: THEORY.md §VI.1 (generation over composition —
509/// the `.metadata.deletion_timestamp.is_some()` projection recurred
510/// as TWO byte-identical inherent implementations on
511/// [`crate::prelude::Process`] + [`crate::prelude::EphemeralPool`]
512/// past the ★★ PRIME-DIRECTIVE ≥ 2 duplication trigger and is
513/// lifted onto ONE trait method here). THEORY.md §II.1 invariant 5
514/// (composition preserves proofs — the pins bind the missing-
515/// tombstone corner + the present-tombstone corner + the copy-form
516/// `bool` return + the byte-identical parity with the pre-lift
517/// `.is_some()` chain + cross-CRD coherence with both inherent
518/// forwarders on the SAME `Process` / `EphemeralPool` value, so a
519/// regression that skewed either surface surfaces at
520/// `deletion_tombstoned_tests::*` rather than as silent operator-
521/// facing skew between the top-level dispatcher's SIGTERM preempt,
522/// the SIGTERM cascade's child-fan-out DELETE-skip, the pool
523/// reconciler's Drain gate, and the allocation reconciler's release
524/// short-circuit on three sibling CRDs.
525pub trait DeletionTombstoned: kube::Resource<DynamicType = ()> {
526    /// True iff the K8s API server has stamped `metadata.deletionTimestamp`
527    /// on this resource — a DELETE is in flight and finalizers are
528    /// draining. See the trait-level docs for the axis-family context,
529    /// peer inherent methods, and future-normalization anchor.
530    fn is_being_deleted(&self) -> bool {
531        self.meta().deletion_timestamp.is_some()
532    }
533}
534
535impl<T> DeletionTombstoned for T where T: kube::Resource<DynamicType = ()> {}
536
537/// Substrate-primitive trait for the ONE **borrow-form annotation
538/// lookup** every tatara CRD reconciler restated as the 3-line
539/// `.metadata.annotations.as_ref().and_then(|m| m.get(key)).map(String::as_str)`
540/// chain (or a `.cloned()` / `.cloned().unwrap_or_default()` variant
541/// of the same shape) on the K8s `metadata.annotations` map: returns
542/// `Some(&str)` iff the annotations block is present AND the key is
543/// present inside it; both missing corners collapse to `None`.
544///
545/// Peer to [`DeletionTombstoned`] + [`NamespacedApiCoordinates`] on
546/// the substrate-primitive-trait axis (kube-Resource blanket impls
547/// over `DynamicType = ()`), and peer to the pre-existing
548/// [`crate::prelude::Process::annotation`] inherent forwarder on the
549/// axis of "one annotation-lookup shape shared across every kube
550/// resource, tatara CRD or K8s built-in". The inherent stays as a
551/// peer — Rust method resolution prefers an inherent over a trait's
552/// blanket impl, so the three consumers already routed through
553/// `Process::annotation`
554/// (`tatara-reconciler::signals::ingest`,
555/// `tatara-reconciler::phase_machine::released_from_annotation`,
556/// `tatara-pool-reconciler::controller_pool::process_belongs_to_pool`)
557/// keep hitting the byte-identical code path — and the trait's
558/// blanket impl closes the substrate corner for kube resources
559/// WITHOUT the inherent: post-lift the hand-authored
560/// `.metadata.annotations.as_ref().and_then(|m| m.get(KEY))...` chain
561/// in `tatara-export-worker::main` (on `k8s_openapi`'s `ConfigMap`,
562/// which has no tatara-owned inherent) routes through the trait at
563/// `cm.annotation(KEY)`, and any future `EphemeralPool` /
564/// `EphemeralAllocation` (or new tatara CRD) consumer that needs an
565/// annotation lookup inherits the primitive for free — the same
566/// solve-once discipline the two peer traits already established.
567///
568/// Return-form axis: `Option<&str>` matches the borrow-first
569/// discipline of the peer metadata primitives
570/// ([`crate::prelude::Process::namespace_or_default`],
571/// [`crate::prelude::Process::name_or_placeholder`],
572/// [`crate::prelude::Process::coordinates_or_none`], and the inherent
573/// [`crate::prelude::Process::annotation`] this trait mirrors). The
574/// two corners the pre-lift chain swallowed (missing `annotations`
575/// map, missing key inside the map) BOTH collapse to `None` so
576/// `.is_some()` / `if let Some(_)` / `Option::map` behave identically
577/// on a resource whose annotations block is `None` and on one whose
578/// annotations block is populated but omits the key — matching what
579/// the pre-lift `.and_then(...)` chain produced.
580///
581/// A future normalization step (a key-canonicalization pass, a
582/// case-fold lookup, a per-key alias table for renamed annotations
583/// across API versions, a per-namespace override substrate) lands at
584/// ONE trait method here and every downstream consumer — the four
585/// current sites plus every future CRD reconciler that inherits the
586/// blanket impl — picks up the upgrade mechanically. If the inherent
587/// is ever rewired to `<Self as Annotated>::annotation(self, key)`
588/// as a follow-up sweep, the three inherent-preferred callsites
589/// automatically inherit any trait-level upgrade too.
590///
591/// Theory anchor: THEORY.md §VI.1 (generation over composition —
592/// the annotation-lookup shape recurred as ONE inherent forwarder on
593/// `Process` PLUS a hand-authored chain on `ConfigMap` past the
594/// ★★ PRIME-DIRECTIVE ≥ 2 duplication trigger, and is lifted onto
595/// ONE trait method here). THEORY.md §II.1 invariant 5 (composition
596/// preserves proofs — the pins bind the missing-annotations corner +
597/// the missing-key corner + the borrow-form `&str` lifetime + the
598/// byte-identical parity with the pre-lift 3-line chain + the
599/// cross-primitive coherence with `Process::annotation` on the SAME
600/// `Process` value, so a regression that skewed either surface
601/// surfaces at `annotated_tests::*` rather than as silent operator-
602/// facing skew between the SIGNAL / RELEASED_FROM / POOL annotation
603/// readers on Process and the receipts-owner filter on ConfigMap).
604pub trait Annotated: kube::Resource<DynamicType = ()> {
605    /// Borrow one key from `metadata.annotations`. See the trait-level
606    /// docs for the axis-family context, peer inherent method, and
607    /// future-normalization anchor.
608    fn annotation(&self, key: &str) -> Option<&str> {
609        self.meta()
610            .annotations
611            .as_ref()
612            .and_then(|m| m.get(key))
613            .map(String::as_str)
614    }
615}
616
617impl<T> Annotated for T where T: kube::Resource<DynamicType = ()> {}
618
619/// Substrate-primitive trait for the **place-in-namespace** fluent
620/// builder every consumer of a `kube::Resource` restated as
621/// `let mut cr = <CRD>::new(name, spec); cr.meta_mut().namespace = Some(ns.into()); cr`
622/// on the freshly-minted resource whose derive-supplied
623/// `::new(name, spec)` constructor stamps `metadata.name` alone and
624/// leaves `metadata.namespace` at `None`.
625///
626/// Pre-lift the pattern was hand-authored across THREE tatara-owned
627/// axes past the ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold:
628///
629/// * `tatara-reconciler::render::tests::render_through_top_level_intent_dispatch`
630///   — the ONE remaining hand-authored site on the `Process` CRD
631///   (the sibling `Process::new_in` was not opened in the prior
632///   pool/allocation sweep because no `Process`-side pool fixture
633///   restated the pattern at ≥ 2 sites in isolation).
634/// * [`crate::pool::EphemeralPool::new_in`] — a per-CRD inherent
635///   composer opened in commit `a5dbb26` that inlined the identical
636///   `Self::new(name, spec); metadata.namespace = Some(namespace.into())`
637///   body on the `EphemeralPool` axis.
638/// * [`crate::allocation::EphemeralAllocation::new_in`] — the sister
639///   inherent composer opened in the same commit on the
640///   `EphemeralAllocation` axis with the byte-identical body.
641///
642/// Post-lift the substrate owns the `metadata.namespace` stamp at
643/// ONE trait method with a blanket impl over every
644/// `kube::Resource<DynamicType = ()>`, so:
645///
646/// * The two per-CRD `new_in` composers forward through
647///   `Self::new(name, spec).in_namespace(namespace)` — three
648///   substrate copies of the mutation collapse to one. The
649///   composers keep their ergonomic per-CRD signatures so existing
650///   callers stay unchanged; only the body threads through here.
651/// * The `tatara-reconciler::render` fixture routes through
652///   `Process::new(...).in_namespace(...)` on the SAME trait method,
653///   closing the last hand-authored site on the tatara CRD trio.
654/// * Any future tatara CRD (a routing-edge object, a receipt
655///   registry, a fleet-wide claim registry) inherits the builder at
656///   its own operator-facing factory + its own test-fixture site
657///   with zero per-CRD lift work — the same solve-once discipline
658///   [`NamespacedApiCoordinates`] established for the paired
659///   coordinate extractor and [`DeletionTombstoned`] established
660///   for the deletion-tombstone probe.
661/// * Any K8s built-in CRD (`ConfigMap`, `Job`, `Ingress`) inherits
662///   the builder too — the sibling [`Annotated`] blanket already
663///   covers the same category on the annotation-read axis, so an
664///   emitter that composes a `ConfigMap` in a specific namespace can
665///   now write `<owner-composer>().in_namespace(ns)` on the SAME
666///   finished value.
667///
668/// Return-form axis: `Self` (owned, by-value) — the builder
669/// consumes `self` and returns the mutated value so chained
670/// composers read left-to-right as `<CRD>::new(name, spec)
671/// .in_namespace(ns)` in the ONE natural composition order operators
672/// reach for. Peer to the borrow-form observer
673/// [`Annotated::annotation`] on the (mutation direction ×
674/// ObjectMeta-slot family) axis pair; both traits close their
675/// respective ObjectMeta-slot corners at ONE trait method with a
676/// blanket impl over the SAME `kube::Resource<DynamicType = ()>`
677/// bound so a future consumer that alternates between reading an
678/// annotation and stamping a namespace never sees two different
679/// trait-import spellings.
680///
681/// A future normalization step (a per-fleet virtual-cluster prefix
682/// rewrite on the `namespace` slot, a per-cluster canonical
683/// case-fold pass, an operator-scoped default namespace for
684/// cluster-local test rigs, a promotion to a typed `Namespace`
685/// newtype that carries K8s DNS-1123 validation as a phantom-type
686/// guard) lands at ONE substrate trait method here — every
687/// downstream consumer routed through `.in_namespace(...)` picks up
688/// the upgrade mechanically, and the two per-CRD `new_in` composers
689/// inherit it for free through their one-line forwarders.
690///
691/// Theory anchor: THEORY.md §II.1 invariant 5 (composition preserves
692/// proofs — the pins bind `<CRD>::new(name, spec).in_namespace(ns)
693/// .metadata.namespace == Some(ns.to_string())` on every corner of
694/// the (CRD ∈ {`Process`, `EphemeralPool`, `EphemeralAllocation`,
695/// `ConfigMap`} × input form ∈ {`&str`, `String`}) input matrix
696/// PLUS the overwrite corner where `.in_namespace(a).in_namespace(b)`
697/// binds `b`, so a regression that skewed either surface surfaces
698/// at `placed_in_namespace_tests::*` rather than as silent
699/// operator-facing skew between the tatara-reconciler render
700/// fixture, the two per-CRD `new_in` composers, and any future
701/// CRD-adjacent namespace-stamping consumer). THEORY.md §VI.1
702/// (generation over composition — the mutation recurred as three
703/// substrate copies past the ★★ PRIME-DIRECTIVE ≥ 2 duplication
704/// trigger).
705pub trait PlacedInNamespace: kube::Resource<DynamicType = ()> + Sized {
706    /// Stamp `namespace` onto `self.metadata.namespace` and return
707    /// the mutated value by-value. See the trait-level docs for the
708    /// axis-family context, peer trait, and future-normalization
709    /// anchor.
710    #[must_use]
711    fn in_namespace(mut self, namespace: impl Into<String>) -> Self {
712        self.meta_mut().namespace = Some(namespace.into());
713        self
714    }
715}
716
717impl<T> PlacedInNamespace for T where T: kube::Resource<DynamicType = ()> {}
718
719/// Annotation keys the reconciler reads/writes on owned FluxCD resources.
720pub mod annotations {
721    pub const MANAGED_BY: &str = "tatara.pleme.io/managed-by";
722    pub const PROCESS: &str = "tatara.pleme.io/process";
723    pub const PID: &str = "tatara.pleme.io/pid";
724    pub const CONTENT_HASH: &str = "tatara.pleme.io/content-hash";
725    pub const ATTESTATION_ROOT: &str = "tatara.pleme.io/attestation-root";
726    pub const GENERATION: &str = "tatara.pleme.io/generation";
727    pub const SIGNAL: &str = "tatara.pleme.io/signal";
728    /// Stamped by the reconciler when transitioning into `Releasing`
729    /// — records which terminal-reached gate the Process came from
730    /// (`Attested` or `Failed`) so `handle_releasing` can pick the
731    /// matching `ExportTrigger` set + the correct post-Releasing
732    /// destination (`Exiting` from Attested, `Zombie` from Failed).
733    pub const RELEASED_FROM: &str = "tatara.pleme.io/released-from";
734    /// Labels the export-worker Jobs the reconciler emits during
735    /// `Releasing`. Selector: `tatara.pleme.io/role=export`.
736    pub const ROLE: &str = "tatara.pleme.io/role";
737    /// Index of an export inside `lifetime.ephemeral.exports`.
738    /// Stamped on the corresponding tatara-export-worker Job + its
739    /// receipt ConfigMap so the reconciler can correlate them
740    /// without re-parsing the spec JSON.
741    pub const EXPORT_INDEX: &str = "tatara.pleme.io/export-index";
742    /// Label / annotation key stamping which
743    /// `RoutingSpec.hostnames` entry a routing edge (Ingress /
744    /// DNSEndpoint) belongs to. Value is the entry's `app` slot;
745    /// a `label`-selector on this key slices every emitted edge
746    /// for a given `app` regardless of hostname form. Peer to
747    /// [`ROUTING_FORM`] on the routing-axis pair.
748    pub const APP: &str = "tatara.pleme.io/app";
749    /// Label / annotation key stamping the routing form
750    /// (`"stable"` | `"instance"`) on every emitted routing edge.
751    /// Value is a [`crate::routing::RoutingForm`] wire-form string;
752    /// consumers filtering the two forms compare to
753    /// [`RoutingForm::as_str`][crate::routing::RoutingForm::as_str],
754    /// never to a bare literal.
755    pub const ROUTING_FORM: &str = "tatara.pleme.io/routing-form";
756    /// Stamped by `tatara-pool-reconciler::controller_allocation::
757    /// reconcile` on the member `Process` at the moment an
758    /// `EphemeralAllocation` transitions Queued → Bound. Value is
759    /// the requestor Allocation's `<ns>/<name>` qualified reference
760    /// (composed through the same `<ns>/<name>` shape every peer
761    /// substrate composer routes through — see
762    /// [`crate::qualified_process_ref`]). Downstream consumers
763    /// (operator dashboards, admission webhooks, audit-trail
764    /// scrapers) grep for this key to answer "which allocator drove
765    /// this member Process into its ephemeral overlay".
766    pub const REQUESTOR: &str = "tatara.pleme.io/requestor";
767    /// Peer to [`REQUESTOR`] on the same allocator-bind axis: the
768    /// bare Allocation name (no namespace prefix), stamped alongside
769    /// so downstream consumers that key on the Allocation identity
770    /// alone (a single-namespace UI, an in-cluster label selector
771    /// that already carries the namespace) don't need to re-split
772    /// [`REQUESTOR`]'s composed reference.
773    pub const ALLOCATION: &str = "tatara.pleme.io/allocation";
774    /// Peer to [`REQUESTOR`] + [`ALLOCATION`] on the same
775    /// allocator-bind axis: mirrors
776    /// [`crate::allocation::RequestorRef.kind`] verbatim onto the
777    /// bound member Process so consumers that dispatch on the
778    /// requestor-kind axis (a GitHub-PR-scoped webhook, a
779    /// scheduler-window scoped fairness gate, a per-kind quota
780    /// enforcer) never have to fetch the Allocation object again.
781    pub const REQUESTOR_KIND: &str = "tatara.pleme.io/requestor-kind";
782    /// Stamped by `tatara-pool-reconciler::controller_pool::
783    /// build_member_process` on every Process the pool controller
784    /// materializes into a pool slot. Value is the owning
785    /// [`crate::pool::EphemeralPool`]'s `metadata.name`; the pool
786    /// controller's `process_belongs_to_pool` membership gate reads
787    /// this key back through the substrate primitive
788    /// [`crate::prelude::Process::annotation`] to filter its owned
789    /// members out of the cluster-wide Process listing. Peer to
790    /// [`POOL_SLOT`] on the same pool-membership axis; the two keys
791    /// travel together at every write site so any future rename (a
792    /// `tatara.pleme.io/v2/pool` migration, an alias table for
793    /// cross-cluster pool identity, a per-cluster ownership prefix)
794    /// lands at ONE `pub const` in the substrate and every
795    /// downstream consumer (the pool reconciler's membership gate,
796    /// any future observability label emitter, a cross-namespace
797    /// pool-topology walker) inherits the upgrade mechanically.
798    pub const POOL: &str = "tatara.pleme.io/pool";
799    /// Peer to [`POOL`] on the same pool-membership axis: the
800    /// zero-based slot index the pool controller assigned to the
801    /// member Process, stamped alongside so downstream consumers
802    /// that need per-slot identity (a UI grid layout, a per-slot
803    /// affinity gate, a slot-scoped audit-trail scraper) can
804    /// dispatch on it without re-scanning the pool controller's
805    /// naming scheme. Value is the slot's `u32` rendered through
806    /// `.to_string()`.
807    pub const POOL_SLOT: &str = "tatara.pleme.io/pool-slot";
808}
809
810/// Standard finalizer for the Process reconciler.
811pub const PROCESS_FINALIZER: &str = "tatara.pleme.io/process-finalizer";
812
813/// Shared schemars helpers — emit OpenAPI schemas Kubernetes accepts.
814/// Free-form `serde_json::Value` fields default to an *empty* schema
815/// in schemars, which the K8s API server rejects with "type: Required
816/// value: must not be empty for specified object fields". The typed
817/// workaround is to emit `{type: object, x-kubernetes-preserve-unknown-
818/// fields: true}` — same shape kube-rs's own helpers produce.
819pub mod schema_helpers {
820    use schemars::{gen::SchemaGenerator, schema::Schema};
821    /// Schema for a free-form JSON object field. Apply via
822    /// `#[schemars(schema_with = "tatara_process::schema_helpers::preserve_unknown_object")]`
823    /// on any `serde_json::Value` / `BTreeMap<String, serde_json::Value>`
824    /// field exposed through a CRD.
825    pub fn preserve_unknown_object(_g: &mut SchemaGenerator) -> Schema {
826        serde_json::from_value(serde_json::json!({
827            "type": "object",
828            "x-kubernetes-preserve-unknown-fields": true
829        }))
830        .expect("static JSON literal parses as Schema")
831    }
832}
833
834#[cfg(test)]
835mod owner_reference_tests {
836    //! Pin the `owner_reference_json` composer at fail-before-pass-
837    //! after granularity. Every shape a pre-lift caller hand-authored
838    //! is re-asserted here so a regression that inlined any of the
839    //! six slots at a call site (breaking the primitive's role as
840    //! the ONE source of truth) fails HERE at the composer's shipped-
841    //! shape pin rather than as silent drift between the pre-lift
842    //! `render.rs` / `edges.rs` / `ssapply.rs` sites (which pre-lift
843    //! already carried TWO different `apiVersion` spellings — a
844    //! composed `format!("{}/{}", GROUP, VERSION)` at two sites and
845    //! the frozen literal `"tatara.pleme.io/v1alpha1"` at the third).
846    use super::{
847        api_version, owner_reference_json, owner_references_json, GROUP, PROCESS_KIND, VERSION,
848    };
849    use serde_json::json;
850
851    #[test]
852    fn api_version_composes_group_and_version() {
853        // Any bump of GROUP or VERSION lands at ONE composer.
854        assert_eq!(api_version(), format!("{GROUP}/{VERSION}"));
855    }
856
857    #[test]
858    fn api_version_byte_matches_wire_form_pre_lift() {
859        // Byte-identity pin: the frozen wire-form literal
860        // `"tatara.pleme.io/v1alpha1"` that `ssapply.rs::
861        // build_owner_reference` hand-wrote pre-lift must equal the
862        // composed shape now sourced through the ONE owner. A
863        // future VERSION bump that missed this test would land as
864        // an operator-visible reference-mismatch after apply.
865        assert_eq!(api_version(), "tatara.pleme.io/v1alpha1");
866    }
867
868    #[test]
869    fn process_kind_is_process_literal() {
870        // Symbol-vs-string pin: any consumer that hand-wrote `"Process"`
871        // pre-lift routes through this const post-lift.
872        assert_eq!(PROCESS_KIND, "Process");
873    }
874
875    #[test]
876    fn owner_reference_json_has_all_six_slots_present() {
877        let v = owner_reference_json("my-process", "abc-uid");
878        let obj = v.as_object().expect("owner reference is a JSON object");
879        for k in [
880            "apiVersion",
881            "kind",
882            "name",
883            "uid",
884            "controller",
885            "blockOwnerDeletion",
886        ] {
887            assert!(obj.contains_key(k), "missing owner-reference slot: {k}");
888        }
889        assert_eq!(obj.len(), 6, "owner reference must have exactly 6 slots");
890    }
891
892    #[test]
893    fn owner_reference_json_apiversion_routes_through_api_version_owner() {
894        let v = owner_reference_json("x", "y");
895        assert_eq!(v["apiVersion"], api_version());
896    }
897
898    #[test]
899    fn owner_reference_json_kind_routes_through_process_kind_const() {
900        let v = owner_reference_json("x", "y");
901        assert_eq!(v["kind"], PROCESS_KIND);
902    }
903
904    #[test]
905    fn owner_reference_json_stamps_supplied_name_and_uid() {
906        let v = owner_reference_json("some-name", "some-uid");
907        assert_eq!(v["name"], "some-name");
908        assert_eq!(v["uid"], "some-uid");
909    }
910
911    #[test]
912    fn owner_reference_json_controller_and_block_owner_deletion_are_true() {
913        // These are structural — a Process-owned resource always
914        // has a controlling reference that cascade-deletes with
915        // the owner. A regression that flipped either boolean
916        // would silently detach every emitted resource.
917        let v = owner_reference_json("x", "y");
918        assert_eq!(v["controller"], true);
919        assert_eq!(v["blockOwnerDeletion"], true);
920    }
921
922    #[test]
923    fn owner_reference_json_matches_hand_authored_shape_pre_lift() {
924        // Byte-shape pin against the exact `json!({…})` incantation
925        // every pre-lift call site restated. A regression that
926        // reordered a slot, dropped one, or added a seventh here
927        // surfaces at THIS pin rather than as a subtle SSA-apply
928        // failure downstream when the K8s API server rejects the
929        // OwnerReference on schema mismatch.
930        let via_owner = owner_reference_json("p", "u");
931        let hand_authored = json!({
932            "apiVersion": "tatara.pleme.io/v1alpha1",
933            "kind": "Process",
934            "name": "p",
935            "uid": "u",
936            "controller": true,
937            "blockOwnerDeletion": true,
938        });
939        assert_eq!(via_owner, hand_authored);
940    }
941
942    #[test]
943    fn owner_reference_json_preserves_empty_name_and_uid_bytewise() {
944        // The primitive does not guard against empty inputs — its
945        // callers pre-lift did the empty-check upstream (both the
946        // `edges.rs::build_owner_refs` and `render.rs::one_export_job`
947        // sites gated on `!uid.is_empty()` before calling this composer,
948        // and both now route through `owner_references_json` below;
949        // `ssapply.rs::build_owner_reference` unwraps a required
950        // `metadata.uid` via anyhow). The scalar composer owns
951        // shape composition, not admission control; a downstream
952        // rename that wants strict input validation lands as a
953        // peer, not a change to the composer's contract.
954        let v = owner_reference_json("", "");
955        assert_eq!(v["name"], "");
956        assert_eq!(v["uid"], "");
957    }
958
959    // ─── owner_references_json substrate pins ────────────────────────
960    //
961    // The 3-line `let mut owner_refs = vec![]; if !uid.is_empty()
962    // { owner_refs.push(owner_reference_json(name, uid)); }` gate was
963    // hand-authored at TWO sites in `tatara-reconciler`
964    // (`edges::build_owner_refs` + `render::one_export_job`) before
965    // this primitive existed, each restating the same optional-uid
966    // posture that emits `[]` when the caller lacks a K8s-assigned
967    // uid to point owners at. These pins bind the primitive at
968    // fail-before-pass-after granularity so a regression that
969    // inlined an owner reference for an empty uid — silently
970    // detaching the resource from cascade-delete — surfaces HERE
971    // rather than as an operator-visible ownerless resource after
972    // apply, and a regression that added an owner reference of the
973    // wrong SHAPE (a peer of `owner_reference_json` that swapped a
974    // slot) surfaces via the composed-shape pin below rather than
975    // as silent drift at every downstream emit site.
976
977    #[test]
978    fn owner_references_json_emits_single_entry_when_uid_present() {
979        // The primary shape: a caller with a materialized uid gets
980        // exactly one owner reference back — the pre-lift 3-line
981        // `vec![]` + `push` gate collapses to this ONE call, and
982        // the returned array is a direct-drop `ownerReferences`
983        // slot value at every callsite.
984        let refs = owner_references_json("demo-app", "abc-uid");
985        assert_eq!(refs.len(), 1);
986        assert_eq!(refs[0]["kind"], PROCESS_KIND);
987        assert_eq!(refs[0]["name"], "demo-app");
988        assert_eq!(refs[0]["uid"], "abc-uid");
989        // controller + blockOwnerDeletion routed through the scalar
990        // composer — a regression that hand-composed the vec entry
991        // rather than delegating would flip one of these booleans.
992        assert_eq!(refs[0]["controller"], true);
993        assert_eq!(refs[0]["blockOwnerDeletion"], true);
994    }
995
996    #[test]
997    fn owner_references_json_emits_empty_when_uid_empty() {
998        // The load-bearing gate — a pre-metadata Process (fixtured in
999        // tests, or caught mid-Forking) has no admissible owner
1000        // reference to point at. Post-lift the gate lives at ONE
1001        // primitive so every emit site stamps `[]` uniformly rather
1002        // than one site accidentally emitting a placeholder-uid
1003        // owner reference the K8s GC would quietly detach from
1004        // cascade-delete.
1005        let refs = owner_references_json("demo-app", "");
1006        assert!(
1007            refs.is_empty(),
1008            "empty uid must produce zero owner references, not a placeholder-uid entry"
1009        );
1010    }
1011
1012    #[test]
1013    fn owner_references_json_gates_on_uid_not_name() {
1014        // The gate axis is `uid`, not `name` — a Process with a
1015        // non-empty name but no uid still emits `[]` (the pre-metadata
1016        // shape), while a Process with a non-empty uid emits ONE
1017        // entry even when the name slot is empty (matching the
1018        // scalar composer's admission-control-free contract). Pin
1019        // both cross-diagonal combinations so a regression that
1020        // swapped the gate axis surfaces HERE rather than at every
1021        // downstream owner-refs consumer.
1022        assert!(
1023            owner_references_json("has-name", "").is_empty(),
1024            "empty uid gates to []; name presence is irrelevant"
1025        );
1026        let refs = owner_references_json("", "has-uid");
1027        assert_eq!(
1028            refs.len(),
1029            1,
1030            "empty name but present uid still emits one entry (name is not the gate)"
1031        );
1032        assert_eq!(refs[0]["name"], "");
1033        assert_eq!(refs[0]["uid"], "has-uid");
1034    }
1035
1036    #[test]
1037    fn owner_references_json_matches_hand_authored_pre_lift_bytewise() {
1038        // Byte-identical parity with the exact pre-lift 3-line
1039        // `let mut owner_refs = vec![]; if !uid.is_empty() {
1040        // owner_refs.push(owner_reference_json(name, uid)); }` gate
1041        // across the two axis combinations every callsite plausibly
1042        // encounters. A regression that reordered the two branches,
1043        // dropped the gate, or reshaped the vec composition surfaces
1044        // HERE rather than at every downstream `ownerReferences`
1045        // slot pinned across `edges.rs` + `render.rs` tests.
1046        for (name, uid) in [
1047            ("demo-app", "uid-abc"),
1048            ("demo-app", ""),
1049            ("", "uid-abc"),
1050            ("", ""),
1051        ] {
1052            let via_primitive = owner_references_json(name, uid);
1053
1054            // The pre-lift 3-line block, byte-for-byte.
1055            let mut hand_authored: Vec<serde_json::Value> = vec![];
1056            if !uid.is_empty() {
1057                hand_authored.push(owner_reference_json(name, uid));
1058            }
1059
1060            assert_eq!(
1061                via_primitive, hand_authored,
1062                "owner_references_json must be byte-identical to the pre-lift 3-line gate on ({name:?}, {uid:?})"
1063            );
1064        }
1065    }
1066
1067    #[test]
1068    fn owner_references_json_interpolates_cleanly_as_owner_refs_slot() {
1069        // Both callsites drop the returned vec directly under a
1070        // `"ownerReferences"` key inside a `json!({...})` block. Pin
1071        // the interop shape: a JSON-macro-wrapped Value carries the
1072        // primitive's output as a JSON array with the exact 6-slot
1073        // entries at each index. A regression that returned a
1074        // non-array (e.g. a single Value on the one-entry path,
1075        // requiring per-site vec-wrapping) surfaces HERE rather than
1076        // as a broken `metadata.ownerReferences` slot on every
1077        // emitted Ingress / DNSEndpoint / export Job.
1078        let refs = owner_references_json("demo-app", "abc-uid");
1079        let wrapped = json!({
1080            "metadata": {
1081                "name": "resource",
1082                "ownerReferences": refs,
1083            },
1084        });
1085        let owner_refs = &wrapped["metadata"]["ownerReferences"];
1086        assert!(
1087            owner_refs.is_array(),
1088            "ownerReferences must land as a JSON array"
1089        );
1090        assert_eq!(owner_refs.as_array().unwrap().len(), 1);
1091        assert_eq!(owner_refs[0]["kind"], PROCESS_KIND);
1092
1093        // And the empty-uid path lands as an EMPTY array, not a
1094        // missing key or a null — matches the K8s API server's
1095        // expectation that the slot is either an array of entries
1096        // or absent, never a null.
1097        let empty_refs = owner_references_json("demo-app", "");
1098        let wrapped_empty = json!({
1099            "metadata": {
1100                "name": "resource",
1101                "ownerReferences": empty_refs,
1102            },
1103        });
1104        let owner_refs_empty = &wrapped_empty["metadata"]["ownerReferences"];
1105        assert!(owner_refs_empty.is_array());
1106        assert!(owner_refs_empty.as_array().unwrap().is_empty());
1107    }
1108}
1109
1110#[cfg(test)]
1111mod qualified_process_ref_tests {
1112    //! Pin the [`qualified_process_ref`] composer at fail-before-
1113    //! pass-after granularity. The `<ns>/<name>` shape is the
1114    //! workspace-wide convention for a namespaced K8s resource
1115    //! reference — every downstream grep (the reconciler's
1116    //! `tatara.pleme.io/process` annotation reader, the
1117    //! [`crate::table::ClaimRecord.holder`] slot, the
1118    //! export-worker's receipt-owner filter, the reconciler's
1119    //! `PROCESS=<ref>` label-selector composer) depends on the
1120    //! two axes landing in `(ns, name)` order joined by a single
1121    //! `/` separator. A regression that swapped the axes, dropped
1122    //! either half, or renormalized the input surfaces HERE rather
1123    //! than as silent operator-facing drift at every downstream
1124    //! consumer.
1125    use super::qualified_process_ref;
1126
1127    #[test]
1128    fn qualified_process_ref_joins_ns_and_name_with_slash() {
1129        // The invariant every downstream consumer composes against:
1130        // the qualified reference is EXACTLY `<ns>/<name>`, in that
1131        // order, joined by a single `/`.
1132        assert_eq!(
1133            qualified_process_ref("demo-ns", "ephemeral-demo"),
1134            "demo-ns/ephemeral-demo",
1135        );
1136    }
1137
1138    #[test]
1139    fn qualified_process_ref_binds_positional_slots_by_axis_order() {
1140        // Positional pin — a copy-paste that swapped the two `&str`
1141        // arguments (both mechanically interchangeable at the type
1142        // level) would silently produce `<name>/<ns>` and break every
1143        // downstream grep keyed on the reference shape. Distinct
1144        // input slot values so a swap surfaces as an equality
1145        // failure rather than accidental identity.
1146        let out = qualified_process_ref("first-slot-ns", "second-slot-name");
1147        assert!(
1148            out.starts_with("first-slot-ns/"),
1149            "position 0 must be the namespace slot: got {out}"
1150        );
1151        assert!(
1152            out.ends_with("/second-slot-name"),
1153            "position 1 must be the name slot: got {out}"
1154        );
1155    }
1156
1157    #[test]
1158    fn qualified_process_ref_accepts_string_deref_and_str_slice_shapes() {
1159        // Consumers split across two callsite shapes: owned
1160        // `String` locals (via deref coercion), bare `&str` slices,
1161        // and mixed provenance. Every shape must ride cleanly
1162        // through the same 2-arg signature — matches every current
1163        // pre-lift caller in `tatara-export-worker` (CLI-arg driven
1164        // owned strings + `&str` from a struct field) and in
1165        // `tatara-reconciler` (owned locals + function-param
1166        // slices).
1167        let owned_ns = String::from("owned-ns");
1168        let owned_name = String::from("owned-app");
1169        let borrowed_ns: &str = "borrowed-ns";
1170        let borrowed_name: &str = "borrowed-app";
1171        assert_eq!(
1172            qualified_process_ref(&owned_ns, &owned_name),
1173            "owned-ns/owned-app",
1174        );
1175        assert_eq!(
1176            qualified_process_ref(borrowed_ns, borrowed_name),
1177            "borrowed-ns/borrowed-app",
1178        );
1179        assert_eq!(
1180            qualified_process_ref(&owned_ns, borrowed_name),
1181            "owned-ns/borrowed-app",
1182        );
1183    }
1184
1185    #[test]
1186    fn qualified_process_ref_rides_edge_case_axis_shapes() {
1187        // The composer shapes the two axes as arbitrary strings —
1188        // no length/character validation happens at the composer,
1189        // so any shape a Process's `metadata.namespace` /
1190        // `metadata.name` can hold rides through unchanged. Pin
1191        // the empty-string cases (unnamed process pre-metadata,
1192        // cluster-scoped `namespace = ""` fallback), and the
1193        // whitespace-and-slash-in-name pathological case (a
1194        // regression that URL-escaped or path-normalized the input
1195        // at this primitive would silently break every downstream
1196        // grep).
1197        assert_eq!(qualified_process_ref("", ""), "/");
1198        assert_eq!(qualified_process_ref("default", ""), "default/");
1199        assert_eq!(qualified_process_ref("", "orphan"), "/orphan");
1200        assert_eq!(
1201            qualified_process_ref("weird ns", "with/slash"),
1202            "weird ns/with/slash",
1203        );
1204    }
1205
1206    #[test]
1207    fn qualified_process_ref_composes_from_process_coordinates_or_defaults() {
1208        // The primary Process-driven callsite: a live
1209        // [`crate::prelude::Process`] with populated metadata
1210        // composes through
1211        // [`crate::prelude::Process::coordinates_or_defaults`] +
1212        // [`qualified_process_ref`]. Pin the composition so a
1213        // regression in either primitive that broke the `(ns,
1214        // name)` positional contract surfaces HERE rather than as
1215        // silent drift at every downstream reconciler / export-
1216        // worker / pool-reconciler consumer.
1217        use crate::crd::{Process, ProcessSpec};
1218        // Routes through the ONE substrate composer
1219        // `ProcessSpec::gate_compute_defaults` — pre-lift this was a
1220        // 12-line inline struct-literal restated verbatim inside this
1221        // pin body.
1222        let spec = ProcessSpec::gate_compute_defaults();
1223        let mut p = Process::new("ephemeral-demo", spec);
1224        p.metadata.namespace = Some("demo-ns".into());
1225        let (ns, name) = p.coordinates_or_defaults();
1226        assert_eq!(
1227            qualified_process_ref(ns, name),
1228            "demo-ns/ephemeral-demo",
1229            "coordinates_or_defaults + qualified_process_ref must \
1230             compose to the canonical <ns>/<name> shape"
1231        );
1232    }
1233
1234    #[test]
1235    fn qualified_process_ref_matches_hand_authored_pre_lift_bytewise() {
1236        // Byte-identical parity with the exact pre-lift
1237        // `format!("{ns}/{name}")` incantation. A regression that
1238        // reshaped the separator, reordered the axes, or dropped
1239        // either half surfaces HERE rather than at every downstream
1240        // annotation / claim-key / run-id consumer. Sweeps every
1241        // shape combination the pre-lift callers plausibly
1242        // encountered.
1243        for (ns, name) in [
1244            ("demo-ns", "ephemeral-demo"),
1245            ("", ""),
1246            ("default", ""),
1247            ("", "orphan"),
1248        ] {
1249            let via_primitive = qualified_process_ref(ns, name);
1250            let hand_authored = format!("{ns}/{name}");
1251            assert_eq!(
1252                via_primitive, hand_authored,
1253                "qualified_process_ref must be byte-identical to \
1254                 the pre-lift `format!(\"{{ns}}/{{name}}\")` \
1255                 hand-authored shape on ({ns:?}, {name:?})"
1256            );
1257        }
1258    }
1259}
1260
1261#[cfg(test)]
1262mod namespaced_api_coordinates_tests {
1263    //! Pin the [`NamespacedApiCoordinates`] trait's
1264    //! `owned_coordinates_required` extractor at fail-before-pass-
1265    //! after granularity across every corner of the (namespace slot,
1266    //! name slot) × (present, absent) input matrix, on BOTH CRDs the
1267    //! trait's blanket impl covers today (`EphemeralPool` +
1268    //! `EphemeralAllocation`). A regression that reordered the two
1269    //! `ok_or_else` gates, dropped the `Self::kind` prefix, or drifted
1270    //! the error-string spelling surfaces HERE rather than as silent
1271    //! operator-facing skew between the two reconcilers' top-level
1272    //! error messages.
1273    use super::NamespacedApiCoordinates;
1274    use crate::allocation::{AllocationSpec, EphemeralAllocation, Requestor};
1275    use crate::ephemeral::EphemeralSpec;
1276    use crate::intent::AplicacaoIntent;
1277    use crate::lifetime::TeardownPolicy;
1278    use crate::pool::{EphemeralPool, PoolSpec};
1279
1280    fn empty_template() -> EphemeralSpec {
1281        // Mirror `tatara-pool-reconciler::router::tests::empty_template`
1282        // — the workspace-wide minimal `EphemeralSpec` fixture the sister
1283        // reconciler tests already use for pool wiring exercised here.
1284        EphemeralSpec {
1285            aplicacao: AplicacaoIntent::chart_only("oci://x", "1"),
1286            ttl: "1h".into(),
1287            teardown: TeardownPolicy::Always,
1288            max_concurrent: 0,
1289            postconditions: vec![],
1290            preconditions: vec![],
1291            verify_timeout: None,
1292            classification: None,
1293            parent: None,
1294            exports: vec![],
1295            routing: None,
1296        }
1297    }
1298
1299    fn pool_fixture(name: &str, ns: Option<&str>) -> EphemeralPool {
1300        // Every non-template slot rides the ONE substrate composer
1301        // [`PoolSpec::with_template`]; pre-lift this fixture spelled the
1302        // full 11-slot struct-literal verbatim as one of eight cross-
1303        // crate hand-authored copies. See the primitive's doc-comment
1304        // for the full migration rationale.
1305        let spec = PoolSpec {
1306            desired_size: 1,
1307            ..PoolSpec::with_template(empty_template())
1308        };
1309        let mut p = EphemeralPool::new(name, spec);
1310        p.metadata.namespace = ns.map(str::to_string);
1311        p
1312    }
1313
1314    fn alloc_fixture(name: &str, ns: Option<&str>) -> EphemeralAllocation {
1315        // AllocationSpec rides through the ONE substrate composer
1316        // `AllocationSpec::requestor_only`; the inner Requestor rides
1317        // through the peer composer `Requestor::kind_only`. Nine
1318        // pre-lift exact-match sites past the ★★ PRIME-DIRECTIVE ≥ 2
1319        // threshold collapse onto this ONE substrate owner.
1320        let spec = AllocationSpec::requestor_only(Requestor::kind_only("github-pr"));
1321        let mut a = EphemeralAllocation::new(name, spec);
1322        a.metadata.namespace = ns.map(str::to_string);
1323        a
1324    }
1325
1326    fn nameless_pool(ns: Option<&str>) -> EphemeralPool {
1327        let mut p = pool_fixture("placeholder", ns);
1328        p.metadata.name = None;
1329        p
1330    }
1331
1332    fn nameless_alloc(ns: Option<&str>) -> EphemeralAllocation {
1333        let mut a = alloc_fixture("placeholder", ns);
1334        a.metadata.name = None;
1335        a
1336    }
1337
1338    // ── Happy path: both slots present ─────────────────────────────
1339
1340    #[test]
1341    fn owned_coordinates_required_returns_owned_strings_on_ephemeral_pool_when_both_slots_present()
1342    {
1343        let p = pool_fixture("attest-pool", Some("ephemeral-pools"));
1344        let (ns, name) = p.owned_coordinates_required().unwrap();
1345        assert_eq!(ns, "ephemeral-pools");
1346        assert_eq!(name, "attest-pool");
1347    }
1348
1349    #[test]
1350    fn owned_coordinates_required_returns_owned_strings_on_ephemeral_allocation_when_both_slots_present(
1351    ) {
1352        let a = alloc_fixture("pr-42-demo", Some("ephemeral-pools"));
1353        let (ns, name) = a.owned_coordinates_required().unwrap();
1354        assert_eq!(ns, "ephemeral-pools");
1355        assert_eq!(name, "pr-42-demo");
1356    }
1357
1358    // ── Missing namespace ─────────────────────────────────────────
1359
1360    #[test]
1361    fn owned_coordinates_required_errors_on_ephemeral_pool_missing_namespace() {
1362        let p = pool_fixture("attest-pool", None);
1363        let err = p.owned_coordinates_required().unwrap_err();
1364        assert_eq!(err.to_string(), "EphemeralPool has no metadata.namespace");
1365    }
1366
1367    #[test]
1368    fn owned_coordinates_required_errors_on_ephemeral_allocation_missing_namespace() {
1369        let a = alloc_fixture("pr-42-demo", None);
1370        let err = a.owned_coordinates_required().unwrap_err();
1371        assert_eq!(
1372            err.to_string(),
1373            "EphemeralAllocation has no metadata.namespace"
1374        );
1375    }
1376
1377    // ── Missing name ──────────────────────────────────────────────
1378
1379    #[test]
1380    fn owned_coordinates_required_errors_on_ephemeral_pool_missing_name_when_namespace_present() {
1381        let p = nameless_pool(Some("ephemeral-pools"));
1382        let err = p.owned_coordinates_required().unwrap_err();
1383        assert_eq!(err.to_string(), "EphemeralPool has no metadata.name");
1384    }
1385
1386    #[test]
1387    fn owned_coordinates_required_errors_on_ephemeral_allocation_missing_name_when_namespace_present(
1388    ) {
1389        let a = nameless_alloc(Some("ephemeral-pools"));
1390        let err = a.owned_coordinates_required().unwrap_err();
1391        assert_eq!(err.to_string(), "EphemeralAllocation has no metadata.name");
1392    }
1393
1394    // ── Missing both slots: namespace error wins (pre-lift ordering) ──
1395
1396    #[test]
1397    fn owned_coordinates_required_reports_namespace_first_when_both_slots_absent_on_ephemeral_pool()
1398    {
1399        // Pre-lift both reconcilers spelled the paired chain as the
1400        // namespace ok_or_else THEN the name ok_or_else, so the
1401        // reported error on a fixture missing both slots was always
1402        // the namespace one. Pin that ordering post-lift so a
1403        // regression that swapped the two `ok_or_else` blocks
1404        // surfaces HERE rather than at operator-facing log-line
1405        // grep drift between the two reconcilers.
1406        let p = nameless_pool(None);
1407        let err = p.owned_coordinates_required().unwrap_err();
1408        assert_eq!(err.to_string(), "EphemeralPool has no metadata.namespace");
1409    }
1410
1411    #[test]
1412    fn owned_coordinates_required_reports_namespace_first_when_both_slots_absent_on_ephemeral_allocation(
1413    ) {
1414        let a = nameless_alloc(None);
1415        let err = a.owned_coordinates_required().unwrap_err();
1416        assert_eq!(
1417            err.to_string(),
1418            "EphemeralAllocation has no metadata.namespace"
1419        );
1420    }
1421
1422    // ── Byte-identical parity with the pre-lift 5-line chain ──────
1423
1424    #[test]
1425    fn owned_coordinates_required_matches_pre_lift_pool_reconciler_chain_shape() {
1426        // Byte-identical parity pin: the primitive produces the SAME
1427        // `Result<(String, String), anyhow::Error>` shape a pre-lift
1428        // `.metadata.<slot>.clone().ok_or_else(|| anyhow!("<Kind> has
1429        // no metadata.<slot>"))?` chain produced at
1430        // `tatara-pool-reconciler::controller_pool::reconcile_inner`
1431        // pre-lift, on both the happy and the missing-slot corners.
1432        // A regression that changed the error prefix, reordered the
1433        // two gates, or returned a non-`(String, String)` tuple
1434        // surfaces HERE rather than at every consumer downstream.
1435        let cases = [
1436            (Some("prod"), Some("api")),
1437            (Some("prod"), None),
1438            (None, Some("orphan")),
1439            (None, None),
1440        ];
1441        for (ns_slot, name_slot) in cases {
1442            let mut p = pool_fixture("placeholder", ns_slot);
1443            if let Some(nm) = name_slot {
1444                p.metadata.name = Some(nm.into());
1445            } else {
1446                p.metadata.name = None;
1447            }
1448
1449            // Pre-lift 5-line paired chain (with the reconciler's
1450            // hand-authored short-form `"Pool"` prefix updated to the
1451            // canonical kube kind `"EphemeralPool"`, matching the
1452            // primitive's `Self::kind`-driven spelling — the drift
1453            // is intentional per the trait's docs).
1454            let pre_lift: anyhow::Result<(String, String)> = (|| {
1455                let ns =
1456                    p.metadata.namespace.clone().ok_or_else(|| {
1457                        anyhow::anyhow!("EphemeralPool has no metadata.namespace")
1458                    })?;
1459                let name = p
1460                    .metadata
1461                    .name
1462                    .clone()
1463                    .ok_or_else(|| anyhow::anyhow!("EphemeralPool has no metadata.name"))?;
1464                Ok((ns, name))
1465            })();
1466
1467            let via_primitive = p.owned_coordinates_required();
1468
1469            // Compare on both the Ok tuple + the error string
1470            // spelling — anyhow::Error does not derive PartialEq so
1471            // pattern-match on the Result axis rather than a direct
1472            // `assert_eq!` on the whole Result.
1473            match (via_primitive, pre_lift) {
1474                (Ok(a), Ok(b)) => assert_eq!(a, b),
1475                (Err(a), Err(b)) => assert_eq!(a.to_string(), b.to_string()),
1476                (a, b) => panic!(
1477                    "primitive vs pre-lift chain disagree on Ok/Err axis for \
1478                     (ns={ns_slot:?}, name={name_slot:?}): primitive={a:?}, pre_lift={b:?}"
1479                ),
1480            }
1481        }
1482    }
1483
1484    #[test]
1485    fn owned_coordinates_required_matches_pre_lift_allocation_reconciler_chain_shape() {
1486        // Peer to the pool-side pin above — pin the same byte-
1487        // identity contract on the allocation reconciler's chain,
1488        // where the pre-lift error spelling used the short-form
1489        // `"Allocation"` prefix that the primitive now emits as the
1490        // canonical kube-kind `"EphemeralAllocation"`.
1491        let cases = [
1492            (Some("ephemeral-pools"), Some("pr-42-demo")),
1493            (Some("ephemeral-pools"), None),
1494            (None, Some("orphan")),
1495            (None, None),
1496        ];
1497        for (ns_slot, name_slot) in cases {
1498            let mut a = alloc_fixture("placeholder", ns_slot);
1499            if let Some(nm) = name_slot {
1500                a.metadata.name = Some(nm.into());
1501            } else {
1502                a.metadata.name = None;
1503            }
1504
1505            let pre_lift: anyhow::Result<(String, String)> = (|| {
1506                let ns = a.metadata.namespace.clone().ok_or_else(|| {
1507                    anyhow::anyhow!("EphemeralAllocation has no metadata.namespace")
1508                })?;
1509                let name =
1510                    a.metadata.name.clone().ok_or_else(|| {
1511                        anyhow::anyhow!("EphemeralAllocation has no metadata.name")
1512                    })?;
1513                Ok((ns, name))
1514            })();
1515
1516            let via_primitive = a.owned_coordinates_required();
1517
1518            match (via_primitive, pre_lift) {
1519                (Ok(a), Ok(b)) => assert_eq!(a, b),
1520                (Err(a), Err(b)) => assert_eq!(a.to_string(), b.to_string()),
1521                (a, b) => panic!(
1522                    "primitive vs pre-lift chain disagree on Ok/Err axis for \
1523                     (ns={ns_slot:?}, name={name_slot:?}): primitive={a:?}, pre_lift={b:?}"
1524                ),
1525            }
1526        }
1527    }
1528
1529    // ── Cross-CRD symmetry: kube kind drives the error prefix ─────
1530
1531    #[test]
1532    fn owned_coordinates_required_error_prefix_matches_kube_kind_on_each_crd() {
1533        // The error prefix is sourced positionally from `Self::kind`
1534        // so the two CRDs emit distinct kube-canonical spellings
1535        // without either callsite hard-coding a per-CRD literal.
1536        // Regressions that hard-coded a shared prefix (e.g. a
1537        // copy-paste that pasted the pool's error string into the
1538        // allocation callsite) surface HERE.
1539        use kube::Resource;
1540        let p = pool_fixture("p", None);
1541        let a = alloc_fixture("a", None);
1542        assert_eq!(
1543            p.owned_coordinates_required().unwrap_err().to_string(),
1544            format!("{} has no metadata.namespace", EphemeralPool::kind(&()))
1545        );
1546        assert_eq!(
1547            a.owned_coordinates_required().unwrap_err().to_string(),
1548            format!(
1549                "{} has no metadata.namespace",
1550                EphemeralAllocation::kind(&())
1551            )
1552        );
1553        // Belt-and-suspenders: the two kinds are distinct spellings,
1554        // so the error strings are distinct too.
1555        assert_ne!(
1556            p.owned_coordinates_required().unwrap_err().to_string(),
1557            a.owned_coordinates_required().unwrap_err().to_string(),
1558        );
1559    }
1560}
1561
1562#[cfg(test)]
1563mod deletion_tombstoned_tests {
1564    //! Pin the [`DeletionTombstoned`] trait's `is_being_deleted` probe
1565    //! at fail-before-pass-after granularity across every corner of
1566    //! the (tombstone present, tombstone absent) input matrix, on
1567    //! ALL THREE tatara-process CRDs the trait's blanket impl covers
1568    //! today (`Process`, `EphemeralPool`, `EphemeralAllocation`), plus
1569    //! the cross-CRD coherence with the two pre-existing inherent
1570    //! forwarders. A regression that skewed the trait's default,
1571    //! promoted a distinct-payload tombstone to a false negative, or
1572    //! diverged the trait from either inherent forwarder surfaces
1573    //! HERE rather than as silent operator-facing skew between the
1574    //! four consumer sites the primitive owns (the top-level
1575    //! dispatcher's SIGTERM preempt, the SIGTERM cascade's child-
1576    //! fan-out DELETE-skip, the pool reconciler's Drain gate, and
1577    //! the allocation reconciler's release short-circuit) on three
1578    //! sibling CRDs.
1579    use super::DeletionTombstoned;
1580    use crate::allocation::{AllocationSpec, EphemeralAllocation, Requestor};
1581    use crate::crd::{Process, ProcessSpec};
1582    use crate::ephemeral::EphemeralSpec;
1583    use crate::intent::AplicacaoIntent;
1584    use crate::lifetime::TeardownPolicy;
1585    use crate::pool::{EphemeralPool, PoolSpec};
1586    use k8s_openapi::apimachinery::pkg::apis::meta::v1::Time;
1587
1588    fn empty_template() -> EphemeralSpec {
1589        EphemeralSpec {
1590            aplicacao: AplicacaoIntent::chart_only("oci://x", "1"),
1591            ttl: "1h".into(),
1592            teardown: TeardownPolicy::Always,
1593            max_concurrent: 0,
1594            postconditions: vec![],
1595            preconditions: vec![],
1596            verify_timeout: None,
1597            classification: None,
1598            parent: None,
1599            exports: vec![],
1600            routing: None,
1601        }
1602    }
1603
1604    fn empty_pool_spec() -> PoolSpec {
1605        // Every non-template slot rides the ONE substrate composer
1606        // [`PoolSpec::with_template`]; see the primitive's doc-comment
1607        // for the full migration rationale.
1608        PoolSpec {
1609            desired_size: 1,
1610            ..PoolSpec::with_template(empty_template())
1611        }
1612    }
1613
1614    fn empty_alloc_spec() -> AllocationSpec {
1615        // AllocationSpec rides through the ONE substrate composer
1616        // `AllocationSpec::requestor_only`; the inner Requestor rides
1617        // through `Requestor::kind_only`. Nine pre-lift exact-match
1618        // fixture sites past the ★★ PRIME-DIRECTIVE ≥ 2 threshold
1619        // collapse onto this ONE substrate owner.
1620        AllocationSpec::requestor_only(Requestor::kind_only("github-pr"))
1621    }
1622
1623    fn empty_process_spec() -> ProcessSpec {
1624        // Routes through the ONE substrate composer
1625        // `ProcessSpec::gate_compute_defaults` — the minimal
1626        // `ProcessSpec` used across every substrate metadata-projection
1627        // pin. Pre-lift this was the 12-line struct-literal restated
1628        // verbatim at every fixture in this pin family.
1629        ProcessSpec::gate_compute_defaults()
1630    }
1631
1632    // ── Missing tombstone (default fixture) — trait returns false ─────
1633
1634    #[test]
1635    fn is_being_deleted_on_process_missing_tombstone_returns_false_via_trait() {
1636        let p = Process::new("api", empty_process_spec());
1637        assert!(!DeletionTombstoned::is_being_deleted(&p));
1638    }
1639
1640    #[test]
1641    fn is_being_deleted_on_ephemeral_pool_missing_tombstone_returns_false_via_trait() {
1642        let p = EphemeralPool::new("attest-pool", empty_pool_spec());
1643        assert!(!DeletionTombstoned::is_being_deleted(&p));
1644    }
1645
1646    #[test]
1647    fn is_being_deleted_on_ephemeral_allocation_missing_tombstone_returns_false_via_trait() {
1648        // The load-bearing corner: EphemeralAllocation had NO inherent
1649        // is_being_deleted pre-lift — the trait's blanket impl is
1650        // what closes the substrate gap for the allocation reconciler's
1651        // hand-authored `.metadata.deletion_timestamp.is_some()` chain.
1652        let a = EphemeralAllocation::new("pr-42-demo", empty_alloc_spec());
1653        assert!(!DeletionTombstoned::is_being_deleted(&a));
1654    }
1655
1656    // ── Present tombstone — trait returns true ────────────────────────
1657
1658    #[test]
1659    fn is_being_deleted_on_process_present_tombstone_returns_true_via_trait() {
1660        let mut p = Process::new("api", empty_process_spec());
1661        // Routes through the ONE substrate composer
1662        // `tatara_process::time::tombstone_now` — one of 12 pre-lift
1663        // exact-match sites past the ★★ PRIME-DIRECTIVE ≥ 2 threshold
1664        // for the `Some(Time(Utc::now()))` wire shape.
1665        p.metadata.deletion_timestamp = crate::time::tombstone_now();
1666        assert!(DeletionTombstoned::is_being_deleted(&p));
1667    }
1668
1669    #[test]
1670    fn is_being_deleted_on_ephemeral_pool_present_tombstone_returns_true_via_trait() {
1671        let mut p = EphemeralPool::new("attest-pool", empty_pool_spec());
1672        p.metadata.deletion_timestamp = crate::time::tombstone_now();
1673        assert!(DeletionTombstoned::is_being_deleted(&p));
1674    }
1675
1676    #[test]
1677    fn is_being_deleted_on_ephemeral_allocation_present_tombstone_returns_true_via_trait() {
1678        let mut a = EphemeralAllocation::new("pr-42-demo", empty_alloc_spec());
1679        a.metadata.deletion_timestamp = crate::time::tombstone_now();
1680        assert!(DeletionTombstoned::is_being_deleted(&a));
1681    }
1682
1683    // ── Byte-identical parity with the pre-lift `.is_some()` chain ────
1684
1685    #[test]
1686    fn is_being_deleted_matches_pre_lift_deletion_timestamp_is_some_chain_on_ephemeral_allocation()
1687    {
1688        // Byte-identical parity pin: the trait's default produces the
1689        // SAME `bool` a pre-lift `.metadata.deletion_timestamp.is_some()`
1690        // chain produced at `tatara-pool-reconciler::allocation_decide::
1691        // AllocationConvergenceCtx::observe` pre-lift, across every
1692        // corner of the (absent, present-at-now, present-at-past)
1693        // input matrix. A regression that inserted a normalization
1694        // step the pre-lift chain does NOT apply — or vice versa —
1695        // surfaces here rather than as silent drift between the
1696        // substrate owner and the pre-lift consumer.
1697        // Routes through the ONE substrate composer family
1698        // `tatara_process::time::{tombstone_now,tombstone_at}` — the
1699        // present-at-now corner rides `tombstone_now`, the present-at-
1700        // past corner composes `tombstone_at(seconds_ago(3600))` per
1701        // the composer's canonical stale-fixture shape.
1702        let mut cases: Vec<Option<Time>> = vec![None];
1703        cases.push(crate::time::tombstone_now());
1704        cases.push(crate::time::tombstone_at(crate::time::seconds_ago(3600)));
1705
1706        for ts in cases {
1707            let mut a = EphemeralAllocation::new("pr-42-demo", empty_alloc_spec());
1708            a.metadata.deletion_timestamp = ts.clone();
1709
1710            let pre_lift = a.metadata.deletion_timestamp.is_some();
1711            let via_trait = DeletionTombstoned::is_being_deleted(&a);
1712
1713            assert_eq!(
1714                pre_lift, via_trait,
1715                "trait probe must be byte-identical to pre-lift .metadata.deletion_timestamp.is_some() on tombstone={ts:?}",
1716            );
1717        }
1718    }
1719
1720    // ── Cross-CRD coherence with the two inherent forwarders ──────────
1721
1722    #[test]
1723    fn trait_probe_coheres_with_process_inherent_is_being_deleted_on_both_corners() {
1724        // Cross-primitive coherence pin: the trait's default and the
1725        // pre-existing `Process::is_being_deleted` inherent forwarder
1726        // return the SAME `bool` on the SAME `Process` value — a
1727        // future consolidation of the inherent onto the trait's default
1728        // (or vice versa) cannot land any drift between the two
1729        // surfaces because this pin binds them at every corner of the
1730        // (missing, present) input matrix.
1731        // Routes the tombstone-present corner through the ONE
1732        // substrate composer `tatara_process::time::tombstone_now`.
1733        for ts in [None, crate::time::tombstone_now()] {
1734            let mut p = Process::new("api", empty_process_spec());
1735            p.metadata.deletion_timestamp = ts.clone();
1736            assert_eq!(
1737                p.is_being_deleted(),
1738                DeletionTombstoned::is_being_deleted(&p),
1739                "Process trait probe must match inherent on tombstone={ts:?}",
1740            );
1741        }
1742    }
1743
1744    #[test]
1745    fn trait_probe_coheres_with_ephemeral_pool_inherent_is_being_deleted_on_both_corners() {
1746        // Peer coherence pin on the sister CRD.
1747        for ts in [None, crate::time::tombstone_now()] {
1748            let mut p = EphemeralPool::new("attest-pool", empty_pool_spec());
1749            p.metadata.deletion_timestamp = ts.clone();
1750            assert_eq!(
1751                p.is_being_deleted(),
1752                DeletionTombstoned::is_being_deleted(&p),
1753                "EphemeralPool trait probe must match inherent on tombstone={ts:?}",
1754            );
1755        }
1756    }
1757
1758    // ── Inherent-preferred method resolution on Process + EphemeralPool ──
1759
1760    #[test]
1761    fn dot_call_on_process_resolves_to_inherent_when_trait_in_scope() {
1762        // Rust method resolution prefers an inherent over a trait's
1763        // blanket impl, so `process.is_being_deleted()` with the trait
1764        // in scope still routes through the inherent — and both
1765        // return the same `bool` (verified in
1766        // `trait_probe_coheres_with_process_inherent_is_being_deleted_on_both_corners`).
1767        // This pin guards against a future refactor that removes the
1768        // inherent but leaves consumers assuming inherent-preferred
1769        // resolution — the observable output is identical either way,
1770        // so the pin locks the invariant that BOTH paths agree.
1771        let mut p = Process::new("api", empty_process_spec());
1772        // Routes through `tatara_process::time::tombstone_now`.
1773        p.metadata.deletion_timestamp = crate::time::tombstone_now();
1774        assert!(p.is_being_deleted());
1775    }
1776
1777    #[test]
1778    fn dot_call_on_ephemeral_allocation_resolves_to_trait_blanket_impl() {
1779        // The load-bearing corner: `alloc.is_being_deleted()` with
1780        // the trait in scope routes to the trait's blanket impl
1781        // (there is no inherent on `EphemeralAllocation`) and
1782        // produces the expected `bool`. This is what the swept
1783        // allocation-reconciler callsite depends on post-lift.
1784        let mut a = EphemeralAllocation::new("pr-42-demo", empty_alloc_spec());
1785        assert!(!a.is_being_deleted());
1786        a.metadata.deletion_timestamp = crate::time::tombstone_now();
1787        assert!(a.is_being_deleted());
1788    }
1789}
1790
1791#[cfg(test)]
1792mod annotated_tests {
1793    //! Pin the [`Annotated`] trait's `annotation` lookup at fail-
1794    //! before-pass-after granularity across every corner of the
1795    //! (annotations map: absent / present-empty / present-with-key /
1796    //! present-without-key) × (value form: normal / empty-string)
1797    //! input matrix, on the three tatara-process CRDs the trait's
1798    //! blanket impl covers today (`Process`, `EphemeralPool`,
1799    //! `EphemeralAllocation`) PLUS a K8s built-in (`ConfigMap`) — the
1800    //! load-bearing fourth surface that `tatara-export-worker::main`
1801    //! consumes post-lift where no tatara-owned inherent forwarder
1802    //! exists. Also pin cross-primitive coherence with the pre-existing
1803    //! `Process::annotation` inherent so a future consolidation onto
1804    //! the trait's default cannot silently skew the three consumers
1805    //! already routed through the inherent
1806    //! (`signals::ingest`,
1807    //! `phase_machine::released_from_annotation`,
1808    //! `controller_pool::process_belongs_to_pool`).
1809    use super::Annotated;
1810    use crate::allocation::{AllocationSpec, EphemeralAllocation, Requestor};
1811    use crate::crd::{Process, ProcessSpec};
1812    use crate::ephemeral::EphemeralSpec;
1813    use crate::intent::AplicacaoIntent;
1814    use crate::lifetime::TeardownPolicy;
1815    use crate::pool::{EphemeralPool, PoolSpec};
1816    use k8s_openapi::api::core::v1::ConfigMap;
1817    use std::collections::BTreeMap;
1818
1819    fn empty_template() -> EphemeralSpec {
1820        EphemeralSpec {
1821            aplicacao: AplicacaoIntent::chart_only("oci://x", "1"),
1822            ttl: "1h".into(),
1823            teardown: TeardownPolicy::Always,
1824            max_concurrent: 0,
1825            postconditions: vec![],
1826            preconditions: vec![],
1827            verify_timeout: None,
1828            classification: None,
1829            parent: None,
1830            exports: vec![],
1831            routing: None,
1832        }
1833    }
1834
1835    fn empty_pool_spec() -> PoolSpec {
1836        // Every non-template slot rides the ONE substrate composer
1837        // [`PoolSpec::with_template`]; see the primitive's doc-comment
1838        // for the full migration rationale.
1839        PoolSpec {
1840            desired_size: 1,
1841            ..PoolSpec::with_template(empty_template())
1842        }
1843    }
1844
1845    fn empty_alloc_spec() -> AllocationSpec {
1846        // AllocationSpec rides through `AllocationSpec::requestor_only`;
1847        // the inner Requestor rides through `Requestor::kind_only` —
1848        // sibling to the peer `empty_alloc_spec` fixture in the
1849        // DeletionTombstoned pin module above.
1850        AllocationSpec::requestor_only(Requestor::kind_only("github-pr"))
1851    }
1852
1853    fn empty_process_spec() -> ProcessSpec {
1854        // Routes through the ONE substrate composer
1855        // `ProcessSpec::gate_compute_defaults` — sibling to the
1856        // `empty_process_spec` fixture in the DeletionTombstoned pin
1857        // module above and to `empty_spec` in `crd.rs::tests`.
1858        ProcessSpec::gate_compute_defaults()
1859    }
1860
1861    fn one_annotation(key: &str, value: &str) -> BTreeMap<String, String> {
1862        let mut m = BTreeMap::new();
1863        m.insert(key.into(), value.into());
1864        m
1865    }
1866
1867    // ── Missing annotations map — trait returns None on every key ─────
1868
1869    #[test]
1870    fn annotation_on_process_missing_annotations_returns_none_via_trait() {
1871        let mut p = Process::new("api", empty_process_spec());
1872        p.metadata.annotations = None;
1873        assert_eq!(Annotated::annotation(&p, "tatara.pleme.io/signal"), None);
1874        assert_eq!(Annotated::annotation(&p, ""), None);
1875    }
1876
1877    #[test]
1878    fn annotation_on_ephemeral_pool_missing_annotations_returns_none_via_trait() {
1879        let mut p = EphemeralPool::new("attest-pool", empty_pool_spec());
1880        p.metadata.annotations = None;
1881        assert_eq!(Annotated::annotation(&p, "tatara.pleme.io/pool"), None);
1882    }
1883
1884    #[test]
1885    fn annotation_on_ephemeral_allocation_missing_annotations_returns_none_via_trait() {
1886        // The peer load-bearing corner: EphemeralAllocation has NO
1887        // inherent `annotation()` pre-lift — the trait's blanket impl
1888        // is what closes the substrate gap here, exactly as the
1889        // sibling `DeletionTombstoned` trait already did on the
1890        // tombstone axis for the SAME third CRD.
1891        let mut a = EphemeralAllocation::new("pr-42-demo", empty_alloc_spec());
1892        a.metadata.annotations = None;
1893        assert_eq!(
1894            Annotated::annotation(&a, "tatara.pleme.io/requestor-kind"),
1895            None,
1896        );
1897    }
1898
1899    #[test]
1900    fn annotation_on_config_map_missing_annotations_returns_none_via_trait() {
1901        // The load-bearing corner the export-worker's post-lift call
1902        // depends on: `ConfigMap` is a K8s built-in with no tatara-
1903        // owned inherent forwarder, and the receipts-owner filter
1904        // needs to route through the trait's blanket impl at
1905        // `cm.annotation(KEY)`.
1906        let cm = ConfigMap::default();
1907        // `Default::default()` produces an object with an empty
1908        // ObjectMeta whose `annotations` slot is `None` — the exact
1909        // missing-annotations corner the trait must collapse to
1910        // `None` at every key lookup, matching what the pre-lift
1911        // `cm.metadata.annotations.as_ref().and_then(...)` chain
1912        // produced.
1913        assert_eq!(Annotated::annotation(&cm, "tatara.pleme.io/process"), None,);
1914    }
1915
1916    // ── Missing key inside populated map — trait returns None ─────────
1917
1918    #[test]
1919    fn annotation_on_process_missing_key_returns_none_via_trait() {
1920        let mut p = Process::new("api", empty_process_spec());
1921        p.metadata.annotations = Some(one_annotation("other/key", "irrelevant"));
1922        assert_eq!(Annotated::annotation(&p, "tatara.pleme.io/signal"), None);
1923        assert_eq!(Annotated::annotation(&p, ""), None);
1924    }
1925
1926    #[test]
1927    fn annotation_on_config_map_missing_key_returns_none_via_trait() {
1928        let mut cm = ConfigMap::default();
1929        cm.metadata.annotations = Some(one_annotation("unrelated", "yes"));
1930        assert_eq!(Annotated::annotation(&cm, "tatara.pleme.io/process"), None,);
1931    }
1932
1933    // ── Present key — trait returns borrowed slice ────────────────────
1934
1935    #[test]
1936    fn annotation_on_process_present_key_returns_borrowed_slice_via_trait() {
1937        let mut p = Process::new("api", empty_process_spec());
1938        p.metadata.annotations = Some(one_annotation("tatara.pleme.io/signal", "SIGHUP"));
1939        assert_eq!(
1940            Annotated::annotation(&p, "tatara.pleme.io/signal"),
1941            Some("SIGHUP"),
1942        );
1943    }
1944
1945    #[test]
1946    fn annotation_on_ephemeral_pool_present_key_returns_borrowed_slice_via_trait() {
1947        let mut p = EphemeralPool::new("attest-pool", empty_pool_spec());
1948        p.metadata.annotations = Some(one_annotation("tatara.pleme.io/pool", "demo-pool"));
1949        assert_eq!(
1950            Annotated::annotation(&p, "tatara.pleme.io/pool"),
1951            Some("demo-pool"),
1952        );
1953    }
1954
1955    #[test]
1956    fn annotation_on_ephemeral_allocation_present_key_returns_borrowed_slice_via_trait() {
1957        let mut a = EphemeralAllocation::new("pr-42-demo", empty_alloc_spec());
1958        a.metadata.annotations = Some(one_annotation(
1959            "tatara.pleme.io/requestor-kind",
1960            "github-pr",
1961        ));
1962        assert_eq!(
1963            Annotated::annotation(&a, "tatara.pleme.io/requestor-kind"),
1964            Some("github-pr"),
1965        );
1966    }
1967
1968    #[test]
1969    fn annotation_on_config_map_present_key_returns_borrowed_slice_via_trait() {
1970        // The exact receipts-owner filter shape from
1971        // `tatara-export-worker::main`: a ConfigMap carrying the
1972        // `tatara.pleme.io/process` annotation set to the qualified
1973        // process reference `<ns>/<name>`. Pin that the trait produces
1974        // the exact borrowed slice the equality comparison against the
1975        // caller's `want.as_str()` sentinel consumes.
1976        let mut cm = ConfigMap::default();
1977        cm.metadata.annotations = Some(one_annotation(
1978            "tatara.pleme.io/process",
1979            "demo-ns/demo-app",
1980        ));
1981        assert_eq!(
1982            Annotated::annotation(&cm, "tatara.pleme.io/process"),
1983            Some("demo-ns/demo-app"),
1984        );
1985    }
1986
1987    // ── Empty-value contract: `Some("")` — the pre-lift chain never
1988    //    swallowed empty values into `None`, so the trait must not
1989    //    either. Pinned separately from the missing-slot corners.
1990
1991    #[test]
1992    fn annotation_present_key_with_empty_value_returns_some_empty_slice_via_trait() {
1993        let mut p = Process::new("api", empty_process_spec());
1994        p.metadata.annotations = Some(one_annotation("tatara.pleme.io/signal", ""));
1995        assert_eq!(
1996            Annotated::annotation(&p, "tatara.pleme.io/signal"),
1997            Some("")
1998        );
1999    }
2000
2001    // ── Byte-identical parity with the pre-lift 3-line chain ──────────
2002
2003    #[test]
2004    fn annotation_matches_pre_lift_annotations_lookup_chain_on_config_map() {
2005        // The four-corner input matrix the pre-lift
2006        // `cm.metadata.annotations.as_ref().and_then(|m| m.get(KEY))
2007        // .map(String::as_str)` chain traversed in
2008        // `tatara-export-worker::main` pre-lift. A regression that
2009        // inserted a normalization step the pre-lift chain does NOT
2010        // apply — or vice versa — surfaces here rather than as silent
2011        // drift between the substrate owner and the pre-lift consumer.
2012        const KEY: &str = "tatara.pleme.io/process";
2013        let cases: Vec<(Option<BTreeMap<String, String>>, Option<&str>)> = vec![
2014            (None, None),
2015            (Some(BTreeMap::new()), None),
2016            (Some(one_annotation("unrelated", "yes")), None),
2017            (
2018                Some(one_annotation(KEY, "demo-ns/demo-app")),
2019                Some("demo-ns/demo-app"),
2020            ),
2021            (Some(one_annotation(KEY, "")), Some("")),
2022        ];
2023        for (anns, expected) in cases {
2024            let mut cm = ConfigMap::default();
2025            cm.metadata.annotations = anns.clone();
2026
2027            let pre_lift: Option<&str> = cm
2028                .metadata
2029                .annotations
2030                .as_ref()
2031                .and_then(|m| m.get(KEY))
2032                .map(String::as_str);
2033            let via_trait = Annotated::annotation(&cm, KEY);
2034
2035            assert_eq!(
2036                pre_lift, expected,
2037                "pre-lift chain must return {expected:?} for annotations={anns:?}",
2038            );
2039            assert_eq!(
2040                via_trait, pre_lift,
2041                "trait probe must be byte-identical to pre-lift chain for annotations={anns:?}",
2042            );
2043        }
2044    }
2045
2046    // ── Cross-primitive coherence with Process's inherent forwarder ───
2047
2048    #[test]
2049    fn trait_probe_coheres_with_process_inherent_annotation_on_every_corner() {
2050        // Cross-primitive coherence pin: the trait's default and the
2051        // pre-existing `Process::annotation` inherent forwarder return
2052        // the SAME `Option<&str>` on the SAME `Process` value — a
2053        // future consolidation of the inherent onto the trait's
2054        // default cannot land any drift because this pin binds them
2055        // at every corner of the (absent, present-missing-key,
2056        // present-with-key, present-with-empty-value) input matrix.
2057        const KEY: &str = "tatara.pleme.io/signal";
2058        let cases: Vec<Option<BTreeMap<String, String>>> = vec![
2059            None,
2060            Some(BTreeMap::new()),
2061            Some(one_annotation("other/key", "irrelevant")),
2062            Some(one_annotation(KEY, "SIGHUP")),
2063            Some(one_annotation(KEY, "")),
2064        ];
2065        for anns in cases {
2066            let mut p = Process::new("api", empty_process_spec());
2067            p.metadata.annotations = anns.clone();
2068            let via_inherent = p.annotation(KEY);
2069            let via_trait = Annotated::annotation(&p, KEY);
2070            assert_eq!(
2071                via_inherent, via_trait,
2072                "Process inherent + Annotated trait must agree on annotations={anns:?}",
2073            );
2074        }
2075    }
2076
2077    // ── Inherent-preferred method resolution on Process ───────────────
2078
2079    #[test]
2080    fn dot_call_on_process_resolves_to_inherent_when_trait_in_scope() {
2081        // Rust method resolution prefers an inherent over a trait's
2082        // blanket impl, so `process.annotation(key)` with the trait in
2083        // scope still routes through the inherent — and both return
2084        // the same `Option<&str>` (verified in
2085        // `trait_probe_coheres_with_process_inherent_annotation_on_every_corner`).
2086        // This pin guards against a future refactor that removes the
2087        // inherent but leaves consumers assuming inherent-preferred
2088        // resolution — the observable output is identical either way,
2089        // so the pin locks the invariant that BOTH paths agree.
2090        let mut p = Process::new("api", empty_process_spec());
2091        p.metadata.annotations = Some(one_annotation("tatara.pleme.io/signal", "SIGHUP"));
2092        assert_eq!(p.annotation("tatara.pleme.io/signal"), Some("SIGHUP"));
2093    }
2094
2095    #[test]
2096    fn dot_call_on_ephemeral_allocation_resolves_to_trait_blanket_impl() {
2097        // The peer load-bearing corner: `alloc.annotation(key)` with
2098        // the trait in scope routes to the trait's blanket impl —
2099        // there is no inherent on `EphemeralAllocation` — and produces
2100        // the expected `Option<&str>`. The same discipline the sibling
2101        // `DeletionTombstoned` trait already established on the
2102        // tombstone axis for the SAME third CRD.
2103        let mut a = EphemeralAllocation::new("pr-42-demo", empty_alloc_spec());
2104        assert_eq!(a.annotation("tatara.pleme.io/requestor-kind"), None);
2105        a.metadata.annotations = Some(one_annotation(
2106            "tatara.pleme.io/requestor-kind",
2107            "github-pr",
2108        ));
2109        assert_eq!(
2110            a.annotation("tatara.pleme.io/requestor-kind"),
2111            Some("github-pr"),
2112        );
2113    }
2114
2115    #[test]
2116    fn dot_call_on_config_map_resolves_to_trait_blanket_impl() {
2117        // The load-bearing corner the export-worker's post-lift call
2118        // exercises: `cm.annotation(KEY)` with the trait in scope
2119        // routes to the blanket impl (ConfigMap is a K8s built-in
2120        // with no tatara-owned inherent) and produces the same
2121        // `Option<&str>` the pre-lift 3-line chain did.
2122        let mut cm = ConfigMap::default();
2123        assert_eq!(cm.annotation("tatara.pleme.io/process"), None);
2124        cm.metadata.annotations = Some(one_annotation(
2125            "tatara.pleme.io/process",
2126            "demo-ns/demo-app",
2127        ));
2128        assert_eq!(
2129            cm.annotation("tatara.pleme.io/process"),
2130            Some("demo-ns/demo-app"),
2131        );
2132    }
2133}
2134
2135#[cfg(test)]
2136mod annotations_pins {
2137    //! Pin the three newly-lifted allocator-bind annotation keys
2138    //! ([`crate::annotations::REQUESTOR`],
2139    //! [`crate::annotations::ALLOCATION`],
2140    //! [`crate::annotations::REQUESTOR_KIND`]) at their canonical
2141    //! wire-form byte-values, and pin the coherence between each
2142    //! constant and the pre-lift string literal the sibling writer +
2143    //! reader test-sites still spell verbatim.
2144    //!
2145    //! Pre-lift each of the three keys was a bare `"tatara.pleme.io/…"`
2146    //! string literal at both the writer (`tatara-pool-reconciler::
2147    //! controller_allocation::reconcile_inner`'s Bind arm) AND the
2148    //! reader-side test sites in `annotated_tests` above — six
2149    //! restatements of `REQUESTOR_KIND` alone past the ★★
2150    //! PRIME-DIRECTIVE ≥ 2 duplication threshold. Post-lift the writer
2151    //! keys on the substrate constant; these pins bind the constant's
2152    //! byte-shape so a future edit that drifted the constant (a
2153    //! typo'd suffix, an accidental `tatara.pleme.io/v2/…` migration
2154    //! landing at only the writer, an incoming rename that swapped
2155    //! two of the three keys) surfaces here rather than as silent
2156    //! operator-facing skew between the writer and the tatara-process
2157    //! reader tests that still spell the literal.
2158    //!
2159    //! Theory anchor: THEORY.md §II.1 invariant 5 (composition
2160    //! preserves proofs — the wire-form value each downstream reader
2161    //! depends on now has a compile-time pin at the substrate).
2162    use crate::annotations;
2163
2164    #[test]
2165    fn requestor_matches_pre_lift_wire_string() {
2166        assert_eq!(annotations::REQUESTOR, "tatara.pleme.io/requestor");
2167    }
2168
2169    #[test]
2170    fn allocation_matches_pre_lift_wire_string() {
2171        assert_eq!(annotations::ALLOCATION, "tatara.pleme.io/allocation");
2172    }
2173
2174    #[test]
2175    fn requestor_kind_matches_pre_lift_wire_string() {
2176        assert_eq!(
2177            annotations::REQUESTOR_KIND,
2178            "tatara.pleme.io/requestor-kind",
2179        );
2180    }
2181
2182    #[test]
2183    fn allocator_bind_axis_keys_are_distinct() {
2184        // A copy-paste that duplicated one key's value across two
2185        // slots (an oversight during the initial lift or a future
2186        // rename that merged two keys by mistake) collapses BOTH
2187        // downstream readers onto the same wire string and silently
2188        // loses one of the three axes. Pin the closed set is
2189        // partition-distinct.
2190        assert_ne!(annotations::REQUESTOR, annotations::ALLOCATION);
2191        assert_ne!(annotations::REQUESTOR, annotations::REQUESTOR_KIND);
2192        assert_ne!(annotations::ALLOCATION, annotations::REQUESTOR_KIND);
2193    }
2194
2195    #[test]
2196    fn allocator_bind_axis_keys_share_tatara_namespace() {
2197        // Every substrate-owned annotation key inhabits the
2198        // `tatara.pleme.io/` reverse-DNS namespace; a future rename
2199        // that dropped the prefix (a bare `"requestor"` key, a
2200        // typo'd `pleme.io/requestor`) would collide with an
2201        // arbitrary third-party operator's annotations on the same
2202        // Process and silently corrupt cross-consumer reads.
2203        for key in [
2204            annotations::REQUESTOR,
2205            annotations::ALLOCATION,
2206            annotations::REQUESTOR_KIND,
2207        ] {
2208            assert!(
2209                key.starts_with("tatara.pleme.io/"),
2210                "annotation key {key:?} must inhabit tatara.pleme.io/ namespace",
2211            );
2212        }
2213    }
2214
2215    // ── Pool-membership axis pins ────────────────────────────────────
2216    //
2217    // Pins the two newly-lifted pool-membership annotation keys
2218    // ([`crate::annotations::POOL`], [`crate::annotations::POOL_SLOT`])
2219    // at their canonical wire-form byte-values. Pre-lift each key was
2220    // a file-scope `const ANNOTATION_POOL / ANNOTATION_SLOT` in
2221    // `tatara-pool-reconciler::controller_pool` PLUS bare
2222    // `"tatara.pleme.io/pool"` string literals at four reader-side
2223    // test sites in this crate (in the sibling `annotated_tests` above
2224    // and in `crd.rs`'s
2225    // `annotation_composes_borrow_equality_tail_matching_pre_lift_pool`
2226    // + `annotation_returns_none_when_metadata_annotations_is_none`).
2227    // Post-lift the writer routes through the substrate constant; a
2228    // future edit that drifted the constant (a typo'd suffix, an
2229    // accidental `tatara.pleme.io/v2/pool` migration landing at only
2230    // the writer, an incoming rename that swapped POOL and POOL_SLOT)
2231    // surfaces here rather than as silent operator-facing skew
2232    // between the pool controller's writer and its own membership-
2233    // gate reader.
2234
2235    #[test]
2236    fn pool_matches_pre_lift_wire_string() {
2237        assert_eq!(annotations::POOL, "tatara.pleme.io/pool");
2238    }
2239
2240    #[test]
2241    fn pool_slot_matches_pre_lift_wire_string() {
2242        assert_eq!(annotations::POOL_SLOT, "tatara.pleme.io/pool-slot");
2243    }
2244
2245    #[test]
2246    fn pool_membership_axis_keys_are_distinct() {
2247        // A copy-paste that duplicated one key's value across both
2248        // slots (an oversight during the initial lift, or a future
2249        // rename that merged the two keys by mistake) collapses
2250        // BOTH downstream readers onto the same wire string and
2251        // silently loses the slot-index axis — the pool controller
2252        // would still find its own members via POOL but every per-
2253        // slot dispatch consumer would read the pool name where the
2254        // slot index used to sit. Pin the closed set is partition-
2255        // distinct.
2256        assert_ne!(annotations::POOL, annotations::POOL_SLOT);
2257    }
2258
2259    #[test]
2260    fn pool_membership_axis_keys_share_tatara_namespace() {
2261        // Same reverse-DNS namespace invariant the allocator-bind
2262        // axis-family enforces above — a rename that dropped the
2263        // prefix on either POOL or POOL_SLOT would collide with an
2264        // arbitrary third-party operator's annotations on the same
2265        // Process and silently corrupt every pool-membership read.
2266        for key in [annotations::POOL, annotations::POOL_SLOT] {
2267            assert!(
2268                key.starts_with("tatara.pleme.io/"),
2269                "annotation key {key:?} must inhabit tatara.pleme.io/ namespace",
2270            );
2271        }
2272    }
2273
2274    #[test]
2275    fn pool_membership_axis_keys_partition_distinct_from_allocator_bind_axis() {
2276        // Cross-family distinctness pin — the pool-membership axis
2277        // (POOL, POOL_SLOT) and the allocator-bind axis (REQUESTOR,
2278        // ALLOCATION, REQUESTOR_KIND) travel on the SAME member
2279        // Process at the SAME time (the pool controller writes POOL
2280        // + POOL_SLOT at creation; the allocator later merges
2281        // REQUESTOR / ALLOCATION / REQUESTOR_KIND onto the same
2282        // Process at Bind). A copy-paste that collapsed any axis
2283        // pair (e.g. POOL and REQUESTOR onto the same wire string)
2284        // would let one write silently overwrite the other. Pin
2285        // that every substrate-owned annotation key is unique
2286        // across the two axis-families.
2287        let pool_axis = [annotations::POOL, annotations::POOL_SLOT];
2288        let bind_axis = [
2289            annotations::REQUESTOR,
2290            annotations::ALLOCATION,
2291            annotations::REQUESTOR_KIND,
2292        ];
2293        for p in pool_axis {
2294            for b in bind_axis {
2295                assert_ne!(
2296                    p, b,
2297                    "pool-membership key {p:?} collides with allocator-bind key {b:?}",
2298                );
2299            }
2300        }
2301    }
2302}
2303
2304// ── Lisp → ProcessSpec compile bridge ──────────────────────────────────
2305//
2306// `(defpoint NAME :k v …)` compiles to a `NamedDefinition<ProcessSpec>`.
2307// The derive on ProcessSpec handles every field via the serde Deserialize
2308// fallthrough — no hand-rolled keyword parsing needed.
2309
2310/// A named ProcessSpec as produced by `compile_source`.
2311pub type Definition = tatara_lisp::NamedDefinition<crate::crd::ProcessSpec>;
2312
2313/// Compile a Lisp source string into a list of named ProcessSpecs.
2314/// Each top-level `(defpoint NAME …)` form becomes one `Definition`.
2315pub fn compile_source(src: &str) -> tatara_lisp::Result<Vec<Definition>> {
2316    tatara_lisp::compile_named::<crate::crd::ProcessSpec>(src)
2317}
2318
2319/// Register every domain owned by this crate with the global Lisp
2320/// dispatcher. Call once per binary, typically near the top of `main`.
2321/// After this call, `tatara_lisp::domain::lookup("defpoint")` and
2322/// `lookup("defephemeral")` both resolve to the right typed compiler.
2323///
2324/// Idempotent — registering the same type twice is a no-op.
2325pub fn register_all() {
2326    tatara_lisp::domain::register::<crate::crd::ProcessSpec>();
2327    tatara_lisp::domain::register::<crate::ephemeral::EphemeralSpec>();
2328}
2329
2330#[cfg(test)]
2331mod compile_tests {
2332    use super::compile_source;
2333    use crate::classification::{ConvergencePointType, SubstrateType};
2334    use crate::compliance::VerificationPhase;
2335    use crate::spec::MustReachPhase;
2336
2337    /// The full derive-powered pipeline — no hand-rolled parsing anywhere.
2338    /// Every field travels: Lisp → Sexp → serde_json → typed ProcessSpec.
2339    #[test]
2340    fn full_processspec_round_trip_via_derive() {
2341        let src = r#"
2342            (defpoint observability-stack
2343              :identity       (:parent "seph.1")
2344              :classification (:point-type Gate
2345                               :substrate Observability
2346                               :horizon (:kind Bounded)
2347                               :calm Monotone
2348                               :data-classification Internal)
2349              :intent         (:nix (:flake-ref "github:pleme-io/k8s"
2350                                     :attribute "observability"
2351                                     :attic-cache "main"))
2352              :boundary       (:postconditions
2353                                 ((:kind KustomizationHealthy
2354                                   :params (:name "observability-stack"
2355                                            :namespace "flux-system"))
2356                                  (:kind PromQL
2357                                   :params (:query "up == 1")))
2358                               :timeout "15m")
2359              :compliance     (:baseline "fedramp-moderate"
2360                               :bindings ((:framework "nist-800-53"
2361                                           :control-id "SC-7"
2362                                           :phase AtBoundary)))
2363              :depends-on     ((:name "secret-injection" :must-reach Attested))
2364              :signals        (:sigterm-grace-seconds 480
2365                               :sighup-strategy Reconverge))
2366        "#;
2367        let defs = compile_source(src).expect("compile");
2368        assert_eq!(defs.len(), 1);
2369        let d = &defs[0];
2370        assert_eq!(d.name, "observability-stack");
2371
2372        // identity
2373        assert_eq!(d.spec.identity.parent.as_deref(), Some("seph.1"));
2374
2375        // classification (enums deserialized via symbol → string)
2376        assert_eq!(d.spec.classification.point_type, ConvergencePointType::Gate);
2377        assert_eq!(
2378            d.spec.classification.substrate,
2379            SubstrateType::Observability
2380        );
2381
2382        // intent (tagged-union with one of four options)
2383        let nix = d.spec.intent.nix.as_ref().expect("nix intent");
2384        assert_eq!(nix.flake_ref, "github:pleme-io/k8s");
2385        assert_eq!(nix.attribute, "observability");
2386        assert_eq!(nix.attic_cache.as_deref(), Some("main"));
2387
2388        // boundary (Vec<nested struct with params object>)
2389        assert_eq!(d.spec.boundary.postconditions.len(), 2);
2390        assert_eq!(d.spec.boundary.timeout.as_deref(), Some("15m"));
2391
2392        // compliance (Vec<binding with enum phase>)
2393        assert_eq!(
2394            d.spec.compliance.baseline.as_deref(),
2395            Some("fedramp-moderate")
2396        );
2397        assert_eq!(d.spec.compliance.bindings.len(), 1);
2398        assert_eq!(
2399            d.spec.compliance.bindings[0].phase,
2400            VerificationPhase::AtBoundary
2401        );
2402
2403        // depends_on (Vec<struct with enum>)
2404        assert_eq!(d.spec.depends_on.len(), 1);
2405        assert_eq!(d.spec.depends_on[0].must_reach, MustReachPhase::Attested);
2406
2407        // signals (numeric + enum defaults)
2408        assert_eq!(d.spec.signals.sigterm_grace_seconds, 480);
2409    }
2410
2411    #[test]
2412    fn missing_required_field_errors() {
2413        // `:classification` has no #[serde(default)] — omit it and compile must fail.
2414        let src = r#"(defpoint x :intent (:nix (:flake-ref "f" :attribute "a")))"#;
2415        assert!(compile_source(src).is_err());
2416    }
2417
2418    #[test]
2419    fn serde_default_fields_are_optional() {
2420        // Omit every #[serde(default)] field — compile must succeed because
2421        // the derive honors serde defaults.
2422        let src = r#"
2423            (defpoint x
2424              :classification (:point-type Transform :substrate Compute)
2425              :intent (:flux (:git-repository "g" :path ".")))
2426        "#;
2427        let defs = compile_source(src).expect("compile");
2428        assert_eq!(defs.len(), 1);
2429        let d = &defs[0];
2430        assert!(d.spec.depends_on.is_empty());
2431        assert!(d.spec.boundary.postconditions.is_empty());
2432        assert!(d.spec.compliance.bindings.is_empty());
2433        assert!(!d.spec.suspended);
2434        // Lifetime defaults to Permanent (no variant set, resolver still works).
2435        assert!(d.spec.lifetime.is_default());
2436        assert!(!d.spec.lifetime.is_ephemeral());
2437    }
2438
2439    /// Registering all process-owned domains is idempotent and resolves
2440    /// both `defpoint` (ProcessSpec) and `defephemeral` (EphemeralSpec).
2441    #[test]
2442    fn register_all_resolves_defpoint_and_defephemeral() {
2443        use tatara_lisp::domain::lookup;
2444        super::register_all();
2445        super::register_all(); // idempotent
2446        assert!(lookup("defpoint").is_some(), "defpoint must resolve");
2447        assert!(
2448            lookup("defephemeral").is_some(),
2449            "defephemeral must resolve"
2450        );
2451    }
2452
2453    /// End-to-end: a `(defpoint …)` form may carry the full ephemeral
2454    /// shape directly — `:intent (:aplicacao …)` + `:lifetime (:ephemeral …)`.
2455    /// This is what the `(defephemeral …)` sugar lowers to via `From`.
2456    #[test]
2457    fn defpoint_with_aplicacao_intent_and_ephemeral_lifetime() {
2458        use crate::intent::IntentVariant;
2459        use crate::lifetime::{LifetimeVariant, TeardownPolicy};
2460        let src = r#"
2461            (defpoint closed-loop-attest
2462              :classification (:point-type Gate :substrate Compute)
2463              :intent (:aplicacao
2464                        (:chart-ref "oci://ghcr.io/pleme-io/charts/lareira-demo-app"
2465                         :version "0.5.5"
2466                         :profile "all-in-one"
2467                         :values-overlay (:cluster (:name "ephemeral-test-01"))
2468                         :target-namespace "demo-test"))
2469              :boundary (:postconditions
2470                          ((:kind HelmReleaseReleased
2471                            :params (:name "demo-app-consolidated"
2472                                     :namespace "demo-test"))
2473                           (:kind ClosedLoopAuth
2474                            :params (:issuer (:service "demo-app-issuer" :port 8080)
2475                                     :consumer (:service "demo-app-gateway" :port 8000)
2476                                     :probeImage "ghcr.io/pleme-io/closed-loop-probe:0.1.0"))))
2477              :lifetime (:ephemeral (:ttl "1h"
2478                                     :teardown-policy OnAttested
2479                                     :max-concurrent 1)))
2480        "#;
2481        let defs = compile_source(src).expect("compile");
2482        assert_eq!(defs.len(), 1);
2483        let d = &defs[0];
2484
2485        // Aplicacao intent landed.
2486        match d.spec.intent.variant().unwrap() {
2487            IntentVariant::Aplicacao(a) => {
2488                assert_eq!(a.profile, "all-in-one");
2489                assert_eq!(a.version, "0.5.5");
2490                assert_eq!(a.target_namespace.as_deref(), Some("demo-test"));
2491                assert_eq!(a.values_overlay["cluster"]["name"], "ephemeral-test-01");
2492            }
2493            other => panic!("expected Aplicacao, got {other:?}"),
2494        }
2495
2496        // Ephemeral lifetime landed with the right teardown policy.
2497        match d.spec.lifetime.variant().unwrap() {
2498            LifetimeVariant::Ephemeral(e) => {
2499                assert_eq!(e.ttl, "1h");
2500                assert_eq!(e.teardown_policy, TeardownPolicy::OnAttested);
2501                assert_eq!(e.max_concurrent, 1);
2502            }
2503            other => panic!("expected ephemeral, got {other:?}"),
2504        }
2505
2506        // Two typed postconditions including ClosedLoopAuth.
2507        assert_eq!(d.spec.boundary.postconditions.len(), 2);
2508        assert_eq!(
2509            d.spec.boundary.postconditions[1].kind,
2510            crate::boundary::ConditionKind::ClosedLoopAuth
2511        );
2512    }
2513}
2514
2515#[cfg(test)]
2516mod placed_in_namespace_tests {
2517    //! Pin the [`PlacedInNamespace`] trait's `in_namespace` builder at
2518    //! fail-before-pass-after granularity across every corner of the
2519    //! (CRD ∈ {`Process`, `EphemeralPool`, `EphemeralAllocation`,
2520    //! `ConfigMap`}) × (input form ∈ {`&str`, `String`, `&String`})
2521    //! matrix — the three tatara-owned CRDs the trait's blanket impl
2522    //! covers today PLUS one K8s built-in (`ConfigMap`) whose sibling
2523    //! [`Annotated`] blanket already covers the same category on the
2524    //! annotation-read axis. Also pin (a) the overwrite corner where
2525    //! `.in_namespace(a).in_namespace(b)` binds `b`, so a future
2526    //! consumer that chains two stamps in one composition never sees
2527    //! stale semantics, and (b) the byte-identical parity corner with
2528    //! the pre-lift 3-line body of the per-CRD `EphemeralPool::new_in`
2529    //! and `EphemeralAllocation::new_in` composers post-forwarding —
2530    //! `<CRD>::new_in(name, ns, spec)` must yield a value structurally
2531    //! identical to `<CRD>::new(name, spec).in_namespace(ns)` on every
2532    //! metadata slot the derive stamps.
2533    use super::PlacedInNamespace;
2534    use crate::allocation::{AllocationSpec, EphemeralAllocation, Requestor};
2535    use crate::crd::{Process, ProcessSpec};
2536    use crate::pool::{EphemeralPool, PoolSpec};
2537    use k8s_openapi::api::core::v1::ConfigMap;
2538    use kube::api::ObjectMeta;
2539
2540    fn empty_process_spec() -> ProcessSpec {
2541        ProcessSpec::gate_compute_defaults()
2542    }
2543
2544    fn empty_pool_spec() -> PoolSpec {
2545        PoolSpec {
2546            desired_size: 1,
2547            ..PoolSpec::with_template(crate::ephemeral::EphemeralSpec {
2548                aplicacao: crate::intent::AplicacaoIntent::chart_only("oci://x", "1"),
2549                ttl: "1h".into(),
2550                teardown: crate::lifetime::TeardownPolicy::Always,
2551                max_concurrent: 0,
2552                postconditions: vec![],
2553                preconditions: vec![],
2554                verify_timeout: None,
2555                classification: None,
2556                parent: None,
2557                exports: vec![],
2558                routing: None,
2559            })
2560        }
2561    }
2562
2563    fn empty_alloc_spec() -> AllocationSpec {
2564        AllocationSpec::requestor_only(Requestor::kind_only("github-pr"))
2565    }
2566
2567    #[test]
2568    fn in_namespace_on_process_stamps_borrowed_str() {
2569        let p = Process::new("api", empty_process_spec()).in_namespace("prod");
2570        assert_eq!(p.metadata.namespace.as_deref(), Some("prod"));
2571    }
2572
2573    #[test]
2574    fn in_namespace_on_process_stamps_owned_string() {
2575        let ns: String = "prod".into();
2576        let p = Process::new("api", empty_process_spec()).in_namespace(ns);
2577        assert_eq!(p.metadata.namespace.as_deref(), Some("prod"));
2578    }
2579
2580    #[test]
2581    fn in_namespace_on_process_stamps_string_ref() {
2582        let ns: String = "prod".into();
2583        let p = Process::new("api", empty_process_spec()).in_namespace(&ns);
2584        assert_eq!(p.metadata.namespace.as_deref(), Some("prod"));
2585    }
2586
2587    #[test]
2588    fn in_namespace_on_ephemeral_pool_stamps_borrowed_str() {
2589        let p = EphemeralPool::new("pool-1", empty_pool_spec()).in_namespace("pools");
2590        assert_eq!(p.metadata.namespace.as_deref(), Some("pools"));
2591    }
2592
2593    #[test]
2594    fn in_namespace_on_ephemeral_allocation_stamps_borrowed_str() {
2595        let a = EphemeralAllocation::new("alloc-1", empty_alloc_spec()).in_namespace("pools");
2596        assert_eq!(a.metadata.namespace.as_deref(), Some("pools"));
2597    }
2598
2599    #[test]
2600    fn in_namespace_on_configmap_via_blanket_stamps_ns() {
2601        let cm = ConfigMap {
2602            metadata: ObjectMeta {
2603                name: Some("cm-1".into()),
2604                ..Default::default()
2605            },
2606            ..Default::default()
2607        };
2608        let cm = cm.in_namespace("demo");
2609        assert_eq!(cm.metadata.namespace.as_deref(), Some("demo"));
2610    }
2611
2612    #[test]
2613    fn in_namespace_second_call_overwrites_first() {
2614        let p = Process::new("api", empty_process_spec())
2615            .in_namespace("staging")
2616            .in_namespace("prod");
2617        assert_eq!(p.metadata.namespace.as_deref(), Some("prod"));
2618    }
2619
2620    #[test]
2621    fn in_namespace_preserves_name_and_spec_untouched() {
2622        // Byte-identical parity with the pre-lift two-line pattern:
2623        // only `metadata.namespace` moves; `metadata.name` + `spec`
2624        // stay at the values the derive-supplied `::new` stamped.
2625        // Serialize both `spec` sides through serde_json so we can
2626        // pin equality without requiring `PartialEq` on `ProcessSpec`.
2627        let p = Process::new("api", empty_process_spec()).in_namespace("prod");
2628        assert_eq!(p.metadata.name.as_deref(), Some("api"));
2629        assert_eq!(p.metadata.namespace.as_deref(), Some("prod"));
2630        let expected = serde_json::to_value(empty_process_spec()).unwrap();
2631        let actual = serde_json::to_value(&p.spec).unwrap();
2632        assert_eq!(actual, expected);
2633    }
2634
2635    #[test]
2636    fn pool_new_in_forwarder_matches_trait_form() {
2637        // Cross-composer coherence witness — the per-CRD
2638        // `EphemeralPool::new_in` forwarder must produce a value
2639        // structurally identical to what `Process::new(...).in_namespace(...)`
2640        // does on the same axis. Serialize both sides through
2641        // serde_json so any drift between the forwarding form and a
2642        // direct trait-call materializes at this pin.
2643        let via_new_in = EphemeralPool::new_in("pool-x", "pools", empty_pool_spec());
2644        let via_trait = EphemeralPool::new("pool-x", empty_pool_spec()).in_namespace("pools");
2645        assert_eq!(
2646            serde_json::to_value(&via_new_in).unwrap(),
2647            serde_json::to_value(&via_trait).unwrap(),
2648        );
2649    }
2650
2651    #[test]
2652    fn allocation_new_in_forwarder_matches_trait_form() {
2653        let via_new_in = EphemeralAllocation::new_in("alloc-x", "pools", empty_alloc_spec());
2654        let via_trait =
2655            EphemeralAllocation::new("alloc-x", empty_alloc_spec()).in_namespace("pools");
2656        assert_eq!(
2657            serde_json::to_value(&via_new_in).unwrap(),
2658            serde_json::to_value(&via_trait).unwrap(),
2659        );
2660    }
2661}