tatara_process/lib.rs
1//! Process CRD — the K8s-as-Unix-processes wire format.
2//!
3//! A `Process` is one element of the tatara convergence lattice.
4//! Clusters, HelmReleases, migrations, tests — all are Processes.
5//! The reconciliation loop *is* Unix: fork → exec → wait → exit → reap.
6
7pub mod allocation;
8pub mod attestation;
9pub mod boundary;
10pub mod classification;
11pub mod compliance;
12pub mod crd;
13pub mod encapsulates;
14pub mod env;
15pub mod ephemeral;
16pub mod export;
17pub mod flux_resource;
18pub mod hostname;
19pub mod identity;
20pub mod intent;
21pub mod k8s_builtin_resource;
22pub mod k8s_object_ref;
23pub mod k8s_wire_identity;
24pub mod lifetime;
25pub mod lifetime_clock;
26pub mod matrix;
27pub mod phase;
28pub mod pool;
29pub mod receipt;
30pub mod routing;
31pub mod routing_edge_resource;
32pub mod signal;
33pub mod spec;
34pub mod status;
35pub mod table;
36pub mod tagged_union;
37
38pub mod prelude {
39 pub use crate::allocation::{
40 AllocationCondition, AllocationPhase, AllocationSpec, AllocationStatus,
41 EphemeralAllocation, Requestor,
42 };
43 pub use crate::attestation::ProcessAttestation;
44 pub use crate::boundary::{Boundary, Condition, ConditionKind, UnknownConditionKind};
45 pub use crate::classification::{
46 Arity, CalmClassification, Classification, ConvergencePointType, DataClassification,
47 Horizon, HorizonKind, OptimizationDirection, SubstrateType, UnknownCalmClassification,
48 UnknownConvergencePointType, UnknownDataClassification, UnknownHorizonKind,
49 UnknownOptimizationDirection, UnknownSubstrateType,
50 };
51 pub use crate::compliance::{
52 ComplianceBinding, ComplianceSpec, UnknownVerificationPhase, VerificationPhase,
53 };
54 pub use crate::crd::{Process, ProcessSpec, ProcessStatus};
55 pub use crate::encapsulates::{
56 BareWorkload, EncapsulatesSpec, EncapsulationKind, EncapsulationKindError,
57 EncapsulationKindVariant, EncapsulationMode, EncapsulationTarget, ExistingHelmRelease,
58 ExistingKustomization, UnknownEncapsulationMode, UnknownEncapsulationTarget,
59 };
60 pub use crate::ephemeral::{compile_ephemeral_source, EphemeralSpec};
61 pub use crate::export::{
62 ArtifactError, ArtifactKind, ArtifactSource, ArtifactVariant, ChannelError, ChannelKind,
63 ChannelVariant, ExportSpec, ExportTrigger, HttpEventChannel, NatsSubjectChannel,
64 ProcessSnapshotSource, ReceiptsSource, ReportFormat, ReportPayloadShape, RunMarkerSource,
65 StdoutChannel, TestReportSource, UnknownArtifactKind, UnknownChannelKind,
66 UnknownExportTrigger, UnknownReportFormat, VectorChannel, DEFAULT_NATS_URL,
67 DEFAULT_VECTOR_INGEST,
68 };
69 pub use crate::flux_resource::FluxResource;
70 pub use crate::hostname::{
71 ephemeral_id_from_spec, fmt_fqdn, fmt_fqdn_stable, resolve_ephemeral_id, HostnameError,
72 EPHEMERAL_ID_HASH_LEN,
73 };
74 pub use crate::identity::{content_hash, derive_identity, format_process_address, Identity};
75 pub use crate::intent::{
76 AplicacaoIntent, ContainerIntent, FluxIntent, GuestIntent, HelmLifecyclePolicy,
77 HelmRemediationPolicy, Intent, IntentError, IntentKind, IntentVariant, LispIntent,
78 NixIntent, UnknownWorkloadKind, WorkloadKind, FLUX_HELM_DEFAULT_INTERVAL,
79 HELM_LIFECYCLE_DEFAULT_RETRIES, HELM_LIFECYCLE_DEFAULT_TIMEOUT,
80 };
81 pub use crate::k8s_builtin_resource::K8sBuiltinResource;
82 pub use crate::k8s_object_ref::K8sObjectRef;
83 pub use crate::k8s_wire_identity::K8sWireIdentity;
84 pub use crate::lifetime::{
85 EphemeralLifetime, Lifetime, LifetimeError, LifetimeKind, LifetimeVariant,
86 PermanentLifetime, TeardownPolicy, UnknownTeardownPolicy,
87 };
88 pub use crate::lifetime_clock::{
89 evaluate as lifetime_clock_evaluate, AutoTerminate, AutoTerminateKind, TerminateReason,
90 TerminateReasonKind, UnknownAutoTerminateKind, UnknownTerminateReasonKind,
91 };
92 pub use crate::matrix::{
93 compile_env_matrix_source, EnvMatrixSpec, MatrixAxis, MatrixBudget, NamedEphemeral,
94 SelectStrategy, SelectStrategyKind, UnknownSelectStrategyKind,
95 };
96 pub use crate::phase::{ProcessPhase, UnknownPhase};
97 pub use crate::pool::{
98 AllocationRef, EphemeralPool, MatchKey, MemberState, PoolCondition, PoolMember, PoolPhase,
99 PoolSelector, PoolSpec, PoolStatus, ReplacementPolicy, ReturnPolicy, UnknownMemberState,
100 UnknownPoolPhase, UnknownReplacementPolicy,
101 };
102 pub use crate::qualified_process_ref;
103 pub use crate::receipt::{
104 default_receipt_config_map_name, ReceiptEnvelope, ReceiptError, ReceiptKind,
105 RECEIPT_CM_SUFFIX, RECEIPT_VERSION,
106 };
107 pub use crate::routing::{RoutingBackend, RoutingForm, RoutingHostname, RoutingSpec};
108 pub use crate::routing_edge_resource::RoutingEdgeResource;
109 pub use crate::signal::{ProcessSignal, SighupStrategy, UnknownSighupStrategy};
110 pub use crate::spec::{
111 DependsOn, IdentitySpec, MustReachPhase, SignalPolicy, UnknownMustReachPhase,
112 };
113 pub use crate::status::{
114 BoundaryStatus, CheckedCondition, ComplianceStatus, FluxResourceRef, ProcessCondition,
115 RenderedResourceCoords,
116 };
117 pub use crate::table::{
118 ClaimRecord, ProcessEntry, ProcessTable, ProcessTableSpec, ProcessTableStatus,
119 };
120 pub use crate::{Annotated, DeletionTombstoned, NamespacedApiCoordinates};
121}
122
123/// CRD API group for every tatara CRD.
124pub const GROUP: &str = "tatara.pleme.io";
125/// CRD version for this module.
126pub const VERSION: &str = "v1alpha1";
127/// Kind spelling of the tatara Process CRD as it appears in a K8s
128/// [`OwnerReference.kind`][ownref] field. Peer to [`GROUP`] +
129/// [`VERSION`] — centralizes the ONE literal every SSA-time
130/// re-injection helper pre-lift restated by hand across
131/// `tatara-reconciler` (`render.rs`, `edges.rs`, `ssapply.rs`).
132///
133/// [ownref]: https://kubernetes.io/docs/concepts/overview/working-with-objects/owners-dependents/
134pub const PROCESS_KIND: &str = "Process";
135
136/// Canonical `<GROUP>/<VERSION>` as an owned `String` — the ONE
137/// K8s `apiVersion` shape every tatara CRD stamps. Composed from
138/// [`GROUP`] + [`VERSION`] so a bump of either constant lands here
139/// exactly once; pre-lift, two `tatara-reconciler` sites hand-wrote
140/// `format!("{}/{}", tatara_process::GROUP, tatara_process::VERSION)`
141/// while a third inlined the literal `"tatara.pleme.io/v1alpha1"`,
142/// opening a silent drift path if `VERSION` ever advances past
143/// `v1alpha1`.
144pub fn api_version() -> String {
145 format!("{GROUP}/{VERSION}")
146}
147
148/// Substrate-primitive composer for the canonical
149/// **namespace-qualified process reference** — the `<ns>/<name>`
150/// string every consumer that grepped, keyed, or annotated a
151/// Process by "which cluster location owns it" hand-authored as
152/// `format!("{ns}/{name}")` at scattered sites across the workspace.
153/// Lifted onto `tatara-process` (from its prior home at
154/// `tatara_reconciler::ssapply::qualified_process_ref`) so callers
155/// BELOW the reconciler layer — `tatara-export-worker` (which does
156/// NOT depend on `tatara-reconciler`) and `tatara-pool-reconciler` —
157/// reach the SAME composer the reconciler-side sites do, closing
158/// the previously-open substrate corner where a downstream consumer
159/// re-authored the shape by hand rather than routing through the
160/// ONE primitive.
161///
162/// The `<ns>/<name>` shape is the workspace-wide convention for
163/// "how to name a namespaced K8s resource in a single string" — the
164/// same shape the K8s API server itself uses in
165/// [`OwnerReference`][ownref] pretty-printing, in the `holder` slot of
166/// [`crate::table::ClaimRecord`], and in the `tatara.pleme.io/process`
167/// annotation every reconciler-emitted resource carries. Callers
168/// with a live [`crate::prelude::Process`] compose through
169/// [`crate::prelude::Process::coordinates_or_defaults`] +
170/// [`Self`] (this function); callers with bare
171/// `(ns: &str, name: &str)` params (CLI-arg driven binaries,
172/// `metadata`-agnostic composers) call this directly.
173///
174/// The 2-arg signature encodes the invariant "the qualified
175/// reference is EXACTLY `<ns>/<name>`, in that order, joined by a
176/// single `/` separator" at the type level — a caller cannot
177/// accidentally swap the two axes (which would produce `<name>/<ns>`
178/// and silently break every downstream grep) nor omit either half,
179/// the way a pre-lift hand-authored `format!("{name}/{ns}")` or
180/// `format!("{ns}-{name}")` typo would.
181///
182/// A future change to the reference shape — a `<ns>/<name>@<gen>`
183/// multi-generation variant for attestation grepping, a
184/// `<cluster>/<ns>/<name>` cross-cluster form, a normalization
185/// (case-fold, unicode-safe collation) that must apply everywhere —
186/// lands at ONE substrate function here and every downstream
187/// composer (annotation seed, ProcessTable claim key, label
188/// selector, owner metadata, export-worker run-id fallback,
189/// receipt-owner filter) inherits the upgrade mechanically.
190///
191/// Theory anchor: THEORY.md §VI.1 (generation over composition —
192/// the `<ns>/<name>` shape recurred at hand-authored sites past the
193/// ★★ PRIME-DIRECTIVE ≥ 2 duplication trigger, and is lifted onto
194/// the ONE workspace-wide owner here). THEORY.md §II.1 invariant 5
195/// (composition preserves proofs — a regression that swapped the
196/// two axes or the separator at ONE site surfaces at
197/// [`qualified_process_ref_tests::qualified_process_ref_joins_ns_and_name_with_slash`]
198/// rather than as silent drift at every downstream annotation seed
199/// / claim key / label selector / run-id / receipt-owner filter).
200///
201/// [ownref]: https://kubernetes.io/docs/concepts/overview/working-with-objects/owners-dependents/
202#[must_use]
203pub fn qualified_process_ref(ns: &str, name: &str) -> String {
204 format!("{ns}/{name}")
205}
206
207/// Build a Kubernetes [`OwnerReference`][ownref] JSON blob pointing
208/// at a Process (`kind = `[`PROCESS_KIND`], `apiVersion = `
209/// [`api_version`]) with `controller: true` +
210/// `blockOwnerDeletion: true` — the exact 6-slot shape every SSA
211/// re-injection site pre-lift restated three times across
212/// `tatara-reconciler` (`render.rs::owner_refs` for export-Job
213/// owners, `edges.rs::build_owner_refs` for Ingress + DNSEndpoint
214/// owners, `ssapply.rs::build_owner_reference` for the injected
215/// owner-ref stamped on every applied `DynamicObject`). Callers
216/// with a live `Process` value read `metadata.{name,uid}` and pass
217/// them through as `&str`.
218///
219/// The 6-slot shape is fixed (`controller` + `blockOwnerDeletion`
220/// both `true`); a Process-owned resource that wants a non-
221/// controller reference doesn't belong on this owner and can build
222/// its own `json!` inline — this primitive is the composer for the
223/// canonical "Process controls this resource, cascade-delete on
224/// GC" shape, not a general OwnerReference builder.
225///
226/// [ownref]: https://kubernetes.io/docs/concepts/overview/working-with-objects/owners-dependents/
227pub fn owner_reference_json(name: &str, uid: &str) -> serde_json::Value {
228 serde_json::json!({
229 "apiVersion": api_version(),
230 "kind": PROCESS_KIND,
231 "name": name,
232 "uid": uid,
233 "controller": true,
234 "blockOwnerDeletion": true,
235 })
236}
237
238/// Substrate-primitive builder for a Process-owned resource's
239/// **`metadata.ownerReferences` array** — the empty-uid-gated,
240/// single-entry `Vec<Value>` every emit site that lacks a fully
241/// materialized [`crate::prelude::Process`] (i.e. every site that
242/// works from a bare `(name, uid)` pair rather than routing through
243/// [`ssapply::build_owner_reference`](../tatara_reconciler/ssapply/fn.build_owner_reference.html)'s
244/// anyhow-guarded unwrap) hand-composed by wrapping
245/// [`owner_reference_json`] in a `Vec::new()` + `is_empty` gate on
246/// the `uid` slot.
247///
248/// The `uid.is_empty()` gate encodes the invariant every caller
249/// already enforced: a Process pre-metadata (fixtured in tests, or
250/// caught mid-Forking before the API server has stamped a `uid`) has
251/// no admissible owner reference to point at, so the emit site
252/// stamps `metadata.ownerReferences: []` rather than an
253/// owner-referenceless resource pointing at a placeholder uid the K8s
254/// GC would silently ignore. Post-lift the gate lives at ONE
255/// primitive so a regression that inlined an owner reference for
256/// an empty uid — which the API server accepts and quietly detaches
257/// from cascade-delete — surfaces at THIS primitive's pin rather
258/// than as an operator-visible ownerless resource after apply.
259///
260/// Pre-lift the 3-line `let mut owner_refs = vec![]; if
261/// !uid.is_empty() { owner_refs.push(owner_reference_json(name,
262/// uid)); }` incantation was hand-authored at TWO sites past the
263/// ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold in
264/// `tatara-reconciler`, each restating the same gated composition:
265/// * `edges::build_owner_refs` — the shared owner-refs builder both
266/// `IngressEdge` + `DnsEndpointEdge` route through, sourcing
267/// `(process_name, process_uid)` from the [`crate::edges::EdgeContext`].
268/// * `render::one_export_job` — the export Job's owner-refs seed,
269/// sourcing `(name, uid)` from the [`crate::prelude::Process`]
270/// `render_export_jobs` threaded in.
271///
272/// Post-lift both callsites read `owner_references_json(name, uid)`.
273/// A future addition — e.g. a second owner-reference slot naming a
274/// controlling ProcessTable entry, a policy that stamps a stale-uid
275/// warning annotation before returning empty, or a normalization
276/// that strips a cluster-prefix off the uid — lands at ONE
277/// substrate function here and every emit site inherits the upgrade
278/// mechanically. The [`ssapply::build_owner_reference`] path (which
279/// works from a materialized [`crate::prelude::Process`] and errors
280/// on absent `metadata.uid`) is a peer, not a lift candidate: its
281/// contract is "the K8s API server assigned a uid, so refuse to
282/// SSA-apply resources whose owner cannot be materialized", while
283/// this primitive's contract is "the caller has an optional-uid
284/// posture; emit `[]` when the uid is absent". The two shapes
285/// partition the input space at the "is the enclosing scope
286/// obligated to produce a materialized Process reference" axis.
287///
288/// The 2-arg `(&str, &str)` signature accepts both the
289/// `EdgeContext`-sourced `(&str, &str)` slice shape and the
290/// `render_export_jobs`-owned `(name: &str, uid: &str)` local shape
291/// without widening — matches every current callsite.
292pub fn owner_references_json(name: &str, uid: &str) -> Vec<serde_json::Value> {
293 if uid.is_empty() {
294 vec![]
295 } else {
296 vec![owner_reference_json(name, uid)]
297 }
298}
299
300/// Substrate-primitive trait for the **`Api::namespaced`-shaped
301/// coordinate extraction** every tatara-CRD reconciler restated by
302/// hand at its top-level `reconcile` dispatcher: pull owned `String`
303/// forms of `metadata.namespace` and `metadata.name` and refuse to
304/// substitute a workspace-wide default for either slot, because the
305/// caller is about to feed the pair positionally into
306/// `Api::namespaced(client, &ns)` + `Api::patch(&name, …)` and the
307/// K8s API server refuses an empty-string name / namespace path
308/// segment.
309///
310/// Pre-lift the 5-line `.metadata.<slot>.clone().ok_or_else(||
311/// anyhow!("<Kind> has no metadata.<slot>"))?` chain (paired at both
312/// slots inside every controller's `reconcile_inner`) was hand-
313/// authored at TWO sites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication
314/// threshold in `tatara-pool-reconciler`, each restating the SAME
315/// (`namespace` errors, then `name` errors, both owned `String`)
316/// contract on a different CRD:
317/// * `controller_pool::reconcile_inner` — the pool reconciler's
318/// top-level `Pool has no metadata.{namespace,name}` gate,
319/// funneling every subsequent `Api::namespaced` + `Api::patch` call
320/// through the extracted `(ns, name)` pair.
321/// * `controller_allocation::reconcile_inner` — the allocation
322/// reconciler's peer gate on `EphemeralAllocation`, funneling the
323/// `Api::namespaced` + `Api::patch_status` calls that follow.
324///
325/// Both sites walked the SAME 5-line paired chain and both wanted the
326/// `(String, String)` form the primitive returns — because the
327/// produced `ns` outlives the source-object borrow (it feeds
328/// `Api::namespaced(client, &ns)` and later log-line interpolations
329/// across a stretch of `.await` points) and the `name` similarly
330/// threads through `Api::patch(&name, …)` calls downstream. Post-lift
331/// each callsite reads `pool.owned_coordinates_required()?` /
332/// `alloc.owned_coordinates_required()?` and the produced tuple
333/// destructures into the same downstream slots unchanged.
334///
335/// The blanket impl over `kube::Resource<DynamicType = ()>` (which
336/// every `#[derive(CustomResource)]`-generated tatara CRD satisfies)
337/// closes the substrate corner ONCE for the entire workspace: adding
338/// a third or fourth CRD in a peer crate — a routing-edge object, a
339/// receipt registry — inherits the extractor for free at its own
340/// `reconcile_inner` dispatcher with zero per-CRD lift work. This is
341/// the direction the CSE Compounding Directive names by
342/// "solve once, load-bearing fixes only": the primitive lands once
343/// and every downstream controller pattern-matches into it without
344/// re-authoring the chain.
345///
346/// Peer to [`crate::prelude::Process::owned_coordinates_or_err`] on
347/// the (`Process`-specific × namespace-required) axis pair — the two
348/// primitives partition the workspace's owned-form coordinate
349/// extraction on the `namespace-required` axis and cover the
350/// per-CRD needs they were opened for:
351///
352/// * ns-defaulted, name-required, `Process`-inherent →
353/// [`crate::prelude::Process::owned_coordinates_or_err`]
354/// (`tatara-reconciler`'s `phase_machine` / `signals` callers —
355/// consumers whose downstream tolerates the workspace's
356/// [`crate::prelude::Process::DEFAULT_NAMESPACE`] substitute for a
357/// `Process` fixtured pre-namespace-defaulting).
358/// * ns-required + name-required, blanket over every CRD → **this
359/// method** (`tatara-pool-reconciler`'s pool + allocation reconciler
360/// callers — consumers whose downstream refuses BOTH substitutions
361/// because the `Api::namespaced` dispatcher expects a real path
362/// segment on each axis and the enclosing controller is not
363/// authored to run against a namespace-less pool / allocation).
364///
365/// The error strings are shaped as `"{Kind} has no metadata.{slot}"`
366/// with `{Kind}` pulled positionally from `Self::kind(&())` (the
367/// kube-rs canonical CRD kind — `"EphemeralPool"` / `"EphemeralAllocation"`
368/// — which matches `kubectl get ephemeralpools|ephemeralallocations`
369/// output verbatim rather than the pre-lift `"Pool"` / `"Allocation"`
370/// short-forms every callsite hard-coded by hand). Routing the type
371/// name through `Self::kind` closes the drift path where a future
372/// CRD rename or a copy-paste consumer inherited the wrong short-
373/// form; the K8s-kind spelling is the ONE canonical name every
374/// operator-facing surface (kubectl output, RBAC subject strings,
375/// audit-log entries) already uses, so a log-line consumer greppping
376/// for either kind hits the primitive's canonical spelling directly.
377///
378/// A future normalization step (a per-CRD namespace canonicalization
379/// pass — case-fold, unicode-safe path-segment validation, a shared
380/// [`crate::prelude::Process::DEFAULT_NAMESPACE`]-aware fallback
381/// mode gated by an argument) lands at ONE substrate trait method
382/// here and every downstream reconciler picks up the upgrade
383/// mechanically — no per-callsite hand-edit at `controller_pool` /
384/// `controller_allocation` / any future CRD's `reconcile_inner`.
385///
386/// Theory anchor: THEORY.md §VI.1 (generation over composition —
387/// the paired 5-line `.metadata.<slot>.clone().ok_or_else` chain
388/// recurred at two hand-authored sites past the ★★ PRIME-DIRECTIVE
389/// ≥ 2 duplication trigger, and is lifted onto ONE trait method
390/// here). THEORY.md §II.1 invariant 5 (composition preserves
391/// proofs — the pins bind the missing-namespace corner, the
392/// missing-name corner, the missing-both corner (namespace error
393/// wins), the both-slots-present happy path, AND the
394/// `Self::kind`-driven error-string spelling per CRD, so a
395/// regression that reordered the two `ok_or_else` gates or drifted
396/// the error prefix surfaces at `tests::owned_coordinates_required_*`
397/// rather than as silent operator-facing skew between the two
398/// reconcilers' top-level error-message shapes).
399pub trait NamespacedApiCoordinates: kube::Resource<DynamicType = ()> {
400 /// Extract the K8s API path coordinates as owned `String`s,
401 /// erroring with a `Self::kind`-prefixed message when either
402 /// slot is absent. See the trait-level docs for the axis-family
403 /// context, peer primitives, and future-normalization anchor.
404 fn owned_coordinates_required(&self) -> anyhow::Result<(String, String)> {
405 let meta = self.meta();
406 let ns = meta
407 .namespace
408 .clone()
409 .ok_or_else(|| anyhow::anyhow!("{} has no metadata.namespace", Self::kind(&())))?;
410 let name = meta
411 .name
412 .clone()
413 .ok_or_else(|| anyhow::anyhow!("{} has no metadata.name", Self::kind(&())))?;
414 Ok((ns, name))
415 }
416}
417
418impl<T> NamespacedApiCoordinates for T where T: kube::Resource<DynamicType = ()> {}
419
420/// Substrate-primitive trait for the **deletion-tombstone presence
421/// probe** every tatara CRD reconciler restated as
422/// `.metadata.deletion_timestamp.is_some()` on the K8s-API-server-
423/// stamped `metadata.deletionTimestamp` slot: a `true` reading means
424/// the API server has accepted a DELETE and finalizers are draining
425/// (the object is still live but the controller must move into its
426/// SIGTERM cascade / DELETE-skip branch), while a `false` reading
427/// means no delete is in flight.
428///
429/// Pre-lift the ONE-line `.metadata.deletion_timestamp.is_some()`
430/// chain was hand-authored across every tatara-process CRD in
431/// consumer crates and independently re-authored as byte-identical
432/// inherent methods on [`crate::prelude::Process`] +
433/// [`crate::prelude::EphemeralPool`], with the sister CRD
434/// [`crate::prelude::EphemeralAllocation`] still on the raw chain in
435/// `tatara-pool-reconciler::allocation_decide::AllocationConvergenceCtx::observe`.
436/// That's TWO byte-identical inherent implementations past the ★★
437/// PRIME-DIRECTIVE ≥ 2 duplication threshold on the substrate side
438/// PLUS the hand-authored chain on the third CRD — three surfaces
439/// spelling the SAME projection, each with the same drift risk (a
440/// stale-tombstone grace-period gate, a paused-controller
441/// canonicalization, a cross-cluster clock-skew guard would have to
442/// land at every surface plus stay coherent).
443///
444/// Post-lift the substrate owns the probe at ONE trait method with a
445/// blanket impl over every `kube::Resource<DynamicType = ()>`, so:
446/// * [`crate::prelude::EphemeralAllocation`] inherits the probe for
447/// free — its `allocation_decide.rs` hand-authored chain routes
448/// through `alloc.is_being_deleted()` post-lift, closing the
449/// third-CRD gap noted in the [`crate::prelude::EphemeralPool::is_being_deleted`]
450/// commit body (`7f8f104`).
451/// * Any future tatara CRD (a routing-edge object, a receipt
452/// registry, a fleet-wide claim registry) inherits the probe at
453/// its own `reconcile_inner` dispatcher with zero per-CRD lift
454/// work — the same solve-once discipline
455/// [`NamespacedApiCoordinates`] established for the paired
456/// coordinate extractor.
457///
458/// The two existing inherent methods
459/// ([`crate::prelude::Process::is_being_deleted`] +
460/// [`crate::prelude::EphemeralPool::is_being_deleted`]) are peers
461/// rather than lift casualties: Rust method resolution prefers the
462/// inherent over the trait's blanket, so every existing callsite
463/// keeps hitting the same code path. The trait's blanket impl
464/// closes the substrate corner for CRDs WITHOUT the inherent — the
465/// coherence tests pin that the trait and the two inherents produce
466/// byte-identical results across every corner of the (missing,
467/// present) input matrix, so a future rewrite that consolidates
468/// onto the trait doesn't skew any consumer.
469///
470/// Return-form axis: `bool` matches the copy-form discipline of the
471/// two inherent peers and of [`crate::prelude::Process::observed_phase`]
472/// — the underlying wire-format slot is an `Option<Time>` carrying
473/// only presence information at this axis (the RFC-3339 timestamp
474/// payload itself is not what the callers read; all just probe
475/// presence to detect the tombstone-stamped state).
476///
477/// A future normalization step (a per-tombstone staleness gate
478/// returning `false` for a tombstone older than the reconciler's
479/// grace-period budget, a paused-controller tombstone
480/// canonicalization, a cross-cluster tombstone-observation clock
481/// skew guard) lands at ONE substrate trait method here — the two
482/// inherent forwarders inherit the upgrade mechanically if they are
483/// rewired to `<Self as DeletionTombstoned>::is_being_deleted(self)`
484/// as a follow-up sweep, and every downstream consumer that already
485/// routes through this trait picks it up without a per-callsite
486/// hand-edit.
487///
488/// Theory anchor: THEORY.md §VI.1 (generation over composition —
489/// the `.metadata.deletion_timestamp.is_some()` projection recurred
490/// as TWO byte-identical inherent implementations on
491/// [`crate::prelude::Process`] + [`crate::prelude::EphemeralPool`]
492/// past the ★★ PRIME-DIRECTIVE ≥ 2 duplication trigger and is
493/// lifted onto ONE trait method here). THEORY.md §II.1 invariant 5
494/// (composition preserves proofs — the pins bind the missing-
495/// tombstone corner + the present-tombstone corner + the copy-form
496/// `bool` return + the byte-identical parity with the pre-lift
497/// `.is_some()` chain + cross-CRD coherence with both inherent
498/// forwarders on the SAME `Process` / `EphemeralPool` value, so a
499/// regression that skewed either surface surfaces at
500/// `deletion_tombstoned_tests::*` rather than as silent operator-
501/// facing skew between the top-level dispatcher's SIGTERM preempt,
502/// the SIGTERM cascade's child-fan-out DELETE-skip, the pool
503/// reconciler's Drain gate, and the allocation reconciler's release
504/// short-circuit on three sibling CRDs.
505pub trait DeletionTombstoned: kube::Resource<DynamicType = ()> {
506 /// True iff the K8s API server has stamped `metadata.deletionTimestamp`
507 /// on this resource — a DELETE is in flight and finalizers are
508 /// draining. See the trait-level docs for the axis-family context,
509 /// peer inherent methods, and future-normalization anchor.
510 fn is_being_deleted(&self) -> bool {
511 self.meta().deletion_timestamp.is_some()
512 }
513}
514
515impl<T> DeletionTombstoned for T where T: kube::Resource<DynamicType = ()> {}
516
517/// Substrate-primitive trait for the ONE **borrow-form annotation
518/// lookup** every tatara CRD reconciler restated as the 3-line
519/// `.metadata.annotations.as_ref().and_then(|m| m.get(key)).map(String::as_str)`
520/// chain (or a `.cloned()` / `.cloned().unwrap_or_default()` variant
521/// of the same shape) on the K8s `metadata.annotations` map: returns
522/// `Some(&str)` iff the annotations block is present AND the key is
523/// present inside it; both missing corners collapse to `None`.
524///
525/// Peer to [`DeletionTombstoned`] + [`NamespacedApiCoordinates`] on
526/// the substrate-primitive-trait axis (kube-Resource blanket impls
527/// over `DynamicType = ()`), and peer to the pre-existing
528/// [`crate::prelude::Process::annotation`] inherent forwarder on the
529/// axis of "one annotation-lookup shape shared across every kube
530/// resource, tatara CRD or K8s built-in". The inherent stays as a
531/// peer — Rust method resolution prefers an inherent over a trait's
532/// blanket impl, so the three consumers already routed through
533/// `Process::annotation`
534/// (`tatara-reconciler::signals::ingest`,
535/// `tatara-reconciler::phase_machine::released_from_annotation`,
536/// `tatara-pool-reconciler::controller_pool::process_belongs_to_pool`)
537/// keep hitting the byte-identical code path — and the trait's
538/// blanket impl closes the substrate corner for kube resources
539/// WITHOUT the inherent: post-lift the hand-authored
540/// `.metadata.annotations.as_ref().and_then(|m| m.get(KEY))...` chain
541/// in `tatara-export-worker::main` (on `k8s_openapi`'s `ConfigMap`,
542/// which has no tatara-owned inherent) routes through the trait at
543/// `cm.annotation(KEY)`, and any future `EphemeralPool` /
544/// `EphemeralAllocation` (or new tatara CRD) consumer that needs an
545/// annotation lookup inherits the primitive for free — the same
546/// solve-once discipline the two peer traits already established.
547///
548/// Return-form axis: `Option<&str>` matches the borrow-first
549/// discipline of the peer metadata primitives
550/// ([`crate::prelude::Process::namespace_or_default`],
551/// [`crate::prelude::Process::name_or_placeholder`],
552/// [`crate::prelude::Process::coordinates_or_none`], and the inherent
553/// [`crate::prelude::Process::annotation`] this trait mirrors). The
554/// two corners the pre-lift chain swallowed (missing `annotations`
555/// map, missing key inside the map) BOTH collapse to `None` so
556/// `.is_some()` / `if let Some(_)` / `Option::map` behave identically
557/// on a resource whose annotations block is `None` and on one whose
558/// annotations block is populated but omits the key — matching what
559/// the pre-lift `.and_then(...)` chain produced.
560///
561/// A future normalization step (a key-canonicalization pass, a
562/// case-fold lookup, a per-key alias table for renamed annotations
563/// across API versions, a per-namespace override substrate) lands at
564/// ONE trait method here and every downstream consumer — the four
565/// current sites plus every future CRD reconciler that inherits the
566/// blanket impl — picks up the upgrade mechanically. If the inherent
567/// is ever rewired to `<Self as Annotated>::annotation(self, key)`
568/// as a follow-up sweep, the three inherent-preferred callsites
569/// automatically inherit any trait-level upgrade too.
570///
571/// Theory anchor: THEORY.md §VI.1 (generation over composition —
572/// the annotation-lookup shape recurred as ONE inherent forwarder on
573/// `Process` PLUS a hand-authored chain on `ConfigMap` past the
574/// ★★ PRIME-DIRECTIVE ≥ 2 duplication trigger, and is lifted onto
575/// ONE trait method here). THEORY.md §II.1 invariant 5 (composition
576/// preserves proofs — the pins bind the missing-annotations corner +
577/// the missing-key corner + the borrow-form `&str` lifetime + the
578/// byte-identical parity with the pre-lift 3-line chain + the
579/// cross-primitive coherence with `Process::annotation` on the SAME
580/// `Process` value, so a regression that skewed either surface
581/// surfaces at `annotated_tests::*` rather than as silent operator-
582/// facing skew between the SIGNAL / RELEASED_FROM / POOL annotation
583/// readers on Process and the receipts-owner filter on ConfigMap).
584pub trait Annotated: kube::Resource<DynamicType = ()> {
585 /// Borrow one key from `metadata.annotations`. See the trait-level
586 /// docs for the axis-family context, peer inherent method, and
587 /// future-normalization anchor.
588 fn annotation(&self, key: &str) -> Option<&str> {
589 self.meta()
590 .annotations
591 .as_ref()
592 .and_then(|m| m.get(key))
593 .map(String::as_str)
594 }
595}
596
597impl<T> Annotated for T where T: kube::Resource<DynamicType = ()> {}
598
599/// Annotation keys the reconciler reads/writes on owned FluxCD resources.
600pub mod annotations {
601 pub const MANAGED_BY: &str = "tatara.pleme.io/managed-by";
602 pub const PROCESS: &str = "tatara.pleme.io/process";
603 pub const PID: &str = "tatara.pleme.io/pid";
604 pub const CONTENT_HASH: &str = "tatara.pleme.io/content-hash";
605 pub const ATTESTATION_ROOT: &str = "tatara.pleme.io/attestation-root";
606 pub const GENERATION: &str = "tatara.pleme.io/generation";
607 pub const SIGNAL: &str = "tatara.pleme.io/signal";
608 /// Stamped by the reconciler when transitioning into `Releasing`
609 /// — records which terminal-reached gate the Process came from
610 /// (`Attested` or `Failed`) so `handle_releasing` can pick the
611 /// matching `ExportTrigger` set + the correct post-Releasing
612 /// destination (`Exiting` from Attested, `Zombie` from Failed).
613 pub const RELEASED_FROM: &str = "tatara.pleme.io/released-from";
614 /// Labels the export-worker Jobs the reconciler emits during
615 /// `Releasing`. Selector: `tatara.pleme.io/role=export`.
616 pub const ROLE: &str = "tatara.pleme.io/role";
617 /// Index of an export inside `lifetime.ephemeral.exports`.
618 /// Stamped on the corresponding tatara-export-worker Job + its
619 /// receipt ConfigMap so the reconciler can correlate them
620 /// without re-parsing the spec JSON.
621 pub const EXPORT_INDEX: &str = "tatara.pleme.io/export-index";
622 /// Label / annotation key stamping which
623 /// `RoutingSpec.hostnames` entry a routing edge (Ingress /
624 /// DNSEndpoint) belongs to. Value is the entry's `app` slot;
625 /// a `label`-selector on this key slices every emitted edge
626 /// for a given `app` regardless of hostname form. Peer to
627 /// [`ROUTING_FORM`] on the routing-axis pair.
628 pub const APP: &str = "tatara.pleme.io/app";
629 /// Label / annotation key stamping the routing form
630 /// (`"stable"` | `"instance"`) on every emitted routing edge.
631 /// Value is a [`crate::routing::RoutingForm`] wire-form string;
632 /// consumers filtering the two forms compare to
633 /// [`RoutingForm::as_str`][crate::routing::RoutingForm::as_str],
634 /// never to a bare literal.
635 pub const ROUTING_FORM: &str = "tatara.pleme.io/routing-form";
636}
637
638/// Standard finalizer for the Process reconciler.
639pub const PROCESS_FINALIZER: &str = "tatara.pleme.io/process-finalizer";
640
641/// Shared schemars helpers — emit OpenAPI schemas Kubernetes accepts.
642/// Free-form `serde_json::Value` fields default to an *empty* schema
643/// in schemars, which the K8s API server rejects with "type: Required
644/// value: must not be empty for specified object fields". The typed
645/// workaround is to emit `{type: object, x-kubernetes-preserve-unknown-
646/// fields: true}` — same shape kube-rs's own helpers produce.
647pub mod schema_helpers {
648 use schemars::{gen::SchemaGenerator, schema::Schema};
649 /// Schema for a free-form JSON object field. Apply via
650 /// `#[schemars(schema_with = "tatara_process::schema_helpers::preserve_unknown_object")]`
651 /// on any `serde_json::Value` / `BTreeMap<String, serde_json::Value>`
652 /// field exposed through a CRD.
653 pub fn preserve_unknown_object(_g: &mut SchemaGenerator) -> Schema {
654 serde_json::from_value(serde_json::json!({
655 "type": "object",
656 "x-kubernetes-preserve-unknown-fields": true
657 }))
658 .expect("static JSON literal parses as Schema")
659 }
660}
661
662#[cfg(test)]
663mod owner_reference_tests {
664 //! Pin the `owner_reference_json` composer at fail-before-pass-
665 //! after granularity. Every shape a pre-lift caller hand-authored
666 //! is re-asserted here so a regression that inlined any of the
667 //! six slots at a call site (breaking the primitive's role as
668 //! the ONE source of truth) fails HERE at the composer's shipped-
669 //! shape pin rather than as silent drift between the pre-lift
670 //! `render.rs` / `edges.rs` / `ssapply.rs` sites (which pre-lift
671 //! already carried TWO different `apiVersion` spellings — a
672 //! composed `format!("{}/{}", GROUP, VERSION)` at two sites and
673 //! the frozen literal `"tatara.pleme.io/v1alpha1"` at the third).
674 use super::{
675 api_version, owner_reference_json, owner_references_json, GROUP, PROCESS_KIND, VERSION,
676 };
677 use serde_json::json;
678
679 #[test]
680 fn api_version_composes_group_and_version() {
681 // Any bump of GROUP or VERSION lands at ONE composer.
682 assert_eq!(api_version(), format!("{GROUP}/{VERSION}"));
683 }
684
685 #[test]
686 fn api_version_byte_matches_wire_form_pre_lift() {
687 // Byte-identity pin: the frozen wire-form literal
688 // `"tatara.pleme.io/v1alpha1"` that `ssapply.rs::
689 // build_owner_reference` hand-wrote pre-lift must equal the
690 // composed shape now sourced through the ONE owner. A
691 // future VERSION bump that missed this test would land as
692 // an operator-visible reference-mismatch after apply.
693 assert_eq!(api_version(), "tatara.pleme.io/v1alpha1");
694 }
695
696 #[test]
697 fn process_kind_is_process_literal() {
698 // Symbol-vs-string pin: any consumer that hand-wrote `"Process"`
699 // pre-lift routes through this const post-lift.
700 assert_eq!(PROCESS_KIND, "Process");
701 }
702
703 #[test]
704 fn owner_reference_json_has_all_six_slots_present() {
705 let v = owner_reference_json("my-process", "abc-uid");
706 let obj = v.as_object().expect("owner reference is a JSON object");
707 for k in [
708 "apiVersion",
709 "kind",
710 "name",
711 "uid",
712 "controller",
713 "blockOwnerDeletion",
714 ] {
715 assert!(obj.contains_key(k), "missing owner-reference slot: {k}");
716 }
717 assert_eq!(obj.len(), 6, "owner reference must have exactly 6 slots");
718 }
719
720 #[test]
721 fn owner_reference_json_apiversion_routes_through_api_version_owner() {
722 let v = owner_reference_json("x", "y");
723 assert_eq!(v["apiVersion"], api_version());
724 }
725
726 #[test]
727 fn owner_reference_json_kind_routes_through_process_kind_const() {
728 let v = owner_reference_json("x", "y");
729 assert_eq!(v["kind"], PROCESS_KIND);
730 }
731
732 #[test]
733 fn owner_reference_json_stamps_supplied_name_and_uid() {
734 let v = owner_reference_json("some-name", "some-uid");
735 assert_eq!(v["name"], "some-name");
736 assert_eq!(v["uid"], "some-uid");
737 }
738
739 #[test]
740 fn owner_reference_json_controller_and_block_owner_deletion_are_true() {
741 // These are structural — a Process-owned resource always
742 // has a controlling reference that cascade-deletes with
743 // the owner. A regression that flipped either boolean
744 // would silently detach every emitted resource.
745 let v = owner_reference_json("x", "y");
746 assert_eq!(v["controller"], true);
747 assert_eq!(v["blockOwnerDeletion"], true);
748 }
749
750 #[test]
751 fn owner_reference_json_matches_hand_authored_shape_pre_lift() {
752 // Byte-shape pin against the exact `json!({…})` incantation
753 // every pre-lift call site restated. A regression that
754 // reordered a slot, dropped one, or added a seventh here
755 // surfaces at THIS pin rather than as a subtle SSA-apply
756 // failure downstream when the K8s API server rejects the
757 // OwnerReference on schema mismatch.
758 let via_owner = owner_reference_json("p", "u");
759 let hand_authored = json!({
760 "apiVersion": "tatara.pleme.io/v1alpha1",
761 "kind": "Process",
762 "name": "p",
763 "uid": "u",
764 "controller": true,
765 "blockOwnerDeletion": true,
766 });
767 assert_eq!(via_owner, hand_authored);
768 }
769
770 #[test]
771 fn owner_reference_json_preserves_empty_name_and_uid_bytewise() {
772 // The primitive does not guard against empty inputs — its
773 // callers pre-lift did the empty-check upstream (both the
774 // `edges.rs::build_owner_refs` and `render.rs::one_export_job`
775 // sites gated on `!uid.is_empty()` before calling this composer,
776 // and both now route through `owner_references_json` below;
777 // `ssapply.rs::build_owner_reference` unwraps a required
778 // `metadata.uid` via anyhow). The scalar composer owns
779 // shape composition, not admission control; a downstream
780 // rename that wants strict input validation lands as a
781 // peer, not a change to the composer's contract.
782 let v = owner_reference_json("", "");
783 assert_eq!(v["name"], "");
784 assert_eq!(v["uid"], "");
785 }
786
787 // ─── owner_references_json substrate pins ────────────────────────
788 //
789 // The 3-line `let mut owner_refs = vec![]; if !uid.is_empty()
790 // { owner_refs.push(owner_reference_json(name, uid)); }` gate was
791 // hand-authored at TWO sites in `tatara-reconciler`
792 // (`edges::build_owner_refs` + `render::one_export_job`) before
793 // this primitive existed, each restating the same optional-uid
794 // posture that emits `[]` when the caller lacks a K8s-assigned
795 // uid to point owners at. These pins bind the primitive at
796 // fail-before-pass-after granularity so a regression that
797 // inlined an owner reference for an empty uid — silently
798 // detaching the resource from cascade-delete — surfaces HERE
799 // rather than as an operator-visible ownerless resource after
800 // apply, and a regression that added an owner reference of the
801 // wrong SHAPE (a peer of `owner_reference_json` that swapped a
802 // slot) surfaces via the composed-shape pin below rather than
803 // as silent drift at every downstream emit site.
804
805 #[test]
806 fn owner_references_json_emits_single_entry_when_uid_present() {
807 // The primary shape: a caller with a materialized uid gets
808 // exactly one owner reference back — the pre-lift 3-line
809 // `vec![]` + `push` gate collapses to this ONE call, and
810 // the returned array is a direct-drop `ownerReferences`
811 // slot value at every callsite.
812 let refs = owner_references_json("demo-app", "abc-uid");
813 assert_eq!(refs.len(), 1);
814 assert_eq!(refs[0]["kind"], PROCESS_KIND);
815 assert_eq!(refs[0]["name"], "demo-app");
816 assert_eq!(refs[0]["uid"], "abc-uid");
817 // controller + blockOwnerDeletion routed through the scalar
818 // composer — a regression that hand-composed the vec entry
819 // rather than delegating would flip one of these booleans.
820 assert_eq!(refs[0]["controller"], true);
821 assert_eq!(refs[0]["blockOwnerDeletion"], true);
822 }
823
824 #[test]
825 fn owner_references_json_emits_empty_when_uid_empty() {
826 // The load-bearing gate — a pre-metadata Process (fixtured in
827 // tests, or caught mid-Forking) has no admissible owner
828 // reference to point at. Post-lift the gate lives at ONE
829 // primitive so every emit site stamps `[]` uniformly rather
830 // than one site accidentally emitting a placeholder-uid
831 // owner reference the K8s GC would quietly detach from
832 // cascade-delete.
833 let refs = owner_references_json("demo-app", "");
834 assert!(
835 refs.is_empty(),
836 "empty uid must produce zero owner references, not a placeholder-uid entry"
837 );
838 }
839
840 #[test]
841 fn owner_references_json_gates_on_uid_not_name() {
842 // The gate axis is `uid`, not `name` — a Process with a
843 // non-empty name but no uid still emits `[]` (the pre-metadata
844 // shape), while a Process with a non-empty uid emits ONE
845 // entry even when the name slot is empty (matching the
846 // scalar composer's admission-control-free contract). Pin
847 // both cross-diagonal combinations so a regression that
848 // swapped the gate axis surfaces HERE rather than at every
849 // downstream owner-refs consumer.
850 assert!(
851 owner_references_json("has-name", "").is_empty(),
852 "empty uid gates to []; name presence is irrelevant"
853 );
854 let refs = owner_references_json("", "has-uid");
855 assert_eq!(
856 refs.len(),
857 1,
858 "empty name but present uid still emits one entry (name is not the gate)"
859 );
860 assert_eq!(refs[0]["name"], "");
861 assert_eq!(refs[0]["uid"], "has-uid");
862 }
863
864 #[test]
865 fn owner_references_json_matches_hand_authored_pre_lift_bytewise() {
866 // Byte-identical parity with the exact pre-lift 3-line
867 // `let mut owner_refs = vec![]; if !uid.is_empty() {
868 // owner_refs.push(owner_reference_json(name, uid)); }` gate
869 // across the two axis combinations every callsite plausibly
870 // encounters. A regression that reordered the two branches,
871 // dropped the gate, or reshaped the vec composition surfaces
872 // HERE rather than at every downstream `ownerReferences`
873 // slot pinned across `edges.rs` + `render.rs` tests.
874 for (name, uid) in [
875 ("demo-app", "uid-abc"),
876 ("demo-app", ""),
877 ("", "uid-abc"),
878 ("", ""),
879 ] {
880 let via_primitive = owner_references_json(name, uid);
881
882 // The pre-lift 3-line block, byte-for-byte.
883 let mut hand_authored: Vec<serde_json::Value> = vec![];
884 if !uid.is_empty() {
885 hand_authored.push(owner_reference_json(name, uid));
886 }
887
888 assert_eq!(
889 via_primitive, hand_authored,
890 "owner_references_json must be byte-identical to the pre-lift 3-line gate on ({name:?}, {uid:?})"
891 );
892 }
893 }
894
895 #[test]
896 fn owner_references_json_interpolates_cleanly_as_owner_refs_slot() {
897 // Both callsites drop the returned vec directly under a
898 // `"ownerReferences"` key inside a `json!({...})` block. Pin
899 // the interop shape: a JSON-macro-wrapped Value carries the
900 // primitive's output as a JSON array with the exact 6-slot
901 // entries at each index. A regression that returned a
902 // non-array (e.g. a single Value on the one-entry path,
903 // requiring per-site vec-wrapping) surfaces HERE rather than
904 // as a broken `metadata.ownerReferences` slot on every
905 // emitted Ingress / DNSEndpoint / export Job.
906 let refs = owner_references_json("demo-app", "abc-uid");
907 let wrapped = json!({
908 "metadata": {
909 "name": "resource",
910 "ownerReferences": refs,
911 },
912 });
913 let owner_refs = &wrapped["metadata"]["ownerReferences"];
914 assert!(
915 owner_refs.is_array(),
916 "ownerReferences must land as a JSON array"
917 );
918 assert_eq!(owner_refs.as_array().unwrap().len(), 1);
919 assert_eq!(owner_refs[0]["kind"], PROCESS_KIND);
920
921 // And the empty-uid path lands as an EMPTY array, not a
922 // missing key or a null — matches the K8s API server's
923 // expectation that the slot is either an array of entries
924 // or absent, never a null.
925 let empty_refs = owner_references_json("demo-app", "");
926 let wrapped_empty = json!({
927 "metadata": {
928 "name": "resource",
929 "ownerReferences": empty_refs,
930 },
931 });
932 let owner_refs_empty = &wrapped_empty["metadata"]["ownerReferences"];
933 assert!(owner_refs_empty.is_array());
934 assert!(owner_refs_empty.as_array().unwrap().is_empty());
935 }
936}
937
938#[cfg(test)]
939mod qualified_process_ref_tests {
940 //! Pin the [`qualified_process_ref`] composer at fail-before-
941 //! pass-after granularity. The `<ns>/<name>` shape is the
942 //! workspace-wide convention for a namespaced K8s resource
943 //! reference — every downstream grep (the reconciler's
944 //! `tatara.pleme.io/process` annotation reader, the
945 //! [`crate::table::ClaimRecord.holder`] slot, the
946 //! export-worker's receipt-owner filter, the reconciler's
947 //! `PROCESS=<ref>` label-selector composer) depends on the
948 //! two axes landing in `(ns, name)` order joined by a single
949 //! `/` separator. A regression that swapped the axes, dropped
950 //! either half, or renormalized the input surfaces HERE rather
951 //! than as silent operator-facing drift at every downstream
952 //! consumer.
953 use super::qualified_process_ref;
954
955 #[test]
956 fn qualified_process_ref_joins_ns_and_name_with_slash() {
957 // The invariant every downstream consumer composes against:
958 // the qualified reference is EXACTLY `<ns>/<name>`, in that
959 // order, joined by a single `/`.
960 assert_eq!(
961 qualified_process_ref("demo-ns", "ephemeral-demo"),
962 "demo-ns/ephemeral-demo",
963 );
964 }
965
966 #[test]
967 fn qualified_process_ref_binds_positional_slots_by_axis_order() {
968 // Positional pin — a copy-paste that swapped the two `&str`
969 // arguments (both mechanically interchangeable at the type
970 // level) would silently produce `<name>/<ns>` and break every
971 // downstream grep keyed on the reference shape. Distinct
972 // input slot values so a swap surfaces as an equality
973 // failure rather than accidental identity.
974 let out = qualified_process_ref("first-slot-ns", "second-slot-name");
975 assert!(
976 out.starts_with("first-slot-ns/"),
977 "position 0 must be the namespace slot: got {out}"
978 );
979 assert!(
980 out.ends_with("/second-slot-name"),
981 "position 1 must be the name slot: got {out}"
982 );
983 }
984
985 #[test]
986 fn qualified_process_ref_accepts_string_deref_and_str_slice_shapes() {
987 // Consumers split across two callsite shapes: owned
988 // `String` locals (via deref coercion), bare `&str` slices,
989 // and mixed provenance. Every shape must ride cleanly
990 // through the same 2-arg signature — matches every current
991 // pre-lift caller in `tatara-export-worker` (CLI-arg driven
992 // owned strings + `&str` from a struct field) and in
993 // `tatara-reconciler` (owned locals + function-param
994 // slices).
995 let owned_ns = String::from("owned-ns");
996 let owned_name = String::from("owned-app");
997 let borrowed_ns: &str = "borrowed-ns";
998 let borrowed_name: &str = "borrowed-app";
999 assert_eq!(
1000 qualified_process_ref(&owned_ns, &owned_name),
1001 "owned-ns/owned-app",
1002 );
1003 assert_eq!(
1004 qualified_process_ref(borrowed_ns, borrowed_name),
1005 "borrowed-ns/borrowed-app",
1006 );
1007 assert_eq!(
1008 qualified_process_ref(&owned_ns, borrowed_name),
1009 "owned-ns/borrowed-app",
1010 );
1011 }
1012
1013 #[test]
1014 fn qualified_process_ref_rides_edge_case_axis_shapes() {
1015 // The composer shapes the two axes as arbitrary strings —
1016 // no length/character validation happens at the composer,
1017 // so any shape a Process's `metadata.namespace` /
1018 // `metadata.name` can hold rides through unchanged. Pin
1019 // the empty-string cases (unnamed process pre-metadata,
1020 // cluster-scoped `namespace = ""` fallback), and the
1021 // whitespace-and-slash-in-name pathological case (a
1022 // regression that URL-escaped or path-normalized the input
1023 // at this primitive would silently break every downstream
1024 // grep).
1025 assert_eq!(qualified_process_ref("", ""), "/");
1026 assert_eq!(qualified_process_ref("default", ""), "default/");
1027 assert_eq!(qualified_process_ref("", "orphan"), "/orphan");
1028 assert_eq!(
1029 qualified_process_ref("weird ns", "with/slash"),
1030 "weird ns/with/slash",
1031 );
1032 }
1033
1034 #[test]
1035 fn qualified_process_ref_composes_from_process_coordinates_or_defaults() {
1036 // The primary Process-driven callsite: a live
1037 // [`crate::prelude::Process`] with populated metadata
1038 // composes through
1039 // [`crate::prelude::Process::coordinates_or_defaults`] +
1040 // [`qualified_process_ref`]. Pin the composition so a
1041 // regression in either primitive that broke the `(ns,
1042 // name)` positional contract surfaces HERE rather than as
1043 // silent drift at every downstream reconciler / export-
1044 // worker / pool-reconciler consumer.
1045 use crate::classification::{Classification, ConvergencePointType, SubstrateType};
1046 use crate::crd::{Process, ProcessSpec};
1047 let spec = ProcessSpec {
1048 identity: Default::default(),
1049 classification: Classification {
1050 point_type: ConvergencePointType::Gate,
1051 substrate: SubstrateType::Compute,
1052 horizon: Default::default(),
1053 calm: Default::default(),
1054 data_classification: Default::default(),
1055 },
1056 intent: Default::default(),
1057 boundary: Default::default(),
1058 compliance: Default::default(),
1059 depends_on: vec![],
1060 signals: Default::default(),
1061 lifetime: Default::default(),
1062 routing: None,
1063 encapsulates: None,
1064 suspended: false,
1065 };
1066 let mut p = Process::new("ephemeral-demo", spec);
1067 p.metadata.namespace = Some("demo-ns".into());
1068 let (ns, name) = p.coordinates_or_defaults();
1069 assert_eq!(
1070 qualified_process_ref(ns, name),
1071 "demo-ns/ephemeral-demo",
1072 "coordinates_or_defaults + qualified_process_ref must \
1073 compose to the canonical <ns>/<name> shape"
1074 );
1075 }
1076
1077 #[test]
1078 fn qualified_process_ref_matches_hand_authored_pre_lift_bytewise() {
1079 // Byte-identical parity with the exact pre-lift
1080 // `format!("{ns}/{name}")` incantation. A regression that
1081 // reshaped the separator, reordered the axes, or dropped
1082 // either half surfaces HERE rather than at every downstream
1083 // annotation / claim-key / run-id consumer. Sweeps every
1084 // shape combination the pre-lift callers plausibly
1085 // encountered.
1086 for (ns, name) in [
1087 ("demo-ns", "ephemeral-demo"),
1088 ("", ""),
1089 ("default", ""),
1090 ("", "orphan"),
1091 ] {
1092 let via_primitive = qualified_process_ref(ns, name);
1093 let hand_authored = format!("{ns}/{name}");
1094 assert_eq!(
1095 via_primitive, hand_authored,
1096 "qualified_process_ref must be byte-identical to \
1097 the pre-lift `format!(\"{{ns}}/{{name}}\")` \
1098 hand-authored shape on ({ns:?}, {name:?})"
1099 );
1100 }
1101 }
1102}
1103
1104#[cfg(test)]
1105mod namespaced_api_coordinates_tests {
1106 //! Pin the [`NamespacedApiCoordinates`] trait's
1107 //! `owned_coordinates_required` extractor at fail-before-pass-
1108 //! after granularity across every corner of the (namespace slot,
1109 //! name slot) × (present, absent) input matrix, on BOTH CRDs the
1110 //! trait's blanket impl covers today (`EphemeralPool` +
1111 //! `EphemeralAllocation`). A regression that reordered the two
1112 //! `ok_or_else` gates, dropped the `Self::kind` prefix, or drifted
1113 //! the error-string spelling surfaces HERE rather than as silent
1114 //! operator-facing skew between the two reconcilers' top-level
1115 //! error messages.
1116 use super::NamespacedApiCoordinates;
1117 use crate::allocation::{AllocationSpec, EphemeralAllocation, Requestor};
1118 use crate::ephemeral::EphemeralSpec;
1119 use crate::intent::AplicacaoIntent;
1120 use crate::lifetime::TeardownPolicy;
1121 use crate::pool::{EphemeralPool, PoolSelector, PoolSpec, ReturnPolicy};
1122
1123 fn empty_template() -> EphemeralSpec {
1124 // Mirror `tatara-pool-reconciler::router::tests::empty_template`
1125 // — the workspace-wide minimal `EphemeralSpec` fixture the sister
1126 // reconciler tests already use for pool wiring exercised here.
1127 EphemeralSpec {
1128 aplicacao: AplicacaoIntent {
1129 chart_ref: "oci://x".into(),
1130 version: "1".into(),
1131 profile: String::new(),
1132 values_overlay: serde_json::Value::Null,
1133 release_name: None,
1134 target_namespace: None,
1135 install_timeout: None,
1136 },
1137 ttl: "1h".into(),
1138 teardown: TeardownPolicy::Always,
1139 max_concurrent: 0,
1140 postconditions: vec![],
1141 preconditions: vec![],
1142 verify_timeout: None,
1143 classification: None,
1144 parent: None,
1145 exports: vec![],
1146 routing: None,
1147 }
1148 }
1149
1150 fn pool_fixture(name: &str, ns: Option<&str>) -> EphemeralPool {
1151 let spec = PoolSpec {
1152 desired_size: 1,
1153 min_size: 0,
1154 max_size: 0,
1155 return_policy: ReturnPolicy::Replace,
1156 selector: PoolSelector::default(),
1157 template: empty_template(),
1158 free_ttl: "24h".into(),
1159 max_allocation_ttl: "4h".into(),
1160 desired: 0,
1161 replacement_policy: Default::default(),
1162 stable_name_claim: false,
1163 };
1164 let mut p = EphemeralPool::new(name, spec);
1165 p.metadata.namespace = ns.map(str::to_string);
1166 p
1167 }
1168
1169 fn alloc_fixture(name: &str, ns: Option<&str>) -> EphemeralAllocation {
1170 let spec = AllocationSpec {
1171 pool_ref: None,
1172 requestor: Requestor {
1173 kind: "github-pr".into(),
1174 repo: None,
1175 branch: None,
1176 pr_number: None,
1177 sha: None,
1178 pr_labels: vec![],
1179 actor: None,
1180 },
1181 ttl: None,
1182 note: None,
1183 };
1184 let mut a = EphemeralAllocation::new(name, spec);
1185 a.metadata.namespace = ns.map(str::to_string);
1186 a
1187 }
1188
1189 fn nameless_pool(ns: Option<&str>) -> EphemeralPool {
1190 let mut p = pool_fixture("placeholder", ns);
1191 p.metadata.name = None;
1192 p
1193 }
1194
1195 fn nameless_alloc(ns: Option<&str>) -> EphemeralAllocation {
1196 let mut a = alloc_fixture("placeholder", ns);
1197 a.metadata.name = None;
1198 a
1199 }
1200
1201 // ── Happy path: both slots present ─────────────────────────────
1202
1203 #[test]
1204 fn owned_coordinates_required_returns_owned_strings_on_ephemeral_pool_when_both_slots_present()
1205 {
1206 let p = pool_fixture("attest-pool", Some("ephemeral-pools"));
1207 let (ns, name) = p.owned_coordinates_required().unwrap();
1208 assert_eq!(ns, "ephemeral-pools");
1209 assert_eq!(name, "attest-pool");
1210 }
1211
1212 #[test]
1213 fn owned_coordinates_required_returns_owned_strings_on_ephemeral_allocation_when_both_slots_present(
1214 ) {
1215 let a = alloc_fixture("pr-42-demo", Some("ephemeral-pools"));
1216 let (ns, name) = a.owned_coordinates_required().unwrap();
1217 assert_eq!(ns, "ephemeral-pools");
1218 assert_eq!(name, "pr-42-demo");
1219 }
1220
1221 // ── Missing namespace ─────────────────────────────────────────
1222
1223 #[test]
1224 fn owned_coordinates_required_errors_on_ephemeral_pool_missing_namespace() {
1225 let p = pool_fixture("attest-pool", None);
1226 let err = p.owned_coordinates_required().unwrap_err();
1227 assert_eq!(err.to_string(), "EphemeralPool has no metadata.namespace");
1228 }
1229
1230 #[test]
1231 fn owned_coordinates_required_errors_on_ephemeral_allocation_missing_namespace() {
1232 let a = alloc_fixture("pr-42-demo", None);
1233 let err = a.owned_coordinates_required().unwrap_err();
1234 assert_eq!(
1235 err.to_string(),
1236 "EphemeralAllocation has no metadata.namespace"
1237 );
1238 }
1239
1240 // ── Missing name ──────────────────────────────────────────────
1241
1242 #[test]
1243 fn owned_coordinates_required_errors_on_ephemeral_pool_missing_name_when_namespace_present() {
1244 let p = nameless_pool(Some("ephemeral-pools"));
1245 let err = p.owned_coordinates_required().unwrap_err();
1246 assert_eq!(err.to_string(), "EphemeralPool has no metadata.name");
1247 }
1248
1249 #[test]
1250 fn owned_coordinates_required_errors_on_ephemeral_allocation_missing_name_when_namespace_present(
1251 ) {
1252 let a = nameless_alloc(Some("ephemeral-pools"));
1253 let err = a.owned_coordinates_required().unwrap_err();
1254 assert_eq!(err.to_string(), "EphemeralAllocation has no metadata.name");
1255 }
1256
1257 // ── Missing both slots: namespace error wins (pre-lift ordering) ──
1258
1259 #[test]
1260 fn owned_coordinates_required_reports_namespace_first_when_both_slots_absent_on_ephemeral_pool()
1261 {
1262 // Pre-lift both reconcilers spelled the paired chain as the
1263 // namespace ok_or_else THEN the name ok_or_else, so the
1264 // reported error on a fixture missing both slots was always
1265 // the namespace one. Pin that ordering post-lift so a
1266 // regression that swapped the two `ok_or_else` blocks
1267 // surfaces HERE rather than at operator-facing log-line
1268 // grep drift between the two reconcilers.
1269 let p = nameless_pool(None);
1270 let err = p.owned_coordinates_required().unwrap_err();
1271 assert_eq!(err.to_string(), "EphemeralPool has no metadata.namespace");
1272 }
1273
1274 #[test]
1275 fn owned_coordinates_required_reports_namespace_first_when_both_slots_absent_on_ephemeral_allocation(
1276 ) {
1277 let a = nameless_alloc(None);
1278 let err = a.owned_coordinates_required().unwrap_err();
1279 assert_eq!(
1280 err.to_string(),
1281 "EphemeralAllocation has no metadata.namespace"
1282 );
1283 }
1284
1285 // ── Byte-identical parity with the pre-lift 5-line chain ──────
1286
1287 #[test]
1288 fn owned_coordinates_required_matches_pre_lift_pool_reconciler_chain_shape() {
1289 // Byte-identical parity pin: the primitive produces the SAME
1290 // `Result<(String, String), anyhow::Error>` shape a pre-lift
1291 // `.metadata.<slot>.clone().ok_or_else(|| anyhow!("<Kind> has
1292 // no metadata.<slot>"))?` chain produced at
1293 // `tatara-pool-reconciler::controller_pool::reconcile_inner`
1294 // pre-lift, on both the happy and the missing-slot corners.
1295 // A regression that changed the error prefix, reordered the
1296 // two gates, or returned a non-`(String, String)` tuple
1297 // surfaces HERE rather than at every consumer downstream.
1298 let cases = [
1299 (Some("prod"), Some("api")),
1300 (Some("prod"), None),
1301 (None, Some("orphan")),
1302 (None, None),
1303 ];
1304 for (ns_slot, name_slot) in cases {
1305 let mut p = pool_fixture("placeholder", ns_slot);
1306 if let Some(nm) = name_slot {
1307 p.metadata.name = Some(nm.into());
1308 } else {
1309 p.metadata.name = None;
1310 }
1311
1312 // Pre-lift 5-line paired chain (with the reconciler's
1313 // hand-authored short-form `"Pool"` prefix updated to the
1314 // canonical kube kind `"EphemeralPool"`, matching the
1315 // primitive's `Self::kind`-driven spelling — the drift
1316 // is intentional per the trait's docs).
1317 let pre_lift: anyhow::Result<(String, String)> = (|| {
1318 let ns =
1319 p.metadata.namespace.clone().ok_or_else(|| {
1320 anyhow::anyhow!("EphemeralPool has no metadata.namespace")
1321 })?;
1322 let name = p
1323 .metadata
1324 .name
1325 .clone()
1326 .ok_or_else(|| anyhow::anyhow!("EphemeralPool has no metadata.name"))?;
1327 Ok((ns, name))
1328 })();
1329
1330 let via_primitive = p.owned_coordinates_required();
1331
1332 // Compare on both the Ok tuple + the error string
1333 // spelling — anyhow::Error does not derive PartialEq so
1334 // pattern-match on the Result axis rather than a direct
1335 // `assert_eq!` on the whole Result.
1336 match (via_primitive, pre_lift) {
1337 (Ok(a), Ok(b)) => assert_eq!(a, b),
1338 (Err(a), Err(b)) => assert_eq!(a.to_string(), b.to_string()),
1339 (a, b) => panic!(
1340 "primitive vs pre-lift chain disagree on Ok/Err axis for \
1341 (ns={ns_slot:?}, name={name_slot:?}): primitive={a:?}, pre_lift={b:?}"
1342 ),
1343 }
1344 }
1345 }
1346
1347 #[test]
1348 fn owned_coordinates_required_matches_pre_lift_allocation_reconciler_chain_shape() {
1349 // Peer to the pool-side pin above — pin the same byte-
1350 // identity contract on the allocation reconciler's chain,
1351 // where the pre-lift error spelling used the short-form
1352 // `"Allocation"` prefix that the primitive now emits as the
1353 // canonical kube-kind `"EphemeralAllocation"`.
1354 let cases = [
1355 (Some("ephemeral-pools"), Some("pr-42-demo")),
1356 (Some("ephemeral-pools"), None),
1357 (None, Some("orphan")),
1358 (None, None),
1359 ];
1360 for (ns_slot, name_slot) in cases {
1361 let mut a = alloc_fixture("placeholder", ns_slot);
1362 if let Some(nm) = name_slot {
1363 a.metadata.name = Some(nm.into());
1364 } else {
1365 a.metadata.name = None;
1366 }
1367
1368 let pre_lift: anyhow::Result<(String, String)> = (|| {
1369 let ns = a.metadata.namespace.clone().ok_or_else(|| {
1370 anyhow::anyhow!("EphemeralAllocation has no metadata.namespace")
1371 })?;
1372 let name =
1373 a.metadata.name.clone().ok_or_else(|| {
1374 anyhow::anyhow!("EphemeralAllocation has no metadata.name")
1375 })?;
1376 Ok((ns, name))
1377 })();
1378
1379 let via_primitive = a.owned_coordinates_required();
1380
1381 match (via_primitive, pre_lift) {
1382 (Ok(a), Ok(b)) => assert_eq!(a, b),
1383 (Err(a), Err(b)) => assert_eq!(a.to_string(), b.to_string()),
1384 (a, b) => panic!(
1385 "primitive vs pre-lift chain disagree on Ok/Err axis for \
1386 (ns={ns_slot:?}, name={name_slot:?}): primitive={a:?}, pre_lift={b:?}"
1387 ),
1388 }
1389 }
1390 }
1391
1392 // ── Cross-CRD symmetry: kube kind drives the error prefix ─────
1393
1394 #[test]
1395 fn owned_coordinates_required_error_prefix_matches_kube_kind_on_each_crd() {
1396 // The error prefix is sourced positionally from `Self::kind`
1397 // so the two CRDs emit distinct kube-canonical spellings
1398 // without either callsite hard-coding a per-CRD literal.
1399 // Regressions that hard-coded a shared prefix (e.g. a
1400 // copy-paste that pasted the pool's error string into the
1401 // allocation callsite) surface HERE.
1402 use kube::Resource;
1403 let p = pool_fixture("p", None);
1404 let a = alloc_fixture("a", None);
1405 assert_eq!(
1406 p.owned_coordinates_required().unwrap_err().to_string(),
1407 format!("{} has no metadata.namespace", EphemeralPool::kind(&()))
1408 );
1409 assert_eq!(
1410 a.owned_coordinates_required().unwrap_err().to_string(),
1411 format!(
1412 "{} has no metadata.namespace",
1413 EphemeralAllocation::kind(&())
1414 )
1415 );
1416 // Belt-and-suspenders: the two kinds are distinct spellings,
1417 // so the error strings are distinct too.
1418 assert_ne!(
1419 p.owned_coordinates_required().unwrap_err().to_string(),
1420 a.owned_coordinates_required().unwrap_err().to_string(),
1421 );
1422 }
1423}
1424
1425#[cfg(test)]
1426mod deletion_tombstoned_tests {
1427 //! Pin the [`DeletionTombstoned`] trait's `is_being_deleted` probe
1428 //! at fail-before-pass-after granularity across every corner of
1429 //! the (tombstone present, tombstone absent) input matrix, on
1430 //! ALL THREE tatara-process CRDs the trait's blanket impl covers
1431 //! today (`Process`, `EphemeralPool`, `EphemeralAllocation`), plus
1432 //! the cross-CRD coherence with the two pre-existing inherent
1433 //! forwarders. A regression that skewed the trait's default,
1434 //! promoted a distinct-payload tombstone to a false negative, or
1435 //! diverged the trait from either inherent forwarder surfaces
1436 //! HERE rather than as silent operator-facing skew between the
1437 //! four consumer sites the primitive owns (the top-level
1438 //! dispatcher's SIGTERM preempt, the SIGTERM cascade's child-
1439 //! fan-out DELETE-skip, the pool reconciler's Drain gate, and
1440 //! the allocation reconciler's release short-circuit) on three
1441 //! sibling CRDs.
1442 use super::DeletionTombstoned;
1443 use crate::allocation::{AllocationSpec, EphemeralAllocation, Requestor};
1444 use crate::classification::{Classification, ConvergencePointType, SubstrateType};
1445 use crate::crd::{Process, ProcessSpec};
1446 use crate::ephemeral::EphemeralSpec;
1447 use crate::intent::{AplicacaoIntent, Intent};
1448 use crate::lifetime::TeardownPolicy;
1449 use crate::pool::{EphemeralPool, PoolSelector, PoolSpec, ReturnPolicy};
1450 use crate::spec::IdentitySpec;
1451 use k8s_openapi::apimachinery::pkg::apis::meta::v1::Time;
1452
1453 fn empty_template() -> EphemeralSpec {
1454 EphemeralSpec {
1455 aplicacao: AplicacaoIntent {
1456 chart_ref: "oci://x".into(),
1457 version: "1".into(),
1458 profile: String::new(),
1459 values_overlay: serde_json::Value::Null,
1460 release_name: None,
1461 target_namespace: None,
1462 install_timeout: None,
1463 },
1464 ttl: "1h".into(),
1465 teardown: TeardownPolicy::Always,
1466 max_concurrent: 0,
1467 postconditions: vec![],
1468 preconditions: vec![],
1469 verify_timeout: None,
1470 classification: None,
1471 parent: None,
1472 exports: vec![],
1473 routing: None,
1474 }
1475 }
1476
1477 fn empty_pool_spec() -> PoolSpec {
1478 PoolSpec {
1479 desired_size: 1,
1480 min_size: 0,
1481 max_size: 0,
1482 return_policy: ReturnPolicy::Replace,
1483 selector: PoolSelector::default(),
1484 template: empty_template(),
1485 free_ttl: "24h".into(),
1486 max_allocation_ttl: "4h".into(),
1487 desired: 0,
1488 replacement_policy: Default::default(),
1489 stable_name_claim: false,
1490 }
1491 }
1492
1493 fn empty_alloc_spec() -> AllocationSpec {
1494 AllocationSpec {
1495 pool_ref: None,
1496 requestor: Requestor {
1497 kind: "github-pr".into(),
1498 repo: None,
1499 branch: None,
1500 pr_number: None,
1501 sha: None,
1502 pr_labels: vec![],
1503 actor: None,
1504 },
1505 ttl: None,
1506 note: None,
1507 }
1508 }
1509
1510 fn empty_process_spec() -> ProcessSpec {
1511 // Mirrors the workspace-standard `empty_spec()` fixture in
1512 // `crd.rs::tests` — the minimal `ProcessSpec` used across
1513 // every substrate metadata-projection pin.
1514 ProcessSpec {
1515 identity: IdentitySpec::default(),
1516 classification: Classification {
1517 point_type: ConvergencePointType::Gate,
1518 substrate: SubstrateType::Compute,
1519 horizon: Default::default(),
1520 calm: Default::default(),
1521 data_classification: Default::default(),
1522 },
1523 intent: Intent::default(),
1524 boundary: Default::default(),
1525 compliance: Default::default(),
1526 depends_on: vec![],
1527 signals: Default::default(),
1528 lifetime: Default::default(),
1529 routing: None,
1530 encapsulates: None,
1531 suspended: false,
1532 }
1533 }
1534
1535 // ── Missing tombstone (default fixture) — trait returns false ─────
1536
1537 #[test]
1538 fn is_being_deleted_on_process_missing_tombstone_returns_false_via_trait() {
1539 let p = Process::new("api", empty_process_spec());
1540 assert!(!DeletionTombstoned::is_being_deleted(&p));
1541 }
1542
1543 #[test]
1544 fn is_being_deleted_on_ephemeral_pool_missing_tombstone_returns_false_via_trait() {
1545 let p = EphemeralPool::new("attest-pool", empty_pool_spec());
1546 assert!(!DeletionTombstoned::is_being_deleted(&p));
1547 }
1548
1549 #[test]
1550 fn is_being_deleted_on_ephemeral_allocation_missing_tombstone_returns_false_via_trait() {
1551 // The load-bearing corner: EphemeralAllocation had NO inherent
1552 // is_being_deleted pre-lift — the trait's blanket impl is
1553 // what closes the substrate gap for the allocation reconciler's
1554 // hand-authored `.metadata.deletion_timestamp.is_some()` chain.
1555 let a = EphemeralAllocation::new("pr-42-demo", empty_alloc_spec());
1556 assert!(!DeletionTombstoned::is_being_deleted(&a));
1557 }
1558
1559 // ── Present tombstone — trait returns true ────────────────────────
1560
1561 #[test]
1562 fn is_being_deleted_on_process_present_tombstone_returns_true_via_trait() {
1563 let mut p = Process::new("api", empty_process_spec());
1564 p.metadata.deletion_timestamp = Some(Time(chrono::Utc::now()));
1565 assert!(DeletionTombstoned::is_being_deleted(&p));
1566 }
1567
1568 #[test]
1569 fn is_being_deleted_on_ephemeral_pool_present_tombstone_returns_true_via_trait() {
1570 let mut p = EphemeralPool::new("attest-pool", empty_pool_spec());
1571 p.metadata.deletion_timestamp = Some(Time(chrono::Utc::now()));
1572 assert!(DeletionTombstoned::is_being_deleted(&p));
1573 }
1574
1575 #[test]
1576 fn is_being_deleted_on_ephemeral_allocation_present_tombstone_returns_true_via_trait() {
1577 let mut a = EphemeralAllocation::new("pr-42-demo", empty_alloc_spec());
1578 a.metadata.deletion_timestamp = Some(Time(chrono::Utc::now()));
1579 assert!(DeletionTombstoned::is_being_deleted(&a));
1580 }
1581
1582 // ── Byte-identical parity with the pre-lift `.is_some()` chain ────
1583
1584 #[test]
1585 fn is_being_deleted_matches_pre_lift_deletion_timestamp_is_some_chain_on_ephemeral_allocation()
1586 {
1587 // Byte-identical parity pin: the trait's default produces the
1588 // SAME `bool` a pre-lift `.metadata.deletion_timestamp.is_some()`
1589 // chain produced at `tatara-pool-reconciler::allocation_decide::
1590 // AllocationConvergenceCtx::observe` pre-lift, across every
1591 // corner of the (absent, present-at-now, present-at-past)
1592 // input matrix. A regression that inserted a normalization
1593 // step the pre-lift chain does NOT apply — or vice versa —
1594 // surfaces here rather than as silent drift between the
1595 // substrate owner and the pre-lift consumer.
1596 let mut cases: Vec<Option<Time>> = vec![None];
1597 cases.push(Some(Time(chrono::Utc::now())));
1598 cases.push(Some(Time(
1599 chrono::Utc::now() - chrono::Duration::seconds(3600),
1600 )));
1601
1602 for ts in cases {
1603 let mut a = EphemeralAllocation::new("pr-42-demo", empty_alloc_spec());
1604 a.metadata.deletion_timestamp = ts.clone();
1605
1606 let pre_lift = a.metadata.deletion_timestamp.is_some();
1607 let via_trait = DeletionTombstoned::is_being_deleted(&a);
1608
1609 assert_eq!(
1610 pre_lift, via_trait,
1611 "trait probe must be byte-identical to pre-lift .metadata.deletion_timestamp.is_some() on tombstone={ts:?}",
1612 );
1613 }
1614 }
1615
1616 // ── Cross-CRD coherence with the two inherent forwarders ──────────
1617
1618 #[test]
1619 fn trait_probe_coheres_with_process_inherent_is_being_deleted_on_both_corners() {
1620 // Cross-primitive coherence pin: the trait's default and the
1621 // pre-existing `Process::is_being_deleted` inherent forwarder
1622 // return the SAME `bool` on the SAME `Process` value — a
1623 // future consolidation of the inherent onto the trait's default
1624 // (or vice versa) cannot land any drift between the two
1625 // surfaces because this pin binds them at every corner of the
1626 // (missing, present) input matrix.
1627 for ts in [None, Some(Time(chrono::Utc::now()))] {
1628 let mut p = Process::new("api", empty_process_spec());
1629 p.metadata.deletion_timestamp = ts.clone();
1630 assert_eq!(
1631 p.is_being_deleted(),
1632 DeletionTombstoned::is_being_deleted(&p),
1633 "Process trait probe must match inherent on tombstone={ts:?}",
1634 );
1635 }
1636 }
1637
1638 #[test]
1639 fn trait_probe_coheres_with_ephemeral_pool_inherent_is_being_deleted_on_both_corners() {
1640 // Peer coherence pin on the sister CRD.
1641 for ts in [None, Some(Time(chrono::Utc::now()))] {
1642 let mut p = EphemeralPool::new("attest-pool", empty_pool_spec());
1643 p.metadata.deletion_timestamp = ts.clone();
1644 assert_eq!(
1645 p.is_being_deleted(),
1646 DeletionTombstoned::is_being_deleted(&p),
1647 "EphemeralPool trait probe must match inherent on tombstone={ts:?}",
1648 );
1649 }
1650 }
1651
1652 // ── Inherent-preferred method resolution on Process + EphemeralPool ──
1653
1654 #[test]
1655 fn dot_call_on_process_resolves_to_inherent_when_trait_in_scope() {
1656 // Rust method resolution prefers an inherent over a trait's
1657 // blanket impl, so `process.is_being_deleted()` with the trait
1658 // in scope still routes through the inherent — and both
1659 // return the same `bool` (verified in
1660 // `trait_probe_coheres_with_process_inherent_is_being_deleted_on_both_corners`).
1661 // This pin guards against a future refactor that removes the
1662 // inherent but leaves consumers assuming inherent-preferred
1663 // resolution — the observable output is identical either way,
1664 // so the pin locks the invariant that BOTH paths agree.
1665 let mut p = Process::new("api", empty_process_spec());
1666 p.metadata.deletion_timestamp = Some(Time(chrono::Utc::now()));
1667 assert!(p.is_being_deleted());
1668 }
1669
1670 #[test]
1671 fn dot_call_on_ephemeral_allocation_resolves_to_trait_blanket_impl() {
1672 // The load-bearing corner: `alloc.is_being_deleted()` with
1673 // the trait in scope routes to the trait's blanket impl
1674 // (there is no inherent on `EphemeralAllocation`) and
1675 // produces the expected `bool`. This is what the swept
1676 // allocation-reconciler callsite depends on post-lift.
1677 let mut a = EphemeralAllocation::new("pr-42-demo", empty_alloc_spec());
1678 assert!(!a.is_being_deleted());
1679 a.metadata.deletion_timestamp = Some(Time(chrono::Utc::now()));
1680 assert!(a.is_being_deleted());
1681 }
1682}
1683
1684#[cfg(test)]
1685mod annotated_tests {
1686 //! Pin the [`Annotated`] trait's `annotation` lookup at fail-
1687 //! before-pass-after granularity across every corner of the
1688 //! (annotations map: absent / present-empty / present-with-key /
1689 //! present-without-key) × (value form: normal / empty-string)
1690 //! input matrix, on the three tatara-process CRDs the trait's
1691 //! blanket impl covers today (`Process`, `EphemeralPool`,
1692 //! `EphemeralAllocation`) PLUS a K8s built-in (`ConfigMap`) — the
1693 //! load-bearing fourth surface that `tatara-export-worker::main`
1694 //! consumes post-lift where no tatara-owned inherent forwarder
1695 //! exists. Also pin cross-primitive coherence with the pre-existing
1696 //! `Process::annotation` inherent so a future consolidation onto
1697 //! the trait's default cannot silently skew the three consumers
1698 //! already routed through the inherent
1699 //! (`signals::ingest`,
1700 //! `phase_machine::released_from_annotation`,
1701 //! `controller_pool::process_belongs_to_pool`).
1702 use super::Annotated;
1703 use crate::allocation::{AllocationSpec, EphemeralAllocation, Requestor};
1704 use crate::classification::{Classification, ConvergencePointType, SubstrateType};
1705 use crate::crd::{Process, ProcessSpec};
1706 use crate::ephemeral::EphemeralSpec;
1707 use crate::intent::{AplicacaoIntent, Intent};
1708 use crate::lifetime::TeardownPolicy;
1709 use crate::pool::{EphemeralPool, PoolSelector, PoolSpec, ReturnPolicy};
1710 use crate::spec::IdentitySpec;
1711 use k8s_openapi::api::core::v1::ConfigMap;
1712 use std::collections::BTreeMap;
1713
1714 fn empty_template() -> EphemeralSpec {
1715 EphemeralSpec {
1716 aplicacao: AplicacaoIntent {
1717 chart_ref: "oci://x".into(),
1718 version: "1".into(),
1719 profile: String::new(),
1720 values_overlay: serde_json::Value::Null,
1721 release_name: None,
1722 target_namespace: None,
1723 install_timeout: None,
1724 },
1725 ttl: "1h".into(),
1726 teardown: TeardownPolicy::Always,
1727 max_concurrent: 0,
1728 postconditions: vec![],
1729 preconditions: vec![],
1730 verify_timeout: None,
1731 classification: None,
1732 parent: None,
1733 exports: vec![],
1734 routing: None,
1735 }
1736 }
1737
1738 fn empty_pool_spec() -> PoolSpec {
1739 PoolSpec {
1740 desired_size: 1,
1741 min_size: 0,
1742 max_size: 0,
1743 return_policy: ReturnPolicy::Replace,
1744 selector: PoolSelector::default(),
1745 template: empty_template(),
1746 free_ttl: "24h".into(),
1747 max_allocation_ttl: "4h".into(),
1748 desired: 0,
1749 replacement_policy: Default::default(),
1750 stable_name_claim: false,
1751 }
1752 }
1753
1754 fn empty_alloc_spec() -> AllocationSpec {
1755 AllocationSpec {
1756 pool_ref: None,
1757 requestor: Requestor {
1758 kind: "github-pr".into(),
1759 repo: None,
1760 branch: None,
1761 pr_number: None,
1762 sha: None,
1763 pr_labels: vec![],
1764 actor: None,
1765 },
1766 ttl: None,
1767 note: None,
1768 }
1769 }
1770
1771 fn empty_process_spec() -> ProcessSpec {
1772 ProcessSpec {
1773 identity: IdentitySpec::default(),
1774 classification: Classification {
1775 point_type: ConvergencePointType::Gate,
1776 substrate: SubstrateType::Compute,
1777 horizon: Default::default(),
1778 calm: Default::default(),
1779 data_classification: Default::default(),
1780 },
1781 intent: Intent::default(),
1782 boundary: Default::default(),
1783 compliance: Default::default(),
1784 depends_on: vec![],
1785 signals: Default::default(),
1786 lifetime: Default::default(),
1787 routing: None,
1788 encapsulates: None,
1789 suspended: false,
1790 }
1791 }
1792
1793 fn one_annotation(key: &str, value: &str) -> BTreeMap<String, String> {
1794 let mut m = BTreeMap::new();
1795 m.insert(key.into(), value.into());
1796 m
1797 }
1798
1799 // ── Missing annotations map — trait returns None on every key ─────
1800
1801 #[test]
1802 fn annotation_on_process_missing_annotations_returns_none_via_trait() {
1803 let mut p = Process::new("api", empty_process_spec());
1804 p.metadata.annotations = None;
1805 assert_eq!(Annotated::annotation(&p, "tatara.pleme.io/signal"), None);
1806 assert_eq!(Annotated::annotation(&p, ""), None);
1807 }
1808
1809 #[test]
1810 fn annotation_on_ephemeral_pool_missing_annotations_returns_none_via_trait() {
1811 let mut p = EphemeralPool::new("attest-pool", empty_pool_spec());
1812 p.metadata.annotations = None;
1813 assert_eq!(Annotated::annotation(&p, "tatara.pleme.io/pool"), None);
1814 }
1815
1816 #[test]
1817 fn annotation_on_ephemeral_allocation_missing_annotations_returns_none_via_trait() {
1818 // The peer load-bearing corner: EphemeralAllocation has NO
1819 // inherent `annotation()` pre-lift — the trait's blanket impl
1820 // is what closes the substrate gap here, exactly as the
1821 // sibling `DeletionTombstoned` trait already did on the
1822 // tombstone axis for the SAME third CRD.
1823 let mut a = EphemeralAllocation::new("pr-42-demo", empty_alloc_spec());
1824 a.metadata.annotations = None;
1825 assert_eq!(
1826 Annotated::annotation(&a, "tatara.pleme.io/requestor-kind"),
1827 None,
1828 );
1829 }
1830
1831 #[test]
1832 fn annotation_on_config_map_missing_annotations_returns_none_via_trait() {
1833 // The load-bearing corner the export-worker's post-lift call
1834 // depends on: `ConfigMap` is a K8s built-in with no tatara-
1835 // owned inherent forwarder, and the receipts-owner filter
1836 // needs to route through the trait's blanket impl at
1837 // `cm.annotation(KEY)`.
1838 let cm = ConfigMap::default();
1839 // `Default::default()` produces an object with an empty
1840 // ObjectMeta whose `annotations` slot is `None` — the exact
1841 // missing-annotations corner the trait must collapse to
1842 // `None` at every key lookup, matching what the pre-lift
1843 // `cm.metadata.annotations.as_ref().and_then(...)` chain
1844 // produced.
1845 assert_eq!(Annotated::annotation(&cm, "tatara.pleme.io/process"), None,);
1846 }
1847
1848 // ── Missing key inside populated map — trait returns None ─────────
1849
1850 #[test]
1851 fn annotation_on_process_missing_key_returns_none_via_trait() {
1852 let mut p = Process::new("api", empty_process_spec());
1853 p.metadata.annotations = Some(one_annotation("other/key", "irrelevant"));
1854 assert_eq!(Annotated::annotation(&p, "tatara.pleme.io/signal"), None);
1855 assert_eq!(Annotated::annotation(&p, ""), None);
1856 }
1857
1858 #[test]
1859 fn annotation_on_config_map_missing_key_returns_none_via_trait() {
1860 let mut cm = ConfigMap::default();
1861 cm.metadata.annotations = Some(one_annotation("unrelated", "yes"));
1862 assert_eq!(Annotated::annotation(&cm, "tatara.pleme.io/process"), None,);
1863 }
1864
1865 // ── Present key — trait returns borrowed slice ────────────────────
1866
1867 #[test]
1868 fn annotation_on_process_present_key_returns_borrowed_slice_via_trait() {
1869 let mut p = Process::new("api", empty_process_spec());
1870 p.metadata.annotations = Some(one_annotation("tatara.pleme.io/signal", "SIGHUP"));
1871 assert_eq!(
1872 Annotated::annotation(&p, "tatara.pleme.io/signal"),
1873 Some("SIGHUP"),
1874 );
1875 }
1876
1877 #[test]
1878 fn annotation_on_ephemeral_pool_present_key_returns_borrowed_slice_via_trait() {
1879 let mut p = EphemeralPool::new("attest-pool", empty_pool_spec());
1880 p.metadata.annotations = Some(one_annotation("tatara.pleme.io/pool", "demo-pool"));
1881 assert_eq!(
1882 Annotated::annotation(&p, "tatara.pleme.io/pool"),
1883 Some("demo-pool"),
1884 );
1885 }
1886
1887 #[test]
1888 fn annotation_on_ephemeral_allocation_present_key_returns_borrowed_slice_via_trait() {
1889 let mut a = EphemeralAllocation::new("pr-42-demo", empty_alloc_spec());
1890 a.metadata.annotations = Some(one_annotation(
1891 "tatara.pleme.io/requestor-kind",
1892 "github-pr",
1893 ));
1894 assert_eq!(
1895 Annotated::annotation(&a, "tatara.pleme.io/requestor-kind"),
1896 Some("github-pr"),
1897 );
1898 }
1899
1900 #[test]
1901 fn annotation_on_config_map_present_key_returns_borrowed_slice_via_trait() {
1902 // The exact receipts-owner filter shape from
1903 // `tatara-export-worker::main`: a ConfigMap carrying the
1904 // `tatara.pleme.io/process` annotation set to the qualified
1905 // process reference `<ns>/<name>`. Pin that the trait produces
1906 // the exact borrowed slice the equality comparison against the
1907 // caller's `want.as_str()` sentinel consumes.
1908 let mut cm = ConfigMap::default();
1909 cm.metadata.annotations = Some(one_annotation(
1910 "tatara.pleme.io/process",
1911 "demo-ns/demo-app",
1912 ));
1913 assert_eq!(
1914 Annotated::annotation(&cm, "tatara.pleme.io/process"),
1915 Some("demo-ns/demo-app"),
1916 );
1917 }
1918
1919 // ── Empty-value contract: `Some("")` — the pre-lift chain never
1920 // swallowed empty values into `None`, so the trait must not
1921 // either. Pinned separately from the missing-slot corners.
1922
1923 #[test]
1924 fn annotation_present_key_with_empty_value_returns_some_empty_slice_via_trait() {
1925 let mut p = Process::new("api", empty_process_spec());
1926 p.metadata.annotations = Some(one_annotation("tatara.pleme.io/signal", ""));
1927 assert_eq!(
1928 Annotated::annotation(&p, "tatara.pleme.io/signal"),
1929 Some("")
1930 );
1931 }
1932
1933 // ── Byte-identical parity with the pre-lift 3-line chain ──────────
1934
1935 #[test]
1936 fn annotation_matches_pre_lift_annotations_lookup_chain_on_config_map() {
1937 // The four-corner input matrix the pre-lift
1938 // `cm.metadata.annotations.as_ref().and_then(|m| m.get(KEY))
1939 // .map(String::as_str)` chain traversed in
1940 // `tatara-export-worker::main` pre-lift. A regression that
1941 // inserted a normalization step the pre-lift chain does NOT
1942 // apply — or vice versa — surfaces here rather than as silent
1943 // drift between the substrate owner and the pre-lift consumer.
1944 const KEY: &str = "tatara.pleme.io/process";
1945 let cases: Vec<(Option<BTreeMap<String, String>>, Option<&str>)> = vec![
1946 (None, None),
1947 (Some(BTreeMap::new()), None),
1948 (Some(one_annotation("unrelated", "yes")), None),
1949 (
1950 Some(one_annotation(KEY, "demo-ns/demo-app")),
1951 Some("demo-ns/demo-app"),
1952 ),
1953 (Some(one_annotation(KEY, "")), Some("")),
1954 ];
1955 for (anns, expected) in cases {
1956 let mut cm = ConfigMap::default();
1957 cm.metadata.annotations = anns.clone();
1958
1959 let pre_lift: Option<&str> = cm
1960 .metadata
1961 .annotations
1962 .as_ref()
1963 .and_then(|m| m.get(KEY))
1964 .map(String::as_str);
1965 let via_trait = Annotated::annotation(&cm, KEY);
1966
1967 assert_eq!(
1968 pre_lift, expected,
1969 "pre-lift chain must return {expected:?} for annotations={anns:?}",
1970 );
1971 assert_eq!(
1972 via_trait, pre_lift,
1973 "trait probe must be byte-identical to pre-lift chain for annotations={anns:?}",
1974 );
1975 }
1976 }
1977
1978 // ── Cross-primitive coherence with Process's inherent forwarder ───
1979
1980 #[test]
1981 fn trait_probe_coheres_with_process_inherent_annotation_on_every_corner() {
1982 // Cross-primitive coherence pin: the trait's default and the
1983 // pre-existing `Process::annotation` inherent forwarder return
1984 // the SAME `Option<&str>` on the SAME `Process` value — a
1985 // future consolidation of the inherent onto the trait's
1986 // default cannot land any drift because this pin binds them
1987 // at every corner of the (absent, present-missing-key,
1988 // present-with-key, present-with-empty-value) input matrix.
1989 const KEY: &str = "tatara.pleme.io/signal";
1990 let cases: Vec<Option<BTreeMap<String, String>>> = vec![
1991 None,
1992 Some(BTreeMap::new()),
1993 Some(one_annotation("other/key", "irrelevant")),
1994 Some(one_annotation(KEY, "SIGHUP")),
1995 Some(one_annotation(KEY, "")),
1996 ];
1997 for anns in cases {
1998 let mut p = Process::new("api", empty_process_spec());
1999 p.metadata.annotations = anns.clone();
2000 let via_inherent = p.annotation(KEY);
2001 let via_trait = Annotated::annotation(&p, KEY);
2002 assert_eq!(
2003 via_inherent, via_trait,
2004 "Process inherent + Annotated trait must agree on annotations={anns:?}",
2005 );
2006 }
2007 }
2008
2009 // ── Inherent-preferred method resolution on Process ───────────────
2010
2011 #[test]
2012 fn dot_call_on_process_resolves_to_inherent_when_trait_in_scope() {
2013 // Rust method resolution prefers an inherent over a trait's
2014 // blanket impl, so `process.annotation(key)` with the trait in
2015 // scope still routes through the inherent — and both return
2016 // the same `Option<&str>` (verified in
2017 // `trait_probe_coheres_with_process_inherent_annotation_on_every_corner`).
2018 // This pin guards against a future refactor that removes the
2019 // inherent but leaves consumers assuming inherent-preferred
2020 // resolution — the observable output is identical either way,
2021 // so the pin locks the invariant that BOTH paths agree.
2022 let mut p = Process::new("api", empty_process_spec());
2023 p.metadata.annotations = Some(one_annotation("tatara.pleme.io/signal", "SIGHUP"));
2024 assert_eq!(p.annotation("tatara.pleme.io/signal"), Some("SIGHUP"));
2025 }
2026
2027 #[test]
2028 fn dot_call_on_ephemeral_allocation_resolves_to_trait_blanket_impl() {
2029 // The peer load-bearing corner: `alloc.annotation(key)` with
2030 // the trait in scope routes to the trait's blanket impl —
2031 // there is no inherent on `EphemeralAllocation` — and produces
2032 // the expected `Option<&str>`. The same discipline the sibling
2033 // `DeletionTombstoned` trait already established on the
2034 // tombstone axis for the SAME third CRD.
2035 let mut a = EphemeralAllocation::new("pr-42-demo", empty_alloc_spec());
2036 assert_eq!(a.annotation("tatara.pleme.io/requestor-kind"), None);
2037 a.metadata.annotations = Some(one_annotation(
2038 "tatara.pleme.io/requestor-kind",
2039 "github-pr",
2040 ));
2041 assert_eq!(
2042 a.annotation("tatara.pleme.io/requestor-kind"),
2043 Some("github-pr"),
2044 );
2045 }
2046
2047 #[test]
2048 fn dot_call_on_config_map_resolves_to_trait_blanket_impl() {
2049 // The load-bearing corner the export-worker's post-lift call
2050 // exercises: `cm.annotation(KEY)` with the trait in scope
2051 // routes to the blanket impl (ConfigMap is a K8s built-in
2052 // with no tatara-owned inherent) and produces the same
2053 // `Option<&str>` the pre-lift 3-line chain did.
2054 let mut cm = ConfigMap::default();
2055 assert_eq!(cm.annotation("tatara.pleme.io/process"), None);
2056 cm.metadata.annotations = Some(one_annotation(
2057 "tatara.pleme.io/process",
2058 "demo-ns/demo-app",
2059 ));
2060 assert_eq!(
2061 cm.annotation("tatara.pleme.io/process"),
2062 Some("demo-ns/demo-app"),
2063 );
2064 }
2065}
2066
2067// ── Lisp → ProcessSpec compile bridge ──────────────────────────────────
2068//
2069// `(defpoint NAME :k v …)` compiles to a `NamedDefinition<ProcessSpec>`.
2070// The derive on ProcessSpec handles every field via the serde Deserialize
2071// fallthrough — no hand-rolled keyword parsing needed.
2072
2073/// A named ProcessSpec as produced by `compile_source`.
2074pub type Definition = tatara_lisp::NamedDefinition<crate::crd::ProcessSpec>;
2075
2076/// Compile a Lisp source string into a list of named ProcessSpecs.
2077/// Each top-level `(defpoint NAME …)` form becomes one `Definition`.
2078pub fn compile_source(src: &str) -> tatara_lisp::Result<Vec<Definition>> {
2079 tatara_lisp::compile_named::<crate::crd::ProcessSpec>(src)
2080}
2081
2082/// Register every domain owned by this crate with the global Lisp
2083/// dispatcher. Call once per binary, typically near the top of `main`.
2084/// After this call, `tatara_lisp::domain::lookup("defpoint")` and
2085/// `lookup("defephemeral")` both resolve to the right typed compiler.
2086///
2087/// Idempotent — registering the same type twice is a no-op.
2088pub fn register_all() {
2089 tatara_lisp::domain::register::<crate::crd::ProcessSpec>();
2090 tatara_lisp::domain::register::<crate::ephemeral::EphemeralSpec>();
2091}
2092
2093#[cfg(test)]
2094mod compile_tests {
2095 use super::compile_source;
2096 use crate::classification::{ConvergencePointType, SubstrateType};
2097 use crate::compliance::VerificationPhase;
2098 use crate::spec::MustReachPhase;
2099
2100 /// The full derive-powered pipeline — no hand-rolled parsing anywhere.
2101 /// Every field travels: Lisp → Sexp → serde_json → typed ProcessSpec.
2102 #[test]
2103 fn full_processspec_round_trip_via_derive() {
2104 let src = r#"
2105 (defpoint observability-stack
2106 :identity (:parent "seph.1")
2107 :classification (:point-type Gate
2108 :substrate Observability
2109 :horizon (:kind Bounded)
2110 :calm Monotone
2111 :data-classification Internal)
2112 :intent (:nix (:flake-ref "github:pleme-io/k8s"
2113 :attribute "observability"
2114 :attic-cache "main"))
2115 :boundary (:postconditions
2116 ((:kind KustomizationHealthy
2117 :params (:name "observability-stack"
2118 :namespace "flux-system"))
2119 (:kind PromQL
2120 :params (:query "up == 1")))
2121 :timeout "15m")
2122 :compliance (:baseline "fedramp-moderate"
2123 :bindings ((:framework "nist-800-53"
2124 :control-id "SC-7"
2125 :phase AtBoundary)))
2126 :depends-on ((:name "secret-injection" :must-reach Attested))
2127 :signals (:sigterm-grace-seconds 480
2128 :sighup-strategy Reconverge))
2129 "#;
2130 let defs = compile_source(src).expect("compile");
2131 assert_eq!(defs.len(), 1);
2132 let d = &defs[0];
2133 assert_eq!(d.name, "observability-stack");
2134
2135 // identity
2136 assert_eq!(d.spec.identity.parent.as_deref(), Some("seph.1"));
2137
2138 // classification (enums deserialized via symbol → string)
2139 assert_eq!(d.spec.classification.point_type, ConvergencePointType::Gate);
2140 assert_eq!(
2141 d.spec.classification.substrate,
2142 SubstrateType::Observability
2143 );
2144
2145 // intent (tagged-union with one of four options)
2146 let nix = d.spec.intent.nix.as_ref().expect("nix intent");
2147 assert_eq!(nix.flake_ref, "github:pleme-io/k8s");
2148 assert_eq!(nix.attribute, "observability");
2149 assert_eq!(nix.attic_cache.as_deref(), Some("main"));
2150
2151 // boundary (Vec<nested struct with params object>)
2152 assert_eq!(d.spec.boundary.postconditions.len(), 2);
2153 assert_eq!(d.spec.boundary.timeout.as_deref(), Some("15m"));
2154
2155 // compliance (Vec<binding with enum phase>)
2156 assert_eq!(
2157 d.spec.compliance.baseline.as_deref(),
2158 Some("fedramp-moderate")
2159 );
2160 assert_eq!(d.spec.compliance.bindings.len(), 1);
2161 assert_eq!(
2162 d.spec.compliance.bindings[0].phase,
2163 VerificationPhase::AtBoundary
2164 );
2165
2166 // depends_on (Vec<struct with enum>)
2167 assert_eq!(d.spec.depends_on.len(), 1);
2168 assert_eq!(d.spec.depends_on[0].must_reach, MustReachPhase::Attested);
2169
2170 // signals (numeric + enum defaults)
2171 assert_eq!(d.spec.signals.sigterm_grace_seconds, 480);
2172 }
2173
2174 #[test]
2175 fn missing_required_field_errors() {
2176 // `:classification` has no #[serde(default)] — omit it and compile must fail.
2177 let src = r#"(defpoint x :intent (:nix (:flake-ref "f" :attribute "a")))"#;
2178 assert!(compile_source(src).is_err());
2179 }
2180
2181 #[test]
2182 fn serde_default_fields_are_optional() {
2183 // Omit every #[serde(default)] field — compile must succeed because
2184 // the derive honors serde defaults.
2185 let src = r#"
2186 (defpoint x
2187 :classification (:point-type Transform :substrate Compute)
2188 :intent (:flux (:git-repository "g" :path ".")))
2189 "#;
2190 let defs = compile_source(src).expect("compile");
2191 assert_eq!(defs.len(), 1);
2192 let d = &defs[0];
2193 assert!(d.spec.depends_on.is_empty());
2194 assert!(d.spec.boundary.postconditions.is_empty());
2195 assert!(d.spec.compliance.bindings.is_empty());
2196 assert!(!d.spec.suspended);
2197 // Lifetime defaults to Permanent (no variant set, resolver still works).
2198 assert!(d.spec.lifetime.is_default());
2199 assert!(!d.spec.lifetime.is_ephemeral());
2200 }
2201
2202 /// Registering all process-owned domains is idempotent and resolves
2203 /// both `defpoint` (ProcessSpec) and `defephemeral` (EphemeralSpec).
2204 #[test]
2205 fn register_all_resolves_defpoint_and_defephemeral() {
2206 use tatara_lisp::domain::lookup;
2207 super::register_all();
2208 super::register_all(); // idempotent
2209 assert!(lookup("defpoint").is_some(), "defpoint must resolve");
2210 assert!(
2211 lookup("defephemeral").is_some(),
2212 "defephemeral must resolve"
2213 );
2214 }
2215
2216 /// End-to-end: a `(defpoint …)` form may carry the full ephemeral
2217 /// shape directly — `:intent (:aplicacao …)` + `:lifetime (:ephemeral …)`.
2218 /// This is what the `(defephemeral …)` sugar lowers to via `From`.
2219 #[test]
2220 fn defpoint_with_aplicacao_intent_and_ephemeral_lifetime() {
2221 use crate::intent::IntentVariant;
2222 use crate::lifetime::{LifetimeVariant, TeardownPolicy};
2223 let src = r#"
2224 (defpoint closed-loop-attest
2225 :classification (:point-type Gate :substrate Compute)
2226 :intent (:aplicacao
2227 (:chart-ref "oci://ghcr.io/pleme-io/charts/lareira-demo-app"
2228 :version "0.5.5"
2229 :profile "all-in-one"
2230 :values-overlay (:cluster (:name "ephemeral-test-01"))
2231 :target-namespace "demo-test"))
2232 :boundary (:postconditions
2233 ((:kind HelmReleaseReleased
2234 :params (:name "demo-app-consolidated"
2235 :namespace "demo-test"))
2236 (:kind ClosedLoopAuth
2237 :params (:issuer (:service "demo-app-issuer" :port 8080)
2238 :consumer (:service "demo-app-gateway" :port 8000)
2239 :probeImage "ghcr.io/pleme-io/closed-loop-probe:0.1.0"))))
2240 :lifetime (:ephemeral (:ttl "1h"
2241 :teardown-policy OnAttested
2242 :max-concurrent 1)))
2243 "#;
2244 let defs = compile_source(src).expect("compile");
2245 assert_eq!(defs.len(), 1);
2246 let d = &defs[0];
2247
2248 // Aplicacao intent landed.
2249 match d.spec.intent.variant().unwrap() {
2250 IntentVariant::Aplicacao(a) => {
2251 assert_eq!(a.profile, "all-in-one");
2252 assert_eq!(a.version, "0.5.5");
2253 assert_eq!(a.target_namespace.as_deref(), Some("demo-test"));
2254 assert_eq!(a.values_overlay["cluster"]["name"], "ephemeral-test-01");
2255 }
2256 other => panic!("expected Aplicacao, got {other:?}"),
2257 }
2258
2259 // Ephemeral lifetime landed with the right teardown policy.
2260 match d.spec.lifetime.variant().unwrap() {
2261 LifetimeVariant::Ephemeral(e) => {
2262 assert_eq!(e.ttl, "1h");
2263 assert_eq!(e.teardown_policy, TeardownPolicy::OnAttested);
2264 assert_eq!(e.max_concurrent, 1);
2265 }
2266 other => panic!("expected ephemeral, got {other:?}"),
2267 }
2268
2269 // Two typed postconditions including ClosedLoopAuth.
2270 assert_eq!(d.spec.boundary.postconditions.len(), 2);
2271 assert_eq!(
2272 d.spec.boundary.postconditions[1].kind,
2273 crate::boundary::ConditionKind::ClosedLoopAuth
2274 );
2275 }
2276}