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