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