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