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