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