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/// Compose the merge-patch wire body `{"spec": {"suspended": <bool>}}` — the
242/// SIGSTOP/SIGCONT-driven suspend/resume shape both
243/// `SignalEffect::Suspend` and `SignalEffect::Resume` arms of
244/// `tatara-reconciler::signals::consume_effect` stamp on the Process spec.
245///
246/// Both arms compose through this ONE substrate owner and hand the produced
247/// body straight to [`merge`]; pre-lift each arm restated `json!({ "spec":
248/// { "suspended": <bool> } })` verbatim at its callsite (both are named in
249/// the `merge` docstring's six-consumer inventory above). Two hand-authored
250/// restatements past the ★★ PRIME-DIRECTIVE ≥ 2 duplication trigger; post-
251/// lift a future addition to the suspend/resume wire body (a `by:` slot
252/// naming the signal source, a `suspendedAt:` transition timestamp, a
253/// symmetry gate that refuses conflicting suspend + resume overlays, a
254/// version-tagged wrap for a `spec.suspend.v2` migration) lands at THIS
255/// function and both arms inherit the upgrade mechanically.
256///
257/// The `bool` argument matches the pre-lift call sites' spelling exactly
258/// (`true` at the Suspend arm, `false` at the Resume arm) — the primitive
259/// does not force one polarity, because the merge-patch body itself is
260/// symmetric between the two arms and the shape stays load-bearing at
261/// both polarities.
262///
263/// Sibling to [`merge_status_body`] on the (wire-endpoint × wrap-posture)
264/// pair: [`merge_status_body`] owns the `/status` subresource wrap;
265/// this primitive owns one specific `{"spec": …}` primary-resource wrap
266/// (the suspend/resume one) — a body composer, not a wire-dispatcher, so
267/// consumers still hand the produced body to [`merge`] for the round-
268/// trip.
269///
270/// Theory anchor: THEORY.md §VI.1 (generation over composition — the
271/// two-arm `json!({ "spec": { "suspended": <bool> } })` restatement is
272/// lifted onto ONE substrate composer). THEORY.md §II.1 invariant 5
273/// (composition preserves proofs — the pin block below binds the shape
274/// at fail-before-pass-after granularity so a regression that drifts the
275/// top-level `spec` slot, the inner `suspended` slot, or the JSON bool
276/// value type at either polarity surfaces here rather than as silent
277/// signal-arm skew at the two suspend/resume callsites).
278#[must_use]
279pub fn spec_suspended_body(suspended: bool) -> serde_json::Value {
280 json!({ "spec": { "suspended": suspended } })
281}
282
283#[cfg(test)]
284mod tests {
285 use super::*;
286 use serde::Serialize;
287 use serde_json::json;
288
289 // ─── merge_status_body substrate pins ───────────────────────────
290 //
291 // The pre-lift `json!({"status": <typed>})` wrap recurred at 7
292 // hand-authored sites across `tatara-pool-reconciler` (both
293 // controllers) + `tatara-reconciler::patch::patch_process_status`
294 // pre-lift. These pins bind the wire-body shape at
295 // fail-before-pass-after granularity so a regression that drifts
296 // the top-level slot key, reshapes the wrap posture, or leaks a
297 // sibling slot surfaces here rather than as silent status-write
298 // drift at every downstream controller.
299
300 #[test]
301 fn merge_status_body_wraps_typed_status_under_top_level_status_slot() {
302 #[derive(Serialize)]
303 struct S {
304 phase: &'static str,
305 reason: &'static str,
306 }
307 let body = merge_status_body(&S {
308 phase: "Bound",
309 reason: "member allocated",
310 });
311 assert_eq!(
312 body,
313 json!({ "status": { "phase": "Bound", "reason": "member allocated" } }),
314 );
315 }
316
317 #[test]
318 fn merge_status_body_top_level_key_is_exactly_status_lowercase() {
319 // Any drift on the top-level slot name (case-fold to `Status`,
320 // a substrate-side rename to `status_patch`, a version-tagged
321 // wrap like `v1alpha1_status`) breaks every status writer on
322 // the wire. This pin binds the exact spelling downstream K8s
323 // API + K8s-openapi generated types expect.
324 let body = merge_status_body(&json!({"phase": "Running"}));
325 let obj = body.as_object().expect("top-level must be a JSON object");
326 assert_eq!(obj.len(), 1, "wrap adds exactly ONE top-level slot");
327 assert!(
328 obj.contains_key("status"),
329 "top-level slot must be exactly `status` (lowercase)"
330 );
331 }
332
333 #[test]
334 fn merge_status_body_accepts_pre_serialized_json_value_verbatim() {
335 // Callers that already have a `serde_json::Value` (e.g. the
336 // existing `tatara-reconciler::patch::patch_process_status`
337 // callers that hand-build a `Value` via one of the
338 // `phase_status_*` builders) pass it directly to the primitive
339 // without re-serialization. This pin binds that pass-through
340 // shape: the wrap layer never re-encodes an already-JSON slot.
341 let pre = json!({"phase": "Attested", "phaseSince": "2026-05-01T00:00:00Z"});
342 let body = merge_status_body(&pre);
343 assert_eq!(body, json!({"status": pre}));
344 }
345
346 #[test]
347 fn merge_status_body_wraps_scalar_status_without_object_promotion() {
348 // The primitive is not "wrap into an object with a phase
349 // slot" — it is exactly "wrap into `{"status": <serialized>}`".
350 // A scalar status (unusual in practice, but permitted by the
351 // Serialize bound) rides through as the top-level `status`
352 // value verbatim.
353 let body = merge_status_body(&"Attested");
354 assert_eq!(body, json!({"status": "Attested"}));
355 }
356
357 #[test]
358 fn merge_status_body_preserves_struct_update_composition_bytewise() {
359 // The pool-reconciler `AllocationStatus { bound_pool: Some(p),
360 // ..AllocationStatus::transition(...) }` struct-update shape
361 // composes a typed value that serialize into a stable JSON
362 // shape. This pin binds a smaller-scale peer: a struct-update
363 // over a base composer produces the same JSON as the fully
364 // spelled-out struct literal.
365 #[derive(Serialize)]
366 struct Base {
367 phase: &'static str,
368 phase_since: &'static str,
369 extra: Option<&'static str>,
370 }
371 fn base() -> Base {
372 Base {
373 phase: "Queued",
374 phase_since: "2026-05-01T00:00:00Z",
375 extra: None,
376 }
377 }
378 let struct_update = Base {
379 extra: Some("pool matched"),
380 ..base()
381 };
382 let spelled_out = Base {
383 phase: "Queued",
384 phase_since: "2026-05-01T00:00:00Z",
385 extra: Some("pool matched"),
386 };
387 assert_eq!(
388 merge_status_body(&struct_update),
389 merge_status_body(&spelled_out),
390 "struct-update composition serializes byte-identically to the fully-spelled struct literal",
391 );
392 }
393
394 // ─── merge_status wire-side round-trip pin ──────────────────────
395 //
396 // Bind that the async entry composes the same wire body the pure
397 // helper does (i.e. `merge_status` delegates to
398 // `merge_status_body` verbatim rather than restating the wrap).
399 // A regression that hand-rolled the wrap inside `merge_status`
400 // (thereby drifting from `merge_status_body`'s pinned shape) would
401 // surface here.
402 #[test]
403 fn merge_status_delegates_wire_body_construction_to_merge_status_body() {
404 // The invariant this binds is a source-level one: whichever
405 // call path a caller takes (direct body-construction, or the
406 // async entry composing internally), the wire body is the same
407 // shape. We witness it by having both call sites hit the same
408 // helper. The pure helper's pins above cover the shape; this
409 // pin binds the wire-side entry does not fork.
410 let body_via_helper = merge_status_body(&json!({"phase": "Running"}));
411 // `merge_status` is `async` and needs an `Api<K>` we cannot
412 // construct here without a client — but its body composition
413 // step calls exactly `merge_status_body(status)`, so the pin
414 // above already covers the shape. This test exists to name the
415 // delegation invariant so a future refactor that inlined the
416 // wrap would need to move THIS pin's docstring first.
417 assert_eq!(body_via_helper["status"]["phase"], "Running");
418 }
419
420 // ─── apply_patch_params substrate pins ──────────────────────────
421 //
422 // The 2-link `PatchParams::apply(<mgr>).force()` chain now rides
423 // through the ONE substrate primitive [`apply_patch_params`]
424 // across THREE consumer crates: `tatara-reconciler::ssapply`
425 // (field-manager-const-bound wrapper delegating to this one),
426 // `tatara-pool-reconciler::controller_allocation` (bind + release
427 // arms, feeding a per-instance `ctx.config.field_manager` String
428 // through the pass-through slot), `tatara-export-worker::main::
429 // write_receipt` (feeding a `"tatara-export-worker"` literal
430 // through the same slot). These pins bind the primitive at
431 // fail-before-pass-after granularity so a regression that drops
432 // `.force()`, drifts the field-manager pass-through, reintroduces
433 // a hand-authored literal at any consumer, or widens the posture
434 // (auto-`dry_run`, non-`None` `field_validation`) surfaces HERE
435 // rather than as silent SSA writer skew across three workspace
436 // crates.
437
438 #[test]
439 fn apply_patch_params_binds_field_manager_pass_through_slot_verbatim() {
440 // The pass-through slot is byte-identical to the caller's
441 // `&str`: no re-encoding, no case-fold, no substitution. A
442 // regression that trimmed / normalized the manager string
443 // silently would surface here — every consumer relies on the
444 // exact spelling landing in the SSA wire request so downstream
445 // field-manager ownership queries key on the exact identity
446 // each callsite stamps.
447 let pp = apply_patch_params("tatara-reconciler");
448 assert_eq!(pp.field_manager.as_deref(), Some("tatara-reconciler"));
449
450 let pp = apply_patch_params("tatara-export-worker");
451 assert_eq!(pp.field_manager.as_deref(), Some("tatara-export-worker"));
452
453 let pp = apply_patch_params("per-shard-manager-42");
454 assert_eq!(pp.field_manager.as_deref(), Some("per-shard-manager-42"));
455 }
456
457 #[test]
458 fn apply_patch_params_stamps_force_true() {
459 // `force = true` matches the SSA `force` directive every pre-
460 // lift chain applied at every SSA writer site across the three
461 // consumer crates — every consumer is the authoritative owner
462 // of the field pathways it stamps and reclaims conflicting
463 // slots on every apply. A regression that dropped `.force()`
464 // from the primitive would silently 409-conflict at every SSA
465 // write on any field already owned by a prior field manager.
466 let pp = apply_patch_params("tatara-reconciler");
467 assert!(pp.force);
468 }
469
470 #[test]
471 fn apply_patch_params_defaults_dry_run_and_field_validation_off() {
472 // The primitive stamps ONLY the `field_manager` + `force` slots
473 // every pre-lift chain stamped — `dry_run` stays `false` and
474 // `field_validation` stays `None`. A regression that widened
475 // the primitive's slot set (auto-enabled `dry_run` during a
476 // debug pass, added a default `field_validation` mode) would
477 // silently no-op every SSA write (dry_run) or reject apply
478 // bodies previous consumers accepted (field_validation).
479 let pp = apply_patch_params("tatara-reconciler");
480 assert!(!pp.dry_run);
481 assert!(pp.field_validation.is_none());
482 }
483
484 #[test]
485 fn apply_patch_params_matches_pre_lift_hand_authored_chain_bytewise() {
486 // Byte-shape parity with the pre-lift 2-link chain at every
487 // observable slot (`field_manager`, `force`, `dry_run`,
488 // `field_validation`) at each of the three consumer crates'
489 // hand-authored spellings. A regression that reordered the
490 // chain (e.g. `apply(...).dry_run().force()` swap) or drifted
491 // any slot's wire representation lands HERE.
492 for mgr in [
493 "tatara-reconciler",
494 "tatara-export-worker",
495 "per-shard-manager-42",
496 ] {
497 let pre_lift = PatchParams::apply(mgr).force();
498 let lifted = apply_patch_params(mgr);
499 assert_eq!(lifted.field_manager, pre_lift.field_manager);
500 assert_eq!(lifted.force, pre_lift.force);
501 assert_eq!(lifted.dry_run, pre_lift.dry_run);
502 assert_eq!(
503 lifted.field_validation.is_none(),
504 pre_lift.field_validation.is_none()
505 );
506 }
507 }
508
509 // ─── merge (primary-resource) substrate pins ────────────────────
510 //
511 // The 3-link `api.patch(name, &PatchParams::default(),
512 // &Patch::Merge(&body))` chain now rides through the ONE substrate
513 // primitive [`merge`] across TWO consumer crates:
514 // `tatara-reconciler::patch::{patch_process_table_spec,
515 // apply_finalizer_transform}` + `tatara-reconciler::signals::
516 // {ingest, consume_effect (Suspend + Resume arms)}` and
517 // `tatara-closed-loop-probe::main::write_receipt_configmap`. These
518 // pins bind the primitive at fail-before-pass-after granularity so
519 // a regression that switches `Patch::Merge` for `Patch::Strategic`,
520 // drifts `PatchParams::default()` to a non-default posture (a
521 // hardcoded field manager, an auto-`dry_run`, a non-`None`
522 // `field_validation` mode), reorders the 3-arg positional slots,
523 // or hijacks the pass-through body (a hidden top-level wrap, an
524 // accidental re-encode through `serde_json::to_value` and back)
525 // surfaces HERE rather than as silent primary-resource writer skew
526 // across the six pre-lift callsites.
527 //
528 // These are source-level pins on the pure helpers the async entry
529 // composes: the wire-side round-trip needs a live `Api<K>` we
530 // cannot construct without a kube client, but the substrate's
531 // async entry is a single-expression delegation to
532 // `api.patch(name, &PatchParams::default(), &Patch::Merge(body))`,
533 // so binding each ingredient (default patch-params posture, merge-
534 // strategy selection, verbatim body pass-through) at the pure
535 // level pins every observable slot of the wire request the primitive
536 // will issue.
537
538 #[test]
539 fn merge_uses_default_patch_params_posture_no_field_manager_no_dry_run_no_force() {
540 // The primary-resource merge primitive stamps the DEFAULT
541 // `PatchParams` posture — no field_manager (merge writes are
542 // not SSA and do not participate in the field-manager
543 // ownership model), no dry_run, no force, no field_validation.
544 // A regression that swapped in a partially-populated
545 // `PatchParams` (a stray `apply(...)`, a debug-mode `dry_run`,
546 // a `field_validation` mode) would silently reshape every
547 // primary-resource merge into an SSA-adjacent or dry-run write.
548 let pp = PatchParams::default();
549 assert!(pp.field_manager.is_none(), "default has no field_manager");
550 assert!(!pp.dry_run, "default has dry_run false");
551 assert!(!pp.force, "default has force false");
552 assert!(
553 pp.field_validation.is_none(),
554 "default has no field_validation"
555 );
556 }
557
558 #[test]
559 fn merge_selects_patch_merge_strategy_not_apply_or_strategic() {
560 // The primitive dispatches through `Patch::Merge(&body)` — the
561 // JSON merge patch posture (RFC 7396) every pre-lift consumer
562 // used. A regression that selected `Patch::Apply` would inject
563 // an SSA wire request against the primary-resource endpoint
564 // (which either 415s without an `apiVersion`/`kind` slot or
565 // takes ownership away from the API server's merge
566 // reconciliation model); a regression that selected
567 // `Patch::Strategic` would reshape merge semantics for arrays
568 // of tagged sub-objects (finalizers, annotations, labels) into
569 // strategic-merge behavior that silently deduplicates entries
570 // by strategic-merge-key rather than treating the slot as a
571 // JSON scalar to overwrite.
572 let body = json!({"spec": {"suspended": true}});
573 let patch: Patch<&serde_json::Value> = Patch::Merge(&body);
574 assert!(
575 matches!(patch, Patch::Merge(_)),
576 "merge primitive dispatches through Patch::Merge, not Apply/Strategic/Json"
577 );
578 }
579
580 #[test]
581 fn merge_dispatches_body_verbatim_no_wrap_or_re_encode() {
582 // Unlike [`merge_status`] which wraps its input into
583 // `{"status": …}`, the primary-resource merge primitive is
584 // verbatim: the caller composes the full top-level shape
585 // (`{"spec": …}`, `{"metadata": {"finalizers": …}}`,
586 // `{"data": …}`) and the primitive passes it through untouched.
587 // A regression that hid an implicit wrap or re-encoded the
588 // body through `serde_json::to_value` and back would surface
589 // here — every pre-lift callsite already composed the top-
590 // level shape and delegated straight to
591 // `api.patch(..., &Patch::Merge(&body))` with no intervening
592 // transform.
593 //
594 // Sweep every top-level shape the six pre-lift consumers
595 // compose so a regression on any one lands here.
596 let spec_body = json!({"spec": {"suspended": true}});
597 let meta_body = json!({
598 "metadata": {"finalizers": ["tatara.pleme.io/process-finalizer"]},
599 });
600 let strip_body = json!({
601 "metadata": {"annotations": {"tatara.pleme.io/signal": serde_json::Value::Null}},
602 });
603 let data_body = json!({"data": {"receipt.json": "{...}"}});
604 let spec_next_body = json!({"spec": {"nextSequence": 42}});
605 for body in [spec_body, meta_body, strip_body, data_body, spec_next_body] {
606 // The primitive's body-passing step is a `&Patch::Merge(body)`
607 // borrow with no intervening transform — witness that the
608 // top-level slot survives verbatim.
609 let round_trip = serde_json::to_value(&body).unwrap();
610 assert_eq!(round_trip, body, "body serializes to itself verbatim");
611 // Extract the ONE top-level slot the pre-lift caller
612 // composed; the primitive must not add a sibling slot.
613 let obj = body.as_object().expect("pre-lift bodies are JSON objects");
614 assert_eq!(
615 obj.len(),
616 1,
617 "each pre-lift consumer composed exactly ONE top-level slot"
618 );
619 }
620 }
621
622 #[test]
623 fn merge_body_composition_matches_pre_lift_signals_and_finalizer_shapes_bytewise() {
624 // Byte-shape parity against each of the six pre-lift bodies —
625 // signals::ingest strip annotation, signals::consume_effect
626 // Suspend + Resume, patch::patch_process_table_spec's
627 // `{"spec": …}` seed, patch::apply_finalizer_transform's
628 // `{"metadata": {"finalizers": …}}` seed, and
629 // closed-loop-probe::write_receipt_configmap's `{"data": …}`
630 // seed. A regression that reshaped any body composer at its
631 // callsite (case-fold slot names, added sibling debug slots)
632 // surfaces here rather than as silent behavioral drift at the
633 // wire.
634
635 // signals::ingest strip shape
636 let strip = json!({
637 "metadata": {
638 "annotations": { "tatara.pleme.io/signal": serde_json::Value::Null }
639 }
640 });
641 assert_eq!(
642 strip["metadata"]["annotations"]["tatara.pleme.io/signal"],
643 serde_json::Value::Null,
644 "strip stamps JSON null to trigger merge-patch key removal"
645 );
646
647 // signals::consume_effect Suspend shape
648 let suspend = json!({ "spec": { "suspended": true } });
649 assert_eq!(suspend["spec"]["suspended"], serde_json::Value::Bool(true));
650
651 // signals::consume_effect Resume shape
652 let resume = json!({ "spec": { "suspended": false } });
653 assert_eq!(resume["spec"]["suspended"], serde_json::Value::Bool(false));
654 }
655
656 // ─── spec_suspended_body substrate pins ─────────────────────────
657 //
658 // The pre-lift `json!({ "spec": { "suspended": <bool> } })`
659 // restatement recurred at TWO hand-authored sites in
660 // `tatara-reconciler::signals::consume_effect` (Suspend arm feeding
661 // `true`, Resume arm feeding `false`) past the ★★ PRIME-DIRECTIVE
662 // ≥ 2 duplication threshold. These pins bind the composer at fail-
663 // before-pass-after granularity so a regression that drifts the
664 // top-level `spec` slot (case-fold to `Spec`, verbose rename to
665 // `spec_patch`), the inner `suspended` slot (camelCase drift to
666 // `Suspended`, alias rename to `paused`), the JSON bool value type
667 // (accidental promotion to `"true"` / `"false"` strings), or the
668 // wrap posture (a `{"metadata": {...}}` sibling slot slipping in at
669 // the top-level) surfaces HERE rather than as silent signal-arm
670 // skew across the two hand-authored suspend/resume callsites.
671
672 #[test]
673 fn spec_suspended_body_wraps_true_under_spec_suspended_slot() {
674 let body = spec_suspended_body(true);
675 assert_eq!(body, json!({ "spec": { "suspended": true } }));
676 }
677
678 #[test]
679 fn spec_suspended_body_wraps_false_under_spec_suspended_slot() {
680 let body = spec_suspended_body(false);
681 assert_eq!(body, json!({ "spec": { "suspended": false } }));
682 }
683
684 #[test]
685 fn spec_suspended_body_top_level_slot_is_exactly_spec_lowercase() {
686 // Any drift on the top-level slot name (case-fold to `Spec`, a
687 // substrate-side rename to `spec_patch`, a version-tagged wrap
688 // like `v1alpha1_spec`) breaks the merge-patch on the wire.
689 // This pin binds the exact spelling downstream K8s API + the
690 // Process CRD's `.spec.suspended` field path expect.
691 for value in [true, false] {
692 let body = spec_suspended_body(value);
693 let obj = body.as_object().expect("top-level must be a JSON object");
694 assert_eq!(obj.len(), 1, "wrap adds exactly ONE top-level slot");
695 assert!(
696 obj.contains_key("spec"),
697 "top-level slot must be exactly `spec` (lowercase)"
698 );
699 }
700 }
701
702 #[test]
703 fn spec_suspended_body_inner_slot_is_exactly_suspended_lowercase() {
704 // Any drift on the inner slot name (camelCase to `Suspended`, a
705 // rename to `paused`, a version-tagged rename to `suspend_v2`)
706 // breaks the merge-patch: the K8s API silently applies the wrong
707 // field and the reconciler's suspend gate never fires.
708 for value in [true, false] {
709 let body = spec_suspended_body(value);
710 let spec = body["spec"]
711 .as_object()
712 .expect("inner `spec` must be a JSON object");
713 assert_eq!(
714 spec.len(),
715 1,
716 "inner spec carries exactly ONE slot (`suspended`)"
717 );
718 assert!(
719 spec.contains_key("suspended"),
720 "inner slot must be exactly `suspended` (lowercase)"
721 );
722 }
723 }
724
725 #[test]
726 fn spec_suspended_body_inner_value_is_json_bool_not_string() {
727 // Accidental promotion of the bool to a `"true"` / `"false"`
728 // JSON string would silently 400 on the wire (schema validation
729 // rejects a string on a bool field) or silently deserialize as
730 // `Default::default()` on the field, breaking the suspend gate.
731 assert_eq!(
732 spec_suspended_body(true)["spec"]["suspended"],
733 serde_json::Value::Bool(true),
734 );
735 assert_eq!(
736 spec_suspended_body(false)["spec"]["suspended"],
737 serde_json::Value::Bool(false),
738 );
739 }
740
741 #[test]
742 fn spec_suspended_body_matches_pre_lift_hand_authored_shape_bytewise() {
743 // Byte-shape parity with the pre-lift 2-site `json!({ "spec": {
744 // "suspended": <bool> } })` block that both `SignalEffect::
745 // Suspend` (true polarity) and `SignalEffect::Resume` (false
746 // polarity) arms restated pre-lift. A regression that reshaped
747 // either polarity would drift here rather than at the wire.
748 for value in [true, false] {
749 let composed = spec_suspended_body(value);
750 let hand_authored = json!({ "spec": { "suspended": value } });
751 assert_eq!(
752 composed, hand_authored,
753 "spec_suspended_body({value}) must be byte-identical to the pre-lift `json!` block",
754 );
755 }
756 }
757}