Skip to main content

tatara_process/
lib.rs

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