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