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::receipt::{
103        default_receipt_config_map_name, ReceiptEnvelope, ReceiptError, ReceiptKind,
104        RECEIPT_CM_SUFFIX, RECEIPT_VERSION,
105    };
106    pub use crate::routing::{RoutingBackend, RoutingForm, RoutingHostname, RoutingSpec};
107    pub use crate::routing_edge_resource::RoutingEdgeResource;
108    pub use crate::signal::{ProcessSignal, SighupStrategy, UnknownSighupStrategy};
109    pub use crate::spec::{
110        DependsOn, IdentitySpec, MustReachPhase, SignalPolicy, UnknownMustReachPhase,
111    };
112    pub use crate::status::{
113        BoundaryStatus, CheckedCondition, ComplianceStatus, FluxResourceRef, ProcessCondition,
114        RenderedResourceCoords,
115    };
116    pub use crate::table::{
117        ClaimRecord, ProcessEntry, ProcessTable, ProcessTableSpec, ProcessTableStatus,
118    };
119}
120
121/// CRD API group for every tatara CRD.
122pub const GROUP: &str = "tatara.pleme.io";
123/// CRD version for this module.
124pub const VERSION: &str = "v1alpha1";
125/// Kind spelling of the tatara Process CRD as it appears in a K8s
126/// [`OwnerReference.kind`][ownref] field. Peer to [`GROUP`] +
127/// [`VERSION`] — centralizes the ONE literal every SSA-time
128/// re-injection helper pre-lift restated by hand across
129/// `tatara-reconciler` (`render.rs`, `edges.rs`, `ssapply.rs`).
130///
131/// [ownref]: https://kubernetes.io/docs/concepts/overview/working-with-objects/owners-dependents/
132pub const PROCESS_KIND: &str = "Process";
133
134/// Canonical `<GROUP>/<VERSION>` as an owned `String` — the ONE
135/// K8s `apiVersion` shape every tatara CRD stamps. Composed from
136/// [`GROUP`] + [`VERSION`] so a bump of either constant lands here
137/// exactly once; pre-lift, two `tatara-reconciler` sites hand-wrote
138/// `format!("{}/{}", tatara_process::GROUP, tatara_process::VERSION)`
139/// while a third inlined the literal `"tatara.pleme.io/v1alpha1"`,
140/// opening a silent drift path if `VERSION` ever advances past
141/// `v1alpha1`.
142pub fn api_version() -> String {
143    format!("{GROUP}/{VERSION}")
144}
145
146/// Build a Kubernetes [`OwnerReference`][ownref] JSON blob pointing
147/// at a Process (`kind = `[`PROCESS_KIND`], `apiVersion = `
148/// [`api_version`]) with `controller: true` +
149/// `blockOwnerDeletion: true` — the exact 6-slot shape every SSA
150/// re-injection site pre-lift restated three times across
151/// `tatara-reconciler` (`render.rs::owner_refs` for export-Job
152/// owners, `edges.rs::build_owner_refs` for Ingress + DNSEndpoint
153/// owners, `ssapply.rs::build_owner_reference` for the injected
154/// owner-ref stamped on every applied `DynamicObject`). Callers
155/// with a live `Process` value read `metadata.{name,uid}` and pass
156/// them through as `&str`.
157///
158/// The 6-slot shape is fixed (`controller` + `blockOwnerDeletion`
159/// both `true`); a Process-owned resource that wants a non-
160/// controller reference doesn't belong on this owner and can build
161/// its own `json!` inline — this primitive is the composer for the
162/// canonical "Process controls this resource, cascade-delete on
163/// GC" shape, not a general OwnerReference builder.
164///
165/// [ownref]: https://kubernetes.io/docs/concepts/overview/working-with-objects/owners-dependents/
166pub fn owner_reference_json(name: &str, uid: &str) -> serde_json::Value {
167    serde_json::json!({
168        "apiVersion": api_version(),
169        "kind": PROCESS_KIND,
170        "name": name,
171        "uid": uid,
172        "controller": true,
173        "blockOwnerDeletion": true,
174    })
175}
176
177/// Substrate-primitive builder for a Process-owned resource's
178/// **`metadata.ownerReferences` array** — the empty-uid-gated,
179/// single-entry `Vec<Value>` every emit site that lacks a fully
180/// materialized [`crate::prelude::Process`] (i.e. every site that
181/// works from a bare `(name, uid)` pair rather than routing through
182/// [`ssapply::build_owner_reference`](../tatara_reconciler/ssapply/fn.build_owner_reference.html)'s
183/// anyhow-guarded unwrap) hand-composed by wrapping
184/// [`owner_reference_json`] in a `Vec::new()` + `is_empty` gate on
185/// the `uid` slot.
186///
187/// The `uid.is_empty()` gate encodes the invariant every caller
188/// already enforced: a Process pre-metadata (fixtured in tests, or
189/// caught mid-Forking before the API server has stamped a `uid`) has
190/// no admissible owner reference to point at, so the emit site
191/// stamps `metadata.ownerReferences: []` rather than an
192/// owner-referenceless resource pointing at a placeholder uid the K8s
193/// GC would silently ignore. Post-lift the gate lives at ONE
194/// primitive so a regression that inlined an owner reference for
195/// an empty uid — which the API server accepts and quietly detaches
196/// from cascade-delete — surfaces at THIS primitive's pin rather
197/// than as an operator-visible ownerless resource after apply.
198///
199/// Pre-lift the 3-line `let mut owner_refs = vec![]; if
200/// !uid.is_empty() { owner_refs.push(owner_reference_json(name,
201/// uid)); }` incantation was hand-authored at TWO sites past the
202/// ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold in
203/// `tatara-reconciler`, each restating the same gated composition:
204/// * `edges::build_owner_refs` — the shared owner-refs builder both
205///   `IngressEdge` + `DnsEndpointEdge` route through, sourcing
206///   `(process_name, process_uid)` from the [`crate::edges::EdgeContext`].
207/// * `render::one_export_job` — the export Job's owner-refs seed,
208///   sourcing `(name, uid)` from the [`crate::prelude::Process`]
209///   `render_export_jobs` threaded in.
210///
211/// Post-lift both callsites read `owner_references_json(name, uid)`.
212/// A future addition — e.g. a second owner-reference slot naming a
213/// controlling ProcessTable entry, a policy that stamps a stale-uid
214/// warning annotation before returning empty, or a normalization
215/// that strips a cluster-prefix off the uid — lands at ONE
216/// substrate function here and every emit site inherits the upgrade
217/// mechanically. The [`ssapply::build_owner_reference`] path (which
218/// works from a materialized [`crate::prelude::Process`] and errors
219/// on absent `metadata.uid`) is a peer, not a lift candidate: its
220/// contract is "the K8s API server assigned a uid, so refuse to
221/// SSA-apply resources whose owner cannot be materialized", while
222/// this primitive's contract is "the caller has an optional-uid
223/// posture; emit `[]` when the uid is absent". The two shapes
224/// partition the input space at the "is the enclosing scope
225/// obligated to produce a materialized Process reference" axis.
226///
227/// The 2-arg `(&str, &str)` signature accepts both the
228/// `EdgeContext`-sourced `(&str, &str)` slice shape and the
229/// `render_export_jobs`-owned `(name: &str, uid: &str)` local shape
230/// without widening — matches every current callsite.
231pub fn owner_references_json(name: &str, uid: &str) -> Vec<serde_json::Value> {
232    if uid.is_empty() {
233        vec![]
234    } else {
235        vec![owner_reference_json(name, uid)]
236    }
237}
238
239/// Annotation keys the reconciler reads/writes on owned FluxCD resources.
240pub mod annotations {
241    pub const MANAGED_BY: &str = "tatara.pleme.io/managed-by";
242    pub const PROCESS: &str = "tatara.pleme.io/process";
243    pub const PID: &str = "tatara.pleme.io/pid";
244    pub const CONTENT_HASH: &str = "tatara.pleme.io/content-hash";
245    pub const ATTESTATION_ROOT: &str = "tatara.pleme.io/attestation-root";
246    pub const GENERATION: &str = "tatara.pleme.io/generation";
247    pub const SIGNAL: &str = "tatara.pleme.io/signal";
248    /// Stamped by the reconciler when transitioning into `Releasing`
249    /// — records which terminal-reached gate the Process came from
250    /// (`Attested` or `Failed`) so `handle_releasing` can pick the
251    /// matching `ExportTrigger` set + the correct post-Releasing
252    /// destination (`Exiting` from Attested, `Zombie` from Failed).
253    pub const RELEASED_FROM: &str = "tatara.pleme.io/released-from";
254    /// Labels the export-worker Jobs the reconciler emits during
255    /// `Releasing`. Selector: `tatara.pleme.io/role=export`.
256    pub const ROLE: &str = "tatara.pleme.io/role";
257    /// Index of an export inside `lifetime.ephemeral.exports`.
258    /// Stamped on the corresponding tatara-export-worker Job + its
259    /// receipt ConfigMap so the reconciler can correlate them
260    /// without re-parsing the spec JSON.
261    pub const EXPORT_INDEX: &str = "tatara.pleme.io/export-index";
262    /// Label / annotation key stamping which
263    /// `RoutingSpec.hostnames` entry a routing edge (Ingress /
264    /// DNSEndpoint) belongs to. Value is the entry's `app` slot;
265    /// a `label`-selector on this key slices every emitted edge
266    /// for a given `app` regardless of hostname form. Peer to
267    /// [`ROUTING_FORM`] on the routing-axis pair.
268    pub const APP: &str = "tatara.pleme.io/app";
269    /// Label / annotation key stamping the routing form
270    /// (`"stable"` | `"instance"`) on every emitted routing edge.
271    /// Value is a [`crate::routing::RoutingForm`] wire-form string;
272    /// consumers filtering the two forms compare to
273    /// [`RoutingForm::as_str`][crate::routing::RoutingForm::as_str],
274    /// never to a bare literal.
275    pub const ROUTING_FORM: &str = "tatara.pleme.io/routing-form";
276}
277
278/// Standard finalizer for the Process reconciler.
279pub const PROCESS_FINALIZER: &str = "tatara.pleme.io/process-finalizer";
280
281/// Shared schemars helpers — emit OpenAPI schemas Kubernetes accepts.
282/// Free-form `serde_json::Value` fields default to an *empty* schema
283/// in schemars, which the K8s API server rejects with "type: Required
284/// value: must not be empty for specified object fields". The typed
285/// workaround is to emit `{type: object, x-kubernetes-preserve-unknown-
286/// fields: true}` — same shape kube-rs's own helpers produce.
287pub mod schema_helpers {
288    use schemars::{gen::SchemaGenerator, schema::Schema};
289    /// Schema for a free-form JSON object field. Apply via
290    /// `#[schemars(schema_with = "tatara_process::schema_helpers::preserve_unknown_object")]`
291    /// on any `serde_json::Value` / `BTreeMap<String, serde_json::Value>`
292    /// field exposed through a CRD.
293    pub fn preserve_unknown_object(_g: &mut SchemaGenerator) -> Schema {
294        serde_json::from_value(serde_json::json!({
295            "type": "object",
296            "x-kubernetes-preserve-unknown-fields": true
297        }))
298        .expect("static JSON literal parses as Schema")
299    }
300}
301
302#[cfg(test)]
303mod owner_reference_tests {
304    //! Pin the `owner_reference_json` composer at fail-before-pass-
305    //! after granularity. Every shape a pre-lift caller hand-authored
306    //! is re-asserted here so a regression that inlined any of the
307    //! six slots at a call site (breaking the primitive's role as
308    //! the ONE source of truth) fails HERE at the composer's shipped-
309    //! shape pin rather than as silent drift between the pre-lift
310    //! `render.rs` / `edges.rs` / `ssapply.rs` sites (which pre-lift
311    //! already carried TWO different `apiVersion` spellings — a
312    //! composed `format!("{}/{}", GROUP, VERSION)` at two sites and
313    //! the frozen literal `"tatara.pleme.io/v1alpha1"` at the third).
314    use super::{
315        api_version, owner_reference_json, owner_references_json, GROUP, PROCESS_KIND, VERSION,
316    };
317    use serde_json::json;
318
319    #[test]
320    fn api_version_composes_group_and_version() {
321        // Any bump of GROUP or VERSION lands at ONE composer.
322        assert_eq!(api_version(), format!("{GROUP}/{VERSION}"));
323    }
324
325    #[test]
326    fn api_version_byte_matches_wire_form_pre_lift() {
327        // Byte-identity pin: the frozen wire-form literal
328        // `"tatara.pleme.io/v1alpha1"` that `ssapply.rs::
329        // build_owner_reference` hand-wrote pre-lift must equal the
330        // composed shape now sourced through the ONE owner. A
331        // future VERSION bump that missed this test would land as
332        // an operator-visible reference-mismatch after apply.
333        assert_eq!(api_version(), "tatara.pleme.io/v1alpha1");
334    }
335
336    #[test]
337    fn process_kind_is_process_literal() {
338        // Symbol-vs-string pin: any consumer that hand-wrote `"Process"`
339        // pre-lift routes through this const post-lift.
340        assert_eq!(PROCESS_KIND, "Process");
341    }
342
343    #[test]
344    fn owner_reference_json_has_all_six_slots_present() {
345        let v = owner_reference_json("my-process", "abc-uid");
346        let obj = v.as_object().expect("owner reference is a JSON object");
347        for k in [
348            "apiVersion",
349            "kind",
350            "name",
351            "uid",
352            "controller",
353            "blockOwnerDeletion",
354        ] {
355            assert!(obj.contains_key(k), "missing owner-reference slot: {k}");
356        }
357        assert_eq!(obj.len(), 6, "owner reference must have exactly 6 slots");
358    }
359
360    #[test]
361    fn owner_reference_json_apiversion_routes_through_api_version_owner() {
362        let v = owner_reference_json("x", "y");
363        assert_eq!(v["apiVersion"], api_version());
364    }
365
366    #[test]
367    fn owner_reference_json_kind_routes_through_process_kind_const() {
368        let v = owner_reference_json("x", "y");
369        assert_eq!(v["kind"], PROCESS_KIND);
370    }
371
372    #[test]
373    fn owner_reference_json_stamps_supplied_name_and_uid() {
374        let v = owner_reference_json("some-name", "some-uid");
375        assert_eq!(v["name"], "some-name");
376        assert_eq!(v["uid"], "some-uid");
377    }
378
379    #[test]
380    fn owner_reference_json_controller_and_block_owner_deletion_are_true() {
381        // These are structural — a Process-owned resource always
382        // has a controlling reference that cascade-deletes with
383        // the owner. A regression that flipped either boolean
384        // would silently detach every emitted resource.
385        let v = owner_reference_json("x", "y");
386        assert_eq!(v["controller"], true);
387        assert_eq!(v["blockOwnerDeletion"], true);
388    }
389
390    #[test]
391    fn owner_reference_json_matches_hand_authored_shape_pre_lift() {
392        // Byte-shape pin against the exact `json!({…})` incantation
393        // every pre-lift call site restated. A regression that
394        // reordered a slot, dropped one, or added a seventh here
395        // surfaces at THIS pin rather than as a subtle SSA-apply
396        // failure downstream when the K8s API server rejects the
397        // OwnerReference on schema mismatch.
398        let via_owner = owner_reference_json("p", "u");
399        let hand_authored = json!({
400            "apiVersion": "tatara.pleme.io/v1alpha1",
401            "kind": "Process",
402            "name": "p",
403            "uid": "u",
404            "controller": true,
405            "blockOwnerDeletion": true,
406        });
407        assert_eq!(via_owner, hand_authored);
408    }
409
410    #[test]
411    fn owner_reference_json_preserves_empty_name_and_uid_bytewise() {
412        // The primitive does not guard against empty inputs — its
413        // callers pre-lift did the empty-check upstream (both the
414        // `edges.rs::build_owner_refs` and `render.rs::one_export_job`
415        // sites gated on `!uid.is_empty()` before calling this composer,
416        // and both now route through `owner_references_json` below;
417        // `ssapply.rs::build_owner_reference` unwraps a required
418        // `metadata.uid` via anyhow). The scalar composer owns
419        // shape composition, not admission control; a downstream
420        // rename that wants strict input validation lands as a
421        // peer, not a change to the composer's contract.
422        let v = owner_reference_json("", "");
423        assert_eq!(v["name"], "");
424        assert_eq!(v["uid"], "");
425    }
426
427    // ─── owner_references_json substrate pins ────────────────────────
428    //
429    // The 3-line `let mut owner_refs = vec![]; if !uid.is_empty()
430    // { owner_refs.push(owner_reference_json(name, uid)); }` gate was
431    // hand-authored at TWO sites in `tatara-reconciler`
432    // (`edges::build_owner_refs` + `render::one_export_job`) before
433    // this primitive existed, each restating the same optional-uid
434    // posture that emits `[]` when the caller lacks a K8s-assigned
435    // uid to point owners at. These pins bind the primitive at
436    // fail-before-pass-after granularity so a regression that
437    // inlined an owner reference for an empty uid — silently
438    // detaching the resource from cascade-delete — surfaces HERE
439    // rather than as an operator-visible ownerless resource after
440    // apply, and a regression that added an owner reference of the
441    // wrong SHAPE (a peer of `owner_reference_json` that swapped a
442    // slot) surfaces via the composed-shape pin below rather than
443    // as silent drift at every downstream emit site.
444
445    #[test]
446    fn owner_references_json_emits_single_entry_when_uid_present() {
447        // The primary shape: a caller with a materialized uid gets
448        // exactly one owner reference back — the pre-lift 3-line
449        // `vec![]` + `push` gate collapses to this ONE call, and
450        // the returned array is a direct-drop `ownerReferences`
451        // slot value at every callsite.
452        let refs = owner_references_json("demo-app", "abc-uid");
453        assert_eq!(refs.len(), 1);
454        assert_eq!(refs[0]["kind"], PROCESS_KIND);
455        assert_eq!(refs[0]["name"], "demo-app");
456        assert_eq!(refs[0]["uid"], "abc-uid");
457        // controller + blockOwnerDeletion routed through the scalar
458        // composer — a regression that hand-composed the vec entry
459        // rather than delegating would flip one of these booleans.
460        assert_eq!(refs[0]["controller"], true);
461        assert_eq!(refs[0]["blockOwnerDeletion"], true);
462    }
463
464    #[test]
465    fn owner_references_json_emits_empty_when_uid_empty() {
466        // The load-bearing gate — a pre-metadata Process (fixtured in
467        // tests, or caught mid-Forking) has no admissible owner
468        // reference to point at. Post-lift the gate lives at ONE
469        // primitive so every emit site stamps `[]` uniformly rather
470        // than one site accidentally emitting a placeholder-uid
471        // owner reference the K8s GC would quietly detach from
472        // cascade-delete.
473        let refs = owner_references_json("demo-app", "");
474        assert!(
475            refs.is_empty(),
476            "empty uid must produce zero owner references, not a placeholder-uid entry"
477        );
478    }
479
480    #[test]
481    fn owner_references_json_gates_on_uid_not_name() {
482        // The gate axis is `uid`, not `name` — a Process with a
483        // non-empty name but no uid still emits `[]` (the pre-metadata
484        // shape), while a Process with a non-empty uid emits ONE
485        // entry even when the name slot is empty (matching the
486        // scalar composer's admission-control-free contract). Pin
487        // both cross-diagonal combinations so a regression that
488        // swapped the gate axis surfaces HERE rather than at every
489        // downstream owner-refs consumer.
490        assert!(
491            owner_references_json("has-name", "").is_empty(),
492            "empty uid gates to []; name presence is irrelevant"
493        );
494        let refs = owner_references_json("", "has-uid");
495        assert_eq!(
496            refs.len(),
497            1,
498            "empty name but present uid still emits one entry (name is not the gate)"
499        );
500        assert_eq!(refs[0]["name"], "");
501        assert_eq!(refs[0]["uid"], "has-uid");
502    }
503
504    #[test]
505    fn owner_references_json_matches_hand_authored_pre_lift_bytewise() {
506        // Byte-identical parity with the exact pre-lift 3-line
507        // `let mut owner_refs = vec![]; if !uid.is_empty() {
508        // owner_refs.push(owner_reference_json(name, uid)); }` gate
509        // across the two axis combinations every callsite plausibly
510        // encounters. A regression that reordered the two branches,
511        // dropped the gate, or reshaped the vec composition surfaces
512        // HERE rather than at every downstream `ownerReferences`
513        // slot pinned across `edges.rs` + `render.rs` tests.
514        for (name, uid) in [
515            ("demo-app", "uid-abc"),
516            ("demo-app", ""),
517            ("", "uid-abc"),
518            ("", ""),
519        ] {
520            let via_primitive = owner_references_json(name, uid);
521
522            // The pre-lift 3-line block, byte-for-byte.
523            let mut hand_authored: Vec<serde_json::Value> = vec![];
524            if !uid.is_empty() {
525                hand_authored.push(owner_reference_json(name, uid));
526            }
527
528            assert_eq!(
529                via_primitive, hand_authored,
530                "owner_references_json must be byte-identical to the pre-lift 3-line gate on ({name:?}, {uid:?})"
531            );
532        }
533    }
534
535    #[test]
536    fn owner_references_json_interpolates_cleanly_as_owner_refs_slot() {
537        // Both callsites drop the returned vec directly under a
538        // `"ownerReferences"` key inside a `json!({...})` block. Pin
539        // the interop shape: a JSON-macro-wrapped Value carries the
540        // primitive's output as a JSON array with the exact 6-slot
541        // entries at each index. A regression that returned a
542        // non-array (e.g. a single Value on the one-entry path,
543        // requiring per-site vec-wrapping) surfaces HERE rather than
544        // as a broken `metadata.ownerReferences` slot on every
545        // emitted Ingress / DNSEndpoint / export Job.
546        let refs = owner_references_json("demo-app", "abc-uid");
547        let wrapped = json!({
548            "metadata": {
549                "name": "resource",
550                "ownerReferences": refs,
551            },
552        });
553        let owner_refs = &wrapped["metadata"]["ownerReferences"];
554        assert!(
555            owner_refs.is_array(),
556            "ownerReferences must land as a JSON array"
557        );
558        assert_eq!(owner_refs.as_array().unwrap().len(), 1);
559        assert_eq!(owner_refs[0]["kind"], PROCESS_KIND);
560
561        // And the empty-uid path lands as an EMPTY array, not a
562        // missing key or a null — matches the K8s API server's
563        // expectation that the slot is either an array of entries
564        // or absent, never a null.
565        let empty_refs = owner_references_json("demo-app", "");
566        let wrapped_empty = json!({
567            "metadata": {
568                "name": "resource",
569                "ownerReferences": empty_refs,
570            },
571        });
572        let owner_refs_empty = &wrapped_empty["metadata"]["ownerReferences"];
573        assert!(owner_refs_empty.is_array());
574        assert!(owner_refs_empty.as_array().unwrap().is_empty());
575    }
576}
577
578// ── Lisp → ProcessSpec compile bridge ──────────────────────────────────
579//
580// `(defpoint NAME :k v …)` compiles to a `NamedDefinition<ProcessSpec>`.
581// The derive on ProcessSpec handles every field via the serde Deserialize
582// fallthrough — no hand-rolled keyword parsing needed.
583
584/// A named ProcessSpec as produced by `compile_source`.
585pub type Definition = tatara_lisp::NamedDefinition<crate::crd::ProcessSpec>;
586
587/// Compile a Lisp source string into a list of named ProcessSpecs.
588/// Each top-level `(defpoint NAME …)` form becomes one `Definition`.
589pub fn compile_source(src: &str) -> tatara_lisp::Result<Vec<Definition>> {
590    tatara_lisp::compile_named::<crate::crd::ProcessSpec>(src)
591}
592
593/// Register every domain owned by this crate with the global Lisp
594/// dispatcher. Call once per binary, typically near the top of `main`.
595/// After this call, `tatara_lisp::domain::lookup("defpoint")` and
596/// `lookup("defephemeral")` both resolve to the right typed compiler.
597///
598/// Idempotent — registering the same type twice is a no-op.
599pub fn register_all() {
600    tatara_lisp::domain::register::<crate::crd::ProcessSpec>();
601    tatara_lisp::domain::register::<crate::ephemeral::EphemeralSpec>();
602}
603
604#[cfg(test)]
605mod compile_tests {
606    use super::compile_source;
607    use crate::classification::{ConvergencePointType, SubstrateType};
608    use crate::compliance::VerificationPhase;
609    use crate::spec::MustReachPhase;
610
611    /// The full derive-powered pipeline — no hand-rolled parsing anywhere.
612    /// Every field travels: Lisp → Sexp → serde_json → typed ProcessSpec.
613    #[test]
614    fn full_processspec_round_trip_via_derive() {
615        let src = r#"
616            (defpoint observability-stack
617              :identity       (:parent "seph.1")
618              :classification (:point-type Gate
619                               :substrate Observability
620                               :horizon (:kind Bounded)
621                               :calm Monotone
622                               :data-classification Internal)
623              :intent         (:nix (:flake-ref "github:pleme-io/k8s"
624                                     :attribute "observability"
625                                     :attic-cache "main"))
626              :boundary       (:postconditions
627                                 ((:kind KustomizationHealthy
628                                   :params (:name "observability-stack"
629                                            :namespace "flux-system"))
630                                  (:kind PromQL
631                                   :params (:query "up == 1")))
632                               :timeout "15m")
633              :compliance     (:baseline "fedramp-moderate"
634                               :bindings ((:framework "nist-800-53"
635                                           :control-id "SC-7"
636                                           :phase AtBoundary)))
637              :depends-on     ((:name "secret-injection" :must-reach Attested))
638              :signals        (:sigterm-grace-seconds 480
639                               :sighup-strategy Reconverge))
640        "#;
641        let defs = compile_source(src).expect("compile");
642        assert_eq!(defs.len(), 1);
643        let d = &defs[0];
644        assert_eq!(d.name, "observability-stack");
645
646        // identity
647        assert_eq!(d.spec.identity.parent.as_deref(), Some("seph.1"));
648
649        // classification (enums deserialized via symbol → string)
650        assert_eq!(d.spec.classification.point_type, ConvergencePointType::Gate);
651        assert_eq!(
652            d.spec.classification.substrate,
653            SubstrateType::Observability
654        );
655
656        // intent (tagged-union with one of four options)
657        let nix = d.spec.intent.nix.as_ref().expect("nix intent");
658        assert_eq!(nix.flake_ref, "github:pleme-io/k8s");
659        assert_eq!(nix.attribute, "observability");
660        assert_eq!(nix.attic_cache.as_deref(), Some("main"));
661
662        // boundary (Vec<nested struct with params object>)
663        assert_eq!(d.spec.boundary.postconditions.len(), 2);
664        assert_eq!(d.spec.boundary.timeout.as_deref(), Some("15m"));
665
666        // compliance (Vec<binding with enum phase>)
667        assert_eq!(
668            d.spec.compliance.baseline.as_deref(),
669            Some("fedramp-moderate")
670        );
671        assert_eq!(d.spec.compliance.bindings.len(), 1);
672        assert_eq!(
673            d.spec.compliance.bindings[0].phase,
674            VerificationPhase::AtBoundary
675        );
676
677        // depends_on (Vec<struct with enum>)
678        assert_eq!(d.spec.depends_on.len(), 1);
679        assert_eq!(d.spec.depends_on[0].must_reach, MustReachPhase::Attested);
680
681        // signals (numeric + enum defaults)
682        assert_eq!(d.spec.signals.sigterm_grace_seconds, 480);
683    }
684
685    #[test]
686    fn missing_required_field_errors() {
687        // `:classification` has no #[serde(default)] — omit it and compile must fail.
688        let src = r#"(defpoint x :intent (:nix (:flake-ref "f" :attribute "a")))"#;
689        assert!(compile_source(src).is_err());
690    }
691
692    #[test]
693    fn serde_default_fields_are_optional() {
694        // Omit every #[serde(default)] field — compile must succeed because
695        // the derive honors serde defaults.
696        let src = r#"
697            (defpoint x
698              :classification (:point-type Transform :substrate Compute)
699              :intent (:flux (:git-repository "g" :path ".")))
700        "#;
701        let defs = compile_source(src).expect("compile");
702        assert_eq!(defs.len(), 1);
703        let d = &defs[0];
704        assert!(d.spec.depends_on.is_empty());
705        assert!(d.spec.boundary.postconditions.is_empty());
706        assert!(d.spec.compliance.bindings.is_empty());
707        assert!(!d.spec.suspended);
708        // Lifetime defaults to Permanent (no variant set, resolver still works).
709        assert!(d.spec.lifetime.is_default());
710        assert!(!d.spec.lifetime.is_ephemeral());
711    }
712
713    /// Registering all process-owned domains is idempotent and resolves
714    /// both `defpoint` (ProcessSpec) and `defephemeral` (EphemeralSpec).
715    #[test]
716    fn register_all_resolves_defpoint_and_defephemeral() {
717        use tatara_lisp::domain::lookup;
718        super::register_all();
719        super::register_all(); // idempotent
720        assert!(lookup("defpoint").is_some(), "defpoint must resolve");
721        assert!(
722            lookup("defephemeral").is_some(),
723            "defephemeral must resolve"
724        );
725    }
726
727    /// End-to-end: a `(defpoint …)` form may carry the full ephemeral
728    /// shape directly — `:intent (:aplicacao …)` + `:lifetime (:ephemeral …)`.
729    /// This is what the `(defephemeral …)` sugar lowers to via `From`.
730    #[test]
731    fn defpoint_with_aplicacao_intent_and_ephemeral_lifetime() {
732        use crate::intent::IntentVariant;
733        use crate::lifetime::{LifetimeVariant, TeardownPolicy};
734        let src = r#"
735            (defpoint closed-loop-attest
736              :classification (:point-type Gate :substrate Compute)
737              :intent (:aplicacao
738                        (:chart-ref "oci://ghcr.io/pleme-io/charts/lareira-demo-app"
739                         :version "0.5.5"
740                         :profile "all-in-one"
741                         :values-overlay (:cluster (:name "ephemeral-test-01"))
742                         :target-namespace "demo-test"))
743              :boundary (:postconditions
744                          ((:kind HelmReleaseReleased
745                            :params (:name "demo-app-consolidated"
746                                     :namespace "demo-test"))
747                           (:kind ClosedLoopAuth
748                            :params (:issuer (:service "demo-app-issuer" :port 8080)
749                                     :consumer (:service "demo-app-gateway" :port 8000)
750                                     :probeImage "ghcr.io/pleme-io/closed-loop-probe:0.1.0"))))
751              :lifetime (:ephemeral (:ttl "1h"
752                                     :teardown-policy OnAttested
753                                     :max-concurrent 1)))
754        "#;
755        let defs = compile_source(src).expect("compile");
756        assert_eq!(defs.len(), 1);
757        let d = &defs[0];
758
759        // Aplicacao intent landed.
760        match d.spec.intent.variant().unwrap() {
761            IntentVariant::Aplicacao(a) => {
762                assert_eq!(a.profile, "all-in-one");
763                assert_eq!(a.version, "0.5.5");
764                assert_eq!(a.target_namespace.as_deref(), Some("demo-test"));
765                assert_eq!(a.values_overlay["cluster"]["name"], "ephemeral-test-01");
766            }
767            other => panic!("expected Aplicacao, got {other:?}"),
768        }
769
770        // Ephemeral lifetime landed with the right teardown policy.
771        match d.spec.lifetime.variant().unwrap() {
772            LifetimeVariant::Ephemeral(e) => {
773                assert_eq!(e.ttl, "1h");
774                assert_eq!(e.teardown_policy, TeardownPolicy::OnAttested);
775                assert_eq!(e.max_concurrent, 1);
776            }
777            other => panic!("expected ephemeral, got {other:?}"),
778        }
779
780        // Two typed postconditions including ClosedLoopAuth.
781        assert_eq!(d.spec.boundary.postconditions.len(), 2);
782        assert_eq!(
783            d.spec.boundary.postconditions[1].kind,
784            crate::boundary::ConditionKind::ClosedLoopAuth
785        );
786    }
787}