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