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