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