Skip to main content

tatara_process/
lib.rs

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