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