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