Skip to main content

tatara_process/
lib.rs

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