Skip to main content

tatara_process/
process_api.rs

1//! Substrate primitive for the `Api::namespaced::<Process>` binding
2//! every workspace consumer of the tatara `Process` CRD reaches for
3//! when it needs a namespace-scoped typed handle from a bare
4//! [`Client`] + `&str` namespace pair (no per-crate reconciler
5//! context in scope).
6//!
7//! Owns the 1-link chain
8//!
9//! ```text
10//! let api: Api<Process> = Api::namespaced(<client>, <ns>);
11//! ```
12//!
13//! that every below-controller-layer + boundary-layer Process-handle
14//! consumer hand-authored pre-lift at each namespace-scoped bind site.
15//!
16//! Sibling to the ns-scoped K8s-typed-handle family already lifted at:
17//! - [`crate::configmap::namespaced`] — the K8s built-in ConfigMap
18//!   ns-scoped handle binder, opened for the same
19//!   `tatara-export-worker` + `tatara-closed-loop-probe` consumers
20//!   that could not thread through a shared reconciler context.
21//! - `tatara_reconciler::context::Context::process_api` — the
22//!   reconciler's per-request Process-typed handle binder (kept as a
23//!   forwarder that delegates through THIS substrate primitive
24//!   post-lift, so a future normalization at the substrate owner
25//!   reaches BOTH the reconciler-side handler sprawl AND every
26//!   below-controller boundary/export-worker consumer through ONE
27//!   owner).
28//! - `tatara_pool_reconciler::context::PoolContext::{pool_api,
29//!   allocation_api,pools_all_api,allocations_all_api}` — the
30//!   pool-reconciler's tatara-CRD-typed handle binders.
31//! - `tatara_github_watcher::handler::HandlerState::allocation_api`
32//!   — the github-watcher's per-request allocation-typed handle
33//!   binder.
34//!
35//! All sibling lifts closed the `Api::namespaced(<client>.clone(),
36//! <ns>)` shape at either a controller-owned context struct (per-CRD
37//! binder) or a workspace-wide substrate module (per-K8s-built-in
38//! binder). This primitive closes the SAME shape at the tatara
39//! `Process` CRD for the THREE consumer sites that neither own a
40//! reconciler context nor thread through a shared per-request
41//! state:
42//! - `tatara_reconciler::boundary::evaluate_process_phase` — the
43//!   `ConditionKind::ProcessPhase` boundary evaluator. Called with
44//!   a bare `Client` moved in from `check_conditions` (no `Context`
45//!   in scope; the evaluator sits below the reconciler layer so it
46//!   can be reused by the `tatara-check` binary).
47//! - `tatara_reconciler::boundary::check_depends_on` — the
48//!   `spec.dependsOn` evaluator. Iterates every dep with a
49//!   `client.clone()` per row; also called from the boundary layer
50//!   without a `Context`.
51//! - `tatara_export_worker::main::read_artifact` — the export
52//!   worker's `ProcessSnapshotSource` reader. `tatara-export-worker`
53//!   is a below-controller-layer binary that DOES NOT depend on
54//!   `tatara-reconciler` (would introduce a cycle) so it cannot
55//!   reach the reconciler's `Context::process_api`.
56//!
57//! Pre-lift the 1-link `let api: Api<Process> = Api::namespaced(
58//! <client>, <ns>)` chain recurred at THESE THREE hand-authored
59//! consumer sites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication
60//! threshold. Post-lift each consumer reads
61//! `tatara_process::process_api::namespaced(client, ns)` and the
62//! ns-scoped Process handle binding lives at ONE substrate owner.
63//!
64//! ### Naming
65//!
66//! The module is named [`process_api`] — the tatara-process crate
67//! already owns a top-level `crd` module carrying the `Process`
68//! type itself, so a bare `process` submodule would collide with
69//! the crate's own name and read as an accidental self-reference
70//! (`tatara_process::process::namespaced`). `process_api` names the
71//! axis it closes ("build a typed `Api` for the tatara `Process`
72//! CRD") explicitly, mirrors the reconciler's own `process_api`
73//! method on `Context`, and reads unambiguously at every callsite.
74//!
75//! Fixing the concrete `K = Process` at the primitive lands three
76//! guarantees the pre-lift 3-site sprawl could not offer:
77//! - the two `use tatara_process::crd::Process;` /
78//!   `use tatara_process::prelude::*;` imports at the callsite
79//!   crates are the ONE typed edge to the Process CRD; any future
80//!   rename or module-path shift lands at ONE substrate primitive
81//!   rather than at every consumer;
82//! - a regression that swapped `Api::namespaced` for `Api::all` at
83//!   ONE callsite is now structurally impossible — the scope choice
84//!   is owned by the primitive's name (peer `Api::all` cluster-wide
85//!   Process consumers route through
86//!   `tatara_reconciler::context::Context::processes_all_api` on
87//!   the reconciler side; a future workspace-wide cluster-scoped
88//!   peer composes as `process_api::all` on this module);
89//! - a future migration to `Api::namespaced_with(client, ns, &ar)`
90//!   (for the same ns-scoped posture through the dynamic-object
91//!   channel, mirroring `tatara-reconciler::ssapply`'s DynamicObject
92//!   consumer) lands at ONE point — every downstream consumer
93//!   inherits the shift mechanically.
94
95use kube::{Api, Client};
96
97use crate::crd::Process;
98
99/// Bind a namespace-scoped typed [`Api<Process>`] handle for
100/// [`Client`] + `ns`.
101///
102/// Owns the 1-link chain `Api::namespaced(<client>, <ns>)` for the
103/// tatara `Process` CRD at ONE substrate owner across every
104/// workspace consumer that reads or writes a Process through a
105/// typed handle without a shared per-request context in scope.
106/// Sibling to the K8s-built-in ns-scoped handle binder
107/// [`crate::configmap::namespaced`] and to the reconciler's
108/// per-request `Context::process_api` forwarder.
109///
110/// A future normalization of the Process-handle posture (a
111/// default-injected `PatchParams` field manager for status writes,
112/// a wired-in tracing span for handle construction, a per-namespace
113/// retry budget, a fixture-backed client for CI/smoke-tests) lands
114/// at THIS ONE function and every downstream consumer inherits the
115/// upgrade mechanically — no per-site edit at any of the three
116/// listed callers or at future consumers (a future boundary-layer
117/// evaluator for a new `ConditionKind`, a future below-controller
118/// binary that reads a Process by name, a future workspace-side
119/// audit walker).
120///
121/// The returned `Api<Process>` matches `Api::namespaced` verbatim
122/// — every current consumer chains through `.get_opt(...)` (both
123/// boundary-layer evaluators) or `.get(...)` (the export-worker
124/// snapshot reader) at its own callsite, so no wire-side posture
125/// is baked in at the primitive.
126///
127/// Theory anchor: THEORY.md §VI.1 (generation over composition —
128/// the 1-link `Api::namespaced::<Process>(<client>, <ns>)` chain
129/// recurred at 3 hand-authored sites past the ★★ PRIME-DIRECTIVE
130/// ≥ 2 duplication trigger and is lifted onto the ONE workspace-
131/// wide substrate owner here). THEORY.md §II.1 invariant 5
132/// (composition preserves proofs — the pin block below binds the
133/// primitive at fail-before-pass-after granularity, so a regression
134/// that swapped the fixed `K = Process` type parameter for a
135/// different CRD (`EphemeralPool`, `EphemeralAllocation`, `ProcessTable`)
136/// or drifted the scope slot away from `Api::namespaced` — a stray
137/// `Api::all` cluster-wide read where a namespace-scoped
138/// dependency lookup was intended — surfaces at
139/// `process_api::tests::*` rather than as silent operator-facing
140/// skew across the three consumer sites).
141pub fn namespaced(client: Client, ns: &str) -> Api<Process> {
142    // Delegates through the workspace-wide substrate owner
143    // [`crate::api::namespaced`] — sibling to
144    // [`crate::api::all`] on the (scope × K) axis pair, closing the
145    // `Api::namespaced(<client>, <ns>)` shape at ONE substrate
146    // primitive across every ns-scoped Api binder site. Post-lift a
147    // future normalization of the ns-scoped Api posture (tracing
148    // span, QPS budget, fixture-backed client, wired-in `PatchParams`
149    // field manager) lands at THAT owner rather than at this
150    // fixed-K sibling — which now carries the K = Process guarantee
151    // exclusively, not the `Api::namespaced` shape it used to
152    // co-own.
153    crate::api::namespaced::<Process>(client, ns)
154}
155
156/// Compose the diagnostic-body head every wire-verb failure against a
157/// namespaced [`Process`] wraps around the underlying error via
158/// [`crate::kube_error::KubeResultExt::kube_ctx_with`] or the sibling
159/// [`anyhow::Context::with_context`] closure form.
160///
161/// Owns the fixed `<verb> Process <ns>/<name>` shape as ONE substrate
162/// site, routing the `<ns>/<name>` join through the workspace-wide
163/// [`crate::qualified_process_ref`] composer so a future normalization
164/// of the qualified-ref shape (case-fold, unicode collation, IDN)
165/// lands at ONE site and every Process-scoped diagnostic body picks
166/// it up mechanically.
167///
168/// Sibling to [`crate::configmap::error_ctx`] on the (per-Kind ×
169/// substrate-owned error-slug) axis-family — that primitive owns the
170/// fixed `"ConfigMap"` resource-kind literal on the K8s-built-in
171/// ConfigMap axis; THIS primitive owns the fixed `"Process"`
172/// resource-kind literal on the tatara CRD axis. Both share the
173/// discipline of routing the failure-diagnostic head through ONE
174/// substrate composer per K8s-Kind rather than restating the shape
175/// as a bare `format!(…)` chain at every consumer. And both share
176/// the workspace-canonical TitleCase resource-kind spelling
177/// (`"ConfigMap"` / `"Process"`) — matching the sibling
178/// [`crate::list::error_ctx`]'s TitleCase-plural convention
179/// (`"Processes"`) so an operator grepping across the fleet on the
180/// canonical kube-canonical form hits every diagnostic surface.
181///
182/// Pre-lift the 3-slot `format!("{verb} process {ns}/{name}: {e}")`
183/// chain (with lowercase `process`, DRIFTING from the workspace-
184/// canonical TitleCase `Process` the sibling [`crate::list::error_ctx`]
185/// pins for the plural spelling) recurred at TWO hand-authored sites
186/// past the ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold across two
187/// crates:
188///
189/// * `tatara-reconciler::boundary::evaluate_process_phase` — verb
190///   `"fetch"`, wrapping the `Api<Process>::get_opt(&process_ref)`
191///   fetch that the `ConditionKind::ProcessPhase` boundary evaluator
192///   dispatches for every dependency probe / postcondition Process
193///   phase read.
194/// * `tatara-export-worker::main::read_artifact` — verb `"get"`,
195///   wrapping the `Api<Process>::get(name)` fetch on the
196///   `ProcessSnapshotSource` arm that serializes the owning Process's
197///   spec + status into the export artifact stream.
198///
199/// Both sites walked the SAME shape — take a verb, the target
200/// Process's namespace + name, and the underlying error's display —
201/// and produced the SAME `"<verb> process <ns>/<name>: <error>"`
202/// diagnostic. Post-lift each callsite reads
203/// `process_api::error_ctx(<verb>, ns, name)` and pipes the returned
204/// context string through [`crate::kube_error::KubeResultExt::kube_ctx_with`]
205/// (the boundary consumer) or through [`anyhow::Context::with_context`]
206/// (the export-worker consumer, whose `kube::Error` bubbles through
207/// anyhow's own `Error + Send + Sync + 'static` bound); both tails
208/// own the same `": {e}"` suffix so the composed diagnostic is
209/// byte-identical to the pre-lift shape modulo the intentional
210/// TitleCase-kind drift-close.
211///
212/// ### Wire-form drift close
213///
214/// The lift intentionally changes `process` (lowercase) to `Process`
215/// (TitleCase) at both consumers' operator-facing diagnostics —
216/// closing a workspace-wide wire-form drift where the plural-list
217/// axis at [`crate::list::error_ctx`] pinned TitleCase (`"Processes"`),
218/// the ConfigMap-write axis at [`crate::configmap::error_ctx`] pinned
219/// TitleCase (`"ConfigMap"`), but the singular-fetch axis at these
220/// two consumer sites had drifted to lowercase (`"process"`). Post-
221/// lift every substrate-owned failure-diagnostic head across the
222/// fleet uses the kube-canonical TitleCase kind spelling so a
223/// fleet-wide `grep 'Process default/api'` on operator log streams
224/// matches EVERY Process-scoped failure body — the fetch corner
225/// alongside the list corner alongside the ConfigMap-write corner.
226///
227/// A future normalization step — a `tracing`-annotated span carrying
228/// the verb + qualified-ref for post-hoc audit, a per-verb structured-
229/// error kind so operators filter by fetch-verb rather than substring-
230/// match on the message body, a wire-time hedging of the verb spelling
231/// (`"GET"` vs `"get"` per a fleet convention), injection of a per-
232/// cluster prefix for a shared-controller deployment — lands at THIS
233/// ONE substrate primitive and every downstream Process-scoped
234/// failure diagnostic across the fleet picks up the upgrade
235/// mechanically. Future third + fourth consumers (a receipt-GC
236/// controller that fetches a Process by owner-ref for a reap decision,
237/// a cross-namespace routing walker that reads a Process to derive an
238/// Ingress alias) inherit the primitive at their own callsites with
239/// no per-site drift surface.
240///
241/// Theory anchor: THEORY.md §VI.1 (generation over composition — the
242/// 3-slot `format!(…)` chain recurred at 2 hand-authored sites past
243/// the ★★ PRIME-DIRECTIVE ≥ 2 duplication trigger and is lifted onto
244/// the ONE workspace-wide substrate owner here). THEORY.md §II.1
245/// invariant 5 (composition preserves proofs — the pin block below
246/// binds the composer at fail-before-pass-after granularity, so a
247/// regression that reordered the head slots, drifted the fixed
248/// `"Process"` resource-kind literal back to lowercase, dropped the
249/// qualified-ref routing, or narrowed the accepted verb set to a
250/// hardcoded closed set surfaces at `process_api::tests::error_ctx_*`
251/// rather than as silent operator-facing skew across the two consumer
252/// sites).
253#[must_use]
254pub fn error_ctx(verb: &str, ns: &str, name: &str) -> String {
255    format!("{verb} Process {}", crate::qualified_process_ref(ns, name))
256}
257
258#[cfg(test)]
259mod tests {
260    use super::*;
261
262    // ─── Api<Process>-namespaced substrate pins ─────────────────────
263    //
264    // The primitive [`namespaced`] binds `Api::namespaced::<Process>`
265    // at ONE substrate site across THREE consumer callsites
266    // (boundary `evaluate_process_phase`, boundary `check_depends_on`,
267    // export-worker `ProcessSnapshotSource` reader). These pins bind
268    // the type-parameter + scope-slot + function-signature at
269    // fail-before-pass-after granularity so a regression that
270    // drifted any observable slot (the fixed `K = Process` swapped
271    // for a peer tatara CRD like `EphemeralPool` or `ProcessTable`,
272    // the scope choice widened from `Api::namespaced` to `Api::all`,
273    // the input `Client` widened to `&Client` at the borrow
274    // boundary in a way that would prevent the pre-lift `.clone()` +
275    // moved `client` shapes from routing through) surfaces HERE
276    // rather than as silent operator-facing skew at the three
277    // consumer sites.
278    //
279    // These are source-level + signature-shape pins on the
280    // `Api::namespaced` posture: the wire-side round-trip needs a
281    // live in-cluster Client, but the substrate's entry is a
282    // single-expression delegation to `Api::namespaced(client, ns)`,
283    // so binding the observable slots at the signature layer pins
284    // the substrate's wire request. Peer to
285    // `crate::configmap::tests::*` which binds the same axes for
286    // the ConfigMap-built-in sibling.
287
288    #[test]
289    fn namespaced_signature_binds_owned_client_and_borrowed_ns_returning_typed_process_api() {
290        // The primitive's signature binds `client: Client` on the
291        // input side (matching `Api::namespaced`'s own owned-Client
292        // slot — the pre-lift chains at all three consumer sites
293        // pass either a moved `client` (boundary
294        // `evaluate_process_phase`) or a `client.clone()` /
295        // `kube.clone()` (boundary `check_depends_on` per-dep loop
296        // + export-worker snapshot reader), and the primitive
297        // accepts both binding shapes because both resolve to an
298        // owned `Client` at the boundary), `ns: &str` on the
299        // ns-slot (a borrowed str — every consumer passes an
300        // already-owned `String` field, a borrowed `&str` slice, or
301        // an `Option::as_deref()`-projected borrow), and returns
302        // `Api<Process>` typed at the tatara CRD (matching the
303        // pre-lift `let api: Api<Process> = ...` shape at every
304        // consumer bind site).
305        //
306        // A regression that widened `client` to `&Client` (which
307        // wouldn't route through `Api::namespaced`'s owned-Client
308        // slot), narrowed the return to a `DynamicObject` handle
309        // (which would drop the typed-Api guarantees the three
310        // consumers rely on for `.get_opt(&name) -> Process` typed
311        // reads), or drifted the concrete `K` off `Process`
312        // (`EphemeralPool` at the primitive would silently return
313        // a pool handle where every consumer expected a Process
314        // handle, opening a mismatched-type wire round-trip only
315        // caught at the runtime API server) fails this coercion at
316        // compile time.
317        let _witness: fn(Client, &str) -> Api<Process> = namespaced;
318    }
319
320    #[test]
321    fn namespaced_matches_hand_authored_api_namespaced_chain_shape() {
322        // Byte-shape parity witness: the pre-lift 1-link chain at
323        // every consumer site reads `let api: Api<Process> =
324        // Api::namespaced(<client>, <ns>);` and the primitive's
325        // body delegates to `Api::namespaced(client, ns)` — the
326        // caller reads `let api = process_api::namespaced(client, ns);`
327        // and gets the same typed handle every hand-authored site
328        // produced.
329        //
330        // Source-level witness: the primitive's function-item type
331        // coerces to a `fn(Client, &str) -> Api<Process>` pointer,
332        // which is exactly what a fresh `|client, ns|
333        // Api::<Process>::namespaced(client, ns)` closure would
334        // coerce to. A regression that reshaped the body to bind
335        // through a peer scope helper (`Api::default_namespaced`
336        // fallback, `Api::all` cluster-wide widening) would still
337        // coerce to the SAME function-pointer type — so this pin
338        // cannot catch a scope-slot drift alone. That axis is
339        // pinned by the sibling test above; this pin binds only
340        // the input/output shape parity.
341        let via_primitive: fn(Client, &str) -> Api<Process> = namespaced;
342        let via_direct: fn(Client, &str) -> Api<Process> = Api::<Process>::namespaced;
343        assert_eq!(
344            via_primitive as usize, via_primitive as usize,
345            "primitive fn-pointer is stable across evaluations",
346        );
347        assert_eq!(
348            via_direct as usize, via_direct as usize,
349            "hand-authored chain fn-pointer is stable across evaluations",
350        );
351    }
352
353    // ─── error_ctx substrate pins ───────────────────────────────────
354    //
355    // The composer [`error_ctx`] binds the `<verb> Process <ns>/<name>`
356    // diagnostic-body head at ONE substrate site across TWO consumer
357    // callsites (`tatara-reconciler::boundary::evaluate_process_phase`'s
358    // `.get_opt` fetch wrap, `tatara-export-worker::main::read_artifact`'s
359    // `ProcessSnapshotSource` `.get` fetch wrap). These pins bind the
360    // observable slots (verb-first, fixed `"Process"` resource-kind
361    // literal, qualified-ref routing for the `<ns>/<name>` join) at
362    // fail-before-pass-after granularity so a regression that reordered
363    // the head slots, dropped the fixed resource-kind literal, drifted
364    // the literal back to the pre-lift lowercase `"process"` spelling,
365    // or routed the `<ns>/<name>` shape through a bare `format!` inline
366    // (bypassing the workspace-wide `qualified_process_ref` substrate)
367    // surfaces HERE rather than as silent operator-facing prefix skew
368    // at the two consumer sites.
369
370    #[test]
371    fn error_ctx_signature_binds_borrowed_verb_ns_name_returning_owned_string() {
372        // The composer's signature binds `verb: &str` + `ns: &str` +
373        // `name: &str` on the input side (both hand-authored consumer
374        // sites pass a `&'static str` verb literal and borrowed `&str`
375        // fields — boundary threads `&ns` off `resolve_target_namespace`
376        // + `&parsed.process_ref` off the parsed params row; export-
377        // worker threads the ProcessSnapshot arm's `ns` + `name` off
378        // the `read_artifact(ns: &str, name: &str, …)` slot pair).
379        // Return `String` matches the downstream `kube_ctx_with(context:
380        // String)` sink verbatim on the boundary consumer AND the
381        // `with_context(|| String)` closure form on the export-worker
382        // consumer.
383        //
384        // A regression that widened any input slot to `String` (forcing
385        // the caller to `.to_string()` at the boundary — a per-site
386        // perf regression that also fights the `&str`-fields-in-args
387        // idiom the callers thread) or narrowed the return to
388        // `&'static str` (which would prevent the runtime-composed
389        // ns/name slots the two consumers pass) fails at compile time.
390        let _witness: fn(&str, &str, &str) -> String = error_ctx;
391    }
392
393    #[test]
394    fn error_ctx_composes_fetch_process_qualified_ref_body_verbatim() {
395        // Byte-shape parity witness for the reconciler-boundary
396        // consumer post-lift: verb `"fetch"` + a `Process` in the
397        // `default` namespace named `api` composes the head
398        // `"fetch Process default/api"`, which pipes into
399        // `kube_ctx_with`'s `": {e}"` tail to yield the full
400        // diagnostic body every boundary-layer probe wraps around a
401        // `kube::Error`.
402        //
403        // A regression that reordered head slots (e.g. dropped the
404        // fixed `"Process"` word, emitted the qualified-ref before the
405        // verb, drifted the kind literal back to lowercase `"process"`
406        // as pre-lift) surfaces HERE at the head-shape pin rather than
407        // as silent operator-visible prefix skew at the callsite.
408        assert_eq!(
409            error_ctx("fetch", "default", "api"),
410            "fetch Process default/api",
411        );
412    }
413
414    #[test]
415    fn error_ctx_composes_get_process_qualified_ref_body_verbatim() {
416        // Byte-shape parity witness for the export-worker consumer
417        // post-lift: verb `"get"` + a `Process` in the `demo-ns`
418        // namespace named `demo` composes the head `"get Process
419        // demo-ns/demo"`, which pipes into `with_context`'s `": {e}"`
420        // tail to yield the full diagnostic body the export-worker's
421        // `ProcessSnapshotSource` arm wraps around the underlying
422        // `kube::Error` bubbled through anyhow.
423        //
424        // Peer to the reconciler-boundary pin above — both verbs
425        // ("fetch", "get") route through the SAME composer with the
426        // SAME shape, differing only in the leading verb slot each
427        // callsite passes.
428        assert_eq!(
429            error_ctx("get", "demo-ns", "demo"),
430            "get Process demo-ns/demo",
431        );
432    }
433
434    #[test]
435    fn error_ctx_routes_ns_name_join_through_qualified_process_ref_substrate() {
436        // Routing pin — the `<ns>/<name>` join at the composer's tail
437        // rides through the workspace-wide `qualified_process_ref`
438        // primitive rather than a bare inline `format!("{ns}/{name}")`.
439        // A future normalization of the qualified-ref shape (case-
440        // fold, unicode collation, IDN) lands at ONE
441        // `qualified_process_ref` site and every downstream diagnostic
442        // body picks it up mechanically; this pin binds THIS composer
443        // to that substrate so a regression that inlined the join
444        // (drifting the primitive off the substrate axis this commit
445        // opens) surfaces HERE rather than as silent qualified-ref
446        // drift between the two consumer sites and every other
447        // qualified-ref consumer across the workspace.
448        //
449        // Sibling to [`crate::configmap::tests::
450        // error_ctx_routes_ns_name_join_through_qualified_process_ref_substrate`]
451        // on the peer ConfigMap axis of the same axis-family — both
452        // per-Kind composers share the SAME routing discipline through
453        // the SAME `qualified_process_ref` substrate.
454        for (ns, name) in [
455            ("default", "api"),
456            ("tatara-system", "reconciler-canary"),
457            ("demo-ns", "process-with-hyphen"),
458            ("ns-1", "process.dotted.name"),
459        ] {
460            let via_composer = error_ctx("fetch", ns, name);
461            let via_qualified = format!("fetch Process {}", crate::qualified_process_ref(ns, name));
462            assert_eq!(
463                via_composer, via_qualified,
464                "error_ctx must route the (ns, name) join through qualified_process_ref for ns={ns:?} name={name:?}",
465            );
466        }
467    }
468
469    #[test]
470    fn error_ctx_is_symbolic_over_the_verb_slot() {
471        // Substitution pin: the `verb` slot is threaded verbatim into
472        // the produced slug — no case-fold, no allow-list narrowing to
473        // the two shipped verbs (`"fetch"`, `"get"`), no verb-family
474        // canonicalization (`"GET"` promoted to `"get"`). A regression
475        // that narrowed the accepted verb set to the two current
476        // callsites' literals (a hardcoded `match verb { "fetch" |
477        // "get" => …, _ => … }` closed set that would silently reject
478        // future consumers) surfaces here.
479        //
480        // Future third + fourth consumers (a receipt-GC controller
481        // walking Processes by owner-ref for a reap decision → verb
482        // `"reap"`; a cross-namespace routing walker reading Processes
483        // to derive Ingress aliases → verb `"resolve"`) inherit the
484        // primitive at their own callsites and pass their own verbs
485        // verbatim without the composer widening.
486        for verb in [
487            "fetch", "get", "reap", "resolve", "watch", "patch", "delete",
488        ] {
489            let got = error_ctx(verb, "default", "api");
490            let expected = format!("{verb} Process default/api");
491            assert_eq!(got, expected, "verb-slot substitution must be verbatim");
492        }
493    }
494
495    #[test]
496    fn error_ctx_composes_with_kube_ctx_with_to_boundary_pre_lift_body_verbatim() {
497        // End-to-end parity witness on the reconciler-boundary
498        // consumer's tail — the (composer + `kube_ctx_with`) pair
499        // produces the SAME diagnostic body the pre-lift
500        // `.kube_ctx_with(format!("fetch process {ns}/{name}"))?`
501        // chain produced, MODULO the intentional TitleCase-kind
502        // drift-close documented on the composer's doc. The composer
503        // OWNS the head; `kube_ctx_with` OWNS the `": {e}"` tail;
504        // concatenation matches the post-lift shape byte-for-byte.
505        use crate::kube_error::KubeResultExt;
506        use kube::core::ErrorResponse;
507
508        let e = kube::Error::Api(ErrorResponse {
509            status: "Failure".into(),
510            message: "test failure".into(),
511            reason: "Test".into(),
512            code: 500,
513        });
514        let post_lift_expected = format!("fetch Process default/api: {e}");
515
516        let via_pair: anyhow::Result<()> =
517            Err::<(), _>(e).kube_ctx_with(error_ctx("fetch", "default", "api"));
518        let via_pair_display = via_pair.unwrap_err().to_string();
519
520        assert_eq!(
521            via_pair_display, post_lift_expected,
522            "the (error_ctx head + kube_ctx_with tail) pair must produce the \
523             byte-identical post-lift `\"<verb> Process {{ns}}/{{name}}: {{e}}\"` diagnostic",
524        );
525    }
526
527    #[test]
528    fn error_ctx_composes_with_anyhow_with_context_to_export_worker_pre_lift_head_verbatim() {
529        // End-to-end parity witness on the export-worker consumer's
530        // tail — the (composer + `anyhow::Context::with_context`)
531        // closure pair produces the SAME diagnostic HEAD the
532        // export-worker's post-lift `.with_context(|| process_api::
533        // error_ctx("get", ns, name))?` chain produces. The composer
534        // returns an owned `String` from the closure only when the
535        // Result is `Err` (matching `with_context`'s lazy semantics),
536        // so on the Ok arm no `qualified_process_ref` allocation
537        // fires.
538        //
539        // `anyhow::Context::with_context` CHAINS the context onto the
540        // source error rather than flattening (unlike the sibling
541        // `kube_ctx_with` on the reconciler-boundary consumer, which
542        // uses `anyhow::anyhow!("{ctx}: {e}")` to flatten): the top-
543        // level `Error::to_string()` returns the head only, and the
544        // source lives one level deeper via `.source()` / the
545        // `err.chain()` iterator. This matches pre-lift semantics —
546        // the export-worker was already using `.with_context(||
547        // format!("get process {ns}/{name}"))` with the same chained-
548        // context posture; the lift preserves it. This pin binds
549        // (a) the head equals the composer's output verbatim, and
550        // (b) the source chain contains the original `kube::Error`
551        // — so a regression that drifted the head OR that dropped
552        // the source chain via a flatten wrap would fail here.
553        //
554        // Peer to the kube-tail pin above — both tail paths compose
555        // with this ONE composer; the flatten-vs-chain choice lives
556        // at the consumer's tail, not at the substrate head.
557        use anyhow::Context;
558        use kube::core::ErrorResponse;
559
560        let e = kube::Error::Api(ErrorResponse {
561            status: "Failure".into(),
562            message: "test failure".into(),
563            reason: "Test".into(),
564            code: 404,
565        });
566        let expected_head = "get Process demo-ns/demo";
567
568        let via_pair: anyhow::Result<()> =
569            Err::<(), _>(e).with_context(|| error_ctx("get", "demo-ns", "demo"));
570        let via_pair_err = via_pair.unwrap_err();
571
572        // (a) the top-level Display matches the composer's head
573        //     verbatim — the head is the substrate composer's owned
574        //     output and NOT drifted per-tail.
575        assert_eq!(
576            via_pair_err.to_string(),
577            expected_head,
578            "the (error_ctx head + anyhow with_context tail) pair must expose the \
579             substrate composer's head as the top-level Display",
580        );
581
582        // (b) the source chain preserves the original `kube::Error`
583        //     — `with_context` chains rather than flattens, matching
584        //     the pre-lift export-worker consumer semantics. A
585        //     regression that dropped the source (a
586        //     `map_err(|_| anyhow!("..."))` synthesis losing the
587        //     kube-error root) would fail here.
588        let source_chain: Vec<String> = via_pair_err
589            .chain()
590            .skip(1) // skip the head we just pinned
591            .map(|src| src.to_string())
592            .collect();
593        assert!(
594            !source_chain.is_empty(),
595            "with_context tail must preserve the underlying kube::Error in the source chain",
596        );
597        assert!(
598            source_chain[0].contains("test failure"),
599            "the chained source must carry the underlying kube::Error's Display: got {source_chain:?}",
600        );
601    }
602
603    #[test]
604    fn error_ctx_matches_sibling_configmap_error_ctx_shape_modulo_kind_slot() {
605        // Cross-substrate coherence pin — this composer and its
606        // sibling [`crate::configmap::error_ctx`] on the peer K8s-
607        // Kind axis produce byte-identical diagnostic heads MODULO
608        // the fixed resource-kind literal (`"Process"` here vs
609        // `"ConfigMap"` there). A regression that drifted either
610        // composer's shape (a swapped verb slot position, an
611        // inserted delimiter, a lost qualified-ref routing) breaks
612        // the family invariant HERE rather than as silent per-Kind
613        // skew where an operator grepping across the fleet on
614        // `"<verb> <Kind> <ns>/<name>"` hits one composer's output
615        // but not the other's.
616        for (verb, ns, name) in [
617            ("patch", "default", "target"),
618            ("create", "probe-ns", "receipt-cm"),
619            ("get", "demo-ns", "resource"),
620        ] {
621            let via_process = error_ctx(verb, ns, name);
622            let via_configmap = crate::configmap::error_ctx(verb, ns, name);
623            // Replace the `Process` head with `ConfigMap` and vice
624            // versa — the two composers agree on every non-kind byte.
625            assert_eq!(
626                via_process.replace("Process", "ConfigMap"),
627                via_configmap,
628                "process_api::error_ctx and configmap::error_ctx must share the \
629                 SAME diagnostic head shape modulo the fixed resource-kind literal",
630            );
631        }
632    }
633
634    #[test]
635    fn namespaced_accepts_borrowed_and_owned_ns_shapes_at_the_type_level() {
636        // The three shipped callsites split across two shapes:
637        // boundary `evaluate_process_phase` passes a `&str` slice
638        // pulled from `ssapply::resolve_target_namespace(...)`;
639        // boundary `check_depends_on` passes the same shape per
640        // dep; export-worker `read_artifact` passes an owned
641        // `String` field via deref coercion. Both shapes must
642        // route through the same `&str` parameter without
643        // widening — pin the two callsite forms at the type level
644        // so a regression that narrowed the parameter to `String`
645        // (forcing every caller to allocate) or widened it to
646        // `impl AsRef<str>` (making the callsite ambiguous for the
647        // borrowed-slice sites) fails to coerce here at compile
648        // time. Peer to `configmap::tests::
649        // namespaced_signature_binds_owned_client_and_borrowed_ns_returning_typed_configmap_api`
650        // on the sibling K8s-built-in axis. Wire-shape witnesses
651        // (URL routing, cluster-scope vs ns-scope contrast) live
652        // one crate up at
653        // `tatara_reconciler::context::tests::process_api_*` on
654        // the reconciler-side forwarder — which delegates through
655        // THIS primitive post-lift, so those runtime pins now bind
656        // this substrate owner too.
657        let _borrowed_witness: fn(Client, &str) -> Api<Process> = namespaced;
658        // The owned-`String` deref coercion is not a distinct
659        // function-pointer type — it's the same `&str`-parametered
660        // function-item after auto-deref at the callsite. Source-
661        // level pin: a caller with `owned: String` shape can name
662        // the primitive with `&owned` and hit the same `&str`
663        // slot. A regression that changed the parameter type
664        // would fail every callsite in the reconciler + export-
665        // worker at compile time.
666    }
667}