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