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 condition_type;
15pub mod configmap;
16pub mod crd;
17pub mod create;
18pub mod delete;
19pub mod encapsulates;
20pub mod env;
21pub mod ephemeral;
22pub mod err_ctx;
23pub mod export;
24pub mod finalizers;
25pub mod flux_resource;
26pub mod hash;
27pub mod hostname;
28pub mod identity;
29pub mod intent;
30pub mod json_object;
31pub mod k8s_builtin_resource;
32pub mod k8s_condition;
33pub mod k8s_object_ref;
34pub mod k8s_wire_identity;
35pub mod kube_error;
36pub mod lifetime;
37pub mod lifetime_clock;
38pub mod list;
39pub mod matrix;
40pub mod patch;
41pub mod phase;
42pub mod pool;
43pub mod process_api;
44pub mod receipt;
45pub mod requeue;
46pub mod routing;
47pub mod routing_edge_resource;
48pub mod secret_env;
49pub mod serde_defaults;
50pub mod signal;
51pub mod spec;
52pub mod status;
53pub mod string_map;
54pub mod table;
55pub mod tagged_union;
56pub mod three_pillar;
57pub mod time;
58
59pub mod prelude {
60    pub use crate::allocation::{
61        AllocationCondition, AllocationPhase, AllocationSpec, AllocationStatus,
62        EphemeralAllocation, Requestor,
63    };
64    pub use crate::anyhow_flatten::FlattenCtxExt;
65    pub use crate::attestation::ProcessAttestation;
66    pub use crate::boundary::{
67        Boundary, Condition, ConditionKind, ConditionSliceExt, UnknownConditionKind,
68    };
69    pub use crate::classification::{
70        Arity, CalmClassification, Classification, ConvergencePointType, DataClassification,
71        Horizon, HorizonKind, OptimizationDirection, SubstrateType, UnknownCalmClassification,
72        UnknownConvergencePointType, UnknownDataClassification, UnknownHorizonKind,
73        UnknownOptimizationDirection, UnknownSubstrateType,
74    };
75    pub use crate::compliance::{
76        ComplianceBinding, ComplianceBindingSliceExt, ComplianceSpec, UnknownVerificationPhase,
77        VerificationPhase,
78    };
79    pub use crate::crd::{Process, ProcessSpec, ProcessStatus};
80    pub use crate::encapsulates::{
81        BareWorkload, EncapsulatesSpec, EncapsulationKind, EncapsulationKindError,
82        EncapsulationKindVariant, EncapsulationMode, EncapsulationTarget, ExistingHelmRelease,
83        ExistingKustomization, UnknownEncapsulationMode, UnknownEncapsulationTarget,
84    };
85    pub use crate::ephemeral::{compile_ephemeral_source, EphemeralSpec};
86    pub use crate::err_ctx::ErrCtxExt;
87    pub use crate::export::{
88        ArtifactError, ArtifactKind, ArtifactSource, ArtifactVariant, ChannelError, ChannelKind,
89        ChannelVariant, ExportSpec, ExportSpecSliceExt, ExportTrigger, HttpEventChannel,
90        NatsSubjectChannel, ProcessSnapshotSource, ReceiptsSource, ReportFormat,
91        ReportPayloadShape, RunMarkerSource, StdoutChannel, TestReportSource, UnknownArtifactKind,
92        UnknownChannelKind, UnknownExportTrigger, UnknownReportFormat, VectorChannel,
93        DEFAULT_NATS_URL, DEFAULT_VECTOR_INGEST,
94    };
95    pub use crate::flux_resource::FluxResource;
96    pub use crate::hash::hex_blake3;
97    pub use crate::hostname::{
98        ephemeral_id_from_spec, fmt_fqdn, fmt_fqdn_stable, resolve_ephemeral_id, HostnameError,
99        HostnameResultExt, EPHEMERAL_ID_HASH_LEN,
100    };
101    pub use crate::identity::{
102        content_hash, derive_identity, format_process_address, join_pid_segment, Identity,
103        PID_PATH_SEPARATOR,
104    };
105    pub use crate::intent::{
106        AplicacaoIntent, ContainerIntent, FluxIntent, GuestIntent, HelmLifecyclePolicy,
107        HelmRemediationPolicy, Intent, IntentError, IntentKind, IntentVariant, LispIntent,
108        NixIntent, UnknownWorkloadKind, WorkloadKind, FLUX_HELM_DEFAULT_INTERVAL,
109        HELM_LIFECYCLE_DEFAULT_RETRIES, HELM_LIFECYCLE_DEFAULT_TIMEOUT,
110    };
111    pub use crate::k8s_builtin_resource::K8sBuiltinResource;
112    pub use crate::k8s_condition::K8sConditionStatus;
113    pub use crate::k8s_object_ref::K8sObjectRef;
114    pub use crate::k8s_wire_identity::K8sWireIdentity;
115    pub use crate::lifetime::{
116        EphemeralLifetime, Lifetime, LifetimeError, LifetimeKind, LifetimeVariant,
117        PermanentLifetime, TeardownPolicy, UnknownTeardownPolicy,
118    };
119    pub use crate::lifetime_clock::{
120        evaluate as lifetime_clock_evaluate, AutoTerminate, AutoTerminateKind, TerminateReason,
121        TerminateReasonKind, UnknownAutoTerminateKind, UnknownTerminateReasonKind,
122    };
123    pub use crate::matrix::{
124        compile_env_matrix_source, EnvMatrixSpec, MatrixAxis, MatrixBudget, NamedEphemeral,
125        SelectStrategy, SelectStrategyKind, UnknownSelectStrategyKind,
126    };
127    pub use crate::phase::{ProcessPhase, UnknownPhase};
128    pub use crate::pool::{
129        AllocationRef, EphemeralPool, MatchKey, MemberState, PoolCondition, PoolMember, PoolPhase,
130        PoolSelector, PoolSpec, PoolStatus, ReplacementPolicy, ReturnPolicy, UnknownMemberState,
131        UnknownPoolPhase, UnknownReplacementPolicy,
132    };
133    pub use crate::receipt::{
134        default_receipt_config_map_name, extract_receipt_payload_json,
135        resolve_receipt_config_map_name, ReceiptEnvelope, ReceiptError, ReceiptKind,
136        ReceiptWireForm, RECEIPT_CM_KEYS, RECEIPT_CM_MISSING_KEY_MSG, RECEIPT_CM_SUFFIX,
137        RECEIPT_JSON_KEY, RECEIPT_VERSION, RECEIPT_YAML_KEY,
138    };
139    pub use crate::requeue::after_secs as requeue_after_secs;
140    pub use crate::routing::{RoutingBackend, RoutingForm, RoutingHostname, RoutingSpec};
141    pub use crate::routing_edge_resource::RoutingEdgeResource;
142    pub use crate::signal::{ProcessSignal, SighupStrategy, UnknownSighupStrategy};
143    pub use crate::spec::{
144        DependsOn, DependsOnSliceExt, IdentitySpec, MustReachPhase, SignalPolicy,
145        UnknownMustReachPhase,
146    };
147    pub use crate::status::{
148        BoundaryStatus, CheckedCondition, ComplianceStatus, FluxResourceRef, ProcessCondition,
149        RenderedResourceCoords,
150    };
151    pub use crate::table::{
152        ClaimRecord, ProcessEntry, ProcessTable, ProcessTableSpec, ProcessTableStatus,
153    };
154    pub use crate::time::{elapsed_since, seconds_ago, tombstone_at, tombstone_now};
155    pub use crate::{qualified_error_ctx, qualified_process_ref};
156    pub use crate::{Annotated, DeletionTombstoned, NamespacedApiCoordinates, PlacedInNamespace};
157}
158
159/// CRD API group for every tatara CRD.
160pub const GROUP: &str = "tatara.pleme.io";
161/// CRD version for this module.
162pub const VERSION: &str = "v1alpha1";
163
164/// Reverse-DNS group prefix — the `<GROUP>/` byte-shape every
165/// tatara-owned `tatara.pleme.io/*` wire-form key (annotation,
166/// finalizer, label, signal) rides through, and the string every
167/// downstream `.starts_with(...)` group-membership filter compares
168/// against.
169///
170/// Peer to [`GROUP`] + [`VERSION`] + [`API_VERSION`] on the CRD-
171/// group×version axis: where [`GROUP`] owns the bare reverse-DNS
172/// segment (`"tatara.pleme.io"`), [`VERSION`] owns the version
173/// segment, and [`API_VERSION`] owns the two-segment compose product
174/// (`"tatara.pleme.io/v1alpha1"`), this const owns the ONE-segment
175/// `<GROUP>/` product every tatara wire-form key uses as its
176/// namespace prefix (`"tatara.pleme.io/"`). Pre-lift the prefix was
177/// spelled inline as a bare `"tatara.pleme.io/"` literal at TWO
178/// substrate-owner sites — [`annotations::GROUP_PREFIX`] +
179/// [`finalizers::GROUP_PREFIX`] — pinned equal to each other by
180/// [`annotations_family_tests::group_prefix_matches_finalizers_group_prefix`]
181/// but with no shared owner binding them to [`GROUP`] itself. A
182/// future rename that shifted the group segment (a
183/// `"tatara.pleme.io/v2/"` migration under a group-segment bump, a
184/// per-fleet override, an alias table) would silently unbind the two
185/// peer families from the CRD [`GROUP`] itself unless every one of
186/// the three inline literals was updated coherently.
187///
188/// Post-lift the prefix lives at ONE substrate owner here; both
189/// [`annotations::GROUP_PREFIX`] and [`finalizers::GROUP_PREFIX`]
190/// route through this const as compile-time aliases
191/// (`pub const GROUP_PREFIX: &str = crate::GROUP_PREFIX;`), so a
192/// rename of the reverse-DNS root lands at ONE `pub const` here + at
193/// [`GROUP`] with the byte-shape pin
194/// [`owner_reference_tests::group_prefix_const_composes_group_slash_bytewise`]
195/// binding the two consts, rather than at three independent per-
196/// module string literals whose coherence relied on convention.
197///
198/// Byte-shape pinned against `format!("{GROUP}/")` by
199/// [`owner_reference_tests::group_prefix_const_composes_group_slash_bytewise`]
200/// (sibling to `api_version_const_composes_group_and_version_bytewise`
201/// on the same GROUP-composition axis) so a rename of [`GROUP`] that
202/// missed this const surfaces HERE rather than as silent skew between
203/// [`GROUP`] (which the [`api_url_prefix`] composer feeds) and every
204/// downstream `<key>.starts_with(GROUP_PREFIX)` gate on the peer
205/// [`annotations::ALL`] / [`finalizers::ALL`] families.
206pub const GROUP_PREFIX: &str = "tatara.pleme.io/";
207/// Kind spelling of the tatara Process CRD as it appears in a K8s
208/// [`OwnerReference.kind`][ownref] field. Peer to [`GROUP`] +
209/// [`VERSION`] — centralizes the ONE literal every SSA-time
210/// re-injection helper pre-lift restated by hand across
211/// `tatara-reconciler` (`render.rs`, `edges.rs`, `ssapply.rs`).
212///
213/// [ownref]: https://kubernetes.io/docs/concepts/overview/working-with-objects/owners-dependents/
214pub const PROCESS_KIND: &str = "Process";
215
216/// Canonical `<GROUP>/<VERSION>` `apiVersion` string as a compile-time
217/// `&'static str` — the ONE typed wire-form binding every tatara CRD
218/// stamps on its own `apiVersion` slot.
219///
220/// Peer to [`GROUP`] + [`VERSION`] on the CRD-group×version axis:
221/// where those two consts own the group segment + the version segment
222/// separately (each addressable in its own right — the [`api_url_prefix`]
223/// composer weaves them into the REST-URL envelope, `#[kube(group = ...,
224/// version = ...)]` derive slots on every tatara CRD struct address
225/// them individually), this const owns the two-segment compose product
226/// every wire-form emit — every K8s `apiVersion:` slot the reconciler
227/// stamps + every [`PROCESS_WIRE_IDENTITY`] projection — routes
228/// through.
229///
230/// Byte-shape pinned against `format!("{GROUP}/{VERSION}")` by
231/// [`owner_reference_tests::api_version_const_composes_group_and_version_bytewise`]
232/// so a rename of [`GROUP`] or a version bump on [`VERSION`] that
233/// missed the const surfaces HERE rather than as silent SSA-apply
234/// skew at every downstream OwnerReference / apiVersion-slot emit
235/// site.
236///
237/// Sibling to the runtime [`api_version`] fn — [`API_VERSION`] is the
238/// `&'static str` typed form (const-callable, feeds
239/// [`PROCESS_WIRE_IDENTITY`]); [`api_version`] returns
240/// [`API_VERSION`]`.to_string()` for owned-String call sites (SSA
241/// re-injection helpers that thread the `apiVersion` slot through a
242/// per-site cloned map).
243pub const API_VERSION: &str = "tatara.pleme.io/v1alpha1";
244
245/// Typed K8s wire-form identity of the tatara `Process` CRD — the
246/// [`k8s_wire_identity::K8sWireIdentity`] projection carrying
247/// `(apiVersion, kind) = (API_VERSION, PROCESS_KIND)` at ONE
248/// compile-time `const`.
249///
250/// Peer on the K8s-wire-form-identity axis-family to the three
251/// pre-existing closed-set `.wire_identity()` projections:
252///
253/// * [`k8s_builtin_resource::K8sBuiltinResource::wire_identity`] owns
254///   the K8s built-in axis (`Job` / `ConfigMap`) — the resources the
255///   reconciler fetches from Kubernetes itself.
256/// * [`flux_resource::FluxResource::wire_identity`] owns the
257///   FluxCD-controller axis (`Kustomization` / `HelmRelease` /
258///   `OCIRepository`).
259/// * [`routing_edge_resource::RoutingEdgeResource::wire_identity`]
260///   owns the routing-edge axis (`Ingress` / `DNSEndpoint`).
261/// * [`PROCESS_WIRE_IDENTITY`] (this const) owns the tatara `Process`
262///   CRD's own wire-form identity — pre-lift the fourth arm was the
263///   open corner every peer closed-set called out in its own docs as
264///   "the tatara `Process` CRD's `(apiVersion, kind)` pair" but which
265///   itself lived only as two disjoint consts + a runtime
266///   [`api_version`] fn threaded through the [`owner_reference_json`]
267///   composer's hand-inlined `json!` slots.
268///
269/// Together the four owners partition every K8s wire-form identity
270/// the workspace's reconcilers reach at run time; the pin
271/// [`owner_reference_tests::process_wire_identity_is_disjoint_from_every_peer_wire_form_axis`]
272/// binds the four axes pairwise-distinct at fail-before-pass-after
273/// granularity so a future variant addition on any peer that
274/// accidentally overlapped this pair (a hypothetical
275/// `K8sBuiltinResource::Process` copy-paste, a Flux-side `Process`
276/// naming collision) surfaces at that pin rather than as silent
277/// cross-axis ambiguity at every reconciler dispatch.
278///
279/// Consumed by [`owner_reference_json`] via
280/// [`k8s_wire_identity::K8sWireIdentity::resource_json`] — pre-lift
281/// the OwnerReference composer hand-inlined the (apiVersion, kind)
282/// pair as two adjacent `json!` slots referencing [`api_version`] +
283/// [`PROCESS_KIND`] separately, leaving a silent-drift path where a
284/// copy-paste that dropped ONE reference (an `apiVersion` bump that
285/// missed the sibling `kind`, a rename of one const that didn't
286/// touch the other) would emit an OwnerReference no K8s controller
287/// recognizes (a 404 at wire time diagnosed as a broken CRD). Post-
288/// lift the emit routes through the ONE typed pair, and the drift
289/// trap is unrepresentable — a caller cannot skew the two slots
290/// because the composer takes the identity as a single struct.
291///
292/// A future consumer of the tatara `Process` wire-form identity — a
293/// second OwnerReference emit site (P3 kenshi-runner's
294/// `TestSuiteBinding` owner-ref, a P1 caixa-tatara-emitted
295/// `HelmRelease`'s parent-Process reference), a future admission-
296/// webhook that filters on the CRD's `(apiVersion, kind)` pair, a
297/// fleet-wide audit walker enumerating every tatara-owned resource —
298/// reads through this ONE const rather than re-composing the pair
299/// from [`API_VERSION`] + [`PROCESS_KIND`] separately.
300///
301/// Theory grounding: THEORY.md §II.1 invariant 5 — composition
302/// preserves proofs. The two-slot (apiVersion, kind) composition
303/// lives at ONE typed algebra projection here; a regression that
304/// drifted either slot surfaces at this module's pins rather than as
305/// silent operator-visible OwnerReference skew. THEORY.md §III —
306/// typescape. The typed [`k8s_wire_identity::K8sWireIdentity`] pair
307/// bounds the axis of variation at the type level — a callsite that
308/// receives a `K8sWireIdentity` cannot skew the two slots at compose
309/// time.
310pub const PROCESS_WIRE_IDENTITY: k8s_wire_identity::K8sWireIdentity =
311    k8s_wire_identity::K8sWireIdentity::new(API_VERSION, PROCESS_KIND);
312
313/// Canonical `<GROUP>/<VERSION>` as an owned `String` — the ONE
314/// K8s `apiVersion` shape every tatara CRD stamps. Delegates to the
315/// compile-time [`API_VERSION`] const so a bump of [`GROUP`] or
316/// [`VERSION`] that missed the const surfaces at
317/// [`owner_reference_tests::api_version_const_composes_group_and_version_bytewise`]
318/// rather than as silent skew between the runtime fn and the typed
319/// [`PROCESS_WIRE_IDENTITY`] const that shares the same wire form.
320///
321/// Pre-lift, two `tatara-reconciler` sites hand-wrote
322/// `format!("{}/{}", tatara_process::GROUP, tatara_process::VERSION)`
323/// while a third inlined the literal `"tatara.pleme.io/v1alpha1"`,
324/// opening a silent drift path if [`VERSION`] ever advances past
325/// `v1alpha1`; both are covered by the ONE substrate owner here.
326pub fn api_version() -> String {
327    API_VERSION.to_string()
328}
329
330/// Canonical `/apis/<GROUP>/<VERSION>/` prefix as an owned `String` —
331/// the ONE K8s REST-path shape every typed `Api::namespaced` /
332/// `Api::all` primitive built off a tatara CRD kind (`Process`,
333/// `ProcessTable`, `EphemeralPool`, `EphemeralAllocation`) emits at
334/// [`kube::Api::resource_url`]. Peer to [`api_version`] — composed
335/// from the SAME [`GROUP`] + [`VERSION`] pair, wrapped in the fixed
336/// `/apis/{…}/` HTTP-path envelope that the K8s API server exposes
337/// every custom-resource group under.
338///
339/// Pre-lift the wire-form literal `"/apis/tatara.pleme.io/v1alpha1/"`
340/// recurred at ELEVEN hand-authored sites across three separate test
341/// modules — six across `tatara-reconciler::context` (`process_api`,
342/// `process_table_api`, `processes_all_api` scope pins), four across
343/// `tatara-pool-reconciler::context` (`pool_api`, `allocation_api`,
344/// `pools_all_api`, `allocations_all_api` scope pins), and one at
345/// `tatara-github-watcher::handler` (`allocation_api` scope pin) —
346/// each restating the same URL prefix a bump of `GROUP` or `VERSION`
347/// would silently miss at every one. Post-lift each of the eleven
348/// sites composes the prefix through this substrate function, so a
349/// future group rename or `v1alpha1` → `v1beta1` bump lands at ONE
350/// composer and the eleven downstream scope guards inherit the shape
351/// mechanically.
352///
353/// Theory anchor: THEORY.md §II.1 invariant 5 — composition preserves
354/// proofs. A regression that drifted the URL prefix at ONE site (a
355/// group typo, a `/apis/` → `/api/` mis-spelling, a stale `v1alpha1`
356/// left behind after a workspace-wide `VERSION` bump) surfaces at the
357/// [`api_url_prefix_tests`] pins below rather than as silent
358/// scope-guard drift between the three reconciler + watcher test
359/// suites (which pre-lift already disagreed with each other on
360/// nothing but were free to drift independently).
361#[must_use]
362pub fn api_url_prefix() -> String {
363    format!("/apis/{GROUP}/{VERSION}/")
364}
365
366/// Substrate-primitive composer for the canonical
367/// **namespace-qualified process reference** — the `<ns>/<name>`
368/// string every consumer that grepped, keyed, or annotated a
369/// Process by "which cluster location owns it" hand-authored as
370/// `format!("{ns}/{name}")` at scattered sites across the workspace.
371/// Lifted onto `tatara-process` (from its prior home at
372/// `tatara_reconciler::ssapply::qualified_process_ref`) so callers
373/// BELOW the reconciler layer — `tatara-export-worker` (which does
374/// NOT depend on `tatara-reconciler`) and `tatara-pool-reconciler` —
375/// reach the SAME composer the reconciler-side sites do, closing
376/// the previously-open substrate corner where a downstream consumer
377/// re-authored the shape by hand rather than routing through the
378/// ONE primitive.
379///
380/// The `<ns>/<name>` shape is the workspace-wide convention for
381/// "how to name a namespaced K8s resource in a single string" — the
382/// same shape the K8s API server itself uses in
383/// [`OwnerReference`][ownref] pretty-printing, in the `holder` slot of
384/// [`crate::table::ClaimRecord`], and in the `tatara.pleme.io/process`
385/// annotation every reconciler-emitted resource carries. Callers
386/// with a live [`crate::prelude::Process`] compose through
387/// [`crate::prelude::Process::coordinates_or_defaults`] +
388/// [`Self`] (this function); callers with bare
389/// `(ns: &str, name: &str)` params (CLI-arg driven binaries,
390/// `metadata`-agnostic composers) call this directly.
391///
392/// The 2-arg signature encodes the invariant "the qualified
393/// reference is EXACTLY `<ns>/<name>`, in that order, joined by a
394/// single `/` separator" at the type level — a caller cannot
395/// accidentally swap the two axes (which would produce `<name>/<ns>`
396/// and silently break every downstream grep) nor omit either half,
397/// the way a pre-lift hand-authored `format!("{name}/{ns}")` or
398/// `format!("{ns}-{name}")` typo would.
399///
400/// A future change to the reference shape — a `<ns>/<name>@<gen>`
401/// multi-generation variant for attestation grepping, a
402/// `<cluster>/<ns>/<name>` cross-cluster form, a normalization
403/// (case-fold, unicode-safe collation) that must apply everywhere —
404/// lands at ONE substrate function here and every downstream
405/// composer (annotation seed, ProcessTable claim key, label
406/// selector, owner metadata, export-worker run-id fallback,
407/// receipt-owner filter) inherits the upgrade mechanically.
408///
409/// Theory anchor: THEORY.md §VI.1 (generation over composition —
410/// the `<ns>/<name>` shape recurred at hand-authored sites past the
411/// ★★ PRIME-DIRECTIVE ≥ 2 duplication trigger, and is lifted onto
412/// the ONE workspace-wide owner here). THEORY.md §II.1 invariant 5
413/// (composition preserves proofs — a regression that swapped the
414/// two axes or the separator at ONE site surfaces at
415/// [`qualified_process_ref_tests::qualified_process_ref_joins_ns_and_name_with_slash`]
416/// rather than as silent drift at every downstream annotation seed
417/// / claim key / label selector / run-id / receipt-owner filter).
418///
419/// [ownref]: https://kubernetes.io/docs/concepts/overview/working-with-objects/owners-dependents/
420#[must_use]
421pub fn qualified_process_ref(ns: &str, name: &str) -> String {
422    format!("{ns}/{name}")
423}
424
425/// Substrate-primitive composer for the workspace-canonical
426/// **`<verb> <Kind> <ns>/<name>`** diagnostic-body head every
427/// per-Kind [`error_ctx`][crate::configmap::error_ctx] peer wraps
428/// around a wire-verb failure against a namespaced K8s resource
429/// (through [`crate::kube_error::KubeResultExt::kube_ctx_with`] on
430/// the reconciler-boundary consumers or through
431/// [`anyhow::Context::with_context`] on the export-worker
432/// consumers).
433///
434/// Owns the fixed 4-slot shape at ONE substrate site, routing the
435/// `<ns>/<name>` join through the workspace-wide
436/// [`qualified_process_ref`] composer so a future normalization of
437/// the qualified-ref shape (case-fold, unicode collation, IDN) lands
438/// at ONE site and every per-Kind diagnostic body picks it up
439/// mechanically.
440///
441/// Pre-lift the 4-slot shape recurred at TWO peer per-Kind
442/// composers in this crate past the ★★ PRIME-DIRECTIVE ≥ 2
443/// duplication threshold, each restating the SAME
444/// `format!("{verb} <Kind> {}", qualified_process_ref(ns, name))`
445/// incantation with only the fixed `<Kind>` literal differing:
446///
447/// * [`crate::configmap::error_ctx`] — the ConfigMap-axis per-Kind
448///   composer (`<Kind> = "ConfigMap"`), routing the closed-loop
449///   probe's receipt-CM writer + the export-worker's SSA-side
450///   ConfigMap writer through ONE substrate slug.
451/// * [`crate::process_api::error_ctx`] — the tatara-CRD
452///   Process-axis per-Kind composer (`<Kind> = "Process"`), routing
453///   the reconciler-boundary ProcessPhase evaluator + the
454///   export-worker's ProcessSnapshotSource reader through ONE
455///   substrate slug.
456///
457/// Both peers walked the SAME 4-slot shape — take a verb, a fixed
458/// `&'static str` per-Kind literal (`"ConfigMap"` / `"Process"`),
459/// and the target resource's namespace + name — and produced the
460/// SAME `"<verb> <Kind> <ns>/<name>"` diagnostic head. Post-lift
461/// each per-Kind composer reads
462/// `crate::qualified_error_ctx(<verb>, "<Kind>", ns, name)` as a
463/// one-line delegate, and the shared 4-slot shape lives at ONE
464/// substrate owner here. A future third + fourth per-Kind composer
465/// (a `crate::secret::error_ctx` for the K8s `Secret` axis, a
466/// `crate::job::error_ctx` for the `batch/v1::Job` axis a future
467/// `ConditionKind::JobAttested` companion reader might open, a
468/// `crate::helm_release::error_ctx` for the FluxCD `HelmRelease`
469/// axis the P2 reconciler already emits) inherits the 4-slot shape
470/// through THIS composer, pinning only its own `&'static str` Kind
471/// literal.
472///
473/// ### Naming — `qualified_error_ctx`, not `error_ctx`
474///
475/// The bare `error_ctx` name is already taken at each per-Kind
476/// composer's module ([`crate::configmap::error_ctx`],
477/// [`crate::process_api::error_ctx`], [`crate::list::error_ctx`]),
478/// each closing its own per-Kind or per-verb axis. This composer's
479/// `qualified_error_ctx` name is deliberately distinct so a caller
480/// with any of the per-Kind modules in scope cannot resolve to the
481/// wrong composer by accident (which would silently drop the
482/// per-Kind literal at the callsite). The `qualified_` prefix names
483/// the routing invariant: the `<ns>/<name>` join at the composer's
484/// tail rides through [`qualified_process_ref`], the SAME workspace-
485/// wide substrate every per-Kind peer already routes through.
486///
487/// ### 4-slot shape, not 3
488///
489/// The `kind` slot is required — the pre-lift per-Kind composers
490/// hard-coded their Kind literal as a `&'static str` at each
491/// `format!` chain, and post-lift the composer keeps that Kind
492/// literal at the caller so the K8s-canonical TitleCase spelling
493/// stays visible in the callsite's grep footprint. A future
494/// caller with a dynamically-composed Kind slot (a CRD-family
495/// walker that renders errors for every `ProcessTable` /
496/// `EphemeralPool` / `EphemeralAllocation` variant at one call)
497/// still reaches through this same 4-slot signature — the `&str`
498/// bound on `kind` accepts both `&'static str` literals (the
499/// per-Kind peer shape) and runtime-composed `&str` slices (the
500/// dynamic-Kind walker shape).
501///
502/// ### `#[must_use]`
503///
504/// The returned `String` is consumed by [`crate::kube_error::
505/// KubeResultExt::kube_ctx_with`], by
506/// [`anyhow::Context::with_context`]'s owned-`String`-returning
507/// closure form, or by the sibling [`crate::err_ctx::ErrCtxExt::
508/// err_ctx_with`] owned-string escape hatch. Dropping the return
509/// silently drops the diagnostic head entirely, which is never the
510/// intended semantic at any pre-lift or post-lift consumer.
511///
512/// Theory anchor: THEORY.md §VI.1 (generation over composition —
513/// the 4-slot `<verb> <Kind> <ns>/<name>` shape recurred at 2 peer
514/// per-Kind composers past the ★★ PRIME-DIRECTIVE ≥ 2 duplication
515/// trigger, and is lifted onto the ONE workspace-wide substrate
516/// owner here). THEORY.md §II.1 invariant 5 (composition preserves
517/// proofs — a regression that reordered the head slots, dropped
518/// the fixed `<Kind>` word, or routed the `<ns>/<name>` join
519/// through a bare inline `format!` — bypassing
520/// [`qualified_process_ref`] — surfaces at
521/// [`qualified_error_ctx_tests`] rather than as silent drift across
522/// every per-Kind diagnostic body and every future per-Kind peer
523/// that opens on this composer).
524#[must_use]
525pub fn qualified_error_ctx(verb: &str, kind: &str, ns: &str, name: &str) -> String {
526    format!("{verb} {kind} {}", qualified_process_ref(ns, name))
527}
528
529/// Build a Kubernetes [`OwnerReference`][ownref] JSON blob pointing
530/// at a Process (`kind = `[`PROCESS_KIND`], `apiVersion = `
531/// [`api_version`]) with `controller: true` +
532/// `blockOwnerDeletion: true` — the exact 6-slot shape every SSA
533/// re-injection site pre-lift restated three times across
534/// `tatara-reconciler` (`render.rs::owner_refs` for export-Job
535/// owners, `edges.rs::build_owner_refs` for Ingress + DNSEndpoint
536/// owners, `ssapply.rs::build_owner_reference` for the injected
537/// owner-ref stamped on every applied `DynamicObject`). Callers
538/// with a live `Process` value read `metadata.{name,uid}` and pass
539/// them through as `&str`.
540///
541/// The 6-slot shape is fixed (`controller` + `blockOwnerDeletion`
542/// both `true`); a Process-owned resource that wants a non-
543/// controller reference doesn't belong on this owner and can build
544/// its own `json!` inline — this primitive is the composer for the
545/// canonical "Process controls this resource, cascade-delete on
546/// GC" shape, not a general OwnerReference builder.
547///
548/// [ownref]: https://kubernetes.io/docs/concepts/overview/working-with-objects/owners-dependents/
549pub fn owner_reference_json(name: &str, uid: &str) -> serde_json::Value {
550    // Route the (apiVersion, kind) pair through the ONE typed
551    // wire-identity const [`PROCESS_WIRE_IDENTITY`] via
552    // [`k8s_wire_identity::K8sWireIdentity::resource_json`] — the
553    // composer stamps the identity slots on top of the caller's
554    // 4-slot extras map (name / uid / controller / blockOwnerDeletion)
555    // and the identity slots win over any accidental extras collision
556    // by construction. Pre-lift the two identity slots were hand-
557    // inlined as adjacent `json!` slots referencing `api_version()` +
558    // `PROCESS_KIND` separately, so a copy-paste that dropped one
559    // reference (or drifted one const under a group rename) would
560    // silently emit an OwnerReference no K8s controller recognizes.
561    // Post-lift the wire-form pair binds structurally at ONE typed
562    // [`PROCESS_WIRE_IDENTITY`] const and the drift trap is
563    // unrepresentable.
564    PROCESS_WIRE_IDENTITY.resource_json(serde_json::json!({
565        "name": name,
566        "uid": uid,
567        "controller": true,
568        "blockOwnerDeletion": true,
569    }))
570}
571
572/// Substrate-primitive builder for a Process-owned resource's
573/// **`metadata.ownerReferences` array** — the empty-uid-gated,
574/// single-entry `Vec<Value>` every emit site that lacks a fully
575/// materialized [`crate::prelude::Process`] (i.e. every site that
576/// works from a bare `(name, uid)` pair rather than routing through
577/// [`ssapply::build_owner_reference`](../tatara_reconciler/ssapply/fn.build_owner_reference.html)'s
578/// anyhow-guarded unwrap) hand-composed by wrapping
579/// [`owner_reference_json`] in a `Vec::new()` + `is_empty` gate on
580/// the `uid` slot.
581///
582/// The `uid.is_empty()` gate encodes the invariant every caller
583/// already enforced: a Process pre-metadata (fixtured in tests, or
584/// caught mid-Forking before the API server has stamped a `uid`) has
585/// no admissible owner reference to point at, so the emit site
586/// stamps `metadata.ownerReferences: []` rather than an
587/// owner-referenceless resource pointing at a placeholder uid the K8s
588/// GC would silently ignore. Post-lift the gate lives at ONE
589/// primitive so a regression that inlined an owner reference for
590/// an empty uid — which the API server accepts and quietly detaches
591/// from cascade-delete — surfaces at THIS primitive's pin rather
592/// than as an operator-visible ownerless resource after apply.
593///
594/// Pre-lift the 3-line `let mut owner_refs = vec![]; if
595/// !uid.is_empty() { owner_refs.push(owner_reference_json(name,
596/// uid)); }` incantation was hand-authored at TWO sites past the
597/// ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold in
598/// `tatara-reconciler`, each restating the same gated composition:
599/// * `edges::build_owner_refs` — the shared owner-refs builder both
600///   `IngressEdge` + `DnsEndpointEdge` route through, sourcing
601///   `(process_name, process_uid)` from the [`crate::edges::EdgeContext`].
602/// * `render::one_export_job` — the export Job's owner-refs seed,
603///   sourcing `(name, uid)` from the [`crate::prelude::Process`]
604///   `render_export_jobs` threaded in.
605///
606/// Post-lift both callsites read `owner_references_json(name, uid)`.
607/// A future addition — e.g. a second owner-reference slot naming a
608/// controlling ProcessTable entry, a policy that stamps a stale-uid
609/// warning annotation before returning empty, or a normalization
610/// that strips a cluster-prefix off the uid — lands at ONE
611/// substrate function here and every emit site inherits the upgrade
612/// mechanically. The [`ssapply::build_owner_reference`] path (which
613/// works from a materialized [`crate::prelude::Process`] and errors
614/// on absent `metadata.uid`) is a peer, not a lift candidate: its
615/// contract is "the K8s API server assigned a uid, so refuse to
616/// SSA-apply resources whose owner cannot be materialized", while
617/// this primitive's contract is "the caller has an optional-uid
618/// posture; emit `[]` when the uid is absent". The two shapes
619/// partition the input space at the "is the enclosing scope
620/// obligated to produce a materialized Process reference" axis.
621///
622/// The 2-arg `(&str, &str)` signature accepts both the
623/// `EdgeContext`-sourced `(&str, &str)` slice shape and the
624/// `render_export_jobs`-owned `(name: &str, uid: &str)` local shape
625/// without widening — matches every current callsite.
626pub fn owner_references_json(name: &str, uid: &str) -> Vec<serde_json::Value> {
627    if uid.is_empty() {
628        vec![]
629    } else {
630        vec![owner_reference_json(name, uid)]
631    }
632}
633
634/// Substrate-primitive trait for the **`Api::namespaced`-shaped
635/// coordinate extraction** every tatara-CRD reconciler restated by
636/// hand at its top-level `reconcile` dispatcher: pull owned `String`
637/// forms of `metadata.namespace` and `metadata.name` and refuse to
638/// substitute a workspace-wide default for either slot, because the
639/// caller is about to feed the pair positionally into
640/// `Api::namespaced(client, &ns)` + `Api::patch(&name, …)` and the
641/// K8s API server refuses an empty-string name / namespace path
642/// segment.
643///
644/// Pre-lift the 5-line `.metadata.<slot>.clone().ok_or_else(||
645/// anyhow!("<Kind> has no metadata.<slot>"))?` chain (paired at both
646/// slots inside every controller's `reconcile_inner`) was hand-
647/// authored at TWO sites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication
648/// threshold in `tatara-pool-reconciler`, each restating the SAME
649/// (`namespace` errors, then `name` errors, both owned `String`)
650/// contract on a different CRD:
651/// * `controller_pool::reconcile_inner` — the pool reconciler's
652///   top-level `Pool has no metadata.{namespace,name}` gate,
653///   funneling every subsequent `Api::namespaced` + `Api::patch` call
654///   through the extracted `(ns, name)` pair.
655/// * `controller_allocation::reconcile_inner` — the allocation
656///   reconciler's peer gate on `EphemeralAllocation`, funneling the
657///   `Api::namespaced` + `Api::patch_status` calls that follow.
658///
659/// Both sites walked the SAME 5-line paired chain and both wanted the
660/// `(String, String)` form the primitive returns — because the
661/// produced `ns` outlives the source-object borrow (it feeds
662/// `Api::namespaced(client, &ns)` and later log-line interpolations
663/// across a stretch of `.await` points) and the `name` similarly
664/// threads through `Api::patch(&name, …)` calls downstream. Post-lift
665/// each callsite reads `pool.owned_coordinates_required()?` /
666/// `alloc.owned_coordinates_required()?` and the produced tuple
667/// destructures into the same downstream slots unchanged.
668///
669/// The blanket impl over `kube::Resource<DynamicType = ()>` (which
670/// every `#[derive(CustomResource)]`-generated tatara CRD satisfies)
671/// closes the substrate corner ONCE for the entire workspace: adding
672/// a third or fourth CRD in a peer crate — a routing-edge object, a
673/// receipt registry — inherits the extractor for free at its own
674/// `reconcile_inner` dispatcher with zero per-CRD lift work. This is
675/// the direction the CSE Compounding Directive names by
676/// "solve once, load-bearing fixes only": the primitive lands once
677/// and every downstream controller pattern-matches into it without
678/// re-authoring the chain.
679///
680/// Peer to [`crate::prelude::Process::owned_coordinates_or_err`] on
681/// the (`Process`-specific × namespace-required) axis pair — the two
682/// primitives partition the workspace's owned-form coordinate
683/// extraction on the `namespace-required` axis and cover the
684/// per-CRD needs they were opened for:
685///
686/// * ns-defaulted, name-required, `Process`-inherent →
687///   [`crate::prelude::Process::owned_coordinates_or_err`]
688///   (`tatara-reconciler`'s `phase_machine` / `signals` callers —
689///   consumers whose downstream tolerates the workspace's
690///   [`crate::prelude::Process::DEFAULT_NAMESPACE`] substitute for a
691///   `Process` fixtured pre-namespace-defaulting).
692/// * ns-required + name-required, blanket over every CRD → **this
693///   method** (`tatara-pool-reconciler`'s pool + allocation reconciler
694///   callers — consumers whose downstream refuses BOTH substitutions
695///   because the `Api::namespaced` dispatcher expects a real path
696///   segment on each axis and the enclosing controller is not
697///   authored to run against a namespace-less pool / allocation).
698///
699/// The error strings are shaped as `"{Kind} has no metadata.{slot}"`
700/// with `{Kind}` pulled positionally from `Self::kind(&())` (the
701/// kube-rs canonical CRD kind — `"EphemeralPool"` / `"EphemeralAllocation"`
702/// — which matches `kubectl get ephemeralpools|ephemeralallocations`
703/// output verbatim rather than the pre-lift `"Pool"` / `"Allocation"`
704/// short-forms every callsite hard-coded by hand). Routing the type
705/// name through `Self::kind` closes the drift path where a future
706/// CRD rename or a copy-paste consumer inherited the wrong short-
707/// form; the K8s-kind spelling is the ONE canonical name every
708/// operator-facing surface (kubectl output, RBAC subject strings,
709/// audit-log entries) already uses, so a log-line consumer greppping
710/// for either kind hits the primitive's canonical spelling directly.
711///
712/// A future normalization step (a per-CRD namespace canonicalization
713/// pass — case-fold, unicode-safe path-segment validation, a shared
714/// [`crate::prelude::Process::DEFAULT_NAMESPACE`]-aware fallback
715/// mode gated by an argument) lands at ONE substrate trait method
716/// here and every downstream reconciler picks up the upgrade
717/// mechanically — no per-callsite hand-edit at `controller_pool` /
718/// `controller_allocation` / any future CRD's `reconcile_inner`.
719///
720/// Theory anchor: THEORY.md §VI.1 (generation over composition —
721/// the paired 5-line `.metadata.<slot>.clone().ok_or_else` chain
722/// recurred at two hand-authored sites past the ★★ PRIME-DIRECTIVE
723/// ≥ 2 duplication trigger, and is lifted onto ONE trait method
724/// here). THEORY.md §II.1 invariant 5 (composition preserves
725/// proofs — the pins bind the missing-namespace corner, the
726/// missing-name corner, the missing-both corner (namespace error
727/// wins), the both-slots-present happy path, AND the
728/// `Self::kind`-driven error-string spelling per CRD, so a
729/// regression that reordered the two `ok_or_else` gates or drifted
730/// the error prefix surfaces at `tests::owned_coordinates_required_*`
731/// rather than as silent operator-facing skew between the two
732/// reconcilers' top-level error-message shapes).
733pub trait NamespacedApiCoordinates: kube::Resource<DynamicType = ()> {
734    /// Extract the K8s API path coordinates as owned `String`s,
735    /// erroring with a `Self::kind`-prefixed message when either
736    /// slot is absent. See the trait-level docs for the axis-family
737    /// context, peer primitives, and future-normalization anchor.
738    fn owned_coordinates_required(&self) -> anyhow::Result<(String, String)> {
739        let meta = self.meta();
740        let ns = meta
741            .namespace
742            .clone()
743            .ok_or_else(|| anyhow::anyhow!("{} has no metadata.namespace", Self::kind(&())))?;
744        let name = meta
745            .name
746            .clone()
747            .ok_or_else(|| anyhow::anyhow!("{} has no metadata.name", Self::kind(&())))?;
748        Ok((ns, name))
749    }
750}
751
752impl<T> NamespacedApiCoordinates for T where T: kube::Resource<DynamicType = ()> {}
753
754/// Substrate-primitive trait for the **deletion-tombstone presence
755/// probe** every tatara CRD reconciler restated as
756/// `.metadata.deletion_timestamp.is_some()` on the K8s-API-server-
757/// stamped `metadata.deletionTimestamp` slot: a `true` reading means
758/// the API server has accepted a DELETE and finalizers are draining
759/// (the object is still live but the controller must move into its
760/// SIGTERM cascade / DELETE-skip branch), while a `false` reading
761/// means no delete is in flight.
762///
763/// Pre-lift the ONE-line `.metadata.deletion_timestamp.is_some()`
764/// chain was hand-authored across every tatara-process CRD in
765/// consumer crates and independently re-authored as byte-identical
766/// inherent methods on [`crate::prelude::Process`] +
767/// [`crate::prelude::EphemeralPool`], with the sister CRD
768/// [`crate::prelude::EphemeralAllocation`] still on the raw chain in
769/// `tatara-pool-reconciler::allocation_decide::AllocationConvergenceCtx::observe`.
770/// That's TWO byte-identical inherent implementations past the ★★
771/// PRIME-DIRECTIVE ≥ 2 duplication threshold on the substrate side
772/// PLUS the hand-authored chain on the third CRD — three surfaces
773/// spelling the SAME projection, each with the same drift risk (a
774/// stale-tombstone grace-period gate, a paused-controller
775/// canonicalization, a cross-cluster clock-skew guard would have to
776/// land at every surface plus stay coherent).
777///
778/// Post-lift the substrate owns the probe at ONE trait method with a
779/// blanket impl over every `kube::Resource<DynamicType = ()>`, so:
780/// * [`crate::prelude::EphemeralAllocation`] inherits the probe for
781///   free — its `allocation_decide.rs` hand-authored chain routes
782///   through `alloc.is_being_deleted()` post-lift, closing the
783///   third-CRD gap noted in the [`crate::prelude::EphemeralPool::is_being_deleted`]
784///   commit body (`7f8f104`).
785/// * Any future tatara CRD (a routing-edge object, a receipt
786///   registry, a fleet-wide claim registry) inherits the probe at
787///   its own `reconcile_inner` dispatcher with zero per-CRD lift
788///   work — the same solve-once discipline
789///   [`NamespacedApiCoordinates`] established for the paired
790///   coordinate extractor.
791///
792/// The two existing inherent methods
793/// ([`crate::prelude::Process::is_being_deleted`] +
794/// [`crate::prelude::EphemeralPool::is_being_deleted`]) are peers
795/// rather than lift casualties: Rust method resolution prefers the
796/// inherent over the trait's blanket, so every existing callsite
797/// keeps hitting the same code path. The trait's blanket impl
798/// closes the substrate corner for CRDs WITHOUT the inherent — the
799/// coherence tests pin that the trait and the two inherents produce
800/// byte-identical results across every corner of the (missing,
801/// present) input matrix, so a future rewrite that consolidates
802/// onto the trait doesn't skew any consumer.
803///
804/// Return-form axis: `bool` matches the copy-form discipline of the
805/// two inherent peers and of [`crate::prelude::Process::observed_phase`]
806/// — the underlying wire-format slot is an `Option<Time>` carrying
807/// only presence information at this axis (the RFC-3339 timestamp
808/// payload itself is not what the callers read; all just probe
809/// presence to detect the tombstone-stamped state).
810///
811/// A future normalization step (a per-tombstone staleness gate
812/// returning `false` for a tombstone older than the reconciler's
813/// grace-period budget, a paused-controller tombstone
814/// canonicalization, a cross-cluster tombstone-observation clock
815/// skew guard) lands at ONE substrate trait method here — the two
816/// inherent forwarders inherit the upgrade mechanically if they are
817/// rewired to `<Self as DeletionTombstoned>::is_being_deleted(self)`
818/// as a follow-up sweep, and every downstream consumer that already
819/// routes through this trait picks it up without a per-callsite
820/// hand-edit.
821///
822/// Theory anchor: THEORY.md §VI.1 (generation over composition —
823/// the `.metadata.deletion_timestamp.is_some()` projection recurred
824/// as TWO byte-identical inherent implementations on
825/// [`crate::prelude::Process`] + [`crate::prelude::EphemeralPool`]
826/// past the ★★ PRIME-DIRECTIVE ≥ 2 duplication trigger and is
827/// lifted onto ONE trait method here). THEORY.md §II.1 invariant 5
828/// (composition preserves proofs — the pins bind the missing-
829/// tombstone corner + the present-tombstone corner + the copy-form
830/// `bool` return + the byte-identical parity with the pre-lift
831/// `.is_some()` chain + cross-CRD coherence with both inherent
832/// forwarders on the SAME `Process` / `EphemeralPool` value, so a
833/// regression that skewed either surface surfaces at
834/// `deletion_tombstoned_tests::*` rather than as silent operator-
835/// facing skew between the top-level dispatcher's SIGTERM preempt,
836/// the SIGTERM cascade's child-fan-out DELETE-skip, the pool
837/// reconciler's Drain gate, and the allocation reconciler's release
838/// short-circuit on three sibling CRDs.
839pub trait DeletionTombstoned: kube::Resource<DynamicType = ()> {
840    /// True iff the K8s API server has stamped `metadata.deletionTimestamp`
841    /// on this resource — a DELETE is in flight and finalizers are
842    /// draining. See the trait-level docs for the axis-family context,
843    /// peer inherent methods, and future-normalization anchor.
844    fn is_being_deleted(&self) -> bool {
845        self.meta().deletion_timestamp.is_some()
846    }
847}
848
849impl<T> DeletionTombstoned for T where T: kube::Resource<DynamicType = ()> {}
850
851/// Substrate-primitive trait for the ONE **borrow-form annotation
852/// lookup** every tatara CRD reconciler restated as the 3-line
853/// `.metadata.annotations.as_ref().and_then(|m| m.get(key)).map(String::as_str)`
854/// chain (or a `.cloned()` / `.cloned().unwrap_or_default()` variant
855/// of the same shape) on the K8s `metadata.annotations` map: returns
856/// `Some(&str)` iff the annotations block is present AND the key is
857/// present inside it; both missing corners collapse to `None`.
858///
859/// Peer to [`DeletionTombstoned`] + [`NamespacedApiCoordinates`] on
860/// the substrate-primitive-trait axis (kube-Resource blanket impls
861/// over `DynamicType = ()`), and peer to the pre-existing
862/// [`crate::prelude::Process::annotation`] inherent forwarder on the
863/// axis of "one annotation-lookup shape shared across every kube
864/// resource, tatara CRD or K8s built-in". The inherent stays as a
865/// peer — Rust method resolution prefers an inherent over a trait's
866/// blanket impl, so the three consumers already routed through
867/// `Process::annotation`
868/// (`tatara-reconciler::signals::ingest`,
869/// `tatara-reconciler::phase_machine::released_from_annotation`,
870/// `tatara-pool-reconciler::controller_pool::process_belongs_to_pool`)
871/// keep hitting the byte-identical code path — and the trait's
872/// blanket impl closes the substrate corner for kube resources
873/// WITHOUT the inherent: post-lift the hand-authored
874/// `.metadata.annotations.as_ref().and_then(|m| m.get(KEY))...` chain
875/// in `tatara-export-worker::main` (on `k8s_openapi`'s `ConfigMap`,
876/// which has no tatara-owned inherent) routes through the trait at
877/// `cm.annotation(KEY)`, and any future `EphemeralPool` /
878/// `EphemeralAllocation` (or new tatara CRD) consumer that needs an
879/// annotation lookup inherits the primitive for free — the same
880/// solve-once discipline the two peer traits already established.
881///
882/// Return-form axis: `Option<&str>` matches the borrow-first
883/// discipline of the peer metadata primitives
884/// ([`crate::prelude::Process::namespace_or_default`],
885/// [`crate::prelude::Process::name_or_placeholder`],
886/// [`crate::prelude::Process::coordinates_or_none`], and the inherent
887/// [`crate::prelude::Process::annotation`] this trait mirrors). The
888/// two corners the pre-lift chain swallowed (missing `annotations`
889/// map, missing key inside the map) BOTH collapse to `None` so
890/// `.is_some()` / `if let Some(_)` / `Option::map` behave identically
891/// on a resource whose annotations block is `None` and on one whose
892/// annotations block is populated but omits the key — matching what
893/// the pre-lift `.and_then(...)` chain produced.
894///
895/// A future normalization step (a key-canonicalization pass, a
896/// case-fold lookup, a per-key alias table for renamed annotations
897/// across API versions, a per-namespace override substrate) lands at
898/// ONE trait method here and every downstream consumer — the four
899/// current sites plus every future CRD reconciler that inherits the
900/// blanket impl — picks up the upgrade mechanically. If the inherent
901/// is ever rewired to `<Self as Annotated>::annotation(self, key)`
902/// as a follow-up sweep, the three inherent-preferred callsites
903/// automatically inherit any trait-level upgrade too.
904///
905/// Theory anchor: THEORY.md §VI.1 (generation over composition —
906/// the annotation-lookup shape recurred as ONE inherent forwarder on
907/// `Process` PLUS a hand-authored chain on `ConfigMap` past the
908/// ★★ PRIME-DIRECTIVE ≥ 2 duplication trigger, and is lifted onto
909/// ONE trait method here). THEORY.md §II.1 invariant 5 (composition
910/// preserves proofs — the pins bind the missing-annotations corner +
911/// the missing-key corner + the borrow-form `&str` lifetime + the
912/// byte-identical parity with the pre-lift 3-line chain + the
913/// cross-primitive coherence with `Process::annotation` on the SAME
914/// `Process` value, so a regression that skewed either surface
915/// surfaces at `annotated_tests::*` rather than as silent operator-
916/// facing skew between the SIGNAL / RELEASED_FROM / POOL annotation
917/// readers on Process and the receipts-owner filter on ConfigMap).
918pub trait Annotated: kube::Resource<DynamicType = ()> {
919    /// Borrow one key from `metadata.annotations`. See the trait-level
920    /// docs for the axis-family context, peer inherent method, and
921    /// future-normalization anchor.
922    fn annotation(&self, key: &str) -> Option<&str> {
923        self.meta()
924            .annotations
925            .as_ref()
926            .and_then(|m| m.get(key))
927            .map(String::as_str)
928    }
929}
930
931impl<T> Annotated for T where T: kube::Resource<DynamicType = ()> {}
932
933/// Substrate-primitive trait for the **place-in-namespace** fluent
934/// builder every consumer of a `kube::Resource` restated as
935/// `let mut cr = <CRD>::new(name, spec); cr.meta_mut().namespace = Some(ns.into()); cr`
936/// on the freshly-minted resource whose derive-supplied
937/// `::new(name, spec)` constructor stamps `metadata.name` alone and
938/// leaves `metadata.namespace` at `None`.
939///
940/// Pre-lift the pattern was hand-authored across THREE tatara-owned
941/// axes past the ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold:
942///
943/// * `tatara-reconciler::render::tests::render_through_top_level_intent_dispatch`
944///   — the ONE remaining hand-authored site on the `Process` CRD
945///   (the sibling `Process::new_in` was not opened in the prior
946///   pool/allocation sweep because no `Process`-side pool fixture
947///   restated the pattern at ≥ 2 sites in isolation).
948/// * [`crate::pool::EphemeralPool::new_in`] — a per-CRD inherent
949///   composer opened in commit `a5dbb26` that inlined the identical
950///   `Self::new(name, spec); metadata.namespace = Some(namespace.into())`
951///   body on the `EphemeralPool` axis.
952/// * [`crate::allocation::EphemeralAllocation::new_in`] — the sister
953///   inherent composer opened in the same commit on the
954///   `EphemeralAllocation` axis with the byte-identical body.
955///
956/// Post-lift the substrate owns the `metadata.namespace` stamp at
957/// ONE trait method with a blanket impl over every
958/// `kube::Resource<DynamicType = ()>`, so:
959///
960/// * The two per-CRD `new_in` composers forward through
961///   `Self::new(name, spec).in_namespace(namespace)` — three
962///   substrate copies of the mutation collapse to one. The
963///   composers keep their ergonomic per-CRD signatures so existing
964///   callers stay unchanged; only the body threads through here.
965/// * The `tatara-reconciler::render` fixture routes through
966///   `Process::new(...).in_namespace(...)` on the SAME trait method,
967///   closing the last hand-authored site on the tatara CRD trio.
968/// * Any future tatara CRD (a routing-edge object, a receipt
969///   registry, a fleet-wide claim registry) inherits the builder at
970///   its own operator-facing factory + its own test-fixture site
971///   with zero per-CRD lift work — the same solve-once discipline
972///   [`NamespacedApiCoordinates`] established for the paired
973///   coordinate extractor and [`DeletionTombstoned`] established
974///   for the deletion-tombstone probe.
975/// * Any K8s built-in CRD (`ConfigMap`, `Job`, `Ingress`) inherits
976///   the builder too — the sibling [`Annotated`] blanket already
977///   covers the same category on the annotation-read axis, so an
978///   emitter that composes a `ConfigMap` in a specific namespace can
979///   now write `<owner-composer>().in_namespace(ns)` on the SAME
980///   finished value.
981///
982/// Return-form axis: `Self` (owned, by-value) — the builder
983/// consumes `self` and returns the mutated value so chained
984/// composers read left-to-right as `<CRD>::new(name, spec)
985/// .in_namespace(ns)` in the ONE natural composition order operators
986/// reach for. Peer to the borrow-form observer
987/// [`Annotated::annotation`] on the (mutation direction ×
988/// ObjectMeta-slot family) axis pair; both traits close their
989/// respective ObjectMeta-slot corners at ONE trait method with a
990/// blanket impl over the SAME `kube::Resource<DynamicType = ()>`
991/// bound so a future consumer that alternates between reading an
992/// annotation and stamping a namespace never sees two different
993/// trait-import spellings.
994///
995/// A future normalization step (a per-fleet virtual-cluster prefix
996/// rewrite on the `namespace` slot, a per-cluster canonical
997/// case-fold pass, an operator-scoped default namespace for
998/// cluster-local test rigs, a promotion to a typed `Namespace`
999/// newtype that carries K8s DNS-1123 validation as a phantom-type
1000/// guard) lands at ONE substrate trait method here — every
1001/// downstream consumer routed through `.in_namespace(...)` picks up
1002/// the upgrade mechanically, and the two per-CRD `new_in` composers
1003/// inherit it for free through their one-line forwarders.
1004///
1005/// Theory anchor: THEORY.md §II.1 invariant 5 (composition preserves
1006/// proofs — the pins bind `<CRD>::new(name, spec).in_namespace(ns)
1007/// .metadata.namespace == Some(ns.to_string())` on every corner of
1008/// the (CRD ∈ {`Process`, `EphemeralPool`, `EphemeralAllocation`,
1009/// `ConfigMap`} × input form ∈ {`&str`, `String`}) input matrix
1010/// PLUS the overwrite corner where `.in_namespace(a).in_namespace(b)`
1011/// binds `b`, so a regression that skewed either surface surfaces
1012/// at `placed_in_namespace_tests::*` rather than as silent
1013/// operator-facing skew between the tatara-reconciler render
1014/// fixture, the two per-CRD `new_in` composers, and any future
1015/// CRD-adjacent namespace-stamping consumer). THEORY.md §VI.1
1016/// (generation over composition — the mutation recurred as three
1017/// substrate copies past the ★★ PRIME-DIRECTIVE ≥ 2 duplication
1018/// trigger).
1019pub trait PlacedInNamespace: kube::Resource<DynamicType = ()> + Sized {
1020    /// Stamp `namespace` onto `self.metadata.namespace` and return
1021    /// the mutated value by-value. See the trait-level docs for the
1022    /// axis-family context, peer trait, and future-normalization
1023    /// anchor.
1024    #[must_use]
1025    fn in_namespace(mut self, namespace: impl Into<String>) -> Self {
1026        self.meta_mut().namespace = Some(namespace.into());
1027        self
1028    }
1029}
1030
1031impl<T> PlacedInNamespace for T where T: kube::Resource<DynamicType = ()> {}
1032
1033/// Annotation keys the reconciler reads/writes on owned FluxCD resources.
1034pub mod annotations {
1035    pub const MANAGED_BY: &str = "tatara.pleme.io/managed-by";
1036    pub const PROCESS: &str = "tatara.pleme.io/process";
1037    pub const PID: &str = "tatara.pleme.io/pid";
1038    pub const CONTENT_HASH: &str = "tatara.pleme.io/content-hash";
1039    pub const ATTESTATION_ROOT: &str = "tatara.pleme.io/attestation-root";
1040    pub const GENERATION: &str = "tatara.pleme.io/generation";
1041    pub const SIGNAL: &str = "tatara.pleme.io/signal";
1042    /// Stamped by the reconciler when transitioning into `Releasing`
1043    /// — records which terminal-reached gate the Process came from
1044    /// (`Attested` or `Failed`) so `handle_releasing` can pick the
1045    /// matching `ExportTrigger` set + the correct post-Releasing
1046    /// destination (`Exiting` from Attested, `Zombie` from Failed).
1047    pub const RELEASED_FROM: &str = "tatara.pleme.io/released-from";
1048    /// Labels the export-worker Jobs the reconciler emits during
1049    /// `Releasing`. Selector: `tatara.pleme.io/role=export`.
1050    pub const ROLE: &str = "tatara.pleme.io/role";
1051    /// Index of an export inside `lifetime.ephemeral.exports`.
1052    /// Stamped on the corresponding tatara-export-worker Job + its
1053    /// receipt ConfigMap so the reconciler can correlate them
1054    /// without re-parsing the spec JSON.
1055    pub const EXPORT_INDEX: &str = "tatara.pleme.io/export-index";
1056    /// Label / annotation key stamping which
1057    /// `RoutingSpec.hostnames` entry a routing edge (Ingress /
1058    /// DNSEndpoint) belongs to. Value is the entry's `app` slot;
1059    /// a `label`-selector on this key slices every emitted edge
1060    /// for a given `app` regardless of hostname form. Peer to
1061    /// [`ROUTING_FORM`] on the routing-axis pair.
1062    pub const APP: &str = "tatara.pleme.io/app";
1063    /// Label / annotation key stamping the routing form
1064    /// (`"stable"` | `"instance"`) on every emitted routing edge.
1065    /// Value is a [`crate::routing::RoutingForm`] wire-form string;
1066    /// consumers filtering the two forms compare to
1067    /// [`RoutingForm::as_str`][crate::routing::RoutingForm::as_str],
1068    /// never to a bare literal.
1069    pub const ROUTING_FORM: &str = "tatara.pleme.io/routing-form";
1070    /// Stamped by `tatara-pool-reconciler::controller_allocation::
1071    /// reconcile` on the member `Process` at the moment an
1072    /// `EphemeralAllocation` transitions Queued → Bound. Value is
1073    /// the requestor Allocation's `<ns>/<name>` qualified reference
1074    /// (composed through the same `<ns>/<name>` shape every peer
1075    /// substrate composer routes through — see
1076    /// [`crate::qualified_process_ref`]). Downstream consumers
1077    /// (operator dashboards, admission webhooks, audit-trail
1078    /// scrapers) grep for this key to answer "which allocator drove
1079    /// this member Process into its ephemeral overlay".
1080    pub const REQUESTOR: &str = "tatara.pleme.io/requestor";
1081    /// Peer to [`REQUESTOR`] on the same allocator-bind axis: the
1082    /// bare Allocation name (no namespace prefix), stamped alongside
1083    /// so downstream consumers that key on the Allocation identity
1084    /// alone (a single-namespace UI, an in-cluster label selector
1085    /// that already carries the namespace) don't need to re-split
1086    /// [`REQUESTOR`]'s composed reference.
1087    pub const ALLOCATION: &str = "tatara.pleme.io/allocation";
1088    /// Peer to [`REQUESTOR`] + [`ALLOCATION`] on the same
1089    /// allocator-bind axis: mirrors
1090    /// [`crate::allocation::RequestorRef.kind`] verbatim onto the
1091    /// bound member Process so consumers that dispatch on the
1092    /// requestor-kind axis (a GitHub-PR-scoped webhook, a
1093    /// scheduler-window scoped fairness gate, a per-kind quota
1094    /// enforcer) never have to fetch the Allocation object again.
1095    pub const REQUESTOR_KIND: &str = "tatara.pleme.io/requestor-kind";
1096    /// Stamped by `tatara-pool-reconciler::controller_pool::
1097    /// build_member_process` on every Process the pool controller
1098    /// materializes into a pool slot. Value is the owning
1099    /// [`crate::pool::EphemeralPool`]'s `metadata.name`; the pool
1100    /// controller's `process_belongs_to_pool` membership gate reads
1101    /// this key back through the substrate primitive
1102    /// [`crate::prelude::Process::annotation`] to filter its owned
1103    /// members out of the cluster-wide Process listing. Peer to
1104    /// [`POOL_SLOT`] on the same pool-membership axis; the two keys
1105    /// travel together at every write site so any future rename (a
1106    /// `tatara.pleme.io/v2/pool` migration, an alias table for
1107    /// cross-cluster pool identity, a per-cluster ownership prefix)
1108    /// lands at ONE `pub const` in the substrate and every
1109    /// downstream consumer (the pool reconciler's membership gate,
1110    /// any future observability label emitter, a cross-namespace
1111    /// pool-topology walker) inherits the upgrade mechanically.
1112    pub const POOL: &str = "tatara.pleme.io/pool";
1113    /// Peer to [`POOL`] on the same pool-membership axis: the
1114    /// zero-based slot index the pool controller assigned to the
1115    /// member Process, stamped alongside so downstream consumers
1116    /// that need per-slot identity (a UI grid layout, a per-slot
1117    /// affinity gate, a slot-scoped audit-trail scraper) can
1118    /// dispatch on it without re-scanning the pool controller's
1119    /// naming scheme. Value is the slot's `u32` rendered through
1120    /// `.to_string()`.
1121    pub const POOL_SLOT: &str = "tatara.pleme.io/pool-slot";
1122    /// Stamped by `tatara-pool-reconciler::controller_allocation::
1123    /// reconcile` on the bound member `Process` at the moment an
1124    /// `EphemeralAllocation` transitions Bound → Released, to nudge
1125    /// the pool reconciler into taking the return path (flip back
1126    /// to `Lifetime::Permanent` on the pool's [`crate::pool::ReturnPolicy::
1127    /// Keep`] arm, or delete the Process outright on the
1128    /// [`crate::pool::ReturnPolicy::Replace`] arm). Value is the wire-
1129    /// form string `"true"` — merge-patch semantics treat a bare
1130    /// `Value::Null` as strip, so the pool reconciler's future strip
1131    /// arm will stamp `Value::Null` under the same key through the
1132    /// same substrate [`crate::patch::annotation_body`] composer. Peer
1133    /// to [`SIGNAL`] (asynchronous signal-annotation ingest by
1134    /// `tatara-reconciler::signals::ingest`) and [`RELEASED_FROM`]
1135    /// (Releasing-gate stamp by `tatara-reconciler::phase_machine::
1136    /// transition_to_releasing`) on the "single-annotation trigger
1137    /// for the next reconcile pass" axis-family; all three keys ride
1138    /// through the same `annotation_body(<key>, <value>)` composer at
1139    /// their stamp sites.
1140    ///
1141    /// Peer to [`POOL`] + [`POOL_SLOT`] on the pool-membership axis:
1142    /// where those two keys travel together at pool-controller
1143    /// creation to identify a Process as a pool member, this key
1144    /// travels alone at the allocator's Release arm to fire the
1145    /// return path. A future rename that shifted the return-trigger
1146    /// wire-form (a `tatara.pleme.io/v2/return-trigger` migration, a
1147    /// per-fleet override, a collapse into a compound
1148    /// `tatara.pleme.io/allocator-trigger` key carrying the
1149    /// (bind|release) discriminator) lands at ONE `pub const` in the
1150    /// substrate and every downstream consumer inherits the upgrade
1151    /// mechanically.
1152    pub const RETURN_TRIGGER: &str = "tatara.pleme.io/return-trigger";
1153    /// Stamped by
1154    /// `tatara-reconciler::render::mark_resources_as_adopting` on every
1155    /// emitted resource of a Process whose
1156    /// [`crate::encapsulates::EncapsulatesSpec.mode`] gates the Adopt
1157    /// arm. Value is the wire-form spelling of the corresponding
1158    /// [`crate::encapsulates::EncapsulationMode`] variant
1159    /// (`"Adopt"` today; future modes ride through the same closed set),
1160    /// so downstream consumers (operator dashboards, admission webhooks,
1161    /// audit-trail scrapers) can filter which owned resources were
1162    /// stamped for adoption vs greenfield management vs pure observation
1163    /// without re-deriving the mode from the parent Process spec. Peer
1164    /// to [`ADOPTED_RELEASE`] on the same encapsulation-diagnostic
1165    /// axis-family; both keys travel together at the same emit site so
1166    /// a future rename (a `tatara.pleme.io/v2/encapsulation-mode`
1167    /// migration, a per-fleet override, a collapse into a compound
1168    /// `tatara.pleme.io/encapsulation` payload key) lands at ONE
1169    /// `pub const` in the substrate and every downstream consumer
1170    /// inherits the upgrade mechanically.
1171    pub const ENCAPSULATION_MODE: &str = "tatara.pleme.io/encapsulation-mode";
1172    /// Peer to [`ENCAPSULATION_MODE`] on the encapsulation-diagnostic
1173    /// axis-family: stamped by
1174    /// `tatara-reconciler::render::mark_resources_as_adopting` on every
1175    /// emitted resource of a Process whose
1176    /// [`crate::encapsulates::EncapsulationKind`] gates the
1177    /// [`crate::encapsulates::ExistingHelmRelease`] arm. Value is the
1178    /// `<ns>/<release>` qualified reference of the pre-existing
1179    /// HelmRelease the Process is adopting, composed through the
1180    /// workspace-wide [`crate::qualified_process_ref`] `<ns>/<name>`
1181    /// substrate composer (never as a hand-authored `format!("{}/{}",
1182    /// ns, release)` chain). Downstream consumers (operator dashboards,
1183    /// audit-trail scrapers, cross-namespace release-lineage walkers)
1184    /// grep for this key to answer "which pre-existing release did this
1185    /// Process take over".
1186    pub const ADOPTED_RELEASE: &str = "tatara.pleme.io/adopted-release";
1187    /// Label key stamped on every receipt [`ConfigMap`] that carries a
1188    /// typed [`crate::receipt::ReceiptEnvelope`] payload, so operators
1189    /// can `kubectl get cm -l tatara.pleme.io/receipt=tatara-receipt/v1`
1190    /// to enumerate every receipt of a given version on a cluster
1191    /// without pre-parsing each CM's embedded JSON/YAML.
1192    ///
1193    /// Value is [`crate::receipt::RECEIPT_VERSION`] — the wire-format
1194    /// version string every parser gates on. A future bump to
1195    /// `tatara-receipt/v2` lands at ONE const declaration on
1196    /// [`crate::receipt::RECEIPT_VERSION`] and every consumer that
1197    /// stamps this label picks up the upgrade mechanically.
1198    ///
1199    /// Load-bearing at TWO production write-sites past the ★★
1200    /// PRIME-DIRECTIVE ≥ 2 duplication threshold:
1201    /// - `tatara-closed-loop-probe::write_receipt_cm`'s
1202    ///   `BTreeMap::from([...])` label seed — the closed-loop auth
1203    ///   probe's receipt-CM label writer.
1204    /// - `tatara_process::configmap::with_data`'s byte-shape parity
1205    ///   witness test that mirrors the closed-loop-probe callsite.
1206    ///
1207    /// The `tatara-export-worker` receipt-CM writer intentionally
1208    /// stamps NO labels (its consumer keys on the CM name the
1209    /// ExportSpec channel already carries), so it is not a consumer of
1210    /// this const; the two production label-stamp sites above are the
1211    /// complete workspace consumer set today.
1212    ///
1213    /// Peer to [`ROLE`] + [`EXPORT_INDEX`] on the "annotation / label
1214    /// key stamped on a receipt-emitting resource other than the
1215    /// Process itself" axis-family: those two keys ride on the
1216    /// export-worker Job the reconciler emits (Job-side), this key
1217    /// rides on the receipt ConfigMap the probe binary writes
1218    /// (ConfigMap-side); all three share the [`GROUP_PREFIX`]
1219    /// reverse-DNS namespace. A future rename of this key (a
1220    /// `tatara.pleme.io/v2/receipt` migration, a per-fleet override, a
1221    /// collapse into a compound `tatara.pleme.io/receipt-envelope`
1222    /// key) lands at ONE `pub const` in the substrate and every
1223    /// downstream consumer inherits the upgrade mechanically.
1224    pub const RECEIPT: &str = "tatara.pleme.io/receipt";
1225
1226    /// Shared reverse-DNS namespace prefix every substrate-owned
1227    /// annotation key in this module carries — the same
1228    /// `tatara.pleme.io/` group segment every tatara-owned CRD
1229    /// annotation + finalizer key rides through, matching the
1230    /// `#[kube(group = "tatara.pleme.io", …)]` derive slot on every
1231    /// tatara CRD struct.
1232    ///
1233    /// Compile-time alias of the crate-wide substrate owner
1234    /// [`crate::GROUP_PREFIX`] — the ONE `pub const &'static str` that
1235    /// owns the `<GROUP>/` byte-shape every tatara wire-form key uses
1236    /// as its reverse-DNS prefix. Pre-lift this const restated the
1237    /// literal `"tatara.pleme.io/"` inline as a byte-parity mirror of
1238    /// the sibling [`crate::finalizers::GROUP_PREFIX`] (pinned equal
1239    /// by
1240    /// [`crate::annotations_family_tests::group_prefix_matches_finalizers_group_prefix`]);
1241    /// post-lift both peer consts route through
1242    /// [`crate::GROUP_PREFIX`] so byte equality holds by construction
1243    /// (the same `&'static str` address), and a future rename of the
1244    /// reverse-DNS root (a `"tatara.pleme.io/v2/"` migration under a
1245    /// group-segment bump, a per-fleet override, an alias table for
1246    /// cross-cluster ownership) lands at the ONE crate-root const with
1247    /// every peer wire-form consumer inheriting the shift mechanically
1248    /// rather than at three independent per-module string literals.
1249    ///
1250    /// Pinned across every arm of [`ALL`] by
1251    /// [`crate::annotations_family_tests::all_share_group_prefix`] so a
1252    /// future addition to the annotation family that drifted the prefix
1253    /// (a `tatara.io/` copy-paste that silently escaped the K8s-side
1254    /// reverse-DNS convention, a group-segment shift on ONE key that
1255    /// missed the ALL slice) surfaces at compile-time / test-time rather
1256    /// than as silent operator-facing skew.
1257    pub const GROUP_PREFIX: &str = crate::GROUP_PREFIX;
1258
1259    /// Closed family of every substrate-owned annotation key in this
1260    /// module, in stable declaration order matching the `pub const`
1261    /// definitions above.
1262    ///
1263    /// Peer to [`crate::finalizers::ALL`] on the "closed slice over a
1264    /// family of tatara-owned wire-form keys sharing the
1265    /// [`GROUP_PREFIX`] reverse-DNS namespace" axis-pair: the
1266    /// [`crate::finalizers`] module owns the same shape over its three
1267    /// finalizer keys; this const opens the mirror over the 20
1268    /// annotation keys in this module.
1269    ///
1270    /// Downstream sweeps that pre-lift the ALL owner had to hand-list
1271    /// every substrate-owned annotation key to iterate them — a
1272    /// fleet-wide annotation-audit binary dumping every
1273    /// `tatara.pleme.io/*` key on a cluster, a per-key coverage report
1274    /// answering "which annotations does the reconciler write vs read",
1275    /// a cross-cluster rename planner, the existing intra-module
1276    /// pairwise-disjointness tests (see the "peer list" arrays in
1277    /// [`crate::annotations_pins`] which hand-list up to 18 sibling
1278    /// keys to prove one axis is disjoint from every other) — iterate
1279    /// through ONE substrate slice post-lift. A future addition to the
1280    /// annotation family that landed a new `pub const` above but forgot
1281    /// this slice surfaces at
1282    /// [`crate::annotations_family_tests::all_matches_declared_length`]
1283    /// rather than by silently escaping every downstream iteration
1284    /// consumer.
1285    ///
1286    /// Pinned to length 21 by
1287    /// [`crate::annotations_family_tests::all_matches_declared_length`],
1288    /// to shared [`GROUP_PREFIX`] membership by
1289    /// [`crate::annotations_family_tests::all_share_group_prefix`],
1290    /// and to pairwise-uniqueness by
1291    /// [`crate::annotations_family_tests::all_are_pairwise_unique`] so
1292    /// a copy-paste that duplicated one arm's wire form at another arm
1293    /// (silently double-booking the K8s metadata slot the two keys
1294    /// share) surfaces at the family pin rather than as silent
1295    /// annotation-writer collision at whichever downstream site
1296    /// stamped the copy-paste'd key.
1297    pub const ALL: &[&str] = &[
1298        MANAGED_BY,
1299        PROCESS,
1300        PID,
1301        CONTENT_HASH,
1302        ATTESTATION_ROOT,
1303        GENERATION,
1304        SIGNAL,
1305        RELEASED_FROM,
1306        ROLE,
1307        EXPORT_INDEX,
1308        APP,
1309        ROUTING_FORM,
1310        REQUESTOR,
1311        ALLOCATION,
1312        REQUESTOR_KIND,
1313        POOL,
1314        POOL_SLOT,
1315        RETURN_TRIGGER,
1316        ENCAPSULATION_MODE,
1317        ADOPTED_RELEASE,
1318        RECEIPT,
1319    ];
1320}
1321
1322/// Standard finalizer for the Process reconciler.
1323///
1324/// Re-export of [`finalizers::PROCESS`] — the substrate-owner
1325/// per-CRD finalizer family lives at [`crate::finalizers`]; this
1326/// top-level const stays put for downstream consumers that predate
1327/// the module, and is coherence-pinned against
1328/// [`finalizers::PROCESS`] by
1329/// [`finalizers::tests::process_finalizer_top_level_reexport_routes_through_finalizers_process`].
1330pub const PROCESS_FINALIZER: &str = finalizers::PROCESS;
1331
1332/// Shared schemars helpers — emit OpenAPI schemas Kubernetes accepts.
1333/// Free-form `serde_json::Value` fields default to an *empty* schema
1334/// in schemars, which the K8s API server rejects with "type: Required
1335/// value: must not be empty for specified object fields". The typed
1336/// workaround is to emit `{type: object, x-kubernetes-preserve-unknown-
1337/// fields: true}` — same shape kube-rs's own helpers produce.
1338pub mod schema_helpers {
1339    use schemars::{gen::SchemaGenerator, schema::Schema};
1340    /// Schema for a free-form JSON object field. Apply via
1341    /// `#[schemars(schema_with = "tatara_process::schema_helpers::preserve_unknown_object")]`
1342    /// on any `serde_json::Value` / `BTreeMap<String, serde_json::Value>`
1343    /// field exposed through a CRD.
1344    pub fn preserve_unknown_object(_g: &mut SchemaGenerator) -> Schema {
1345        serde_json::from_value(serde_json::json!({
1346            "type": "object",
1347            "x-kubernetes-preserve-unknown-fields": true
1348        }))
1349        .expect("static JSON literal parses as Schema")
1350    }
1351}
1352
1353#[cfg(test)]
1354mod owner_reference_tests {
1355    //! Pin the `owner_reference_json` composer at fail-before-pass-
1356    //! after granularity. Every shape a pre-lift caller hand-authored
1357    //! is re-asserted here so a regression that inlined any of the
1358    //! six slots at a call site (breaking the primitive's role as
1359    //! the ONE source of truth) fails HERE at the composer's shipped-
1360    //! shape pin rather than as silent drift between the pre-lift
1361    //! `render.rs` / `edges.rs` / `ssapply.rs` sites (which pre-lift
1362    //! already carried TWO different `apiVersion` spellings — a
1363    //! composed `format!("{}/{}", GROUP, VERSION)` at two sites and
1364    //! the frozen literal `"tatara.pleme.io/v1alpha1"` at the third).
1365    use super::{
1366        api_version, owner_reference_json, owner_references_json, API_VERSION, GROUP, GROUP_PREFIX,
1367        PROCESS_KIND, PROCESS_WIRE_IDENTITY, VERSION,
1368    };
1369    use crate::flux_resource::FluxResource;
1370    use crate::k8s_builtin_resource::K8sBuiltinResource;
1371    use crate::k8s_wire_identity::K8sWireIdentity;
1372    use crate::routing_edge_resource::RoutingEdgeResource;
1373    use serde_json::json;
1374
1375    #[test]
1376    fn api_version_composes_group_and_version() {
1377        // Any bump of GROUP or VERSION lands at ONE composer.
1378        assert_eq!(api_version(), format!("{GROUP}/{VERSION}"));
1379    }
1380
1381    // ─── API_VERSION const substrate pins ───────────────────────────
1382    //
1383    // The compile-time `&'static str` [`API_VERSION`] const feeds the
1384    // typed [`PROCESS_WIRE_IDENTITY`] const and delegates the runtime
1385    // [`api_version`] fn — these pins bind the const at fail-before-
1386    // pass-after granularity so a regression that drifted the const
1387    // (a rename that touched [`GROUP`] but not the const's baked
1388    // literal, a VERSION bump that only updated [`VERSION`]) surfaces
1389    // HERE rather than as silent operator-facing skew between the
1390    // typed-const consumers and the fn-based consumers on the same
1391    // wire-form axis.
1392
1393    #[test]
1394    fn api_version_const_composes_group_and_version_bytewise() {
1395        // Cross-const coherence pin: the compile-time [`API_VERSION`]
1396        // must be byte-identical to the runtime `format!("{GROUP}/
1397        // {VERSION}")` composition. A regression that drifted either
1398        // the const or the two segment consts would surface HERE
1399        // rather than as silent skew between [`PROCESS_WIRE_IDENTITY`]
1400        // (which composes over the const) and [`api_url_prefix`]
1401        // (which composes over the two segment consts at runtime).
1402        assert_eq!(API_VERSION, format!("{GROUP}/{VERSION}"));
1403    }
1404
1405    #[test]
1406    fn api_version_const_byte_matches_wire_form_pre_lift() {
1407        // Byte-identity pin: the frozen wire-form literal is the SAME
1408        // string every downstream consumer (the typed
1409        // [`PROCESS_WIRE_IDENTITY`] const, the runtime [`api_version`]
1410        // fn, every K8s `apiVersion:` slot the reconciler stamps)
1411        // must emit. Peer of the pre-existing runtime pin
1412        // [`api_version_byte_matches_wire_form_pre_lift`]; both close
1413        // the axis at the SAME wire form.
1414        assert_eq!(API_VERSION, "tatara.pleme.io/v1alpha1");
1415    }
1416
1417    #[test]
1418    fn api_version_fn_delegates_through_const_owner() {
1419        // Routing pin: the runtime `api_version()` fn returns
1420        // [`API_VERSION`]`.to_string()` — the ONE substrate owner of
1421        // the wire-form literal. A regression that re-open-coded the
1422        // fn's body (restoring the pre-lift `format!("{GROUP}/
1423        // {VERSION}")` composition, or inlining a stale literal) would
1424        // surface HERE rather than as silent skew between the two
1425        // sibling emit paths (typed-const vs owned-String).
1426        assert_eq!(api_version(), API_VERSION);
1427    }
1428
1429    #[test]
1430    fn api_version_const_is_reachable_at_compile_time() {
1431        // Compile-time reachability pin: [`API_VERSION`] is a `const
1432        // &'static str` so a caller can bind it into a `const` slot —
1433        // exactly what [`PROCESS_WIRE_IDENTITY`] does through
1434        // [`K8sWireIdentity::new`]'s `const fn`. A regression that
1435        // widened the const to an owned `String` or a `Lazy<String>`
1436        // would fail-loudly at this coercion rather than at the
1437        // silent runtime-vs-const composition boundary at
1438        // [`PROCESS_WIRE_IDENTITY`].
1439        const AV: &str = API_VERSION;
1440        assert_eq!(AV, "tatara.pleme.io/v1alpha1");
1441    }
1442
1443    // ─── GROUP_PREFIX const substrate pins ──────────────────────────
1444    //
1445    // The compile-time `&'static str` [`GROUP_PREFIX`] const owns the
1446    // `<GROUP>/` reverse-DNS prefix every tatara-owned wire-form key
1447    // (annotation, finalizer, label, signal) uses as its namespace
1448    // prefix, and every downstream `.starts_with(...)` group-membership
1449    // gate compares against. Pre-lift the prefix was spelled inline as
1450    // a bare `"tatara.pleme.io/"` literal at TWO substrate-owner sites
1451    // ([`crate::annotations::GROUP_PREFIX`] +
1452    // [`crate::finalizers::GROUP_PREFIX`]) pinned byte-equal to each
1453    // other but with no shared owner binding them to [`GROUP`] itself.
1454    // Post-lift both peer consts route through this ONE crate-root
1455    // owner as compile-time aliases so byte equality holds by
1456    // construction. These pins bind the const at fail-before-pass-after
1457    // granularity so a regression that drifted it (a rename that
1458    // touched [`GROUP`] but not the const's baked literal, a partial
1459    // edit that unbound the two peer aliases from the ONE owner) would
1460    // surface HERE rather than as silent operator-facing skew between
1461    // the [`GROUP`] const the [`api_url_prefix`] composer feeds and the
1462    // [`GROUP_PREFIX`] const every downstream annotation / finalizer
1463    // family gate consumes.
1464
1465    #[test]
1466    fn group_prefix_const_composes_group_slash_bytewise() {
1467        // Cross-const coherence pin: the compile-time [`GROUP_PREFIX`]
1468        // must be byte-identical to the runtime `format!("{GROUP}/")`
1469        // composition. A regression that drifted either the const or
1470        // the [`GROUP`] segment would surface HERE rather than as
1471        // silent skew between [`GROUP`] (which
1472        // [`api_url_prefix`] + [`api_version`] compose over) and
1473        // [`GROUP_PREFIX`] (which every downstream annotation /
1474        // finalizer family gate consumes as its reverse-DNS prefix).
1475        assert_eq!(GROUP_PREFIX, format!("{GROUP}/"));
1476    }
1477
1478    #[test]
1479    fn group_prefix_const_byte_matches_wire_form_pre_lift() {
1480        // Byte-identity pin: the frozen wire-form literal is the SAME
1481        // string every downstream consumer (the peer aliases
1482        // [`crate::annotations::GROUP_PREFIX`] +
1483        // [`crate::finalizers::GROUP_PREFIX`], every
1484        // `<key>.starts_with(GROUP_PREFIX)` gate on the peer
1485        // [`crate::annotations::ALL`] / [`crate::finalizers::ALL`]
1486        // families) must compare against. Peer of the pre-existing
1487        // wire-form pin
1488        // [`api_version_const_byte_matches_wire_form_pre_lift`]; both
1489        // close the axis at the SAME reverse-DNS root.
1490        assert_eq!(GROUP_PREFIX, "tatara.pleme.io/");
1491    }
1492
1493    #[test]
1494    fn group_prefix_const_is_reachable_at_compile_time() {
1495        // Compile-time reachability pin: [`GROUP_PREFIX`] is a `const
1496        // &'static str` so callers can bind it into a `const` slot —
1497        // exactly what [`crate::annotations::GROUP_PREFIX`] +
1498        // [`crate::finalizers::GROUP_PREFIX`] do as compile-time
1499        // aliases. A regression that widened the const to an owned
1500        // `String` or a `Lazy<String>` would fail-loudly at this
1501        // coercion rather than at the silent alias-coercion boundary
1502        // at the two peer consts.
1503        const GP: &str = GROUP_PREFIX;
1504        assert_eq!(GP, "tatara.pleme.io/");
1505    }
1506
1507    #[test]
1508    fn annotations_group_prefix_routes_through_crate_root_owner() {
1509        // Routing pin: [`crate::annotations::GROUP_PREFIX`] is a
1510        // compile-time alias of [`GROUP_PREFIX`] — the ONE substrate
1511        // owner of the reverse-DNS prefix wire form. A regression that
1512        // re-open-coded the annotation-family const (restoring the
1513        // pre-lift inline `"tatara.pleme.io/"` literal, inlining a
1514        // stale byte string) would surface HERE rather than as silent
1515        // skew between the two sibling substrate owners (annotation vs
1516        // finalizer families) on the SAME reverse-DNS prefix.
1517        assert_eq!(crate::annotations::GROUP_PREFIX, GROUP_PREFIX);
1518    }
1519
1520    #[test]
1521    fn finalizers_group_prefix_routes_through_crate_root_owner() {
1522        // Routing pin: [`crate::finalizers::GROUP_PREFIX`] is a
1523        // compile-time alias of [`GROUP_PREFIX`] — the ONE substrate
1524        // owner of the reverse-DNS prefix wire form. A regression that
1525        // re-open-coded the finalizer-family const (restoring the
1526        // pre-lift inline `"tatara.pleme.io/"` literal, inlining a
1527        // stale byte string) would surface HERE rather than as silent
1528        // skew between the two sibling substrate owners (finalizer vs
1529        // annotation families) on the SAME reverse-DNS prefix.
1530        assert_eq!(crate::finalizers::GROUP_PREFIX, GROUP_PREFIX);
1531    }
1532
1533    // ─── PROCESS_WIRE_IDENTITY substrate pins ───────────────────────
1534    //
1535    // The typed [`PROCESS_WIRE_IDENTITY`] const closes the fourth arm
1536    // of the K8s-wire-form-identity axis-family (peer to
1537    // [`K8sBuiltinResource::wire_identity`],
1538    // [`FluxResource::wire_identity`],
1539    // [`RoutingEdgeResource::wire_identity`]). These pins bind the
1540    // const at fail-before-pass-after granularity so a regression that
1541    // drifted either slot (an `apiVersion` slot that stopped routing
1542    // through [`API_VERSION`], a `kind` slot that stopped routing
1543    // through [`PROCESS_KIND`]) surfaces HERE rather than as silent
1544    // OwnerReference-emit skew at every downstream consumer.
1545
1546    #[test]
1547    fn process_wire_identity_pairs_api_version_and_kind_through_substrate_owners() {
1548        // Slot-routing pin: both slots MUST route through the ONE
1549        // substrate owner per slot ([`API_VERSION`] for the
1550        // `apiVersion` slot, [`PROCESS_KIND`] for the `kind` slot).
1551        // A regression that re-inlined either slot's literal at the
1552        // const declaration would surface HERE rather than as silent
1553        // skew between the wire-identity const and its slot owners.
1554        assert_eq!(PROCESS_WIRE_IDENTITY.api_version, API_VERSION);
1555        assert_eq!(PROCESS_WIRE_IDENTITY.kind, PROCESS_KIND);
1556    }
1557
1558    #[test]
1559    fn process_wire_identity_byte_matches_wire_form_pre_lift() {
1560        // Byte-identity pin: the const's `(apiVersion, kind)` pair
1561        // must equal the two frozen wire-form strings every pre-lift
1562        // consumer hand-authored — a regression that drifted either
1563        // slot would surface HERE rather than as a wire-time 404 the
1564        // K8s API server would misdiagnose as a broken CRD.
1565        assert_eq!(
1566            PROCESS_WIRE_IDENTITY.api_version,
1567            "tatara.pleme.io/v1alpha1"
1568        );
1569        assert_eq!(PROCESS_WIRE_IDENTITY.kind, "Process");
1570    }
1571
1572    #[test]
1573    fn process_wire_identity_is_const_reachable() {
1574        // Compile-time reachability pin: [`PROCESS_WIRE_IDENTITY`] is
1575        // a compile-time `const K8sWireIdentity` so a caller can bind
1576        // it into a `const` slot. A regression that dropped the
1577        // `const fn` qualifier on [`K8sWireIdentity::new`] or widened
1578        // [`API_VERSION`] off the `&'static str` axis would fail-loudly
1579        // HERE rather than as a runtime dispatch at every OwnerReference
1580        // emit site.
1581        const ID: K8sWireIdentity = PROCESS_WIRE_IDENTITY;
1582        assert_eq!(ID.api_version, "tatara.pleme.io/v1alpha1");
1583        assert_eq!(ID.kind, "Process");
1584    }
1585
1586    #[test]
1587    fn process_wire_identity_is_disjoint_from_every_peer_wire_form_axis() {
1588        // Cross-substrate coherence pin: the tatara `Process` CRD's
1589        // typed `(apiVersion, kind)` pair MUST NOT collide with any
1590        // variant of the three peer closed-set axes on the K8s wire-
1591        // form-identity axis-family
1592        // ([`K8sBuiltinResource`] / [`FluxResource`] /
1593        // [`RoutingEdgeResource`]) — a hypothetical variant addition
1594        // on any peer that copy-pasted the tatara `Process` pair
1595        // (a `FluxResource::Process` renaming collision, a
1596        // `K8sBuiltinResource::Process` typo) would silently let a
1597        // reconciler dispatch reach through the wrong closed set. Pin
1598        // the disjointness so every future addition to any peer axis
1599        // that would collide with this const surfaces HERE.
1600        for k in K8sBuiltinResource::ALL {
1601            assert_ne!(
1602                (
1603                    PROCESS_WIRE_IDENTITY.api_version,
1604                    PROCESS_WIRE_IDENTITY.kind
1605                ),
1606                (k.api_version(), k.kind()),
1607                "PROCESS_WIRE_IDENTITY must not share a wire-form pair with K8sBuiltinResource {k:?}"
1608            );
1609        }
1610        for f in FluxResource::ALL {
1611            assert_ne!(
1612                (
1613                    PROCESS_WIRE_IDENTITY.api_version,
1614                    PROCESS_WIRE_IDENTITY.kind
1615                ),
1616                (f.api_version(), f.kind()),
1617                "PROCESS_WIRE_IDENTITY must not share a wire-form pair with FluxResource {f:?}"
1618            );
1619        }
1620        for r in RoutingEdgeResource::ALL {
1621            assert_ne!(
1622                (
1623                    PROCESS_WIRE_IDENTITY.api_version,
1624                    PROCESS_WIRE_IDENTITY.kind
1625                ),
1626                (r.api_version(), r.kind()),
1627                "PROCESS_WIRE_IDENTITY must not share a wire-form pair with RoutingEdgeResource {r:?}"
1628            );
1629        }
1630    }
1631
1632    #[test]
1633    fn owner_reference_json_routes_apiversion_and_kind_through_process_wire_identity() {
1634        // Routing pin: the `owner_reference_json` composer's
1635        // `(apiVersion, kind)` pair MUST match the typed
1636        // [`PROCESS_WIRE_IDENTITY`] const's `(api_version, kind)`
1637        // fields byte-for-byte. Post-lift the composer routes through
1638        // [`K8sWireIdentity::resource_json`], so this equality holds
1639        // by construction; a regression that re-open-coded the two
1640        // slots at the composer body (restoring the pre-lift `json!`
1641        // inline reference to `api_version()` + `PROCESS_KIND`
1642        // separately) would surface HERE rather than as silent skew
1643        // between the OwnerReference emit and the typed const owner.
1644        let v = owner_reference_json("p", "u");
1645        assert_eq!(v["apiVersion"], PROCESS_WIRE_IDENTITY.api_version);
1646        assert_eq!(v["kind"], PROCESS_WIRE_IDENTITY.kind);
1647    }
1648
1649    #[test]
1650    fn api_version_byte_matches_wire_form_pre_lift() {
1651        // Byte-identity pin: the frozen wire-form literal
1652        // `"tatara.pleme.io/v1alpha1"` that `ssapply.rs::
1653        // build_owner_reference` hand-wrote pre-lift must equal the
1654        // composed shape now sourced through the ONE owner. A
1655        // future VERSION bump that missed this test would land as
1656        // an operator-visible reference-mismatch after apply.
1657        assert_eq!(api_version(), "tatara.pleme.io/v1alpha1");
1658    }
1659
1660    #[test]
1661    fn api_url_prefix_composes_apis_group_version_slash() {
1662        // Composition pin: any bump of GROUP or VERSION lands at
1663        // ONE composer.
1664        assert_eq!(super::api_url_prefix(), format!("/apis/{GROUP}/{VERSION}/"));
1665    }
1666
1667    #[test]
1668    fn api_url_prefix_byte_matches_wire_form_pre_lift() {
1669        // Byte-identity pin: the frozen wire-form literal
1670        // `"/apis/tatara.pleme.io/v1alpha1/"` that eleven
1671        // hand-authored scope guards across `tatara-reconciler::
1672        // context`, `tatara-pool-reconciler::context`, and
1673        // `tatara-github-watcher::handler` restated pre-lift must
1674        // equal the composed shape now sourced through the ONE
1675        // owner. A future group rename or VERSION bump that missed
1676        // this pin would land as a silent scope-guard mismatch at
1677        // every downstream Api-primitive test.
1678        assert_eq!(super::api_url_prefix(), "/apis/tatara.pleme.io/v1alpha1/");
1679    }
1680
1681    #[test]
1682    fn api_url_prefix_carries_api_version_between_apis_and_trailing_slash() {
1683        // Cross-primitive pin: the URL prefix and the `apiVersion`
1684        // wire form share the SAME `<GROUP>/<VERSION>` shape,
1685        // wrapped by the fixed `/apis/…/` HTTP-path envelope. A
1686        // regression that drifted the two composers apart (a bump
1687        // that missed one of the two owners) surfaces here rather
1688        // than as an operator-visible mismatch between an emitted
1689        // ownerReference's `apiVersion` and the REST url every typed
1690        // `Api` primitive routes through.
1691        let prefix = super::api_url_prefix();
1692        let version = api_version();
1693        assert!(
1694            prefix.starts_with("/apis/") && prefix.ends_with('/'),
1695            "prefix must be wrapped as `/apis/…/`; got {prefix}"
1696        );
1697        let inner = &prefix["/apis/".len()..prefix.len() - 1];
1698        assert_eq!(
1699            inner, version,
1700            "prefix inner slot must equal api_version(); got inner={inner:?} version={version:?}"
1701        );
1702    }
1703
1704    #[test]
1705    fn process_kind_is_process_literal() {
1706        // Symbol-vs-string pin: any consumer that hand-wrote `"Process"`
1707        // pre-lift routes through this const post-lift.
1708        assert_eq!(PROCESS_KIND, "Process");
1709    }
1710
1711    #[test]
1712    fn owner_reference_json_has_all_six_slots_present() {
1713        let v = owner_reference_json("my-process", "abc-uid");
1714        let obj = v.as_object().expect("owner reference is a JSON object");
1715        for k in [
1716            "apiVersion",
1717            "kind",
1718            "name",
1719            "uid",
1720            "controller",
1721            "blockOwnerDeletion",
1722        ] {
1723            assert!(obj.contains_key(k), "missing owner-reference slot: {k}");
1724        }
1725        assert_eq!(obj.len(), 6, "owner reference must have exactly 6 slots");
1726    }
1727
1728    #[test]
1729    fn owner_reference_json_apiversion_routes_through_api_version_owner() {
1730        let v = owner_reference_json("x", "y");
1731        assert_eq!(v["apiVersion"], api_version());
1732    }
1733
1734    #[test]
1735    fn owner_reference_json_kind_routes_through_process_kind_const() {
1736        let v = owner_reference_json("x", "y");
1737        assert_eq!(v["kind"], PROCESS_KIND);
1738    }
1739
1740    #[test]
1741    fn owner_reference_json_stamps_supplied_name_and_uid() {
1742        let v = owner_reference_json("some-name", "some-uid");
1743        assert_eq!(v["name"], "some-name");
1744        assert_eq!(v["uid"], "some-uid");
1745    }
1746
1747    #[test]
1748    fn owner_reference_json_controller_and_block_owner_deletion_are_true() {
1749        // These are structural — a Process-owned resource always
1750        // has a controlling reference that cascade-deletes with
1751        // the owner. A regression that flipped either boolean
1752        // would silently detach every emitted resource.
1753        let v = owner_reference_json("x", "y");
1754        assert_eq!(v["controller"], true);
1755        assert_eq!(v["blockOwnerDeletion"], true);
1756    }
1757
1758    #[test]
1759    fn owner_reference_json_matches_hand_authored_shape_pre_lift() {
1760        // Byte-shape pin against the exact `json!({…})` incantation
1761        // every pre-lift call site restated. A regression that
1762        // reordered a slot, dropped one, or added a seventh here
1763        // surfaces at THIS pin rather than as a subtle SSA-apply
1764        // failure downstream when the K8s API server rejects the
1765        // OwnerReference on schema mismatch.
1766        let via_owner = owner_reference_json("p", "u");
1767        let hand_authored = json!({
1768            "apiVersion": "tatara.pleme.io/v1alpha1",
1769            "kind": "Process",
1770            "name": "p",
1771            "uid": "u",
1772            "controller": true,
1773            "blockOwnerDeletion": true,
1774        });
1775        assert_eq!(via_owner, hand_authored);
1776    }
1777
1778    #[test]
1779    fn owner_reference_json_preserves_empty_name_and_uid_bytewise() {
1780        // The primitive does not guard against empty inputs — its
1781        // callers pre-lift did the empty-check upstream (both the
1782        // `edges.rs::build_owner_refs` and `render.rs::one_export_job`
1783        // sites gated on `!uid.is_empty()` before calling this composer,
1784        // and both now route through `owner_references_json` below;
1785        // `ssapply.rs::build_owner_reference` unwraps a required
1786        // `metadata.uid` via anyhow). The scalar composer owns
1787        // shape composition, not admission control; a downstream
1788        // rename that wants strict input validation lands as a
1789        // peer, not a change to the composer's contract.
1790        let v = owner_reference_json("", "");
1791        assert_eq!(v["name"], "");
1792        assert_eq!(v["uid"], "");
1793    }
1794
1795    // ─── owner_references_json substrate pins ────────────────────────
1796    //
1797    // The 3-line `let mut owner_refs = vec![]; if !uid.is_empty()
1798    // { owner_refs.push(owner_reference_json(name, uid)); }` gate was
1799    // hand-authored at TWO sites in `tatara-reconciler`
1800    // (`edges::build_owner_refs` + `render::one_export_job`) before
1801    // this primitive existed, each restating the same optional-uid
1802    // posture that emits `[]` when the caller lacks a K8s-assigned
1803    // uid to point owners at. These pins bind the primitive at
1804    // fail-before-pass-after granularity so a regression that
1805    // inlined an owner reference for an empty uid — silently
1806    // detaching the resource from cascade-delete — surfaces HERE
1807    // rather than as an operator-visible ownerless resource after
1808    // apply, and a regression that added an owner reference of the
1809    // wrong SHAPE (a peer of `owner_reference_json` that swapped a
1810    // slot) surfaces via the composed-shape pin below rather than
1811    // as silent drift at every downstream emit site.
1812
1813    #[test]
1814    fn owner_references_json_emits_single_entry_when_uid_present() {
1815        // The primary shape: a caller with a materialized uid gets
1816        // exactly one owner reference back — the pre-lift 3-line
1817        // `vec![]` + `push` gate collapses to this ONE call, and
1818        // the returned array is a direct-drop `ownerReferences`
1819        // slot value at every callsite.
1820        let refs = owner_references_json("demo-app", "abc-uid");
1821        assert_eq!(refs.len(), 1);
1822        assert_eq!(refs[0]["kind"], PROCESS_KIND);
1823        assert_eq!(refs[0]["name"], "demo-app");
1824        assert_eq!(refs[0]["uid"], "abc-uid");
1825        // controller + blockOwnerDeletion routed through the scalar
1826        // composer — a regression that hand-composed the vec entry
1827        // rather than delegating would flip one of these booleans.
1828        assert_eq!(refs[0]["controller"], true);
1829        assert_eq!(refs[0]["blockOwnerDeletion"], true);
1830    }
1831
1832    #[test]
1833    fn owner_references_json_emits_empty_when_uid_empty() {
1834        // The load-bearing gate — a pre-metadata Process (fixtured in
1835        // tests, or caught mid-Forking) has no admissible owner
1836        // reference to point at. Post-lift the gate lives at ONE
1837        // primitive so every emit site stamps `[]` uniformly rather
1838        // than one site accidentally emitting a placeholder-uid
1839        // owner reference the K8s GC would quietly detach from
1840        // cascade-delete.
1841        let refs = owner_references_json("demo-app", "");
1842        assert!(
1843            refs.is_empty(),
1844            "empty uid must produce zero owner references, not a placeholder-uid entry"
1845        );
1846    }
1847
1848    #[test]
1849    fn owner_references_json_gates_on_uid_not_name() {
1850        // The gate axis is `uid`, not `name` — a Process with a
1851        // non-empty name but no uid still emits `[]` (the pre-metadata
1852        // shape), while a Process with a non-empty uid emits ONE
1853        // entry even when the name slot is empty (matching the
1854        // scalar composer's admission-control-free contract). Pin
1855        // both cross-diagonal combinations so a regression that
1856        // swapped the gate axis surfaces HERE rather than at every
1857        // downstream owner-refs consumer.
1858        assert!(
1859            owner_references_json("has-name", "").is_empty(),
1860            "empty uid gates to []; name presence is irrelevant"
1861        );
1862        let refs = owner_references_json("", "has-uid");
1863        assert_eq!(
1864            refs.len(),
1865            1,
1866            "empty name but present uid still emits one entry (name is not the gate)"
1867        );
1868        assert_eq!(refs[0]["name"], "");
1869        assert_eq!(refs[0]["uid"], "has-uid");
1870    }
1871
1872    #[test]
1873    fn owner_references_json_matches_hand_authored_pre_lift_bytewise() {
1874        // Byte-identical parity with the exact pre-lift 3-line
1875        // `let mut owner_refs = vec![]; if !uid.is_empty() {
1876        // owner_refs.push(owner_reference_json(name, uid)); }` gate
1877        // across the two axis combinations every callsite plausibly
1878        // encounters. A regression that reordered the two branches,
1879        // dropped the gate, or reshaped the vec composition surfaces
1880        // HERE rather than at every downstream `ownerReferences`
1881        // slot pinned across `edges.rs` + `render.rs` tests.
1882        for (name, uid) in [
1883            ("demo-app", "uid-abc"),
1884            ("demo-app", ""),
1885            ("", "uid-abc"),
1886            ("", ""),
1887        ] {
1888            let via_primitive = owner_references_json(name, uid);
1889
1890            // The pre-lift 3-line block, byte-for-byte.
1891            let mut hand_authored: Vec<serde_json::Value> = vec![];
1892            if !uid.is_empty() {
1893                hand_authored.push(owner_reference_json(name, uid));
1894            }
1895
1896            assert_eq!(
1897                via_primitive, hand_authored,
1898                "owner_references_json must be byte-identical to the pre-lift 3-line gate on ({name:?}, {uid:?})"
1899            );
1900        }
1901    }
1902
1903    #[test]
1904    fn owner_references_json_interpolates_cleanly_as_owner_refs_slot() {
1905        // Both callsites drop the returned vec directly under a
1906        // `"ownerReferences"` key inside a `json!({...})` block. Pin
1907        // the interop shape: a JSON-macro-wrapped Value carries the
1908        // primitive's output as a JSON array with the exact 6-slot
1909        // entries at each index. A regression that returned a
1910        // non-array (e.g. a single Value on the one-entry path,
1911        // requiring per-site vec-wrapping) surfaces HERE rather than
1912        // as a broken `metadata.ownerReferences` slot on every
1913        // emitted Ingress / DNSEndpoint / export Job.
1914        let refs = owner_references_json("demo-app", "abc-uid");
1915        let wrapped = json!({
1916            "metadata": {
1917                "name": "resource",
1918                "ownerReferences": refs,
1919            },
1920        });
1921        let owner_refs = &wrapped["metadata"]["ownerReferences"];
1922        assert!(
1923            owner_refs.is_array(),
1924            "ownerReferences must land as a JSON array"
1925        );
1926        assert_eq!(owner_refs.as_array().unwrap().len(), 1);
1927        assert_eq!(owner_refs[0]["kind"], PROCESS_KIND);
1928
1929        // And the empty-uid path lands as an EMPTY array, not a
1930        // missing key or a null — matches the K8s API server's
1931        // expectation that the slot is either an array of entries
1932        // or absent, never a null.
1933        let empty_refs = owner_references_json("demo-app", "");
1934        let wrapped_empty = json!({
1935            "metadata": {
1936                "name": "resource",
1937                "ownerReferences": empty_refs,
1938            },
1939        });
1940        let owner_refs_empty = &wrapped_empty["metadata"]["ownerReferences"];
1941        assert!(owner_refs_empty.is_array());
1942        assert!(owner_refs_empty.as_array().unwrap().is_empty());
1943    }
1944}
1945
1946#[cfg(test)]
1947mod qualified_process_ref_tests {
1948    //! Pin the [`qualified_process_ref`] composer at fail-before-
1949    //! pass-after granularity. The `<ns>/<name>` shape is the
1950    //! workspace-wide convention for a namespaced K8s resource
1951    //! reference — every downstream grep (the reconciler's
1952    //! `tatara.pleme.io/process` annotation reader, the
1953    //! [`crate::table::ClaimRecord.holder`] slot, the
1954    //! export-worker's receipt-owner filter, the reconciler's
1955    //! `PROCESS=<ref>` label-selector composer) depends on the
1956    //! two axes landing in `(ns, name)` order joined by a single
1957    //! `/` separator. A regression that swapped the axes, dropped
1958    //! either half, or renormalized the input surfaces HERE rather
1959    //! than as silent operator-facing drift at every downstream
1960    //! consumer.
1961    use super::qualified_process_ref;
1962
1963    #[test]
1964    fn qualified_process_ref_joins_ns_and_name_with_slash() {
1965        // The invariant every downstream consumer composes against:
1966        // the qualified reference is EXACTLY `<ns>/<name>`, in that
1967        // order, joined by a single `/`.
1968        assert_eq!(
1969            qualified_process_ref("demo-ns", "ephemeral-demo"),
1970            "demo-ns/ephemeral-demo",
1971        );
1972    }
1973
1974    #[test]
1975    fn qualified_process_ref_binds_positional_slots_by_axis_order() {
1976        // Positional pin — a copy-paste that swapped the two `&str`
1977        // arguments (both mechanically interchangeable at the type
1978        // level) would silently produce `<name>/<ns>` and break every
1979        // downstream grep keyed on the reference shape. Distinct
1980        // input slot values so a swap surfaces as an equality
1981        // failure rather than accidental identity.
1982        let out = qualified_process_ref("first-slot-ns", "second-slot-name");
1983        assert!(
1984            out.starts_with("first-slot-ns/"),
1985            "position 0 must be the namespace slot: got {out}"
1986        );
1987        assert!(
1988            out.ends_with("/second-slot-name"),
1989            "position 1 must be the name slot: got {out}"
1990        );
1991    }
1992
1993    #[test]
1994    fn qualified_process_ref_accepts_string_deref_and_str_slice_shapes() {
1995        // Consumers split across two callsite shapes: owned
1996        // `String` locals (via deref coercion), bare `&str` slices,
1997        // and mixed provenance. Every shape must ride cleanly
1998        // through the same 2-arg signature — matches every current
1999        // pre-lift caller in `tatara-export-worker` (CLI-arg driven
2000        // owned strings + `&str` from a struct field) and in
2001        // `tatara-reconciler` (owned locals + function-param
2002        // slices).
2003        let owned_ns = String::from("owned-ns");
2004        let owned_name = String::from("owned-app");
2005        let borrowed_ns: &str = "borrowed-ns";
2006        let borrowed_name: &str = "borrowed-app";
2007        assert_eq!(
2008            qualified_process_ref(&owned_ns, &owned_name),
2009            "owned-ns/owned-app",
2010        );
2011        assert_eq!(
2012            qualified_process_ref(borrowed_ns, borrowed_name),
2013            "borrowed-ns/borrowed-app",
2014        );
2015        assert_eq!(
2016            qualified_process_ref(&owned_ns, borrowed_name),
2017            "owned-ns/borrowed-app",
2018        );
2019    }
2020
2021    #[test]
2022    fn qualified_process_ref_rides_edge_case_axis_shapes() {
2023        // The composer shapes the two axes as arbitrary strings —
2024        // no length/character validation happens at the composer,
2025        // so any shape a Process's `metadata.namespace` /
2026        // `metadata.name` can hold rides through unchanged. Pin
2027        // the empty-string cases (unnamed process pre-metadata,
2028        // cluster-scoped `namespace = ""` fallback), and the
2029        // whitespace-and-slash-in-name pathological case (a
2030        // regression that URL-escaped or path-normalized the input
2031        // at this primitive would silently break every downstream
2032        // grep).
2033        assert_eq!(qualified_process_ref("", ""), "/");
2034        assert_eq!(qualified_process_ref("default", ""), "default/");
2035        assert_eq!(qualified_process_ref("", "orphan"), "/orphan");
2036        assert_eq!(
2037            qualified_process_ref("weird ns", "with/slash"),
2038            "weird ns/with/slash",
2039        );
2040    }
2041
2042    #[test]
2043    fn qualified_process_ref_composes_from_process_coordinates_or_defaults() {
2044        // The primary Process-driven callsite: a live
2045        // [`crate::prelude::Process`] with populated metadata
2046        // composes through
2047        // [`crate::prelude::Process::coordinates_or_defaults`] +
2048        // [`qualified_process_ref`]. Pin the composition so a
2049        // regression in either primitive that broke the `(ns,
2050        // name)` positional contract surfaces HERE rather than as
2051        // silent drift at every downstream reconciler / export-
2052        // worker / pool-reconciler consumer.
2053        use crate::crd::{Process, ProcessSpec};
2054        // Routes through the ONE substrate composer
2055        // `ProcessSpec::gate_compute_defaults` — pre-lift this was a
2056        // 12-line inline struct-literal restated verbatim inside this
2057        // pin body.
2058        let spec = ProcessSpec::gate_compute_defaults();
2059        let mut p = Process::new("ephemeral-demo", spec);
2060        p.metadata.namespace = Some("demo-ns".into());
2061        let (ns, name) = p.coordinates_or_defaults();
2062        assert_eq!(
2063            qualified_process_ref(ns, name),
2064            "demo-ns/ephemeral-demo",
2065            "coordinates_or_defaults + qualified_process_ref must \
2066             compose to the canonical <ns>/<name> shape"
2067        );
2068    }
2069
2070    #[test]
2071    fn qualified_process_ref_matches_hand_authored_pre_lift_bytewise() {
2072        // Byte-identical parity with the exact pre-lift
2073        // `format!("{ns}/{name}")` incantation. A regression that
2074        // reshaped the separator, reordered the axes, or dropped
2075        // either half surfaces HERE rather than at every downstream
2076        // annotation / claim-key / run-id consumer. Sweeps every
2077        // shape combination the pre-lift callers plausibly
2078        // encountered.
2079        for (ns, name) in [
2080            ("demo-ns", "ephemeral-demo"),
2081            ("", ""),
2082            ("default", ""),
2083            ("", "orphan"),
2084        ] {
2085            let via_primitive = qualified_process_ref(ns, name);
2086            let hand_authored = format!("{ns}/{name}");
2087            assert_eq!(
2088                via_primitive, hand_authored,
2089                "qualified_process_ref must be byte-identical to \
2090                 the pre-lift `format!(\"{{ns}}/{{name}}\")` \
2091                 hand-authored shape on ({ns:?}, {name:?})"
2092            );
2093        }
2094    }
2095}
2096
2097#[cfg(test)]
2098mod qualified_error_ctx_tests {
2099    //! Pin the [`qualified_error_ctx`] composer at fail-before-
2100    //! pass-after granularity across the shape it factored out of
2101    //! the two peer per-Kind composers
2102    //! ([`crate::configmap::error_ctx`],
2103    //! [`crate::process_api::error_ctx`]). Every observable slot
2104    //! (verb-first, fixed-Kind literal in the middle, `<ns>/<name>`
2105    //! join at the tail routed through
2106    //! [`qualified_process_ref`]) is bound here so a regression
2107    //! that reordered the head slots, dropped the fixed `<Kind>`
2108    //! word, drifted the qualified-ref join off the substrate axis,
2109    //! or narrowed any input slot to a closed set (would silently
2110    //! reject a future per-Kind peer that composes a fresh verb or
2111    //! Kind literal) surfaces HERE rather than as silent operator-
2112    //! facing skew at the two consumer peers.
2113    use super::qualified_error_ctx;
2114
2115    #[test]
2116    fn qualified_error_ctx_signature_binds_borrowed_slots_returning_owned_string() {
2117        // Signature pin: `verb: &str` + `kind: &str` + `ns: &str` +
2118        // `name: &str` on the input side (both pre-lift per-Kind
2119        // peers pass a `&'static str` verb + `&'static str` fixed-
2120        // Kind literal + borrowed `&str` ns/name fields). Return
2121        // `String` matches the downstream `kube_ctx_with(context:
2122        // String)` sink verbatim on the reconciler-boundary
2123        // consumers AND the `with_context(|| String)` closure form
2124        // on the export-worker consumers.
2125        //
2126        // A regression that widened any input slot to `String`
2127        // (forcing the caller to `.to_string()` at the boundary — a
2128        // per-site perf regression that also fights the
2129        // `&str`-fields-in-args idiom the callers thread) or
2130        // narrowed the return to `&'static str` (which would prevent
2131        // the runtime-composed ns/name slots the two peer composers
2132        // pass) fails at compile time.
2133        let _witness: fn(&str, &str, &str, &str) -> String = qualified_error_ctx;
2134    }
2135
2136    #[test]
2137    fn qualified_error_ctx_composes_verb_kind_qualified_ref_head_verbatim() {
2138        // Byte-shape parity witness on the primary shape both peer
2139        // composers depend on: the composed slug MUST be exactly
2140        // `"<verb> <Kind> <ns>/<name>"` in that order. A regression
2141        // that reordered the head slots (verb after Kind, Kind
2142        // after the qualified ref) would silently break every
2143        // operator-facing grep every downstream diagnostic body
2144        // riding through the sibling per-Kind peers uses.
2145        assert_eq!(
2146            qualified_error_ctx("fetch", "Process", "default", "api"),
2147            "fetch Process default/api",
2148        );
2149        assert_eq!(
2150            qualified_error_ctx("patch", "ConfigMap", "demo-ns", "receipt-cm"),
2151            "patch ConfigMap demo-ns/receipt-cm",
2152        );
2153    }
2154
2155    #[test]
2156    fn qualified_error_ctx_routes_ns_name_join_through_qualified_process_ref_substrate() {
2157        // Routing pin — the `<ns>/<name>` join at the composer's
2158        // tail rides through the workspace-wide
2159        // [`qualified_process_ref`] primitive rather than a bare
2160        // inline `format!("{ns}/{name}")`. A future normalization
2161        // of the qualified-ref shape (case-fold, unicode collation,
2162        // IDN) lands at ONE [`qualified_process_ref`] site and
2163        // every per-Kind diagnostic body picks it up mechanically;
2164        // this pin binds THIS composer to that substrate so a
2165        // regression that inlined the join (drifting the primitive
2166        // off the substrate axis this commit opens) surfaces HERE
2167        // rather than as silent qualified-ref drift between the
2168        // two peer per-Kind composers and every other qualified-
2169        // ref consumer across the workspace.
2170        for (verb, kind, ns, name) in [
2171            ("fetch", "Process", "default", "api"),
2172            ("get", "Process", "tatara-system", "reconciler-canary"),
2173            ("patch", "ConfigMap", "demo-ns", "receipt-cm"),
2174            ("create", "ConfigMap", "ns-1", "cm.dotted.name"),
2175        ] {
2176            let via_composer = qualified_error_ctx(verb, kind, ns, name);
2177            let via_qualified = format!("{verb} {kind} {}", super::qualified_process_ref(ns, name));
2178            assert_eq!(
2179                via_composer, via_qualified,
2180                "qualified_error_ctx must route the (ns, name) join through \
2181                 qualified_process_ref for ({verb:?}, {kind:?}, {ns:?}, {name:?})",
2182            );
2183        }
2184    }
2185
2186    #[test]
2187    fn qualified_error_ctx_is_symbolic_over_the_kind_slot() {
2188        // Symbolic pin: the `kind` slot is threaded verbatim into
2189        // the produced slug — no case-fold, no allow-list narrowing
2190        // to the two shipped Kinds (`"ConfigMap"`, `"Process"`), no
2191        // per-Kind canonicalization. A regression that hardcoded
2192        // an allow-list (a `match kind { "ConfigMap" | "Process" =>
2193        // …, _ => … }` closed set that would silently reject future
2194        // per-Kind peers) surfaces HERE.
2195        //
2196        // Future third + fourth per-Kind peers (a `Secret` axis
2197        // reader, a `batch/v1::Job` axis reader for the
2198        // ConditionKind::JobAttested companion, a FluxCD
2199        // `HelmRelease` axis reader for the P2 reconciler's
2200        // emit-side) inherit the primitive at their own peer
2201        // composers and pass their own Kind literals verbatim
2202        // without the composer widening.
2203        for kind in [
2204            "ConfigMap",
2205            "Process",
2206            "Secret",
2207            "Job",
2208            "HelmRelease",
2209            "OCIRepository",
2210            "Deployment",
2211            "StatefulSet",
2212        ] {
2213            let got = qualified_error_ctx("fetch", kind, "default", "api");
2214            let expected = format!("fetch {kind} default/api");
2215            assert_eq!(
2216                got, expected,
2217                "kind-slot substitution must be verbatim for {kind:?}"
2218            );
2219        }
2220    }
2221
2222    #[test]
2223    fn qualified_error_ctx_is_symbolic_over_the_verb_slot() {
2224        // Symbolic pin: the `verb` slot is threaded verbatim — same
2225        // discipline as the sibling verb-slot pins on the two peer
2226        // per-Kind composers ([`crate::configmap::tests::
2227        // error_ctx_is_symbolic_over_the_verb_slot`] via absence,
2228        // [`crate::process_api::tests::
2229        // error_ctx_is_symbolic_over_the_verb_slot`]). Post-lift
2230        // both peers route through this composer so this pin binds
2231        // the shared symbolic contract at ONE substrate owner rather
2232        // than as two parallel pins that could drift.
2233        for verb in [
2234            "fetch", "get", "reap", "resolve", "watch", "patch", "delete", "create",
2235        ] {
2236            let got = qualified_error_ctx(verb, "Process", "default", "api");
2237            let expected = format!("{verb} Process default/api");
2238            assert_eq!(
2239                got, expected,
2240                "verb-slot substitution must be verbatim for {verb:?}"
2241            );
2242        }
2243    }
2244
2245    #[test]
2246    fn qualified_error_ctx_matches_configmap_peer_bytewise() {
2247        // Post-lift peer coherence pin: the composer's output at
2248        // `<Kind> = "ConfigMap"` MUST be byte-identical to the
2249        // [`crate::configmap::error_ctx`] peer's output at the SAME
2250        // (verb, ns, name) triple. The peer is now a one-line
2251        // delegate through this composer, so a regression that
2252        // dropped or drifted the delegation would surface HERE.
2253        for (verb, ns, name) in [
2254            ("patch", "default", "receipt-cm"),
2255            ("create", "demo-ns", "cm-01"),
2256            ("get", "ns-1", "receipt.dotted.name"),
2257        ] {
2258            let via_composer = qualified_error_ctx(verb, "ConfigMap", ns, name);
2259            let via_peer = crate::configmap::error_ctx(verb, ns, name);
2260            assert_eq!(
2261                via_composer, via_peer,
2262                "configmap::error_ctx must route through qualified_error_ctx \
2263                 for ({verb:?}, {ns:?}, {name:?})"
2264            );
2265        }
2266    }
2267
2268    #[test]
2269    fn qualified_error_ctx_matches_process_api_peer_bytewise() {
2270        // Post-lift peer coherence pin: the composer's output at
2271        // `<Kind> = "Process"` MUST be byte-identical to the
2272        // [`crate::process_api::error_ctx`] peer's output at the
2273        // SAME (verb, ns, name) triple. Peer to the ConfigMap
2274        // coherence pin above — both peers now delegate through the
2275        // SAME 4-slot composer, so a regression that drifted either
2276        // delegation surfaces at exactly ONE of the two
2277        // fail-before-pass-after pins.
2278        for (verb, ns, name) in [
2279            ("fetch", "default", "api"),
2280            ("get", "demo-ns", "demo"),
2281            ("watch", "tatara-system", "reconciler-canary"),
2282        ] {
2283            let via_composer = qualified_error_ctx(verb, "Process", ns, name);
2284            let via_peer = crate::process_api::error_ctx(verb, ns, name);
2285            assert_eq!(
2286                via_composer, via_peer,
2287                "process_api::error_ctx must route through qualified_error_ctx \
2288                 for ({verb:?}, {ns:?}, {name:?})"
2289            );
2290        }
2291    }
2292
2293    #[test]
2294    fn qualified_error_ctx_rides_edge_case_axis_shapes() {
2295        // Edge-case pin: the composer performs NO validation on the
2296        // four slots — an empty verb / empty Kind / empty ns / empty
2297        // name / slash-in-name pathological input rides through
2298        // unchanged. Matches the pre-lift per-Kind peers' semantics
2299        // (both were unconditional `format!(…)` chains). A
2300        // regression that added a normalization step (URL-escaping
2301        // the slot values, path-normalizing the qualified-ref tail,
2302        // trimming empty slots) at this primitive would silently
2303        // break every downstream grep operators run to bisect an
2304        // authoring bug in the pre-lift consumers' input surface.
2305        assert_eq!(qualified_error_ctx("", "", "", ""), "  /");
2306        assert_eq!(
2307            qualified_error_ctx("fetch", "Process", "", ""),
2308            "fetch Process /",
2309        );
2310        assert_eq!(
2311            qualified_error_ctx("fetch", "Process", "default", ""),
2312            "fetch Process default/",
2313        );
2314        assert_eq!(
2315            qualified_error_ctx("get", "Process", "ns", "with/slash"),
2316            "get Process ns/with/slash",
2317        );
2318    }
2319}
2320
2321#[cfg(test)]
2322mod namespaced_api_coordinates_tests {
2323    //! Pin the [`NamespacedApiCoordinates`] trait's
2324    //! `owned_coordinates_required` extractor at fail-before-pass-
2325    //! after granularity across every corner of the (namespace slot,
2326    //! name slot) × (present, absent) input matrix, on BOTH CRDs the
2327    //! trait's blanket impl covers today (`EphemeralPool` +
2328    //! `EphemeralAllocation`). A regression that reordered the two
2329    //! `ok_or_else` gates, dropped the `Self::kind` prefix, or drifted
2330    //! the error-string spelling surfaces HERE rather than as silent
2331    //! operator-facing skew between the two reconcilers' top-level
2332    //! error messages.
2333    use super::NamespacedApiCoordinates;
2334    use crate::allocation::{AllocationSpec, EphemeralAllocation, Requestor};
2335    use crate::ephemeral::EphemeralSpec;
2336    use crate::intent::AplicacaoIntent;
2337    use crate::lifetime::TeardownPolicy;
2338    use crate::pool::{EphemeralPool, PoolSpec};
2339
2340    fn empty_template() -> EphemeralSpec {
2341        // Mirror `tatara-pool-reconciler::router::tests::empty_template`
2342        // — the workspace-wide minimal `EphemeralSpec` fixture the sister
2343        // reconciler tests already use for pool wiring exercised here.
2344        EphemeralSpec {
2345            aplicacao: AplicacaoIntent::chart_only("oci://x", "1"),
2346            ttl: "1h".into(),
2347            teardown: TeardownPolicy::Always,
2348            max_concurrent: 0,
2349            postconditions: vec![],
2350            preconditions: vec![],
2351            verify_timeout: None,
2352            classification: None,
2353            parent: None,
2354            exports: vec![],
2355            routing: None,
2356        }
2357    }
2358
2359    fn pool_fixture(name: &str, ns: Option<&str>) -> EphemeralPool {
2360        // Every non-template slot rides the ONE substrate composer
2361        // [`PoolSpec::with_template`]; pre-lift this fixture spelled the
2362        // full 11-slot struct-literal verbatim as one of eight cross-
2363        // crate hand-authored copies. See the primitive's doc-comment
2364        // for the full migration rationale.
2365        let spec = PoolSpec {
2366            desired_size: 1,
2367            ..PoolSpec::with_template(empty_template())
2368        };
2369        let mut p = EphemeralPool::new(name, spec);
2370        p.metadata.namespace = ns.map(str::to_string);
2371        p
2372    }
2373
2374    fn alloc_fixture(name: &str, ns: Option<&str>) -> EphemeralAllocation {
2375        // AllocationSpec rides through the ONE substrate composer
2376        // `AllocationSpec::requestor_only`; the inner Requestor rides
2377        // through the peer composer `Requestor::kind_only`. Nine
2378        // pre-lift exact-match sites past the ★★ PRIME-DIRECTIVE ≥ 2
2379        // threshold collapse onto this ONE substrate owner.
2380        let spec = AllocationSpec::requestor_only(Requestor::kind_only("github-pr"));
2381        let mut a = EphemeralAllocation::new(name, spec);
2382        a.metadata.namespace = ns.map(str::to_string);
2383        a
2384    }
2385
2386    fn nameless_pool(ns: Option<&str>) -> EphemeralPool {
2387        let mut p = pool_fixture("placeholder", ns);
2388        p.metadata.name = None;
2389        p
2390    }
2391
2392    fn nameless_alloc(ns: Option<&str>) -> EphemeralAllocation {
2393        let mut a = alloc_fixture("placeholder", ns);
2394        a.metadata.name = None;
2395        a
2396    }
2397
2398    // ── Happy path: both slots present ─────────────────────────────
2399
2400    #[test]
2401    fn owned_coordinates_required_returns_owned_strings_on_ephemeral_pool_when_both_slots_present()
2402    {
2403        let p = pool_fixture("attest-pool", Some("ephemeral-pools"));
2404        let (ns, name) = p.owned_coordinates_required().unwrap();
2405        assert_eq!(ns, "ephemeral-pools");
2406        assert_eq!(name, "attest-pool");
2407    }
2408
2409    #[test]
2410    fn owned_coordinates_required_returns_owned_strings_on_ephemeral_allocation_when_both_slots_present(
2411    ) {
2412        let a = alloc_fixture("pr-42-demo", Some("ephemeral-pools"));
2413        let (ns, name) = a.owned_coordinates_required().unwrap();
2414        assert_eq!(ns, "ephemeral-pools");
2415        assert_eq!(name, "pr-42-demo");
2416    }
2417
2418    // ── Missing namespace ─────────────────────────────────────────
2419
2420    #[test]
2421    fn owned_coordinates_required_errors_on_ephemeral_pool_missing_namespace() {
2422        let p = pool_fixture("attest-pool", None);
2423        let err = p.owned_coordinates_required().unwrap_err();
2424        assert_eq!(err.to_string(), "EphemeralPool has no metadata.namespace");
2425    }
2426
2427    #[test]
2428    fn owned_coordinates_required_errors_on_ephemeral_allocation_missing_namespace() {
2429        let a = alloc_fixture("pr-42-demo", None);
2430        let err = a.owned_coordinates_required().unwrap_err();
2431        assert_eq!(
2432            err.to_string(),
2433            "EphemeralAllocation has no metadata.namespace"
2434        );
2435    }
2436
2437    // ── Missing name ──────────────────────────────────────────────
2438
2439    #[test]
2440    fn owned_coordinates_required_errors_on_ephemeral_pool_missing_name_when_namespace_present() {
2441        let p = nameless_pool(Some("ephemeral-pools"));
2442        let err = p.owned_coordinates_required().unwrap_err();
2443        assert_eq!(err.to_string(), "EphemeralPool has no metadata.name");
2444    }
2445
2446    #[test]
2447    fn owned_coordinates_required_errors_on_ephemeral_allocation_missing_name_when_namespace_present(
2448    ) {
2449        let a = nameless_alloc(Some("ephemeral-pools"));
2450        let err = a.owned_coordinates_required().unwrap_err();
2451        assert_eq!(err.to_string(), "EphemeralAllocation has no metadata.name");
2452    }
2453
2454    // ── Missing both slots: namespace error wins (pre-lift ordering) ──
2455
2456    #[test]
2457    fn owned_coordinates_required_reports_namespace_first_when_both_slots_absent_on_ephemeral_pool()
2458    {
2459        // Pre-lift both reconcilers spelled the paired chain as the
2460        // namespace ok_or_else THEN the name ok_or_else, so the
2461        // reported error on a fixture missing both slots was always
2462        // the namespace one. Pin that ordering post-lift so a
2463        // regression that swapped the two `ok_or_else` blocks
2464        // surfaces HERE rather than at operator-facing log-line
2465        // grep drift between the two reconcilers.
2466        let p = nameless_pool(None);
2467        let err = p.owned_coordinates_required().unwrap_err();
2468        assert_eq!(err.to_string(), "EphemeralPool has no metadata.namespace");
2469    }
2470
2471    #[test]
2472    fn owned_coordinates_required_reports_namespace_first_when_both_slots_absent_on_ephemeral_allocation(
2473    ) {
2474        let a = nameless_alloc(None);
2475        let err = a.owned_coordinates_required().unwrap_err();
2476        assert_eq!(
2477            err.to_string(),
2478            "EphemeralAllocation has no metadata.namespace"
2479        );
2480    }
2481
2482    // ── Byte-identical parity with the pre-lift 5-line chain ──────
2483
2484    #[test]
2485    fn owned_coordinates_required_matches_pre_lift_pool_reconciler_chain_shape() {
2486        // Byte-identical parity pin: the primitive produces the SAME
2487        // `Result<(String, String), anyhow::Error>` shape a pre-lift
2488        // `.metadata.<slot>.clone().ok_or_else(|| anyhow!("<Kind> has
2489        // no metadata.<slot>"))?` chain produced at
2490        // `tatara-pool-reconciler::controller_pool::reconcile_inner`
2491        // pre-lift, on both the happy and the missing-slot corners.
2492        // A regression that changed the error prefix, reordered the
2493        // two gates, or returned a non-`(String, String)` tuple
2494        // surfaces HERE rather than at every consumer downstream.
2495        let cases = [
2496            (Some("prod"), Some("api")),
2497            (Some("prod"), None),
2498            (None, Some("orphan")),
2499            (None, None),
2500        ];
2501        for (ns_slot, name_slot) in cases {
2502            let mut p = pool_fixture("placeholder", ns_slot);
2503            if let Some(nm) = name_slot {
2504                p.metadata.name = Some(nm.into());
2505            } else {
2506                p.metadata.name = None;
2507            }
2508
2509            // Pre-lift 5-line paired chain (with the reconciler's
2510            // hand-authored short-form `"Pool"` prefix updated to the
2511            // canonical kube kind `"EphemeralPool"`, matching the
2512            // primitive's `Self::kind`-driven spelling — the drift
2513            // is intentional per the trait's docs).
2514            let pre_lift: anyhow::Result<(String, String)> = (|| {
2515                let ns =
2516                    p.metadata.namespace.clone().ok_or_else(|| {
2517                        anyhow::anyhow!("EphemeralPool has no metadata.namespace")
2518                    })?;
2519                let name = p
2520                    .metadata
2521                    .name
2522                    .clone()
2523                    .ok_or_else(|| anyhow::anyhow!("EphemeralPool has no metadata.name"))?;
2524                Ok((ns, name))
2525            })();
2526
2527            let via_primitive = p.owned_coordinates_required();
2528
2529            // Compare on both the Ok tuple + the error string
2530            // spelling — anyhow::Error does not derive PartialEq so
2531            // pattern-match on the Result axis rather than a direct
2532            // `assert_eq!` on the whole Result.
2533            match (via_primitive, pre_lift) {
2534                (Ok(a), Ok(b)) => assert_eq!(a, b),
2535                (Err(a), Err(b)) => assert_eq!(a.to_string(), b.to_string()),
2536                (a, b) => panic!(
2537                    "primitive vs pre-lift chain disagree on Ok/Err axis for \
2538                     (ns={ns_slot:?}, name={name_slot:?}): primitive={a:?}, pre_lift={b:?}"
2539                ),
2540            }
2541        }
2542    }
2543
2544    #[test]
2545    fn owned_coordinates_required_matches_pre_lift_allocation_reconciler_chain_shape() {
2546        // Peer to the pool-side pin above — pin the same byte-
2547        // identity contract on the allocation reconciler's chain,
2548        // where the pre-lift error spelling used the short-form
2549        // `"Allocation"` prefix that the primitive now emits as the
2550        // canonical kube-kind `"EphemeralAllocation"`.
2551        let cases = [
2552            (Some("ephemeral-pools"), Some("pr-42-demo")),
2553            (Some("ephemeral-pools"), None),
2554            (None, Some("orphan")),
2555            (None, None),
2556        ];
2557        for (ns_slot, name_slot) in cases {
2558            let mut a = alloc_fixture("placeholder", ns_slot);
2559            if let Some(nm) = name_slot {
2560                a.metadata.name = Some(nm.into());
2561            } else {
2562                a.metadata.name = None;
2563            }
2564
2565            let pre_lift: anyhow::Result<(String, String)> = (|| {
2566                let ns = a.metadata.namespace.clone().ok_or_else(|| {
2567                    anyhow::anyhow!("EphemeralAllocation has no metadata.namespace")
2568                })?;
2569                let name =
2570                    a.metadata.name.clone().ok_or_else(|| {
2571                        anyhow::anyhow!("EphemeralAllocation has no metadata.name")
2572                    })?;
2573                Ok((ns, name))
2574            })();
2575
2576            let via_primitive = a.owned_coordinates_required();
2577
2578            match (via_primitive, pre_lift) {
2579                (Ok(a), Ok(b)) => assert_eq!(a, b),
2580                (Err(a), Err(b)) => assert_eq!(a.to_string(), b.to_string()),
2581                (a, b) => panic!(
2582                    "primitive vs pre-lift chain disagree on Ok/Err axis for \
2583                     (ns={ns_slot:?}, name={name_slot:?}): primitive={a:?}, pre_lift={b:?}"
2584                ),
2585            }
2586        }
2587    }
2588
2589    // ── Cross-CRD symmetry: kube kind drives the error prefix ─────
2590
2591    #[test]
2592    fn owned_coordinates_required_error_prefix_matches_kube_kind_on_each_crd() {
2593        // The error prefix is sourced positionally from `Self::kind`
2594        // so the two CRDs emit distinct kube-canonical spellings
2595        // without either callsite hard-coding a per-CRD literal.
2596        // Regressions that hard-coded a shared prefix (e.g. a
2597        // copy-paste that pasted the pool's error string into the
2598        // allocation callsite) surface HERE.
2599        use kube::Resource;
2600        let p = pool_fixture("p", None);
2601        let a = alloc_fixture("a", None);
2602        assert_eq!(
2603            p.owned_coordinates_required().unwrap_err().to_string(),
2604            format!("{} has no metadata.namespace", EphemeralPool::kind(&()))
2605        );
2606        assert_eq!(
2607            a.owned_coordinates_required().unwrap_err().to_string(),
2608            format!(
2609                "{} has no metadata.namespace",
2610                EphemeralAllocation::kind(&())
2611            )
2612        );
2613        // Belt-and-suspenders: the two kinds are distinct spellings,
2614        // so the error strings are distinct too.
2615        assert_ne!(
2616            p.owned_coordinates_required().unwrap_err().to_string(),
2617            a.owned_coordinates_required().unwrap_err().to_string(),
2618        );
2619    }
2620}
2621
2622#[cfg(test)]
2623mod deletion_tombstoned_tests {
2624    //! Pin the [`DeletionTombstoned`] trait's `is_being_deleted` probe
2625    //! at fail-before-pass-after granularity across every corner of
2626    //! the (tombstone present, tombstone absent) input matrix, on
2627    //! ALL THREE tatara-process CRDs the trait's blanket impl covers
2628    //! today (`Process`, `EphemeralPool`, `EphemeralAllocation`), plus
2629    //! the cross-CRD coherence with the two pre-existing inherent
2630    //! forwarders. A regression that skewed the trait's default,
2631    //! promoted a distinct-payload tombstone to a false negative, or
2632    //! diverged the trait from either inherent forwarder surfaces
2633    //! HERE rather than as silent operator-facing skew between the
2634    //! four consumer sites the primitive owns (the top-level
2635    //! dispatcher's SIGTERM preempt, the SIGTERM cascade's child-
2636    //! fan-out DELETE-skip, the pool reconciler's Drain gate, and
2637    //! the allocation reconciler's release short-circuit) on three
2638    //! sibling CRDs.
2639    use super::DeletionTombstoned;
2640    use crate::allocation::{AllocationSpec, EphemeralAllocation, Requestor};
2641    use crate::crd::{Process, ProcessSpec};
2642    use crate::ephemeral::EphemeralSpec;
2643    use crate::intent::AplicacaoIntent;
2644    use crate::lifetime::TeardownPolicy;
2645    use crate::pool::{EphemeralPool, PoolSpec};
2646    use k8s_openapi::apimachinery::pkg::apis::meta::v1::Time;
2647
2648    fn empty_template() -> EphemeralSpec {
2649        EphemeralSpec {
2650            aplicacao: AplicacaoIntent::chart_only("oci://x", "1"),
2651            ttl: "1h".into(),
2652            teardown: TeardownPolicy::Always,
2653            max_concurrent: 0,
2654            postconditions: vec![],
2655            preconditions: vec![],
2656            verify_timeout: None,
2657            classification: None,
2658            parent: None,
2659            exports: vec![],
2660            routing: None,
2661        }
2662    }
2663
2664    fn empty_pool_spec() -> PoolSpec {
2665        // Every non-template slot rides the ONE substrate composer
2666        // [`PoolSpec::with_template`]; see the primitive's doc-comment
2667        // for the full migration rationale.
2668        PoolSpec {
2669            desired_size: 1,
2670            ..PoolSpec::with_template(empty_template())
2671        }
2672    }
2673
2674    fn empty_alloc_spec() -> AllocationSpec {
2675        // AllocationSpec rides through the ONE substrate composer
2676        // `AllocationSpec::requestor_only`; the inner Requestor rides
2677        // through `Requestor::kind_only`. Nine pre-lift exact-match
2678        // fixture sites past the ★★ PRIME-DIRECTIVE ≥ 2 threshold
2679        // collapse onto this ONE substrate owner.
2680        AllocationSpec::requestor_only(Requestor::kind_only("github-pr"))
2681    }
2682
2683    fn empty_process_spec() -> ProcessSpec {
2684        // Routes through the ONE substrate composer
2685        // `ProcessSpec::gate_compute_defaults` — the minimal
2686        // `ProcessSpec` used across every substrate metadata-projection
2687        // pin. Pre-lift this was the 12-line struct-literal restated
2688        // verbatim at every fixture in this pin family.
2689        ProcessSpec::gate_compute_defaults()
2690    }
2691
2692    // ── Missing tombstone (default fixture) — trait returns false ─────
2693
2694    #[test]
2695    fn is_being_deleted_on_process_missing_tombstone_returns_false_via_trait() {
2696        let p = Process::new("api", empty_process_spec());
2697        assert!(!DeletionTombstoned::is_being_deleted(&p));
2698    }
2699
2700    #[test]
2701    fn is_being_deleted_on_ephemeral_pool_missing_tombstone_returns_false_via_trait() {
2702        let p = EphemeralPool::new("attest-pool", empty_pool_spec());
2703        assert!(!DeletionTombstoned::is_being_deleted(&p));
2704    }
2705
2706    #[test]
2707    fn is_being_deleted_on_ephemeral_allocation_missing_tombstone_returns_false_via_trait() {
2708        // The load-bearing corner: EphemeralAllocation had NO inherent
2709        // is_being_deleted pre-lift — the trait's blanket impl is
2710        // what closes the substrate gap for the allocation reconciler's
2711        // hand-authored `.metadata.deletion_timestamp.is_some()` chain.
2712        let a = EphemeralAllocation::new("pr-42-demo", empty_alloc_spec());
2713        assert!(!DeletionTombstoned::is_being_deleted(&a));
2714    }
2715
2716    // ── Present tombstone — trait returns true ────────────────────────
2717
2718    #[test]
2719    fn is_being_deleted_on_process_present_tombstone_returns_true_via_trait() {
2720        let mut p = Process::new("api", empty_process_spec());
2721        // Routes through the ONE substrate composer
2722        // `tatara_process::time::tombstone_now` — one of 12 pre-lift
2723        // exact-match sites past the ★★ PRIME-DIRECTIVE ≥ 2 threshold
2724        // for the `Some(Time(Utc::now()))` wire shape.
2725        p.metadata.deletion_timestamp = crate::time::tombstone_now();
2726        assert!(DeletionTombstoned::is_being_deleted(&p));
2727    }
2728
2729    #[test]
2730    fn is_being_deleted_on_ephemeral_pool_present_tombstone_returns_true_via_trait() {
2731        let mut p = EphemeralPool::new("attest-pool", empty_pool_spec());
2732        p.metadata.deletion_timestamp = crate::time::tombstone_now();
2733        assert!(DeletionTombstoned::is_being_deleted(&p));
2734    }
2735
2736    #[test]
2737    fn is_being_deleted_on_ephemeral_allocation_present_tombstone_returns_true_via_trait() {
2738        let mut a = EphemeralAllocation::new("pr-42-demo", empty_alloc_spec());
2739        a.metadata.deletion_timestamp = crate::time::tombstone_now();
2740        assert!(DeletionTombstoned::is_being_deleted(&a));
2741    }
2742
2743    // ── Byte-identical parity with the pre-lift `.is_some()` chain ────
2744
2745    #[test]
2746    fn is_being_deleted_matches_pre_lift_deletion_timestamp_is_some_chain_on_ephemeral_allocation()
2747    {
2748        // Byte-identical parity pin: the trait's default produces the
2749        // SAME `bool` a pre-lift `.metadata.deletion_timestamp.is_some()`
2750        // chain produced at `tatara-pool-reconciler::allocation_decide::
2751        // AllocationConvergenceCtx::observe` pre-lift, across every
2752        // corner of the (absent, present-at-now, present-at-past)
2753        // input matrix. A regression that inserted a normalization
2754        // step the pre-lift chain does NOT apply — or vice versa —
2755        // surfaces here rather than as silent drift between the
2756        // substrate owner and the pre-lift consumer.
2757        // Routes through the ONE substrate composer family
2758        // `tatara_process::time::{tombstone_now,tombstone_at}` — the
2759        // present-at-now corner rides `tombstone_now`, the present-at-
2760        // past corner composes `tombstone_at(seconds_ago(3600))` per
2761        // the composer's canonical stale-fixture shape.
2762        let mut cases: Vec<Option<Time>> = vec![None];
2763        cases.push(crate::time::tombstone_now());
2764        cases.push(crate::time::tombstone_at(crate::time::seconds_ago(3600)));
2765
2766        for ts in cases {
2767            let mut a = EphemeralAllocation::new("pr-42-demo", empty_alloc_spec());
2768            a.metadata.deletion_timestamp = ts.clone();
2769
2770            let pre_lift = a.metadata.deletion_timestamp.is_some();
2771            let via_trait = DeletionTombstoned::is_being_deleted(&a);
2772
2773            assert_eq!(
2774                pre_lift, via_trait,
2775                "trait probe must be byte-identical to pre-lift .metadata.deletion_timestamp.is_some() on tombstone={ts:?}",
2776            );
2777        }
2778    }
2779
2780    // ── Cross-CRD coherence with the two inherent forwarders ──────────
2781
2782    #[test]
2783    fn trait_probe_coheres_with_process_inherent_is_being_deleted_on_both_corners() {
2784        // Cross-primitive coherence pin: the trait's default and the
2785        // pre-existing `Process::is_being_deleted` inherent forwarder
2786        // return the SAME `bool` on the SAME `Process` value — a
2787        // future consolidation of the inherent onto the trait's default
2788        // (or vice versa) cannot land any drift between the two
2789        // surfaces because this pin binds them at every corner of the
2790        // (missing, present) input matrix.
2791        // Routes the tombstone-present corner through the ONE
2792        // substrate composer `tatara_process::time::tombstone_now`.
2793        for ts in [None, crate::time::tombstone_now()] {
2794            let mut p = Process::new("api", empty_process_spec());
2795            p.metadata.deletion_timestamp = ts.clone();
2796            assert_eq!(
2797                p.is_being_deleted(),
2798                DeletionTombstoned::is_being_deleted(&p),
2799                "Process trait probe must match inherent on tombstone={ts:?}",
2800            );
2801        }
2802    }
2803
2804    #[test]
2805    fn trait_probe_coheres_with_ephemeral_pool_inherent_is_being_deleted_on_both_corners() {
2806        // Peer coherence pin on the sister CRD.
2807        for ts in [None, crate::time::tombstone_now()] {
2808            let mut p = EphemeralPool::new("attest-pool", empty_pool_spec());
2809            p.metadata.deletion_timestamp = ts.clone();
2810            assert_eq!(
2811                p.is_being_deleted(),
2812                DeletionTombstoned::is_being_deleted(&p),
2813                "EphemeralPool trait probe must match inherent on tombstone={ts:?}",
2814            );
2815        }
2816    }
2817
2818    // ── Inherent-preferred method resolution on Process + EphemeralPool ──
2819
2820    #[test]
2821    fn dot_call_on_process_resolves_to_inherent_when_trait_in_scope() {
2822        // Rust method resolution prefers an inherent over a trait's
2823        // blanket impl, so `process.is_being_deleted()` with the trait
2824        // in scope still routes through the inherent — and both
2825        // return the same `bool` (verified in
2826        // `trait_probe_coheres_with_process_inherent_is_being_deleted_on_both_corners`).
2827        // This pin guards against a future refactor that removes the
2828        // inherent but leaves consumers assuming inherent-preferred
2829        // resolution — the observable output is identical either way,
2830        // so the pin locks the invariant that BOTH paths agree.
2831        let mut p = Process::new("api", empty_process_spec());
2832        // Routes through `tatara_process::time::tombstone_now`.
2833        p.metadata.deletion_timestamp = crate::time::tombstone_now();
2834        assert!(p.is_being_deleted());
2835    }
2836
2837    #[test]
2838    fn dot_call_on_ephemeral_allocation_resolves_to_trait_blanket_impl() {
2839        // The load-bearing corner: `alloc.is_being_deleted()` with
2840        // the trait in scope routes to the trait's blanket impl
2841        // (there is no inherent on `EphemeralAllocation`) and
2842        // produces the expected `bool`. This is what the swept
2843        // allocation-reconciler callsite depends on post-lift.
2844        let mut a = EphemeralAllocation::new("pr-42-demo", empty_alloc_spec());
2845        assert!(!a.is_being_deleted());
2846        a.metadata.deletion_timestamp = crate::time::tombstone_now();
2847        assert!(a.is_being_deleted());
2848    }
2849}
2850
2851#[cfg(test)]
2852mod annotated_tests {
2853    //! Pin the [`Annotated`] trait's `annotation` lookup at fail-
2854    //! before-pass-after granularity across every corner of the
2855    //! (annotations map: absent / present-empty / present-with-key /
2856    //! present-without-key) × (value form: normal / empty-string)
2857    //! input matrix, on the three tatara-process CRDs the trait's
2858    //! blanket impl covers today (`Process`, `EphemeralPool`,
2859    //! `EphemeralAllocation`) PLUS a K8s built-in (`ConfigMap`) — the
2860    //! load-bearing fourth surface that `tatara-export-worker::main`
2861    //! consumes post-lift where no tatara-owned inherent forwarder
2862    //! exists. Also pin cross-primitive coherence with the pre-existing
2863    //! `Process::annotation` inherent so a future consolidation onto
2864    //! the trait's default cannot silently skew the three consumers
2865    //! already routed through the inherent
2866    //! (`signals::ingest`,
2867    //! `phase_machine::released_from_annotation`,
2868    //! `controller_pool::process_belongs_to_pool`).
2869    use super::Annotated;
2870    use crate::allocation::{AllocationSpec, EphemeralAllocation, Requestor};
2871    use crate::crd::{Process, ProcessSpec};
2872    use crate::ephemeral::EphemeralSpec;
2873    use crate::intent::AplicacaoIntent;
2874    use crate::lifetime::TeardownPolicy;
2875    use crate::pool::{EphemeralPool, PoolSpec};
2876    use k8s_openapi::api::core::v1::ConfigMap;
2877    use std::collections::BTreeMap;
2878
2879    fn empty_template() -> EphemeralSpec {
2880        EphemeralSpec {
2881            aplicacao: AplicacaoIntent::chart_only("oci://x", "1"),
2882            ttl: "1h".into(),
2883            teardown: TeardownPolicy::Always,
2884            max_concurrent: 0,
2885            postconditions: vec![],
2886            preconditions: vec![],
2887            verify_timeout: None,
2888            classification: None,
2889            parent: None,
2890            exports: vec![],
2891            routing: None,
2892        }
2893    }
2894
2895    fn empty_pool_spec() -> PoolSpec {
2896        // Every non-template slot rides the ONE substrate composer
2897        // [`PoolSpec::with_template`]; see the primitive's doc-comment
2898        // for the full migration rationale.
2899        PoolSpec {
2900            desired_size: 1,
2901            ..PoolSpec::with_template(empty_template())
2902        }
2903    }
2904
2905    fn empty_alloc_spec() -> AllocationSpec {
2906        // AllocationSpec rides through `AllocationSpec::requestor_only`;
2907        // the inner Requestor rides through `Requestor::kind_only` —
2908        // sibling to the peer `empty_alloc_spec` fixture in the
2909        // DeletionTombstoned pin module above.
2910        AllocationSpec::requestor_only(Requestor::kind_only("github-pr"))
2911    }
2912
2913    fn empty_process_spec() -> ProcessSpec {
2914        // Routes through the ONE substrate composer
2915        // `ProcessSpec::gate_compute_defaults` — sibling to the
2916        // `empty_process_spec` fixture in the DeletionTombstoned pin
2917        // module above and to `empty_spec` in `crd.rs::tests`.
2918        ProcessSpec::gate_compute_defaults()
2919    }
2920
2921    fn one_annotation(key: &str, value: &str) -> BTreeMap<String, String> {
2922        let mut m = BTreeMap::new();
2923        m.insert(key.into(), value.into());
2924        m
2925    }
2926
2927    // ── Missing annotations map — trait returns None on every key ─────
2928
2929    #[test]
2930    fn annotation_on_process_missing_annotations_returns_none_via_trait() {
2931        let mut p = Process::new("api", empty_process_spec());
2932        p.metadata.annotations = None;
2933        assert_eq!(Annotated::annotation(&p, "tatara.pleme.io/signal"), None);
2934        assert_eq!(Annotated::annotation(&p, ""), None);
2935    }
2936
2937    #[test]
2938    fn annotation_on_ephemeral_pool_missing_annotations_returns_none_via_trait() {
2939        let mut p = EphemeralPool::new("attest-pool", empty_pool_spec());
2940        p.metadata.annotations = None;
2941        assert_eq!(Annotated::annotation(&p, "tatara.pleme.io/pool"), None);
2942    }
2943
2944    #[test]
2945    fn annotation_on_ephemeral_allocation_missing_annotations_returns_none_via_trait() {
2946        // The peer load-bearing corner: EphemeralAllocation has NO
2947        // inherent `annotation()` pre-lift — the trait's blanket impl
2948        // is what closes the substrate gap here, exactly as the
2949        // sibling `DeletionTombstoned` trait already did on the
2950        // tombstone axis for the SAME third CRD.
2951        let mut a = EphemeralAllocation::new("pr-42-demo", empty_alloc_spec());
2952        a.metadata.annotations = None;
2953        assert_eq!(
2954            Annotated::annotation(&a, "tatara.pleme.io/requestor-kind"),
2955            None,
2956        );
2957    }
2958
2959    #[test]
2960    fn annotation_on_config_map_missing_annotations_returns_none_via_trait() {
2961        // The load-bearing corner the export-worker's post-lift call
2962        // depends on: `ConfigMap` is a K8s built-in with no tatara-
2963        // owned inherent forwarder, and the receipts-owner filter
2964        // needs to route through the trait's blanket impl at
2965        // `cm.annotation(KEY)`.
2966        let cm = ConfigMap::default();
2967        // `Default::default()` produces an object with an empty
2968        // ObjectMeta whose `annotations` slot is `None` — the exact
2969        // missing-annotations corner the trait must collapse to
2970        // `None` at every key lookup, matching what the pre-lift
2971        // `cm.metadata.annotations.as_ref().and_then(...)` chain
2972        // produced.
2973        assert_eq!(Annotated::annotation(&cm, "tatara.pleme.io/process"), None,);
2974    }
2975
2976    // ── Missing key inside populated map — trait returns None ─────────
2977
2978    #[test]
2979    fn annotation_on_process_missing_key_returns_none_via_trait() {
2980        let mut p = Process::new("api", empty_process_spec());
2981        p.metadata.annotations = Some(one_annotation("other/key", "irrelevant"));
2982        assert_eq!(Annotated::annotation(&p, "tatara.pleme.io/signal"), None);
2983        assert_eq!(Annotated::annotation(&p, ""), None);
2984    }
2985
2986    #[test]
2987    fn annotation_on_config_map_missing_key_returns_none_via_trait() {
2988        let mut cm = ConfigMap::default();
2989        cm.metadata.annotations = Some(one_annotation("unrelated", "yes"));
2990        assert_eq!(Annotated::annotation(&cm, "tatara.pleme.io/process"), None,);
2991    }
2992
2993    // ── Present key — trait returns borrowed slice ────────────────────
2994
2995    #[test]
2996    fn annotation_on_process_present_key_returns_borrowed_slice_via_trait() {
2997        let mut p = Process::new("api", empty_process_spec());
2998        p.metadata.annotations = Some(one_annotation("tatara.pleme.io/signal", "SIGHUP"));
2999        assert_eq!(
3000            Annotated::annotation(&p, "tatara.pleme.io/signal"),
3001            Some("SIGHUP"),
3002        );
3003    }
3004
3005    #[test]
3006    fn annotation_on_ephemeral_pool_present_key_returns_borrowed_slice_via_trait() {
3007        let mut p = EphemeralPool::new("attest-pool", empty_pool_spec());
3008        p.metadata.annotations = Some(one_annotation("tatara.pleme.io/pool", "demo-pool"));
3009        assert_eq!(
3010            Annotated::annotation(&p, "tatara.pleme.io/pool"),
3011            Some("demo-pool"),
3012        );
3013    }
3014
3015    #[test]
3016    fn annotation_on_ephemeral_allocation_present_key_returns_borrowed_slice_via_trait() {
3017        let mut a = EphemeralAllocation::new("pr-42-demo", empty_alloc_spec());
3018        a.metadata.annotations = Some(one_annotation(
3019            "tatara.pleme.io/requestor-kind",
3020            "github-pr",
3021        ));
3022        assert_eq!(
3023            Annotated::annotation(&a, "tatara.pleme.io/requestor-kind"),
3024            Some("github-pr"),
3025        );
3026    }
3027
3028    #[test]
3029    fn annotation_on_config_map_present_key_returns_borrowed_slice_via_trait() {
3030        // The exact receipts-owner filter shape from
3031        // `tatara-export-worker::main`: a ConfigMap carrying the
3032        // `tatara.pleme.io/process` annotation set to the qualified
3033        // process reference `<ns>/<name>`. Pin that the trait produces
3034        // the exact borrowed slice the equality comparison against the
3035        // caller's `want.as_str()` sentinel consumes.
3036        let mut cm = ConfigMap::default();
3037        cm.metadata.annotations = Some(one_annotation(
3038            "tatara.pleme.io/process",
3039            "demo-ns/demo-app",
3040        ));
3041        assert_eq!(
3042            Annotated::annotation(&cm, "tatara.pleme.io/process"),
3043            Some("demo-ns/demo-app"),
3044        );
3045    }
3046
3047    // ── Empty-value contract: `Some("")` — the pre-lift chain never
3048    //    swallowed empty values into `None`, so the trait must not
3049    //    either. Pinned separately from the missing-slot corners.
3050
3051    #[test]
3052    fn annotation_present_key_with_empty_value_returns_some_empty_slice_via_trait() {
3053        let mut p = Process::new("api", empty_process_spec());
3054        p.metadata.annotations = Some(one_annotation("tatara.pleme.io/signal", ""));
3055        assert_eq!(
3056            Annotated::annotation(&p, "tatara.pleme.io/signal"),
3057            Some("")
3058        );
3059    }
3060
3061    // ── Byte-identical parity with the pre-lift 3-line chain ──────────
3062
3063    #[test]
3064    fn annotation_matches_pre_lift_annotations_lookup_chain_on_config_map() {
3065        // The four-corner input matrix the pre-lift
3066        // `cm.metadata.annotations.as_ref().and_then(|m| m.get(KEY))
3067        // .map(String::as_str)` chain traversed in
3068        // `tatara-export-worker::main` pre-lift. A regression that
3069        // inserted a normalization step the pre-lift chain does NOT
3070        // apply — or vice versa — surfaces here rather than as silent
3071        // drift between the substrate owner and the pre-lift consumer.
3072        const KEY: &str = "tatara.pleme.io/process";
3073        let cases: Vec<(Option<BTreeMap<String, String>>, Option<&str>)> = vec![
3074            (None, None),
3075            (Some(BTreeMap::new()), None),
3076            (Some(one_annotation("unrelated", "yes")), None),
3077            (
3078                Some(one_annotation(KEY, "demo-ns/demo-app")),
3079                Some("demo-ns/demo-app"),
3080            ),
3081            (Some(one_annotation(KEY, "")), Some("")),
3082        ];
3083        for (anns, expected) in cases {
3084            let mut cm = ConfigMap::default();
3085            cm.metadata.annotations = anns.clone();
3086
3087            let pre_lift: Option<&str> = cm
3088                .metadata
3089                .annotations
3090                .as_ref()
3091                .and_then(|m| m.get(KEY))
3092                .map(String::as_str);
3093            let via_trait = Annotated::annotation(&cm, KEY);
3094
3095            assert_eq!(
3096                pre_lift, expected,
3097                "pre-lift chain must return {expected:?} for annotations={anns:?}",
3098            );
3099            assert_eq!(
3100                via_trait, pre_lift,
3101                "trait probe must be byte-identical to pre-lift chain for annotations={anns:?}",
3102            );
3103        }
3104    }
3105
3106    // ── Cross-primitive coherence with Process's inherent forwarder ───
3107
3108    #[test]
3109    fn trait_probe_coheres_with_process_inherent_annotation_on_every_corner() {
3110        // Cross-primitive coherence pin: the trait's default and the
3111        // pre-existing `Process::annotation` inherent forwarder return
3112        // the SAME `Option<&str>` on the SAME `Process` value — a
3113        // future consolidation of the inherent onto the trait's
3114        // default cannot land any drift because this pin binds them
3115        // at every corner of the (absent, present-missing-key,
3116        // present-with-key, present-with-empty-value) input matrix.
3117        const KEY: &str = "tatara.pleme.io/signal";
3118        let cases: Vec<Option<BTreeMap<String, String>>> = vec![
3119            None,
3120            Some(BTreeMap::new()),
3121            Some(one_annotation("other/key", "irrelevant")),
3122            Some(one_annotation(KEY, "SIGHUP")),
3123            Some(one_annotation(KEY, "")),
3124        ];
3125        for anns in cases {
3126            let mut p = Process::new("api", empty_process_spec());
3127            p.metadata.annotations = anns.clone();
3128            let via_inherent = p.annotation(KEY);
3129            let via_trait = Annotated::annotation(&p, KEY);
3130            assert_eq!(
3131                via_inherent, via_trait,
3132                "Process inherent + Annotated trait must agree on annotations={anns:?}",
3133            );
3134        }
3135    }
3136
3137    // ── Inherent-preferred method resolution on Process ───────────────
3138
3139    #[test]
3140    fn dot_call_on_process_resolves_to_inherent_when_trait_in_scope() {
3141        // Rust method resolution prefers an inherent over a trait's
3142        // blanket impl, so `process.annotation(key)` with the trait in
3143        // scope still routes through the inherent — and both return
3144        // the same `Option<&str>` (verified in
3145        // `trait_probe_coheres_with_process_inherent_annotation_on_every_corner`).
3146        // This pin guards against a future refactor that removes the
3147        // inherent but leaves consumers assuming inherent-preferred
3148        // resolution — the observable output is identical either way,
3149        // so the pin locks the invariant that BOTH paths agree.
3150        let mut p = Process::new("api", empty_process_spec());
3151        p.metadata.annotations = Some(one_annotation("tatara.pleme.io/signal", "SIGHUP"));
3152        assert_eq!(p.annotation("tatara.pleme.io/signal"), Some("SIGHUP"));
3153    }
3154
3155    #[test]
3156    fn dot_call_on_ephemeral_allocation_resolves_to_trait_blanket_impl() {
3157        // The peer load-bearing corner: `alloc.annotation(key)` with
3158        // the trait in scope routes to the trait's blanket impl —
3159        // there is no inherent on `EphemeralAllocation` — and produces
3160        // the expected `Option<&str>`. The same discipline the sibling
3161        // `DeletionTombstoned` trait already established on the
3162        // tombstone axis for the SAME third CRD.
3163        let mut a = EphemeralAllocation::new("pr-42-demo", empty_alloc_spec());
3164        assert_eq!(a.annotation("tatara.pleme.io/requestor-kind"), None);
3165        a.metadata.annotations = Some(one_annotation(
3166            "tatara.pleme.io/requestor-kind",
3167            "github-pr",
3168        ));
3169        assert_eq!(
3170            a.annotation("tatara.pleme.io/requestor-kind"),
3171            Some("github-pr"),
3172        );
3173    }
3174
3175    #[test]
3176    fn dot_call_on_config_map_resolves_to_trait_blanket_impl() {
3177        // The load-bearing corner the export-worker's post-lift call
3178        // exercises: `cm.annotation(KEY)` with the trait in scope
3179        // routes to the blanket impl (ConfigMap is a K8s built-in
3180        // with no tatara-owned inherent) and produces the same
3181        // `Option<&str>` the pre-lift 3-line chain did.
3182        let mut cm = ConfigMap::default();
3183        assert_eq!(cm.annotation("tatara.pleme.io/process"), None);
3184        cm.metadata.annotations = Some(one_annotation(
3185            "tatara.pleme.io/process",
3186            "demo-ns/demo-app",
3187        ));
3188        assert_eq!(
3189            cm.annotation("tatara.pleme.io/process"),
3190            Some("demo-ns/demo-app"),
3191        );
3192    }
3193}
3194
3195#[cfg(test)]
3196mod annotations_pins {
3197    //! Pin the three newly-lifted allocator-bind annotation keys
3198    //! ([`crate::annotations::REQUESTOR`],
3199    //! [`crate::annotations::ALLOCATION`],
3200    //! [`crate::annotations::REQUESTOR_KIND`]) at their canonical
3201    //! wire-form byte-values, and pin the coherence between each
3202    //! constant and the pre-lift string literal the sibling writer +
3203    //! reader test-sites still spell verbatim.
3204    //!
3205    //! Pre-lift each of the three keys was a bare `"tatara.pleme.io/…"`
3206    //! string literal at both the writer (`tatara-pool-reconciler::
3207    //! controller_allocation::reconcile_inner`'s Bind arm) AND the
3208    //! reader-side test sites in `annotated_tests` above — six
3209    //! restatements of `REQUESTOR_KIND` alone past the ★★
3210    //! PRIME-DIRECTIVE ≥ 2 duplication threshold. Post-lift the writer
3211    //! keys on the substrate constant; these pins bind the constant's
3212    //! byte-shape so a future edit that drifted the constant (a
3213    //! typo'd suffix, an accidental `tatara.pleme.io/v2/…` migration
3214    //! landing at only the writer, an incoming rename that swapped
3215    //! two of the three keys) surfaces here rather than as silent
3216    //! operator-facing skew between the writer and the tatara-process
3217    //! reader tests that still spell the literal.
3218    //!
3219    //! Theory anchor: THEORY.md §II.1 invariant 5 (composition
3220    //! preserves proofs — the wire-form value each downstream reader
3221    //! depends on now has a compile-time pin at the substrate).
3222    use crate::annotations;
3223
3224    #[test]
3225    fn requestor_matches_pre_lift_wire_string() {
3226        assert_eq!(annotations::REQUESTOR, "tatara.pleme.io/requestor");
3227    }
3228
3229    #[test]
3230    fn allocation_matches_pre_lift_wire_string() {
3231        assert_eq!(annotations::ALLOCATION, "tatara.pleme.io/allocation");
3232    }
3233
3234    #[test]
3235    fn requestor_kind_matches_pre_lift_wire_string() {
3236        assert_eq!(
3237            annotations::REQUESTOR_KIND,
3238            "tatara.pleme.io/requestor-kind",
3239        );
3240    }
3241
3242    #[test]
3243    fn allocator_bind_axis_keys_are_distinct() {
3244        // A copy-paste that duplicated one key's value across two
3245        // slots (an oversight during the initial lift or a future
3246        // rename that merged two keys by mistake) collapses BOTH
3247        // downstream readers onto the same wire string and silently
3248        // loses one of the three axes. Pin the closed set is
3249        // partition-distinct.
3250        assert_ne!(annotations::REQUESTOR, annotations::ALLOCATION);
3251        assert_ne!(annotations::REQUESTOR, annotations::REQUESTOR_KIND);
3252        assert_ne!(annotations::ALLOCATION, annotations::REQUESTOR_KIND);
3253    }
3254
3255    #[test]
3256    fn allocator_bind_axis_keys_share_tatara_namespace() {
3257        // Every substrate-owned annotation key inhabits the
3258        // `tatara.pleme.io/` reverse-DNS namespace; a future rename
3259        // that dropped the prefix (a bare `"requestor"` key, a
3260        // typo'd `pleme.io/requestor`) would collide with an
3261        // arbitrary third-party operator's annotations on the same
3262        // Process and silently corrupt cross-consumer reads.
3263        for key in [
3264            annotations::REQUESTOR,
3265            annotations::ALLOCATION,
3266            annotations::REQUESTOR_KIND,
3267        ] {
3268            assert!(
3269                key.starts_with("tatara.pleme.io/"),
3270                "annotation key {key:?} must inhabit tatara.pleme.io/ namespace",
3271            );
3272        }
3273    }
3274
3275    // ── Pool-membership axis pins ────────────────────────────────────
3276    //
3277    // Pins the two newly-lifted pool-membership annotation keys
3278    // ([`crate::annotations::POOL`], [`crate::annotations::POOL_SLOT`])
3279    // at their canonical wire-form byte-values. Pre-lift each key was
3280    // a file-scope `const ANNOTATION_POOL / ANNOTATION_SLOT` in
3281    // `tatara-pool-reconciler::controller_pool` PLUS bare
3282    // `"tatara.pleme.io/pool"` string literals at four reader-side
3283    // test sites in this crate (in the sibling `annotated_tests` above
3284    // and in `crd.rs`'s
3285    // `annotation_composes_borrow_equality_tail_matching_pre_lift_pool`
3286    // + `annotation_returns_none_when_metadata_annotations_is_none`).
3287    // Post-lift the writer routes through the substrate constant; a
3288    // future edit that drifted the constant (a typo'd suffix, an
3289    // accidental `tatara.pleme.io/v2/pool` migration landing at only
3290    // the writer, an incoming rename that swapped POOL and POOL_SLOT)
3291    // surfaces here rather than as silent operator-facing skew
3292    // between the pool controller's writer and its own membership-
3293    // gate reader.
3294
3295    #[test]
3296    fn pool_matches_pre_lift_wire_string() {
3297        assert_eq!(annotations::POOL, "tatara.pleme.io/pool");
3298    }
3299
3300    #[test]
3301    fn pool_slot_matches_pre_lift_wire_string() {
3302        assert_eq!(annotations::POOL_SLOT, "tatara.pleme.io/pool-slot");
3303    }
3304
3305    #[test]
3306    fn pool_membership_axis_keys_are_distinct() {
3307        // A copy-paste that duplicated one key's value across both
3308        // slots (an oversight during the initial lift, or a future
3309        // rename that merged the two keys by mistake) collapses
3310        // BOTH downstream readers onto the same wire string and
3311        // silently loses the slot-index axis — the pool controller
3312        // would still find its own members via POOL but every per-
3313        // slot dispatch consumer would read the pool name where the
3314        // slot index used to sit. Pin the closed set is partition-
3315        // distinct.
3316        assert_ne!(annotations::POOL, annotations::POOL_SLOT);
3317    }
3318
3319    #[test]
3320    fn pool_membership_axis_keys_share_tatara_namespace() {
3321        // Same reverse-DNS namespace invariant the allocator-bind
3322        // axis-family enforces above — a rename that dropped the
3323        // prefix on either POOL or POOL_SLOT would collide with an
3324        // arbitrary third-party operator's annotations on the same
3325        // Process and silently corrupt every pool-membership read.
3326        for key in [annotations::POOL, annotations::POOL_SLOT] {
3327            assert!(
3328                key.starts_with("tatara.pleme.io/"),
3329                "annotation key {key:?} must inhabit tatara.pleme.io/ namespace",
3330            );
3331        }
3332    }
3333
3334    #[test]
3335    fn pool_membership_axis_keys_partition_distinct_from_allocator_bind_axis() {
3336        // Cross-family distinctness pin — the pool-membership axis
3337        // (POOL, POOL_SLOT) and the allocator-bind axis (REQUESTOR,
3338        // ALLOCATION, REQUESTOR_KIND) travel on the SAME member
3339        // Process at the SAME time (the pool controller writes POOL
3340        // + POOL_SLOT at creation; the allocator later merges
3341        // REQUESTOR / ALLOCATION / REQUESTOR_KIND onto the same
3342        // Process at Bind). A copy-paste that collapsed any axis
3343        // pair (e.g. POOL and REQUESTOR onto the same wire string)
3344        // would let one write silently overwrite the other. Pin
3345        // that every substrate-owned annotation key is unique
3346        // across the two axis-families.
3347        let pool_axis = [annotations::POOL, annotations::POOL_SLOT];
3348        let bind_axis = [
3349            annotations::REQUESTOR,
3350            annotations::ALLOCATION,
3351            annotations::REQUESTOR_KIND,
3352        ];
3353        for p in pool_axis {
3354            for b in bind_axis {
3355                assert_ne!(
3356                    p, b,
3357                    "pool-membership key {p:?} collides with allocator-bind key {b:?}",
3358                );
3359            }
3360        }
3361    }
3362
3363    // ── Release-return axis pins ─────────────────────────────────────
3364    //
3365    // Pins the newly-lifted release-return annotation key
3366    // ([`crate::annotations::RETURN_TRIGGER`]) at its canonical
3367    // wire-form byte-value. Pre-lift the key was a bare
3368    // `"tatara.pleme.io/return-trigger"` string literal at the
3369    // pool-reconciler's Release-arm stamp (`tatara-pool-reconciler::
3370    // controller_allocation::reconcile_inner`) — the ONE remaining
3371    // hand-authored annotation-key literal in the workspace's active
3372    // controllers after every sibling single-annotation key on the
3373    // same axis-family (`SIGNAL`, `RELEASED_FROM`, `POOL`, `POOL_SLOT`,
3374    // `REQUESTOR`, `ALLOCATION`, `REQUESTOR_KIND`) already routed
3375    // through a `pub const` in the substrate. Post-lift the writer
3376    // routes through the substrate constant; these pins bind the
3377    // constant's byte-shape + tatara-namespace membership + partition-
3378    // distinctness against every peer key so a future edit that
3379    // drifted the constant (a typo'd suffix, an incoming rename that
3380    // collapsed RETURN_TRIGGER onto a peer key, a `tatara.pleme.io/v2/
3381    // return-trigger` migration landing at only the writer) surfaces
3382    // HERE rather than as silent operator-facing skew between the
3383    // allocator's Release-arm stamp and every downstream reader (an
3384    // audit-trail scraper, a future pool-reconciler return-path arm,
3385    // an admission-webhook gate on the return trigger).
3386
3387    #[test]
3388    fn return_trigger_matches_pre_lift_wire_string() {
3389        assert_eq!(
3390            annotations::RETURN_TRIGGER,
3391            "tatara.pleme.io/return-trigger",
3392        );
3393    }
3394
3395    #[test]
3396    fn return_trigger_inhabits_tatara_namespace() {
3397        // Same reverse-DNS namespace invariant every sibling key on
3398        // the axis-family enforces above — a rename that dropped the
3399        // prefix on RETURN_TRIGGER would collide with an arbitrary
3400        // third-party operator's annotations on the same Process and
3401        // silently corrupt the allocator's Release-arm write.
3402        assert!(
3403            annotations::RETURN_TRIGGER.starts_with("tatara.pleme.io/"),
3404            "annotation key {:?} must inhabit tatara.pleme.io/ namespace",
3405            annotations::RETURN_TRIGGER,
3406        );
3407    }
3408
3409    #[test]
3410    fn return_trigger_is_distinct_from_every_peer_annotation_key() {
3411        // Cross-family distinctness pin — RETURN_TRIGGER travels on
3412        // the SAME member Process (at Release) that already carries
3413        // the pool-membership axis (POOL, POOL_SLOT, stamped at
3414        // creation), the allocator-bind axis (REQUESTOR, ALLOCATION,
3415        // REQUESTOR_KIND, stamped at Bind), and the
3416        // "single-annotation trigger for the next reconcile pass"
3417        // axis-family (SIGNAL, RELEASED_FROM). A copy-paste that
3418        // collapsed RETURN_TRIGGER onto any peer would let one write
3419        // silently overwrite the other. Pin the key against every
3420        // sibling substrate-owned annotation key on the workspace.
3421        for peer in [
3422            annotations::SIGNAL,
3423            annotations::RELEASED_FROM,
3424            annotations::POOL,
3425            annotations::POOL_SLOT,
3426            annotations::REQUESTOR,
3427            annotations::ALLOCATION,
3428            annotations::REQUESTOR_KIND,
3429            annotations::MANAGED_BY,
3430            annotations::PROCESS,
3431            annotations::PID,
3432            annotations::CONTENT_HASH,
3433            annotations::ATTESTATION_ROOT,
3434            annotations::GENERATION,
3435            annotations::ROLE,
3436            annotations::EXPORT_INDEX,
3437            annotations::APP,
3438            annotations::ROUTING_FORM,
3439        ] {
3440            assert_ne!(
3441                annotations::RETURN_TRIGGER,
3442                peer,
3443                "RETURN_TRIGGER key {:?} collides with peer annotation key {peer:?}",
3444                annotations::RETURN_TRIGGER,
3445            );
3446        }
3447    }
3448
3449    #[test]
3450    fn return_trigger_composes_at_annotation_body_key_slot() {
3451        // End-to-end composability pin: the substrate composer
3452        // [`crate::patch::annotation_body`] takes a `key: &str`; the
3453        // pre-lift Release-arm callsite fed a bare `"tatara.pleme.io/
3454        // return-trigger"` literal and the post-lift callsite feeds
3455        // `annotations::RETURN_TRIGGER`. Both shapes produce a JSON
3456        // merge-body whose `metadata.annotations.<KEY>` slot equals
3457        // `"true"`; pin that the substrate constant threads through
3458        // the composer verbatim so a regression that reshaped the
3459        // `annotation_body` key-slot (a case-fold pass, an unexpected
3460        // trim, a prefix-normalization step) surfaces HERE rather
3461        // than at every downstream consumer.
3462        let body = crate::patch::annotation_body(annotations::RETURN_TRIGGER, "true");
3463        assert_eq!(
3464            body["metadata"]["annotations"][annotations::RETURN_TRIGGER],
3465            "true",
3466            "annotation_body must stamp RETURN_TRIGGER verbatim at the metadata.annotations slot",
3467        );
3468        assert_eq!(
3469            body["metadata"]["annotations"]["tatara.pleme.io/return-trigger"],
3470            "true",
3471            "byte-shape parity — the pre-lift hand-authored key spelling routes through the constant to the same nested slot",
3472        );
3473    }
3474
3475    // ── Encapsulation-diagnostic axis pins ──────────────────────────
3476    //
3477    // Pins the two newly-lifted encapsulation-diagnostic annotation
3478    // keys ([`crate::annotations::ENCAPSULATION_MODE`],
3479    // [`crate::annotations::ADOPTED_RELEASE`]) at their canonical
3480    // wire-form byte-values. Pre-lift the two keys were bare
3481    // `"tatara.pleme.io/encapsulation-mode"` /
3482    // `"tatara.pleme.io/adopted-release"` string literals inline at
3483    // `tatara-reconciler::render::mark_resources_as_adopting`'s two
3484    // `anns_obj.insert_str(...)` writer sites — the ONE remaining
3485    // hand-authored annotation-key pair in the workspace's active
3486    // reconciler after every sibling annotation key already routed
3487    // through a `pub const` in the substrate. Post-lift the writer
3488    // routes through the substrate constants; these pins bind each
3489    // constant's byte-shape + tatara-namespace membership + partition-
3490    // distinctness against every peer key so a future edit that
3491    // drifted the constants (a typo'd suffix, an incoming rename that
3492    // collapsed the pair onto a peer key, a
3493    // `tatara.pleme.io/v2/encapsulation-mode` migration landing at
3494    // only the writer, a collapse into a compound
3495    // `tatara.pleme.io/encapsulation` payload key) surfaces HERE
3496    // rather than as silent operator-facing skew between the render
3497    // emitter and every downstream reader (an operator dashboard
3498    // filtering adopted resources, an admission-webhook gate on the
3499    // encapsulation mode, an audit-trail scraper following the
3500    // `<ns>/<release>` adoption lineage).
3501
3502    #[test]
3503    fn encapsulation_mode_matches_pre_lift_wire_string() {
3504        assert_eq!(
3505            annotations::ENCAPSULATION_MODE,
3506            "tatara.pleme.io/encapsulation-mode",
3507        );
3508    }
3509
3510    #[test]
3511    fn adopted_release_matches_pre_lift_wire_string() {
3512        assert_eq!(
3513            annotations::ADOPTED_RELEASE,
3514            "tatara.pleme.io/adopted-release",
3515        );
3516    }
3517
3518    #[test]
3519    fn encapsulation_diagnostic_axis_keys_are_distinct() {
3520        // A copy-paste that duplicated one key's value across the pair
3521        // (an oversight during the initial lift, or a future rename
3522        // that merged the two keys by mistake) collapses BOTH
3523        // downstream readers onto the same wire string and silently
3524        // loses one of the two axes — an operator dashboard would
3525        // still see the mode via ENCAPSULATION_MODE but every
3526        // `<ns>/<release>` back-reference consumer would read the
3527        // mode literal where the qualified reference used to sit.
3528        // Pin the closed set is partition-distinct.
3529        assert_ne!(
3530            annotations::ENCAPSULATION_MODE,
3531            annotations::ADOPTED_RELEASE
3532        );
3533    }
3534
3535    #[test]
3536    fn encapsulation_diagnostic_axis_keys_share_tatara_namespace() {
3537        // Same reverse-DNS namespace invariant every sibling
3538        // annotation key on the workspace enforces above — a rename
3539        // that dropped the prefix on either constant would collide
3540        // with an arbitrary third-party operator's annotations on the
3541        // same emitted resource (a HelmRelease, a Kustomization, an
3542        // adopted secondary) and silently corrupt every
3543        // encapsulation-diagnostic read.
3544        for key in [
3545            annotations::ENCAPSULATION_MODE,
3546            annotations::ADOPTED_RELEASE,
3547        ] {
3548            assert!(
3549                key.starts_with("tatara.pleme.io/"),
3550                "annotation key {key:?} must inhabit tatara.pleme.io/ namespace",
3551            );
3552        }
3553    }
3554
3555    #[test]
3556    fn encapsulation_diagnostic_axis_keys_partition_distinct_from_every_peer() {
3557        // Cross-family distinctness pin — the encapsulation-diagnostic
3558        // axis (ENCAPSULATION_MODE, ADOPTED_RELEASE) is stamped on
3559        // every RESOURCE the reconciler emits for an Adopt-mode
3560        // Process, whereas every peer annotation key on the workspace
3561        // is stamped on the PROCESS itself (SIGNAL, RELEASED_FROM,
3562        // POOL, POOL_SLOT, REQUESTOR, ALLOCATION, REQUESTOR_KIND,
3563        // RETURN_TRIGGER) OR on emitted routing edges (APP,
3564        // ROUTING_FORM) OR on export-worker Jobs (ROLE, EXPORT_INDEX).
3565        // A copy-paste that collapsed the pair onto any peer would
3566        // let one write silently overwrite the other. Pin that both
3567        // constants are unique across every substrate-owned peer.
3568        let diag_axis = [
3569            annotations::ENCAPSULATION_MODE,
3570            annotations::ADOPTED_RELEASE,
3571        ];
3572        let peers = [
3573            annotations::MANAGED_BY,
3574            annotations::PROCESS,
3575            annotations::PID,
3576            annotations::CONTENT_HASH,
3577            annotations::ATTESTATION_ROOT,
3578            annotations::GENERATION,
3579            annotations::SIGNAL,
3580            annotations::RELEASED_FROM,
3581            annotations::ROLE,
3582            annotations::EXPORT_INDEX,
3583            annotations::APP,
3584            annotations::ROUTING_FORM,
3585            annotations::REQUESTOR,
3586            annotations::ALLOCATION,
3587            annotations::REQUESTOR_KIND,
3588            annotations::POOL,
3589            annotations::POOL_SLOT,
3590            annotations::RETURN_TRIGGER,
3591        ];
3592        for d in diag_axis {
3593            for p in peers {
3594                assert_ne!(
3595                    d, p,
3596                    "encapsulation-diagnostic key {d:?} collides with peer annotation key {p:?}",
3597                );
3598            }
3599        }
3600    }
3601
3602    // ── Receipt-CM-label axis pins ──────────────────────────────────
3603    //
3604    // Pins the newly-lifted receipt-CM label KEY
3605    // ([`crate::annotations::RECEIPT`]) at its canonical wire-form
3606    // byte-value. Pre-lift the key was a bare
3607    // `"tatara.pleme.io/receipt"` string literal inline at
3608    // `tatara-closed-loop-probe::write_receipt_cm`'s
3609    // `BTreeMap::from([...])` label seed AND at the byte-shape parity
3610    // witness in `tatara_process::configmap::with_data`'s
3611    // `with_data_preserves_passed_labels_map_verbatim_when_some` test —
3612    // TWO restatements past the ★★ PRIME-DIRECTIVE ≥ 2 duplication
3613    // threshold. Post-lift both callsites route through the substrate
3614    // constant; these pins bind the constant's byte-shape +
3615    // tatara-namespace membership + partition-distinctness against
3616    // every peer key so a future edit that drifted the constant (a
3617    // typo'd suffix, an incoming rename that collapsed RECEIPT onto a
3618    // peer key, a `tatara.pleme.io/v2/receipt` migration landing at
3619    // only the writer, a collapse into a compound
3620    // `tatara.pleme.io/receipt-envelope` payload key) surfaces HERE
3621    // rather than as silent operator-facing kubectl-selector skew
3622    // between the probe's receipt-CM writer and every downstream
3623    // consumer (a receipt-collection walker, an admission-webhook gate
3624    // on receipt version, an audit-trail scraper enumerating every
3625    // `tatara-receipt/v1` payload on a cluster).
3626
3627    #[test]
3628    fn receipt_matches_pre_lift_wire_string() {
3629        assert_eq!(annotations::RECEIPT, "tatara.pleme.io/receipt");
3630    }
3631
3632    #[test]
3633    fn receipt_inhabits_tatara_namespace() {
3634        // Same reverse-DNS namespace invariant every sibling key on
3635        // the workspace enforces above — a rename that dropped the
3636        // prefix on RECEIPT would collide with an arbitrary
3637        // third-party operator's labels on the same ConfigMap and
3638        // silently corrupt every downstream kubectl-selector that
3639        // enumerates receipt CMs of a given version on a cluster.
3640        assert!(
3641            annotations::RECEIPT.starts_with(annotations::GROUP_PREFIX),
3642            "annotation key {:?} must inhabit {:?} namespace",
3643            annotations::RECEIPT,
3644            annotations::GROUP_PREFIX,
3645        );
3646    }
3647
3648    #[test]
3649    fn receipt_is_distinct_from_every_peer_annotation_key() {
3650        // Cross-family distinctness pin — RECEIPT rides on the
3651        // receipt ConfigMap the probe binary writes (a peer resource
3652        // of the Process itself), whereas every peer annotation key on
3653        // the workspace is stamped on the PROCESS (SIGNAL,
3654        // RELEASED_FROM, POOL, POOL_SLOT, REQUESTOR, ALLOCATION,
3655        // REQUESTOR_KIND, RETURN_TRIGGER) OR on emitted routing edges
3656        // (APP, ROUTING_FORM) OR on export-worker Jobs (ROLE,
3657        // EXPORT_INDEX) OR on encapsulation-diagnostic side-resources
3658        // (ENCAPSULATION_MODE, ADOPTED_RELEASE). A copy-paste that
3659        // collapsed RECEIPT onto any peer would let one write silently
3660        // overwrite the other. Pin the key against every sibling
3661        // substrate-owned annotation key on the workspace.
3662        for peer in [
3663            annotations::MANAGED_BY,
3664            annotations::PROCESS,
3665            annotations::PID,
3666            annotations::CONTENT_HASH,
3667            annotations::ATTESTATION_ROOT,
3668            annotations::GENERATION,
3669            annotations::SIGNAL,
3670            annotations::RELEASED_FROM,
3671            annotations::ROLE,
3672            annotations::EXPORT_INDEX,
3673            annotations::APP,
3674            annotations::ROUTING_FORM,
3675            annotations::REQUESTOR,
3676            annotations::ALLOCATION,
3677            annotations::REQUESTOR_KIND,
3678            annotations::POOL,
3679            annotations::POOL_SLOT,
3680            annotations::RETURN_TRIGGER,
3681            annotations::ENCAPSULATION_MODE,
3682            annotations::ADOPTED_RELEASE,
3683        ] {
3684            assert_ne!(
3685                annotations::RECEIPT,
3686                peer,
3687                "RECEIPT key {:?} collides with peer annotation key {peer:?}",
3688                annotations::RECEIPT,
3689            );
3690        }
3691    }
3692
3693    #[test]
3694    fn receipt_value_slot_routes_through_receipt_version_const() {
3695        // Value-side coherence pin — the SUBSTRATE convention is that
3696        // every ConfigMap labeled `RECEIPT` carries a payload whose
3697        // envelope `version` slot equals [`crate::receipt::RECEIPT_VERSION`],
3698        // so a kubectl `-l tatara.pleme.io/receipt=tatara-receipt/v1`
3699        // selector matches exactly the CMs whose payloads pass the
3700        // `RECEIPT_VERSION` gate. Pin that the label VALUE the probe
3701        // stamps IS `RECEIPT_VERSION` (routed through the const, not a
3702        // parallel `"tatara-receipt/v1"` literal): a future bump to
3703        // `tatara-receipt/v2` at the version const propagates
3704        // MECHANICALLY to the label value without touching any writer.
3705        assert_eq!(
3706            crate::receipt::RECEIPT_VERSION,
3707            "tatara-receipt/v1",
3708            "RECEIPT_VERSION wire-form pin — a bump surfaces here",
3709        );
3710    }
3711
3712    #[test]
3713    fn encapsulation_mode_value_slot_routes_through_encapsulation_mode_closed_set() {
3714        // Value-side pin — the render emitter's `ENCAPSULATION_MODE`
3715        // slot writes the wire-form spelling of an
3716        // [`crate::encapsulates::EncapsulationMode`] variant. Pre-lift
3717        // the site hand-authored the fixed `"Adopt"` literal;
3718        // post-lift the writer feeds
3719        // `EncapsulationMode::Adopt.as_str()` — the SAME closed-set
3720        // owner every peer consumer (the reconciler's status-condition
3721        // reason string, the operator dashboard's per-mode filter, the
3722        // admission webhook's Adopt/Manage/Observe dispatch) routes
3723        // through. A regression that drifted the closed-set wire form
3724        // (a lowercase `"adopt"`, a `"Adoption"` typo) surfaces at
3725        // `EncapsulationMode::as_str`'s own pin AND here at the value
3726        // slot the render emitter stamps.
3727        assert_eq!(
3728            crate::encapsulates::EncapsulationMode::Adopt.as_str(),
3729            "Adopt",
3730            "the render emitter's ENCAPSULATION_MODE value slot must byte-match the closed-set wire form",
3731        );
3732    }
3733}
3734
3735// ── Lisp → ProcessSpec compile bridge ──────────────────────────────────
3736//
3737// `(defpoint NAME :k v …)` compiles to a `NamedDefinition<ProcessSpec>`.
3738// The derive on ProcessSpec handles every field via the serde Deserialize
3739// fallthrough — no hand-rolled keyword parsing needed.
3740
3741/// A named ProcessSpec as produced by `compile_source`.
3742pub type Definition = tatara_lisp::NamedDefinition<crate::crd::ProcessSpec>;
3743
3744/// Compile a Lisp source string into a list of named ProcessSpecs.
3745/// Each top-level `(defpoint NAME …)` form becomes one `Definition`.
3746pub fn compile_source(src: &str) -> tatara_lisp::Result<Vec<Definition>> {
3747    tatara_lisp::compile_named::<crate::crd::ProcessSpec>(src)
3748}
3749
3750/// Register every domain owned by this crate with the global Lisp
3751/// dispatcher. Call once per binary, typically near the top of `main`.
3752/// After this call, `tatara_lisp::domain::lookup("defpoint")` and
3753/// `lookup("defephemeral")` both resolve to the right typed compiler.
3754///
3755/// Idempotent — registering the same type twice is a no-op.
3756pub fn register_all() {
3757    tatara_lisp::domain::register::<crate::crd::ProcessSpec>();
3758    tatara_lisp::domain::register::<crate::ephemeral::EphemeralSpec>();
3759}
3760
3761#[cfg(test)]
3762mod compile_tests {
3763    use super::compile_source;
3764    use crate::classification::{ConvergencePointType, SubstrateType};
3765    use crate::compliance::VerificationPhase;
3766    use crate::spec::MustReachPhase;
3767
3768    /// The full derive-powered pipeline — no hand-rolled parsing anywhere.
3769    /// Every field travels: Lisp → Sexp → serde_json → typed ProcessSpec.
3770    #[test]
3771    fn full_processspec_round_trip_via_derive() {
3772        let src = r#"
3773            (defpoint observability-stack
3774              :identity       (:parent "seph.1")
3775              :classification (:point-type Gate
3776                               :substrate Observability
3777                               :horizon (:kind Bounded)
3778                               :calm Monotone
3779                               :data-classification Internal)
3780              :intent         (:nix (:flake-ref "github:pleme-io/k8s"
3781                                     :attribute "observability"
3782                                     :attic-cache "main"))
3783              :boundary       (:postconditions
3784                                 ((:kind KustomizationHealthy
3785                                   :params (:name "observability-stack"
3786                                            :namespace "flux-system"))
3787                                  (:kind PromQL
3788                                   :params (:query "up == 1")))
3789                               :timeout "15m")
3790              :compliance     (:baseline "fedramp-moderate"
3791                               :bindings ((:framework "nist-800-53"
3792                                           :control-id "SC-7"
3793                                           :phase AtBoundary)))
3794              :depends-on     ((:name "secret-injection" :must-reach Attested))
3795              :signals        (:sigterm-grace-seconds 480
3796                               :sighup-strategy Reconverge))
3797        "#;
3798        let defs = compile_source(src).expect("compile");
3799        assert_eq!(defs.len(), 1);
3800        let d = &defs[0];
3801        assert_eq!(d.name, "observability-stack");
3802
3803        // identity
3804        assert_eq!(d.spec.identity.parent.as_deref(), Some("seph.1"));
3805
3806        // classification (enums deserialized via symbol → string)
3807        assert_eq!(d.spec.classification.point_type, ConvergencePointType::Gate);
3808        assert_eq!(
3809            d.spec.classification.substrate,
3810            SubstrateType::Observability
3811        );
3812
3813        // intent (tagged-union with one of four options)
3814        let nix = d.spec.intent.nix.as_ref().expect("nix intent");
3815        assert_eq!(nix.flake_ref, "github:pleme-io/k8s");
3816        assert_eq!(nix.attribute, "observability");
3817        assert_eq!(nix.attic_cache.as_deref(), Some("main"));
3818
3819        // boundary (Vec<nested struct with params object>)
3820        assert_eq!(d.spec.boundary.postconditions.len(), 2);
3821        assert_eq!(d.spec.boundary.timeout.as_deref(), Some("15m"));
3822
3823        // compliance (Vec<binding with enum phase>)
3824        assert_eq!(
3825            d.spec.compliance.baseline.as_deref(),
3826            Some("fedramp-moderate")
3827        );
3828        assert_eq!(d.spec.compliance.bindings.len(), 1);
3829        assert_eq!(
3830            d.spec.compliance.bindings[0].phase,
3831            VerificationPhase::AtBoundary
3832        );
3833
3834        // depends_on (Vec<struct with enum>)
3835        assert_eq!(d.spec.depends_on.len(), 1);
3836        assert_eq!(d.spec.depends_on[0].must_reach, MustReachPhase::Attested);
3837
3838        // signals (numeric + enum defaults)
3839        assert_eq!(d.spec.signals.sigterm_grace_seconds, 480);
3840    }
3841
3842    #[test]
3843    fn missing_required_field_errors() {
3844        // `:classification` has no #[serde(default)] — omit it and compile must fail.
3845        let src = r#"(defpoint x :intent (:nix (:flake-ref "f" :attribute "a")))"#;
3846        assert!(compile_source(src).is_err());
3847    }
3848
3849    #[test]
3850    fn serde_default_fields_are_optional() {
3851        // Omit every #[serde(default)] field — compile must succeed because
3852        // the derive honors serde defaults.
3853        let src = r#"
3854            (defpoint x
3855              :classification (:point-type Transform :substrate Compute)
3856              :intent (:flux (:git-repository "g" :path ".")))
3857        "#;
3858        let defs = compile_source(src).expect("compile");
3859        assert_eq!(defs.len(), 1);
3860        let d = &defs[0];
3861        assert!(d.spec.depends_on.is_empty());
3862        assert!(d.spec.boundary.postconditions.is_empty());
3863        assert!(d.spec.compliance.bindings.is_empty());
3864        assert!(!d.spec.suspended);
3865        // Lifetime defaults to Permanent (no variant set, resolver still works).
3866        assert!(d.spec.lifetime.is_default());
3867        assert!(!d.spec.lifetime.is_ephemeral());
3868    }
3869
3870    /// Registering all process-owned domains is idempotent and resolves
3871    /// both `defpoint` (ProcessSpec) and `defephemeral` (EphemeralSpec).
3872    #[test]
3873    fn register_all_resolves_defpoint_and_defephemeral() {
3874        use tatara_lisp::domain::lookup;
3875        super::register_all();
3876        super::register_all(); // idempotent
3877        assert!(lookup("defpoint").is_some(), "defpoint must resolve");
3878        assert!(
3879            lookup("defephemeral").is_some(),
3880            "defephemeral must resolve"
3881        );
3882    }
3883
3884    /// End-to-end: a `(defpoint …)` form may carry the full ephemeral
3885    /// shape directly — `:intent (:aplicacao …)` + `:lifetime (:ephemeral …)`.
3886    /// This is what the `(defephemeral …)` sugar lowers to via `From`.
3887    #[test]
3888    fn defpoint_with_aplicacao_intent_and_ephemeral_lifetime() {
3889        use crate::intent::IntentVariant;
3890        use crate::lifetime::{LifetimeVariant, TeardownPolicy};
3891        let src = r#"
3892            (defpoint closed-loop-attest
3893              :classification (:point-type Gate :substrate Compute)
3894              :intent (:aplicacao
3895                        (:chart-ref "oci://ghcr.io/pleme-io/charts/lareira-demo-app"
3896                         :version "0.5.5"
3897                         :profile "all-in-one"
3898                         :values-overlay (:cluster (:name "ephemeral-test-01"))
3899                         :target-namespace "demo-test"))
3900              :boundary (:postconditions
3901                          ((:kind HelmReleaseReleased
3902                            :params (:name "demo-app-consolidated"
3903                                     :namespace "demo-test"))
3904                           (:kind ClosedLoopAuth
3905                            :params (:issuer (:service "demo-app-issuer" :port 8080)
3906                                     :consumer (:service "demo-app-gateway" :port 8000)
3907                                     :probeImage "ghcr.io/pleme-io/closed-loop-probe:0.1.0"))))
3908              :lifetime (:ephemeral (:ttl "1h"
3909                                     :teardown-policy OnAttested
3910                                     :max-concurrent 1)))
3911        "#;
3912        let defs = compile_source(src).expect("compile");
3913        assert_eq!(defs.len(), 1);
3914        let d = &defs[0];
3915
3916        // Aplicacao intent landed.
3917        match d.spec.intent.variant().unwrap() {
3918            IntentVariant::Aplicacao(a) => {
3919                assert_eq!(a.profile, "all-in-one");
3920                assert_eq!(a.version, "0.5.5");
3921                assert_eq!(a.target_namespace.as_deref(), Some("demo-test"));
3922                assert_eq!(a.values_overlay["cluster"]["name"], "ephemeral-test-01");
3923            }
3924            other => panic!("expected Aplicacao, got {other:?}"),
3925        }
3926
3927        // Ephemeral lifetime landed with the right teardown policy.
3928        match d.spec.lifetime.variant().unwrap() {
3929            LifetimeVariant::Ephemeral(e) => {
3930                assert_eq!(e.ttl, "1h");
3931                assert_eq!(e.teardown_policy, TeardownPolicy::OnAttested);
3932                assert_eq!(e.max_concurrent, 1);
3933            }
3934            other => panic!("expected ephemeral, got {other:?}"),
3935        }
3936
3937        // Two typed postconditions including ClosedLoopAuth.
3938        assert_eq!(d.spec.boundary.postconditions.len(), 2);
3939        assert_eq!(
3940            d.spec.boundary.postconditions[1].kind,
3941            crate::boundary::ConditionKind::ClosedLoopAuth
3942        );
3943    }
3944}
3945
3946#[cfg(test)]
3947mod placed_in_namespace_tests {
3948    //! Pin the [`PlacedInNamespace`] trait's `in_namespace` builder at
3949    //! fail-before-pass-after granularity across every corner of the
3950    //! (CRD ∈ {`Process`, `EphemeralPool`, `EphemeralAllocation`,
3951    //! `ConfigMap`}) × (input form ∈ {`&str`, `String`, `&String`})
3952    //! matrix — the three tatara-owned CRDs the trait's blanket impl
3953    //! covers today PLUS one K8s built-in (`ConfigMap`) whose sibling
3954    //! [`Annotated`] blanket already covers the same category on the
3955    //! annotation-read axis. Also pin (a) the overwrite corner where
3956    //! `.in_namespace(a).in_namespace(b)` binds `b`, so a future
3957    //! consumer that chains two stamps in one composition never sees
3958    //! stale semantics, and (b) the byte-identical parity corner with
3959    //! the pre-lift 3-line body of the per-CRD `EphemeralPool::new_in`
3960    //! and `EphemeralAllocation::new_in` composers post-forwarding —
3961    //! `<CRD>::new_in(name, ns, spec)` must yield a value structurally
3962    //! identical to `<CRD>::new(name, spec).in_namespace(ns)` on every
3963    //! metadata slot the derive stamps.
3964    use super::PlacedInNamespace;
3965    use crate::allocation::{AllocationSpec, EphemeralAllocation, Requestor};
3966    use crate::crd::{Process, ProcessSpec};
3967    use crate::pool::{EphemeralPool, PoolSpec};
3968    use k8s_openapi::api::core::v1::ConfigMap;
3969    use kube::api::ObjectMeta;
3970
3971    fn empty_process_spec() -> ProcessSpec {
3972        ProcessSpec::gate_compute_defaults()
3973    }
3974
3975    fn empty_pool_spec() -> PoolSpec {
3976        PoolSpec {
3977            desired_size: 1,
3978            ..PoolSpec::with_template(crate::ephemeral::EphemeralSpec {
3979                aplicacao: crate::intent::AplicacaoIntent::chart_only("oci://x", "1"),
3980                ttl: "1h".into(),
3981                teardown: crate::lifetime::TeardownPolicy::Always,
3982                max_concurrent: 0,
3983                postconditions: vec![],
3984                preconditions: vec![],
3985                verify_timeout: None,
3986                classification: None,
3987                parent: None,
3988                exports: vec![],
3989                routing: None,
3990            })
3991        }
3992    }
3993
3994    fn empty_alloc_spec() -> AllocationSpec {
3995        AllocationSpec::requestor_only(Requestor::kind_only("github-pr"))
3996    }
3997
3998    #[test]
3999    fn in_namespace_on_process_stamps_borrowed_str() {
4000        let p = Process::new("api", empty_process_spec()).in_namespace("prod");
4001        assert_eq!(p.metadata.namespace.as_deref(), Some("prod"));
4002    }
4003
4004    #[test]
4005    fn in_namespace_on_process_stamps_owned_string() {
4006        let ns: String = "prod".into();
4007        let p = Process::new("api", empty_process_spec()).in_namespace(ns);
4008        assert_eq!(p.metadata.namespace.as_deref(), Some("prod"));
4009    }
4010
4011    #[test]
4012    fn in_namespace_on_process_stamps_string_ref() {
4013        let ns: String = "prod".into();
4014        let p = Process::new("api", empty_process_spec()).in_namespace(&ns);
4015        assert_eq!(p.metadata.namespace.as_deref(), Some("prod"));
4016    }
4017
4018    #[test]
4019    fn in_namespace_on_ephemeral_pool_stamps_borrowed_str() {
4020        let p = EphemeralPool::new("pool-1", empty_pool_spec()).in_namespace("pools");
4021        assert_eq!(p.metadata.namespace.as_deref(), Some("pools"));
4022    }
4023
4024    #[test]
4025    fn in_namespace_on_ephemeral_allocation_stamps_borrowed_str() {
4026        let a = EphemeralAllocation::new("alloc-1", empty_alloc_spec()).in_namespace("pools");
4027        assert_eq!(a.metadata.namespace.as_deref(), Some("pools"));
4028    }
4029
4030    #[test]
4031    fn in_namespace_on_configmap_via_blanket_stamps_ns() {
4032        let cm = ConfigMap {
4033            metadata: ObjectMeta {
4034                name: Some("cm-1".into()),
4035                ..Default::default()
4036            },
4037            ..Default::default()
4038        };
4039        let cm = cm.in_namespace("demo");
4040        assert_eq!(cm.metadata.namespace.as_deref(), Some("demo"));
4041    }
4042
4043    #[test]
4044    fn in_namespace_second_call_overwrites_first() {
4045        let p = Process::new("api", empty_process_spec())
4046            .in_namespace("staging")
4047            .in_namespace("prod");
4048        assert_eq!(p.metadata.namespace.as_deref(), Some("prod"));
4049    }
4050
4051    #[test]
4052    fn in_namespace_preserves_name_and_spec_untouched() {
4053        // Byte-identical parity with the pre-lift two-line pattern:
4054        // only `metadata.namespace` moves; `metadata.name` + `spec`
4055        // stay at the values the derive-supplied `::new` stamped.
4056        // Serialize both `spec` sides through serde_json so we can
4057        // pin equality without requiring `PartialEq` on `ProcessSpec`.
4058        let p = Process::new("api", empty_process_spec()).in_namespace("prod");
4059        assert_eq!(p.metadata.name.as_deref(), Some("api"));
4060        assert_eq!(p.metadata.namespace.as_deref(), Some("prod"));
4061        let expected = serde_json::to_value(empty_process_spec()).unwrap();
4062        let actual = serde_json::to_value(&p.spec).unwrap();
4063        assert_eq!(actual, expected);
4064    }
4065
4066    #[test]
4067    fn pool_new_in_forwarder_matches_trait_form() {
4068        // Cross-composer coherence witness — the per-CRD
4069        // `EphemeralPool::new_in` forwarder must produce a value
4070        // structurally identical to what `Process::new(...).in_namespace(...)`
4071        // does on the same axis. Serialize both sides through
4072        // serde_json so any drift between the forwarding form and a
4073        // direct trait-call materializes at this pin.
4074        let via_new_in = EphemeralPool::new_in("pool-x", "pools", empty_pool_spec());
4075        let via_trait = EphemeralPool::new("pool-x", empty_pool_spec()).in_namespace("pools");
4076        assert_eq!(
4077            serde_json::to_value(&via_new_in).unwrap(),
4078            serde_json::to_value(&via_trait).unwrap(),
4079        );
4080    }
4081
4082    #[test]
4083    fn allocation_new_in_forwarder_matches_trait_form() {
4084        let via_new_in = EphemeralAllocation::new_in("alloc-x", "pools", empty_alloc_spec());
4085        let via_trait =
4086            EphemeralAllocation::new("alloc-x", empty_alloc_spec()).in_namespace("pools");
4087        assert_eq!(
4088            serde_json::to_value(&via_new_in).unwrap(),
4089            serde_json::to_value(&via_trait).unwrap(),
4090        );
4091    }
4092}
4093
4094#[cfg(test)]
4095mod annotations_family_tests {
4096    //! Family-invariant pins for the substrate-owned annotation-key
4097    //! family that the [`crate::annotations`] module owns.
4098    //!
4099    //! Mirror of the sibling [`crate::finalizers::tests`] family-
4100    //! invariant block on the peer-family axis: the [`crate::finalizers`]
4101    //! module already carries the same closed-family + shared-prefix
4102    //! + pairwise-uniqueness discipline over its three finalizer keys;
4103    //! this block extends the same solve-once discipline to the 21-key
4104    //! annotation family.
4105    //!
4106    //! Each pin binds ONE invariant at fail-before-pass-after
4107    //! granularity so a future addition to the annotation family that
4108    //! violated the invariant (a new `pub const` that missed the
4109    //! [`crate::annotations::ALL`] slice, a prefix drift that dropped
4110    //! the shared [`crate::annotations::GROUP_PREFIX`] on ONE arm, a
4111    //! copy-paste that duplicated one arm's wire form at another)
4112    //! surfaces HERE rather than at some downstream sweep binary or
4113    //! silent K8s-API-server-side skew whichever consumer hit the
4114    //! broken invariant first.
4115    use crate::{annotations, finalizers};
4116
4117    #[test]
4118    fn group_prefix_matches_tatara_reverse_dns() {
4119        // Byte-shape pin — the shared prefix is the same
4120        // reverse-DNS namespace every tatara-owned wire-form key
4121        // (annotation, finalizer, CRD group) rides through.
4122        assert_eq!(annotations::GROUP_PREFIX, "tatara.pleme.io/");
4123    }
4124
4125    #[test]
4126    fn group_prefix_matches_finalizers_group_prefix() {
4127        // Cross-peer-family coherence pin — the annotation family +
4128        // the finalizer family MUST share the same reverse-DNS
4129        // namespace prefix at the substrate level. A future rename
4130        // that shifted ONE module's prefix (a group-segment migration
4131        // that landed at the annotation family but forgot the
4132        // finalizer family, or vice-versa) would silently unbind the
4133        // two peer families and let one CRD's finalizers escape the
4134        // reverse-DNS convention every annotation key on the same CRD
4135        // still carried. Pin the two consts equal at the ONE
4136        // substrate-level coherence witness.
4137        assert_eq!(annotations::GROUP_PREFIX, finalizers::GROUP_PREFIX);
4138    }
4139
4140    #[test]
4141    fn all_matches_declared_length() {
4142        // A regression that added a 22nd `pub const` above the ALL
4143        // slice without appending it to ALL (or shrank the family
4144        // without pruning the slice) would surface here. The
4145        // 21-arm listing pins the declaration order every downstream
4146        // audit sweep iterates through.
4147        assert_eq!(annotations::ALL.len(), 21);
4148    }
4149
4150    #[test]
4151    fn all_share_group_prefix() {
4152        // Every arm of the family MUST start with the shared
4153        // [`crate::annotations::GROUP_PREFIX`] reverse-DNS namespace
4154        // — matching the `#[kube(group = "tatara.pleme.io", …)]`
4155        // slot on every CRD struct. A future rename that drifted ONE
4156        // arm's prefix (a `tatara.io/` copy-paste that silently
4157        // escaped the K8s-side convention) would silently corrupt
4158        // every downstream annotation read on that key; the pin
4159        // surfaces the drift here rather than at operator-visible
4160        // annotation-read skew.
4161        for key in annotations::ALL {
4162            assert!(
4163                key.starts_with(annotations::GROUP_PREFIX),
4164                "annotation key {key:?} must start with {:?}",
4165                annotations::GROUP_PREFIX,
4166            );
4167        }
4168    }
4169
4170    #[test]
4171    fn all_are_pairwise_unique() {
4172        // No two arms of the family may share the same wire form —
4173        // a copy-paste regression that duplicated one arm's wire
4174        // form at another arm (e.g. a `POOL_SLOT` const that got
4175        // copy-pasted to the `RETURN_TRIGGER` const's value) would
4176        // silently double-book the K8s metadata slot the two keys
4177        // share, letting one write overwrite the other at whichever
4178        // downstream stamp site fired second.
4179        let mut seen: Vec<&str> = Vec::new();
4180        for key in annotations::ALL {
4181            assert!(
4182                !seen.contains(key),
4183                "duplicate annotation key in ALL: {key:?}",
4184            );
4185            seen.push(key);
4186        }
4187        assert_eq!(seen.len(), annotations::ALL.len());
4188    }
4189
4190    #[test]
4191    fn all_contains_every_declared_const() {
4192        // Coherence pin — a regression that added a new `pub const`
4193        // above the ALL slice but forgot to append it here surfaces
4194        // by name at this pin. Every currently-declared const in
4195        // [`crate::annotations`] MUST appear at least once in the
4196        // [`crate::annotations::ALL`] slice; if a future editor
4197        // adds a 22nd const above but omits it below, this pin +
4198        // [`all_matches_declared_length`] together catch both the
4199        // slice-length drift and the omitted-const case.
4200        for key in [
4201            annotations::MANAGED_BY,
4202            annotations::PROCESS,
4203            annotations::PID,
4204            annotations::CONTENT_HASH,
4205            annotations::ATTESTATION_ROOT,
4206            annotations::GENERATION,
4207            annotations::SIGNAL,
4208            annotations::RELEASED_FROM,
4209            annotations::ROLE,
4210            annotations::EXPORT_INDEX,
4211            annotations::APP,
4212            annotations::ROUTING_FORM,
4213            annotations::REQUESTOR,
4214            annotations::ALLOCATION,
4215            annotations::REQUESTOR_KIND,
4216            annotations::POOL,
4217            annotations::POOL_SLOT,
4218            annotations::RETURN_TRIGGER,
4219            annotations::ENCAPSULATION_MODE,
4220            annotations::ADOPTED_RELEASE,
4221            annotations::RECEIPT,
4222        ] {
4223            assert!(
4224                annotations::ALL.contains(&key),
4225                "annotation key {key:?} missing from ALL slice",
4226            );
4227        }
4228    }
4229
4230    #[test]
4231    fn all_disjoint_from_finalizer_family() {
4232        // Cross-peer-family disjointness pin — the annotation +
4233        // finalizer families share the reverse-DNS namespace
4234        // [`crate::annotations::GROUP_PREFIX`] but MUST NOT share
4235        // any specific wire-form key. A copy-paste that landed a
4236        // finalizer key (`tatara.pleme.io/<owner>-finalizer`) in
4237        // the annotation family, or an annotation key on the
4238        // finalizer family, would let a metadata-list writer
4239        // silently double-book the K8s garbage-collection slot on
4240        // the SAME resource the annotation reader consumes.
4241        for ann in annotations::ALL {
4242            for fin in finalizers::ALL {
4243                assert_ne!(
4244                    ann, fin,
4245                    "annotation key {ann:?} collides with finalizer key {fin:?}",
4246                );
4247            }
4248        }
4249    }
4250}