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