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::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/// Annotation keys the reconciler reads/writes on owned FluxCD resources.
421pub mod annotations {
422    pub const MANAGED_BY: &str = "tatara.pleme.io/managed-by";
423    pub const PROCESS: &str = "tatara.pleme.io/process";
424    pub const PID: &str = "tatara.pleme.io/pid";
425    pub const CONTENT_HASH: &str = "tatara.pleme.io/content-hash";
426    pub const ATTESTATION_ROOT: &str = "tatara.pleme.io/attestation-root";
427    pub const GENERATION: &str = "tatara.pleme.io/generation";
428    pub const SIGNAL: &str = "tatara.pleme.io/signal";
429    /// Stamped by the reconciler when transitioning into `Releasing`
430    /// — records which terminal-reached gate the Process came from
431    /// (`Attested` or `Failed`) so `handle_releasing` can pick the
432    /// matching `ExportTrigger` set + the correct post-Releasing
433    /// destination (`Exiting` from Attested, `Zombie` from Failed).
434    pub const RELEASED_FROM: &str = "tatara.pleme.io/released-from";
435    /// Labels the export-worker Jobs the reconciler emits during
436    /// `Releasing`. Selector: `tatara.pleme.io/role=export`.
437    pub const ROLE: &str = "tatara.pleme.io/role";
438    /// Index of an export inside `lifetime.ephemeral.exports`.
439    /// Stamped on the corresponding tatara-export-worker Job + its
440    /// receipt ConfigMap so the reconciler can correlate them
441    /// without re-parsing the spec JSON.
442    pub const EXPORT_INDEX: &str = "tatara.pleme.io/export-index";
443    /// Label / annotation key stamping which
444    /// `RoutingSpec.hostnames` entry a routing edge (Ingress /
445    /// DNSEndpoint) belongs to. Value is the entry's `app` slot;
446    /// a `label`-selector on this key slices every emitted edge
447    /// for a given `app` regardless of hostname form. Peer to
448    /// [`ROUTING_FORM`] on the routing-axis pair.
449    pub const APP: &str = "tatara.pleme.io/app";
450    /// Label / annotation key stamping the routing form
451    /// (`"stable"` | `"instance"`) on every emitted routing edge.
452    /// Value is a [`crate::routing::RoutingForm`] wire-form string;
453    /// consumers filtering the two forms compare to
454    /// [`RoutingForm::as_str`][crate::routing::RoutingForm::as_str],
455    /// never to a bare literal.
456    pub const ROUTING_FORM: &str = "tatara.pleme.io/routing-form";
457}
458
459/// Standard finalizer for the Process reconciler.
460pub const PROCESS_FINALIZER: &str = "tatara.pleme.io/process-finalizer";
461
462/// Shared schemars helpers — emit OpenAPI schemas Kubernetes accepts.
463/// Free-form `serde_json::Value` fields default to an *empty* schema
464/// in schemars, which the K8s API server rejects with "type: Required
465/// value: must not be empty for specified object fields". The typed
466/// workaround is to emit `{type: object, x-kubernetes-preserve-unknown-
467/// fields: true}` — same shape kube-rs's own helpers produce.
468pub mod schema_helpers {
469    use schemars::{gen::SchemaGenerator, schema::Schema};
470    /// Schema for a free-form JSON object field. Apply via
471    /// `#[schemars(schema_with = "tatara_process::schema_helpers::preserve_unknown_object")]`
472    /// on any `serde_json::Value` / `BTreeMap<String, serde_json::Value>`
473    /// field exposed through a CRD.
474    pub fn preserve_unknown_object(_g: &mut SchemaGenerator) -> Schema {
475        serde_json::from_value(serde_json::json!({
476            "type": "object",
477            "x-kubernetes-preserve-unknown-fields": true
478        }))
479        .expect("static JSON literal parses as Schema")
480    }
481}
482
483#[cfg(test)]
484mod owner_reference_tests {
485    //! Pin the `owner_reference_json` composer at fail-before-pass-
486    //! after granularity. Every shape a pre-lift caller hand-authored
487    //! is re-asserted here so a regression that inlined any of the
488    //! six slots at a call site (breaking the primitive's role as
489    //! the ONE source of truth) fails HERE at the composer's shipped-
490    //! shape pin rather than as silent drift between the pre-lift
491    //! `render.rs` / `edges.rs` / `ssapply.rs` sites (which pre-lift
492    //! already carried TWO different `apiVersion` spellings — a
493    //! composed `format!("{}/{}", GROUP, VERSION)` at two sites and
494    //! the frozen literal `"tatara.pleme.io/v1alpha1"` at the third).
495    use super::{
496        api_version, owner_reference_json, owner_references_json, GROUP, PROCESS_KIND, VERSION,
497    };
498    use serde_json::json;
499
500    #[test]
501    fn api_version_composes_group_and_version() {
502        // Any bump of GROUP or VERSION lands at ONE composer.
503        assert_eq!(api_version(), format!("{GROUP}/{VERSION}"));
504    }
505
506    #[test]
507    fn api_version_byte_matches_wire_form_pre_lift() {
508        // Byte-identity pin: the frozen wire-form literal
509        // `"tatara.pleme.io/v1alpha1"` that `ssapply.rs::
510        // build_owner_reference` hand-wrote pre-lift must equal the
511        // composed shape now sourced through the ONE owner. A
512        // future VERSION bump that missed this test would land as
513        // an operator-visible reference-mismatch after apply.
514        assert_eq!(api_version(), "tatara.pleme.io/v1alpha1");
515    }
516
517    #[test]
518    fn process_kind_is_process_literal() {
519        // Symbol-vs-string pin: any consumer that hand-wrote `"Process"`
520        // pre-lift routes through this const post-lift.
521        assert_eq!(PROCESS_KIND, "Process");
522    }
523
524    #[test]
525    fn owner_reference_json_has_all_six_slots_present() {
526        let v = owner_reference_json("my-process", "abc-uid");
527        let obj = v.as_object().expect("owner reference is a JSON object");
528        for k in [
529            "apiVersion",
530            "kind",
531            "name",
532            "uid",
533            "controller",
534            "blockOwnerDeletion",
535        ] {
536            assert!(obj.contains_key(k), "missing owner-reference slot: {k}");
537        }
538        assert_eq!(obj.len(), 6, "owner reference must have exactly 6 slots");
539    }
540
541    #[test]
542    fn owner_reference_json_apiversion_routes_through_api_version_owner() {
543        let v = owner_reference_json("x", "y");
544        assert_eq!(v["apiVersion"], api_version());
545    }
546
547    #[test]
548    fn owner_reference_json_kind_routes_through_process_kind_const() {
549        let v = owner_reference_json("x", "y");
550        assert_eq!(v["kind"], PROCESS_KIND);
551    }
552
553    #[test]
554    fn owner_reference_json_stamps_supplied_name_and_uid() {
555        let v = owner_reference_json("some-name", "some-uid");
556        assert_eq!(v["name"], "some-name");
557        assert_eq!(v["uid"], "some-uid");
558    }
559
560    #[test]
561    fn owner_reference_json_controller_and_block_owner_deletion_are_true() {
562        // These are structural — a Process-owned resource always
563        // has a controlling reference that cascade-deletes with
564        // the owner. A regression that flipped either boolean
565        // would silently detach every emitted resource.
566        let v = owner_reference_json("x", "y");
567        assert_eq!(v["controller"], true);
568        assert_eq!(v["blockOwnerDeletion"], true);
569    }
570
571    #[test]
572    fn owner_reference_json_matches_hand_authored_shape_pre_lift() {
573        // Byte-shape pin against the exact `json!({…})` incantation
574        // every pre-lift call site restated. A regression that
575        // reordered a slot, dropped one, or added a seventh here
576        // surfaces at THIS pin rather than as a subtle SSA-apply
577        // failure downstream when the K8s API server rejects the
578        // OwnerReference on schema mismatch.
579        let via_owner = owner_reference_json("p", "u");
580        let hand_authored = json!({
581            "apiVersion": "tatara.pleme.io/v1alpha1",
582            "kind": "Process",
583            "name": "p",
584            "uid": "u",
585            "controller": true,
586            "blockOwnerDeletion": true,
587        });
588        assert_eq!(via_owner, hand_authored);
589    }
590
591    #[test]
592    fn owner_reference_json_preserves_empty_name_and_uid_bytewise() {
593        // The primitive does not guard against empty inputs — its
594        // callers pre-lift did the empty-check upstream (both the
595        // `edges.rs::build_owner_refs` and `render.rs::one_export_job`
596        // sites gated on `!uid.is_empty()` before calling this composer,
597        // and both now route through `owner_references_json` below;
598        // `ssapply.rs::build_owner_reference` unwraps a required
599        // `metadata.uid` via anyhow). The scalar composer owns
600        // shape composition, not admission control; a downstream
601        // rename that wants strict input validation lands as a
602        // peer, not a change to the composer's contract.
603        let v = owner_reference_json("", "");
604        assert_eq!(v["name"], "");
605        assert_eq!(v["uid"], "");
606    }
607
608    // ─── owner_references_json substrate pins ────────────────────────
609    //
610    // The 3-line `let mut owner_refs = vec![]; if !uid.is_empty()
611    // { owner_refs.push(owner_reference_json(name, uid)); }` gate was
612    // hand-authored at TWO sites in `tatara-reconciler`
613    // (`edges::build_owner_refs` + `render::one_export_job`) before
614    // this primitive existed, each restating the same optional-uid
615    // posture that emits `[]` when the caller lacks a K8s-assigned
616    // uid to point owners at. These pins bind the primitive at
617    // fail-before-pass-after granularity so a regression that
618    // inlined an owner reference for an empty uid — silently
619    // detaching the resource from cascade-delete — surfaces HERE
620    // rather than as an operator-visible ownerless resource after
621    // apply, and a regression that added an owner reference of the
622    // wrong SHAPE (a peer of `owner_reference_json` that swapped a
623    // slot) surfaces via the composed-shape pin below rather than
624    // as silent drift at every downstream emit site.
625
626    #[test]
627    fn owner_references_json_emits_single_entry_when_uid_present() {
628        // The primary shape: a caller with a materialized uid gets
629        // exactly one owner reference back — the pre-lift 3-line
630        // `vec![]` + `push` gate collapses to this ONE call, and
631        // the returned array is a direct-drop `ownerReferences`
632        // slot value at every callsite.
633        let refs = owner_references_json("demo-app", "abc-uid");
634        assert_eq!(refs.len(), 1);
635        assert_eq!(refs[0]["kind"], PROCESS_KIND);
636        assert_eq!(refs[0]["name"], "demo-app");
637        assert_eq!(refs[0]["uid"], "abc-uid");
638        // controller + blockOwnerDeletion routed through the scalar
639        // composer — a regression that hand-composed the vec entry
640        // rather than delegating would flip one of these booleans.
641        assert_eq!(refs[0]["controller"], true);
642        assert_eq!(refs[0]["blockOwnerDeletion"], true);
643    }
644
645    #[test]
646    fn owner_references_json_emits_empty_when_uid_empty() {
647        // The load-bearing gate — a pre-metadata Process (fixtured in
648        // tests, or caught mid-Forking) has no admissible owner
649        // reference to point at. Post-lift the gate lives at ONE
650        // primitive so every emit site stamps `[]` uniformly rather
651        // than one site accidentally emitting a placeholder-uid
652        // owner reference the K8s GC would quietly detach from
653        // cascade-delete.
654        let refs = owner_references_json("demo-app", "");
655        assert!(
656            refs.is_empty(),
657            "empty uid must produce zero owner references, not a placeholder-uid entry"
658        );
659    }
660
661    #[test]
662    fn owner_references_json_gates_on_uid_not_name() {
663        // The gate axis is `uid`, not `name` — a Process with a
664        // non-empty name but no uid still emits `[]` (the pre-metadata
665        // shape), while a Process with a non-empty uid emits ONE
666        // entry even when the name slot is empty (matching the
667        // scalar composer's admission-control-free contract). Pin
668        // both cross-diagonal combinations so a regression that
669        // swapped the gate axis surfaces HERE rather than at every
670        // downstream owner-refs consumer.
671        assert!(
672            owner_references_json("has-name", "").is_empty(),
673            "empty uid gates to []; name presence is irrelevant"
674        );
675        let refs = owner_references_json("", "has-uid");
676        assert_eq!(
677            refs.len(),
678            1,
679            "empty name but present uid still emits one entry (name is not the gate)"
680        );
681        assert_eq!(refs[0]["name"], "");
682        assert_eq!(refs[0]["uid"], "has-uid");
683    }
684
685    #[test]
686    fn owner_references_json_matches_hand_authored_pre_lift_bytewise() {
687        // Byte-identical parity with the exact pre-lift 3-line
688        // `let mut owner_refs = vec![]; if !uid.is_empty() {
689        // owner_refs.push(owner_reference_json(name, uid)); }` gate
690        // across the two axis combinations every callsite plausibly
691        // encounters. A regression that reordered the two branches,
692        // dropped the gate, or reshaped the vec composition surfaces
693        // HERE rather than at every downstream `ownerReferences`
694        // slot pinned across `edges.rs` + `render.rs` tests.
695        for (name, uid) in [
696            ("demo-app", "uid-abc"),
697            ("demo-app", ""),
698            ("", "uid-abc"),
699            ("", ""),
700        ] {
701            let via_primitive = owner_references_json(name, uid);
702
703            // The pre-lift 3-line block, byte-for-byte.
704            let mut hand_authored: Vec<serde_json::Value> = vec![];
705            if !uid.is_empty() {
706                hand_authored.push(owner_reference_json(name, uid));
707            }
708
709            assert_eq!(
710                via_primitive, hand_authored,
711                "owner_references_json must be byte-identical to the pre-lift 3-line gate on ({name:?}, {uid:?})"
712            );
713        }
714    }
715
716    #[test]
717    fn owner_references_json_interpolates_cleanly_as_owner_refs_slot() {
718        // Both callsites drop the returned vec directly under a
719        // `"ownerReferences"` key inside a `json!({...})` block. Pin
720        // the interop shape: a JSON-macro-wrapped Value carries the
721        // primitive's output as a JSON array with the exact 6-slot
722        // entries at each index. A regression that returned a
723        // non-array (e.g. a single Value on the one-entry path,
724        // requiring per-site vec-wrapping) surfaces HERE rather than
725        // as a broken `metadata.ownerReferences` slot on every
726        // emitted Ingress / DNSEndpoint / export Job.
727        let refs = owner_references_json("demo-app", "abc-uid");
728        let wrapped = json!({
729            "metadata": {
730                "name": "resource",
731                "ownerReferences": refs,
732            },
733        });
734        let owner_refs = &wrapped["metadata"]["ownerReferences"];
735        assert!(
736            owner_refs.is_array(),
737            "ownerReferences must land as a JSON array"
738        );
739        assert_eq!(owner_refs.as_array().unwrap().len(), 1);
740        assert_eq!(owner_refs[0]["kind"], PROCESS_KIND);
741
742        // And the empty-uid path lands as an EMPTY array, not a
743        // missing key or a null — matches the K8s API server's
744        // expectation that the slot is either an array of entries
745        // or absent, never a null.
746        let empty_refs = owner_references_json("demo-app", "");
747        let wrapped_empty = json!({
748            "metadata": {
749                "name": "resource",
750                "ownerReferences": empty_refs,
751            },
752        });
753        let owner_refs_empty = &wrapped_empty["metadata"]["ownerReferences"];
754        assert!(owner_refs_empty.is_array());
755        assert!(owner_refs_empty.as_array().unwrap().is_empty());
756    }
757}
758
759#[cfg(test)]
760mod qualified_process_ref_tests {
761    //! Pin the [`qualified_process_ref`] composer at fail-before-
762    //! pass-after granularity. The `<ns>/<name>` shape is the
763    //! workspace-wide convention for a namespaced K8s resource
764    //! reference — every downstream grep (the reconciler's
765    //! `tatara.pleme.io/process` annotation reader, the
766    //! [`crate::table::ClaimRecord.holder`] slot, the
767    //! export-worker's receipt-owner filter, the reconciler's
768    //! `PROCESS=<ref>` label-selector composer) depends on the
769    //! two axes landing in `(ns, name)` order joined by a single
770    //! `/` separator. A regression that swapped the axes, dropped
771    //! either half, or renormalized the input surfaces HERE rather
772    //! than as silent operator-facing drift at every downstream
773    //! consumer.
774    use super::qualified_process_ref;
775
776    #[test]
777    fn qualified_process_ref_joins_ns_and_name_with_slash() {
778        // The invariant every downstream consumer composes against:
779        // the qualified reference is EXACTLY `<ns>/<name>`, in that
780        // order, joined by a single `/`.
781        assert_eq!(
782            qualified_process_ref("demo-ns", "ephemeral-demo"),
783            "demo-ns/ephemeral-demo",
784        );
785    }
786
787    #[test]
788    fn qualified_process_ref_binds_positional_slots_by_axis_order() {
789        // Positional pin — a copy-paste that swapped the two `&str`
790        // arguments (both mechanically interchangeable at the type
791        // level) would silently produce `<name>/<ns>` and break every
792        // downstream grep keyed on the reference shape. Distinct
793        // input slot values so a swap surfaces as an equality
794        // failure rather than accidental identity.
795        let out = qualified_process_ref("first-slot-ns", "second-slot-name");
796        assert!(
797            out.starts_with("first-slot-ns/"),
798            "position 0 must be the namespace slot: got {out}"
799        );
800        assert!(
801            out.ends_with("/second-slot-name"),
802            "position 1 must be the name slot: got {out}"
803        );
804    }
805
806    #[test]
807    fn qualified_process_ref_accepts_string_deref_and_str_slice_shapes() {
808        // Consumers split across two callsite shapes: owned
809        // `String` locals (via deref coercion), bare `&str` slices,
810        // and mixed provenance. Every shape must ride cleanly
811        // through the same 2-arg signature — matches every current
812        // pre-lift caller in `tatara-export-worker` (CLI-arg driven
813        // owned strings + `&str` from a struct field) and in
814        // `tatara-reconciler` (owned locals + function-param
815        // slices).
816        let owned_ns = String::from("owned-ns");
817        let owned_name = String::from("owned-app");
818        let borrowed_ns: &str = "borrowed-ns";
819        let borrowed_name: &str = "borrowed-app";
820        assert_eq!(
821            qualified_process_ref(&owned_ns, &owned_name),
822            "owned-ns/owned-app",
823        );
824        assert_eq!(
825            qualified_process_ref(borrowed_ns, borrowed_name),
826            "borrowed-ns/borrowed-app",
827        );
828        assert_eq!(
829            qualified_process_ref(&owned_ns, borrowed_name),
830            "owned-ns/borrowed-app",
831        );
832    }
833
834    #[test]
835    fn qualified_process_ref_rides_edge_case_axis_shapes() {
836        // The composer shapes the two axes as arbitrary strings —
837        // no length/character validation happens at the composer,
838        // so any shape a Process's `metadata.namespace` /
839        // `metadata.name` can hold rides through unchanged. Pin
840        // the empty-string cases (unnamed process pre-metadata,
841        // cluster-scoped `namespace = ""` fallback), and the
842        // whitespace-and-slash-in-name pathological case (a
843        // regression that URL-escaped or path-normalized the input
844        // at this primitive would silently break every downstream
845        // grep).
846        assert_eq!(qualified_process_ref("", ""), "/");
847        assert_eq!(qualified_process_ref("default", ""), "default/");
848        assert_eq!(qualified_process_ref("", "orphan"), "/orphan");
849        assert_eq!(
850            qualified_process_ref("weird ns", "with/slash"),
851            "weird ns/with/slash",
852        );
853    }
854
855    #[test]
856    fn qualified_process_ref_composes_from_process_coordinates_or_defaults() {
857        // The primary Process-driven callsite: a live
858        // [`crate::prelude::Process`] with populated metadata
859        // composes through
860        // [`crate::prelude::Process::coordinates_or_defaults`] +
861        // [`qualified_process_ref`]. Pin the composition so a
862        // regression in either primitive that broke the `(ns,
863        // name)` positional contract surfaces HERE rather than as
864        // silent drift at every downstream reconciler / export-
865        // worker / pool-reconciler consumer.
866        use crate::classification::{Classification, ConvergencePointType, SubstrateType};
867        use crate::crd::{Process, ProcessSpec};
868        let spec = ProcessSpec {
869            identity: Default::default(),
870            classification: Classification {
871                point_type: ConvergencePointType::Gate,
872                substrate: SubstrateType::Compute,
873                horizon: Default::default(),
874                calm: Default::default(),
875                data_classification: Default::default(),
876            },
877            intent: Default::default(),
878            boundary: Default::default(),
879            compliance: Default::default(),
880            depends_on: vec![],
881            signals: Default::default(),
882            lifetime: Default::default(),
883            routing: None,
884            encapsulates: None,
885            suspended: false,
886        };
887        let mut p = Process::new("ephemeral-demo", spec);
888        p.metadata.namespace = Some("demo-ns".into());
889        let (ns, name) = p.coordinates_or_defaults();
890        assert_eq!(
891            qualified_process_ref(ns, name),
892            "demo-ns/ephemeral-demo",
893            "coordinates_or_defaults + qualified_process_ref must \
894             compose to the canonical <ns>/<name> shape"
895        );
896    }
897
898    #[test]
899    fn qualified_process_ref_matches_hand_authored_pre_lift_bytewise() {
900        // Byte-identical parity with the exact pre-lift
901        // `format!("{ns}/{name}")` incantation. A regression that
902        // reshaped the separator, reordered the axes, or dropped
903        // either half surfaces HERE rather than at every downstream
904        // annotation / claim-key / run-id consumer. Sweeps every
905        // shape combination the pre-lift callers plausibly
906        // encountered.
907        for (ns, name) in [
908            ("demo-ns", "ephemeral-demo"),
909            ("", ""),
910            ("default", ""),
911            ("", "orphan"),
912        ] {
913            let via_primitive = qualified_process_ref(ns, name);
914            let hand_authored = format!("{ns}/{name}");
915            assert_eq!(
916                via_primitive, hand_authored,
917                "qualified_process_ref must be byte-identical to \
918                 the pre-lift `format!(\"{{ns}}/{{name}}\")` \
919                 hand-authored shape on ({ns:?}, {name:?})"
920            );
921        }
922    }
923}
924
925#[cfg(test)]
926mod namespaced_api_coordinates_tests {
927    //! Pin the [`NamespacedApiCoordinates`] trait's
928    //! `owned_coordinates_required` extractor at fail-before-pass-
929    //! after granularity across every corner of the (namespace slot,
930    //! name slot) × (present, absent) input matrix, on BOTH CRDs the
931    //! trait's blanket impl covers today (`EphemeralPool` +
932    //! `EphemeralAllocation`). A regression that reordered the two
933    //! `ok_or_else` gates, dropped the `Self::kind` prefix, or drifted
934    //! the error-string spelling surfaces HERE rather than as silent
935    //! operator-facing skew between the two reconcilers' top-level
936    //! error messages.
937    use super::NamespacedApiCoordinates;
938    use crate::allocation::{AllocationSpec, EphemeralAllocation, Requestor};
939    use crate::ephemeral::EphemeralSpec;
940    use crate::intent::AplicacaoIntent;
941    use crate::lifetime::TeardownPolicy;
942    use crate::pool::{EphemeralPool, PoolSelector, PoolSpec, ReturnPolicy};
943
944    fn empty_template() -> EphemeralSpec {
945        // Mirror `tatara-pool-reconciler::router::tests::empty_template`
946        // — the workspace-wide minimal `EphemeralSpec` fixture the sister
947        // reconciler tests already use for pool wiring exercised here.
948        EphemeralSpec {
949            aplicacao: AplicacaoIntent {
950                chart_ref: "oci://x".into(),
951                version: "1".into(),
952                profile: String::new(),
953                values_overlay: serde_json::Value::Null,
954                release_name: None,
955                target_namespace: None,
956                install_timeout: None,
957            },
958            ttl: "1h".into(),
959            teardown: TeardownPolicy::Always,
960            max_concurrent: 0,
961            postconditions: vec![],
962            preconditions: vec![],
963            verify_timeout: None,
964            classification: None,
965            parent: None,
966            exports: vec![],
967            routing: None,
968        }
969    }
970
971    fn pool_fixture(name: &str, ns: Option<&str>) -> EphemeralPool {
972        let spec = PoolSpec {
973            desired_size: 1,
974            min_size: 0,
975            max_size: 0,
976            return_policy: ReturnPolicy::Replace,
977            selector: PoolSelector::default(),
978            template: empty_template(),
979            free_ttl: "24h".into(),
980            max_allocation_ttl: "4h".into(),
981            desired: 0,
982            replacement_policy: Default::default(),
983            stable_name_claim: false,
984        };
985        let mut p = EphemeralPool::new(name, spec);
986        p.metadata.namespace = ns.map(str::to_string);
987        p
988    }
989
990    fn alloc_fixture(name: &str, ns: Option<&str>) -> EphemeralAllocation {
991        let spec = AllocationSpec {
992            pool_ref: None,
993            requestor: Requestor {
994                kind: "github-pr".into(),
995                repo: None,
996                branch: None,
997                pr_number: None,
998                sha: None,
999                pr_labels: vec![],
1000                actor: None,
1001            },
1002            ttl: None,
1003            note: None,
1004        };
1005        let mut a = EphemeralAllocation::new(name, spec);
1006        a.metadata.namespace = ns.map(str::to_string);
1007        a
1008    }
1009
1010    fn nameless_pool(ns: Option<&str>) -> EphemeralPool {
1011        let mut p = pool_fixture("placeholder", ns);
1012        p.metadata.name = None;
1013        p
1014    }
1015
1016    fn nameless_alloc(ns: Option<&str>) -> EphemeralAllocation {
1017        let mut a = alloc_fixture("placeholder", ns);
1018        a.metadata.name = None;
1019        a
1020    }
1021
1022    // ── Happy path: both slots present ─────────────────────────────
1023
1024    #[test]
1025    fn owned_coordinates_required_returns_owned_strings_on_ephemeral_pool_when_both_slots_present()
1026    {
1027        let p = pool_fixture("attest-pool", Some("ephemeral-pools"));
1028        let (ns, name) = p.owned_coordinates_required().unwrap();
1029        assert_eq!(ns, "ephemeral-pools");
1030        assert_eq!(name, "attest-pool");
1031    }
1032
1033    #[test]
1034    fn owned_coordinates_required_returns_owned_strings_on_ephemeral_allocation_when_both_slots_present(
1035    ) {
1036        let a = alloc_fixture("pr-42-demo", Some("ephemeral-pools"));
1037        let (ns, name) = a.owned_coordinates_required().unwrap();
1038        assert_eq!(ns, "ephemeral-pools");
1039        assert_eq!(name, "pr-42-demo");
1040    }
1041
1042    // ── Missing namespace ─────────────────────────────────────────
1043
1044    #[test]
1045    fn owned_coordinates_required_errors_on_ephemeral_pool_missing_namespace() {
1046        let p = pool_fixture("attest-pool", None);
1047        let err = p.owned_coordinates_required().unwrap_err();
1048        assert_eq!(err.to_string(), "EphemeralPool has no metadata.namespace");
1049    }
1050
1051    #[test]
1052    fn owned_coordinates_required_errors_on_ephemeral_allocation_missing_namespace() {
1053        let a = alloc_fixture("pr-42-demo", None);
1054        let err = a.owned_coordinates_required().unwrap_err();
1055        assert_eq!(
1056            err.to_string(),
1057            "EphemeralAllocation has no metadata.namespace"
1058        );
1059    }
1060
1061    // ── Missing name ──────────────────────────────────────────────
1062
1063    #[test]
1064    fn owned_coordinates_required_errors_on_ephemeral_pool_missing_name_when_namespace_present() {
1065        let p = nameless_pool(Some("ephemeral-pools"));
1066        let err = p.owned_coordinates_required().unwrap_err();
1067        assert_eq!(err.to_string(), "EphemeralPool has no metadata.name");
1068    }
1069
1070    #[test]
1071    fn owned_coordinates_required_errors_on_ephemeral_allocation_missing_name_when_namespace_present(
1072    ) {
1073        let a = nameless_alloc(Some("ephemeral-pools"));
1074        let err = a.owned_coordinates_required().unwrap_err();
1075        assert_eq!(err.to_string(), "EphemeralAllocation has no metadata.name");
1076    }
1077
1078    // ── Missing both slots: namespace error wins (pre-lift ordering) ──
1079
1080    #[test]
1081    fn owned_coordinates_required_reports_namespace_first_when_both_slots_absent_on_ephemeral_pool()
1082    {
1083        // Pre-lift both reconcilers spelled the paired chain as the
1084        // namespace ok_or_else THEN the name ok_or_else, so the
1085        // reported error on a fixture missing both slots was always
1086        // the namespace one. Pin that ordering post-lift so a
1087        // regression that swapped the two `ok_or_else` blocks
1088        // surfaces HERE rather than at operator-facing log-line
1089        // grep drift between the two reconcilers.
1090        let p = nameless_pool(None);
1091        let err = p.owned_coordinates_required().unwrap_err();
1092        assert_eq!(err.to_string(), "EphemeralPool has no metadata.namespace");
1093    }
1094
1095    #[test]
1096    fn owned_coordinates_required_reports_namespace_first_when_both_slots_absent_on_ephemeral_allocation(
1097    ) {
1098        let a = nameless_alloc(None);
1099        let err = a.owned_coordinates_required().unwrap_err();
1100        assert_eq!(
1101            err.to_string(),
1102            "EphemeralAllocation has no metadata.namespace"
1103        );
1104    }
1105
1106    // ── Byte-identical parity with the pre-lift 5-line chain ──────
1107
1108    #[test]
1109    fn owned_coordinates_required_matches_pre_lift_pool_reconciler_chain_shape() {
1110        // Byte-identical parity pin: the primitive produces the SAME
1111        // `Result<(String, String), anyhow::Error>` shape a pre-lift
1112        // `.metadata.<slot>.clone().ok_or_else(|| anyhow!("<Kind> has
1113        // no metadata.<slot>"))?` chain produced at
1114        // `tatara-pool-reconciler::controller_pool::reconcile_inner`
1115        // pre-lift, on both the happy and the missing-slot corners.
1116        // A regression that changed the error prefix, reordered the
1117        // two gates, or returned a non-`(String, String)` tuple
1118        // surfaces HERE rather than at every consumer downstream.
1119        let cases = [
1120            (Some("prod"), Some("api")),
1121            (Some("prod"), None),
1122            (None, Some("orphan")),
1123            (None, None),
1124        ];
1125        for (ns_slot, name_slot) in cases {
1126            let mut p = pool_fixture("placeholder", ns_slot);
1127            if let Some(nm) = name_slot {
1128                p.metadata.name = Some(nm.into());
1129            } else {
1130                p.metadata.name = None;
1131            }
1132
1133            // Pre-lift 5-line paired chain (with the reconciler's
1134            // hand-authored short-form `"Pool"` prefix updated to the
1135            // canonical kube kind `"EphemeralPool"`, matching the
1136            // primitive's `Self::kind`-driven spelling — the drift
1137            // is intentional per the trait's docs).
1138            let pre_lift: anyhow::Result<(String, String)> = (|| {
1139                let ns =
1140                    p.metadata.namespace.clone().ok_or_else(|| {
1141                        anyhow::anyhow!("EphemeralPool has no metadata.namespace")
1142                    })?;
1143                let name = p
1144                    .metadata
1145                    .name
1146                    .clone()
1147                    .ok_or_else(|| anyhow::anyhow!("EphemeralPool has no metadata.name"))?;
1148                Ok((ns, name))
1149            })();
1150
1151            let via_primitive = p.owned_coordinates_required();
1152
1153            // Compare on both the Ok tuple + the error string
1154            // spelling — anyhow::Error does not derive PartialEq so
1155            // pattern-match on the Result axis rather than a direct
1156            // `assert_eq!` on the whole Result.
1157            match (via_primitive, pre_lift) {
1158                (Ok(a), Ok(b)) => assert_eq!(a, b),
1159                (Err(a), Err(b)) => assert_eq!(a.to_string(), b.to_string()),
1160                (a, b) => panic!(
1161                    "primitive vs pre-lift chain disagree on Ok/Err axis for \
1162                     (ns={ns_slot:?}, name={name_slot:?}): primitive={a:?}, pre_lift={b:?}"
1163                ),
1164            }
1165        }
1166    }
1167
1168    #[test]
1169    fn owned_coordinates_required_matches_pre_lift_allocation_reconciler_chain_shape() {
1170        // Peer to the pool-side pin above — pin the same byte-
1171        // identity contract on the allocation reconciler's chain,
1172        // where the pre-lift error spelling used the short-form
1173        // `"Allocation"` prefix that the primitive now emits as the
1174        // canonical kube-kind `"EphemeralAllocation"`.
1175        let cases = [
1176            (Some("ephemeral-pools"), Some("pr-42-demo")),
1177            (Some("ephemeral-pools"), None),
1178            (None, Some("orphan")),
1179            (None, None),
1180        ];
1181        for (ns_slot, name_slot) in cases {
1182            let mut a = alloc_fixture("placeholder", ns_slot);
1183            if let Some(nm) = name_slot {
1184                a.metadata.name = Some(nm.into());
1185            } else {
1186                a.metadata.name = None;
1187            }
1188
1189            let pre_lift: anyhow::Result<(String, String)> = (|| {
1190                let ns = a.metadata.namespace.clone().ok_or_else(|| {
1191                    anyhow::anyhow!("EphemeralAllocation has no metadata.namespace")
1192                })?;
1193                let name =
1194                    a.metadata.name.clone().ok_or_else(|| {
1195                        anyhow::anyhow!("EphemeralAllocation has no metadata.name")
1196                    })?;
1197                Ok((ns, name))
1198            })();
1199
1200            let via_primitive = a.owned_coordinates_required();
1201
1202            match (via_primitive, pre_lift) {
1203                (Ok(a), Ok(b)) => assert_eq!(a, b),
1204                (Err(a), Err(b)) => assert_eq!(a.to_string(), b.to_string()),
1205                (a, b) => panic!(
1206                    "primitive vs pre-lift chain disagree on Ok/Err axis for \
1207                     (ns={ns_slot:?}, name={name_slot:?}): primitive={a:?}, pre_lift={b:?}"
1208                ),
1209            }
1210        }
1211    }
1212
1213    // ── Cross-CRD symmetry: kube kind drives the error prefix ─────
1214
1215    #[test]
1216    fn owned_coordinates_required_error_prefix_matches_kube_kind_on_each_crd() {
1217        // The error prefix is sourced positionally from `Self::kind`
1218        // so the two CRDs emit distinct kube-canonical spellings
1219        // without either callsite hard-coding a per-CRD literal.
1220        // Regressions that hard-coded a shared prefix (e.g. a
1221        // copy-paste that pasted the pool's error string into the
1222        // allocation callsite) surface HERE.
1223        use kube::Resource;
1224        let p = pool_fixture("p", None);
1225        let a = alloc_fixture("a", None);
1226        assert_eq!(
1227            p.owned_coordinates_required().unwrap_err().to_string(),
1228            format!("{} has no metadata.namespace", EphemeralPool::kind(&()))
1229        );
1230        assert_eq!(
1231            a.owned_coordinates_required().unwrap_err().to_string(),
1232            format!(
1233                "{} has no metadata.namespace",
1234                EphemeralAllocation::kind(&())
1235            )
1236        );
1237        // Belt-and-suspenders: the two kinds are distinct spellings,
1238        // so the error strings are distinct too.
1239        assert_ne!(
1240            p.owned_coordinates_required().unwrap_err().to_string(),
1241            a.owned_coordinates_required().unwrap_err().to_string(),
1242        );
1243    }
1244}
1245
1246// ── Lisp → ProcessSpec compile bridge ──────────────────────────────────
1247//
1248// `(defpoint NAME :k v …)` compiles to a `NamedDefinition<ProcessSpec>`.
1249// The derive on ProcessSpec handles every field via the serde Deserialize
1250// fallthrough — no hand-rolled keyword parsing needed.
1251
1252/// A named ProcessSpec as produced by `compile_source`.
1253pub type Definition = tatara_lisp::NamedDefinition<crate::crd::ProcessSpec>;
1254
1255/// Compile a Lisp source string into a list of named ProcessSpecs.
1256/// Each top-level `(defpoint NAME …)` form becomes one `Definition`.
1257pub fn compile_source(src: &str) -> tatara_lisp::Result<Vec<Definition>> {
1258    tatara_lisp::compile_named::<crate::crd::ProcessSpec>(src)
1259}
1260
1261/// Register every domain owned by this crate with the global Lisp
1262/// dispatcher. Call once per binary, typically near the top of `main`.
1263/// After this call, `tatara_lisp::domain::lookup("defpoint")` and
1264/// `lookup("defephemeral")` both resolve to the right typed compiler.
1265///
1266/// Idempotent — registering the same type twice is a no-op.
1267pub fn register_all() {
1268    tatara_lisp::domain::register::<crate::crd::ProcessSpec>();
1269    tatara_lisp::domain::register::<crate::ephemeral::EphemeralSpec>();
1270}
1271
1272#[cfg(test)]
1273mod compile_tests {
1274    use super::compile_source;
1275    use crate::classification::{ConvergencePointType, SubstrateType};
1276    use crate::compliance::VerificationPhase;
1277    use crate::spec::MustReachPhase;
1278
1279    /// The full derive-powered pipeline — no hand-rolled parsing anywhere.
1280    /// Every field travels: Lisp → Sexp → serde_json → typed ProcessSpec.
1281    #[test]
1282    fn full_processspec_round_trip_via_derive() {
1283        let src = r#"
1284            (defpoint observability-stack
1285              :identity       (:parent "seph.1")
1286              :classification (:point-type Gate
1287                               :substrate Observability
1288                               :horizon (:kind Bounded)
1289                               :calm Monotone
1290                               :data-classification Internal)
1291              :intent         (:nix (:flake-ref "github:pleme-io/k8s"
1292                                     :attribute "observability"
1293                                     :attic-cache "main"))
1294              :boundary       (:postconditions
1295                                 ((:kind KustomizationHealthy
1296                                   :params (:name "observability-stack"
1297                                            :namespace "flux-system"))
1298                                  (:kind PromQL
1299                                   :params (:query "up == 1")))
1300                               :timeout "15m")
1301              :compliance     (:baseline "fedramp-moderate"
1302                               :bindings ((:framework "nist-800-53"
1303                                           :control-id "SC-7"
1304                                           :phase AtBoundary)))
1305              :depends-on     ((:name "secret-injection" :must-reach Attested))
1306              :signals        (:sigterm-grace-seconds 480
1307                               :sighup-strategy Reconverge))
1308        "#;
1309        let defs = compile_source(src).expect("compile");
1310        assert_eq!(defs.len(), 1);
1311        let d = &defs[0];
1312        assert_eq!(d.name, "observability-stack");
1313
1314        // identity
1315        assert_eq!(d.spec.identity.parent.as_deref(), Some("seph.1"));
1316
1317        // classification (enums deserialized via symbol → string)
1318        assert_eq!(d.spec.classification.point_type, ConvergencePointType::Gate);
1319        assert_eq!(
1320            d.spec.classification.substrate,
1321            SubstrateType::Observability
1322        );
1323
1324        // intent (tagged-union with one of four options)
1325        let nix = d.spec.intent.nix.as_ref().expect("nix intent");
1326        assert_eq!(nix.flake_ref, "github:pleme-io/k8s");
1327        assert_eq!(nix.attribute, "observability");
1328        assert_eq!(nix.attic_cache.as_deref(), Some("main"));
1329
1330        // boundary (Vec<nested struct with params object>)
1331        assert_eq!(d.spec.boundary.postconditions.len(), 2);
1332        assert_eq!(d.spec.boundary.timeout.as_deref(), Some("15m"));
1333
1334        // compliance (Vec<binding with enum phase>)
1335        assert_eq!(
1336            d.spec.compliance.baseline.as_deref(),
1337            Some("fedramp-moderate")
1338        );
1339        assert_eq!(d.spec.compliance.bindings.len(), 1);
1340        assert_eq!(
1341            d.spec.compliance.bindings[0].phase,
1342            VerificationPhase::AtBoundary
1343        );
1344
1345        // depends_on (Vec<struct with enum>)
1346        assert_eq!(d.spec.depends_on.len(), 1);
1347        assert_eq!(d.spec.depends_on[0].must_reach, MustReachPhase::Attested);
1348
1349        // signals (numeric + enum defaults)
1350        assert_eq!(d.spec.signals.sigterm_grace_seconds, 480);
1351    }
1352
1353    #[test]
1354    fn missing_required_field_errors() {
1355        // `:classification` has no #[serde(default)] — omit it and compile must fail.
1356        let src = r#"(defpoint x :intent (:nix (:flake-ref "f" :attribute "a")))"#;
1357        assert!(compile_source(src).is_err());
1358    }
1359
1360    #[test]
1361    fn serde_default_fields_are_optional() {
1362        // Omit every #[serde(default)] field — compile must succeed because
1363        // the derive honors serde defaults.
1364        let src = r#"
1365            (defpoint x
1366              :classification (:point-type Transform :substrate Compute)
1367              :intent (:flux (:git-repository "g" :path ".")))
1368        "#;
1369        let defs = compile_source(src).expect("compile");
1370        assert_eq!(defs.len(), 1);
1371        let d = &defs[0];
1372        assert!(d.spec.depends_on.is_empty());
1373        assert!(d.spec.boundary.postconditions.is_empty());
1374        assert!(d.spec.compliance.bindings.is_empty());
1375        assert!(!d.spec.suspended);
1376        // Lifetime defaults to Permanent (no variant set, resolver still works).
1377        assert!(d.spec.lifetime.is_default());
1378        assert!(!d.spec.lifetime.is_ephemeral());
1379    }
1380
1381    /// Registering all process-owned domains is idempotent and resolves
1382    /// both `defpoint` (ProcessSpec) and `defephemeral` (EphemeralSpec).
1383    #[test]
1384    fn register_all_resolves_defpoint_and_defephemeral() {
1385        use tatara_lisp::domain::lookup;
1386        super::register_all();
1387        super::register_all(); // idempotent
1388        assert!(lookup("defpoint").is_some(), "defpoint must resolve");
1389        assert!(
1390            lookup("defephemeral").is_some(),
1391            "defephemeral must resolve"
1392        );
1393    }
1394
1395    /// End-to-end: a `(defpoint …)` form may carry the full ephemeral
1396    /// shape directly — `:intent (:aplicacao …)` + `:lifetime (:ephemeral …)`.
1397    /// This is what the `(defephemeral …)` sugar lowers to via `From`.
1398    #[test]
1399    fn defpoint_with_aplicacao_intent_and_ephemeral_lifetime() {
1400        use crate::intent::IntentVariant;
1401        use crate::lifetime::{LifetimeVariant, TeardownPolicy};
1402        let src = r#"
1403            (defpoint closed-loop-attest
1404              :classification (:point-type Gate :substrate Compute)
1405              :intent (:aplicacao
1406                        (:chart-ref "oci://ghcr.io/pleme-io/charts/lareira-demo-app"
1407                         :version "0.5.5"
1408                         :profile "all-in-one"
1409                         :values-overlay (:cluster (:name "ephemeral-test-01"))
1410                         :target-namespace "demo-test"))
1411              :boundary (:postconditions
1412                          ((:kind HelmReleaseReleased
1413                            :params (:name "demo-app-consolidated"
1414                                     :namespace "demo-test"))
1415                           (:kind ClosedLoopAuth
1416                            :params (:issuer (:service "demo-app-issuer" :port 8080)
1417                                     :consumer (:service "demo-app-gateway" :port 8000)
1418                                     :probeImage "ghcr.io/pleme-io/closed-loop-probe:0.1.0"))))
1419              :lifetime (:ephemeral (:ttl "1h"
1420                                     :teardown-policy OnAttested
1421                                     :max-concurrent 1)))
1422        "#;
1423        let defs = compile_source(src).expect("compile");
1424        assert_eq!(defs.len(), 1);
1425        let d = &defs[0];
1426
1427        // Aplicacao intent landed.
1428        match d.spec.intent.variant().unwrap() {
1429            IntentVariant::Aplicacao(a) => {
1430                assert_eq!(a.profile, "all-in-one");
1431                assert_eq!(a.version, "0.5.5");
1432                assert_eq!(a.target_namespace.as_deref(), Some("demo-test"));
1433                assert_eq!(a.values_overlay["cluster"]["name"], "ephemeral-test-01");
1434            }
1435            other => panic!("expected Aplicacao, got {other:?}"),
1436        }
1437
1438        // Ephemeral lifetime landed with the right teardown policy.
1439        match d.spec.lifetime.variant().unwrap() {
1440            LifetimeVariant::Ephemeral(e) => {
1441                assert_eq!(e.ttl, "1h");
1442                assert_eq!(e.teardown_policy, TeardownPolicy::OnAttested);
1443                assert_eq!(e.max_concurrent, 1);
1444            }
1445            other => panic!("expected ephemeral, got {other:?}"),
1446        }
1447
1448        // Two typed postconditions including ClosedLoopAuth.
1449        assert_eq!(d.spec.boundary.postconditions.len(), 2);
1450        assert_eq!(
1451            d.spec.boundary.postconditions[1].kind,
1452            crate::boundary::ConditionKind::ClosedLoopAuth
1453        );
1454    }
1455}