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