tatara_process/patch.rs
1//! Substrate primitive for the merge-patch idiom over the `/status`
2//! subresource of any kube [`Resource`].
3//!
4//! Owns the 2-link chain
5//!
6//! ```text
7//! let body = json!({ "status": <typed> });
8//! api.patch_status(name, &PatchParams::default(), &Patch::Merge(&body)).await
9//! ```
10//!
11//! that every controller-side writer hand-authored pre-lift at each
12//! phase-transition + observed-fanout site.
13//!
14//! Sibling to the SSA-side substrate primitive
15//! [`crate::api_version`]-adjacent `tatara_reconciler::ssapply::apply_patch_params`
16//! (which owns the `PatchParams::apply(<mgr>).force()` peer on the
17//! server-side-apply axis). Together, the two primitives own the two
18//! wire-side write-posture axes the workspace's controllers stamp:
19//!
20//! - `Patch::Merge + PatchParams::default()` — status-subresource
21//! writes, applied here by every phase-transition writer in the
22//! `tatara-pool-reconciler` (allocation controller, pool controller)
23//! and the `tatara-reconciler` (Process status writer).
24//! - `Patch::Apply + PatchParams::apply(<mgr>).force()` — rendered
25//! FluxCD resource applies + `RELEASED_FROM` marker + the
26//! `ProcessTable.status.claims` writer.
27//!
28//! ### Return type + `#[must_use]`
29//!
30//! Returns the reconstructed `K` on success — matches `Api::patch_status`
31//! verbatim. Pool + Process controllers today discard the returned `K`
32//! (`let _ = merge_status(...).await;` after `AllocationDecision` /
33//! phase-transition branches), but the primitive keeps the return in
34//! the signature so a future writer that needs the reconciled
35//! resource-version / observed-generation from the same wire round-trip
36//! doesn't have to re-fetch. `#[must_use]` on the returned `Future`
37//! keeps a caller from building the patch call and dropping it
38//! un-awaited — the same silent-drop defect the pre-lift free-chain
39//! form quietly permitted.
40
41use kube::api::{Api, Patch, PatchParams};
42use kube::Resource;
43use serde::{de::DeserializeOwned, Serialize};
44use serde_json::json;
45use std::fmt::Debug;
46
47/// Compose the merge-patch wire body `{"status": <status>}` — the
48/// pure step [`merge_status`] performs before handing off to
49/// `Api::patch_status`.
50///
51/// Extracted as a standalone helper so the wire-body shape can be
52/// pinned by fail-before-pass-after tests without a live kube client
53/// or tokio reactor. A regression that drifts the top-level slot name
54/// (a `"Status": …` case-fold, a `"status_patch": …` verbose rename,
55/// an accidental array-wrap) surfaces here at every invariant pin
56/// rather than as silent operator-facing drift at each downstream
57/// consumer.
58#[must_use]
59pub fn merge_status_body<S: Serialize + ?Sized>(status: &S) -> serde_json::Value {
60 json!({ "status": status })
61}
62
63/// Merge-patch the `/status` subresource of any kube [`Resource`] with
64/// a typed `status` value.
65///
66/// Owns the 2-step wire-side chain `merge_status_body(status) →
67/// Api::patch_status(name, PatchParams::default(), Patch::Merge)` at
68/// ONE substrate owner across every workspace controller. Pre-lift the
69/// chain recurred at 7 hand-authored sites (4 in
70/// `tatara-pool-reconciler::controller_allocation`, 2 in
71/// `tatara-pool-reconciler::controller_pool`, 1 wrapped inside
72/// `tatara-reconciler::patch::patch_process_status`) past the ★★
73/// PRIME-DIRECTIVE ≥ 2 duplication trigger.
74///
75/// A future normalization of the merge-patch posture (an injectable
76/// field manager for status writes, a strategic-merge escape hatch, a
77/// dry-run gate for one-shot dry-runs, an added `resourceVersion`
78/// precondition slot) lands at THIS ONE function and every downstream
79/// consumer inherits the upgrade mechanically.
80pub async fn merge_status<K, S>(api: &Api<K>, name: &str, status: &S) -> Result<K, kube::Error>
81where
82 K: Resource + DeserializeOwned + Clone + Debug,
83 K::DynamicType: Default,
84 S: Serialize + ?Sized,
85{
86 let body = merge_status_body(status);
87 api.patch_status(name, &PatchParams::default(), &Patch::Merge(&body))
88 .await
89}
90
91/// Merge-patch the PRIMARY resource endpoint of any kube [`Resource`]
92/// with a caller-composed wire body.
93///
94/// Primary-resource sibling to [`merge_status`] on the (wire-endpoint ×
95/// wrap-posture) pair: [`merge_status`] owns the `/status` subresource
96/// axis (`api.patch_status(...)`) AND wraps the caller's typed value
97/// into `{"status": <typed>}` before dispatching; this primitive owns
98/// the primary-resource axis (`api.patch(...)`) and passes the caller's
99/// body through verbatim — the caller composes the top-level `spec:`,
100/// `metadata:`, `data:`, or other merge-patch slot before hand-off.
101///
102/// The wrap asymmetry between the two primitives matches the pre-lift
103/// callsite discipline exactly: every `/status` writer built a typed
104/// status value (an `AllocationStatus`, a `ProcessStatus`, a raw
105/// `Value`) and delegated the `{"status": …}` wrap uniformly, so
106/// [`merge_status`] owns that wrap; every primary-resource writer
107/// composed a task-specific body (a `spec:` slot for a spec patch, a
108/// `metadata:` slot for a finalizer / annotation edit, a `data:` slot
109/// for a ConfigMap edit) with no shared top-level shape, so this
110/// primitive dispatches the caller's body verbatim rather than
111/// speculating a wrap. A future normalization that WOULD apply to every
112/// primary-resource writer (a hardcoded field-manager pass-through for
113/// primary-resource merge writes, a strategic-merge escape hatch, a
114/// dry-run gate, a `resourceVersion` precondition slot) lands at THIS
115/// ONE function and every downstream consumer inherits the upgrade
116/// mechanically.
117///
118/// Pre-lift the 3-link chain
119/// `api.patch(name, &PatchParams::default(), &Patch::Merge(&body))` was
120/// hand-authored at SIX consumer sites past the ★★ PRIME-DIRECTIVE ≥ 2
121/// duplication threshold, spanning TWO workspace crates:
122/// * `tatara-reconciler::patch::patch_process_table_spec` — the
123/// `{"spec": ...}` merge that stamps `next_sequence` bumps on the
124/// ProcessTable singleton.
125/// * `tatara-reconciler::patch::apply_finalizer_transform` — the
126/// `{"metadata": {"finalizers": [...]}}` merge that owns finalizer
127/// ensure / remove on the Process (shared by both public wrappers).
128/// * `tatara-reconciler::signals::ingest` — the
129/// `{"metadata": {"annotations": {SIGNAL: null}}}` merge that strips
130/// the tatara-pleme-io/signal annotation off the Process after
131/// ingestion.
132/// * `tatara-reconciler::signals::consume_effect` (`SignalEffect::Suspend`
133/// arm) — the `{"spec": {"suspended": true}}` merge that stamps
134/// SIGSTOP-persistent suspend state on the Process.
135/// * `tatara-reconciler::signals::consume_effect` (`SignalEffect::Resume`
136/// arm) — the `{"spec": {"suspended": false}}` merge that lifts
137/// suspend state on SIGCONT.
138/// * `tatara-closed-loop-probe::main::write_receipt_configmap` (409
139/// already-exists retry path) — the `{"data": <receipt payload>}`
140/// merge that updates the receipt ConfigMap in-place when the create
141/// arm loses the race with a prior probe emission.
142///
143/// Post-lift each callsite reads `patch::merge(&api, name, &body)` and
144/// the 3-link chain lives at ONE substrate owner. The pin block below
145/// binds the primitive at fail-before-pass-after granularity so a
146/// regression that drops `Patch::Merge` for `Patch::Strategic`, drifts
147/// the `PatchParams::default()` slot, or reorders the 3-arg positional
148/// slots surfaces here rather than as silent primary-resource writer
149/// skew across the two consumer crates.
150///
151/// Theory anchor: THEORY.md §VI.1 (generation over composition — the
152/// 3-link primary-resource merge chain recurred at 6 hand-authored
153/// sites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication trigger, and is
154/// lifted onto the ONE workspace-wide substrate owner here). THEORY.md
155/// §II.1 invariant 5 (composition preserves proofs — the pin block
156/// binds the `Patch::Merge` posture + the default `PatchParams` slot +
157/// the pass-through body composition + the byte-identical parity with
158/// the pre-lift 3-link chain, so a regression that drifted any surface
159/// surfaces here rather than as silent operator-facing skew across the
160/// six primary-resource writer sites).
161pub async fn merge<K, B>(api: &Api<K>, name: &str, body: &B) -> Result<K, kube::Error>
162where
163 K: Resource + DeserializeOwned + Clone + Debug,
164 K::DynamicType: Default,
165 B: Serialize + Debug + ?Sized,
166{
167 api.patch(name, &PatchParams::default(), &Patch::Merge(body))
168 .await
169}
170
171/// Server-side-apply [`PatchParams`] with `field_manager` bound to the
172/// caller-supplied slot and `force = true` — the ONE substrate
173/// primitive owning the `PatchParams::apply(<mgr>).force()` incantation
174/// every workspace SSA writer restated by hand pre-lift.
175///
176/// SSA-side sibling to [`merge_status`] on the (wire-posture × axis)
177/// pair: [`merge_status`] owns the merge-patch axis
178/// (`Patch::Merge + PatchParams::default()` over `/status`); this
179/// primitive owns the server-side-apply axis
180/// (`Patch::Apply + PatchParams::apply(<mgr>).force()` over the primary
181/// resource). Together they own the two wire-side write-posture
182/// primitives the workspace's controllers stamp.
183///
184/// Pre-lift the 2-link chain was hand-authored at THREE consumer sites
185/// past the ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold, spanning THREE
186/// crates:
187/// * `tatara-pool-reconciler::controller_allocation` (bind arm +
188/// release arm) — `PatchParams::apply(&ctx.config.field_manager)
189/// .force()` on the Process patch that stamps requestor / allocation
190/// binding annotations, and on the return-trigger annotation patch.
191/// * `tatara-export-worker::main::write_receipt` — `PatchParams::apply
192/// ("tatara-export-worker").force()` on the receipt ConfigMap apply.
193///
194/// And a fourth site owns the reconciler-crate-local
195/// [`FIELD_MANAGER`]-bound wrapper
196/// (`tatara_reconciler::ssapply::apply_patch_params`), which post-lift
197/// delegates to THIS substrate primitive rather than re-stating the
198/// chain: the SSA-side wire posture now has ONE workspace-wide owner.
199///
200/// The `field_manager` slot is caller-supplied because the SSA writers
201/// this primitive serves span three different field-manager
202/// disciplines:
203/// * `tatara-reconciler` — a `pub const FIELD_MANAGER: &str =
204/// "tatara-reconciler"` bound at the reconciler-crate wrapper.
205/// * `tatara-pool-reconciler` — a per-instance `ctx.config.field_manager`
206/// String, so a per-shard or per-cluster deployment can distinguish
207/// its allocator's SSA writes from a sibling deployment's.
208/// * `tatara-export-worker` — a `"tatara-export-worker"` literal, so
209/// the reconciler / operator distinguishes worker-emitted receipt
210/// ConfigMaps from reconciler-emitted resources at field-manager
211/// ownership queries.
212///
213/// The `force = true` semantics matches the SSA `force` directive every
214/// pre-lift chain applied — every consumer of this primitive is the
215/// authoritative owner of the field pathways it stamps
216/// (rendered-resource annotations, `RELEASED_FROM` marker,
217/// `ProcessTable.status.claims`, allocation-bind annotations, receipt
218/// ConfigMap data) and reclaims conflicting slots from prior
219/// field-manager owners on every apply.
220///
221/// A `#[must_use]` return keeps a caller from building a `PatchParams`
222/// via this primitive and then dropping it un-passed to `Api::patch`;
223/// the primitive exists to be consumed at a wire-side write, not to
224/// probe field-manager state.
225///
226/// Theory anchor: THEORY.md §VI.1 (generation over composition — the
227/// `.apply(<mgr>).force()` chain recurred at 3 hand-authored sites
228/// past the ★★ PRIME-DIRECTIVE ≥ 2 duplication trigger, spanning three
229/// workspace crates, and is lifted to ONE workspace-wide substrate
230/// owner here). THEORY.md §II.1 invariant 5 (composition preserves
231/// proofs — the pin block below binds the primitive at
232/// fail-before-pass-after granularity, so a regression that drops
233/// `.force()`, drifts the field-manager pass-through, or widens the
234/// posture surfaces at THESE pins rather than as silent SSA writer
235/// skew across the three consumer crates).
236#[must_use]
237pub fn apply_patch_params(field_manager: &str) -> PatchParams {
238 PatchParams::apply(field_manager).force()
239}
240
241/// Server-side-apply the caller-composed `body` against the PRIMARY resource
242/// endpoint of any kube [`Resource`] under `field_manager` with `force = true`.
243///
244/// SSA-side sibling to [`merge`] on the (wire-endpoint × wrap-posture) pair:
245/// [`merge`] owns the primary-resource `Patch::Merge + PatchParams::default()`
246/// axis; this primitive owns the primary-resource
247/// `Patch::Apply + PatchParams::apply(<mgr>).force()` axis and composes the
248/// two-link `apply_patch_params + api.patch(&Patch::Apply(...))` chain every
249/// workspace SSA writer hand-authored pre-lift at each ownership-taking
250/// apply site.
251///
252/// Pre-lift the 3-link chain
253/// `let pp = apply_patch_params(<mgr>);
254/// api.patch(name, &pp, &Patch::Apply(&body)).await`
255/// was hand-authored at THREE workspace-wide consumer sites past the ★★
256/// PRIME-DIRECTIVE ≥ 2 duplication threshold, spanning TWO active crates:
257/// * `tatara-reconciler::ssapply::apply_owned` — the DynamicObject SSA
258/// writer for every rendered flux/aplicacao resource; the manager
259/// is [`tatara_reconciler::ssapply::FIELD_MANAGER`].
260/// * `tatara-reconciler::phase_machine::transition_to_releasing` — the
261/// `RELEASED_FROM` annotation stamp on Attested/Failed → Releasing;
262/// same manager as above.
263/// * `tatara-export-worker::main::write_receipt` — the receipt ConfigMap
264/// SSA apply; the manager is the `"tatara-export-worker"` literal.
265///
266/// All three sites walked the SAME two-link chain — build a `PatchParams`
267/// via [`apply_patch_params`], then dispatch through
268/// `api.patch(name, &pp, &Patch::Apply(&body))`. Post-lift each callsite
269/// reads `tatara_process::patch::apply(&api, name, <mgr>, &body).await`
270/// and the params-build + `Patch::Apply` wire dispatch lives at ONE
271/// substrate owner.
272///
273/// The `field_manager` slot is caller-supplied because the three SSA
274/// writers this primitive serves span two field-manager disciplines:
275/// tatara-reconciler feeds its `FIELD_MANAGER` const (via the
276/// crate-local `ssapply::apply_patch_params()` wrapper's callers, which
277/// after this lift call THIS primitive with the const directly),
278/// tatara-export-worker feeds the `"tatara-export-worker"` literal.
279///
280/// A future normalization of the SSA-side wire posture (an injectable
281/// `dry_run` mode, a `field_validation` default, a per-fleet retry
282/// policy, a `resourceVersion` precondition slot, a `tracing`-annotated
283/// span carrying the apply's manager + body-summary for post-hoc audit)
284/// lands at THIS ONE substrate primitive (or at [`apply_patch_params`]
285/// on the params sub-axis) and every downstream SSA writer inherits
286/// the upgrade mechanically. No per-site edit at any of the three
287/// listed callers or at future consumers (a new SSA writer for a
288/// non-DynamicObject typed resource, a fourth crate stamping receipts,
289/// a per-Kind apply sink).
290///
291/// Return-form axis: `Result<K, kube::Error>` matches `Api::patch`
292/// verbatim. Consumers today either drop the returned `K`
293/// (`.await.map_err(...)?` at ssapply + phase_machine) or discard it
294/// through `.await.map(|_| ()).with_context(...)?` at export-worker;
295/// keeping the return in the signature lets a future writer that needs
296/// the reconciled `resourceVersion` / `generation` from the same wire
297/// round-trip read it without a re-fetch.
298///
299/// Theory anchor: THEORY.md §VI.1 (generation over composition — the
300/// 2-link `apply_patch_params + api.patch(&Patch::Apply(...))` chain
301/// recurred at 3 hand-authored sites past the ★★ PRIME-DIRECTIVE ≥ 2
302/// duplication trigger, spanning two workspace crates, and is lifted
303/// onto ONE substrate owner here). THEORY.md §II.1 invariant 5
304/// (composition preserves proofs — the pin block below binds the
305/// `Patch::Apply` posture + the [`apply_patch_params`] pass-through +
306/// the byte-identical parity with the pre-lift chain, so a regression
307/// that drifts any surface surfaces here rather than as silent SSA
308/// writer skew across the three primary-resource apply sites).
309pub async fn apply<K, B>(
310 api: &Api<K>,
311 name: &str,
312 field_manager: &str,
313 body: &B,
314) -> Result<K, kube::Error>
315where
316 K: Resource + DeserializeOwned + Clone + Debug,
317 B: Serialize + Debug + ?Sized,
318{
319 // NOTE: `K::DynamicType: Default` is deliberately NOT required here
320 // (unlike [`merge`] / [`merge_status`]) so [`Api<DynamicObject>`]
321 // consumers — whose `DynamicType = ApiResource` is not `Default` —
322 // ride the same primitive as concrete `Api<ConfigMap>` /
323 // `Api<Process>` consumers. `Api::patch` itself needs only
324 // `K: Clone + DeserializeOwned + Debug` on its own impl block; the
325 // `Default` bound on the sibling primitives is a legacy of their
326 // pre-lift call sites, none of which exercised DynamicObject.
327 let pp = apply_patch_params(field_manager);
328 api.patch(name, &pp, &Patch::Apply(body)).await
329}
330
331/// Merge-patch the PRIMARY resource endpoint of any kube [`Resource`] under
332/// `field_manager` with `force = true` — the merge-strategy sibling to
333/// [`apply`] on the (Patch-strategy × PatchParams-posture) matrix.
334///
335/// Owns the two-link chain
336/// `apply_patch_params(<mgr>) + api.patch(name, &pp, &Patch::Merge(&body))`
337/// at ONE substrate owner. Closes the four-corner posture matrix the
338/// wire-side patch family stamps:
339///
340/// | Strategy | `PatchParams::default()` | `apply_patch_params(<mgr>)` |
341/// |----------|--------------------------|-----------------------------|
342/// | Merge | [`merge`] | **`merge_as`** (this one) |
343/// | Apply | (invalid — SSA requires a field manager) | [`apply`] |
344///
345/// [`merge`] owns the anonymous-writer merge-patch corner
346/// (`PatchParams::default()`, no field-manager ownership); [`apply`] owns
347/// the SSA corner (`Patch::Apply` under a named field manager); this
348/// primitive owns the remaining corner — a merge-patch that STILL stamps
349/// a named field manager on the write, chosen when the caller wants
350/// merge-patch semantics (server merges the caller's partial body into
351/// the existing object per RFC 7396, rather than the SSA ownership
352/// reconciliation model) BUT wants the write attributed to a named
353/// controller in the field-manager ownership audit (so downstream `kubectl
354/// get -o yaml`'s `managedFields` distinguishes a
355/// `tatara-pool-reconciler`-stamped bind edit from a
356/// `tatara-reconciler`-stamped phase-transition status write).
357///
358/// Pre-lift the two-link chain was hand-authored at TWO workspace-wide
359/// consumer sites past the ★★ PRIME-DIRECTIVE ≥ 2 duplication threshold,
360/// both inside `tatara-pool-reconciler::controller_allocation`:
361/// * Bind arm — stamps the compound `spec.lifetime` overlay + the three
362/// `metadata.annotations` requestor / allocation / requestor-kind
363/// labels onto the pool member Process on transition from Queued to
364/// Bound. Body: `{"spec": {"lifetime": …}, "metadata": {"annotations":
365/// {REQUESTOR: …, ALLOCATION: …, REQUESTOR_KIND: …}}}`. Field manager:
366/// `ctx.config.field_manager` (per-instance String).
367/// * Release arm — stamps the single `tatara.pleme.io/return-trigger`
368/// annotation onto the member Process to nudge the Pool reconciler
369/// into taking the return path. Body: [`annotation_body`]-composed
370/// single-key metadata edit. Field manager: `ctx.config.field_manager`
371/// (same String).
372///
373/// Both sites walked the SAME two-link chain — build a `PatchParams` via
374/// [`apply_patch_params`] with the pool-reconciler's per-instance
375/// `field_manager`, then dispatch through `api.patch(name, &pp,
376/// &Patch::Merge(&body))`. Post-lift each callsite reads
377/// `tatara_process::patch::merge_as(&api, name, <mgr>, &body).await`
378/// and the params-build + `Patch::Merge` wire dispatch lives at ONE
379/// substrate owner. A future normalization of the named-merge-writer
380/// posture (an injectable `dry_run` mode for a shadow-mode rollout, a
381/// `field_validation` default when the pool-reconciler flips on strict
382/// validation, an injectable retry policy for the transient-conflict
383/// class the bind arm surfaces on race with a sibling pool controller,
384/// a `resourceVersion` precondition slot when the pool controller
385/// stamps generation-fenced binds) lands at THIS ONE substrate primitive
386/// (or at [`apply_patch_params`] on the params sub-axis) and every
387/// downstream named-merge writer inherits the upgrade mechanically.
388///
389/// Directly benefits the P3 kenshi-runner library lift (any test-Job
390/// controller that stamps a named-merge overlay on its owning Process
391/// — a suite-progress annotation, a per-run bind edit — rides through
392/// the same primitive as the pool-reconciler's bind + release arms) and
393/// the P5 shigoto Dag refactor (any RecordingJob that stamps a
394/// per-instance-named merge edit on a phase transition, rather than
395/// through the [`crate::patch::apply`] SSA path or the anonymous
396/// [`merge`] path, rides through this substrate corner rather than
397/// hand-authoring the two-link chain a third time).
398///
399/// The bound relaxation `K::DynamicType: Default` is NOT required here
400/// (matching [`apply`]'s posture, differing from [`merge`] /
401/// [`merge_status`]) so a future [`Api<DynamicObject>`] consumer of the
402/// named-merge corner rides the same primitive as the current
403/// concrete-`Api<Process>` consumers. `Api::patch` itself needs only
404/// `K: Clone + DeserializeOwned + Debug` on its own impl block; the
405/// `Default` bound on the sibling merge primitives is a legacy of their
406/// pre-lift call sites, none of which exercised DynamicObject.
407///
408/// Return-form axis: `Result<K, kube::Error>` matches `Api::patch`
409/// verbatim. Both pre-lift consumers ignore the returned `K` (the bind
410/// arm captures the `Err` for a retry decision; the release arm discards
411/// through `let _ = …`); keeping the return in the signature lets a
412/// future writer that needs the reconciled `resourceVersion` /
413/// `generation` from the same wire round-trip read it without a
414/// re-fetch.
415///
416/// Theory anchor: THEORY.md §VI.1 (generation over composition — the
417/// two-link `apply_patch_params(<mgr>) + api.patch(name, &pp,
418/// &Patch::Merge(&body))` chain recurred at 2 hand-authored sites past
419/// the ★★ PRIME-DIRECTIVE ≥ 2 duplication trigger inside one workspace
420/// crate, and is lifted onto ONE substrate owner here, closing the
421/// (Patch-strategy × PatchParams-posture) matrix's remaining hand-
422/// authored corner). THEORY.md §II.1 invariant 5 (composition preserves
423/// proofs — the pin block below binds the `Patch::Merge` posture + the
424/// [`apply_patch_params`] pass-through + the byte-identical parity with
425/// the pre-lift two-link chain, so a regression that drifts any surface
426/// surfaces here rather than as silent named-merge writer skew across
427/// the two pool-reconciler callsites).
428pub async fn merge_as<K, B>(
429 api: &Api<K>,
430 name: &str,
431 field_manager: &str,
432 body: &B,
433) -> Result<K, kube::Error>
434where
435 K: Resource + DeserializeOwned + Clone + Debug,
436 B: Serialize + Debug + ?Sized,
437{
438 let pp = apply_patch_params(field_manager);
439 api.patch(name, &pp, &Patch::Merge(body)).await
440}
441
442/// Compose the merge-patch wire body `{"spec": {"suspended": <bool>}}` — the
443/// SIGSTOP/SIGCONT-driven suspend/resume shape both
444/// `SignalEffect::Suspend` and `SignalEffect::Resume` arms of
445/// `tatara-reconciler::signals::consume_effect` stamp on the Process spec.
446///
447/// Both arms compose through this ONE substrate owner and hand the produced
448/// body straight to [`merge`]; pre-lift each arm restated `json!({ "spec":
449/// { "suspended": <bool> } })` verbatim at its callsite (both are named in
450/// the `merge` docstring's six-consumer inventory above). Two hand-authored
451/// restatements past the ★★ PRIME-DIRECTIVE ≥ 2 duplication trigger; post-
452/// lift a future addition to the suspend/resume wire body (a `by:` slot
453/// naming the signal source, a `suspendedAt:` transition timestamp, a
454/// symmetry gate that refuses conflicting suspend + resume overlays, a
455/// version-tagged wrap for a `spec.suspend.v2` migration) lands at THIS
456/// function and both arms inherit the upgrade mechanically.
457///
458/// The `bool` argument matches the pre-lift call sites' spelling exactly
459/// (`true` at the Suspend arm, `false` at the Resume arm) — the primitive
460/// does not force one polarity, because the merge-patch body itself is
461/// symmetric between the two arms and the shape stays load-bearing at
462/// both polarities.
463///
464/// Sibling to [`merge_status_body`] on the (wire-endpoint × wrap-posture)
465/// pair: [`merge_status_body`] owns the `/status` subresource wrap;
466/// this primitive owns one specific `{"spec": …}` primary-resource wrap
467/// (the suspend/resume one) — a body composer, not a wire-dispatcher, so
468/// consumers still hand the produced body to [`merge`] for the round-
469/// trip.
470///
471/// Theory anchor: THEORY.md §VI.1 (generation over composition — the
472/// two-arm `json!({ "spec": { "suspended": <bool> } })` restatement is
473/// lifted onto ONE substrate composer). THEORY.md §II.1 invariant 5
474/// (composition preserves proofs — the pin block below binds the shape
475/// at fail-before-pass-after granularity so a regression that drifts the
476/// top-level `spec` slot, the inner `suspended` slot, or the JSON bool
477/// value type at either polarity surfaces here rather than as silent
478/// signal-arm skew at the two suspend/resume callsites).
479#[must_use]
480pub fn spec_suspended_body(suspended: bool) -> serde_json::Value {
481 json!({ "spec": { "suspended": suspended } })
482}
483
484/// Compose the merge-patch wire body
485/// `{"metadata": {"annotations": {<key>: <value>}}}` — the ONE substrate
486/// owner of the single-annotation stamp / strip merge-body shape every
487/// workspace controller reaches for when it needs to publish exactly ONE
488/// operator-visible annotation on the primary resource (or strip one by
489/// stamping `Value::Null`) through the merge-patch semantics of either
490/// [`merge`] or [`apply`].
491///
492/// Pre-lift the wire-shape recurred at THREE hand-authored consumer
493/// sites across TWO active workspace crates past the ★★ PRIME-DIRECTIVE
494/// ≥ 2 duplication threshold:
495///
496/// - `tatara-reconciler::signals::ingest` — strips the
497/// `tatara.pleme.io/signal` annotation off the Process after
498/// ingestion by stamping `serde_json::Value::Null` (JSON merge patch
499/// interprets `null` as "remove key"). Dispatched through
500/// [`merge`] on the primary-resource merge-patch axis.
501/// - `tatara-reconciler::phase_machine::transition_to_releasing` —
502/// stamps the caller-observed `tatara.pleme.io/released-from`
503/// annotation with the current phase string on Attested/Failed →
504/// Releasing. Dispatched through [`apply`] on the primary-resource
505/// SSA axis (SSA `Patch::Apply` accepts the same
506/// `{"metadata": {"annotations": …}}` body shape as `Patch::Merge`
507/// — the top-level slot naming is what this composer owns).
508/// - `tatara-pool-reconciler::controller_allocation` (Release arm) —
509/// stamps the `tatara.pleme.io/return-trigger` annotation with the
510/// literal `"true"` on the member Process to nudge the Pool
511/// reconciler into taking the return path. Dispatched through the
512/// raw `Api::patch` call inside the release arm (also with
513/// [`apply_patch_params`]-composed PatchParams; the wire shape is
514/// the same `{"metadata": {"annotations": {<one key>: <one value>}}}`
515/// this composer names).
516///
517/// Post-lift each site reads `tatara_process::patch::annotation_body(
518/// <key>, <value>)` and the merge-body wire-shape composition lives at
519/// ONE substrate owner. A future normalization of the single-annotation
520/// merge-body posture (a canonicalization pass over the key spelling —
521/// a case-fold or a namespace-prefix normalization for a future annotation
522/// naming discipline; a stricter serde-failure return in place of the
523/// silent `Value::Null` fallback; a `by:` sibling slot naming the
524/// stamping controller for post-hoc audit; a version-tagged wrap for a
525/// future `metadata.v2.annotations` migration) lands at THIS ONE function
526/// and every downstream single-annotation writer inherits the upgrade
527/// mechanically. Directly benefits the P3 kenshi-runner library lift
528/// (any Job-based observer that stamps a per-suite annotation on its
529/// owning Process rides through the same composer as the strip / stamp
530/// / return-trigger family) and the P5 shigoto Dag refactor (every
531/// phase-machine RecordingJob that stamps an annotation on a transition
532/// rides through the same composer).
533///
534/// ### Value axis — `impl Serialize` accepts every pre-lift shape
535///
536/// The `value` slot is `impl Serialize` matching the discipline of
537/// [`phase_status_with`] on the extra-key axis: accepts owned or borrowed
538/// values of any serde-serialisable type without widening the signature.
539/// All three pre-lift consumer sites pass distinct value shapes and this
540/// composer serves each verbatim through `serde_json::to_value`:
541///
542/// - `serde_json::Value::Null` (signals::ingest strip) — the primitive
543/// [`serde_json::to_value`] round-trips a `Value::Null` back to
544/// `Value::Null`, which JSON merge patch interprets as "remove key".
545/// - `String` (phase_machine::transition_to_releasing) — the primitive
546/// [`serde_json::to_value`] serializes a `String` to a JSON string
547/// verbatim.
548/// - `&'static str` (controller_allocation Release arm) — the primitive
549/// [`serde_json::to_value`] serializes a `&str` to a JSON string
550/// verbatim, matching the pre-lift `"true"` literal.
551///
552/// A serialisation failure resolves to `Value::Null`, matching the
553/// existing [`phase_status_with`] primitive's posture. In practice
554/// serialisation of the shapes this composer accepts (a
555/// `serde_json::Value`, a `String`, a `&str`) never fails; the fallback
556/// is a defensive guard against a future caller passing a `T: Serialize`
557/// whose `Serialize` impl signals a runtime error.
558///
559/// ### Key axis — `&str` matches every pre-lift call form
560///
561/// The `key` slot is `&str` matching the pre-lift call forms exactly:
562/// [`crate::annotations::SIGNAL`] via `SIGNAL_ANNOTATION: &str` at
563/// signals.rs, [`crate::annotations::RELEASED_FROM`] via a `pub const:
564/// &str` at phase_machine.rs, and a `"tatara.pleme.io/return-trigger"`
565/// literal at controller_allocation.rs. `&str` accepts both the
566/// pre-existing `pub const: &str` constants in [`crate::annotations`]
567/// and inline `&'static str` literals at the same signature.
568///
569/// A future caller composing a `String` key at runtime (a per-fleet
570/// prefix, a runtime-computed annotation name) coerces via `&*key`
571/// or `key.as_str()` at the call site — the composer stays borrowed
572/// so the common const-fed path pays no allocation.
573///
574/// ### `must_use` on the return
575///
576/// The primitive exists to be handed to a wire-side write ([`merge`],
577/// [`apply`], or a raw `Api::patch` call at the pool-reconciler's
578/// release arm), not to probe the merge-body shape. `#[must_use]`
579/// keeps a caller from building the body and dropping it un-passed to
580/// a wire dispatcher.
581///
582/// Theory anchor: THEORY.md §VI.1 (generation over composition — the
583/// 3-link `json!({"metadata": {"annotations": {<key>: <value>}}})` merge-
584/// body composition recurred at 3 hand-authored sites past the ★★
585/// PRIME-DIRECTIVE ≥ 2 duplication trigger, spanning two active
586/// workspace crates, and is lifted onto ONE substrate owner here).
587/// THEORY.md §II.1 invariant 5 (composition preserves proofs — the pin
588/// block below binds the composer at fail-before-pass-after granularity,
589/// so a regression that drifts the top-level `metadata` slot, the nested
590/// `annotations` slot, the caller-passed key spelling, or the value-slot
591/// pass-through discipline surfaces HERE rather than as silent
592/// operator-facing annotation-writer skew across the three consumer
593/// sites).
594#[must_use]
595pub fn annotation_body(key: &str, value: impl Serialize) -> serde_json::Value {
596 let v = serde_json::to_value(value).unwrap_or(serde_json::Value::Null);
597 json!({
598 "metadata": {
599 "annotations": {
600 key: v,
601 }
602 }
603 })
604}
605
606#[cfg(test)]
607mod tests {
608 use super::*;
609 use serde::Serialize;
610 use serde_json::json;
611
612 // ─── merge_status_body substrate pins ───────────────────────────
613 //
614 // The pre-lift `json!({"status": <typed>})` wrap recurred at 7
615 // hand-authored sites across `tatara-pool-reconciler` (both
616 // controllers) + `tatara-reconciler::patch::patch_process_status`
617 // pre-lift. These pins bind the wire-body shape at
618 // fail-before-pass-after granularity so a regression that drifts
619 // the top-level slot key, reshapes the wrap posture, or leaks a
620 // sibling slot surfaces here rather than as silent status-write
621 // drift at every downstream controller.
622
623 #[test]
624 fn merge_status_body_wraps_typed_status_under_top_level_status_slot() {
625 #[derive(Serialize)]
626 struct S {
627 phase: &'static str,
628 reason: &'static str,
629 }
630 let body = merge_status_body(&S {
631 phase: "Bound",
632 reason: "member allocated",
633 });
634 assert_eq!(
635 body,
636 json!({ "status": { "phase": "Bound", "reason": "member allocated" } }),
637 );
638 }
639
640 #[test]
641 fn merge_status_body_top_level_key_is_exactly_status_lowercase() {
642 // Any drift on the top-level slot name (case-fold to `Status`,
643 // a substrate-side rename to `status_patch`, a version-tagged
644 // wrap like `v1alpha1_status`) breaks every status writer on
645 // the wire. This pin binds the exact spelling downstream K8s
646 // API + K8s-openapi generated types expect.
647 let body = merge_status_body(&json!({"phase": "Running"}));
648 let obj = body.as_object().expect("top-level must be a JSON object");
649 assert_eq!(obj.len(), 1, "wrap adds exactly ONE top-level slot");
650 assert!(
651 obj.contains_key("status"),
652 "top-level slot must be exactly `status` (lowercase)"
653 );
654 }
655
656 #[test]
657 fn merge_status_body_accepts_pre_serialized_json_value_verbatim() {
658 // Callers that already have a `serde_json::Value` (e.g. the
659 // existing `tatara-reconciler::patch::patch_process_status`
660 // callers that hand-build a `Value` via one of the
661 // `phase_status_*` builders) pass it directly to the primitive
662 // without re-serialization. This pin binds that pass-through
663 // shape: the wrap layer never re-encodes an already-JSON slot.
664 let pre = json!({"phase": "Attested", "phaseSince": "2026-05-01T00:00:00Z"});
665 let body = merge_status_body(&pre);
666 assert_eq!(body, json!({"status": pre}));
667 }
668
669 #[test]
670 fn merge_status_body_wraps_scalar_status_without_object_promotion() {
671 // The primitive is not "wrap into an object with a phase
672 // slot" — it is exactly "wrap into `{"status": <serialized>}`".
673 // A scalar status (unusual in practice, but permitted by the
674 // Serialize bound) rides through as the top-level `status`
675 // value verbatim.
676 let body = merge_status_body(&"Attested");
677 assert_eq!(body, json!({"status": "Attested"}));
678 }
679
680 #[test]
681 fn merge_status_body_preserves_struct_update_composition_bytewise() {
682 // The pool-reconciler `AllocationStatus { bound_pool: Some(p),
683 // ..AllocationStatus::transition(...) }` struct-update shape
684 // composes a typed value that serialize into a stable JSON
685 // shape. This pin binds a smaller-scale peer: a struct-update
686 // over a base composer produces the same JSON as the fully
687 // spelled-out struct literal.
688 #[derive(Serialize)]
689 struct Base {
690 phase: &'static str,
691 phase_since: &'static str,
692 extra: Option<&'static str>,
693 }
694 fn base() -> Base {
695 Base {
696 phase: "Queued",
697 phase_since: "2026-05-01T00:00:00Z",
698 extra: None,
699 }
700 }
701 let struct_update = Base {
702 extra: Some("pool matched"),
703 ..base()
704 };
705 let spelled_out = Base {
706 phase: "Queued",
707 phase_since: "2026-05-01T00:00:00Z",
708 extra: Some("pool matched"),
709 };
710 assert_eq!(
711 merge_status_body(&struct_update),
712 merge_status_body(&spelled_out),
713 "struct-update composition serializes byte-identically to the fully-spelled struct literal",
714 );
715 }
716
717 // ─── merge_status wire-side round-trip pin ──────────────────────
718 //
719 // Bind that the async entry composes the same wire body the pure
720 // helper does (i.e. `merge_status` delegates to
721 // `merge_status_body` verbatim rather than restating the wrap).
722 // A regression that hand-rolled the wrap inside `merge_status`
723 // (thereby drifting from `merge_status_body`'s pinned shape) would
724 // surface here.
725 #[test]
726 fn merge_status_delegates_wire_body_construction_to_merge_status_body() {
727 // The invariant this binds is a source-level one: whichever
728 // call path a caller takes (direct body-construction, or the
729 // async entry composing internally), the wire body is the same
730 // shape. We witness it by having both call sites hit the same
731 // helper. The pure helper's pins above cover the shape; this
732 // pin binds the wire-side entry does not fork.
733 let body_via_helper = merge_status_body(&json!({"phase": "Running"}));
734 // `merge_status` is `async` and needs an `Api<K>` we cannot
735 // construct here without a client — but its body composition
736 // step calls exactly `merge_status_body(status)`, so the pin
737 // above already covers the shape. This test exists to name the
738 // delegation invariant so a future refactor that inlined the
739 // wrap would need to move THIS pin's docstring first.
740 assert_eq!(body_via_helper["status"]["phase"], "Running");
741 }
742
743 // ─── apply_patch_params substrate pins ──────────────────────────
744 //
745 // The 2-link `PatchParams::apply(<mgr>).force()` chain now rides
746 // through the ONE substrate primitive [`apply_patch_params`]
747 // across THREE consumer crates: `tatara-reconciler::ssapply`
748 // (field-manager-const-bound wrapper delegating to this one),
749 // `tatara-pool-reconciler::controller_allocation` (bind + release
750 // arms, feeding a per-instance `ctx.config.field_manager` String
751 // through the pass-through slot), `tatara-export-worker::main::
752 // write_receipt` (feeding a `"tatara-export-worker"` literal
753 // through the same slot). These pins bind the primitive at
754 // fail-before-pass-after granularity so a regression that drops
755 // `.force()`, drifts the field-manager pass-through, reintroduces
756 // a hand-authored literal at any consumer, or widens the posture
757 // (auto-`dry_run`, non-`None` `field_validation`) surfaces HERE
758 // rather than as silent SSA writer skew across three workspace
759 // crates.
760
761 #[test]
762 fn apply_patch_params_binds_field_manager_pass_through_slot_verbatim() {
763 // The pass-through slot is byte-identical to the caller's
764 // `&str`: no re-encoding, no case-fold, no substitution. A
765 // regression that trimmed / normalized the manager string
766 // silently would surface here — every consumer relies on the
767 // exact spelling landing in the SSA wire request so downstream
768 // field-manager ownership queries key on the exact identity
769 // each callsite stamps.
770 let pp = apply_patch_params("tatara-reconciler");
771 assert_eq!(pp.field_manager.as_deref(), Some("tatara-reconciler"));
772
773 let pp = apply_patch_params("tatara-export-worker");
774 assert_eq!(pp.field_manager.as_deref(), Some("tatara-export-worker"));
775
776 let pp = apply_patch_params("per-shard-manager-42");
777 assert_eq!(pp.field_manager.as_deref(), Some("per-shard-manager-42"));
778 }
779
780 #[test]
781 fn apply_patch_params_stamps_force_true() {
782 // `force = true` matches the SSA `force` directive every pre-
783 // lift chain applied at every SSA writer site across the three
784 // consumer crates — every consumer is the authoritative owner
785 // of the field pathways it stamps and reclaims conflicting
786 // slots on every apply. A regression that dropped `.force()`
787 // from the primitive would silently 409-conflict at every SSA
788 // write on any field already owned by a prior field manager.
789 let pp = apply_patch_params("tatara-reconciler");
790 assert!(pp.force);
791 }
792
793 #[test]
794 fn apply_patch_params_defaults_dry_run_and_field_validation_off() {
795 // The primitive stamps ONLY the `field_manager` + `force` slots
796 // every pre-lift chain stamped — `dry_run` stays `false` and
797 // `field_validation` stays `None`. A regression that widened
798 // the primitive's slot set (auto-enabled `dry_run` during a
799 // debug pass, added a default `field_validation` mode) would
800 // silently no-op every SSA write (dry_run) or reject apply
801 // bodies previous consumers accepted (field_validation).
802 let pp = apply_patch_params("tatara-reconciler");
803 assert!(!pp.dry_run);
804 assert!(pp.field_validation.is_none());
805 }
806
807 #[test]
808 fn apply_patch_params_matches_pre_lift_hand_authored_chain_bytewise() {
809 // Byte-shape parity with the pre-lift 2-link chain at every
810 // observable slot (`field_manager`, `force`, `dry_run`,
811 // `field_validation`) at each of the three consumer crates'
812 // hand-authored spellings. A regression that reordered the
813 // chain (e.g. `apply(...).dry_run().force()` swap) or drifted
814 // any slot's wire representation lands HERE.
815 for mgr in [
816 "tatara-reconciler",
817 "tatara-export-worker",
818 "per-shard-manager-42",
819 ] {
820 let pre_lift = PatchParams::apply(mgr).force();
821 let lifted = apply_patch_params(mgr);
822 assert_eq!(lifted.field_manager, pre_lift.field_manager);
823 assert_eq!(lifted.force, pre_lift.force);
824 assert_eq!(lifted.dry_run, pre_lift.dry_run);
825 assert_eq!(
826 lifted.field_validation.is_none(),
827 pre_lift.field_validation.is_none()
828 );
829 }
830 }
831
832 // ─── merge (primary-resource) substrate pins ────────────────────
833 //
834 // The 3-link `api.patch(name, &PatchParams::default(),
835 // &Patch::Merge(&body))` chain now rides through the ONE substrate
836 // primitive [`merge`] across TWO consumer crates:
837 // `tatara-reconciler::patch::{patch_process_table_spec,
838 // apply_finalizer_transform}` + `tatara-reconciler::signals::
839 // {ingest, consume_effect (Suspend + Resume arms)}` and
840 // `tatara-closed-loop-probe::main::write_receipt_configmap`. These
841 // pins bind the primitive at fail-before-pass-after granularity so
842 // a regression that switches `Patch::Merge` for `Patch::Strategic`,
843 // drifts `PatchParams::default()` to a non-default posture (a
844 // hardcoded field manager, an auto-`dry_run`, a non-`None`
845 // `field_validation` mode), reorders the 3-arg positional slots,
846 // or hijacks the pass-through body (a hidden top-level wrap, an
847 // accidental re-encode through `serde_json::to_value` and back)
848 // surfaces HERE rather than as silent primary-resource writer skew
849 // across the six pre-lift callsites.
850 //
851 // These are source-level pins on the pure helpers the async entry
852 // composes: the wire-side round-trip needs a live `Api<K>` we
853 // cannot construct without a kube client, but the substrate's
854 // async entry is a single-expression delegation to
855 // `api.patch(name, &PatchParams::default(), &Patch::Merge(body))`,
856 // so binding each ingredient (default patch-params posture, merge-
857 // strategy selection, verbatim body pass-through) at the pure
858 // level pins every observable slot of the wire request the primitive
859 // will issue.
860
861 #[test]
862 fn merge_uses_default_patch_params_posture_no_field_manager_no_dry_run_no_force() {
863 // The primary-resource merge primitive stamps the DEFAULT
864 // `PatchParams` posture — no field_manager (merge writes are
865 // not SSA and do not participate in the field-manager
866 // ownership model), no dry_run, no force, no field_validation.
867 // A regression that swapped in a partially-populated
868 // `PatchParams` (a stray `apply(...)`, a debug-mode `dry_run`,
869 // a `field_validation` mode) would silently reshape every
870 // primary-resource merge into an SSA-adjacent or dry-run write.
871 let pp = PatchParams::default();
872 assert!(pp.field_manager.is_none(), "default has no field_manager");
873 assert!(!pp.dry_run, "default has dry_run false");
874 assert!(!pp.force, "default has force false");
875 assert!(
876 pp.field_validation.is_none(),
877 "default has no field_validation"
878 );
879 }
880
881 #[test]
882 fn merge_selects_patch_merge_strategy_not_apply_or_strategic() {
883 // The primitive dispatches through `Patch::Merge(&body)` — the
884 // JSON merge patch posture (RFC 7396) every pre-lift consumer
885 // used. A regression that selected `Patch::Apply` would inject
886 // an SSA wire request against the primary-resource endpoint
887 // (which either 415s without an `apiVersion`/`kind` slot or
888 // takes ownership away from the API server's merge
889 // reconciliation model); a regression that selected
890 // `Patch::Strategic` would reshape merge semantics for arrays
891 // of tagged sub-objects (finalizers, annotations, labels) into
892 // strategic-merge behavior that silently deduplicates entries
893 // by strategic-merge-key rather than treating the slot as a
894 // JSON scalar to overwrite.
895 let body = json!({"spec": {"suspended": true}});
896 let patch: Patch<&serde_json::Value> = Patch::Merge(&body);
897 assert!(
898 matches!(patch, Patch::Merge(_)),
899 "merge primitive dispatches through Patch::Merge, not Apply/Strategic/Json"
900 );
901 }
902
903 #[test]
904 fn merge_dispatches_body_verbatim_no_wrap_or_re_encode() {
905 // Unlike [`merge_status`] which wraps its input into
906 // `{"status": …}`, the primary-resource merge primitive is
907 // verbatim: the caller composes the full top-level shape
908 // (`{"spec": …}`, `{"metadata": {"finalizers": …}}`,
909 // `{"data": …}`) and the primitive passes it through untouched.
910 // A regression that hid an implicit wrap or re-encoded the
911 // body through `serde_json::to_value` and back would surface
912 // here — every pre-lift callsite already composed the top-
913 // level shape and delegated straight to
914 // `api.patch(..., &Patch::Merge(&body))` with no intervening
915 // transform.
916 //
917 // Sweep every top-level shape the six pre-lift consumers
918 // compose so a regression on any one lands here.
919 let spec_body = json!({"spec": {"suspended": true}});
920 let meta_body = json!({
921 "metadata": {"finalizers": ["tatara.pleme.io/process-finalizer"]},
922 });
923 let strip_body = json!({
924 "metadata": {"annotations": {"tatara.pleme.io/signal": serde_json::Value::Null}},
925 });
926 let data_body = json!({"data": {"receipt.json": "{...}"}});
927 let spec_next_body = json!({"spec": {"nextSequence": 42}});
928 for body in [spec_body, meta_body, strip_body, data_body, spec_next_body] {
929 // The primitive's body-passing step is a `&Patch::Merge(body)`
930 // borrow with no intervening transform — witness that the
931 // top-level slot survives verbatim.
932 let round_trip = serde_json::to_value(&body).unwrap();
933 assert_eq!(round_trip, body, "body serializes to itself verbatim");
934 // Extract the ONE top-level slot the pre-lift caller
935 // composed; the primitive must not add a sibling slot.
936 let obj = body.as_object().expect("pre-lift bodies are JSON objects");
937 assert_eq!(
938 obj.len(),
939 1,
940 "each pre-lift consumer composed exactly ONE top-level slot"
941 );
942 }
943 }
944
945 #[test]
946 fn merge_body_composition_matches_pre_lift_signals_and_finalizer_shapes_bytewise() {
947 // Byte-shape parity against each of the six pre-lift bodies —
948 // signals::ingest strip annotation, signals::consume_effect
949 // Suspend + Resume, patch::patch_process_table_spec's
950 // `{"spec": …}` seed, patch::apply_finalizer_transform's
951 // `{"metadata": {"finalizers": …}}` seed, and
952 // closed-loop-probe::write_receipt_configmap's `{"data": …}`
953 // seed. A regression that reshaped any body composer at its
954 // callsite (case-fold slot names, added sibling debug slots)
955 // surfaces here rather than as silent behavioral drift at the
956 // wire.
957
958 // signals::ingest strip shape
959 let strip = json!({
960 "metadata": {
961 "annotations": { "tatara.pleme.io/signal": serde_json::Value::Null }
962 }
963 });
964 assert_eq!(
965 strip["metadata"]["annotations"]["tatara.pleme.io/signal"],
966 serde_json::Value::Null,
967 "strip stamps JSON null to trigger merge-patch key removal"
968 );
969
970 // signals::consume_effect Suspend shape
971 let suspend = json!({ "spec": { "suspended": true } });
972 assert_eq!(suspend["spec"]["suspended"], serde_json::Value::Bool(true));
973
974 // signals::consume_effect Resume shape
975 let resume = json!({ "spec": { "suspended": false } });
976 assert_eq!(resume["spec"]["suspended"], serde_json::Value::Bool(false));
977 }
978
979 // ─── apply (SSA primary-resource) substrate pins ───────────────
980 //
981 // The 2-link `apply_patch_params(<mgr>) + api.patch(name, &pp,
982 // &Patch::Apply(&body))` chain now rides through the ONE substrate
983 // primitive [`apply`] across TWO consumer crates:
984 // `tatara-reconciler::ssapply::apply_owned` (DynamicObject SSA
985 // writer for every rendered flux/aplicacao resource, feeding
986 // `FIELD_MANAGER` through the const wrapper),
987 // `tatara-reconciler::phase_machine::transition_to_releasing`
988 // (RELEASED_FROM annotation stamp on Attested/Failed → Releasing,
989 // same manager), and `tatara-export-worker::main::write_receipt`
990 // (receipt ConfigMap SSA apply, feeding `"tatara-export-worker"`).
991 // These pins bind the primitive at fail-before-pass-after
992 // granularity so a regression that swaps `Patch::Apply` for
993 // `Patch::Merge` (silently losing SSA ownership + reverting to
994 // merge-patch semantics), drops the [`apply_patch_params`]
995 // pass-through (silently reverting to `PatchParams::default()`
996 // and losing `.force()` + field-manager), or reorders the 3-arg
997 // positional slots surfaces HERE rather than as silent SSA
998 // writer skew across the three pre-lift callsites.
999 //
1000 // These are source-level pins on the ingredients [`apply`]
1001 // composes: the wire-side round-trip needs a live `Api<K>` we
1002 // cannot construct without a kube client, but the substrate's
1003 // async entry is a two-line body (`let pp = apply_patch_params
1004 // (field_manager); api.patch(name, &pp, &Patch::Apply(body))`),
1005 // so binding each ingredient (the [`apply_patch_params`]-composed
1006 // PatchParams shape, the `Patch::Apply` posture selection, the
1007 // verbatim body pass-through) at the pure level pins every
1008 // observable slot of the SSA wire request the primitive will
1009 // issue.
1010
1011 #[test]
1012 fn apply_composes_apply_patch_params_at_the_field_manager_slot_verbatim() {
1013 // The primitive's params-build step is
1014 // `apply_patch_params(field_manager)` — every pre-lift caller
1015 // supplied a field-manager `&str` (the reconciler's
1016 // `FIELD_MANAGER` const, the export-worker's `"tatara-export-
1017 // worker"` literal). A regression that hardcoded a manager
1018 // inside the primitive or reshaped the slot would silently
1019 // reassign field-manager ownership at every consumer's wire
1020 // request. Witness the params-side ingredient by re-composing
1021 // it through [`apply_patch_params`] here and checking the
1022 // observable slots the SSA wire path keys on.
1023 for mgr in ["tatara-reconciler", "tatara-export-worker", "per-shard-42"] {
1024 let pp = apply_patch_params(mgr);
1025 assert_eq!(pp.field_manager.as_deref(), Some(mgr));
1026 assert!(pp.force, "SSA apply must stamp force = true");
1027 assert!(!pp.dry_run, "default posture: dry_run stays false");
1028 assert!(
1029 pp.field_validation.is_none(),
1030 "default posture: field_validation stays None",
1031 );
1032 }
1033 }
1034
1035 #[test]
1036 fn apply_selects_patch_apply_strategy_not_merge_or_strategic_or_json() {
1037 // The primitive dispatches through `Patch::Apply(&body)` — the
1038 // SSA posture (JSON server-side apply) every pre-lift consumer
1039 // used to take ownership of the field pathways it stamps
1040 // (rendered-resource annotations, RELEASED_FROM marker, the
1041 // receipt ConfigMap). A regression that selected
1042 // `Patch::Merge` would silently revert to JSON merge patch
1043 // semantics — losing SSA field-manager ownership recording
1044 // and dropping the `.force()` reclaim of conflicting slots;
1045 // `Patch::Strategic` would reshape apply into strategic-merge
1046 // over the primary resource (with the same ownership loss);
1047 // `Patch::Json` would demand an RFC 6902 op list instead of
1048 // the object body every consumer composes. Witness the wire
1049 // posture selection by constructing the Patch and pattern-
1050 // matching on the variant.
1051 let body = json!({"metadata": {"annotations": {"x.io/marker": "1"}}});
1052 let patch: Patch<&serde_json::Value> = Patch::Apply(&body);
1053 assert!(
1054 matches!(patch, Patch::Apply(_)),
1055 "apply primitive dispatches through Patch::Apply, not Merge/Strategic/Json"
1056 );
1057 }
1058
1059 #[test]
1060 fn apply_dispatches_body_verbatim_no_wrap_or_re_encode() {
1061 // The SSA apply primitive is verbatim: the caller composes the
1062 // full top-level shape (a DynamicObject serialization, a
1063 // `{"metadata": {"annotations": ...}}` for the released-from
1064 // stamp, a ConfigMap serialization) and the primitive passes
1065 // it through untouched. A regression that hid an implicit
1066 // wrap (a `{"apply": <body>}` sibling slot, an `{"kind":
1067 // ..., "apiVersion": ..., "spec": <body>}` re-shape) or
1068 // re-encoded the body through `serde_json::to_value` and back
1069 // would surface here — every pre-lift callsite already
1070 // composed the full apply body and delegated straight to
1071 // `api.patch(..., &Patch::Apply(&body))` with no intervening
1072 // transform.
1073 //
1074 // Sweep every top-level shape the three pre-lift consumers
1075 // apply so a regression on any one lands here.
1076 let annotation_body = json!({
1077 "metadata": {"annotations": {"tatara.pleme.io/released-from": "Attested"}},
1078 });
1079 let configmap_body = json!({
1080 "apiVersion": "v1",
1081 "kind": "ConfigMap",
1082 "metadata": {"name": "r", "namespace": "n"},
1083 "data": {"receipt.yaml": "..."},
1084 });
1085 let dynamic_body = json!({
1086 "apiVersion": "helm.toolkit.fluxcd.io/v2",
1087 "kind": "HelmRelease",
1088 "metadata": {"name": "app", "namespace": "n"},
1089 "spec": {"chart": {"spec": {"chart": "app"}}},
1090 });
1091 for body in [annotation_body, configmap_body, dynamic_body] {
1092 let round_trip = serde_json::to_value(&body).unwrap();
1093 assert_eq!(round_trip, body, "body serializes to itself verbatim");
1094 let obj = body.as_object().expect("pre-lift bodies are JSON objects");
1095 assert!(!obj.is_empty(), "pre-lift bodies carry at least one slot");
1096 }
1097 }
1098
1099 #[test]
1100 fn apply_params_match_pre_lift_hand_authored_chain_bytewise() {
1101 // Byte-shape parity between the primitive's internal params
1102 // composition and the pre-lift `PatchParams::apply(<mgr>)
1103 // .force()` chain every consumer restated verbatim. A
1104 // regression that reordered the chain (`.force().apply(...)`
1105 // swap) or widened the posture inside the primitive would
1106 // surface HERE rather than at the wire.
1107 for mgr in ["tatara-reconciler", "tatara-export-worker"] {
1108 let pre_lift = PatchParams::apply(mgr).force();
1109 let lifted = apply_patch_params(mgr);
1110 assert_eq!(lifted.field_manager, pre_lift.field_manager);
1111 assert_eq!(lifted.force, pre_lift.force);
1112 assert_eq!(lifted.dry_run, pre_lift.dry_run);
1113 assert_eq!(
1114 lifted.field_validation.is_none(),
1115 pre_lift.field_validation.is_none(),
1116 );
1117 }
1118 }
1119
1120 // ─── spec_suspended_body substrate pins ─────────────────────────
1121 //
1122 // The pre-lift `json!({ "spec": { "suspended": <bool> } })`
1123 // restatement recurred at TWO hand-authored sites in
1124 // `tatara-reconciler::signals::consume_effect` (Suspend arm feeding
1125 // `true`, Resume arm feeding `false`) past the ★★ PRIME-DIRECTIVE
1126 // ≥ 2 duplication threshold. These pins bind the composer at fail-
1127 // before-pass-after granularity so a regression that drifts the
1128 // top-level `spec` slot (case-fold to `Spec`, verbose rename to
1129 // `spec_patch`), the inner `suspended` slot (camelCase drift to
1130 // `Suspended`, alias rename to `paused`), the JSON bool value type
1131 // (accidental promotion to `"true"` / `"false"` strings), or the
1132 // wrap posture (a `{"metadata": {...}}` sibling slot slipping in at
1133 // the top-level) surfaces HERE rather than as silent signal-arm
1134 // skew across the two hand-authored suspend/resume callsites.
1135
1136 #[test]
1137 fn spec_suspended_body_wraps_true_under_spec_suspended_slot() {
1138 let body = spec_suspended_body(true);
1139 assert_eq!(body, json!({ "spec": { "suspended": true } }));
1140 }
1141
1142 #[test]
1143 fn spec_suspended_body_wraps_false_under_spec_suspended_slot() {
1144 let body = spec_suspended_body(false);
1145 assert_eq!(body, json!({ "spec": { "suspended": false } }));
1146 }
1147
1148 #[test]
1149 fn spec_suspended_body_top_level_slot_is_exactly_spec_lowercase() {
1150 // Any drift on the top-level slot name (case-fold to `Spec`, a
1151 // substrate-side rename to `spec_patch`, a version-tagged wrap
1152 // like `v1alpha1_spec`) breaks the merge-patch on the wire.
1153 // This pin binds the exact spelling downstream K8s API + the
1154 // Process CRD's `.spec.suspended` field path expect.
1155 for value in [true, false] {
1156 let body = spec_suspended_body(value);
1157 let obj = body.as_object().expect("top-level must be a JSON object");
1158 assert_eq!(obj.len(), 1, "wrap adds exactly ONE top-level slot");
1159 assert!(
1160 obj.contains_key("spec"),
1161 "top-level slot must be exactly `spec` (lowercase)"
1162 );
1163 }
1164 }
1165
1166 #[test]
1167 fn spec_suspended_body_inner_slot_is_exactly_suspended_lowercase() {
1168 // Any drift on the inner slot name (camelCase to `Suspended`, a
1169 // rename to `paused`, a version-tagged rename to `suspend_v2`)
1170 // breaks the merge-patch: the K8s API silently applies the wrong
1171 // field and the reconciler's suspend gate never fires.
1172 for value in [true, false] {
1173 let body = spec_suspended_body(value);
1174 let spec = body["spec"]
1175 .as_object()
1176 .expect("inner `spec` must be a JSON object");
1177 assert_eq!(
1178 spec.len(),
1179 1,
1180 "inner spec carries exactly ONE slot (`suspended`)"
1181 );
1182 assert!(
1183 spec.contains_key("suspended"),
1184 "inner slot must be exactly `suspended` (lowercase)"
1185 );
1186 }
1187 }
1188
1189 #[test]
1190 fn spec_suspended_body_inner_value_is_json_bool_not_string() {
1191 // Accidental promotion of the bool to a `"true"` / `"false"`
1192 // JSON string would silently 400 on the wire (schema validation
1193 // rejects a string on a bool field) or silently deserialize as
1194 // `Default::default()` on the field, breaking the suspend gate.
1195 assert_eq!(
1196 spec_suspended_body(true)["spec"]["suspended"],
1197 serde_json::Value::Bool(true),
1198 );
1199 assert_eq!(
1200 spec_suspended_body(false)["spec"]["suspended"],
1201 serde_json::Value::Bool(false),
1202 );
1203 }
1204
1205 #[test]
1206 fn spec_suspended_body_matches_pre_lift_hand_authored_shape_bytewise() {
1207 // Byte-shape parity with the pre-lift 2-site `json!({ "spec": {
1208 // "suspended": <bool> } })` block that both `SignalEffect::
1209 // Suspend` (true polarity) and `SignalEffect::Resume` (false
1210 // polarity) arms restated pre-lift. A regression that reshaped
1211 // either polarity would drift here rather than at the wire.
1212 for value in [true, false] {
1213 let composed = spec_suspended_body(value);
1214 let hand_authored = json!({ "spec": { "suspended": value } });
1215 assert_eq!(
1216 composed, hand_authored,
1217 "spec_suspended_body({value}) must be byte-identical to the pre-lift `json!` block",
1218 );
1219 }
1220 }
1221
1222 // ─── annotation_body substrate pins ─────────────────────────────
1223 //
1224 // The pre-lift `json!({"metadata": {"annotations": {<key>: <value>}}})`
1225 // merge-body composition recurred at THREE hand-authored consumer
1226 // sites across TWO active workspace crates past the ★★ PRIME-
1227 // DIRECTIVE ≥ 2 duplication threshold: `tatara-reconciler::signals::
1228 // ingest` (Null-value strip of the SIGNAL annotation), `tatara-
1229 // reconciler::phase_machine::transition_to_releasing` (String-value
1230 // stamp of the RELEASED_FROM annotation), and `tatara-pool-
1231 // reconciler::controller_allocation` Release arm (&str-value stamp
1232 // of the return-trigger annotation). These pins bind the composer
1233 // at fail-before-pass-after granularity so a regression that drifts
1234 // the top-level `metadata` slot (case-fold to `Metadata`, alias
1235 // rename to `meta`, version-tagged wrap like `v1_metadata`), the
1236 // nested `annotations` slot (camelCase drift to `Annotations`,
1237 // rename to `annotationMap`, a stray sibling like `labels`
1238 // leaking in), the caller-passed key spelling (silent trimming,
1239 // case-fold, per-key allow-list gate), or the value-slot pass-
1240 // through (accidental promotion of `Value::Null` to
1241 // `Value::String("null")` breaking the JSON-merge-patch strip
1242 // semantics; an over-eager `to_value` re-encoding a `Value` argument
1243 // through a `String` wrap; the fallback silently promoting a
1244 // Serialize-failure to a non-null sentinel) surfaces HERE rather
1245 // than as silent operator-facing annotation-writer skew across the
1246 // three consumer sites.
1247
1248 #[test]
1249 fn annotation_body_wraps_null_value_for_merge_patch_strip_semantics() {
1250 // Byte-shape parity witness against the `signals::ingest` pre-
1251 // lift strip block (`json!({"metadata": {"annotations":
1252 // {SIGNAL_ANNOTATION: serde_json::Value::Null}}})`) — passing
1253 // `Value::Null` at the value slot round-trips through
1254 // `serde_json::to_value` to a `Value::Null` in the composed
1255 // body, so the K8s API server's JSON-merge-patch semantics
1256 // interpret it as "remove key". A regression that promoted the
1257 // null to a `"null"` string, dropped the slot entirely, or
1258 // reshaped the null through an intermediate wrapper would
1259 // silently un-strip every signal annotation post-ingestion.
1260 let body = annotation_body("tatara.pleme.io/signal", serde_json::Value::Null);
1261 assert_eq!(
1262 body,
1263 json!({
1264 "metadata": {
1265 "annotations": { "tatara.pleme.io/signal": serde_json::Value::Null }
1266 }
1267 }),
1268 );
1269 assert_eq!(
1270 body["metadata"]["annotations"]["tatara.pleme.io/signal"],
1271 serde_json::Value::Null,
1272 "value at the caller-passed key rides through as JSON null verbatim",
1273 );
1274 }
1275
1276 #[test]
1277 fn annotation_body_wraps_string_value_for_merge_patch_stamp_semantics() {
1278 // Byte-shape parity witness against the `phase_machine::
1279 // transition_to_releasing` pre-lift stamp block (`json!(
1280 // {"metadata": {"annotations": {RELEASED_FROM: gate}}})` where
1281 // `gate: String` is the current phase spelling) — passing an
1282 // owned `String` at the value slot round-trips through
1283 // `serde_json::to_value` to a JSON string in the composed body.
1284 // A regression that dropped the String's ownership or reshaped
1285 // it through a wrapper would silently drift the stamped value.
1286 let body = annotation_body("tatara.pleme.io/released-from", String::from("Attested"));
1287 assert_eq!(
1288 body,
1289 json!({
1290 "metadata": {
1291 "annotations": { "tatara.pleme.io/released-from": "Attested" }
1292 }
1293 }),
1294 );
1295 assert_eq!(
1296 body["metadata"]["annotations"]["tatara.pleme.io/released-from"],
1297 serde_json::Value::String("Attested".to_string()),
1298 "String value rides through as JSON string verbatim",
1299 );
1300 }
1301
1302 #[test]
1303 fn annotation_body_wraps_str_literal_value_for_return_trigger_stamp() {
1304 // Byte-shape parity witness against the `controller_allocation`
1305 // Release-arm pre-lift stamp block (`json!({"metadata":
1306 // {"annotations": {"tatara.pleme.io/return-trigger": "true"}}})`)
1307 // — passing a `&'static str` literal at the value slot round-
1308 // trips through `serde_json::to_value` to a JSON string in the
1309 // composed body, matching the pre-lift shape byte-identically.
1310 let body = annotation_body("tatara.pleme.io/return-trigger", "true");
1311 assert_eq!(
1312 body,
1313 json!({
1314 "metadata": {
1315 "annotations": { "tatara.pleme.io/return-trigger": "true" }
1316 }
1317 }),
1318 );
1319 }
1320
1321 #[test]
1322 fn annotation_body_top_level_slot_is_exactly_metadata_lowercase() {
1323 // Any drift on the top-level slot name (case-fold to `Metadata`,
1324 // an alias rename to `meta`, a version-tagged wrap like
1325 // `v1_metadata`) breaks the merge-patch on the wire: the K8s
1326 // API server silently applies to a sibling field the CRD does
1327 // not define, and the operator sees the annotation never
1328 // appear. This pin binds the exact spelling the K8s API server
1329 // + every generated openapi type expect.
1330 let body = annotation_body("k", "v");
1331 let obj = body.as_object().expect("top-level must be a JSON object");
1332 assert_eq!(obj.len(), 1, "wrap adds exactly ONE top-level slot");
1333 assert!(
1334 obj.contains_key("metadata"),
1335 "top-level slot must be exactly `metadata` (lowercase)"
1336 );
1337 }
1338
1339 #[test]
1340 fn annotation_body_nested_slot_is_exactly_annotations_lowercase() {
1341 // Any drift on the nested slot name (camelCase to `Annotations`,
1342 // an alias rename to `annotationMap`, a stray sibling like
1343 // `labels` leaking in) breaks the merge-patch: the K8s API
1344 // silently applies to a wrong field. This pin binds the exact
1345 // spelling downstream metadata handlers expect and guards
1346 // against a sibling-slot leak inside the metadata wrap.
1347 let body = annotation_body("k", "v");
1348 let meta = body["metadata"]
1349 .as_object()
1350 .expect("nested metadata must be a JSON object");
1351 assert_eq!(
1352 meta.len(),
1353 1,
1354 "metadata carries exactly ONE nested slot (`annotations`) — no `labels` / `finalizers` sibling leaks"
1355 );
1356 assert!(
1357 meta.contains_key("annotations"),
1358 "nested slot must be exactly `annotations` (lowercase)"
1359 );
1360 }
1361
1362 #[test]
1363 fn annotation_body_preserves_caller_key_verbatim_no_trim_or_case_fold() {
1364 // The `key` argument is stamped byte-identically as the inner
1365 // JSON slot name: no trimming of whitespace-adjacent chars, no
1366 // case-fold of any segment (a `tatara.pleme.io/RELEASED-from`
1367 // caller would land on the wire exactly that way), no per-key
1368 // allow-list gate that silently drops "unknown" annotations.
1369 // Sweep across every pre-lift caller's key spelling so a
1370 // regression that added a canonicalization pass surfaces here
1371 // rather than as a silent annotation drop at any downstream
1372 // writer.
1373 for key in [
1374 "tatara.pleme.io/signal",
1375 "tatara.pleme.io/released-from",
1376 "tatara.pleme.io/return-trigger",
1377 "custom-fleet.example.com/opaque",
1378 "SCREAMING.CASE/PRESERVED",
1379 ] {
1380 let body = annotation_body(key, "v");
1381 let annotations = body["metadata"]["annotations"]
1382 .as_object()
1383 .expect("annotations must be a JSON object");
1384 assert_eq!(
1385 annotations.len(),
1386 1,
1387 "annotations carries exactly ONE key ({key}) — no synthetic sibling leaks",
1388 );
1389 assert!(
1390 annotations.contains_key(key),
1391 "annotations key must be exactly `{key}` verbatim (no trim / case-fold / allow-list gate)",
1392 );
1393 }
1394 }
1395
1396 #[test]
1397 fn annotation_body_matches_pre_lift_hand_authored_shapes_bytewise() {
1398 // Byte-shape parity witness against all THREE pre-lift consumer
1399 // sites' hand-authored blocks — the signals::ingest strip
1400 // (Null value), the phase_machine::transition_to_releasing
1401 // stamp (String value), and the controller_allocation Release-
1402 // arm return-trigger (&str value). A regression that reshaped
1403 // ANY site's byte-shape at the composer surfaces HERE rather
1404 // than at the wire.
1405 //
1406 // Sweep three representative (key, value) tuples matching the
1407 // three pre-lift call forms.
1408 let signal_strip = annotation_body("tatara.pleme.io/signal", serde_json::Value::Null);
1409 assert_eq!(
1410 signal_strip,
1411 json!({
1412 "metadata": {
1413 "annotations": { "tatara.pleme.io/signal": serde_json::Value::Null }
1414 }
1415 }),
1416 "signals::ingest strip byte-shape",
1417 );
1418
1419 let released_stamp =
1420 annotation_body("tatara.pleme.io/released-from", String::from("Running"));
1421 assert_eq!(
1422 released_stamp,
1423 json!({
1424 "metadata": {
1425 "annotations": { "tatara.pleme.io/released-from": "Running" }
1426 }
1427 }),
1428 "phase_machine::transition_to_releasing stamp byte-shape",
1429 );
1430
1431 let return_trigger = annotation_body("tatara.pleme.io/return-trigger", "true");
1432 assert_eq!(
1433 return_trigger,
1434 json!({
1435 "metadata": {
1436 "annotations": { "tatara.pleme.io/return-trigger": "true" }
1437 }
1438 }),
1439 "controller_allocation Release-arm return-trigger byte-shape",
1440 );
1441 }
1442
1443 #[test]
1444 fn annotation_body_accepts_serde_json_value_at_value_slot_without_double_wrap() {
1445 // Callers that already have a `serde_json::Value` (e.g. a
1446 // `Value::String` or `Value::Number` computed upstream via a
1447 // typed derivation) pass it directly through `impl Serialize`
1448 // without a double-wrap. A regression that re-encoded a
1449 // `Value` argument through a `String` wrap (silently producing
1450 // `Value::String("\"stamped\"")` — a JSON-encoded string of a
1451 // JSON-encoded string) would surface HERE.
1452 let pre = serde_json::Value::String("stamped".to_string());
1453 let body = annotation_body("k.io/v", pre);
1454 assert_eq!(
1455 body["metadata"]["annotations"]["k.io/v"],
1456 serde_json::Value::String("stamped".to_string()),
1457 "pre-serialized Value rides through without a double-wrap",
1458 );
1459 }
1460
1461 // ─── merge_as (named primary-resource merge) substrate pins ─────
1462 //
1463 // The two-link `apply_patch_params(<mgr>) + api.patch(name, &pp,
1464 // &Patch::Merge(&body))` chain now rides through the ONE substrate
1465 // primitive [`merge_as`] across the two consumer sites in
1466 // `tatara-pool-reconciler::controller_allocation` (bind arm's
1467 // `spec.lifetime + metadata.annotations` compound edit; release
1468 // arm's single `metadata.annotations.<return-trigger>` edit). These
1469 // pins bind the primitive at fail-before-pass-after granularity so
1470 // a regression that swaps `Patch::Merge` for `Patch::Apply` (silently
1471 // reshaping merge semantics into SSA ownership reconciliation),
1472 // swaps `Patch::Merge` for `Patch::Strategic` (silently reshaping
1473 // scalar merges into strategic-merge deduplication over
1474 // strategic-merge-keyed arrays), drops the [`apply_patch_params`]
1475 // pass-through (silently reverting to `PatchParams::default()` and
1476 // erasing the field-manager attribution downstream `managedFields`
1477 // audits key on), or reorders the 3-arg positional slots surfaces
1478 // HERE rather than as silent named-merge writer skew across the two
1479 // pool-reconciler callsites.
1480 //
1481 // Source-level pins on the ingredients [`merge_as`] composes: the
1482 // wire-side round-trip needs a live `Api<K>` we cannot construct
1483 // without a kube client, but the substrate's async entry is a
1484 // two-line body (`let pp = apply_patch_params(field_manager);
1485 // api.patch(name, &pp, &Patch::Merge(body))`), so binding each
1486 // ingredient (the [`apply_patch_params`]-composed PatchParams
1487 // shape, the `Patch::Merge` posture selection, the verbatim body
1488 // pass-through) at the pure level pins every observable slot of
1489 // the wire request the primitive will issue.
1490
1491 #[test]
1492 fn merge_as_composes_apply_patch_params_at_the_field_manager_slot_verbatim() {
1493 // The primitive's params-build step is
1494 // `apply_patch_params(field_manager)` — every pre-lift caller
1495 // supplied a field-manager `&str` (the pool-reconciler's
1496 // `ctx.config.field_manager` per-instance String). A regression
1497 // that hardcoded a manager inside the primitive or reshaped
1498 // the slot would silently reassign field-manager attribution
1499 // at every consumer's wire request. Witness the params-side
1500 // ingredient by re-composing it through [`apply_patch_params`]
1501 // here and checking the observable slots the wire path keys on.
1502 for mgr in [
1503 "tatara-pool-reconciler",
1504 "per-shard-pool-reconciler-42",
1505 "tatara-reconciler",
1506 ] {
1507 let pp = apply_patch_params(mgr);
1508 assert_eq!(pp.field_manager.as_deref(), Some(mgr));
1509 assert!(pp.force, "named-merge must stamp force = true");
1510 assert!(!pp.dry_run, "default posture: dry_run stays false");
1511 assert!(
1512 pp.field_validation.is_none(),
1513 "default posture: field_validation stays None",
1514 );
1515 }
1516 }
1517
1518 #[test]
1519 fn merge_as_selects_patch_merge_strategy_not_apply_or_strategic_or_json() {
1520 // The primitive dispatches through `Patch::Merge(&body)` — the
1521 // JSON merge patch posture (RFC 7396) both pre-lift consumers
1522 // used. A regression that selected `Patch::Apply` would silently
1523 // reshape the pool-reconciler's bind + release edits into SSA
1524 // ownership reconciliation (a different conflict-resolution
1525 // model than the pre-lift wire behavior); `Patch::Strategic`
1526 // would reshape merges over `metadata.annotations` /
1527 // `spec.lifetime` sub-objects with strategic-merge semantics
1528 // (silently deduplicating annotation entries by
1529 // strategic-merge-key rather than treating the map as JSON to
1530 // overwrite); `Patch::Json` would demand an RFC 6902 op list
1531 // instead of the object body both consumers compose. Witness
1532 // the wire posture selection by constructing the Patch and
1533 // pattern-matching on the variant.
1534 let body = json!({"metadata": {"annotations": {"x.io/marker": "1"}}});
1535 let patch: Patch<&serde_json::Value> = Patch::Merge(&body);
1536 assert!(
1537 matches!(patch, Patch::Merge(_)),
1538 "merge_as primitive dispatches through Patch::Merge, not Apply/Strategic/Json"
1539 );
1540 }
1541
1542 #[test]
1543 fn merge_as_dispatches_body_verbatim_no_wrap_or_re_encode() {
1544 // The named-merge primitive is verbatim: the caller composes
1545 // the full top-level shape (the bind arm's compound
1546 // `{"spec": {"lifetime": …}, "metadata": {"annotations": …}}`,
1547 // the release arm's [`annotation_body`]-composed
1548 // `{"metadata": {"annotations": {<return-trigger>: "true"}}}`)
1549 // and the primitive passes it through untouched. A regression
1550 // that hid an implicit wrap or re-encoded the body through
1551 // `serde_json::to_value` and back would surface here — both
1552 // pre-lift callsites already composed the full top-level shape
1553 // and delegated straight to `api.patch(..., &Patch::Merge(&body))`
1554 // with no intervening transform.
1555 let bind_body = json!({
1556 "spec": {"lifetime": {"ephemeral": {"ttl": "1h"}}},
1557 "metadata": {"annotations": {
1558 "tatara.pleme.io/requestor": "ns/name",
1559 "tatara.pleme.io/allocation": "alloc-1",
1560 "tatara.pleme.io/requestor-kind": "GitHubPullRequest",
1561 }},
1562 });
1563 let release_body = annotation_body("tatara.pleme.io/return-trigger", "true");
1564 for body in [bind_body, release_body] {
1565 let round_trip = serde_json::to_value(&body).unwrap();
1566 assert_eq!(round_trip, body, "body serializes to itself verbatim");
1567 let obj = body.as_object().expect("pre-lift bodies are JSON objects");
1568 assert!(!obj.is_empty(), "pre-lift bodies carry at least one slot");
1569 }
1570 }
1571
1572 #[test]
1573 fn merge_as_params_match_pre_lift_hand_authored_chain_bytewise() {
1574 // Byte-shape parity between the primitive's internal params
1575 // composition and the pre-lift `PatchParams::apply(<mgr>)
1576 // .force()` chain both consumers restated verbatim. A
1577 // regression that reordered the chain (`.force().apply(...)`
1578 // swap) or widened the posture inside the primitive would
1579 // surface HERE rather than at the wire.
1580 for mgr in ["tatara-pool-reconciler", "per-shard-mgr"] {
1581 let pre_lift = PatchParams::apply(mgr).force();
1582 let lifted = apply_patch_params(mgr);
1583 assert_eq!(lifted.field_manager, pre_lift.field_manager);
1584 assert_eq!(lifted.force, pre_lift.force);
1585 assert_eq!(lifted.dry_run, pre_lift.dry_run);
1586 assert_eq!(
1587 lifted.field_validation.is_none(),
1588 pre_lift.field_validation.is_none(),
1589 );
1590 }
1591 }
1592
1593 #[test]
1594 fn merge_as_closes_patch_strategy_by_patch_params_matrix_at_the_named_merge_corner() {
1595 // Corner-partition pin — the four primitives [`merge`],
1596 // [`apply`], [`merge_status`], [`merge_as`] partition the
1597 // (Patch-strategy × PatchParams-posture × wire-endpoint) matrix
1598 // the workspace's wire-side patch family stamps. This pin
1599 // witnesses that [`merge_as`] stamps EXACTLY the
1600 // (Patch::Merge × apply_patch_params × primary-resource)
1601 // corner — distinct from [`merge`]'s
1602 // (Patch::Merge × PatchParams::default × primary-resource)
1603 // corner and from [`apply`]'s
1604 // (Patch::Apply × apply_patch_params × primary-resource)
1605 // corner. A regression that collapsed any two corners onto
1606 // ONE primitive (e.g. `merge_as` accidentally routing through
1607 // `apply`'s `Patch::Apply` posture, or reverting to
1608 // `PatchParams::default()` and drifting into `merge`'s corner)
1609 // would break the partition and surface HERE rather than as
1610 // silent field-manager attribution loss or SSA-vs-merge
1611 // semantics drift at the two pool-reconciler callsites.
1612
1613 // Corner witness: named-merge params ≠ default params
1614 let named = apply_patch_params("mgr");
1615 let default = PatchParams::default();
1616 assert_ne!(
1617 named.field_manager, default.field_manager,
1618 "merge_as's params carry a field manager; merge's do not — the corner distinction is load-bearing"
1619 );
1620 assert_ne!(
1621 named.force, default.force,
1622 "merge_as's params stamp force = true; merge's do not — the corner distinction is load-bearing"
1623 );
1624
1625 // Corner witness: merge strategy ≠ apply strategy at the same params
1626 let body = json!({"metadata": {"annotations": {"k": "v"}}});
1627 let merge_patch: Patch<&serde_json::Value> = Patch::Merge(&body);
1628 let apply_patch: Patch<&serde_json::Value> = Patch::Apply(&body);
1629 assert!(
1630 matches!(merge_patch, Patch::Merge(_)),
1631 "merge_as dispatches Patch::Merge, distinguishing it from apply's Patch::Apply corner"
1632 );
1633 assert!(
1634 matches!(apply_patch, Patch::Apply(_)),
1635 "apply dispatches Patch::Apply, distinguishing it from merge_as's Patch::Merge corner"
1636 );
1637 }
1638}