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