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