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