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 /// Label key stamped on every receipt [`ConfigMap`] that carries a
1140 /// typed [`crate::receipt::ReceiptEnvelope`] payload, so operators
1141 /// can `kubectl get cm -l tatara.pleme.io/receipt=tatara-receipt/v1`
1142 /// to enumerate every receipt of a given version on a cluster
1143 /// without pre-parsing each CM's embedded JSON/YAML.
1144 ///
1145 /// Value is [`crate::receipt::RECEIPT_VERSION`] — the wire-format
1146 /// version string every parser gates on. A future bump to
1147 /// `tatara-receipt/v2` lands at ONE const declaration on
1148 /// [`crate::receipt::RECEIPT_VERSION`] and every consumer that
1149 /// stamps this label picks up the upgrade mechanically.
1150 ///
1151 /// Load-bearing at TWO production write-sites past the ★★
1152 /// PRIME-DIRECTIVE ≥ 2 duplication threshold:
1153 /// - `tatara-closed-loop-probe::write_receipt_cm`'s
1154 /// `BTreeMap::from([...])` label seed — the closed-loop auth
1155 /// probe's receipt-CM label writer.
1156 /// - `tatara_process::configmap::with_data`'s byte-shape parity
1157 /// witness test that mirrors the closed-loop-probe callsite.
1158 ///
1159 /// The `tatara-export-worker` receipt-CM writer intentionally
1160 /// stamps NO labels (its consumer keys on the CM name the
1161 /// ExportSpec channel already carries), so it is not a consumer of
1162 /// this const; the two production label-stamp sites above are the
1163 /// complete workspace consumer set today.
1164 ///
1165 /// Peer to [`ROLE`] + [`EXPORT_INDEX`] on the "annotation / label
1166 /// key stamped on a receipt-emitting resource other than the
1167 /// Process itself" axis-family: those two keys ride on the
1168 /// export-worker Job the reconciler emits (Job-side), this key
1169 /// rides on the receipt ConfigMap the probe binary writes
1170 /// (ConfigMap-side); all three share the [`GROUP_PREFIX`]
1171 /// reverse-DNS namespace. A future rename of this key (a
1172 /// `tatara.pleme.io/v2/receipt` migration, a per-fleet override, a
1173 /// collapse into a compound `tatara.pleme.io/receipt-envelope`
1174 /// key) lands at ONE `pub const` in the substrate and every
1175 /// downstream consumer inherits the upgrade mechanically.
1176 pub const RECEIPT: &str = "tatara.pleme.io/receipt";
1177
1178 /// Shared reverse-DNS namespace prefix every substrate-owned
1179 /// annotation key in this module carries — the same
1180 /// `tatara.pleme.io/` group segment every tatara-owned CRD
1181 /// annotation + finalizer key rides through, matching the
1182 /// `#[kube(group = "tatara.pleme.io", …)]` derive slot on every
1183 /// tatara CRD struct.
1184 ///
1185 /// Byte-parity mirror of the sibling
1186 /// [`crate::finalizers::GROUP_PREFIX`] on the peer-family axis: the
1187 /// [`crate::finalizers`] module owns the ONE canonical
1188 /// `tatara.pleme.io/` const on the finalizer-key family axis; this
1189 /// const opens the SAME canonical prefix on the annotation-key
1190 /// family axis. Both families ride the same reverse-DNS namespace;
1191 /// pinning them at a shared const AND at a coherence pin
1192 /// ([`crate::annotations_family_tests::group_prefix_matches_finalizers_group_prefix`])
1193 /// binds the two peer families to ONE substrate owner rather than
1194 /// two independent per-module string literals — a future
1195 /// group-segment shift (a `tatara.pleme.io/v2/` migration, a
1196 /// per-fleet override, a per-cluster ownership prefix) lands at ONE
1197 /// crate-wide const pair here + at [`crate::finalizers::GROUP_PREFIX`]
1198 /// with the pin catching any partial edit, rather than at 20 +
1199 /// 3 hand-authored per-key literals spread across the two modules.
1200 ///
1201 /// Pinned across every arm of [`ALL`] by
1202 /// [`crate::annotations_family_tests::all_share_group_prefix`] so a
1203 /// future addition to the annotation family that drifted the prefix
1204 /// (a `tatara.io/` copy-paste that silently escaped the K8s-side
1205 /// reverse-DNS convention, a group-segment shift on ONE key that
1206 /// missed the ALL slice) surfaces at compile-time / test-time rather
1207 /// than as silent operator-facing skew.
1208 pub const GROUP_PREFIX: &str = "tatara.pleme.io/";
1209
1210 /// Closed family of every substrate-owned annotation key in this
1211 /// module, in stable declaration order matching the `pub const`
1212 /// definitions above.
1213 ///
1214 /// Peer to [`crate::finalizers::ALL`] on the "closed slice over a
1215 /// family of tatara-owned wire-form keys sharing the
1216 /// [`GROUP_PREFIX`] reverse-DNS namespace" axis-pair: the
1217 /// [`crate::finalizers`] module owns the same shape over its three
1218 /// finalizer keys; this const opens the mirror over the 20
1219 /// annotation keys in this module.
1220 ///
1221 /// Downstream sweeps that pre-lift the ALL owner had to hand-list
1222 /// every substrate-owned annotation key to iterate them — a
1223 /// fleet-wide annotation-audit binary dumping every
1224 /// `tatara.pleme.io/*` key on a cluster, a per-key coverage report
1225 /// answering "which annotations does the reconciler write vs read",
1226 /// a cross-cluster rename planner, the existing intra-module
1227 /// pairwise-disjointness tests (see the "peer list" arrays in
1228 /// [`crate::annotations_pins`] which hand-list up to 18 sibling
1229 /// keys to prove one axis is disjoint from every other) — iterate
1230 /// through ONE substrate slice post-lift. A future addition to the
1231 /// annotation family that landed a new `pub const` above but forgot
1232 /// this slice surfaces at
1233 /// [`crate::annotations_family_tests::all_matches_declared_length`]
1234 /// rather than by silently escaping every downstream iteration
1235 /// consumer.
1236 ///
1237 /// Pinned to length 21 by
1238 /// [`crate::annotations_family_tests::all_matches_declared_length`],
1239 /// to shared [`GROUP_PREFIX`] membership by
1240 /// [`crate::annotations_family_tests::all_share_group_prefix`],
1241 /// and to pairwise-uniqueness by
1242 /// [`crate::annotations_family_tests::all_are_pairwise_unique`] so
1243 /// a copy-paste that duplicated one arm's wire form at another arm
1244 /// (silently double-booking the K8s metadata slot the two keys
1245 /// share) surfaces at the family pin rather than as silent
1246 /// annotation-writer collision at whichever downstream site
1247 /// stamped the copy-paste'd key.
1248 pub const ALL: &[&str] = &[
1249 MANAGED_BY,
1250 PROCESS,
1251 PID,
1252 CONTENT_HASH,
1253 ATTESTATION_ROOT,
1254 GENERATION,
1255 SIGNAL,
1256 RELEASED_FROM,
1257 ROLE,
1258 EXPORT_INDEX,
1259 APP,
1260 ROUTING_FORM,
1261 REQUESTOR,
1262 ALLOCATION,
1263 REQUESTOR_KIND,
1264 POOL,
1265 POOL_SLOT,
1266 RETURN_TRIGGER,
1267 ENCAPSULATION_MODE,
1268 ADOPTED_RELEASE,
1269 RECEIPT,
1270 ];
1271}
1272
1273/// Standard finalizer for the Process reconciler.
1274///
1275/// Re-export of [`finalizers::PROCESS`] — the substrate-owner
1276/// per-CRD finalizer family lives at [`crate::finalizers`]; this
1277/// top-level const stays put for downstream consumers that predate
1278/// the module, and is coherence-pinned against
1279/// [`finalizers::PROCESS`] by
1280/// [`finalizers::tests::process_finalizer_top_level_reexport_routes_through_finalizers_process`].
1281pub const PROCESS_FINALIZER: &str = finalizers::PROCESS;
1282
1283/// Shared schemars helpers — emit OpenAPI schemas Kubernetes accepts.
1284/// Free-form `serde_json::Value` fields default to an *empty* schema
1285/// in schemars, which the K8s API server rejects with "type: Required
1286/// value: must not be empty for specified object fields". The typed
1287/// workaround is to emit `{type: object, x-kubernetes-preserve-unknown-
1288/// fields: true}` — same shape kube-rs's own helpers produce.
1289pub mod schema_helpers {
1290 use schemars::{gen::SchemaGenerator, schema::Schema};
1291 /// Schema for a free-form JSON object field. Apply via
1292 /// `#[schemars(schema_with = "tatara_process::schema_helpers::preserve_unknown_object")]`
1293 /// on any `serde_json::Value` / `BTreeMap<String, serde_json::Value>`
1294 /// field exposed through a CRD.
1295 pub fn preserve_unknown_object(_g: &mut SchemaGenerator) -> Schema {
1296 serde_json::from_value(serde_json::json!({
1297 "type": "object",
1298 "x-kubernetes-preserve-unknown-fields": true
1299 }))
1300 .expect("static JSON literal parses as Schema")
1301 }
1302}
1303
1304#[cfg(test)]
1305mod owner_reference_tests {
1306 //! Pin the `owner_reference_json` composer at fail-before-pass-
1307 //! after granularity. Every shape a pre-lift caller hand-authored
1308 //! is re-asserted here so a regression that inlined any of the
1309 //! six slots at a call site (breaking the primitive's role as
1310 //! the ONE source of truth) fails HERE at the composer's shipped-
1311 //! shape pin rather than as silent drift between the pre-lift
1312 //! `render.rs` / `edges.rs` / `ssapply.rs` sites (which pre-lift
1313 //! already carried TWO different `apiVersion` spellings — a
1314 //! composed `format!("{}/{}", GROUP, VERSION)` at two sites and
1315 //! the frozen literal `"tatara.pleme.io/v1alpha1"` at the third).
1316 use super::{
1317 api_version, owner_reference_json, owner_references_json, API_VERSION, GROUP, PROCESS_KIND,
1318 PROCESS_WIRE_IDENTITY, VERSION,
1319 };
1320 use crate::flux_resource::FluxResource;
1321 use crate::k8s_builtin_resource::K8sBuiltinResource;
1322 use crate::k8s_wire_identity::K8sWireIdentity;
1323 use crate::routing_edge_resource::RoutingEdgeResource;
1324 use serde_json::json;
1325
1326 #[test]
1327 fn api_version_composes_group_and_version() {
1328 // Any bump of GROUP or VERSION lands at ONE composer.
1329 assert_eq!(api_version(), format!("{GROUP}/{VERSION}"));
1330 }
1331
1332 // ─── API_VERSION const substrate pins ───────────────────────────
1333 //
1334 // The compile-time `&'static str` [`API_VERSION`] const feeds the
1335 // typed [`PROCESS_WIRE_IDENTITY`] const and delegates the runtime
1336 // [`api_version`] fn — these pins bind the const at fail-before-
1337 // pass-after granularity so a regression that drifted the const
1338 // (a rename that touched [`GROUP`] but not the const's baked
1339 // literal, a VERSION bump that only updated [`VERSION`]) surfaces
1340 // HERE rather than as silent operator-facing skew between the
1341 // typed-const consumers and the fn-based consumers on the same
1342 // wire-form axis.
1343
1344 #[test]
1345 fn api_version_const_composes_group_and_version_bytewise() {
1346 // Cross-const coherence pin: the compile-time [`API_VERSION`]
1347 // must be byte-identical to the runtime `format!("{GROUP}/
1348 // {VERSION}")` composition. A regression that drifted either
1349 // the const or the two segment consts would surface HERE
1350 // rather than as silent skew between [`PROCESS_WIRE_IDENTITY`]
1351 // (which composes over the const) and [`api_url_prefix`]
1352 // (which composes over the two segment consts at runtime).
1353 assert_eq!(API_VERSION, format!("{GROUP}/{VERSION}"));
1354 }
1355
1356 #[test]
1357 fn api_version_const_byte_matches_wire_form_pre_lift() {
1358 // Byte-identity pin: the frozen wire-form literal is the SAME
1359 // string every downstream consumer (the typed
1360 // [`PROCESS_WIRE_IDENTITY`] const, the runtime [`api_version`]
1361 // fn, every K8s `apiVersion:` slot the reconciler stamps)
1362 // must emit. Peer of the pre-existing runtime pin
1363 // [`api_version_byte_matches_wire_form_pre_lift`]; both close
1364 // the axis at the SAME wire form.
1365 assert_eq!(API_VERSION, "tatara.pleme.io/v1alpha1");
1366 }
1367
1368 #[test]
1369 fn api_version_fn_delegates_through_const_owner() {
1370 // Routing pin: the runtime `api_version()` fn returns
1371 // [`API_VERSION`]`.to_string()` — the ONE substrate owner of
1372 // the wire-form literal. A regression that re-open-coded the
1373 // fn's body (restoring the pre-lift `format!("{GROUP}/
1374 // {VERSION}")` composition, or inlining a stale literal) would
1375 // surface HERE rather than as silent skew between the two
1376 // sibling emit paths (typed-const vs owned-String).
1377 assert_eq!(api_version(), API_VERSION);
1378 }
1379
1380 #[test]
1381 fn api_version_const_is_reachable_at_compile_time() {
1382 // Compile-time reachability pin: [`API_VERSION`] is a `const
1383 // &'static str` so a caller can bind it into a `const` slot —
1384 // exactly what [`PROCESS_WIRE_IDENTITY`] does through
1385 // [`K8sWireIdentity::new`]'s `const fn`. A regression that
1386 // widened the const to an owned `String` or a `Lazy<String>`
1387 // would fail-loudly at this coercion rather than at the
1388 // silent runtime-vs-const composition boundary at
1389 // [`PROCESS_WIRE_IDENTITY`].
1390 const AV: &str = API_VERSION;
1391 assert_eq!(AV, "tatara.pleme.io/v1alpha1");
1392 }
1393
1394 // ─── PROCESS_WIRE_IDENTITY substrate pins ───────────────────────
1395 //
1396 // The typed [`PROCESS_WIRE_IDENTITY`] const closes the fourth arm
1397 // of the K8s-wire-form-identity axis-family (peer to
1398 // [`K8sBuiltinResource::wire_identity`],
1399 // [`FluxResource::wire_identity`],
1400 // [`RoutingEdgeResource::wire_identity`]). These pins bind the
1401 // const at fail-before-pass-after granularity so a regression that
1402 // drifted either slot (an `apiVersion` slot that stopped routing
1403 // through [`API_VERSION`], a `kind` slot that stopped routing
1404 // through [`PROCESS_KIND`]) surfaces HERE rather than as silent
1405 // OwnerReference-emit skew at every downstream consumer.
1406
1407 #[test]
1408 fn process_wire_identity_pairs_api_version_and_kind_through_substrate_owners() {
1409 // Slot-routing pin: both slots MUST route through the ONE
1410 // substrate owner per slot ([`API_VERSION`] for the
1411 // `apiVersion` slot, [`PROCESS_KIND`] for the `kind` slot).
1412 // A regression that re-inlined either slot's literal at the
1413 // const declaration would surface HERE rather than as silent
1414 // skew between the wire-identity const and its slot owners.
1415 assert_eq!(PROCESS_WIRE_IDENTITY.api_version, API_VERSION);
1416 assert_eq!(PROCESS_WIRE_IDENTITY.kind, PROCESS_KIND);
1417 }
1418
1419 #[test]
1420 fn process_wire_identity_byte_matches_wire_form_pre_lift() {
1421 // Byte-identity pin: the const's `(apiVersion, kind)` pair
1422 // must equal the two frozen wire-form strings every pre-lift
1423 // consumer hand-authored — a regression that drifted either
1424 // slot would surface HERE rather than as a wire-time 404 the
1425 // K8s API server would misdiagnose as a broken CRD.
1426 assert_eq!(
1427 PROCESS_WIRE_IDENTITY.api_version,
1428 "tatara.pleme.io/v1alpha1"
1429 );
1430 assert_eq!(PROCESS_WIRE_IDENTITY.kind, "Process");
1431 }
1432
1433 #[test]
1434 fn process_wire_identity_is_const_reachable() {
1435 // Compile-time reachability pin: [`PROCESS_WIRE_IDENTITY`] is
1436 // a compile-time `const K8sWireIdentity` so a caller can bind
1437 // it into a `const` slot. A regression that dropped the
1438 // `const fn` qualifier on [`K8sWireIdentity::new`] or widened
1439 // [`API_VERSION`] off the `&'static str` axis would fail-loudly
1440 // HERE rather than as a runtime dispatch at every OwnerReference
1441 // emit site.
1442 const ID: K8sWireIdentity = PROCESS_WIRE_IDENTITY;
1443 assert_eq!(ID.api_version, "tatara.pleme.io/v1alpha1");
1444 assert_eq!(ID.kind, "Process");
1445 }
1446
1447 #[test]
1448 fn process_wire_identity_is_disjoint_from_every_peer_wire_form_axis() {
1449 // Cross-substrate coherence pin: the tatara `Process` CRD's
1450 // typed `(apiVersion, kind)` pair MUST NOT collide with any
1451 // variant of the three peer closed-set axes on the K8s wire-
1452 // form-identity axis-family
1453 // ([`K8sBuiltinResource`] / [`FluxResource`] /
1454 // [`RoutingEdgeResource`]) — a hypothetical variant addition
1455 // on any peer that copy-pasted the tatara `Process` pair
1456 // (a `FluxResource::Process` renaming collision, a
1457 // `K8sBuiltinResource::Process` typo) would silently let a
1458 // reconciler dispatch reach through the wrong closed set. Pin
1459 // the disjointness so every future addition to any peer axis
1460 // that would collide with this const surfaces HERE.
1461 for k in K8sBuiltinResource::ALL {
1462 assert_ne!(
1463 (
1464 PROCESS_WIRE_IDENTITY.api_version,
1465 PROCESS_WIRE_IDENTITY.kind
1466 ),
1467 (k.api_version(), k.kind()),
1468 "PROCESS_WIRE_IDENTITY must not share a wire-form pair with K8sBuiltinResource {k:?}"
1469 );
1470 }
1471 for f in FluxResource::ALL {
1472 assert_ne!(
1473 (
1474 PROCESS_WIRE_IDENTITY.api_version,
1475 PROCESS_WIRE_IDENTITY.kind
1476 ),
1477 (f.api_version(), f.kind()),
1478 "PROCESS_WIRE_IDENTITY must not share a wire-form pair with FluxResource {f:?}"
1479 );
1480 }
1481 for r in RoutingEdgeResource::ALL {
1482 assert_ne!(
1483 (
1484 PROCESS_WIRE_IDENTITY.api_version,
1485 PROCESS_WIRE_IDENTITY.kind
1486 ),
1487 (r.api_version(), r.kind()),
1488 "PROCESS_WIRE_IDENTITY must not share a wire-form pair with RoutingEdgeResource {r:?}"
1489 );
1490 }
1491 }
1492
1493 #[test]
1494 fn owner_reference_json_routes_apiversion_and_kind_through_process_wire_identity() {
1495 // Routing pin: the `owner_reference_json` composer's
1496 // `(apiVersion, kind)` pair MUST match the typed
1497 // [`PROCESS_WIRE_IDENTITY`] const's `(api_version, kind)`
1498 // fields byte-for-byte. Post-lift the composer routes through
1499 // [`K8sWireIdentity::resource_json`], so this equality holds
1500 // by construction; a regression that re-open-coded the two
1501 // slots at the composer body (restoring the pre-lift `json!`
1502 // inline reference to `api_version()` + `PROCESS_KIND`
1503 // separately) would surface HERE rather than as silent skew
1504 // between the OwnerReference emit and the typed const owner.
1505 let v = owner_reference_json("p", "u");
1506 assert_eq!(v["apiVersion"], PROCESS_WIRE_IDENTITY.api_version);
1507 assert_eq!(v["kind"], PROCESS_WIRE_IDENTITY.kind);
1508 }
1509
1510 #[test]
1511 fn api_version_byte_matches_wire_form_pre_lift() {
1512 // Byte-identity pin: the frozen wire-form literal
1513 // `"tatara.pleme.io/v1alpha1"` that `ssapply.rs::
1514 // build_owner_reference` hand-wrote pre-lift must equal the
1515 // composed shape now sourced through the ONE owner. A
1516 // future VERSION bump that missed this test would land as
1517 // an operator-visible reference-mismatch after apply.
1518 assert_eq!(api_version(), "tatara.pleme.io/v1alpha1");
1519 }
1520
1521 #[test]
1522 fn api_url_prefix_composes_apis_group_version_slash() {
1523 // Composition pin: any bump of GROUP or VERSION lands at
1524 // ONE composer.
1525 assert_eq!(super::api_url_prefix(), format!("/apis/{GROUP}/{VERSION}/"));
1526 }
1527
1528 #[test]
1529 fn api_url_prefix_byte_matches_wire_form_pre_lift() {
1530 // Byte-identity pin: the frozen wire-form literal
1531 // `"/apis/tatara.pleme.io/v1alpha1/"` that eleven
1532 // hand-authored scope guards across `tatara-reconciler::
1533 // context`, `tatara-pool-reconciler::context`, and
1534 // `tatara-github-watcher::handler` restated pre-lift must
1535 // equal the composed shape now sourced through the ONE
1536 // owner. A future group rename or VERSION bump that missed
1537 // this pin would land as a silent scope-guard mismatch at
1538 // every downstream Api-primitive test.
1539 assert_eq!(super::api_url_prefix(), "/apis/tatara.pleme.io/v1alpha1/");
1540 }
1541
1542 #[test]
1543 fn api_url_prefix_carries_api_version_between_apis_and_trailing_slash() {
1544 // Cross-primitive pin: the URL prefix and the `apiVersion`
1545 // wire form share the SAME `<GROUP>/<VERSION>` shape,
1546 // wrapped by the fixed `/apis/…/` HTTP-path envelope. A
1547 // regression that drifted the two composers apart (a bump
1548 // that missed one of the two owners) surfaces here rather
1549 // than as an operator-visible mismatch between an emitted
1550 // ownerReference's `apiVersion` and the REST url every typed
1551 // `Api` primitive routes through.
1552 let prefix = super::api_url_prefix();
1553 let version = api_version();
1554 assert!(
1555 prefix.starts_with("/apis/") && prefix.ends_with('/'),
1556 "prefix must be wrapped as `/apis/…/`; got {prefix}"
1557 );
1558 let inner = &prefix["/apis/".len()..prefix.len() - 1];
1559 assert_eq!(
1560 inner, version,
1561 "prefix inner slot must equal api_version(); got inner={inner:?} version={version:?}"
1562 );
1563 }
1564
1565 #[test]
1566 fn process_kind_is_process_literal() {
1567 // Symbol-vs-string pin: any consumer that hand-wrote `"Process"`
1568 // pre-lift routes through this const post-lift.
1569 assert_eq!(PROCESS_KIND, "Process");
1570 }
1571
1572 #[test]
1573 fn owner_reference_json_has_all_six_slots_present() {
1574 let v = owner_reference_json("my-process", "abc-uid");
1575 let obj = v.as_object().expect("owner reference is a JSON object");
1576 for k in [
1577 "apiVersion",
1578 "kind",
1579 "name",
1580 "uid",
1581 "controller",
1582 "blockOwnerDeletion",
1583 ] {
1584 assert!(obj.contains_key(k), "missing owner-reference slot: {k}");
1585 }
1586 assert_eq!(obj.len(), 6, "owner reference must have exactly 6 slots");
1587 }
1588
1589 #[test]
1590 fn owner_reference_json_apiversion_routes_through_api_version_owner() {
1591 let v = owner_reference_json("x", "y");
1592 assert_eq!(v["apiVersion"], api_version());
1593 }
1594
1595 #[test]
1596 fn owner_reference_json_kind_routes_through_process_kind_const() {
1597 let v = owner_reference_json("x", "y");
1598 assert_eq!(v["kind"], PROCESS_KIND);
1599 }
1600
1601 #[test]
1602 fn owner_reference_json_stamps_supplied_name_and_uid() {
1603 let v = owner_reference_json("some-name", "some-uid");
1604 assert_eq!(v["name"], "some-name");
1605 assert_eq!(v["uid"], "some-uid");
1606 }
1607
1608 #[test]
1609 fn owner_reference_json_controller_and_block_owner_deletion_are_true() {
1610 // These are structural — a Process-owned resource always
1611 // has a controlling reference that cascade-deletes with
1612 // the owner. A regression that flipped either boolean
1613 // would silently detach every emitted resource.
1614 let v = owner_reference_json("x", "y");
1615 assert_eq!(v["controller"], true);
1616 assert_eq!(v["blockOwnerDeletion"], true);
1617 }
1618
1619 #[test]
1620 fn owner_reference_json_matches_hand_authored_shape_pre_lift() {
1621 // Byte-shape pin against the exact `json!({…})` incantation
1622 // every pre-lift call site restated. A regression that
1623 // reordered a slot, dropped one, or added a seventh here
1624 // surfaces at THIS pin rather than as a subtle SSA-apply
1625 // failure downstream when the K8s API server rejects the
1626 // OwnerReference on schema mismatch.
1627 let via_owner = owner_reference_json("p", "u");
1628 let hand_authored = json!({
1629 "apiVersion": "tatara.pleme.io/v1alpha1",
1630 "kind": "Process",
1631 "name": "p",
1632 "uid": "u",
1633 "controller": true,
1634 "blockOwnerDeletion": true,
1635 });
1636 assert_eq!(via_owner, hand_authored);
1637 }
1638
1639 #[test]
1640 fn owner_reference_json_preserves_empty_name_and_uid_bytewise() {
1641 // The primitive does not guard against empty inputs — its
1642 // callers pre-lift did the empty-check upstream (both the
1643 // `edges.rs::build_owner_refs` and `render.rs::one_export_job`
1644 // sites gated on `!uid.is_empty()` before calling this composer,
1645 // and both now route through `owner_references_json` below;
1646 // `ssapply.rs::build_owner_reference` unwraps a required
1647 // `metadata.uid` via anyhow). The scalar composer owns
1648 // shape composition, not admission control; a downstream
1649 // rename that wants strict input validation lands as a
1650 // peer, not a change to the composer's contract.
1651 let v = owner_reference_json("", "");
1652 assert_eq!(v["name"], "");
1653 assert_eq!(v["uid"], "");
1654 }
1655
1656 // ─── owner_references_json substrate pins ────────────────────────
1657 //
1658 // The 3-line `let mut owner_refs = vec![]; if !uid.is_empty()
1659 // { owner_refs.push(owner_reference_json(name, uid)); }` gate was
1660 // hand-authored at TWO sites in `tatara-reconciler`
1661 // (`edges::build_owner_refs` + `render::one_export_job`) before
1662 // this primitive existed, each restating the same optional-uid
1663 // posture that emits `[]` when the caller lacks a K8s-assigned
1664 // uid to point owners at. These pins bind the primitive at
1665 // fail-before-pass-after granularity so a regression that
1666 // inlined an owner reference for an empty uid — silently
1667 // detaching the resource from cascade-delete — surfaces HERE
1668 // rather than as an operator-visible ownerless resource after
1669 // apply, and a regression that added an owner reference of the
1670 // wrong SHAPE (a peer of `owner_reference_json` that swapped a
1671 // slot) surfaces via the composed-shape pin below rather than
1672 // as silent drift at every downstream emit site.
1673
1674 #[test]
1675 fn owner_references_json_emits_single_entry_when_uid_present() {
1676 // The primary shape: a caller with a materialized uid gets
1677 // exactly one owner reference back — the pre-lift 3-line
1678 // `vec![]` + `push` gate collapses to this ONE call, and
1679 // the returned array is a direct-drop `ownerReferences`
1680 // slot value at every callsite.
1681 let refs = owner_references_json("demo-app", "abc-uid");
1682 assert_eq!(refs.len(), 1);
1683 assert_eq!(refs[0]["kind"], PROCESS_KIND);
1684 assert_eq!(refs[0]["name"], "demo-app");
1685 assert_eq!(refs[0]["uid"], "abc-uid");
1686 // controller + blockOwnerDeletion routed through the scalar
1687 // composer — a regression that hand-composed the vec entry
1688 // rather than delegating would flip one of these booleans.
1689 assert_eq!(refs[0]["controller"], true);
1690 assert_eq!(refs[0]["blockOwnerDeletion"], true);
1691 }
1692
1693 #[test]
1694 fn owner_references_json_emits_empty_when_uid_empty() {
1695 // The load-bearing gate — a pre-metadata Process (fixtured in
1696 // tests, or caught mid-Forking) has no admissible owner
1697 // reference to point at. Post-lift the gate lives at ONE
1698 // primitive so every emit site stamps `[]` uniformly rather
1699 // than one site accidentally emitting a placeholder-uid
1700 // owner reference the K8s GC would quietly detach from
1701 // cascade-delete.
1702 let refs = owner_references_json("demo-app", "");
1703 assert!(
1704 refs.is_empty(),
1705 "empty uid must produce zero owner references, not a placeholder-uid entry"
1706 );
1707 }
1708
1709 #[test]
1710 fn owner_references_json_gates_on_uid_not_name() {
1711 // The gate axis is `uid`, not `name` — a Process with a
1712 // non-empty name but no uid still emits `[]` (the pre-metadata
1713 // shape), while a Process with a non-empty uid emits ONE
1714 // entry even when the name slot is empty (matching the
1715 // scalar composer's admission-control-free contract). Pin
1716 // both cross-diagonal combinations so a regression that
1717 // swapped the gate axis surfaces HERE rather than at every
1718 // downstream owner-refs consumer.
1719 assert!(
1720 owner_references_json("has-name", "").is_empty(),
1721 "empty uid gates to []; name presence is irrelevant"
1722 );
1723 let refs = owner_references_json("", "has-uid");
1724 assert_eq!(
1725 refs.len(),
1726 1,
1727 "empty name but present uid still emits one entry (name is not the gate)"
1728 );
1729 assert_eq!(refs[0]["name"], "");
1730 assert_eq!(refs[0]["uid"], "has-uid");
1731 }
1732
1733 #[test]
1734 fn owner_references_json_matches_hand_authored_pre_lift_bytewise() {
1735 // Byte-identical parity with the exact pre-lift 3-line
1736 // `let mut owner_refs = vec![]; if !uid.is_empty() {
1737 // owner_refs.push(owner_reference_json(name, uid)); }` gate
1738 // across the two axis combinations every callsite plausibly
1739 // encounters. A regression that reordered the two branches,
1740 // dropped the gate, or reshaped the vec composition surfaces
1741 // HERE rather than at every downstream `ownerReferences`
1742 // slot pinned across `edges.rs` + `render.rs` tests.
1743 for (name, uid) in [
1744 ("demo-app", "uid-abc"),
1745 ("demo-app", ""),
1746 ("", "uid-abc"),
1747 ("", ""),
1748 ] {
1749 let via_primitive = owner_references_json(name, uid);
1750
1751 // The pre-lift 3-line block, byte-for-byte.
1752 let mut hand_authored: Vec<serde_json::Value> = vec![];
1753 if !uid.is_empty() {
1754 hand_authored.push(owner_reference_json(name, uid));
1755 }
1756
1757 assert_eq!(
1758 via_primitive, hand_authored,
1759 "owner_references_json must be byte-identical to the pre-lift 3-line gate on ({name:?}, {uid:?})"
1760 );
1761 }
1762 }
1763
1764 #[test]
1765 fn owner_references_json_interpolates_cleanly_as_owner_refs_slot() {
1766 // Both callsites drop the returned vec directly under a
1767 // `"ownerReferences"` key inside a `json!({...})` block. Pin
1768 // the interop shape: a JSON-macro-wrapped Value carries the
1769 // primitive's output as a JSON array with the exact 6-slot
1770 // entries at each index. A regression that returned a
1771 // non-array (e.g. a single Value on the one-entry path,
1772 // requiring per-site vec-wrapping) surfaces HERE rather than
1773 // as a broken `metadata.ownerReferences` slot on every
1774 // emitted Ingress / DNSEndpoint / export Job.
1775 let refs = owner_references_json("demo-app", "abc-uid");
1776 let wrapped = json!({
1777 "metadata": {
1778 "name": "resource",
1779 "ownerReferences": refs,
1780 },
1781 });
1782 let owner_refs = &wrapped["metadata"]["ownerReferences"];
1783 assert!(
1784 owner_refs.is_array(),
1785 "ownerReferences must land as a JSON array"
1786 );
1787 assert_eq!(owner_refs.as_array().unwrap().len(), 1);
1788 assert_eq!(owner_refs[0]["kind"], PROCESS_KIND);
1789
1790 // And the empty-uid path lands as an EMPTY array, not a
1791 // missing key or a null — matches the K8s API server's
1792 // expectation that the slot is either an array of entries
1793 // or absent, never a null.
1794 let empty_refs = owner_references_json("demo-app", "");
1795 let wrapped_empty = json!({
1796 "metadata": {
1797 "name": "resource",
1798 "ownerReferences": empty_refs,
1799 },
1800 });
1801 let owner_refs_empty = &wrapped_empty["metadata"]["ownerReferences"];
1802 assert!(owner_refs_empty.is_array());
1803 assert!(owner_refs_empty.as_array().unwrap().is_empty());
1804 }
1805}
1806
1807#[cfg(test)]
1808mod qualified_process_ref_tests {
1809 //! Pin the [`qualified_process_ref`] composer at fail-before-
1810 //! pass-after granularity. The `<ns>/<name>` shape is the
1811 //! workspace-wide convention for a namespaced K8s resource
1812 //! reference — every downstream grep (the reconciler's
1813 //! `tatara.pleme.io/process` annotation reader, the
1814 //! [`crate::table::ClaimRecord.holder`] slot, the
1815 //! export-worker's receipt-owner filter, the reconciler's
1816 //! `PROCESS=<ref>` label-selector composer) depends on the
1817 //! two axes landing in `(ns, name)` order joined by a single
1818 //! `/` separator. A regression that swapped the axes, dropped
1819 //! either half, or renormalized the input surfaces HERE rather
1820 //! than as silent operator-facing drift at every downstream
1821 //! consumer.
1822 use super::qualified_process_ref;
1823
1824 #[test]
1825 fn qualified_process_ref_joins_ns_and_name_with_slash() {
1826 // The invariant every downstream consumer composes against:
1827 // the qualified reference is EXACTLY `<ns>/<name>`, in that
1828 // order, joined by a single `/`.
1829 assert_eq!(
1830 qualified_process_ref("demo-ns", "ephemeral-demo"),
1831 "demo-ns/ephemeral-demo",
1832 );
1833 }
1834
1835 #[test]
1836 fn qualified_process_ref_binds_positional_slots_by_axis_order() {
1837 // Positional pin — a copy-paste that swapped the two `&str`
1838 // arguments (both mechanically interchangeable at the type
1839 // level) would silently produce `<name>/<ns>` and break every
1840 // downstream grep keyed on the reference shape. Distinct
1841 // input slot values so a swap surfaces as an equality
1842 // failure rather than accidental identity.
1843 let out = qualified_process_ref("first-slot-ns", "second-slot-name");
1844 assert!(
1845 out.starts_with("first-slot-ns/"),
1846 "position 0 must be the namespace slot: got {out}"
1847 );
1848 assert!(
1849 out.ends_with("/second-slot-name"),
1850 "position 1 must be the name slot: got {out}"
1851 );
1852 }
1853
1854 #[test]
1855 fn qualified_process_ref_accepts_string_deref_and_str_slice_shapes() {
1856 // Consumers split across two callsite shapes: owned
1857 // `String` locals (via deref coercion), bare `&str` slices,
1858 // and mixed provenance. Every shape must ride cleanly
1859 // through the same 2-arg signature — matches every current
1860 // pre-lift caller in `tatara-export-worker` (CLI-arg driven
1861 // owned strings + `&str` from a struct field) and in
1862 // `tatara-reconciler` (owned locals + function-param
1863 // slices).
1864 let owned_ns = String::from("owned-ns");
1865 let owned_name = String::from("owned-app");
1866 let borrowed_ns: &str = "borrowed-ns";
1867 let borrowed_name: &str = "borrowed-app";
1868 assert_eq!(
1869 qualified_process_ref(&owned_ns, &owned_name),
1870 "owned-ns/owned-app",
1871 );
1872 assert_eq!(
1873 qualified_process_ref(borrowed_ns, borrowed_name),
1874 "borrowed-ns/borrowed-app",
1875 );
1876 assert_eq!(
1877 qualified_process_ref(&owned_ns, borrowed_name),
1878 "owned-ns/borrowed-app",
1879 );
1880 }
1881
1882 #[test]
1883 fn qualified_process_ref_rides_edge_case_axis_shapes() {
1884 // The composer shapes the two axes as arbitrary strings —
1885 // no length/character validation happens at the composer,
1886 // so any shape a Process's `metadata.namespace` /
1887 // `metadata.name` can hold rides through unchanged. Pin
1888 // the empty-string cases (unnamed process pre-metadata,
1889 // cluster-scoped `namespace = ""` fallback), and the
1890 // whitespace-and-slash-in-name pathological case (a
1891 // regression that URL-escaped or path-normalized the input
1892 // at this primitive would silently break every downstream
1893 // grep).
1894 assert_eq!(qualified_process_ref("", ""), "/");
1895 assert_eq!(qualified_process_ref("default", ""), "default/");
1896 assert_eq!(qualified_process_ref("", "orphan"), "/orphan");
1897 assert_eq!(
1898 qualified_process_ref("weird ns", "with/slash"),
1899 "weird ns/with/slash",
1900 );
1901 }
1902
1903 #[test]
1904 fn qualified_process_ref_composes_from_process_coordinates_or_defaults() {
1905 // The primary Process-driven callsite: a live
1906 // [`crate::prelude::Process`] with populated metadata
1907 // composes through
1908 // [`crate::prelude::Process::coordinates_or_defaults`] +
1909 // [`qualified_process_ref`]. Pin the composition so a
1910 // regression in either primitive that broke the `(ns,
1911 // name)` positional contract surfaces HERE rather than as
1912 // silent drift at every downstream reconciler / export-
1913 // worker / pool-reconciler consumer.
1914 use crate::crd::{Process, ProcessSpec};
1915 // Routes through the ONE substrate composer
1916 // `ProcessSpec::gate_compute_defaults` — pre-lift this was a
1917 // 12-line inline struct-literal restated verbatim inside this
1918 // pin body.
1919 let spec = ProcessSpec::gate_compute_defaults();
1920 let mut p = Process::new("ephemeral-demo", spec);
1921 p.metadata.namespace = Some("demo-ns".into());
1922 let (ns, name) = p.coordinates_or_defaults();
1923 assert_eq!(
1924 qualified_process_ref(ns, name),
1925 "demo-ns/ephemeral-demo",
1926 "coordinates_or_defaults + qualified_process_ref must \
1927 compose to the canonical <ns>/<name> shape"
1928 );
1929 }
1930
1931 #[test]
1932 fn qualified_process_ref_matches_hand_authored_pre_lift_bytewise() {
1933 // Byte-identical parity with the exact pre-lift
1934 // `format!("{ns}/{name}")` incantation. A regression that
1935 // reshaped the separator, reordered the axes, or dropped
1936 // either half surfaces HERE rather than at every downstream
1937 // annotation / claim-key / run-id consumer. Sweeps every
1938 // shape combination the pre-lift callers plausibly
1939 // encountered.
1940 for (ns, name) in [
1941 ("demo-ns", "ephemeral-demo"),
1942 ("", ""),
1943 ("default", ""),
1944 ("", "orphan"),
1945 ] {
1946 let via_primitive = qualified_process_ref(ns, name);
1947 let hand_authored = format!("{ns}/{name}");
1948 assert_eq!(
1949 via_primitive, hand_authored,
1950 "qualified_process_ref must be byte-identical to \
1951 the pre-lift `format!(\"{{ns}}/{{name}}\")` \
1952 hand-authored shape on ({ns:?}, {name:?})"
1953 );
1954 }
1955 }
1956}
1957
1958#[cfg(test)]
1959mod qualified_error_ctx_tests {
1960 //! Pin the [`qualified_error_ctx`] composer at fail-before-
1961 //! pass-after granularity across the shape it factored out of
1962 //! the two peer per-Kind composers
1963 //! ([`crate::configmap::error_ctx`],
1964 //! [`crate::process_api::error_ctx`]). Every observable slot
1965 //! (verb-first, fixed-Kind literal in the middle, `<ns>/<name>`
1966 //! join at the tail routed through
1967 //! [`qualified_process_ref`]) is bound here so a regression
1968 //! that reordered the head slots, dropped the fixed `<Kind>`
1969 //! word, drifted the qualified-ref join off the substrate axis,
1970 //! or narrowed any input slot to a closed set (would silently
1971 //! reject a future per-Kind peer that composes a fresh verb or
1972 //! Kind literal) surfaces HERE rather than as silent operator-
1973 //! facing skew at the two consumer peers.
1974 use super::qualified_error_ctx;
1975
1976 #[test]
1977 fn qualified_error_ctx_signature_binds_borrowed_slots_returning_owned_string() {
1978 // Signature pin: `verb: &str` + `kind: &str` + `ns: &str` +
1979 // `name: &str` on the input side (both pre-lift per-Kind
1980 // peers pass a `&'static str` verb + `&'static str` fixed-
1981 // Kind literal + borrowed `&str` ns/name fields). Return
1982 // `String` matches the downstream `kube_ctx_with(context:
1983 // String)` sink verbatim on the reconciler-boundary
1984 // consumers AND the `with_context(|| String)` closure form
1985 // on the export-worker consumers.
1986 //
1987 // A regression that widened any input slot to `String`
1988 // (forcing the caller to `.to_string()` at the boundary — a
1989 // per-site perf regression that also fights the
1990 // `&str`-fields-in-args idiom the callers thread) or
1991 // narrowed the return to `&'static str` (which would prevent
1992 // the runtime-composed ns/name slots the two peer composers
1993 // pass) fails at compile time.
1994 let _witness: fn(&str, &str, &str, &str) -> String = qualified_error_ctx;
1995 }
1996
1997 #[test]
1998 fn qualified_error_ctx_composes_verb_kind_qualified_ref_head_verbatim() {
1999 // Byte-shape parity witness on the primary shape both peer
2000 // composers depend on: the composed slug MUST be exactly
2001 // `"<verb> <Kind> <ns>/<name>"` in that order. A regression
2002 // that reordered the head slots (verb after Kind, Kind
2003 // after the qualified ref) would silently break every
2004 // operator-facing grep every downstream diagnostic body
2005 // riding through the sibling per-Kind peers uses.
2006 assert_eq!(
2007 qualified_error_ctx("fetch", "Process", "default", "api"),
2008 "fetch Process default/api",
2009 );
2010 assert_eq!(
2011 qualified_error_ctx("patch", "ConfigMap", "demo-ns", "receipt-cm"),
2012 "patch ConfigMap demo-ns/receipt-cm",
2013 );
2014 }
2015
2016 #[test]
2017 fn qualified_error_ctx_routes_ns_name_join_through_qualified_process_ref_substrate() {
2018 // Routing pin — the `<ns>/<name>` join at the composer's
2019 // tail rides through the workspace-wide
2020 // [`qualified_process_ref`] primitive rather than a bare
2021 // inline `format!("{ns}/{name}")`. A future normalization
2022 // of the qualified-ref shape (case-fold, unicode collation,
2023 // IDN) lands at ONE [`qualified_process_ref`] site and
2024 // every per-Kind diagnostic body picks it up mechanically;
2025 // this pin binds THIS composer to that substrate so a
2026 // regression that inlined the join (drifting the primitive
2027 // off the substrate axis this commit opens) surfaces HERE
2028 // rather than as silent qualified-ref drift between the
2029 // two peer per-Kind composers and every other qualified-
2030 // ref consumer across the workspace.
2031 for (verb, kind, ns, name) in [
2032 ("fetch", "Process", "default", "api"),
2033 ("get", "Process", "tatara-system", "reconciler-canary"),
2034 ("patch", "ConfigMap", "demo-ns", "receipt-cm"),
2035 ("create", "ConfigMap", "ns-1", "cm.dotted.name"),
2036 ] {
2037 let via_composer = qualified_error_ctx(verb, kind, ns, name);
2038 let via_qualified = format!("{verb} {kind} {}", super::qualified_process_ref(ns, name));
2039 assert_eq!(
2040 via_composer, via_qualified,
2041 "qualified_error_ctx must route the (ns, name) join through \
2042 qualified_process_ref for ({verb:?}, {kind:?}, {ns:?}, {name:?})",
2043 );
2044 }
2045 }
2046
2047 #[test]
2048 fn qualified_error_ctx_is_symbolic_over_the_kind_slot() {
2049 // Symbolic pin: the `kind` slot is threaded verbatim into
2050 // the produced slug — no case-fold, no allow-list narrowing
2051 // to the two shipped Kinds (`"ConfigMap"`, `"Process"`), no
2052 // per-Kind canonicalization. A regression that hardcoded
2053 // an allow-list (a `match kind { "ConfigMap" | "Process" =>
2054 // …, _ => … }` closed set that would silently reject future
2055 // per-Kind peers) surfaces HERE.
2056 //
2057 // Future third + fourth per-Kind peers (a `Secret` axis
2058 // reader, a `batch/v1::Job` axis reader for the
2059 // ConditionKind::JobAttested companion, a FluxCD
2060 // `HelmRelease` axis reader for the P2 reconciler's
2061 // emit-side) inherit the primitive at their own peer
2062 // composers and pass their own Kind literals verbatim
2063 // without the composer widening.
2064 for kind in [
2065 "ConfigMap",
2066 "Process",
2067 "Secret",
2068 "Job",
2069 "HelmRelease",
2070 "OCIRepository",
2071 "Deployment",
2072 "StatefulSet",
2073 ] {
2074 let got = qualified_error_ctx("fetch", kind, "default", "api");
2075 let expected = format!("fetch {kind} default/api");
2076 assert_eq!(
2077 got, expected,
2078 "kind-slot substitution must be verbatim for {kind:?}"
2079 );
2080 }
2081 }
2082
2083 #[test]
2084 fn qualified_error_ctx_is_symbolic_over_the_verb_slot() {
2085 // Symbolic pin: the `verb` slot is threaded verbatim — same
2086 // discipline as the sibling verb-slot pins on the two peer
2087 // per-Kind composers ([`crate::configmap::tests::
2088 // error_ctx_is_symbolic_over_the_verb_slot`] via absence,
2089 // [`crate::process_api::tests::
2090 // error_ctx_is_symbolic_over_the_verb_slot`]). Post-lift
2091 // both peers route through this composer so this pin binds
2092 // the shared symbolic contract at ONE substrate owner rather
2093 // than as two parallel pins that could drift.
2094 for verb in [
2095 "fetch", "get", "reap", "resolve", "watch", "patch", "delete", "create",
2096 ] {
2097 let got = qualified_error_ctx(verb, "Process", "default", "api");
2098 let expected = format!("{verb} Process default/api");
2099 assert_eq!(
2100 got, expected,
2101 "verb-slot substitution must be verbatim for {verb:?}"
2102 );
2103 }
2104 }
2105
2106 #[test]
2107 fn qualified_error_ctx_matches_configmap_peer_bytewise() {
2108 // Post-lift peer coherence pin: the composer's output at
2109 // `<Kind> = "ConfigMap"` MUST be byte-identical to the
2110 // [`crate::configmap::error_ctx`] peer's output at the SAME
2111 // (verb, ns, name) triple. The peer is now a one-line
2112 // delegate through this composer, so a regression that
2113 // dropped or drifted the delegation would surface HERE.
2114 for (verb, ns, name) in [
2115 ("patch", "default", "receipt-cm"),
2116 ("create", "demo-ns", "cm-01"),
2117 ("get", "ns-1", "receipt.dotted.name"),
2118 ] {
2119 let via_composer = qualified_error_ctx(verb, "ConfigMap", ns, name);
2120 let via_peer = crate::configmap::error_ctx(verb, ns, name);
2121 assert_eq!(
2122 via_composer, via_peer,
2123 "configmap::error_ctx must route through qualified_error_ctx \
2124 for ({verb:?}, {ns:?}, {name:?})"
2125 );
2126 }
2127 }
2128
2129 #[test]
2130 fn qualified_error_ctx_matches_process_api_peer_bytewise() {
2131 // Post-lift peer coherence pin: the composer's output at
2132 // `<Kind> = "Process"` MUST be byte-identical to the
2133 // [`crate::process_api::error_ctx`] peer's output at the
2134 // SAME (verb, ns, name) triple. Peer to the ConfigMap
2135 // coherence pin above — both peers now delegate through the
2136 // SAME 4-slot composer, so a regression that drifted either
2137 // delegation surfaces at exactly ONE of the two
2138 // fail-before-pass-after pins.
2139 for (verb, ns, name) in [
2140 ("fetch", "default", "api"),
2141 ("get", "demo-ns", "demo"),
2142 ("watch", "tatara-system", "reconciler-canary"),
2143 ] {
2144 let via_composer = qualified_error_ctx(verb, "Process", ns, name);
2145 let via_peer = crate::process_api::error_ctx(verb, ns, name);
2146 assert_eq!(
2147 via_composer, via_peer,
2148 "process_api::error_ctx must route through qualified_error_ctx \
2149 for ({verb:?}, {ns:?}, {name:?})"
2150 );
2151 }
2152 }
2153
2154 #[test]
2155 fn qualified_error_ctx_rides_edge_case_axis_shapes() {
2156 // Edge-case pin: the composer performs NO validation on the
2157 // four slots — an empty verb / empty Kind / empty ns / empty
2158 // name / slash-in-name pathological input rides through
2159 // unchanged. Matches the pre-lift per-Kind peers' semantics
2160 // (both were unconditional `format!(…)` chains). A
2161 // regression that added a normalization step (URL-escaping
2162 // the slot values, path-normalizing the qualified-ref tail,
2163 // trimming empty slots) at this primitive would silently
2164 // break every downstream grep operators run to bisect an
2165 // authoring bug in the pre-lift consumers' input surface.
2166 assert_eq!(qualified_error_ctx("", "", "", ""), " /");
2167 assert_eq!(
2168 qualified_error_ctx("fetch", "Process", "", ""),
2169 "fetch Process /",
2170 );
2171 assert_eq!(
2172 qualified_error_ctx("fetch", "Process", "default", ""),
2173 "fetch Process default/",
2174 );
2175 assert_eq!(
2176 qualified_error_ctx("get", "Process", "ns", "with/slash"),
2177 "get Process ns/with/slash",
2178 );
2179 }
2180}
2181
2182#[cfg(test)]
2183mod namespaced_api_coordinates_tests {
2184 //! Pin the [`NamespacedApiCoordinates`] trait's
2185 //! `owned_coordinates_required` extractor at fail-before-pass-
2186 //! after granularity across every corner of the (namespace slot,
2187 //! name slot) × (present, absent) input matrix, on BOTH CRDs the
2188 //! trait's blanket impl covers today (`EphemeralPool` +
2189 //! `EphemeralAllocation`). A regression that reordered the two
2190 //! `ok_or_else` gates, dropped the `Self::kind` prefix, or drifted
2191 //! the error-string spelling surfaces HERE rather than as silent
2192 //! operator-facing skew between the two reconcilers' top-level
2193 //! error messages.
2194 use super::NamespacedApiCoordinates;
2195 use crate::allocation::{AllocationSpec, EphemeralAllocation, Requestor};
2196 use crate::ephemeral::EphemeralSpec;
2197 use crate::intent::AplicacaoIntent;
2198 use crate::lifetime::TeardownPolicy;
2199 use crate::pool::{EphemeralPool, PoolSpec};
2200
2201 fn empty_template() -> EphemeralSpec {
2202 // Mirror `tatara-pool-reconciler::router::tests::empty_template`
2203 // — the workspace-wide minimal `EphemeralSpec` fixture the sister
2204 // reconciler tests already use for pool wiring exercised here.
2205 EphemeralSpec {
2206 aplicacao: AplicacaoIntent::chart_only("oci://x", "1"),
2207 ttl: "1h".into(),
2208 teardown: TeardownPolicy::Always,
2209 max_concurrent: 0,
2210 postconditions: vec![],
2211 preconditions: vec![],
2212 verify_timeout: None,
2213 classification: None,
2214 parent: None,
2215 exports: vec![],
2216 routing: None,
2217 }
2218 }
2219
2220 fn pool_fixture(name: &str, ns: Option<&str>) -> EphemeralPool {
2221 // Every non-template slot rides the ONE substrate composer
2222 // [`PoolSpec::with_template`]; pre-lift this fixture spelled the
2223 // full 11-slot struct-literal verbatim as one of eight cross-
2224 // crate hand-authored copies. See the primitive's doc-comment
2225 // for the full migration rationale.
2226 let spec = PoolSpec {
2227 desired_size: 1,
2228 ..PoolSpec::with_template(empty_template())
2229 };
2230 let mut p = EphemeralPool::new(name, spec);
2231 p.metadata.namespace = ns.map(str::to_string);
2232 p
2233 }
2234
2235 fn alloc_fixture(name: &str, ns: Option<&str>) -> EphemeralAllocation {
2236 // AllocationSpec rides through the ONE substrate composer
2237 // `AllocationSpec::requestor_only`; the inner Requestor rides
2238 // through the peer composer `Requestor::kind_only`. Nine
2239 // pre-lift exact-match sites past the ★★ PRIME-DIRECTIVE ≥ 2
2240 // threshold collapse onto this ONE substrate owner.
2241 let spec = AllocationSpec::requestor_only(Requestor::kind_only("github-pr"));
2242 let mut a = EphemeralAllocation::new(name, spec);
2243 a.metadata.namespace = ns.map(str::to_string);
2244 a
2245 }
2246
2247 fn nameless_pool(ns: Option<&str>) -> EphemeralPool {
2248 let mut p = pool_fixture("placeholder", ns);
2249 p.metadata.name = None;
2250 p
2251 }
2252
2253 fn nameless_alloc(ns: Option<&str>) -> EphemeralAllocation {
2254 let mut a = alloc_fixture("placeholder", ns);
2255 a.metadata.name = None;
2256 a
2257 }
2258
2259 // ── Happy path: both slots present ─────────────────────────────
2260
2261 #[test]
2262 fn owned_coordinates_required_returns_owned_strings_on_ephemeral_pool_when_both_slots_present()
2263 {
2264 let p = pool_fixture("attest-pool", Some("ephemeral-pools"));
2265 let (ns, name) = p.owned_coordinates_required().unwrap();
2266 assert_eq!(ns, "ephemeral-pools");
2267 assert_eq!(name, "attest-pool");
2268 }
2269
2270 #[test]
2271 fn owned_coordinates_required_returns_owned_strings_on_ephemeral_allocation_when_both_slots_present(
2272 ) {
2273 let a = alloc_fixture("pr-42-demo", Some("ephemeral-pools"));
2274 let (ns, name) = a.owned_coordinates_required().unwrap();
2275 assert_eq!(ns, "ephemeral-pools");
2276 assert_eq!(name, "pr-42-demo");
2277 }
2278
2279 // ── Missing namespace ─────────────────────────────────────────
2280
2281 #[test]
2282 fn owned_coordinates_required_errors_on_ephemeral_pool_missing_namespace() {
2283 let p = pool_fixture("attest-pool", None);
2284 let err = p.owned_coordinates_required().unwrap_err();
2285 assert_eq!(err.to_string(), "EphemeralPool has no metadata.namespace");
2286 }
2287
2288 #[test]
2289 fn owned_coordinates_required_errors_on_ephemeral_allocation_missing_namespace() {
2290 let a = alloc_fixture("pr-42-demo", None);
2291 let err = a.owned_coordinates_required().unwrap_err();
2292 assert_eq!(
2293 err.to_string(),
2294 "EphemeralAllocation has no metadata.namespace"
2295 );
2296 }
2297
2298 // ── Missing name ──────────────────────────────────────────────
2299
2300 #[test]
2301 fn owned_coordinates_required_errors_on_ephemeral_pool_missing_name_when_namespace_present() {
2302 let p = nameless_pool(Some("ephemeral-pools"));
2303 let err = p.owned_coordinates_required().unwrap_err();
2304 assert_eq!(err.to_string(), "EphemeralPool has no metadata.name");
2305 }
2306
2307 #[test]
2308 fn owned_coordinates_required_errors_on_ephemeral_allocation_missing_name_when_namespace_present(
2309 ) {
2310 let a = nameless_alloc(Some("ephemeral-pools"));
2311 let err = a.owned_coordinates_required().unwrap_err();
2312 assert_eq!(err.to_string(), "EphemeralAllocation has no metadata.name");
2313 }
2314
2315 // ── Missing both slots: namespace error wins (pre-lift ordering) ──
2316
2317 #[test]
2318 fn owned_coordinates_required_reports_namespace_first_when_both_slots_absent_on_ephemeral_pool()
2319 {
2320 // Pre-lift both reconcilers spelled the paired chain as the
2321 // namespace ok_or_else THEN the name ok_or_else, so the
2322 // reported error on a fixture missing both slots was always
2323 // the namespace one. Pin that ordering post-lift so a
2324 // regression that swapped the two `ok_or_else` blocks
2325 // surfaces HERE rather than at operator-facing log-line
2326 // grep drift between the two reconcilers.
2327 let p = nameless_pool(None);
2328 let err = p.owned_coordinates_required().unwrap_err();
2329 assert_eq!(err.to_string(), "EphemeralPool has no metadata.namespace");
2330 }
2331
2332 #[test]
2333 fn owned_coordinates_required_reports_namespace_first_when_both_slots_absent_on_ephemeral_allocation(
2334 ) {
2335 let a = nameless_alloc(None);
2336 let err = a.owned_coordinates_required().unwrap_err();
2337 assert_eq!(
2338 err.to_string(),
2339 "EphemeralAllocation has no metadata.namespace"
2340 );
2341 }
2342
2343 // ── Byte-identical parity with the pre-lift 5-line chain ──────
2344
2345 #[test]
2346 fn owned_coordinates_required_matches_pre_lift_pool_reconciler_chain_shape() {
2347 // Byte-identical parity pin: the primitive produces the SAME
2348 // `Result<(String, String), anyhow::Error>` shape a pre-lift
2349 // `.metadata.<slot>.clone().ok_or_else(|| anyhow!("<Kind> has
2350 // no metadata.<slot>"))?` chain produced at
2351 // `tatara-pool-reconciler::controller_pool::reconcile_inner`
2352 // pre-lift, on both the happy and the missing-slot corners.
2353 // A regression that changed the error prefix, reordered the
2354 // two gates, or returned a non-`(String, String)` tuple
2355 // surfaces HERE rather than at every consumer downstream.
2356 let cases = [
2357 (Some("prod"), Some("api")),
2358 (Some("prod"), None),
2359 (None, Some("orphan")),
2360 (None, None),
2361 ];
2362 for (ns_slot, name_slot) in cases {
2363 let mut p = pool_fixture("placeholder", ns_slot);
2364 if let Some(nm) = name_slot {
2365 p.metadata.name = Some(nm.into());
2366 } else {
2367 p.metadata.name = None;
2368 }
2369
2370 // Pre-lift 5-line paired chain (with the reconciler's
2371 // hand-authored short-form `"Pool"` prefix updated to the
2372 // canonical kube kind `"EphemeralPool"`, matching the
2373 // primitive's `Self::kind`-driven spelling — the drift
2374 // is intentional per the trait's docs).
2375 let pre_lift: anyhow::Result<(String, String)> = (|| {
2376 let ns =
2377 p.metadata.namespace.clone().ok_or_else(|| {
2378 anyhow::anyhow!("EphemeralPool has no metadata.namespace")
2379 })?;
2380 let name = p
2381 .metadata
2382 .name
2383 .clone()
2384 .ok_or_else(|| anyhow::anyhow!("EphemeralPool has no metadata.name"))?;
2385 Ok((ns, name))
2386 })();
2387
2388 let via_primitive = p.owned_coordinates_required();
2389
2390 // Compare on both the Ok tuple + the error string
2391 // spelling — anyhow::Error does not derive PartialEq so
2392 // pattern-match on the Result axis rather than a direct
2393 // `assert_eq!` on the whole Result.
2394 match (via_primitive, pre_lift) {
2395 (Ok(a), Ok(b)) => assert_eq!(a, b),
2396 (Err(a), Err(b)) => assert_eq!(a.to_string(), b.to_string()),
2397 (a, b) => panic!(
2398 "primitive vs pre-lift chain disagree on Ok/Err axis for \
2399 (ns={ns_slot:?}, name={name_slot:?}): primitive={a:?}, pre_lift={b:?}"
2400 ),
2401 }
2402 }
2403 }
2404
2405 #[test]
2406 fn owned_coordinates_required_matches_pre_lift_allocation_reconciler_chain_shape() {
2407 // Peer to the pool-side pin above — pin the same byte-
2408 // identity contract on the allocation reconciler's chain,
2409 // where the pre-lift error spelling used the short-form
2410 // `"Allocation"` prefix that the primitive now emits as the
2411 // canonical kube-kind `"EphemeralAllocation"`.
2412 let cases = [
2413 (Some("ephemeral-pools"), Some("pr-42-demo")),
2414 (Some("ephemeral-pools"), None),
2415 (None, Some("orphan")),
2416 (None, None),
2417 ];
2418 for (ns_slot, name_slot) in cases {
2419 let mut a = alloc_fixture("placeholder", ns_slot);
2420 if let Some(nm) = name_slot {
2421 a.metadata.name = Some(nm.into());
2422 } else {
2423 a.metadata.name = None;
2424 }
2425
2426 let pre_lift: anyhow::Result<(String, String)> = (|| {
2427 let ns = a.metadata.namespace.clone().ok_or_else(|| {
2428 anyhow::anyhow!("EphemeralAllocation has no metadata.namespace")
2429 })?;
2430 let name =
2431 a.metadata.name.clone().ok_or_else(|| {
2432 anyhow::anyhow!("EphemeralAllocation has no metadata.name")
2433 })?;
2434 Ok((ns, name))
2435 })();
2436
2437 let via_primitive = a.owned_coordinates_required();
2438
2439 match (via_primitive, pre_lift) {
2440 (Ok(a), Ok(b)) => assert_eq!(a, b),
2441 (Err(a), Err(b)) => assert_eq!(a.to_string(), b.to_string()),
2442 (a, b) => panic!(
2443 "primitive vs pre-lift chain disagree on Ok/Err axis for \
2444 (ns={ns_slot:?}, name={name_slot:?}): primitive={a:?}, pre_lift={b:?}"
2445 ),
2446 }
2447 }
2448 }
2449
2450 // ── Cross-CRD symmetry: kube kind drives the error prefix ─────
2451
2452 #[test]
2453 fn owned_coordinates_required_error_prefix_matches_kube_kind_on_each_crd() {
2454 // The error prefix is sourced positionally from `Self::kind`
2455 // so the two CRDs emit distinct kube-canonical spellings
2456 // without either callsite hard-coding a per-CRD literal.
2457 // Regressions that hard-coded a shared prefix (e.g. a
2458 // copy-paste that pasted the pool's error string into the
2459 // allocation callsite) surface HERE.
2460 use kube::Resource;
2461 let p = pool_fixture("p", None);
2462 let a = alloc_fixture("a", None);
2463 assert_eq!(
2464 p.owned_coordinates_required().unwrap_err().to_string(),
2465 format!("{} has no metadata.namespace", EphemeralPool::kind(&()))
2466 );
2467 assert_eq!(
2468 a.owned_coordinates_required().unwrap_err().to_string(),
2469 format!(
2470 "{} has no metadata.namespace",
2471 EphemeralAllocation::kind(&())
2472 )
2473 );
2474 // Belt-and-suspenders: the two kinds are distinct spellings,
2475 // so the error strings are distinct too.
2476 assert_ne!(
2477 p.owned_coordinates_required().unwrap_err().to_string(),
2478 a.owned_coordinates_required().unwrap_err().to_string(),
2479 );
2480 }
2481}
2482
2483#[cfg(test)]
2484mod deletion_tombstoned_tests {
2485 //! Pin the [`DeletionTombstoned`] trait's `is_being_deleted` probe
2486 //! at fail-before-pass-after granularity across every corner of
2487 //! the (tombstone present, tombstone absent) input matrix, on
2488 //! ALL THREE tatara-process CRDs the trait's blanket impl covers
2489 //! today (`Process`, `EphemeralPool`, `EphemeralAllocation`), plus
2490 //! the cross-CRD coherence with the two pre-existing inherent
2491 //! forwarders. A regression that skewed the trait's default,
2492 //! promoted a distinct-payload tombstone to a false negative, or
2493 //! diverged the trait from either inherent forwarder surfaces
2494 //! HERE rather than as silent operator-facing skew between the
2495 //! four consumer sites the primitive owns (the top-level
2496 //! dispatcher's SIGTERM preempt, the SIGTERM cascade's child-
2497 //! fan-out DELETE-skip, the pool reconciler's Drain gate, and
2498 //! the allocation reconciler's release short-circuit) on three
2499 //! sibling CRDs.
2500 use super::DeletionTombstoned;
2501 use crate::allocation::{AllocationSpec, EphemeralAllocation, Requestor};
2502 use crate::crd::{Process, ProcessSpec};
2503 use crate::ephemeral::EphemeralSpec;
2504 use crate::intent::AplicacaoIntent;
2505 use crate::lifetime::TeardownPolicy;
2506 use crate::pool::{EphemeralPool, PoolSpec};
2507 use k8s_openapi::apimachinery::pkg::apis::meta::v1::Time;
2508
2509 fn empty_template() -> EphemeralSpec {
2510 EphemeralSpec {
2511 aplicacao: AplicacaoIntent::chart_only("oci://x", "1"),
2512 ttl: "1h".into(),
2513 teardown: TeardownPolicy::Always,
2514 max_concurrent: 0,
2515 postconditions: vec![],
2516 preconditions: vec![],
2517 verify_timeout: None,
2518 classification: None,
2519 parent: None,
2520 exports: vec![],
2521 routing: None,
2522 }
2523 }
2524
2525 fn empty_pool_spec() -> PoolSpec {
2526 // Every non-template slot rides the ONE substrate composer
2527 // [`PoolSpec::with_template`]; see the primitive's doc-comment
2528 // for the full migration rationale.
2529 PoolSpec {
2530 desired_size: 1,
2531 ..PoolSpec::with_template(empty_template())
2532 }
2533 }
2534
2535 fn empty_alloc_spec() -> AllocationSpec {
2536 // AllocationSpec rides through the ONE substrate composer
2537 // `AllocationSpec::requestor_only`; the inner Requestor rides
2538 // through `Requestor::kind_only`. Nine pre-lift exact-match
2539 // fixture sites past the ★★ PRIME-DIRECTIVE ≥ 2 threshold
2540 // collapse onto this ONE substrate owner.
2541 AllocationSpec::requestor_only(Requestor::kind_only("github-pr"))
2542 }
2543
2544 fn empty_process_spec() -> ProcessSpec {
2545 // Routes through the ONE substrate composer
2546 // `ProcessSpec::gate_compute_defaults` — the minimal
2547 // `ProcessSpec` used across every substrate metadata-projection
2548 // pin. Pre-lift this was the 12-line struct-literal restated
2549 // verbatim at every fixture in this pin family.
2550 ProcessSpec::gate_compute_defaults()
2551 }
2552
2553 // ── Missing tombstone (default fixture) — trait returns false ─────
2554
2555 #[test]
2556 fn is_being_deleted_on_process_missing_tombstone_returns_false_via_trait() {
2557 let p = Process::new("api", empty_process_spec());
2558 assert!(!DeletionTombstoned::is_being_deleted(&p));
2559 }
2560
2561 #[test]
2562 fn is_being_deleted_on_ephemeral_pool_missing_tombstone_returns_false_via_trait() {
2563 let p = EphemeralPool::new("attest-pool", empty_pool_spec());
2564 assert!(!DeletionTombstoned::is_being_deleted(&p));
2565 }
2566
2567 #[test]
2568 fn is_being_deleted_on_ephemeral_allocation_missing_tombstone_returns_false_via_trait() {
2569 // The load-bearing corner: EphemeralAllocation had NO inherent
2570 // is_being_deleted pre-lift — the trait's blanket impl is
2571 // what closes the substrate gap for the allocation reconciler's
2572 // hand-authored `.metadata.deletion_timestamp.is_some()` chain.
2573 let a = EphemeralAllocation::new("pr-42-demo", empty_alloc_spec());
2574 assert!(!DeletionTombstoned::is_being_deleted(&a));
2575 }
2576
2577 // ── Present tombstone — trait returns true ────────────────────────
2578
2579 #[test]
2580 fn is_being_deleted_on_process_present_tombstone_returns_true_via_trait() {
2581 let mut p = Process::new("api", empty_process_spec());
2582 // Routes through the ONE substrate composer
2583 // `tatara_process::time::tombstone_now` — one of 12 pre-lift
2584 // exact-match sites past the ★★ PRIME-DIRECTIVE ≥ 2 threshold
2585 // for the `Some(Time(Utc::now()))` wire shape.
2586 p.metadata.deletion_timestamp = crate::time::tombstone_now();
2587 assert!(DeletionTombstoned::is_being_deleted(&p));
2588 }
2589
2590 #[test]
2591 fn is_being_deleted_on_ephemeral_pool_present_tombstone_returns_true_via_trait() {
2592 let mut p = EphemeralPool::new("attest-pool", empty_pool_spec());
2593 p.metadata.deletion_timestamp = crate::time::tombstone_now();
2594 assert!(DeletionTombstoned::is_being_deleted(&p));
2595 }
2596
2597 #[test]
2598 fn is_being_deleted_on_ephemeral_allocation_present_tombstone_returns_true_via_trait() {
2599 let mut a = EphemeralAllocation::new("pr-42-demo", empty_alloc_spec());
2600 a.metadata.deletion_timestamp = crate::time::tombstone_now();
2601 assert!(DeletionTombstoned::is_being_deleted(&a));
2602 }
2603
2604 // ── Byte-identical parity with the pre-lift `.is_some()` chain ────
2605
2606 #[test]
2607 fn is_being_deleted_matches_pre_lift_deletion_timestamp_is_some_chain_on_ephemeral_allocation()
2608 {
2609 // Byte-identical parity pin: the trait's default produces the
2610 // SAME `bool` a pre-lift `.metadata.deletion_timestamp.is_some()`
2611 // chain produced at `tatara-pool-reconciler::allocation_decide::
2612 // AllocationConvergenceCtx::observe` pre-lift, across every
2613 // corner of the (absent, present-at-now, present-at-past)
2614 // input matrix. A regression that inserted a normalization
2615 // step the pre-lift chain does NOT apply — or vice versa —
2616 // surfaces here rather than as silent drift between the
2617 // substrate owner and the pre-lift consumer.
2618 // Routes through the ONE substrate composer family
2619 // `tatara_process::time::{tombstone_now,tombstone_at}` — the
2620 // present-at-now corner rides `tombstone_now`, the present-at-
2621 // past corner composes `tombstone_at(seconds_ago(3600))` per
2622 // the composer's canonical stale-fixture shape.
2623 let mut cases: Vec<Option<Time>> = vec![None];
2624 cases.push(crate::time::tombstone_now());
2625 cases.push(crate::time::tombstone_at(crate::time::seconds_ago(3600)));
2626
2627 for ts in cases {
2628 let mut a = EphemeralAllocation::new("pr-42-demo", empty_alloc_spec());
2629 a.metadata.deletion_timestamp = ts.clone();
2630
2631 let pre_lift = a.metadata.deletion_timestamp.is_some();
2632 let via_trait = DeletionTombstoned::is_being_deleted(&a);
2633
2634 assert_eq!(
2635 pre_lift, via_trait,
2636 "trait probe must be byte-identical to pre-lift .metadata.deletion_timestamp.is_some() on tombstone={ts:?}",
2637 );
2638 }
2639 }
2640
2641 // ── Cross-CRD coherence with the two inherent forwarders ──────────
2642
2643 #[test]
2644 fn trait_probe_coheres_with_process_inherent_is_being_deleted_on_both_corners() {
2645 // Cross-primitive coherence pin: the trait's default and the
2646 // pre-existing `Process::is_being_deleted` inherent forwarder
2647 // return the SAME `bool` on the SAME `Process` value — a
2648 // future consolidation of the inherent onto the trait's default
2649 // (or vice versa) cannot land any drift between the two
2650 // surfaces because this pin binds them at every corner of the
2651 // (missing, present) input matrix.
2652 // Routes the tombstone-present corner through the ONE
2653 // substrate composer `tatara_process::time::tombstone_now`.
2654 for ts in [None, crate::time::tombstone_now()] {
2655 let mut p = Process::new("api", empty_process_spec());
2656 p.metadata.deletion_timestamp = ts.clone();
2657 assert_eq!(
2658 p.is_being_deleted(),
2659 DeletionTombstoned::is_being_deleted(&p),
2660 "Process trait probe must match inherent on tombstone={ts:?}",
2661 );
2662 }
2663 }
2664
2665 #[test]
2666 fn trait_probe_coheres_with_ephemeral_pool_inherent_is_being_deleted_on_both_corners() {
2667 // Peer coherence pin on the sister CRD.
2668 for ts in [None, crate::time::tombstone_now()] {
2669 let mut p = EphemeralPool::new("attest-pool", empty_pool_spec());
2670 p.metadata.deletion_timestamp = ts.clone();
2671 assert_eq!(
2672 p.is_being_deleted(),
2673 DeletionTombstoned::is_being_deleted(&p),
2674 "EphemeralPool trait probe must match inherent on tombstone={ts:?}",
2675 );
2676 }
2677 }
2678
2679 // ── Inherent-preferred method resolution on Process + EphemeralPool ──
2680
2681 #[test]
2682 fn dot_call_on_process_resolves_to_inherent_when_trait_in_scope() {
2683 // Rust method resolution prefers an inherent over a trait's
2684 // blanket impl, so `process.is_being_deleted()` with the trait
2685 // in scope still routes through the inherent — and both
2686 // return the same `bool` (verified in
2687 // `trait_probe_coheres_with_process_inherent_is_being_deleted_on_both_corners`).
2688 // This pin guards against a future refactor that removes the
2689 // inherent but leaves consumers assuming inherent-preferred
2690 // resolution — the observable output is identical either way,
2691 // so the pin locks the invariant that BOTH paths agree.
2692 let mut p = Process::new("api", empty_process_spec());
2693 // Routes through `tatara_process::time::tombstone_now`.
2694 p.metadata.deletion_timestamp = crate::time::tombstone_now();
2695 assert!(p.is_being_deleted());
2696 }
2697
2698 #[test]
2699 fn dot_call_on_ephemeral_allocation_resolves_to_trait_blanket_impl() {
2700 // The load-bearing corner: `alloc.is_being_deleted()` with
2701 // the trait in scope routes to the trait's blanket impl
2702 // (there is no inherent on `EphemeralAllocation`) and
2703 // produces the expected `bool`. This is what the swept
2704 // allocation-reconciler callsite depends on post-lift.
2705 let mut a = EphemeralAllocation::new("pr-42-demo", empty_alloc_spec());
2706 assert!(!a.is_being_deleted());
2707 a.metadata.deletion_timestamp = crate::time::tombstone_now();
2708 assert!(a.is_being_deleted());
2709 }
2710}
2711
2712#[cfg(test)]
2713mod annotated_tests {
2714 //! Pin the [`Annotated`] trait's `annotation` lookup at fail-
2715 //! before-pass-after granularity across every corner of the
2716 //! (annotations map: absent / present-empty / present-with-key /
2717 //! present-without-key) × (value form: normal / empty-string)
2718 //! input matrix, on the three tatara-process CRDs the trait's
2719 //! blanket impl covers today (`Process`, `EphemeralPool`,
2720 //! `EphemeralAllocation`) PLUS a K8s built-in (`ConfigMap`) — the
2721 //! load-bearing fourth surface that `tatara-export-worker::main`
2722 //! consumes post-lift where no tatara-owned inherent forwarder
2723 //! exists. Also pin cross-primitive coherence with the pre-existing
2724 //! `Process::annotation` inherent so a future consolidation onto
2725 //! the trait's default cannot silently skew the three consumers
2726 //! already routed through the inherent
2727 //! (`signals::ingest`,
2728 //! `phase_machine::released_from_annotation`,
2729 //! `controller_pool::process_belongs_to_pool`).
2730 use super::Annotated;
2731 use crate::allocation::{AllocationSpec, EphemeralAllocation, Requestor};
2732 use crate::crd::{Process, ProcessSpec};
2733 use crate::ephemeral::EphemeralSpec;
2734 use crate::intent::AplicacaoIntent;
2735 use crate::lifetime::TeardownPolicy;
2736 use crate::pool::{EphemeralPool, PoolSpec};
2737 use k8s_openapi::api::core::v1::ConfigMap;
2738 use std::collections::BTreeMap;
2739
2740 fn empty_template() -> EphemeralSpec {
2741 EphemeralSpec {
2742 aplicacao: AplicacaoIntent::chart_only("oci://x", "1"),
2743 ttl: "1h".into(),
2744 teardown: TeardownPolicy::Always,
2745 max_concurrent: 0,
2746 postconditions: vec![],
2747 preconditions: vec![],
2748 verify_timeout: None,
2749 classification: None,
2750 parent: None,
2751 exports: vec![],
2752 routing: None,
2753 }
2754 }
2755
2756 fn empty_pool_spec() -> PoolSpec {
2757 // Every non-template slot rides the ONE substrate composer
2758 // [`PoolSpec::with_template`]; see the primitive's doc-comment
2759 // for the full migration rationale.
2760 PoolSpec {
2761 desired_size: 1,
2762 ..PoolSpec::with_template(empty_template())
2763 }
2764 }
2765
2766 fn empty_alloc_spec() -> AllocationSpec {
2767 // AllocationSpec rides through `AllocationSpec::requestor_only`;
2768 // the inner Requestor rides through `Requestor::kind_only` —
2769 // sibling to the peer `empty_alloc_spec` fixture in the
2770 // DeletionTombstoned pin module above.
2771 AllocationSpec::requestor_only(Requestor::kind_only("github-pr"))
2772 }
2773
2774 fn empty_process_spec() -> ProcessSpec {
2775 // Routes through the ONE substrate composer
2776 // `ProcessSpec::gate_compute_defaults` — sibling to the
2777 // `empty_process_spec` fixture in the DeletionTombstoned pin
2778 // module above and to `empty_spec` in `crd.rs::tests`.
2779 ProcessSpec::gate_compute_defaults()
2780 }
2781
2782 fn one_annotation(key: &str, value: &str) -> BTreeMap<String, String> {
2783 let mut m = BTreeMap::new();
2784 m.insert(key.into(), value.into());
2785 m
2786 }
2787
2788 // ── Missing annotations map — trait returns None on every key ─────
2789
2790 #[test]
2791 fn annotation_on_process_missing_annotations_returns_none_via_trait() {
2792 let mut p = Process::new("api", empty_process_spec());
2793 p.metadata.annotations = None;
2794 assert_eq!(Annotated::annotation(&p, "tatara.pleme.io/signal"), None);
2795 assert_eq!(Annotated::annotation(&p, ""), None);
2796 }
2797
2798 #[test]
2799 fn annotation_on_ephemeral_pool_missing_annotations_returns_none_via_trait() {
2800 let mut p = EphemeralPool::new("attest-pool", empty_pool_spec());
2801 p.metadata.annotations = None;
2802 assert_eq!(Annotated::annotation(&p, "tatara.pleme.io/pool"), None);
2803 }
2804
2805 #[test]
2806 fn annotation_on_ephemeral_allocation_missing_annotations_returns_none_via_trait() {
2807 // The peer load-bearing corner: EphemeralAllocation has NO
2808 // inherent `annotation()` pre-lift — the trait's blanket impl
2809 // is what closes the substrate gap here, exactly as the
2810 // sibling `DeletionTombstoned` trait already did on the
2811 // tombstone axis for the SAME third CRD.
2812 let mut a = EphemeralAllocation::new("pr-42-demo", empty_alloc_spec());
2813 a.metadata.annotations = None;
2814 assert_eq!(
2815 Annotated::annotation(&a, "tatara.pleme.io/requestor-kind"),
2816 None,
2817 );
2818 }
2819
2820 #[test]
2821 fn annotation_on_config_map_missing_annotations_returns_none_via_trait() {
2822 // The load-bearing corner the export-worker's post-lift call
2823 // depends on: `ConfigMap` is a K8s built-in with no tatara-
2824 // owned inherent forwarder, and the receipts-owner filter
2825 // needs to route through the trait's blanket impl at
2826 // `cm.annotation(KEY)`.
2827 let cm = ConfigMap::default();
2828 // `Default::default()` produces an object with an empty
2829 // ObjectMeta whose `annotations` slot is `None` — the exact
2830 // missing-annotations corner the trait must collapse to
2831 // `None` at every key lookup, matching what the pre-lift
2832 // `cm.metadata.annotations.as_ref().and_then(...)` chain
2833 // produced.
2834 assert_eq!(Annotated::annotation(&cm, "tatara.pleme.io/process"), None,);
2835 }
2836
2837 // ── Missing key inside populated map — trait returns None ─────────
2838
2839 #[test]
2840 fn annotation_on_process_missing_key_returns_none_via_trait() {
2841 let mut p = Process::new("api", empty_process_spec());
2842 p.metadata.annotations = Some(one_annotation("other/key", "irrelevant"));
2843 assert_eq!(Annotated::annotation(&p, "tatara.pleme.io/signal"), None);
2844 assert_eq!(Annotated::annotation(&p, ""), None);
2845 }
2846
2847 #[test]
2848 fn annotation_on_config_map_missing_key_returns_none_via_trait() {
2849 let mut cm = ConfigMap::default();
2850 cm.metadata.annotations = Some(one_annotation("unrelated", "yes"));
2851 assert_eq!(Annotated::annotation(&cm, "tatara.pleme.io/process"), None,);
2852 }
2853
2854 // ── Present key — trait returns borrowed slice ────────────────────
2855
2856 #[test]
2857 fn annotation_on_process_present_key_returns_borrowed_slice_via_trait() {
2858 let mut p = Process::new("api", empty_process_spec());
2859 p.metadata.annotations = Some(one_annotation("tatara.pleme.io/signal", "SIGHUP"));
2860 assert_eq!(
2861 Annotated::annotation(&p, "tatara.pleme.io/signal"),
2862 Some("SIGHUP"),
2863 );
2864 }
2865
2866 #[test]
2867 fn annotation_on_ephemeral_pool_present_key_returns_borrowed_slice_via_trait() {
2868 let mut p = EphemeralPool::new("attest-pool", empty_pool_spec());
2869 p.metadata.annotations = Some(one_annotation("tatara.pleme.io/pool", "demo-pool"));
2870 assert_eq!(
2871 Annotated::annotation(&p, "tatara.pleme.io/pool"),
2872 Some("demo-pool"),
2873 );
2874 }
2875
2876 #[test]
2877 fn annotation_on_ephemeral_allocation_present_key_returns_borrowed_slice_via_trait() {
2878 let mut a = EphemeralAllocation::new("pr-42-demo", empty_alloc_spec());
2879 a.metadata.annotations = Some(one_annotation(
2880 "tatara.pleme.io/requestor-kind",
2881 "github-pr",
2882 ));
2883 assert_eq!(
2884 Annotated::annotation(&a, "tatara.pleme.io/requestor-kind"),
2885 Some("github-pr"),
2886 );
2887 }
2888
2889 #[test]
2890 fn annotation_on_config_map_present_key_returns_borrowed_slice_via_trait() {
2891 // The exact receipts-owner filter shape from
2892 // `tatara-export-worker::main`: a ConfigMap carrying the
2893 // `tatara.pleme.io/process` annotation set to the qualified
2894 // process reference `<ns>/<name>`. Pin that the trait produces
2895 // the exact borrowed slice the equality comparison against the
2896 // caller's `want.as_str()` sentinel consumes.
2897 let mut cm = ConfigMap::default();
2898 cm.metadata.annotations = Some(one_annotation(
2899 "tatara.pleme.io/process",
2900 "demo-ns/demo-app",
2901 ));
2902 assert_eq!(
2903 Annotated::annotation(&cm, "tatara.pleme.io/process"),
2904 Some("demo-ns/demo-app"),
2905 );
2906 }
2907
2908 // ── Empty-value contract: `Some("")` — the pre-lift chain never
2909 // swallowed empty values into `None`, so the trait must not
2910 // either. Pinned separately from the missing-slot corners.
2911
2912 #[test]
2913 fn annotation_present_key_with_empty_value_returns_some_empty_slice_via_trait() {
2914 let mut p = Process::new("api", empty_process_spec());
2915 p.metadata.annotations = Some(one_annotation("tatara.pleme.io/signal", ""));
2916 assert_eq!(
2917 Annotated::annotation(&p, "tatara.pleme.io/signal"),
2918 Some("")
2919 );
2920 }
2921
2922 // ── Byte-identical parity with the pre-lift 3-line chain ──────────
2923
2924 #[test]
2925 fn annotation_matches_pre_lift_annotations_lookup_chain_on_config_map() {
2926 // The four-corner input matrix the pre-lift
2927 // `cm.metadata.annotations.as_ref().and_then(|m| m.get(KEY))
2928 // .map(String::as_str)` chain traversed in
2929 // `tatara-export-worker::main` pre-lift. A regression that
2930 // inserted a normalization step the pre-lift chain does NOT
2931 // apply — or vice versa — surfaces here rather than as silent
2932 // drift between the substrate owner and the pre-lift consumer.
2933 const KEY: &str = "tatara.pleme.io/process";
2934 let cases: Vec<(Option<BTreeMap<String, String>>, Option<&str>)> = vec![
2935 (None, None),
2936 (Some(BTreeMap::new()), None),
2937 (Some(one_annotation("unrelated", "yes")), None),
2938 (
2939 Some(one_annotation(KEY, "demo-ns/demo-app")),
2940 Some("demo-ns/demo-app"),
2941 ),
2942 (Some(one_annotation(KEY, "")), Some("")),
2943 ];
2944 for (anns, expected) in cases {
2945 let mut cm = ConfigMap::default();
2946 cm.metadata.annotations = anns.clone();
2947
2948 let pre_lift: Option<&str> = cm
2949 .metadata
2950 .annotations
2951 .as_ref()
2952 .and_then(|m| m.get(KEY))
2953 .map(String::as_str);
2954 let via_trait = Annotated::annotation(&cm, KEY);
2955
2956 assert_eq!(
2957 pre_lift, expected,
2958 "pre-lift chain must return {expected:?} for annotations={anns:?}",
2959 );
2960 assert_eq!(
2961 via_trait, pre_lift,
2962 "trait probe must be byte-identical to pre-lift chain for annotations={anns:?}",
2963 );
2964 }
2965 }
2966
2967 // ── Cross-primitive coherence with Process's inherent forwarder ───
2968
2969 #[test]
2970 fn trait_probe_coheres_with_process_inherent_annotation_on_every_corner() {
2971 // Cross-primitive coherence pin: the trait's default and the
2972 // pre-existing `Process::annotation` inherent forwarder return
2973 // the SAME `Option<&str>` on the SAME `Process` value — a
2974 // future consolidation of the inherent onto the trait's
2975 // default cannot land any drift because this pin binds them
2976 // at every corner of the (absent, present-missing-key,
2977 // present-with-key, present-with-empty-value) input matrix.
2978 const KEY: &str = "tatara.pleme.io/signal";
2979 let cases: Vec<Option<BTreeMap<String, String>>> = vec![
2980 None,
2981 Some(BTreeMap::new()),
2982 Some(one_annotation("other/key", "irrelevant")),
2983 Some(one_annotation(KEY, "SIGHUP")),
2984 Some(one_annotation(KEY, "")),
2985 ];
2986 for anns in cases {
2987 let mut p = Process::new("api", empty_process_spec());
2988 p.metadata.annotations = anns.clone();
2989 let via_inherent = p.annotation(KEY);
2990 let via_trait = Annotated::annotation(&p, KEY);
2991 assert_eq!(
2992 via_inherent, via_trait,
2993 "Process inherent + Annotated trait must agree on annotations={anns:?}",
2994 );
2995 }
2996 }
2997
2998 // ── Inherent-preferred method resolution on Process ───────────────
2999
3000 #[test]
3001 fn dot_call_on_process_resolves_to_inherent_when_trait_in_scope() {
3002 // Rust method resolution prefers an inherent over a trait's
3003 // blanket impl, so `process.annotation(key)` with the trait in
3004 // scope still routes through the inherent — and both return
3005 // the same `Option<&str>` (verified in
3006 // `trait_probe_coheres_with_process_inherent_annotation_on_every_corner`).
3007 // This pin guards against a future refactor that removes the
3008 // inherent but leaves consumers assuming inherent-preferred
3009 // resolution — the observable output is identical either way,
3010 // so the pin locks the invariant that BOTH paths agree.
3011 let mut p = Process::new("api", empty_process_spec());
3012 p.metadata.annotations = Some(one_annotation("tatara.pleme.io/signal", "SIGHUP"));
3013 assert_eq!(p.annotation("tatara.pleme.io/signal"), Some("SIGHUP"));
3014 }
3015
3016 #[test]
3017 fn dot_call_on_ephemeral_allocation_resolves_to_trait_blanket_impl() {
3018 // The peer load-bearing corner: `alloc.annotation(key)` with
3019 // the trait in scope routes to the trait's blanket impl —
3020 // there is no inherent on `EphemeralAllocation` — and produces
3021 // the expected `Option<&str>`. The same discipline the sibling
3022 // `DeletionTombstoned` trait already established on the
3023 // tombstone axis for the SAME third CRD.
3024 let mut a = EphemeralAllocation::new("pr-42-demo", empty_alloc_spec());
3025 assert_eq!(a.annotation("tatara.pleme.io/requestor-kind"), None);
3026 a.metadata.annotations = Some(one_annotation(
3027 "tatara.pleme.io/requestor-kind",
3028 "github-pr",
3029 ));
3030 assert_eq!(
3031 a.annotation("tatara.pleme.io/requestor-kind"),
3032 Some("github-pr"),
3033 );
3034 }
3035
3036 #[test]
3037 fn dot_call_on_config_map_resolves_to_trait_blanket_impl() {
3038 // The load-bearing corner the export-worker's post-lift call
3039 // exercises: `cm.annotation(KEY)` with the trait in scope
3040 // routes to the blanket impl (ConfigMap is a K8s built-in
3041 // with no tatara-owned inherent) and produces the same
3042 // `Option<&str>` the pre-lift 3-line chain did.
3043 let mut cm = ConfigMap::default();
3044 assert_eq!(cm.annotation("tatara.pleme.io/process"), None);
3045 cm.metadata.annotations = Some(one_annotation(
3046 "tatara.pleme.io/process",
3047 "demo-ns/demo-app",
3048 ));
3049 assert_eq!(
3050 cm.annotation("tatara.pleme.io/process"),
3051 Some("demo-ns/demo-app"),
3052 );
3053 }
3054}
3055
3056#[cfg(test)]
3057mod annotations_pins {
3058 //! Pin the three newly-lifted allocator-bind annotation keys
3059 //! ([`crate::annotations::REQUESTOR`],
3060 //! [`crate::annotations::ALLOCATION`],
3061 //! [`crate::annotations::REQUESTOR_KIND`]) at their canonical
3062 //! wire-form byte-values, and pin the coherence between each
3063 //! constant and the pre-lift string literal the sibling writer +
3064 //! reader test-sites still spell verbatim.
3065 //!
3066 //! Pre-lift each of the three keys was a bare `"tatara.pleme.io/…"`
3067 //! string literal at both the writer (`tatara-pool-reconciler::
3068 //! controller_allocation::reconcile_inner`'s Bind arm) AND the
3069 //! reader-side test sites in `annotated_tests` above — six
3070 //! restatements of `REQUESTOR_KIND` alone past the ★★
3071 //! PRIME-DIRECTIVE ≥ 2 duplication threshold. Post-lift the writer
3072 //! keys on the substrate constant; these pins bind the constant's
3073 //! byte-shape so a future edit that drifted the constant (a
3074 //! typo'd suffix, an accidental `tatara.pleme.io/v2/…` migration
3075 //! landing at only the writer, an incoming rename that swapped
3076 //! two of the three keys) surfaces here rather than as silent
3077 //! operator-facing skew between the writer and the tatara-process
3078 //! reader tests that still spell the literal.
3079 //!
3080 //! Theory anchor: THEORY.md §II.1 invariant 5 (composition
3081 //! preserves proofs — the wire-form value each downstream reader
3082 //! depends on now has a compile-time pin at the substrate).
3083 use crate::annotations;
3084
3085 #[test]
3086 fn requestor_matches_pre_lift_wire_string() {
3087 assert_eq!(annotations::REQUESTOR, "tatara.pleme.io/requestor");
3088 }
3089
3090 #[test]
3091 fn allocation_matches_pre_lift_wire_string() {
3092 assert_eq!(annotations::ALLOCATION, "tatara.pleme.io/allocation");
3093 }
3094
3095 #[test]
3096 fn requestor_kind_matches_pre_lift_wire_string() {
3097 assert_eq!(
3098 annotations::REQUESTOR_KIND,
3099 "tatara.pleme.io/requestor-kind",
3100 );
3101 }
3102
3103 #[test]
3104 fn allocator_bind_axis_keys_are_distinct() {
3105 // A copy-paste that duplicated one key's value across two
3106 // slots (an oversight during the initial lift or a future
3107 // rename that merged two keys by mistake) collapses BOTH
3108 // downstream readers onto the same wire string and silently
3109 // loses one of the three axes. Pin the closed set is
3110 // partition-distinct.
3111 assert_ne!(annotations::REQUESTOR, annotations::ALLOCATION);
3112 assert_ne!(annotations::REQUESTOR, annotations::REQUESTOR_KIND);
3113 assert_ne!(annotations::ALLOCATION, annotations::REQUESTOR_KIND);
3114 }
3115
3116 #[test]
3117 fn allocator_bind_axis_keys_share_tatara_namespace() {
3118 // Every substrate-owned annotation key inhabits the
3119 // `tatara.pleme.io/` reverse-DNS namespace; a future rename
3120 // that dropped the prefix (a bare `"requestor"` key, a
3121 // typo'd `pleme.io/requestor`) would collide with an
3122 // arbitrary third-party operator's annotations on the same
3123 // Process and silently corrupt cross-consumer reads.
3124 for key in [
3125 annotations::REQUESTOR,
3126 annotations::ALLOCATION,
3127 annotations::REQUESTOR_KIND,
3128 ] {
3129 assert!(
3130 key.starts_with("tatara.pleme.io/"),
3131 "annotation key {key:?} must inhabit tatara.pleme.io/ namespace",
3132 );
3133 }
3134 }
3135
3136 // ── Pool-membership axis pins ────────────────────────────────────
3137 //
3138 // Pins the two newly-lifted pool-membership annotation keys
3139 // ([`crate::annotations::POOL`], [`crate::annotations::POOL_SLOT`])
3140 // at their canonical wire-form byte-values. Pre-lift each key was
3141 // a file-scope `const ANNOTATION_POOL / ANNOTATION_SLOT` in
3142 // `tatara-pool-reconciler::controller_pool` PLUS bare
3143 // `"tatara.pleme.io/pool"` string literals at four reader-side
3144 // test sites in this crate (in the sibling `annotated_tests` above
3145 // and in `crd.rs`'s
3146 // `annotation_composes_borrow_equality_tail_matching_pre_lift_pool`
3147 // + `annotation_returns_none_when_metadata_annotations_is_none`).
3148 // Post-lift the writer routes through the substrate constant; a
3149 // future edit that drifted the constant (a typo'd suffix, an
3150 // accidental `tatara.pleme.io/v2/pool` migration landing at only
3151 // the writer, an incoming rename that swapped POOL and POOL_SLOT)
3152 // surfaces here rather than as silent operator-facing skew
3153 // between the pool controller's writer and its own membership-
3154 // gate reader.
3155
3156 #[test]
3157 fn pool_matches_pre_lift_wire_string() {
3158 assert_eq!(annotations::POOL, "tatara.pleme.io/pool");
3159 }
3160
3161 #[test]
3162 fn pool_slot_matches_pre_lift_wire_string() {
3163 assert_eq!(annotations::POOL_SLOT, "tatara.pleme.io/pool-slot");
3164 }
3165
3166 #[test]
3167 fn pool_membership_axis_keys_are_distinct() {
3168 // A copy-paste that duplicated one key's value across both
3169 // slots (an oversight during the initial lift, or a future
3170 // rename that merged the two keys by mistake) collapses
3171 // BOTH downstream readers onto the same wire string and
3172 // silently loses the slot-index axis — the pool controller
3173 // would still find its own members via POOL but every per-
3174 // slot dispatch consumer would read the pool name where the
3175 // slot index used to sit. Pin the closed set is partition-
3176 // distinct.
3177 assert_ne!(annotations::POOL, annotations::POOL_SLOT);
3178 }
3179
3180 #[test]
3181 fn pool_membership_axis_keys_share_tatara_namespace() {
3182 // Same reverse-DNS namespace invariant the allocator-bind
3183 // axis-family enforces above — a rename that dropped the
3184 // prefix on either POOL or POOL_SLOT would collide with an
3185 // arbitrary third-party operator's annotations on the same
3186 // Process and silently corrupt every pool-membership read.
3187 for key in [annotations::POOL, annotations::POOL_SLOT] {
3188 assert!(
3189 key.starts_with("tatara.pleme.io/"),
3190 "annotation key {key:?} must inhabit tatara.pleme.io/ namespace",
3191 );
3192 }
3193 }
3194
3195 #[test]
3196 fn pool_membership_axis_keys_partition_distinct_from_allocator_bind_axis() {
3197 // Cross-family distinctness pin — the pool-membership axis
3198 // (POOL, POOL_SLOT) and the allocator-bind axis (REQUESTOR,
3199 // ALLOCATION, REQUESTOR_KIND) travel on the SAME member
3200 // Process at the SAME time (the pool controller writes POOL
3201 // + POOL_SLOT at creation; the allocator later merges
3202 // REQUESTOR / ALLOCATION / REQUESTOR_KIND onto the same
3203 // Process at Bind). A copy-paste that collapsed any axis
3204 // pair (e.g. POOL and REQUESTOR onto the same wire string)
3205 // would let one write silently overwrite the other. Pin
3206 // that every substrate-owned annotation key is unique
3207 // across the two axis-families.
3208 let pool_axis = [annotations::POOL, annotations::POOL_SLOT];
3209 let bind_axis = [
3210 annotations::REQUESTOR,
3211 annotations::ALLOCATION,
3212 annotations::REQUESTOR_KIND,
3213 ];
3214 for p in pool_axis {
3215 for b in bind_axis {
3216 assert_ne!(
3217 p, b,
3218 "pool-membership key {p:?} collides with allocator-bind key {b:?}",
3219 );
3220 }
3221 }
3222 }
3223
3224 // ── Release-return axis pins ─────────────────────────────────────
3225 //
3226 // Pins the newly-lifted release-return annotation key
3227 // ([`crate::annotations::RETURN_TRIGGER`]) at its canonical
3228 // wire-form byte-value. Pre-lift the key was a bare
3229 // `"tatara.pleme.io/return-trigger"` string literal at the
3230 // pool-reconciler's Release-arm stamp (`tatara-pool-reconciler::
3231 // controller_allocation::reconcile_inner`) — the ONE remaining
3232 // hand-authored annotation-key literal in the workspace's active
3233 // controllers after every sibling single-annotation key on the
3234 // same axis-family (`SIGNAL`, `RELEASED_FROM`, `POOL`, `POOL_SLOT`,
3235 // `REQUESTOR`, `ALLOCATION`, `REQUESTOR_KIND`) already routed
3236 // through a `pub const` in the substrate. Post-lift the writer
3237 // routes through the substrate constant; these pins bind the
3238 // constant's byte-shape + tatara-namespace membership + partition-
3239 // distinctness against every peer key so a future edit that
3240 // drifted the constant (a typo'd suffix, an incoming rename that
3241 // collapsed RETURN_TRIGGER onto a peer key, a `tatara.pleme.io/v2/
3242 // return-trigger` migration landing at only the writer) surfaces
3243 // HERE rather than as silent operator-facing skew between the
3244 // allocator's Release-arm stamp and every downstream reader (an
3245 // audit-trail scraper, a future pool-reconciler return-path arm,
3246 // an admission-webhook gate on the return trigger).
3247
3248 #[test]
3249 fn return_trigger_matches_pre_lift_wire_string() {
3250 assert_eq!(
3251 annotations::RETURN_TRIGGER,
3252 "tatara.pleme.io/return-trigger",
3253 );
3254 }
3255
3256 #[test]
3257 fn return_trigger_inhabits_tatara_namespace() {
3258 // Same reverse-DNS namespace invariant every sibling key on
3259 // the axis-family enforces above — a rename that dropped the
3260 // prefix on RETURN_TRIGGER would collide with an arbitrary
3261 // third-party operator's annotations on the same Process and
3262 // silently corrupt the allocator's Release-arm write.
3263 assert!(
3264 annotations::RETURN_TRIGGER.starts_with("tatara.pleme.io/"),
3265 "annotation key {:?} must inhabit tatara.pleme.io/ namespace",
3266 annotations::RETURN_TRIGGER,
3267 );
3268 }
3269
3270 #[test]
3271 fn return_trigger_is_distinct_from_every_peer_annotation_key() {
3272 // Cross-family distinctness pin — RETURN_TRIGGER travels on
3273 // the SAME member Process (at Release) that already carries
3274 // the pool-membership axis (POOL, POOL_SLOT, stamped at
3275 // creation), the allocator-bind axis (REQUESTOR, ALLOCATION,
3276 // REQUESTOR_KIND, stamped at Bind), and the
3277 // "single-annotation trigger for the next reconcile pass"
3278 // axis-family (SIGNAL, RELEASED_FROM). A copy-paste that
3279 // collapsed RETURN_TRIGGER onto any peer would let one write
3280 // silently overwrite the other. Pin the key against every
3281 // sibling substrate-owned annotation key on the workspace.
3282 for peer in [
3283 annotations::SIGNAL,
3284 annotations::RELEASED_FROM,
3285 annotations::POOL,
3286 annotations::POOL_SLOT,
3287 annotations::REQUESTOR,
3288 annotations::ALLOCATION,
3289 annotations::REQUESTOR_KIND,
3290 annotations::MANAGED_BY,
3291 annotations::PROCESS,
3292 annotations::PID,
3293 annotations::CONTENT_HASH,
3294 annotations::ATTESTATION_ROOT,
3295 annotations::GENERATION,
3296 annotations::ROLE,
3297 annotations::EXPORT_INDEX,
3298 annotations::APP,
3299 annotations::ROUTING_FORM,
3300 ] {
3301 assert_ne!(
3302 annotations::RETURN_TRIGGER,
3303 peer,
3304 "RETURN_TRIGGER key {:?} collides with peer annotation key {peer:?}",
3305 annotations::RETURN_TRIGGER,
3306 );
3307 }
3308 }
3309
3310 #[test]
3311 fn return_trigger_composes_at_annotation_body_key_slot() {
3312 // End-to-end composability pin: the substrate composer
3313 // [`crate::patch::annotation_body`] takes a `key: &str`; the
3314 // pre-lift Release-arm callsite fed a bare `"tatara.pleme.io/
3315 // return-trigger"` literal and the post-lift callsite feeds
3316 // `annotations::RETURN_TRIGGER`. Both shapes produce a JSON
3317 // merge-body whose `metadata.annotations.<KEY>` slot equals
3318 // `"true"`; pin that the substrate constant threads through
3319 // the composer verbatim so a regression that reshaped the
3320 // `annotation_body` key-slot (a case-fold pass, an unexpected
3321 // trim, a prefix-normalization step) surfaces HERE rather
3322 // than at every downstream consumer.
3323 let body = crate::patch::annotation_body(annotations::RETURN_TRIGGER, "true");
3324 assert_eq!(
3325 body["metadata"]["annotations"][annotations::RETURN_TRIGGER],
3326 "true",
3327 "annotation_body must stamp RETURN_TRIGGER verbatim at the metadata.annotations slot",
3328 );
3329 assert_eq!(
3330 body["metadata"]["annotations"]["tatara.pleme.io/return-trigger"],
3331 "true",
3332 "byte-shape parity — the pre-lift hand-authored key spelling routes through the constant to the same nested slot",
3333 );
3334 }
3335
3336 // ── Encapsulation-diagnostic axis pins ──────────────────────────
3337 //
3338 // Pins the two newly-lifted encapsulation-diagnostic annotation
3339 // keys ([`crate::annotations::ENCAPSULATION_MODE`],
3340 // [`crate::annotations::ADOPTED_RELEASE`]) at their canonical
3341 // wire-form byte-values. Pre-lift the two keys were bare
3342 // `"tatara.pleme.io/encapsulation-mode"` /
3343 // `"tatara.pleme.io/adopted-release"` string literals inline at
3344 // `tatara-reconciler::render::mark_resources_as_adopting`'s two
3345 // `anns_obj.insert_str(...)` writer sites — the ONE remaining
3346 // hand-authored annotation-key pair in the workspace's active
3347 // reconciler after every sibling annotation key already routed
3348 // through a `pub const` in the substrate. Post-lift the writer
3349 // routes through the substrate constants; these pins bind each
3350 // constant's byte-shape + tatara-namespace membership + partition-
3351 // distinctness against every peer key so a future edit that
3352 // drifted the constants (a typo'd suffix, an incoming rename that
3353 // collapsed the pair onto a peer key, a
3354 // `tatara.pleme.io/v2/encapsulation-mode` migration landing at
3355 // only the writer, a collapse into a compound
3356 // `tatara.pleme.io/encapsulation` payload key) surfaces HERE
3357 // rather than as silent operator-facing skew between the render
3358 // emitter and every downstream reader (an operator dashboard
3359 // filtering adopted resources, an admission-webhook gate on the
3360 // encapsulation mode, an audit-trail scraper following the
3361 // `<ns>/<release>` adoption lineage).
3362
3363 #[test]
3364 fn encapsulation_mode_matches_pre_lift_wire_string() {
3365 assert_eq!(
3366 annotations::ENCAPSULATION_MODE,
3367 "tatara.pleme.io/encapsulation-mode",
3368 );
3369 }
3370
3371 #[test]
3372 fn adopted_release_matches_pre_lift_wire_string() {
3373 assert_eq!(
3374 annotations::ADOPTED_RELEASE,
3375 "tatara.pleme.io/adopted-release",
3376 );
3377 }
3378
3379 #[test]
3380 fn encapsulation_diagnostic_axis_keys_are_distinct() {
3381 // A copy-paste that duplicated one key's value across the pair
3382 // (an oversight during the initial lift, or a future rename
3383 // that merged the two keys by mistake) collapses BOTH
3384 // downstream readers onto the same wire string and silently
3385 // loses one of the two axes — an operator dashboard would
3386 // still see the mode via ENCAPSULATION_MODE but every
3387 // `<ns>/<release>` back-reference consumer would read the
3388 // mode literal where the qualified reference used to sit.
3389 // Pin the closed set is partition-distinct.
3390 assert_ne!(
3391 annotations::ENCAPSULATION_MODE,
3392 annotations::ADOPTED_RELEASE
3393 );
3394 }
3395
3396 #[test]
3397 fn encapsulation_diagnostic_axis_keys_share_tatara_namespace() {
3398 // Same reverse-DNS namespace invariant every sibling
3399 // annotation key on the workspace enforces above — a rename
3400 // that dropped the prefix on either constant would collide
3401 // with an arbitrary third-party operator's annotations on the
3402 // same emitted resource (a HelmRelease, a Kustomization, an
3403 // adopted secondary) and silently corrupt every
3404 // encapsulation-diagnostic read.
3405 for key in [
3406 annotations::ENCAPSULATION_MODE,
3407 annotations::ADOPTED_RELEASE,
3408 ] {
3409 assert!(
3410 key.starts_with("tatara.pleme.io/"),
3411 "annotation key {key:?} must inhabit tatara.pleme.io/ namespace",
3412 );
3413 }
3414 }
3415
3416 #[test]
3417 fn encapsulation_diagnostic_axis_keys_partition_distinct_from_every_peer() {
3418 // Cross-family distinctness pin — the encapsulation-diagnostic
3419 // axis (ENCAPSULATION_MODE, ADOPTED_RELEASE) is stamped on
3420 // every RESOURCE the reconciler emits for an Adopt-mode
3421 // Process, whereas every peer annotation key on the workspace
3422 // is stamped on the PROCESS itself (SIGNAL, RELEASED_FROM,
3423 // POOL, POOL_SLOT, REQUESTOR, ALLOCATION, REQUESTOR_KIND,
3424 // RETURN_TRIGGER) OR on emitted routing edges (APP,
3425 // ROUTING_FORM) OR on export-worker Jobs (ROLE, EXPORT_INDEX).
3426 // A copy-paste that collapsed the pair onto any peer would
3427 // let one write silently overwrite the other. Pin that both
3428 // constants are unique across every substrate-owned peer.
3429 let diag_axis = [
3430 annotations::ENCAPSULATION_MODE,
3431 annotations::ADOPTED_RELEASE,
3432 ];
3433 let peers = [
3434 annotations::MANAGED_BY,
3435 annotations::PROCESS,
3436 annotations::PID,
3437 annotations::CONTENT_HASH,
3438 annotations::ATTESTATION_ROOT,
3439 annotations::GENERATION,
3440 annotations::SIGNAL,
3441 annotations::RELEASED_FROM,
3442 annotations::ROLE,
3443 annotations::EXPORT_INDEX,
3444 annotations::APP,
3445 annotations::ROUTING_FORM,
3446 annotations::REQUESTOR,
3447 annotations::ALLOCATION,
3448 annotations::REQUESTOR_KIND,
3449 annotations::POOL,
3450 annotations::POOL_SLOT,
3451 annotations::RETURN_TRIGGER,
3452 ];
3453 for d in diag_axis {
3454 for p in peers {
3455 assert_ne!(
3456 d, p,
3457 "encapsulation-diagnostic key {d:?} collides with peer annotation key {p:?}",
3458 );
3459 }
3460 }
3461 }
3462
3463 // ── Receipt-CM-label axis pins ──────────────────────────────────
3464 //
3465 // Pins the newly-lifted receipt-CM label KEY
3466 // ([`crate::annotations::RECEIPT`]) at its canonical wire-form
3467 // byte-value. Pre-lift the key was a bare
3468 // `"tatara.pleme.io/receipt"` string literal inline at
3469 // `tatara-closed-loop-probe::write_receipt_cm`'s
3470 // `BTreeMap::from([...])` label seed AND at the byte-shape parity
3471 // witness in `tatara_process::configmap::with_data`'s
3472 // `with_data_preserves_passed_labels_map_verbatim_when_some` test —
3473 // TWO restatements past the ★★ PRIME-DIRECTIVE ≥ 2 duplication
3474 // threshold. Post-lift both callsites route through the substrate
3475 // constant; these pins bind the constant's byte-shape +
3476 // tatara-namespace membership + partition-distinctness against
3477 // every peer key so a future edit that drifted the constant (a
3478 // typo'd suffix, an incoming rename that collapsed RECEIPT onto a
3479 // peer key, a `tatara.pleme.io/v2/receipt` migration landing at
3480 // only the writer, a collapse into a compound
3481 // `tatara.pleme.io/receipt-envelope` payload key) surfaces HERE
3482 // rather than as silent operator-facing kubectl-selector skew
3483 // between the probe's receipt-CM writer and every downstream
3484 // consumer (a receipt-collection walker, an admission-webhook gate
3485 // on receipt version, an audit-trail scraper enumerating every
3486 // `tatara-receipt/v1` payload on a cluster).
3487
3488 #[test]
3489 fn receipt_matches_pre_lift_wire_string() {
3490 assert_eq!(annotations::RECEIPT, "tatara.pleme.io/receipt");
3491 }
3492
3493 #[test]
3494 fn receipt_inhabits_tatara_namespace() {
3495 // Same reverse-DNS namespace invariant every sibling key on
3496 // the workspace enforces above — a rename that dropped the
3497 // prefix on RECEIPT would collide with an arbitrary
3498 // third-party operator's labels on the same ConfigMap and
3499 // silently corrupt every downstream kubectl-selector that
3500 // enumerates receipt CMs of a given version on a cluster.
3501 assert!(
3502 annotations::RECEIPT.starts_with(annotations::GROUP_PREFIX),
3503 "annotation key {:?} must inhabit {:?} namespace",
3504 annotations::RECEIPT,
3505 annotations::GROUP_PREFIX,
3506 );
3507 }
3508
3509 #[test]
3510 fn receipt_is_distinct_from_every_peer_annotation_key() {
3511 // Cross-family distinctness pin — RECEIPT rides on the
3512 // receipt ConfigMap the probe binary writes (a peer resource
3513 // of the Process itself), whereas every peer annotation key on
3514 // the workspace is stamped on the PROCESS (SIGNAL,
3515 // RELEASED_FROM, POOL, POOL_SLOT, REQUESTOR, ALLOCATION,
3516 // REQUESTOR_KIND, RETURN_TRIGGER) OR on emitted routing edges
3517 // (APP, ROUTING_FORM) OR on export-worker Jobs (ROLE,
3518 // EXPORT_INDEX) OR on encapsulation-diagnostic side-resources
3519 // (ENCAPSULATION_MODE, ADOPTED_RELEASE). A copy-paste that
3520 // collapsed RECEIPT onto any peer would let one write silently
3521 // overwrite the other. Pin the key against every sibling
3522 // substrate-owned annotation key on the workspace.
3523 for peer in [
3524 annotations::MANAGED_BY,
3525 annotations::PROCESS,
3526 annotations::PID,
3527 annotations::CONTENT_HASH,
3528 annotations::ATTESTATION_ROOT,
3529 annotations::GENERATION,
3530 annotations::SIGNAL,
3531 annotations::RELEASED_FROM,
3532 annotations::ROLE,
3533 annotations::EXPORT_INDEX,
3534 annotations::APP,
3535 annotations::ROUTING_FORM,
3536 annotations::REQUESTOR,
3537 annotations::ALLOCATION,
3538 annotations::REQUESTOR_KIND,
3539 annotations::POOL,
3540 annotations::POOL_SLOT,
3541 annotations::RETURN_TRIGGER,
3542 annotations::ENCAPSULATION_MODE,
3543 annotations::ADOPTED_RELEASE,
3544 ] {
3545 assert_ne!(
3546 annotations::RECEIPT,
3547 peer,
3548 "RECEIPT key {:?} collides with peer annotation key {peer:?}",
3549 annotations::RECEIPT,
3550 );
3551 }
3552 }
3553
3554 #[test]
3555 fn receipt_value_slot_routes_through_receipt_version_const() {
3556 // Value-side coherence pin — the SUBSTRATE convention is that
3557 // every ConfigMap labeled `RECEIPT` carries a payload whose
3558 // envelope `version` slot equals [`crate::receipt::RECEIPT_VERSION`],
3559 // so a kubectl `-l tatara.pleme.io/receipt=tatara-receipt/v1`
3560 // selector matches exactly the CMs whose payloads pass the
3561 // `RECEIPT_VERSION` gate. Pin that the label VALUE the probe
3562 // stamps IS `RECEIPT_VERSION` (routed through the const, not a
3563 // parallel `"tatara-receipt/v1"` literal): a future bump to
3564 // `tatara-receipt/v2` at the version const propagates
3565 // MECHANICALLY to the label value without touching any writer.
3566 assert_eq!(
3567 crate::receipt::RECEIPT_VERSION,
3568 "tatara-receipt/v1",
3569 "RECEIPT_VERSION wire-form pin — a bump surfaces here",
3570 );
3571 }
3572
3573 #[test]
3574 fn encapsulation_mode_value_slot_routes_through_encapsulation_mode_closed_set() {
3575 // Value-side pin — the render emitter's `ENCAPSULATION_MODE`
3576 // slot writes the wire-form spelling of an
3577 // [`crate::encapsulates::EncapsulationMode`] variant. Pre-lift
3578 // the site hand-authored the fixed `"Adopt"` literal;
3579 // post-lift the writer feeds
3580 // `EncapsulationMode::Adopt.as_str()` — the SAME closed-set
3581 // owner every peer consumer (the reconciler's status-condition
3582 // reason string, the operator dashboard's per-mode filter, the
3583 // admission webhook's Adopt/Manage/Observe dispatch) routes
3584 // through. A regression that drifted the closed-set wire form
3585 // (a lowercase `"adopt"`, a `"Adoption"` typo) surfaces at
3586 // `EncapsulationMode::as_str`'s own pin AND here at the value
3587 // slot the render emitter stamps.
3588 assert_eq!(
3589 crate::encapsulates::EncapsulationMode::Adopt.as_str(),
3590 "Adopt",
3591 "the render emitter's ENCAPSULATION_MODE value slot must byte-match the closed-set wire form",
3592 );
3593 }
3594}
3595
3596// ── Lisp → ProcessSpec compile bridge ──────────────────────────────────
3597//
3598// `(defpoint NAME :k v …)` compiles to a `NamedDefinition<ProcessSpec>`.
3599// The derive on ProcessSpec handles every field via the serde Deserialize
3600// fallthrough — no hand-rolled keyword parsing needed.
3601
3602/// A named ProcessSpec as produced by `compile_source`.
3603pub type Definition = tatara_lisp::NamedDefinition<crate::crd::ProcessSpec>;
3604
3605/// Compile a Lisp source string into a list of named ProcessSpecs.
3606/// Each top-level `(defpoint NAME …)` form becomes one `Definition`.
3607pub fn compile_source(src: &str) -> tatara_lisp::Result<Vec<Definition>> {
3608 tatara_lisp::compile_named::<crate::crd::ProcessSpec>(src)
3609}
3610
3611/// Register every domain owned by this crate with the global Lisp
3612/// dispatcher. Call once per binary, typically near the top of `main`.
3613/// After this call, `tatara_lisp::domain::lookup("defpoint")` and
3614/// `lookup("defephemeral")` both resolve to the right typed compiler.
3615///
3616/// Idempotent — registering the same type twice is a no-op.
3617pub fn register_all() {
3618 tatara_lisp::domain::register::<crate::crd::ProcessSpec>();
3619 tatara_lisp::domain::register::<crate::ephemeral::EphemeralSpec>();
3620}
3621
3622#[cfg(test)]
3623mod compile_tests {
3624 use super::compile_source;
3625 use crate::classification::{ConvergencePointType, SubstrateType};
3626 use crate::compliance::VerificationPhase;
3627 use crate::spec::MustReachPhase;
3628
3629 /// The full derive-powered pipeline — no hand-rolled parsing anywhere.
3630 /// Every field travels: Lisp → Sexp → serde_json → typed ProcessSpec.
3631 #[test]
3632 fn full_processspec_round_trip_via_derive() {
3633 let src = r#"
3634 (defpoint observability-stack
3635 :identity (:parent "seph.1")
3636 :classification (:point-type Gate
3637 :substrate Observability
3638 :horizon (:kind Bounded)
3639 :calm Monotone
3640 :data-classification Internal)
3641 :intent (:nix (:flake-ref "github:pleme-io/k8s"
3642 :attribute "observability"
3643 :attic-cache "main"))
3644 :boundary (:postconditions
3645 ((:kind KustomizationHealthy
3646 :params (:name "observability-stack"
3647 :namespace "flux-system"))
3648 (:kind PromQL
3649 :params (:query "up == 1")))
3650 :timeout "15m")
3651 :compliance (:baseline "fedramp-moderate"
3652 :bindings ((:framework "nist-800-53"
3653 :control-id "SC-7"
3654 :phase AtBoundary)))
3655 :depends-on ((:name "secret-injection" :must-reach Attested))
3656 :signals (:sigterm-grace-seconds 480
3657 :sighup-strategy Reconverge))
3658 "#;
3659 let defs = compile_source(src).expect("compile");
3660 assert_eq!(defs.len(), 1);
3661 let d = &defs[0];
3662 assert_eq!(d.name, "observability-stack");
3663
3664 // identity
3665 assert_eq!(d.spec.identity.parent.as_deref(), Some("seph.1"));
3666
3667 // classification (enums deserialized via symbol → string)
3668 assert_eq!(d.spec.classification.point_type, ConvergencePointType::Gate);
3669 assert_eq!(
3670 d.spec.classification.substrate,
3671 SubstrateType::Observability
3672 );
3673
3674 // intent (tagged-union with one of four options)
3675 let nix = d.spec.intent.nix.as_ref().expect("nix intent");
3676 assert_eq!(nix.flake_ref, "github:pleme-io/k8s");
3677 assert_eq!(nix.attribute, "observability");
3678 assert_eq!(nix.attic_cache.as_deref(), Some("main"));
3679
3680 // boundary (Vec<nested struct with params object>)
3681 assert_eq!(d.spec.boundary.postconditions.len(), 2);
3682 assert_eq!(d.spec.boundary.timeout.as_deref(), Some("15m"));
3683
3684 // compliance (Vec<binding with enum phase>)
3685 assert_eq!(
3686 d.spec.compliance.baseline.as_deref(),
3687 Some("fedramp-moderate")
3688 );
3689 assert_eq!(d.spec.compliance.bindings.len(), 1);
3690 assert_eq!(
3691 d.spec.compliance.bindings[0].phase,
3692 VerificationPhase::AtBoundary
3693 );
3694
3695 // depends_on (Vec<struct with enum>)
3696 assert_eq!(d.spec.depends_on.len(), 1);
3697 assert_eq!(d.spec.depends_on[0].must_reach, MustReachPhase::Attested);
3698
3699 // signals (numeric + enum defaults)
3700 assert_eq!(d.spec.signals.sigterm_grace_seconds, 480);
3701 }
3702
3703 #[test]
3704 fn missing_required_field_errors() {
3705 // `:classification` has no #[serde(default)] — omit it and compile must fail.
3706 let src = r#"(defpoint x :intent (:nix (:flake-ref "f" :attribute "a")))"#;
3707 assert!(compile_source(src).is_err());
3708 }
3709
3710 #[test]
3711 fn serde_default_fields_are_optional() {
3712 // Omit every #[serde(default)] field — compile must succeed because
3713 // the derive honors serde defaults.
3714 let src = r#"
3715 (defpoint x
3716 :classification (:point-type Transform :substrate Compute)
3717 :intent (:flux (:git-repository "g" :path ".")))
3718 "#;
3719 let defs = compile_source(src).expect("compile");
3720 assert_eq!(defs.len(), 1);
3721 let d = &defs[0];
3722 assert!(d.spec.depends_on.is_empty());
3723 assert!(d.spec.boundary.postconditions.is_empty());
3724 assert!(d.spec.compliance.bindings.is_empty());
3725 assert!(!d.spec.suspended);
3726 // Lifetime defaults to Permanent (no variant set, resolver still works).
3727 assert!(d.spec.lifetime.is_default());
3728 assert!(!d.spec.lifetime.is_ephemeral());
3729 }
3730
3731 /// Registering all process-owned domains is idempotent and resolves
3732 /// both `defpoint` (ProcessSpec) and `defephemeral` (EphemeralSpec).
3733 #[test]
3734 fn register_all_resolves_defpoint_and_defephemeral() {
3735 use tatara_lisp::domain::lookup;
3736 super::register_all();
3737 super::register_all(); // idempotent
3738 assert!(lookup("defpoint").is_some(), "defpoint must resolve");
3739 assert!(
3740 lookup("defephemeral").is_some(),
3741 "defephemeral must resolve"
3742 );
3743 }
3744
3745 /// End-to-end: a `(defpoint …)` form may carry the full ephemeral
3746 /// shape directly — `:intent (:aplicacao …)` + `:lifetime (:ephemeral …)`.
3747 /// This is what the `(defephemeral …)` sugar lowers to via `From`.
3748 #[test]
3749 fn defpoint_with_aplicacao_intent_and_ephemeral_lifetime() {
3750 use crate::intent::IntentVariant;
3751 use crate::lifetime::{LifetimeVariant, TeardownPolicy};
3752 let src = r#"
3753 (defpoint closed-loop-attest
3754 :classification (:point-type Gate :substrate Compute)
3755 :intent (:aplicacao
3756 (:chart-ref "oci://ghcr.io/pleme-io/charts/lareira-demo-app"
3757 :version "0.5.5"
3758 :profile "all-in-one"
3759 :values-overlay (:cluster (:name "ephemeral-test-01"))
3760 :target-namespace "demo-test"))
3761 :boundary (:postconditions
3762 ((:kind HelmReleaseReleased
3763 :params (:name "demo-app-consolidated"
3764 :namespace "demo-test"))
3765 (:kind ClosedLoopAuth
3766 :params (:issuer (:service "demo-app-issuer" :port 8080)
3767 :consumer (:service "demo-app-gateway" :port 8000)
3768 :probeImage "ghcr.io/pleme-io/closed-loop-probe:0.1.0"))))
3769 :lifetime (:ephemeral (:ttl "1h"
3770 :teardown-policy OnAttested
3771 :max-concurrent 1)))
3772 "#;
3773 let defs = compile_source(src).expect("compile");
3774 assert_eq!(defs.len(), 1);
3775 let d = &defs[0];
3776
3777 // Aplicacao intent landed.
3778 match d.spec.intent.variant().unwrap() {
3779 IntentVariant::Aplicacao(a) => {
3780 assert_eq!(a.profile, "all-in-one");
3781 assert_eq!(a.version, "0.5.5");
3782 assert_eq!(a.target_namespace.as_deref(), Some("demo-test"));
3783 assert_eq!(a.values_overlay["cluster"]["name"], "ephemeral-test-01");
3784 }
3785 other => panic!("expected Aplicacao, got {other:?}"),
3786 }
3787
3788 // Ephemeral lifetime landed with the right teardown policy.
3789 match d.spec.lifetime.variant().unwrap() {
3790 LifetimeVariant::Ephemeral(e) => {
3791 assert_eq!(e.ttl, "1h");
3792 assert_eq!(e.teardown_policy, TeardownPolicy::OnAttested);
3793 assert_eq!(e.max_concurrent, 1);
3794 }
3795 other => panic!("expected ephemeral, got {other:?}"),
3796 }
3797
3798 // Two typed postconditions including ClosedLoopAuth.
3799 assert_eq!(d.spec.boundary.postconditions.len(), 2);
3800 assert_eq!(
3801 d.spec.boundary.postconditions[1].kind,
3802 crate::boundary::ConditionKind::ClosedLoopAuth
3803 );
3804 }
3805}
3806
3807#[cfg(test)]
3808mod placed_in_namespace_tests {
3809 //! Pin the [`PlacedInNamespace`] trait's `in_namespace` builder at
3810 //! fail-before-pass-after granularity across every corner of the
3811 //! (CRD ∈ {`Process`, `EphemeralPool`, `EphemeralAllocation`,
3812 //! `ConfigMap`}) × (input form ∈ {`&str`, `String`, `&String`})
3813 //! matrix — the three tatara-owned CRDs the trait's blanket impl
3814 //! covers today PLUS one K8s built-in (`ConfigMap`) whose sibling
3815 //! [`Annotated`] blanket already covers the same category on the
3816 //! annotation-read axis. Also pin (a) the overwrite corner where
3817 //! `.in_namespace(a).in_namespace(b)` binds `b`, so a future
3818 //! consumer that chains two stamps in one composition never sees
3819 //! stale semantics, and (b) the byte-identical parity corner with
3820 //! the pre-lift 3-line body of the per-CRD `EphemeralPool::new_in`
3821 //! and `EphemeralAllocation::new_in` composers post-forwarding —
3822 //! `<CRD>::new_in(name, ns, spec)` must yield a value structurally
3823 //! identical to `<CRD>::new(name, spec).in_namespace(ns)` on every
3824 //! metadata slot the derive stamps.
3825 use super::PlacedInNamespace;
3826 use crate::allocation::{AllocationSpec, EphemeralAllocation, Requestor};
3827 use crate::crd::{Process, ProcessSpec};
3828 use crate::pool::{EphemeralPool, PoolSpec};
3829 use k8s_openapi::api::core::v1::ConfigMap;
3830 use kube::api::ObjectMeta;
3831
3832 fn empty_process_spec() -> ProcessSpec {
3833 ProcessSpec::gate_compute_defaults()
3834 }
3835
3836 fn empty_pool_spec() -> PoolSpec {
3837 PoolSpec {
3838 desired_size: 1,
3839 ..PoolSpec::with_template(crate::ephemeral::EphemeralSpec {
3840 aplicacao: crate::intent::AplicacaoIntent::chart_only("oci://x", "1"),
3841 ttl: "1h".into(),
3842 teardown: crate::lifetime::TeardownPolicy::Always,
3843 max_concurrent: 0,
3844 postconditions: vec![],
3845 preconditions: vec![],
3846 verify_timeout: None,
3847 classification: None,
3848 parent: None,
3849 exports: vec![],
3850 routing: None,
3851 })
3852 }
3853 }
3854
3855 fn empty_alloc_spec() -> AllocationSpec {
3856 AllocationSpec::requestor_only(Requestor::kind_only("github-pr"))
3857 }
3858
3859 #[test]
3860 fn in_namespace_on_process_stamps_borrowed_str() {
3861 let p = Process::new("api", empty_process_spec()).in_namespace("prod");
3862 assert_eq!(p.metadata.namespace.as_deref(), Some("prod"));
3863 }
3864
3865 #[test]
3866 fn in_namespace_on_process_stamps_owned_string() {
3867 let ns: String = "prod".into();
3868 let p = Process::new("api", empty_process_spec()).in_namespace(ns);
3869 assert_eq!(p.metadata.namespace.as_deref(), Some("prod"));
3870 }
3871
3872 #[test]
3873 fn in_namespace_on_process_stamps_string_ref() {
3874 let ns: String = "prod".into();
3875 let p = Process::new("api", empty_process_spec()).in_namespace(&ns);
3876 assert_eq!(p.metadata.namespace.as_deref(), Some("prod"));
3877 }
3878
3879 #[test]
3880 fn in_namespace_on_ephemeral_pool_stamps_borrowed_str() {
3881 let p = EphemeralPool::new("pool-1", empty_pool_spec()).in_namespace("pools");
3882 assert_eq!(p.metadata.namespace.as_deref(), Some("pools"));
3883 }
3884
3885 #[test]
3886 fn in_namespace_on_ephemeral_allocation_stamps_borrowed_str() {
3887 let a = EphemeralAllocation::new("alloc-1", empty_alloc_spec()).in_namespace("pools");
3888 assert_eq!(a.metadata.namespace.as_deref(), Some("pools"));
3889 }
3890
3891 #[test]
3892 fn in_namespace_on_configmap_via_blanket_stamps_ns() {
3893 let cm = ConfigMap {
3894 metadata: ObjectMeta {
3895 name: Some("cm-1".into()),
3896 ..Default::default()
3897 },
3898 ..Default::default()
3899 };
3900 let cm = cm.in_namespace("demo");
3901 assert_eq!(cm.metadata.namespace.as_deref(), Some("demo"));
3902 }
3903
3904 #[test]
3905 fn in_namespace_second_call_overwrites_first() {
3906 let p = Process::new("api", empty_process_spec())
3907 .in_namespace("staging")
3908 .in_namespace("prod");
3909 assert_eq!(p.metadata.namespace.as_deref(), Some("prod"));
3910 }
3911
3912 #[test]
3913 fn in_namespace_preserves_name_and_spec_untouched() {
3914 // Byte-identical parity with the pre-lift two-line pattern:
3915 // only `metadata.namespace` moves; `metadata.name` + `spec`
3916 // stay at the values the derive-supplied `::new` stamped.
3917 // Serialize both `spec` sides through serde_json so we can
3918 // pin equality without requiring `PartialEq` on `ProcessSpec`.
3919 let p = Process::new("api", empty_process_spec()).in_namespace("prod");
3920 assert_eq!(p.metadata.name.as_deref(), Some("api"));
3921 assert_eq!(p.metadata.namespace.as_deref(), Some("prod"));
3922 let expected = serde_json::to_value(empty_process_spec()).unwrap();
3923 let actual = serde_json::to_value(&p.spec).unwrap();
3924 assert_eq!(actual, expected);
3925 }
3926
3927 #[test]
3928 fn pool_new_in_forwarder_matches_trait_form() {
3929 // Cross-composer coherence witness — the per-CRD
3930 // `EphemeralPool::new_in` forwarder must produce a value
3931 // structurally identical to what `Process::new(...).in_namespace(...)`
3932 // does on the same axis. Serialize both sides through
3933 // serde_json so any drift between the forwarding form and a
3934 // direct trait-call materializes at this pin.
3935 let via_new_in = EphemeralPool::new_in("pool-x", "pools", empty_pool_spec());
3936 let via_trait = EphemeralPool::new("pool-x", empty_pool_spec()).in_namespace("pools");
3937 assert_eq!(
3938 serde_json::to_value(&via_new_in).unwrap(),
3939 serde_json::to_value(&via_trait).unwrap(),
3940 );
3941 }
3942
3943 #[test]
3944 fn allocation_new_in_forwarder_matches_trait_form() {
3945 let via_new_in = EphemeralAllocation::new_in("alloc-x", "pools", empty_alloc_spec());
3946 let via_trait =
3947 EphemeralAllocation::new("alloc-x", empty_alloc_spec()).in_namespace("pools");
3948 assert_eq!(
3949 serde_json::to_value(&via_new_in).unwrap(),
3950 serde_json::to_value(&via_trait).unwrap(),
3951 );
3952 }
3953}
3954
3955#[cfg(test)]
3956mod annotations_family_tests {
3957 //! Family-invariant pins for the substrate-owned annotation-key
3958 //! family that the [`crate::annotations`] module owns.
3959 //!
3960 //! Mirror of the sibling [`crate::finalizers::tests`] family-
3961 //! invariant block on the peer-family axis: the [`crate::finalizers`]
3962 //! module already carries the same closed-family + shared-prefix
3963 //! + pairwise-uniqueness discipline over its three finalizer keys;
3964 //! this block extends the same solve-once discipline to the 21-key
3965 //! annotation family.
3966 //!
3967 //! Each pin binds ONE invariant at fail-before-pass-after
3968 //! granularity so a future addition to the annotation family that
3969 //! violated the invariant (a new `pub const` that missed the
3970 //! [`crate::annotations::ALL`] slice, a prefix drift that dropped
3971 //! the shared [`crate::annotations::GROUP_PREFIX`] on ONE arm, a
3972 //! copy-paste that duplicated one arm's wire form at another)
3973 //! surfaces HERE rather than at some downstream sweep binary or
3974 //! silent K8s-API-server-side skew whichever consumer hit the
3975 //! broken invariant first.
3976 use crate::{annotations, finalizers};
3977
3978 #[test]
3979 fn group_prefix_matches_tatara_reverse_dns() {
3980 // Byte-shape pin — the shared prefix is the same
3981 // reverse-DNS namespace every tatara-owned wire-form key
3982 // (annotation, finalizer, CRD group) rides through.
3983 assert_eq!(annotations::GROUP_PREFIX, "tatara.pleme.io/");
3984 }
3985
3986 #[test]
3987 fn group_prefix_matches_finalizers_group_prefix() {
3988 // Cross-peer-family coherence pin — the annotation family +
3989 // the finalizer family MUST share the same reverse-DNS
3990 // namespace prefix at the substrate level. A future rename
3991 // that shifted ONE module's prefix (a group-segment migration
3992 // that landed at the annotation family but forgot the
3993 // finalizer family, or vice-versa) would silently unbind the
3994 // two peer families and let one CRD's finalizers escape the
3995 // reverse-DNS convention every annotation key on the same CRD
3996 // still carried. Pin the two consts equal at the ONE
3997 // substrate-level coherence witness.
3998 assert_eq!(annotations::GROUP_PREFIX, finalizers::GROUP_PREFIX);
3999 }
4000
4001 #[test]
4002 fn all_matches_declared_length() {
4003 // A regression that added a 22nd `pub const` above the ALL
4004 // slice without appending it to ALL (or shrank the family
4005 // without pruning the slice) would surface here. The
4006 // 21-arm listing pins the declaration order every downstream
4007 // audit sweep iterates through.
4008 assert_eq!(annotations::ALL.len(), 21);
4009 }
4010
4011 #[test]
4012 fn all_share_group_prefix() {
4013 // Every arm of the family MUST start with the shared
4014 // [`crate::annotations::GROUP_PREFIX`] reverse-DNS namespace
4015 // — matching the `#[kube(group = "tatara.pleme.io", …)]`
4016 // slot on every CRD struct. A future rename that drifted ONE
4017 // arm's prefix (a `tatara.io/` copy-paste that silently
4018 // escaped the K8s-side convention) would silently corrupt
4019 // every downstream annotation read on that key; the pin
4020 // surfaces the drift here rather than at operator-visible
4021 // annotation-read skew.
4022 for key in annotations::ALL {
4023 assert!(
4024 key.starts_with(annotations::GROUP_PREFIX),
4025 "annotation key {key:?} must start with {:?}",
4026 annotations::GROUP_PREFIX,
4027 );
4028 }
4029 }
4030
4031 #[test]
4032 fn all_are_pairwise_unique() {
4033 // No two arms of the family may share the same wire form —
4034 // a copy-paste regression that duplicated one arm's wire
4035 // form at another arm (e.g. a `POOL_SLOT` const that got
4036 // copy-pasted to the `RETURN_TRIGGER` const's value) would
4037 // silently double-book the K8s metadata slot the two keys
4038 // share, letting one write overwrite the other at whichever
4039 // downstream stamp site fired second.
4040 let mut seen: Vec<&str> = Vec::new();
4041 for key in annotations::ALL {
4042 assert!(
4043 !seen.contains(key),
4044 "duplicate annotation key in ALL: {key:?}",
4045 );
4046 seen.push(key);
4047 }
4048 assert_eq!(seen.len(), annotations::ALL.len());
4049 }
4050
4051 #[test]
4052 fn all_contains_every_declared_const() {
4053 // Coherence pin — a regression that added a new `pub const`
4054 // above the ALL slice but forgot to append it here surfaces
4055 // by name at this pin. Every currently-declared const in
4056 // [`crate::annotations`] MUST appear at least once in the
4057 // [`crate::annotations::ALL`] slice; if a future editor
4058 // adds a 22nd const above but omits it below, this pin +
4059 // [`all_matches_declared_length`] together catch both the
4060 // slice-length drift and the omitted-const case.
4061 for key in [
4062 annotations::MANAGED_BY,
4063 annotations::PROCESS,
4064 annotations::PID,
4065 annotations::CONTENT_HASH,
4066 annotations::ATTESTATION_ROOT,
4067 annotations::GENERATION,
4068 annotations::SIGNAL,
4069 annotations::RELEASED_FROM,
4070 annotations::ROLE,
4071 annotations::EXPORT_INDEX,
4072 annotations::APP,
4073 annotations::ROUTING_FORM,
4074 annotations::REQUESTOR,
4075 annotations::ALLOCATION,
4076 annotations::REQUESTOR_KIND,
4077 annotations::POOL,
4078 annotations::POOL_SLOT,
4079 annotations::RETURN_TRIGGER,
4080 annotations::ENCAPSULATION_MODE,
4081 annotations::ADOPTED_RELEASE,
4082 annotations::RECEIPT,
4083 ] {
4084 assert!(
4085 annotations::ALL.contains(&key),
4086 "annotation key {key:?} missing from ALL slice",
4087 );
4088 }
4089 }
4090
4091 #[test]
4092 fn all_disjoint_from_finalizer_family() {
4093 // Cross-peer-family disjointness pin — the annotation +
4094 // finalizer families share the reverse-DNS namespace
4095 // [`crate::annotations::GROUP_PREFIX`] but MUST NOT share
4096 // any specific wire-form key. A copy-paste that landed a
4097 // finalizer key (`tatara.pleme.io/<owner>-finalizer`) in
4098 // the annotation family, or an annotation key on the
4099 // finalizer family, would let a metadata-list writer
4100 // silently double-book the K8s garbage-collection slot on
4101 // the SAME resource the annotation reader consumes.
4102 for ann in annotations::ALL {
4103 for fin in finalizers::ALL {
4104 assert_ne!(
4105 ann, fin,
4106 "annotation key {ann:?} collides with finalizer key {fin:?}",
4107 );
4108 }
4109 }
4110 }
4111}