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