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