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