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