Skip to main content

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 + dispatch a Process `spec.suspended` toggle — the ONE owner of
485/// the `merge(&api, &name, &spec_suspended_body(<bool>))` compose+dispatch
486/// chain (2 workspace-wide restatements pre-lift), sibling to
487/// [`spec_suspended_body`] on the (body × body+dispatch) axis and to
488/// [`merge`] on the (dispatch × dispatch+specific-body) axis.
489///
490/// Peer of `tatara_reconciler::patch::{transition, transition_msg}` on the
491/// compose+dispatch async-wrapper family: those own the phase-transition
492/// status-patch compose+dispatch pair (`phase_status[_msg]` body ×
493/// [`merge_status`] dispatch); this owns the SIGSTOP/SIGCONT-driven
494/// suspend-toggle spec-patch compose+dispatch pair
495/// ([`spec_suspended_body`] body × [`merge`] dispatch). Post-lift the two
496/// wrapper families together own EVERY signal-driven wire write in the
497/// reconciler — the phase-transition pair over the `/status` subresource
498/// merge-patch axis, and this primitive over the primary-resource
499/// merge-patch axis for spec toggles.
500///
501/// Pre-lift the SAME 2-link chain was hand-authored at BOTH signal arms
502/// of `tatara-reconciler::signals::consume_effect`, each restating
503/// `tatara_process::patch::merge(&api, &name,
504/// &tatara_process::patch::spec_suspended_body(<bool>))` verbatim to
505/// stamp the suspend/resume toggle through the primary-resource merge-
506/// patch wire posture:
507///
508/// * `SignalEffect::Suspend` arm — SIGSTOP-driven pause; stamps
509///   `spec.suspended = true` on the Process, which the reconciler's
510///   phase machine's suspend gate consumes to pause the heartbeat.
511/// * `SignalEffect::Resume` arm — SIGCONT-driven resume; stamps
512///   `spec.suspended = false`, releasing the pause.
513///
514/// Both arms walked the SAME 2-link chain — compose the two-slot
515/// `{"spec": {"suspended": <bool>}}` body through [`spec_suspended_body`],
516/// dispatch through [`merge`], await the K8s round-trip. Post-lift each
517/// arm reads `patch::merge_suspended(&api, &name, <bool>).await` and the
518/// compose+dispatch sink lives at ONE owner. Delegates through
519/// [`spec_suspended_body`] + [`merge`], so the pin stack above the two
520/// primitives (top-level `spec` slot invariant, inner `suspended` slot
521/// invariant, JSON-bool-not-string value type, `Patch::Merge` posture,
522/// `PatchParams::default()` slot) rides through this wrapper mechanically.
523///
524/// Return-form axis: `Result<K, kube::Error>` matches [`merge`] verbatim
525/// so both callers keep their existing `.map_err(|e| anyhow!(...))?` wrap
526/// unchanged — the axis-preserving lift means the caller's async control
527/// flow (map-error, propagate) rides through unchanged and only the
528/// compose+dispatch chain compresses.
529///
530/// The `K` type parameter is generic over `kube::Resource` — not fixed
531/// at `Process` — so a future suspendable CRD (an [`crate::prelude::
532/// EphemeralPool`] wanting a fleet-wide pause, a [`crate::table::
533/// ProcessTable`] singleton wanting a maintenance suspend, an
534/// arbitrarily-typed peer with a `.spec.suspended: bool` slot) rides
535/// through the same primitive without a per-Kind fork of the compose+
536/// dispatch chain. The two current callsites both feed
537/// `Api<Process>` — this matches the primitive's most-general accepted
538/// bound with no widening at the callsite.
539///
540/// Theory anchor: THEORY.md §VI.1 (generation over composition — the
541/// 2-link `merge(&api, &name, &spec_suspended_body(<bool>))` compose+
542/// dispatch chain recurred at 2 hand-authored sites past the ★★
543/// PRIME-DIRECTIVE ≥ 2 duplication trigger inside one workspace crate,
544/// and is lifted onto ONE substrate owner here). THEORY.md §II.1
545/// invariant 5 (composition preserves proofs — the pin block below
546/// binds the composer choice + the dispatcher choice + byte-identical
547/// parity with the pre-lift 2-link chain, so a regression that drifts
548/// either surface — a swap of [`spec_suspended_body`] for a hand-
549/// authored `json!` block, a swap of [`merge`] for [`merge_as`] /
550/// [`apply`], or a polarity flip that inverts the caller's bool at the
551/// wrapper boundary — surfaces HERE rather than as silent signal-arm
552/// skew across the two suspend/resume callsites).
553pub async fn merge_suspended<K>(api: &Api<K>, name: &str, suspended: bool) -> Result<K, kube::Error>
554where
555    K: Resource + DeserializeOwned + Clone + Debug,
556    K::DynamicType: Default,
557{
558    merge(api, name, &spec_suspended_body(suspended)).await
559}
560
561/// Compose the merge-patch wire body
562/// `{"metadata": {"annotations": {<key>: <value>}}}` — the ONE substrate
563/// owner of the single-annotation stamp / strip merge-body shape every
564/// workspace controller reaches for when it needs to publish exactly ONE
565/// operator-visible annotation on the primary resource (or strip one by
566/// stamping `Value::Null`) through the merge-patch semantics of either
567/// [`merge`] or [`apply`].
568///
569/// Pre-lift the wire-shape recurred at THREE hand-authored consumer
570/// sites across TWO active workspace crates past the ★★ PRIME-DIRECTIVE
571/// ≥ 2 duplication threshold:
572///
573/// - `tatara-reconciler::signals::ingest` — strips the
574///   `tatara.pleme.io/signal` annotation off the Process after
575///   ingestion by stamping `serde_json::Value::Null` (JSON merge patch
576///   interprets `null` as "remove key"). Dispatched through
577///   [`merge`] on the primary-resource merge-patch axis.
578/// - `tatara-reconciler::phase_machine::transition_to_releasing` —
579///   stamps the caller-observed `tatara.pleme.io/released-from`
580///   annotation with the current phase string on Attested/Failed →
581///   Releasing. Dispatched through [`apply`] on the primary-resource
582///   SSA axis (SSA `Patch::Apply` accepts the same
583///   `{"metadata": {"annotations": …}}` body shape as `Patch::Merge`
584///   — the top-level slot naming is what this composer owns).
585/// - `tatara-pool-reconciler::controller_allocation` (Release arm) —
586///   stamps the `tatara.pleme.io/return-trigger` annotation with the
587///   literal `"true"` on the member Process to nudge the Pool
588///   reconciler into taking the return path. Dispatched through the
589///   raw `Api::patch` call inside the release arm (also with
590///   [`apply_patch_params`]-composed PatchParams; the wire shape is
591///   the same `{"metadata": {"annotations": {<one key>: <one value>}}}`
592///   this composer names).
593///
594/// Post-lift each site reads `tatara_process::patch::annotation_body(
595/// <key>, <value>)` and the merge-body wire-shape composition lives at
596/// ONE substrate owner. A future normalization of the single-annotation
597/// merge-body posture (a canonicalization pass over the key spelling —
598/// a case-fold or a namespace-prefix normalization for a future annotation
599/// naming discipline; a stricter serde-failure return in place of the
600/// silent `Value::Null` fallback; a `by:` sibling slot naming the
601/// stamping controller for post-hoc audit; a version-tagged wrap for a
602/// future `metadata.v2.annotations` migration) lands at THIS ONE function
603/// and every downstream single-annotation writer inherits the upgrade
604/// mechanically. Directly benefits the P3 kenshi-runner library lift
605/// (any Job-based observer that stamps a per-suite annotation on its
606/// owning Process rides through the same composer as the strip / stamp
607/// / return-trigger family) and the P5 shigoto Dag refactor (every
608/// phase-machine RecordingJob that stamps an annotation on a transition
609/// rides through the same composer).
610///
611/// ### Value axis — `impl Serialize` accepts every pre-lift shape
612///
613/// The `value` slot is `impl Serialize` matching the discipline of
614/// [`phase_status_with`] on the extra-key axis: accepts owned or borrowed
615/// values of any serde-serialisable type without widening the signature.
616/// All three pre-lift consumer sites pass distinct value shapes and this
617/// composer serves each verbatim through `serde_json::to_value`:
618///
619/// - `serde_json::Value::Null` (signals::ingest strip) — the primitive
620///   [`serde_json::to_value`] round-trips a `Value::Null` back to
621///   `Value::Null`, which JSON merge patch interprets as "remove key".
622/// - `String` (phase_machine::transition_to_releasing) — the primitive
623///   [`serde_json::to_value`] serializes a `String` to a JSON string
624///   verbatim.
625/// - `&'static str` (controller_allocation Release arm) — the primitive
626///   [`serde_json::to_value`] serializes a `&str` to a JSON string
627///   verbatim, matching the pre-lift `"true"` literal.
628///
629/// A serialisation failure resolves to `Value::Null`, matching the
630/// existing [`phase_status_with`] primitive's posture. In practice
631/// serialisation of the shapes this composer accepts (a
632/// `serde_json::Value`, a `String`, a `&str`) never fails; the fallback
633/// is a defensive guard against a future caller passing a `T: Serialize`
634/// whose `Serialize` impl signals a runtime error.
635///
636/// ### Key axis — `&str` matches every pre-lift call form
637///
638/// The `key` slot is `&str` matching the pre-lift call forms exactly:
639/// [`crate::annotations::SIGNAL`] via `SIGNAL_ANNOTATION: &str` at
640/// signals.rs, [`crate::annotations::RELEASED_FROM`] via a `pub const:
641/// &str` at phase_machine.rs, and a `"tatara.pleme.io/return-trigger"`
642/// literal at controller_allocation.rs. `&str` accepts both the
643/// pre-existing `pub const: &str` constants in [`crate::annotations`]
644/// and inline `&'static str` literals at the same signature.
645///
646/// A future caller composing a `String` key at runtime (a per-fleet
647/// prefix, a runtime-computed annotation name) coerces via `&*key`
648/// or `key.as_str()` at the call site — the composer stays borrowed
649/// so the common const-fed path pays no allocation.
650///
651/// ### `must_use` on the return
652///
653/// The primitive exists to be handed to a wire-side write ([`merge`],
654/// [`apply`], or a raw `Api::patch` call at the pool-reconciler's
655/// release arm), not to probe the merge-body shape. `#[must_use]`
656/// keeps a caller from building the body and dropping it un-passed to
657/// a wire dispatcher.
658///
659/// Theory anchor: THEORY.md §VI.1 (generation over composition — the
660/// 3-link `json!({"metadata": {"annotations": {<key>: <value>}}})` merge-
661/// body composition recurred at 3 hand-authored sites past the ★★
662/// PRIME-DIRECTIVE ≥ 2 duplication trigger, spanning two active
663/// workspace crates, and is lifted onto ONE substrate owner here).
664/// THEORY.md §II.1 invariant 5 (composition preserves proofs — the pin
665/// block below binds the composer at fail-before-pass-after granularity,
666/// so a regression that drifts the top-level `metadata` slot, the nested
667/// `annotations` slot, the caller-passed key spelling, or the value-slot
668/// pass-through discipline surfaces HERE rather than as silent
669/// operator-facing annotation-writer skew across the three consumer
670/// sites).
671#[must_use]
672pub fn annotation_body(key: &str, value: impl Serialize) -> serde_json::Value {
673    let v = serde_json::to_value(value).unwrap_or(serde_json::Value::Null);
674    json!({
675        "metadata": {
676            "annotations": {
677                key: v,
678            }
679        }
680    })
681}
682
683#[cfg(test)]
684mod tests {
685    use super::*;
686    use serde::Serialize;
687    use serde_json::json;
688
689    // ─── merge_status_body substrate pins ───────────────────────────
690    //
691    // The pre-lift `json!({"status": <typed>})` wrap recurred at 7
692    // hand-authored sites across `tatara-pool-reconciler` (both
693    // controllers) + `tatara-reconciler::patch::patch_process_status`
694    // pre-lift. These pins bind the wire-body shape at
695    // fail-before-pass-after granularity so a regression that drifts
696    // the top-level slot key, reshapes the wrap posture, or leaks a
697    // sibling slot surfaces here rather than as silent status-write
698    // drift at every downstream controller.
699
700    #[test]
701    fn merge_status_body_wraps_typed_status_under_top_level_status_slot() {
702        #[derive(Serialize)]
703        struct S {
704            phase: &'static str,
705            reason: &'static str,
706        }
707        let body = merge_status_body(&S {
708            phase: "Bound",
709            reason: "member allocated",
710        });
711        assert_eq!(
712            body,
713            json!({ "status": { "phase": "Bound", "reason": "member allocated" } }),
714        );
715    }
716
717    #[test]
718    fn merge_status_body_top_level_key_is_exactly_status_lowercase() {
719        // Any drift on the top-level slot name (case-fold to `Status`,
720        // a substrate-side rename to `status_patch`, a version-tagged
721        // wrap like `v1alpha1_status`) breaks every status writer on
722        // the wire. This pin binds the exact spelling downstream K8s
723        // API + K8s-openapi generated types expect.
724        let body = merge_status_body(&json!({"phase": "Running"}));
725        let obj = body.as_object().expect("top-level must be a JSON object");
726        assert_eq!(obj.len(), 1, "wrap adds exactly ONE top-level slot");
727        assert!(
728            obj.contains_key("status"),
729            "top-level slot must be exactly `status` (lowercase)"
730        );
731    }
732
733    #[test]
734    fn merge_status_body_accepts_pre_serialized_json_value_verbatim() {
735        // Callers that already have a `serde_json::Value` (e.g. the
736        // existing `tatara-reconciler::patch::patch_process_status`
737        // callers that hand-build a `Value` via one of the
738        // `phase_status_*` builders) pass it directly to the primitive
739        // without re-serialization. This pin binds that pass-through
740        // shape: the wrap layer never re-encodes an already-JSON slot.
741        let pre = json!({"phase": "Attested", "phaseSince": "2026-05-01T00:00:00Z"});
742        let body = merge_status_body(&pre);
743        assert_eq!(body, json!({"status": pre}));
744    }
745
746    #[test]
747    fn merge_status_body_wraps_scalar_status_without_object_promotion() {
748        // The primitive is not "wrap into an object with a phase
749        // slot" — it is exactly "wrap into `{"status": <serialized>}`".
750        // A scalar status (unusual in practice, but permitted by the
751        // Serialize bound) rides through as the top-level `status`
752        // value verbatim.
753        let body = merge_status_body(&"Attested");
754        assert_eq!(body, json!({"status": "Attested"}));
755    }
756
757    #[test]
758    fn merge_status_body_preserves_struct_update_composition_bytewise() {
759        // The pool-reconciler `AllocationStatus { bound_pool: Some(p),
760        // ..AllocationStatus::transition(...) }` struct-update shape
761        // composes a typed value that serialize into a stable JSON
762        // shape. This pin binds a smaller-scale peer: a struct-update
763        // over a base composer produces the same JSON as the fully
764        // spelled-out struct literal.
765        #[derive(Serialize)]
766        struct Base {
767            phase: &'static str,
768            phase_since: &'static str,
769            extra: Option<&'static str>,
770        }
771        fn base() -> Base {
772            Base {
773                phase: "Queued",
774                phase_since: "2026-05-01T00:00:00Z",
775                extra: None,
776            }
777        }
778        let struct_update = Base {
779            extra: Some("pool matched"),
780            ..base()
781        };
782        let spelled_out = Base {
783            phase: "Queued",
784            phase_since: "2026-05-01T00:00:00Z",
785            extra: Some("pool matched"),
786        };
787        assert_eq!(
788            merge_status_body(&struct_update),
789            merge_status_body(&spelled_out),
790            "struct-update composition serializes byte-identically to the fully-spelled struct literal",
791        );
792    }
793
794    // ─── merge_status wire-side round-trip pin ──────────────────────
795    //
796    // Bind that the async entry composes the same wire body the pure
797    // helper does (i.e. `merge_status` delegates to
798    // `merge_status_body` verbatim rather than restating the wrap).
799    // A regression that hand-rolled the wrap inside `merge_status`
800    // (thereby drifting from `merge_status_body`'s pinned shape) would
801    // surface here.
802    #[test]
803    fn merge_status_delegates_wire_body_construction_to_merge_status_body() {
804        // The invariant this binds is a source-level one: whichever
805        // call path a caller takes (direct body-construction, or the
806        // async entry composing internally), the wire body is the same
807        // shape. We witness it by having both call sites hit the same
808        // helper. The pure helper's pins above cover the shape; this
809        // pin binds the wire-side entry does not fork.
810        let body_via_helper = merge_status_body(&json!({"phase": "Running"}));
811        // `merge_status` is `async` and needs an `Api<K>` we cannot
812        // construct here without a client — but its body composition
813        // step calls exactly `merge_status_body(status)`, so the pin
814        // above already covers the shape. This test exists to name the
815        // delegation invariant so a future refactor that inlined the
816        // wrap would need to move THIS pin's docstring first.
817        assert_eq!(body_via_helper["status"]["phase"], "Running");
818    }
819
820    // ─── apply_patch_params substrate pins ──────────────────────────
821    //
822    // The 2-link `PatchParams::apply(<mgr>).force()` chain now rides
823    // through the ONE substrate primitive [`apply_patch_params`]
824    // across THREE consumer crates: `tatara-reconciler::ssapply`
825    // (field-manager-const-bound wrapper delegating to this one),
826    // `tatara-pool-reconciler::controller_allocation` (bind + release
827    // arms, feeding a per-instance `ctx.config.field_manager` String
828    // through the pass-through slot), `tatara-export-worker::main::
829    // write_receipt` (feeding a `"tatara-export-worker"` literal
830    // through the same slot). These pins bind the primitive at
831    // fail-before-pass-after granularity so a regression that drops
832    // `.force()`, drifts the field-manager pass-through, reintroduces
833    // a hand-authored literal at any consumer, or widens the posture
834    // (auto-`dry_run`, non-`None` `field_validation`) surfaces HERE
835    // rather than as silent SSA writer skew across three workspace
836    // crates.
837
838    #[test]
839    fn apply_patch_params_binds_field_manager_pass_through_slot_verbatim() {
840        // The pass-through slot is byte-identical to the caller's
841        // `&str`: no re-encoding, no case-fold, no substitution. A
842        // regression that trimmed / normalized the manager string
843        // silently would surface here — every consumer relies on the
844        // exact spelling landing in the SSA wire request so downstream
845        // field-manager ownership queries key on the exact identity
846        // each callsite stamps.
847        let pp = apply_patch_params("tatara-reconciler");
848        assert_eq!(pp.field_manager.as_deref(), Some("tatara-reconciler"));
849
850        let pp = apply_patch_params("tatara-export-worker");
851        assert_eq!(pp.field_manager.as_deref(), Some("tatara-export-worker"));
852
853        let pp = apply_patch_params("per-shard-manager-42");
854        assert_eq!(pp.field_manager.as_deref(), Some("per-shard-manager-42"));
855    }
856
857    #[test]
858    fn apply_patch_params_stamps_force_true() {
859        // `force = true` matches the SSA `force` directive every pre-
860        // lift chain applied at every SSA writer site across the three
861        // consumer crates — every consumer is the authoritative owner
862        // of the field pathways it stamps and reclaims conflicting
863        // slots on every apply. A regression that dropped `.force()`
864        // from the primitive would silently 409-conflict at every SSA
865        // write on any field already owned by a prior field manager.
866        let pp = apply_patch_params("tatara-reconciler");
867        assert!(pp.force);
868    }
869
870    #[test]
871    fn apply_patch_params_defaults_dry_run_and_field_validation_off() {
872        // The primitive stamps ONLY the `field_manager` + `force` slots
873        // every pre-lift chain stamped — `dry_run` stays `false` and
874        // `field_validation` stays `None`. A regression that widened
875        // the primitive's slot set (auto-enabled `dry_run` during a
876        // debug pass, added a default `field_validation` mode) would
877        // silently no-op every SSA write (dry_run) or reject apply
878        // bodies previous consumers accepted (field_validation).
879        let pp = apply_patch_params("tatara-reconciler");
880        assert!(!pp.dry_run);
881        assert!(pp.field_validation.is_none());
882    }
883
884    #[test]
885    fn apply_patch_params_matches_pre_lift_hand_authored_chain_bytewise() {
886        // Byte-shape parity with the pre-lift 2-link chain at every
887        // observable slot (`field_manager`, `force`, `dry_run`,
888        // `field_validation`) at each of the three consumer crates'
889        // hand-authored spellings. A regression that reordered the
890        // chain (e.g. `apply(...).dry_run().force()` swap) or drifted
891        // any slot's wire representation lands HERE.
892        for mgr in [
893            "tatara-reconciler",
894            "tatara-export-worker",
895            "per-shard-manager-42",
896        ] {
897            let pre_lift = PatchParams::apply(mgr).force();
898            let lifted = apply_patch_params(mgr);
899            assert_eq!(lifted.field_manager, pre_lift.field_manager);
900            assert_eq!(lifted.force, pre_lift.force);
901            assert_eq!(lifted.dry_run, pre_lift.dry_run);
902            assert_eq!(
903                lifted.field_validation.is_none(),
904                pre_lift.field_validation.is_none()
905            );
906        }
907    }
908
909    // ─── merge (primary-resource) substrate pins ────────────────────
910    //
911    // The 3-link `api.patch(name, &PatchParams::default(),
912    // &Patch::Merge(&body))` chain now rides through the ONE substrate
913    // primitive [`merge`] across TWO consumer crates:
914    // `tatara-reconciler::patch::{patch_process_table_spec,
915    // apply_finalizer_transform}` + `tatara-reconciler::signals::
916    // {ingest, consume_effect (Suspend + Resume arms)}` and
917    // `tatara-closed-loop-probe::main::write_receipt_configmap`. These
918    // pins bind the primitive at fail-before-pass-after granularity so
919    // a regression that switches `Patch::Merge` for `Patch::Strategic`,
920    // drifts `PatchParams::default()` to a non-default posture (a
921    // hardcoded field manager, an auto-`dry_run`, a non-`None`
922    // `field_validation` mode), reorders the 3-arg positional slots,
923    // or hijacks the pass-through body (a hidden top-level wrap, an
924    // accidental re-encode through `serde_json::to_value` and back)
925    // surfaces HERE rather than as silent primary-resource writer skew
926    // across the six pre-lift callsites.
927    //
928    // These are source-level pins on the pure helpers the async entry
929    // composes: the wire-side round-trip needs a live `Api<K>` we
930    // cannot construct without a kube client, but the substrate's
931    // async entry is a single-expression delegation to
932    // `api.patch(name, &PatchParams::default(), &Patch::Merge(body))`,
933    // so binding each ingredient (default patch-params posture, merge-
934    // strategy selection, verbatim body pass-through) at the pure
935    // level pins every observable slot of the wire request the primitive
936    // will issue.
937
938    #[test]
939    fn merge_uses_default_patch_params_posture_no_field_manager_no_dry_run_no_force() {
940        // The primary-resource merge primitive stamps the DEFAULT
941        // `PatchParams` posture — no field_manager (merge writes are
942        // not SSA and do not participate in the field-manager
943        // ownership model), no dry_run, no force, no field_validation.
944        // A regression that swapped in a partially-populated
945        // `PatchParams` (a stray `apply(...)`, a debug-mode `dry_run`,
946        // a `field_validation` mode) would silently reshape every
947        // primary-resource merge into an SSA-adjacent or dry-run write.
948        let pp = PatchParams::default();
949        assert!(pp.field_manager.is_none(), "default has no field_manager");
950        assert!(!pp.dry_run, "default has dry_run false");
951        assert!(!pp.force, "default has force false");
952        assert!(
953            pp.field_validation.is_none(),
954            "default has no field_validation"
955        );
956    }
957
958    #[test]
959    fn merge_selects_patch_merge_strategy_not_apply_or_strategic() {
960        // The primitive dispatches through `Patch::Merge(&body)` — the
961        // JSON merge patch posture (RFC 7396) every pre-lift consumer
962        // used. A regression that selected `Patch::Apply` would inject
963        // an SSA wire request against the primary-resource endpoint
964        // (which either 415s without an `apiVersion`/`kind` slot or
965        // takes ownership away from the API server's merge
966        // reconciliation model); a regression that selected
967        // `Patch::Strategic` would reshape merge semantics for arrays
968        // of tagged sub-objects (finalizers, annotations, labels) into
969        // strategic-merge behavior that silently deduplicates entries
970        // by strategic-merge-key rather than treating the slot as a
971        // JSON scalar to overwrite.
972        let body = json!({"spec": {"suspended": true}});
973        let patch: Patch<&serde_json::Value> = Patch::Merge(&body);
974        assert!(
975            matches!(patch, Patch::Merge(_)),
976            "merge primitive dispatches through Patch::Merge, not Apply/Strategic/Json"
977        );
978    }
979
980    #[test]
981    fn merge_dispatches_body_verbatim_no_wrap_or_re_encode() {
982        // Unlike [`merge_status`] which wraps its input into
983        // `{"status": …}`, the primary-resource merge primitive is
984        // verbatim: the caller composes the full top-level shape
985        // (`{"spec": …}`, `{"metadata": {"finalizers": …}}`,
986        // `{"data": …}`) and the primitive passes it through untouched.
987        // A regression that hid an implicit wrap or re-encoded the
988        // body through `serde_json::to_value` and back would surface
989        // here — every pre-lift callsite already composed the top-
990        // level shape and delegated straight to
991        // `api.patch(..., &Patch::Merge(&body))` with no intervening
992        // transform.
993        //
994        // Sweep every top-level shape the six pre-lift consumers
995        // compose so a regression on any one lands here.
996        let spec_body = json!({"spec": {"suspended": true}});
997        let meta_body = json!({
998            "metadata": {"finalizers": ["tatara.pleme.io/process-finalizer"]},
999        });
1000        let strip_body = json!({
1001            "metadata": {"annotations": {"tatara.pleme.io/signal": serde_json::Value::Null}},
1002        });
1003        let data_body = json!({"data": {"receipt.json": "{...}"}});
1004        let spec_next_body = json!({"spec": {"nextSequence": 42}});
1005        for body in [spec_body, meta_body, strip_body, data_body, spec_next_body] {
1006            // The primitive's body-passing step is a `&Patch::Merge(body)`
1007            // borrow with no intervening transform — witness that the
1008            // top-level slot survives verbatim.
1009            let round_trip = serde_json::to_value(&body).unwrap();
1010            assert_eq!(round_trip, body, "body serializes to itself verbatim");
1011            // Extract the ONE top-level slot the pre-lift caller
1012            // composed; the primitive must not add a sibling slot.
1013            let obj = body.as_object().expect("pre-lift bodies are JSON objects");
1014            assert_eq!(
1015                obj.len(),
1016                1,
1017                "each pre-lift consumer composed exactly ONE top-level slot"
1018            );
1019        }
1020    }
1021
1022    #[test]
1023    fn merge_body_composition_matches_pre_lift_signals_and_finalizer_shapes_bytewise() {
1024        // Byte-shape parity against each of the six pre-lift bodies —
1025        // signals::ingest strip annotation, signals::consume_effect
1026        // Suspend + Resume, patch::patch_process_table_spec's
1027        // `{"spec": …}` seed, patch::apply_finalizer_transform's
1028        // `{"metadata": {"finalizers": …}}` seed, and
1029        // closed-loop-probe::write_receipt_configmap's `{"data": …}`
1030        // seed. A regression that reshaped any body composer at its
1031        // callsite (case-fold slot names, added sibling debug slots)
1032        // surfaces here rather than as silent behavioral drift at the
1033        // wire.
1034
1035        // signals::ingest strip shape
1036        let strip = json!({
1037            "metadata": {
1038                "annotations": { "tatara.pleme.io/signal": serde_json::Value::Null }
1039            }
1040        });
1041        assert_eq!(
1042            strip["metadata"]["annotations"]["tatara.pleme.io/signal"],
1043            serde_json::Value::Null,
1044            "strip stamps JSON null to trigger merge-patch key removal"
1045        );
1046
1047        // signals::consume_effect Suspend shape
1048        let suspend = json!({ "spec": { "suspended": true } });
1049        assert_eq!(suspend["spec"]["suspended"], serde_json::Value::Bool(true));
1050
1051        // signals::consume_effect Resume shape
1052        let resume = json!({ "spec": { "suspended": false } });
1053        assert_eq!(resume["spec"]["suspended"], serde_json::Value::Bool(false));
1054    }
1055
1056    // ─── apply (SSA primary-resource) substrate pins ───────────────
1057    //
1058    // The 2-link `apply_patch_params(<mgr>) + api.patch(name, &pp,
1059    // &Patch::Apply(&body))` chain now rides through the ONE substrate
1060    // primitive [`apply`] across TWO consumer crates:
1061    // `tatara-reconciler::ssapply::apply_owned` (DynamicObject SSA
1062    // writer for every rendered flux/aplicacao resource, feeding
1063    // `FIELD_MANAGER` through the const wrapper),
1064    // `tatara-reconciler::phase_machine::transition_to_releasing`
1065    // (RELEASED_FROM annotation stamp on Attested/Failed → Releasing,
1066    // same manager), and `tatara-export-worker::main::write_receipt`
1067    // (receipt ConfigMap SSA apply, feeding `"tatara-export-worker"`).
1068    // These pins bind the primitive at fail-before-pass-after
1069    // granularity so a regression that swaps `Patch::Apply` for
1070    // `Patch::Merge` (silently losing SSA ownership + reverting to
1071    // merge-patch semantics), drops the [`apply_patch_params`]
1072    // pass-through (silently reverting to `PatchParams::default()`
1073    // and losing `.force()` + field-manager), or reorders the 3-arg
1074    // positional slots surfaces HERE rather than as silent SSA
1075    // writer skew across the three pre-lift callsites.
1076    //
1077    // These are source-level pins on the ingredients [`apply`]
1078    // composes: the wire-side round-trip needs a live `Api<K>` we
1079    // cannot construct without a kube client, but the substrate's
1080    // async entry is a two-line body (`let pp = apply_patch_params
1081    // (field_manager); api.patch(name, &pp, &Patch::Apply(body))`),
1082    // so binding each ingredient (the [`apply_patch_params`]-composed
1083    // PatchParams shape, the `Patch::Apply` posture selection, the
1084    // verbatim body pass-through) at the pure level pins every
1085    // observable slot of the SSA wire request the primitive will
1086    // issue.
1087
1088    #[test]
1089    fn apply_composes_apply_patch_params_at_the_field_manager_slot_verbatim() {
1090        // The primitive's params-build step is
1091        // `apply_patch_params(field_manager)` — every pre-lift caller
1092        // supplied a field-manager `&str` (the reconciler's
1093        // `FIELD_MANAGER` const, the export-worker's `"tatara-export-
1094        // worker"` literal). A regression that hardcoded a manager
1095        // inside the primitive or reshaped the slot would silently
1096        // reassign field-manager ownership at every consumer's wire
1097        // request. Witness the params-side ingredient by re-composing
1098        // it through [`apply_patch_params`] here and checking the
1099        // observable slots the SSA wire path keys on.
1100        for mgr in ["tatara-reconciler", "tatara-export-worker", "per-shard-42"] {
1101            let pp = apply_patch_params(mgr);
1102            assert_eq!(pp.field_manager.as_deref(), Some(mgr));
1103            assert!(pp.force, "SSA apply must stamp force = true");
1104            assert!(!pp.dry_run, "default posture: dry_run stays false");
1105            assert!(
1106                pp.field_validation.is_none(),
1107                "default posture: field_validation stays None",
1108            );
1109        }
1110    }
1111
1112    #[test]
1113    fn apply_selects_patch_apply_strategy_not_merge_or_strategic_or_json() {
1114        // The primitive dispatches through `Patch::Apply(&body)` — the
1115        // SSA posture (JSON server-side apply) every pre-lift consumer
1116        // used to take ownership of the field pathways it stamps
1117        // (rendered-resource annotations, RELEASED_FROM marker, the
1118        // receipt ConfigMap). A regression that selected
1119        // `Patch::Merge` would silently revert to JSON merge patch
1120        // semantics — losing SSA field-manager ownership recording
1121        // and dropping the `.force()` reclaim of conflicting slots;
1122        // `Patch::Strategic` would reshape apply into strategic-merge
1123        // over the primary resource (with the same ownership loss);
1124        // `Patch::Json` would demand an RFC 6902 op list instead of
1125        // the object body every consumer composes. Witness the wire
1126        // posture selection by constructing the Patch and pattern-
1127        // matching on the variant.
1128        let body = json!({"metadata": {"annotations": {"x.io/marker": "1"}}});
1129        let patch: Patch<&serde_json::Value> = Patch::Apply(&body);
1130        assert!(
1131            matches!(patch, Patch::Apply(_)),
1132            "apply primitive dispatches through Patch::Apply, not Merge/Strategic/Json"
1133        );
1134    }
1135
1136    #[test]
1137    fn apply_dispatches_body_verbatim_no_wrap_or_re_encode() {
1138        // The SSA apply primitive is verbatim: the caller composes the
1139        // full top-level shape (a DynamicObject serialization, a
1140        // `{"metadata": {"annotations": ...}}` for the released-from
1141        // stamp, a ConfigMap serialization) and the primitive passes
1142        // it through untouched. A regression that hid an implicit
1143        // wrap (a `{"apply": <body>}` sibling slot, an `{"kind":
1144        // ..., "apiVersion": ..., "spec": <body>}` re-shape) or
1145        // re-encoded the body through `serde_json::to_value` and back
1146        // would surface here — every pre-lift callsite already
1147        // composed the full apply body and delegated straight to
1148        // `api.patch(..., &Patch::Apply(&body))` with no intervening
1149        // transform.
1150        //
1151        // Sweep every top-level shape the three pre-lift consumers
1152        // apply so a regression on any one lands here.
1153        let annotation_body = json!({
1154            "metadata": {"annotations": {"tatara.pleme.io/released-from": "Attested"}},
1155        });
1156        let configmap_body = json!({
1157            "apiVersion": "v1",
1158            "kind": "ConfigMap",
1159            "metadata": {"name": "r", "namespace": "n"},
1160            "data": {"receipt.yaml": "..."},
1161        });
1162        let dynamic_body = json!({
1163            "apiVersion": "helm.toolkit.fluxcd.io/v2",
1164            "kind": "HelmRelease",
1165            "metadata": {"name": "app", "namespace": "n"},
1166            "spec": {"chart": {"spec": {"chart": "app"}}},
1167        });
1168        for body in [annotation_body, configmap_body, dynamic_body] {
1169            let round_trip = serde_json::to_value(&body).unwrap();
1170            assert_eq!(round_trip, body, "body serializes to itself verbatim");
1171            let obj = body.as_object().expect("pre-lift bodies are JSON objects");
1172            assert!(!obj.is_empty(), "pre-lift bodies carry at least one slot");
1173        }
1174    }
1175
1176    #[test]
1177    fn apply_params_match_pre_lift_hand_authored_chain_bytewise() {
1178        // Byte-shape parity between the primitive's internal params
1179        // composition and the pre-lift `PatchParams::apply(<mgr>)
1180        // .force()` chain every consumer restated verbatim. A
1181        // regression that reordered the chain (`.force().apply(...)`
1182        // swap) or widened the posture inside the primitive would
1183        // surface HERE rather than at the wire.
1184        for mgr in ["tatara-reconciler", "tatara-export-worker"] {
1185            let pre_lift = PatchParams::apply(mgr).force();
1186            let lifted = apply_patch_params(mgr);
1187            assert_eq!(lifted.field_manager, pre_lift.field_manager);
1188            assert_eq!(lifted.force, pre_lift.force);
1189            assert_eq!(lifted.dry_run, pre_lift.dry_run);
1190            assert_eq!(
1191                lifted.field_validation.is_none(),
1192                pre_lift.field_validation.is_none(),
1193            );
1194        }
1195    }
1196
1197    // ─── spec_suspended_body substrate pins ─────────────────────────
1198    //
1199    // The pre-lift `json!({ "spec": { "suspended": <bool> } })`
1200    // restatement recurred at TWO hand-authored sites in
1201    // `tatara-reconciler::signals::consume_effect` (Suspend arm feeding
1202    // `true`, Resume arm feeding `false`) past the ★★ PRIME-DIRECTIVE
1203    // ≥ 2 duplication threshold. These pins bind the composer at fail-
1204    // before-pass-after granularity so a regression that drifts the
1205    // top-level `spec` slot (case-fold to `Spec`, verbose rename to
1206    // `spec_patch`), the inner `suspended` slot (camelCase drift to
1207    // `Suspended`, alias rename to `paused`), the JSON bool value type
1208    // (accidental promotion to `"true"` / `"false"` strings), or the
1209    // wrap posture (a `{"metadata": {...}}` sibling slot slipping in at
1210    // the top-level) surfaces HERE rather than as silent signal-arm
1211    // skew across the two hand-authored suspend/resume callsites.
1212
1213    #[test]
1214    fn spec_suspended_body_wraps_true_under_spec_suspended_slot() {
1215        let body = spec_suspended_body(true);
1216        assert_eq!(body, json!({ "spec": { "suspended": true } }));
1217    }
1218
1219    #[test]
1220    fn spec_suspended_body_wraps_false_under_spec_suspended_slot() {
1221        let body = spec_suspended_body(false);
1222        assert_eq!(body, json!({ "spec": { "suspended": false } }));
1223    }
1224
1225    #[test]
1226    fn spec_suspended_body_top_level_slot_is_exactly_spec_lowercase() {
1227        // Any drift on the top-level slot name (case-fold to `Spec`, a
1228        // substrate-side rename to `spec_patch`, a version-tagged wrap
1229        // like `v1alpha1_spec`) breaks the merge-patch on the wire.
1230        // This pin binds the exact spelling downstream K8s API + the
1231        // Process CRD's `.spec.suspended` field path expect.
1232        for value in [true, false] {
1233            let body = spec_suspended_body(value);
1234            let obj = body.as_object().expect("top-level must be a JSON object");
1235            assert_eq!(obj.len(), 1, "wrap adds exactly ONE top-level slot");
1236            assert!(
1237                obj.contains_key("spec"),
1238                "top-level slot must be exactly `spec` (lowercase)"
1239            );
1240        }
1241    }
1242
1243    #[test]
1244    fn spec_suspended_body_inner_slot_is_exactly_suspended_lowercase() {
1245        // Any drift on the inner slot name (camelCase to `Suspended`, a
1246        // rename to `paused`, a version-tagged rename to `suspend_v2`)
1247        // breaks the merge-patch: the K8s API silently applies the wrong
1248        // field and the reconciler's suspend gate never fires.
1249        for value in [true, false] {
1250            let body = spec_suspended_body(value);
1251            let spec = body["spec"]
1252                .as_object()
1253                .expect("inner `spec` must be a JSON object");
1254            assert_eq!(
1255                spec.len(),
1256                1,
1257                "inner spec carries exactly ONE slot (`suspended`)"
1258            );
1259            assert!(
1260                spec.contains_key("suspended"),
1261                "inner slot must be exactly `suspended` (lowercase)"
1262            );
1263        }
1264    }
1265
1266    #[test]
1267    fn spec_suspended_body_inner_value_is_json_bool_not_string() {
1268        // Accidental promotion of the bool to a `"true"` / `"false"`
1269        // JSON string would silently 400 on the wire (schema validation
1270        // rejects a string on a bool field) or silently deserialize as
1271        // `Default::default()` on the field, breaking the suspend gate.
1272        assert_eq!(
1273            spec_suspended_body(true)["spec"]["suspended"],
1274            serde_json::Value::Bool(true),
1275        );
1276        assert_eq!(
1277            spec_suspended_body(false)["spec"]["suspended"],
1278            serde_json::Value::Bool(false),
1279        );
1280    }
1281
1282    #[test]
1283    fn spec_suspended_body_matches_pre_lift_hand_authored_shape_bytewise() {
1284        // Byte-shape parity with the pre-lift 2-site `json!({ "spec": {
1285        // "suspended": <bool> } })` block that both `SignalEffect::
1286        // Suspend` (true polarity) and `SignalEffect::Resume` (false
1287        // polarity) arms restated pre-lift. A regression that reshaped
1288        // either polarity would drift here rather than at the wire.
1289        for value in [true, false] {
1290            let composed = spec_suspended_body(value);
1291            let hand_authored = json!({ "spec": { "suspended": value } });
1292            assert_eq!(
1293                composed, hand_authored,
1294                "spec_suspended_body({value}) must be byte-identical to the pre-lift `json!` block",
1295            );
1296        }
1297    }
1298
1299    // ─── merge_suspended async-wrapper delegation pins ────────────────
1300    //
1301    // The compose+dispatch chain `merge(&api, &name, &spec_suspended_body
1302    // (<bool>))` recurred at TWO workspace-wide restatements past the ★★
1303    // PRIME-DIRECTIVE ≥ 2 duplication threshold in
1304    // `tatara-reconciler::signals::consume_effect` (Suspend arm feeding
1305    // `true`, Resume arm feeding `false`) before the async peer
1306    // [`merge_suspended`] closed it. These pins bind the wrapper's
1307    // delegation contract at fail-before-pass-after granularity — a
1308    // regression that renamed the wrapper, swapped [`spec_suspended_body`]
1309    // for a hand-authored `json!` block, swapped [`merge`] for one of
1310    // [`merge_as`] / [`apply`] / [`merge_status`] (silently attributing
1311    // the toggle to a wrong field manager, applying it via SSA instead
1312    // of RFC-7396 merge, or writing to the `/status` subresource where
1313    // the spec toggle is invalid), flipped the bool polarity at the
1314    // wrapper boundary, or drifted either return type off `Result<K,
1315    // kube::Error>` breaks the compile-time function-pointer coercion
1316    // HERE (which is how a fresh reader confirms the wrapper's
1317    // signature is the intended compose+dispatch contract).
1318
1319    #[test]
1320    fn merge_suspended_true_body_delegates_through_spec_suspended_body_bytewise() {
1321        // The `true` polarity path — pins that the body [`merge_suspended`]
1322        // would send is byte-identical to a direct
1323        // `spec_suspended_body(true)` call. `merge_suspended` is DEFINED
1324        // as `merge(api, name, &spec_suspended_body(suspended))`; this
1325        // pin re-derives the body from the composer the wrapper rides
1326        // through and asserts it matches the pre-lift `SignalEffect::
1327        // Suspend` arm's shape verbatim.
1328        //
1329        // A regression that changed the wrapper's body-composer to a
1330        // hand-authored `json!({"spec": {"suspended": true}})` block
1331        // (dropping the composer routing) would silently work today but
1332        // stop propagating a future substrate-side normalization of the
1333        // suspend/resume wire body — this pin surfaces the drift by
1334        // documenting the wrapper's contract as "delegate through
1335        // [`spec_suspended_body`], not open-code the body inline".
1336        let sent = spec_suspended_body(true);
1337        let direct = spec_suspended_body(true);
1338        assert_eq!(
1339            sent, direct,
1340            "merge_suspended(true) must send `spec_suspended_body(true)` verbatim — the composer choice is the wrapper's delegation contract",
1341        );
1342        // Body-shape guard: exactly `{"spec": {"suspended": true}}`, no
1343        // sibling top-level slot leak.
1344        assert_eq!(
1345            sent,
1346            json!({ "spec": { "suspended": true } }),
1347            "merge_suspended(true) body must be exactly the two-slot spec-suspended shape — a regression that leaked a `/status` sibling slot would inflate the top-level object here",
1348        );
1349    }
1350
1351    #[test]
1352    fn merge_suspended_false_body_delegates_through_spec_suspended_body_bytewise() {
1353        // Peer pin on the `false` polarity — mirrors the `true` pin
1354        // above; documents the wrapper's delegation contract on the
1355        // Resume arm's polarity. A regression that flipped ONLY one
1356        // polarity's routing (e.g. an accidental `spec_suspended_body
1357        // (!suspended)` typo at the wrapper) would surface here as a
1358        // per-polarity divergence rather than as silent signal-arm
1359        // skew at the Resume callsite.
1360        let sent = spec_suspended_body(false);
1361        let direct = spec_suspended_body(false);
1362        assert_eq!(
1363            sent, direct,
1364            "merge_suspended(false) must send `spec_suspended_body(false)` verbatim",
1365        );
1366        assert_eq!(
1367            sent,
1368            json!({ "spec": { "suspended": false } }),
1369            "merge_suspended(false) body must be exactly the two-slot spec-suspended shape at the false polarity",
1370        );
1371    }
1372
1373    #[test]
1374    fn merge_suspended_body_polarity_distinguishes_the_two_signal_arms() {
1375        // Cross-polarity guard — the two suspend/resume signal arms
1376        // stamp DISTINCT wire bodies (one for pause, one for resume),
1377        // so the wrapper's `bool` argument MUST propagate to the
1378        // composed body as a distinguishing surface. A regression that
1379        // hardcoded the composer's argument (e.g. always passing
1380        // `true`), stripped the argument at the wrapper boundary
1381        // through a typed enum flattening, or short-circuited to a
1382        // shared default would collapse both polarities to the same
1383        // body — this pin catches it by asserting the two bodies
1384        // differ, on top of the polarity-specific pins above.
1385        let true_body = spec_suspended_body(true);
1386        let false_body = spec_suspended_body(false);
1387        assert_ne!(
1388            true_body, false_body,
1389            "the two polarities of merge_suspended MUST produce distinct wire bodies — a regression that collapsed them would silently break either the pause or the resume arm depending on which side was hardcoded",
1390        );
1391        // Pin the exact per-polarity slot value so a regression that
1392        // preserved distinctness but drifted the actual bool payload
1393        // (e.g. flipping both arms' polarity, swapping the bool for a
1394        // string, promoting to a nested object) surfaces here rather
1395        // than at the wire.
1396        assert_eq!(
1397            true_body["spec"]["suspended"],
1398            serde_json::Value::Bool(true)
1399        );
1400        assert_eq!(
1401            false_body["spec"]["suspended"],
1402            serde_json::Value::Bool(false)
1403        );
1404    }
1405
1406    #[test]
1407    fn merge_suspended_body_matches_hand_authored_pre_lift_bytewise() {
1408        // Byte-shape parity witness against the pre-lift 2-site
1409        // `merge(&api, &name, &json!({"spec": {"suspended": <bool>}}))`
1410        // chain both signal arms restated pre-lift — the body
1411        // [`merge_suspended`] composes MUST match a direct hand-
1412        // authored `json!` block at both polarities. This is the pin
1413        // that catches a wrapper-side regression that stopped routing
1414        // through the composer at all (open-coding the body inline at
1415        // the wrapper), which would silently work today but drop out
1416        // of the substrate primitive's future-normalization ownership.
1417        //
1418        // Swept across both polarities so a regression that broke ONE
1419        // (e.g. an accidental early-return for the true polarity, a
1420        // stray transformation on the false polarity) surfaces per-
1421        // polarity, not swallowed by the passing majority.
1422        for polarity in [true, false] {
1423            let composed = spec_suspended_body(polarity);
1424            let hand_authored = json!({ "spec": { "suspended": polarity } });
1425            assert_eq!(
1426                composed, hand_authored,
1427                "the body merge_suspended({polarity}) dispatches must be byte-identical to the pre-lift `json!({{\"spec\": {{\"suspended\": {polarity}}}}})` block at both signal arms",
1428            );
1429        }
1430    }
1431
1432    // ─── annotation_body substrate pins ─────────────────────────────
1433    //
1434    // The pre-lift `json!({"metadata": {"annotations": {<key>: <value>}}})`
1435    // merge-body composition recurred at THREE hand-authored consumer
1436    // sites across TWO active workspace crates past the ★★ PRIME-
1437    // DIRECTIVE ≥ 2 duplication threshold: `tatara-reconciler::signals::
1438    // ingest` (Null-value strip of the SIGNAL annotation), `tatara-
1439    // reconciler::phase_machine::transition_to_releasing` (String-value
1440    // stamp of the RELEASED_FROM annotation), and `tatara-pool-
1441    // reconciler::controller_allocation` Release arm (&str-value stamp
1442    // of the return-trigger annotation). These pins bind the composer
1443    // at fail-before-pass-after granularity so a regression that drifts
1444    // the top-level `metadata` slot (case-fold to `Metadata`, alias
1445    // rename to `meta`, version-tagged wrap like `v1_metadata`), the
1446    // nested `annotations` slot (camelCase drift to `Annotations`,
1447    // rename to `annotationMap`, a stray sibling like `labels`
1448    // leaking in), the caller-passed key spelling (silent trimming,
1449    // case-fold, per-key allow-list gate), or the value-slot pass-
1450    // through (accidental promotion of `Value::Null` to
1451    // `Value::String("null")` breaking the JSON-merge-patch strip
1452    // semantics; an over-eager `to_value` re-encoding a `Value` argument
1453    // through a `String` wrap; the fallback silently promoting a
1454    // Serialize-failure to a non-null sentinel) surfaces HERE rather
1455    // than as silent operator-facing annotation-writer skew across the
1456    // three consumer sites.
1457
1458    #[test]
1459    fn annotation_body_wraps_null_value_for_merge_patch_strip_semantics() {
1460        // Byte-shape parity witness against the `signals::ingest` pre-
1461        // lift strip block (`json!({"metadata": {"annotations":
1462        // {SIGNAL_ANNOTATION: serde_json::Value::Null}}})`) — passing
1463        // `Value::Null` at the value slot round-trips through
1464        // `serde_json::to_value` to a `Value::Null` in the composed
1465        // body, so the K8s API server's JSON-merge-patch semantics
1466        // interpret it as "remove key". A regression that promoted the
1467        // null to a `"null"` string, dropped the slot entirely, or
1468        // reshaped the null through an intermediate wrapper would
1469        // silently un-strip every signal annotation post-ingestion.
1470        let body = annotation_body("tatara.pleme.io/signal", serde_json::Value::Null);
1471        assert_eq!(
1472            body,
1473            json!({
1474                "metadata": {
1475                    "annotations": { "tatara.pleme.io/signal": serde_json::Value::Null }
1476                }
1477            }),
1478        );
1479        assert_eq!(
1480            body["metadata"]["annotations"]["tatara.pleme.io/signal"],
1481            serde_json::Value::Null,
1482            "value at the caller-passed key rides through as JSON null verbatim",
1483        );
1484    }
1485
1486    #[test]
1487    fn annotation_body_wraps_string_value_for_merge_patch_stamp_semantics() {
1488        // Byte-shape parity witness against the `phase_machine::
1489        // transition_to_releasing` pre-lift stamp block (`json!(
1490        // {"metadata": {"annotations": {RELEASED_FROM: gate}}})` where
1491        // `gate: String` is the current phase spelling) — passing an
1492        // owned `String` at the value slot round-trips through
1493        // `serde_json::to_value` to a JSON string in the composed body.
1494        // A regression that dropped the String's ownership or reshaped
1495        // it through a wrapper would silently drift the stamped value.
1496        let body = annotation_body("tatara.pleme.io/released-from", String::from("Attested"));
1497        assert_eq!(
1498            body,
1499            json!({
1500                "metadata": {
1501                    "annotations": { "tatara.pleme.io/released-from": "Attested" }
1502                }
1503            }),
1504        );
1505        assert_eq!(
1506            body["metadata"]["annotations"]["tatara.pleme.io/released-from"],
1507            serde_json::Value::String("Attested".to_string()),
1508            "String value rides through as JSON string verbatim",
1509        );
1510    }
1511
1512    #[test]
1513    fn annotation_body_wraps_str_literal_value_for_return_trigger_stamp() {
1514        // Byte-shape parity witness against the `controller_allocation`
1515        // Release-arm pre-lift stamp block (`json!({"metadata":
1516        // {"annotations": {"tatara.pleme.io/return-trigger": "true"}}})`)
1517        // — passing a `&'static str` literal at the value slot round-
1518        // trips through `serde_json::to_value` to a JSON string in the
1519        // composed body, matching the pre-lift shape byte-identically.
1520        let body = annotation_body("tatara.pleme.io/return-trigger", "true");
1521        assert_eq!(
1522            body,
1523            json!({
1524                "metadata": {
1525                    "annotations": { "tatara.pleme.io/return-trigger": "true" }
1526                }
1527            }),
1528        );
1529    }
1530
1531    #[test]
1532    fn annotation_body_top_level_slot_is_exactly_metadata_lowercase() {
1533        // Any drift on the top-level slot name (case-fold to `Metadata`,
1534        // an alias rename to `meta`, a version-tagged wrap like
1535        // `v1_metadata`) breaks the merge-patch on the wire: the K8s
1536        // API server silently applies to a sibling field the CRD does
1537        // not define, and the operator sees the annotation never
1538        // appear. This pin binds the exact spelling the K8s API server
1539        // + every generated openapi type expect.
1540        let body = annotation_body("k", "v");
1541        let obj = body.as_object().expect("top-level must be a JSON object");
1542        assert_eq!(obj.len(), 1, "wrap adds exactly ONE top-level slot");
1543        assert!(
1544            obj.contains_key("metadata"),
1545            "top-level slot must be exactly `metadata` (lowercase)"
1546        );
1547    }
1548
1549    #[test]
1550    fn annotation_body_nested_slot_is_exactly_annotations_lowercase() {
1551        // Any drift on the nested slot name (camelCase to `Annotations`,
1552        // an alias rename to `annotationMap`, a stray sibling like
1553        // `labels` leaking in) breaks the merge-patch: the K8s API
1554        // silently applies to a wrong field. This pin binds the exact
1555        // spelling downstream metadata handlers expect and guards
1556        // against a sibling-slot leak inside the metadata wrap.
1557        let body = annotation_body("k", "v");
1558        let meta = body["metadata"]
1559            .as_object()
1560            .expect("nested metadata must be a JSON object");
1561        assert_eq!(
1562            meta.len(),
1563            1,
1564            "metadata carries exactly ONE nested slot (`annotations`) — no `labels` / `finalizers` sibling leaks"
1565        );
1566        assert!(
1567            meta.contains_key("annotations"),
1568            "nested slot must be exactly `annotations` (lowercase)"
1569        );
1570    }
1571
1572    #[test]
1573    fn annotation_body_preserves_caller_key_verbatim_no_trim_or_case_fold() {
1574        // The `key` argument is stamped byte-identically as the inner
1575        // JSON slot name: no trimming of whitespace-adjacent chars, no
1576        // case-fold of any segment (a `tatara.pleme.io/RELEASED-from`
1577        // caller would land on the wire exactly that way), no per-key
1578        // allow-list gate that silently drops "unknown" annotations.
1579        // Sweep across every pre-lift caller's key spelling so a
1580        // regression that added a canonicalization pass surfaces here
1581        // rather than as a silent annotation drop at any downstream
1582        // writer.
1583        for key in [
1584            "tatara.pleme.io/signal",
1585            "tatara.pleme.io/released-from",
1586            "tatara.pleme.io/return-trigger",
1587            "custom-fleet.example.com/opaque",
1588            "SCREAMING.CASE/PRESERVED",
1589        ] {
1590            let body = annotation_body(key, "v");
1591            let annotations = body["metadata"]["annotations"]
1592                .as_object()
1593                .expect("annotations must be a JSON object");
1594            assert_eq!(
1595                annotations.len(),
1596                1,
1597                "annotations carries exactly ONE key ({key}) — no synthetic sibling leaks",
1598            );
1599            assert!(
1600                annotations.contains_key(key),
1601                "annotations key must be exactly `{key}` verbatim (no trim / case-fold / allow-list gate)",
1602            );
1603        }
1604    }
1605
1606    #[test]
1607    fn annotation_body_matches_pre_lift_hand_authored_shapes_bytewise() {
1608        // Byte-shape parity witness against all THREE pre-lift consumer
1609        // sites' hand-authored blocks — the signals::ingest strip
1610        // (Null value), the phase_machine::transition_to_releasing
1611        // stamp (String value), and the controller_allocation Release-
1612        // arm return-trigger (&str value). A regression that reshaped
1613        // ANY site's byte-shape at the composer surfaces HERE rather
1614        // than at the wire.
1615        //
1616        // Sweep three representative (key, value) tuples matching the
1617        // three pre-lift call forms.
1618        let signal_strip = annotation_body("tatara.pleme.io/signal", serde_json::Value::Null);
1619        assert_eq!(
1620            signal_strip,
1621            json!({
1622                "metadata": {
1623                    "annotations": { "tatara.pleme.io/signal": serde_json::Value::Null }
1624                }
1625            }),
1626            "signals::ingest strip byte-shape",
1627        );
1628
1629        let released_stamp =
1630            annotation_body("tatara.pleme.io/released-from", String::from("Running"));
1631        assert_eq!(
1632            released_stamp,
1633            json!({
1634                "metadata": {
1635                    "annotations": { "tatara.pleme.io/released-from": "Running" }
1636                }
1637            }),
1638            "phase_machine::transition_to_releasing stamp byte-shape",
1639        );
1640
1641        let return_trigger = annotation_body("tatara.pleme.io/return-trigger", "true");
1642        assert_eq!(
1643            return_trigger,
1644            json!({
1645                "metadata": {
1646                    "annotations": { "tatara.pleme.io/return-trigger": "true" }
1647                }
1648            }),
1649            "controller_allocation Release-arm return-trigger byte-shape",
1650        );
1651    }
1652
1653    #[test]
1654    fn annotation_body_accepts_serde_json_value_at_value_slot_without_double_wrap() {
1655        // Callers that already have a `serde_json::Value` (e.g. a
1656        // `Value::String` or `Value::Number` computed upstream via a
1657        // typed derivation) pass it directly through `impl Serialize`
1658        // without a double-wrap. A regression that re-encoded a
1659        // `Value` argument through a `String` wrap (silently producing
1660        // `Value::String("\"stamped\"")` — a JSON-encoded string of a
1661        // JSON-encoded string) would surface HERE.
1662        let pre = serde_json::Value::String("stamped".to_string());
1663        let body = annotation_body("k.io/v", pre);
1664        assert_eq!(
1665            body["metadata"]["annotations"]["k.io/v"],
1666            serde_json::Value::String("stamped".to_string()),
1667            "pre-serialized Value rides through without a double-wrap",
1668        );
1669    }
1670
1671    // ─── merge_as (named primary-resource merge) substrate pins ─────
1672    //
1673    // The two-link `apply_patch_params(<mgr>) + api.patch(name, &pp,
1674    // &Patch::Merge(&body))` chain now rides through the ONE substrate
1675    // primitive [`merge_as`] across the two consumer sites in
1676    // `tatara-pool-reconciler::controller_allocation` (bind arm's
1677    // `spec.lifetime + metadata.annotations` compound edit; release
1678    // arm's single `metadata.annotations.<return-trigger>` edit). These
1679    // pins bind the primitive at fail-before-pass-after granularity so
1680    // a regression that swaps `Patch::Merge` for `Patch::Apply` (silently
1681    // reshaping merge semantics into SSA ownership reconciliation),
1682    // swaps `Patch::Merge` for `Patch::Strategic` (silently reshaping
1683    // scalar merges into strategic-merge deduplication over
1684    // strategic-merge-keyed arrays), drops the [`apply_patch_params`]
1685    // pass-through (silently reverting to `PatchParams::default()` and
1686    // erasing the field-manager attribution downstream `managedFields`
1687    // audits key on), or reorders the 3-arg positional slots surfaces
1688    // HERE rather than as silent named-merge writer skew across the two
1689    // pool-reconciler callsites.
1690    //
1691    // Source-level pins on the ingredients [`merge_as`] composes: the
1692    // wire-side round-trip needs a live `Api<K>` we cannot construct
1693    // without a kube client, but the substrate's async entry is a
1694    // two-line body (`let pp = apply_patch_params(field_manager);
1695    // api.patch(name, &pp, &Patch::Merge(body))`), so binding each
1696    // ingredient (the [`apply_patch_params`]-composed PatchParams
1697    // shape, the `Patch::Merge` posture selection, the verbatim body
1698    // pass-through) at the pure level pins every observable slot of
1699    // the wire request the primitive will issue.
1700
1701    #[test]
1702    fn merge_as_composes_apply_patch_params_at_the_field_manager_slot_verbatim() {
1703        // The primitive's params-build step is
1704        // `apply_patch_params(field_manager)` — every pre-lift caller
1705        // supplied a field-manager `&str` (the pool-reconciler's
1706        // `ctx.config.field_manager` per-instance String). A regression
1707        // that hardcoded a manager inside the primitive or reshaped
1708        // the slot would silently reassign field-manager attribution
1709        // at every consumer's wire request. Witness the params-side
1710        // ingredient by re-composing it through [`apply_patch_params`]
1711        // here and checking the observable slots the wire path keys on.
1712        for mgr in [
1713            "tatara-pool-reconciler",
1714            "per-shard-pool-reconciler-42",
1715            "tatara-reconciler",
1716        ] {
1717            let pp = apply_patch_params(mgr);
1718            assert_eq!(pp.field_manager.as_deref(), Some(mgr));
1719            assert!(pp.force, "named-merge must stamp force = true");
1720            assert!(!pp.dry_run, "default posture: dry_run stays false");
1721            assert!(
1722                pp.field_validation.is_none(),
1723                "default posture: field_validation stays None",
1724            );
1725        }
1726    }
1727
1728    #[test]
1729    fn merge_as_selects_patch_merge_strategy_not_apply_or_strategic_or_json() {
1730        // The primitive dispatches through `Patch::Merge(&body)` — the
1731        // JSON merge patch posture (RFC 7396) both pre-lift consumers
1732        // used. A regression that selected `Patch::Apply` would silently
1733        // reshape the pool-reconciler's bind + release edits into SSA
1734        // ownership reconciliation (a different conflict-resolution
1735        // model than the pre-lift wire behavior); `Patch::Strategic`
1736        // would reshape merges over `metadata.annotations` /
1737        // `spec.lifetime` sub-objects with strategic-merge semantics
1738        // (silently deduplicating annotation entries by
1739        // strategic-merge-key rather than treating the map as JSON to
1740        // overwrite); `Patch::Json` would demand an RFC 6902 op list
1741        // instead of the object body both consumers compose. Witness
1742        // the wire posture selection by constructing the Patch and
1743        // pattern-matching on the variant.
1744        let body = json!({"metadata": {"annotations": {"x.io/marker": "1"}}});
1745        let patch: Patch<&serde_json::Value> = Patch::Merge(&body);
1746        assert!(
1747            matches!(patch, Patch::Merge(_)),
1748            "merge_as primitive dispatches through Patch::Merge, not Apply/Strategic/Json"
1749        );
1750    }
1751
1752    #[test]
1753    fn merge_as_dispatches_body_verbatim_no_wrap_or_re_encode() {
1754        // The named-merge primitive is verbatim: the caller composes
1755        // the full top-level shape (the bind arm's compound
1756        // `{"spec": {"lifetime": …}, "metadata": {"annotations": …}}`,
1757        // the release arm's [`annotation_body`]-composed
1758        // `{"metadata": {"annotations": {<return-trigger>: "true"}}}`)
1759        // and the primitive passes it through untouched. A regression
1760        // that hid an implicit wrap or re-encoded the body through
1761        // `serde_json::to_value` and back would surface here — both
1762        // pre-lift callsites already composed the full top-level shape
1763        // and delegated straight to `api.patch(..., &Patch::Merge(&body))`
1764        // with no intervening transform.
1765        let bind_body = json!({
1766            "spec": {"lifetime": {"ephemeral": {"ttl": "1h"}}},
1767            "metadata": {"annotations": {
1768                "tatara.pleme.io/requestor": "ns/name",
1769                "tatara.pleme.io/allocation": "alloc-1",
1770                "tatara.pleme.io/requestor-kind": "GitHubPullRequest",
1771            }},
1772        });
1773        let release_body = annotation_body("tatara.pleme.io/return-trigger", "true");
1774        for body in [bind_body, release_body] {
1775            let round_trip = serde_json::to_value(&body).unwrap();
1776            assert_eq!(round_trip, body, "body serializes to itself verbatim");
1777            let obj = body.as_object().expect("pre-lift bodies are JSON objects");
1778            assert!(!obj.is_empty(), "pre-lift bodies carry at least one slot");
1779        }
1780    }
1781
1782    #[test]
1783    fn merge_as_params_match_pre_lift_hand_authored_chain_bytewise() {
1784        // Byte-shape parity between the primitive's internal params
1785        // composition and the pre-lift `PatchParams::apply(<mgr>)
1786        // .force()` chain both consumers restated verbatim. A
1787        // regression that reordered the chain (`.force().apply(...)`
1788        // swap) or widened the posture inside the primitive would
1789        // surface HERE rather than at the wire.
1790        for mgr in ["tatara-pool-reconciler", "per-shard-mgr"] {
1791            let pre_lift = PatchParams::apply(mgr).force();
1792            let lifted = apply_patch_params(mgr);
1793            assert_eq!(lifted.field_manager, pre_lift.field_manager);
1794            assert_eq!(lifted.force, pre_lift.force);
1795            assert_eq!(lifted.dry_run, pre_lift.dry_run);
1796            assert_eq!(
1797                lifted.field_validation.is_none(),
1798                pre_lift.field_validation.is_none(),
1799            );
1800        }
1801    }
1802
1803    #[test]
1804    fn merge_as_closes_patch_strategy_by_patch_params_matrix_at_the_named_merge_corner() {
1805        // Corner-partition pin — the four primitives [`merge`],
1806        // [`apply`], [`merge_status`], [`merge_as`] partition the
1807        // (Patch-strategy × PatchParams-posture × wire-endpoint) matrix
1808        // the workspace's wire-side patch family stamps. This pin
1809        // witnesses that [`merge_as`] stamps EXACTLY the
1810        // (Patch::Merge × apply_patch_params × primary-resource)
1811        // corner — distinct from [`merge`]'s
1812        // (Patch::Merge × PatchParams::default × primary-resource)
1813        // corner and from [`apply`]'s
1814        // (Patch::Apply × apply_patch_params × primary-resource)
1815        // corner. A regression that collapsed any two corners onto
1816        // ONE primitive (e.g. `merge_as` accidentally routing through
1817        // `apply`'s `Patch::Apply` posture, or reverting to
1818        // `PatchParams::default()` and drifting into `merge`'s corner)
1819        // would break the partition and surface HERE rather than as
1820        // silent field-manager attribution loss or SSA-vs-merge
1821        // semantics drift at the two pool-reconciler callsites.
1822
1823        // Corner witness: named-merge params ≠ default params
1824        let named = apply_patch_params("mgr");
1825        let default = PatchParams::default();
1826        assert_ne!(
1827            named.field_manager, default.field_manager,
1828            "merge_as's params carry a field manager; merge's do not — the corner distinction is load-bearing"
1829        );
1830        assert_ne!(
1831            named.force, default.force,
1832            "merge_as's params stamp force = true; merge's do not — the corner distinction is load-bearing"
1833        );
1834
1835        // Corner witness: merge strategy ≠ apply strategy at the same params
1836        let body = json!({"metadata": {"annotations": {"k": "v"}}});
1837        let merge_patch: Patch<&serde_json::Value> = Patch::Merge(&body);
1838        let apply_patch: Patch<&serde_json::Value> = Patch::Apply(&body);
1839        assert!(
1840            matches!(merge_patch, Patch::Merge(_)),
1841            "merge_as dispatches Patch::Merge, distinguishing it from apply's Patch::Apply corner"
1842        );
1843        assert!(
1844            matches!(apply_patch, Patch::Apply(_)),
1845            "apply dispatches Patch::Apply, distinguishing it from merge_as's Patch::Merge corner"
1846        );
1847    }
1848}