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