caixa_core/supervisor.rs
1//! OTP-shaped supervisor trees, encoded as a typed `:kind Supervisor`
2//! caixa with a strategy + restart-policy children list.
3//!
4//! See `theory/INSPIRATIONS.md` §II.2 + §III.2 for the prior-art frame
5//! (Erlang OTP supervisor + Lunatic supervisor strategies as Rust types).
6//!
7//! ```lisp
8//! (defcaixa
9//! :nome "my-app-root"
10//! :versao "0.1.0"
11//! :kind Supervisor
12//! :estrategia OneForOne
13//! :max-restarts 5
14//! :restart-window "60s"
15//! :children ((:caixa "worker" :versao "^0.1" :restart Permanent)
16//! (:caixa "cache-server" :versao "^0.1" :restart Transient)
17//! (:caixa "scratch-job" :versao "^0.1" :restart Temporary)))
18//! ```
19//!
20//! wasm-operator (M3) walks the tree, materializes one ComputeUnit per
21//! child, and applies the strategy on child failure. The Rust types
22//! here are the typed contract; the runtime owns lifecycle.
23
24use std::time::Duration;
25
26use serde::{Deserialize, Serialize};
27use thiserror::Error;
28
29/// One of the four canonical Erlang/OTP restart strategies.
30///
31/// The strategy decides what happens to *sibling* children when one
32/// child dies. Per-child behaviour is governed by [`RestartPolicy`].
33#[derive(
34 Serialize,
35 Deserialize,
36 Debug,
37 Clone,
38 Copy,
39 PartialEq,
40 Eq,
41 Hash,
42 gen_platform::TypedDispatcher,
43 gen_platform::Discriminant,
44 gen_platform::IsVariant,
45 gen_platform::FromStrKind,
46)]
47pub enum RestartStrategy {
48 /// On child failure, restart only that child. Default; matches
49 /// most "tree of independent workers" use cases.
50 OneForOne,
51 /// On child failure, restart every child. Used when children
52 /// share state and must be in sync.
53 OneForAll,
54 /// On child failure, restart the failed child and every child
55 /// started *after* it (preserving startup order). Used when later
56 /// children depend on earlier ones.
57 RestForOne,
58 /// Dynamic children of the same shape, started on demand. The
59 /// supervisor doesn't know its children at boot; they're added as
60 /// they're needed (e.g. one child per session).
61 SimpleOneForOne,
62}
63
64impl Default for RestartStrategy {
65 fn default() -> Self {
66 // Route the [`Default for RestartStrategy`] impl through the
67 // substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed
68 // `pub const` rather than a raw `Self::OneForOne` arm — one
69 // source of truth for the Erlang/OTP `one_for_one` half of Learn
70 // You Some Erlang's `{one_for_one, intensity, 5, 60}` worker-
71 // supervisor canonical default, paired with the sibling
72 // `SUPERVISOR_MAX_RESTARTS_DEFAULT` `MaxIntensity` half (b698ec0)
73 // and `SUPERVISOR_RESTART_WINDOW_DEFAULT` `Period` half (f7dcd0e).
74 // Pinned by `restart_strategy_default_routes_through_lifted_default`.
75 SUPERVISOR_ESTRATEGIA_DEFAULT
76 }
77}
78
79impl RestartStrategy {
80 /// Exhaustive iteration surface for every consumer that walks the
81 /// closed four-arm [`RestartStrategy`] discriminator set (the future
82 /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
83 /// admission-webhook rejection body naming the accepted-`:estrategia`
84 /// list, a future `feira supervisor --estrategia …` CLI arg-parse's
85 /// "did you mean" hint via a [`Self::from_wire`]-scan over the slice,
86 /// the future `feira app graph` per-supervisor `:estrategia` column,
87 /// any future round-trip fuzz harness that sweeps every arm). A
88 /// future arm addition (an OTP-`rest_for_all` arm the theory
89 /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
90 /// might reach for once the four canonical OTP strategies stop
91 /// covering the substrate's discovered load-shape) extends this
92 /// slice as one edit and every consumer picks up the new entry by
93 /// construction; the compiler-checked exhaustiveness on the sibling
94 /// method `match` arms ([`Self::as_str`] / [`Self::from_wire`]) is
95 /// the build-time guarantee that no arm forgets to grow.
96 ///
97 /// Peer of the sibling closed-set typed enums'
98 /// [`crate::CaixaKind::ALL`] (6b1f4fb) /
99 /// [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
100 /// [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
101 /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
102 /// surfaces — the fifth (and the first M2 OTP-shape) closed-set
103 /// typed enum on the caixa surface to converge onto the same
104 /// one-canonical-arm-list-per-enum discipline.
105 pub const ALL: &'static [Self] = &[
106 Self::OneForOne,
107 Self::OneForAll,
108 Self::RestForOne,
109 Self::SimpleOneForOne,
110 ];
111
112 /// Canonical PascalCase discriminator scalar this variant serializes
113 /// as under [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`]. The four arms
114 /// return the paired [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`]
115 /// / [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
116 /// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
117 /// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] lifted
118 /// constants so every substrate consumer that dispatches on the
119 /// per-supervisor sibling-restart strategy (the future
120 /// wasm-operator's per-supervisor sibling-restart branch, the future
121 /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
122 /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
123 /// reconciliation scheduler's per-strategy fan-out) reads the same
124 /// byte-string the `Serialize` derive emits — the pin test in
125 /// [`tests::restart_strategy_variants_serialize_to_lifted_scalar_values`]
126 /// asserts the two paths agree, peer of the M3
127 /// `PlacementStrategy::as_str` (cc8f749) on the sibling per-Aplicacao
128 /// distribution-strategy axis.
129 #[must_use]
130 pub const fn as_str(self) -> &'static str {
131 match self {
132 Self::OneForOne => crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
133 Self::OneForAll => crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
134 Self::RestForOne => crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
135 Self::SimpleOneForOne => crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
136 }
137 }
138
139 /// Substrate-canonical reverse projection on the `:supervisor
140 /// :estrategia` closed-set axis — parses the `PascalCase`
141 /// discriminator scalar back to the typed variant, or `None` when
142 /// `s` is outside
143 /// the closed-set arm-string set [`Self::as_str`] emits. Dispatches
144 /// on the same lifted
145 /// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
146 /// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
147 /// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
148 /// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
149 /// constants the [`Self::as_str`] emitter walks, so the parse and
150 /// emit halves of the round-trip migrate through one caixa-core
151 /// edit on any future arm addition.
152 ///
153 /// Prior to this lift the substrate carried only the forward
154 /// `Self → &str` projection on the OTP sibling-restart axis (the
155 /// [`Self::as_str`] emitter, the [`std::fmt::Display`] impl routed
156 /// through it, the `Serialize` derive that emits the same
157 /// byte-string under [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`])
158 /// plus the kebab-case dispatcher-catalog identity via
159 /// [`Self::discriminant`] — every non-serde consumer that wanted to
160 /// parse a wire-form `PascalCase` strategy scalar had to re-inline
161 /// a four-arm `match s { "OneForOne" => …, "OneForAll" => …,
162 /// "RestForOne" => …, "SimpleOneForOne" => …, _ => … }` cascade
163 /// that expressed no compile-time link back to the typed variant's
164 /// canonical lifted constant. A future variant rename or per-arm
165 /// serde-attribute drift would silently split the wire byte-string
166 /// one non-serde consumer parsed from the one the emitter wrote,
167 /// with the failure surfacing at parse time far from the rebrand
168 /// commit.
169 ///
170 /// Distinct axis from the [`std::str::FromStr`] impl the
171 /// [`gen_platform::FromStrKind`] derive already installs on this
172 /// enum by design, not by drift: `FromStr` parses the *kebab-case*
173 /// dispatcher-catalog identity (`"one-for-one"` / `"one-for-all"` /
174 /// `"rest-for-one"` / `"simple-one-for-one"` — the inverse of
175 /// [`Self::discriminant`]), while this method inverts the
176 /// `PascalCase` wire byte-string [`Self::as_str`] emits. The
177 /// two-axis split lets the dispatcher-catalog identity live in
178 /// kebab-case
179 /// (where every peer catalog identifier already lives) without
180 /// forcing a wire-format rename on the tatara-lisp author surface
181 /// (`:estrategia OneForOne`, `PascalCase`) — the same two-axis
182 /// distinction the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
183 /// / [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
184 /// carry on their peer closed-set typed-enum wire round-trips.
185 ///
186 /// Same closed-set-reverse-projection discipline the sibling
187 /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
188 /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
189 /// [`crate::aplicacao::RateLimitUnit::from_suffix`] typed enums
190 /// carry on the peer wire-side `str → Self` axes — extended onto
191 /// the M2 OTP-shape sibling-restart-strategy closed-set axis, the
192 /// fifth substrate-side closed-set typed enum to converge on the
193 /// two-way `str ↔ Self` round-trip. Method-named `from_wire` (not
194 /// `from_str`) to match the peer [`crate::CaixaKind::from_wire`]
195 /// shape verbatim and side-step the [`std::str::FromStr`] impl the
196 /// derive already installs on the sibling kebab-case axis. Returns
197 /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
198 /// shapes: the caller picks the diagnostic form appropriate for
199 /// its use site.
200 #[must_use]
201 pub fn from_wire(s: &str) -> Option<Self> {
202 match s {
203 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE => Some(Self::OneForOne),
204 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL => Some(Self::OneForAll),
205 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE => Some(Self::RestForOne),
206 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE => Some(Self::SimpleOneForOne),
207 _ => None,
208 }
209 }
210}
211
212/// [`std::fmt::Display`] routed through [`RestartStrategy::as_str`], so the
213/// pretty-printed byte-string every consumer that formats the strategy as
214/// user-facing text lands on (the future wasm-operator's per-supervisor
215/// sibling-restart-strategy diagnostic line, the future `feira app graph`
216/// per-supervisor strategy line, the future M4
217/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission-webhook
218/// rejection body) reaches for the same lifted
219/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
220/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
221/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
222/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const the
223/// wire-format `Serialize` derive already emits under
224/// [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the
225/// [`RestartStrategy::as_str`] helper already returns.
226///
227/// Pre-convergence the two paths structurally disagreed — the
228/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
229/// route (now retired here) sent [`std::fmt::Display`] through the
230/// gen-platform discriminant catalog string, which arrives kebab-case as
231/// `"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
232/// `"simple-one-for-one"`, while the wire format ran as `PascalCase`
233/// `"OneForOne"` / `"OneForAll"` / `"RestForOne"` / `"SimpleOneForOne"`
234/// through the un-`rename`d serde derive. Every consumer that formatted
235/// the strategy for a diagnostic line, a graph, or a rejection body under
236/// `format!("{v}")` therefore landed under a different byte-string than
237/// the wire format the operator's per-strategy dispatch keyed off — a
238/// silent split whose apply-time symptom (a `format!("{v}")`-carrying
239/// diagnostic quoting `"one-for-one"` while the wire scalar the operator
240/// probed was `"OneForOne"`) surfaced as a confused correlate at
241/// operator-log time far from the two-declaration site.
242///
243/// Routing `Display` through [`RestartStrategy::as_str`] closes the third
244/// path: every `format!("{v}")` call reaches the same lifted
245/// [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const the wire format and
246/// the [`RestartStrategy::as_str`] helper route through — `Debug` (the
247/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
248/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
249/// byte-string per variant. A future variant rename or
250/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
251/// exactly one place, structurally.
252///
253/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
254/// (from `#[derive(gen_platform::Discriminant)]`) still returns
255/// `"one-for-one"` / etc., and the fleet-wide
256/// [`gen_platform::register_dispatcher!("caixa.restart-strategy", …)`]
257/// registration keys the catalog off the same kebab identity. The two
258/// naming worlds now live on separate typed methods (`Display` /
259/// `as_str` for the wire byte-string, `discriminant` for the catalog
260/// identity) rather than sharing one `Display` route that structurally
261/// disagrees with the wire format.
262///
263/// Pin tests
264/// [`tests::restart_strategy_display_routes_through_as_str_helper`]
265/// and
266/// [`tests::restart_strategy_display_matches_serialized_wire_byte_string`]
267/// assert the three paths agree byte-for-byte on every variant, so a
268/// future variant rename or per-arm serde attribute drift is a build
269/// error visible at caixa-core test time, not a silent per-consumer
270/// dispatch miss at apply / reconcile time.
271///
272/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
273/// (aplicacao.rs:2306) on the sibling per-Aplicacao distribution-strategy
274/// axis — same three-path-convergence discipline, extended to close the
275/// second of three OTP-shaped closed-enum discriminator axes on the
276/// caixa typed surface.
277impl std::fmt::Display for RestartStrategy {
278 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
279 f.write_str(self.as_str())
280 }
281}
282
283/// Substrate-canonical [`AsRef<str>`] projection on the M2
284/// per-supervisor sibling-restart [`RestartStrategy`] closed-set typed
285/// enum — routes through the same [`RestartStrategy::as_str`]
286/// `pub const fn` scalar accessor the paired [`std::fmt::Display`]
287/// impl and the un-`rename`d [`serde::Serialize`] derive already key
288/// off, so any future consumer that binds a [`RestartStrategy`]
289/// through the standard-library `impl AsRef<str>` bound (a future
290/// [`caixa-feira`] `feira supervisor --estrategia <arm>` verb that
291/// composes the emitted `PascalCase` wire scalar into a
292/// [`std::process::Command::arg`] shell-out of the future
293/// wasm-operator's admission gate, a per-supervisor structured-log
294/// recorder on the future `caixa-operator`'s hierarchical
295/// reconciliation surface that accepts `impl AsRef<str>` at the
296/// `tracing::field::Value` `Str`-arm, a [`std::collections::HashMap`]
297/// lookup keyed on the estrategia wire byte through
298/// `map.get::<str>(strategy.as_ref())` on a future per-strategy
299/// dispatch table) reaches the paired [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`]
300/// / [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
301/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
302/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
303/// lifted-const through one substrate-primitive dispatch rather
304/// than an open-coded `.as_str()` projection at every wire-up.
305///
306/// Peer of the sibling [`std::fmt::Display`] impl on the same
307/// primitive — both delegate to the shared
308/// [`RestartStrategy::as_str`] `pub const fn` accessor, so
309/// [`format!("{s}")`], `s.as_str()`, and
310/// `<RestartStrategy as AsRef<str>>::as_ref(&s)` resolve to the same
311/// byte-string per instance by construction. A future variant rename
312/// or `#[serde(rename_all = "kebab-case")]` attribute-drift on the
313/// enum reaches every one of the three paths (plus the wire-format
314/// `Serialize` derive that already routes through the same lifted
315/// const) through exactly one caixa-core edit.
316///
317/// Same "route the trait impl through the substrate-primitive
318/// accessor" discipline the sibling [`crate::CaixaVersion`]
319/// [`AsRef<str>`] impl (16d5c7e) carries on the paired top-level
320/// `:versao` typed newtype — extends it onto the second `AsRef<str>`
321/// axis on the caixa typed surface (the first M2 OTP-shape
322/// closed-set typed enum to converge onto the standard-library
323/// [`AsRef<str>`] projection). Rust-side newtype/typed-enum
324/// convention pairs [`AsRef<str>`] and [`fmt::Display`] on the same
325/// primitive so a caller who has one has both; before this lift,
326/// [`RestartStrategy`] carried [`fmt::Display`] but not the paired
327/// [`AsRef<str>`] impl the convention names.
328///
329/// Pinned load-bearing by
330/// [`tests::restart_strategy_as_ref_str_routes_through_as_str_accessor`]
331/// (byte-parity pin against [`RestartStrategy::as_str`] across the
332/// four-arm closed set) — any future silent detour that routes the
333/// impl through a divergent projection (a per-arm inline
334/// `match self { … }` re-inlining that opens a compile-time link to
335/// the un-lifted arm-literal, a swap onto the kebab-case
336/// [`gen_platform::Discriminant`] catalog identity that would collide
337/// the wire axis with the dispatcher-catalog axis) trips at
338/// caixa-core test time under `assert_eq!` rather than at a
339/// downstream `impl AsRef<str>`-bound consumer's silent split.
340impl AsRef<str> for RestartStrategy {
341 fn as_ref(&self) -> &str {
342 self.as_str()
343 }
344}
345
346/// Trait-idiomatic reverse projection on the M2-OTP-shape sibling-restart
347/// [`RestartStrategy`] closed-set typed enum — routes byte-for-byte through
348/// the paired substrate-primitive [`RestartStrategy::from_wire`]
349/// `Option<Self>` accessor so every future consumer that binds a
350/// `PascalCase` `:supervisor :estrategia` wire byte-string through the
351/// standard-library `.try_into()` / [`TryFrom`] axis (a future
352/// [`caixa-feira`] `feira supervisor --estrategia <OneForOne|OneForAll|
353/// RestForOne|SimpleOneForOne>` CLI arg-parse that composes into
354/// `let estrategia: RestartStrategy = s.try_into()?`, a future
355/// `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook that folds a
356/// `spec.estrategia: String` field through
357/// `RestartStrategy::try_from(&s)?`, a generic
358/// `<T: TryFrom<&str>>`-bound loader over any of the substrate's closed-
359/// set typed enums) reaches the same four-arm accept-set the sibling
360/// [`RestartStrategy::from_wire`] resolver parses through and the sibling
361/// [`RestartStrategy::as_str`] emits, rather than an open-coded per-arm
362/// `match s { "OneForOne" => …, "OneForAll" => …, "RestForOne" => …,
363/// "SimpleOneForOne" => …, _ => … }` cascade whose arm-set has no
364/// compile-time link back to the substrate primitive.
365///
366/// Complements the pre-existing forward-projection triple
367/// ([`std::fmt::Display`], [`AsRef<str>`], [`RestartStrategy::as_str`])
368/// with the paired trait-idiomatic reverse-projection axis: Rust-side
369/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
370/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so a
371/// caller who can project *out to* a `&str` can also project *in from*
372/// one. The [`TryFrom<&str>`] axis is deliberately chosen over
373/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
374/// lint the sibling method-named [`RestartStrategy::from_wire`] would
375/// trigger under a `FromStr` impl and to avoid colliding with the
376/// [`std::str::FromStr`] impl the [`gen_platform::FromStrKind`] derive
377/// already installs on the paired *kebab-case dispatcher-catalog* axis
378/// (which parses `"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
379/// `"simple-one-for-one"`, the inverse of [`Self::discriminant`]) — this
380/// impl closes the trait-idiomatic reverse axis on the *`PascalCase` wire*
381/// half without disturbing either the method-named `from_wire` shape every
382/// sibling closed-set typed enum on the substrate already carries or the
383/// pre-existing `FromStr` on the dispatcher-catalog half, keeping the
384/// two-axis split the sibling [`Self::from_wire`] doc block motivates.
385///
386/// `type Error = ()` matches the sibling [`RestartStrategy::from_wire`]'s
387/// `Option<Self>` return-shape's deliberate deferral of error typing: the
388/// caller picks the diagnostic form appropriate for its use site (a future
389/// `feira supervisor --estrategia` arg-parse composes its own per-verb
390/// "unknown strategy: <arg> — accepted: {…}" message enumerating
391/// [`RestartStrategy::ALL`], a future M4 admission-webhook rejection body
392/// wraps the `Err(())` outcome with the accepted-set enumeration for
393/// operator diagnostics, a `Result::map_err` at the call site lifts the
394/// unit-error to a per-verb error type). Same shape the peer
395/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136),
396/// [`crate::aplicacao::PlacementStrategy`] (6fd00cd), and
397/// [`crate::provedor::ferrite::FerriteRuntime::from_wire`] blocks motivate
398/// on their peer closed-set typed enums' reverse projections.
399///
400/// The paired [`TryFrom<&str>`] impl reaches the same four-arm accept-set
401/// the [`RestartStrategy::from_wire`] resolver dispatches through, so any
402/// future arm addition (an OTP-`rest_for_all` fifth arm the theory
403/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
404/// might reach for once the four canonical OTP strategies stop covering
405/// the substrate's discovered load-shape) grows the trait-idiomatic axis
406/// by construction — one caixa-core edit on
407/// [`RestartStrategy::from_wire`] extends both the method-named reverse
408/// projection every existing consumer keys off and the trait-idiomatic
409/// reverse projection this impl exposes, without a coordinated rewrite
410/// across every future `TryFrom<&str>`-bound consumer's arm-set.
411///
412/// Extends the substrate-wide closed-set-enum reverse-projection family
413/// ([`crate::CaixaKind`] via 3c83606, [`crate::CaixaDialeto`] via bf33136,
414/// [`crate::aplicacao::PlacementStrategy`] via 6fd00cd) onto the first
415/// M2-OTP-shape closed-set typed enum on the caixa surface — the
416/// `:supervisor :estrategia` closed set the future wasm-operator's
417/// hierarchical reconciliation scheduler keys off end-to-end.
418///
419/// Pinned load-bearing by
420/// [`tests::restart_strategy_try_from_str_routes_through_from_wire_accessor`]
421/// (byte-parity pin against [`RestartStrategy::from_wire`] across the
422/// four-arm accept-set) and
423/// [`tests::restart_strategy_try_from_str_rejects_unknown_byte_strings`]
424/// (rejection witness against silent accept-set widening).
425impl TryFrom<&str> for RestartStrategy {
426 type Error = ();
427
428 fn try_from(s: &str) -> Result<Self, Self::Error> {
429 Self::from_wire(s).ok_or(())
430 }
431}
432
433/// Trait-idiomatic *forward* projection on the M2-OTP-shape sibling-restart
434/// [`RestartStrategy`] closed-set typed enum onto the `&'static str` axis —
435/// routes byte-for-byte through the paired substrate-primitive
436/// [`RestartStrategy::as_str`] `pub const fn` accessor so every future
437/// consumer that binds a [`RestartStrategy`] through the standard-library
438/// `.into()` / [`From<Self> for &'static str`] (equivalently
439/// [`Into<&'static str>`]) axis (a future
440/// `tracing::field::valuable::Value::Str(strategy.into())` structured-log
441/// recorder where the `Str` arm typing demands `&'static str` and the
442/// sibling [`AsRef<str>`] impl's borrowed `&str` return-type does not
443/// satisfy the bound, a future `Cow::Borrowed::<'static, str>(strategy.into())`
444/// composer on the future M4 admission-webhook rejection body where the
445/// `Cow<'static, str>` typing rules out the sibling [`AsRef<str>`] borrowed
446/// return, a generic `<T: Into<&'static str>>`-bound serializer on a
447/// per-strategy diagnostic column) reaches the same lifted
448/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
449/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
450/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
451/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const the
452/// paired [`std::fmt::Display`], [`AsRef<str>`], and
453/// [`RestartStrategy::as_str`] surfaces already return, rather than an
454/// open-coded per-arm `match s { OneForOne => "OneForOne", … }` cascade
455/// whose arm-set has no compile-time link back to the substrate primitive.
456///
457/// Complements the pre-existing quadruple
458/// ([`std::fmt::Display`], [`AsRef<str>`], [`RestartStrategy::as_str`],
459/// [`TryFrom<&str>`] via 5b828ed) with the paired trait-idiomatic
460/// forward-projection axis: Rust-side newtype/typed-enum convention pairs
461/// [`TryFrom<&str>`] (trait-idiomatic reverse) with [`From<Self> for
462/// &'static str`] (trait-idiomatic forward) on the same primitive so a
463/// caller who can project *in from* a `&str` via the trait axis can also
464/// project *out to* one — mirroring the `strum::IntoStaticStr` /
465/// `serde::Serialize`-shape idiom where both projection halves share one
466/// trait-driven vocabulary. Before this lift the substrate carried a
467/// `&str`-returning [`AsRef<str>`] but not the paired `&'static str`-
468/// returning [`From<Self> for &'static str`] axis every downstream
469/// generic that specifically needs `'static` byte-string bytes reaches for.
470///
471/// The paired [`RestartStrategy::as_str`] returns `&'static str` by
472/// construction (each `match` arm resolves to a
473/// [`crate::render::SUPERVISOR_ESTRATEGIA_*`] `pub const &str` with static
474/// lifetime), so the trait's return-type promise is upheld structurally.
475/// Any future silent detour that routes the impl through a non-static
476/// projection (a per-arm inline `String::from("OneForOne")`-shaped
477/// re-inlining that would `.leak()`-cast for the `'static` bound, a
478/// hypothetical rebrand of one arm's [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
479/// const to a non-`const &str`) is a caixa-core-build-time failure through
480/// the `pub const fn as_str` signature the trait routes through.
481///
482/// The paired impl reaches the same four-arm emit-set the
483/// [`RestartStrategy::as_str`] accessor dispatches through, so any future
484/// arm addition (an OTP-`rest_for_all` fifth arm the theory
485/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
486/// might reach for once the four canonical OTP strategies stop covering
487/// the substrate's discovered load-shape) grows the trait-idiomatic
488/// forward axis by construction — one caixa-core edit on
489/// [`RestartStrategy::as_str`] extends every one of the five sibling
490/// forward-projection paths ([`std::fmt::Display`], [`AsRef<str>`],
491/// [`RestartStrategy::as_str`] itself, this [`From<Self> for &'static str`],
492/// and the un-`rename`d [`serde::Serialize`] derive that also emits
493/// [`Self::as_str`]'s bytes) without a coordinated rewrite across every
494/// future `Into<&'static str>`-bound consumer's arm-set.
495///
496/// Opens the substrate-wide trait-idiomatic *forward*-projection family on
497/// closed-set fieldless typed enums — the mirror of the recently-closed
498/// trait-idiomatic *reverse*-projection family ([`crate::CaixaKind`] via
499/// 3c83606, [`crate::CaixaDialeto`] via bf33136,
500/// [`crate::aplicacao::PlacementStrategy`] via 6fd00cd, this enum via
501/// 5b828ed, [`crate::supervisor::RestartPolicy`] via 6fdd0d9,
502/// [`crate::aplicacao::WitShape`] via 5472902,
503/// [`crate::aplicacao::RateLimitUnit`] via bf78400,
504/// [`crate::render::PathShapeViolation`] via e67e48a, and the four
505/// downstream-crate peers — [`caixa_arch::InvariantKind`] via e21a857,
506/// [`caixa_arch::ArchVerdict`] via 0a4cc45, [`caixa_lint::Severity`] via
507/// a7bf74c, [`caixa_lint::FixSafety`] via df86c94,
508/// [`caixa_theme::Semantic`] via bd7da69, and
509/// [`caixa_provedor::ferrite::FerriteRuntime`] via 42ab951). This lift
510/// picks [`RestartStrategy`] as the first-mover on the forward-projection
511/// family because its wire byte-string (`PascalCase`) and diagnostic
512/// byte-string ([`as_str`] return) coincide by construction — the sibling
513/// [`crate::CaixaKind`] two-axis split (lowercase Portuguese diagnostic
514/// vs `PascalCase` wire) would leave a first-mover peer arbitrarily
515/// picking one axis; on [`RestartStrategy`] the choice is unambiguous.
516///
517/// Pinned load-bearing by
518/// [`tests::restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
519/// (byte-parity pin against [`RestartStrategy::as_str`] across the
520/// four-arm emit-set, plus a `const`-context materialization witness for
521/// the `&'static str` lifetime promise) and
522/// [`tests::restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
523/// (partition pin asserting `<&'static str as From<RestartStrategy>>::from`
524/// and [`RestartStrategy::as_str`] agree on every arm, so no future
525/// silent bifurcation of the two forward-projection paths can land
526/// silently).
527impl From<RestartStrategy> for &'static str {
528 fn from(strategy: RestartStrategy) -> &'static str {
529 strategy.as_str()
530 }
531}
532
533/// Trait-idiomatic *forward* projection on [`RestartStrategy`] from a
534/// *borrowed* input onto the `&'static str` axis — the borrowed-input
535/// companion to the paired owned-input [`From<RestartStrategy> for
536/// &'static str`] impl immediately above. Routes byte-for-byte through
537/// the same substrate-primitive [`RestartStrategy::as_str`] `pub const
538/// fn` accessor so every consumer that binds a `&RestartStrategy`
539/// through the standard-library `.into()` / [`From<&Self> for &'static
540/// str`] axis (a `RestartStrategy::ALL.iter().map(<&'static
541/// str>::from).collect::<Vec<_>>()` per-arm accept-set materializer —
542/// whose iterator over `&'static [RestartStrategy]` yields
543/// `&RestartStrategy`, not `RestartStrategy`, so the owned-input
544/// [`From<RestartStrategy>`] axis alone forces every call site through
545/// an explicit `.copied()` / dereference / [`Copy`]-bound restatement
546/// rather than the direct trait-idiomatic projection; a future generic
547/// `<T: Copy + for<'a> Into<&'static str>>`-bound diagnostic column
548/// that walks the `iter().map(Into::into)` shape verbatim across every
549/// substrate-wide closed-set typed enum; the future wasm-operator's
550/// per-supervisor sibling-restart-strategy diagnostic line that
551/// composes the accepted-set enumeration from an iterated
552/// `RestartStrategy::ALL.iter().map(|s| s.into())` pipe rather than a
553/// per-arm `match s { … }` cascade; a future
554/// `HashMap::<&'static str, RestartStrategy>::from_iter(
555/// RestartStrategy::ALL.iter().map(|s| (s.into(), *s)))`-style
556/// per-strategy reverse-lookup table the sibling [`TryFrom<&str>`]
557/// impl cannot compose without this borrowed-input axis in place)
558/// reaches the same four-arm lifted
559/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
560/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
561/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
562/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
563/// the paired owned-input [`From<RestartStrategy> for &'static str`],
564/// the sibling [`std::fmt::Display`], [`AsRef<str>`], and
565/// [`RestartStrategy::as_str`] surfaces already return.
566///
567/// Fourth peer on the substrate-wide trait-idiomatic *borrowed-input*
568/// forward-projection family opened on [`crate::dep::DepList`]
569/// (64aa742) and extended onto [`crate::CaixaKind`] (5ab993a) and
570/// [`crate::CaixaDialeto`] (807b0b5). Rust's `From` trait does not
571/// auto-derive the `From<&Self>` sibling from a `From<Self>` impl (the
572/// blanket `impl<T, U> From<&T> for U where T: Copy, U: From<T>` does
573/// not exist in `core`), so every closed-set typed enum that carries
574/// the owned-input axis but not the borrowed-input axis forces every
575/// borrowed-input call site through a `.copied()` /
576/// `<&'static str>::from(*strategy)` / `strategy.as_str()` detour whose
577/// type bounds have no compile-time link to the substrate primitive.
578/// [`RestartStrategy`] is the first M2 OTP-shape peer to converge onto
579/// this campaign (mirroring the first-mover role it played on the
580/// owned-input axis in 523157d); the remaining eleven substrate-wide
581/// closed-set fieldless typed enum peers (`RestartPolicy`, `WitShape`,
582/// `RateLimitUnit`, `PlacementStrategy`, `PathShapeViolation`,
583/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
584/// `FerriteRuntime`) are the future targets of this campaign.
585///
586/// Unlike the peer [`crate::CaixaKind`] axis pair (whose forward
587/// [`From<Self> for &'static str`] emits the lowercase Portuguese
588/// [`Self::as_str`] diagnostic vocabulary while the reverse
589/// [`TryFrom<&str>`] parses the `PascalCase` [`Self::wire_name`]
590/// author-surface vocabulary, forcing the round-trip through an
591/// intermediate wire-vocab hop), [`RestartStrategy`]'s
592/// [`Self::as_str`] emit and [`Self::from_wire`] parse share the same
593/// `PascalCase` vocabulary by construction, so the borrowed-input
594/// forward axis and the reverse axis compose directly — the round-trip
595/// witness pin below locks this direct composition without the
596/// intermediate hop the peer axis requires.
597///
598/// Pinned load-bearing by
599/// [`tests::restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
600/// (byte-parity pin against [`RestartStrategy::as_str`] across the
601/// four-arm emit-set via a borrowed input, plus a `const`-context
602/// materialization witness for the `&'static str` lifetime promise,
603/// plus a blanket `.into()` shape) and
604/// [`tests::restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
605/// (cross-axis partition pin against the paired owned-input
606/// [`From<RestartStrategy> for &'static str`] impl, plus a
607/// `.iter().map(Into::into)` pipe witness over
608/// [`RestartStrategy::ALL`], plus a direct round-trip witness through
609/// [`TryFrom<&str>`] that closes the two-way `&Self → &'static str →
610/// Self` round-trip without the wire-vocab intermediate the peer
611/// [`crate::CaixaKind`] axis pair requires).
612impl From<&RestartStrategy> for &'static str {
613 fn from(strategy: &RestartStrategy) -> &'static str {
614 strategy.as_str()
615 }
616}
617
618/// Trait-idiomatic *owned-`String`* forward projection on the M2
619/// OTP-shape sibling-restart-strategy closed-set typed enum — the
620/// owned-heap-string companion to the paired `&'static str`-returning
621/// [`From<RestartStrategy> for &'static str`] / [`From<&RestartStrategy>
622/// for &'static str`] impls immediately above. Routes byte-for-byte
623/// through the substrate-primitive [`RestartStrategy::as_str`]
624/// `pub const fn` accessor (via [`str::to_owned`]) so every consumer
625/// that binds a [`RestartStrategy`] through the standard-library
626/// `.into()` / [`From<Self> for String`] (equivalently
627/// [`Into<String>`]) axis — a future
628/// `serde_json::Value::String(strategy.into())` structured-payload
629/// composer where the `Value::String` arm typing demands an owned
630/// [`String`] and the sibling [`&'static str`]-returning axis forces an
631/// explicit `.to_owned()` / `String::from` restatement at every call
632/// site, a future
633/// `HashMap::<String, RestartStrategy>::from_iter(RestartStrategy::ALL
634/// .iter().map(|s| (s.into(), *s)))` per-strategy lookup where the
635/// map's key type is owned [`String`] rather than [`&'static str`], a
636/// future `Cow::<'static, str>::Owned(strategy.into())` composer on
637/// the future M4 admission-webhook rejection body's owned-arm, the
638/// future wasm-operator's per-supervisor `serde_json::json!({
639/// "estrategia": strategy })` diagnostic emit where the JSON
640/// serializer's `Serialize` impl on [`String`] owns the emit-path — reaches
641/// the same four-arm lifted
642/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
643/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
644/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
645/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const the
646/// paired [`std::fmt::Display`], [`AsRef<str>`],
647/// [`RestartStrategy::as_str`], and the two `&'static str`-returning
648/// forward-projection impls already return.
649///
650/// Opens the trait-idiomatic *owned-`String`* forward-projection axis
651/// on the closed-set fieldless typed enum surface — first-mover on the
652/// M2 OTP-shape sibling-restart-strategy axis, mirror of the
653/// [`crate::supervisor::RestartStrategy`] first-mover position that
654/// opened the paired owned-`&'static str` axis (523157d) and the
655/// borrowed-input `&'static str` axis on
656/// [`crate::dep::DepList`] (64aa742). Rust's standard library does not
657/// carry a blanket `impl<T: AsRef<str>> From<T> for String` (nor an
658/// `impl<T: fmt::Display> From<T> for String`), so every closed-set
659/// typed enum that carries the paired `AsRef<str>` / `Display` /
660/// `From<Self> for &'static str` triple but not the owned-[`String`]
661/// axis forces every owned-string call site through a `.to_string()` /
662/// `.as_str().to_owned()` / `String::from(strategy.as_str())` detour
663/// whose type bounds have no compile-time link to the substrate
664/// primitive.
665///
666/// Deliberately routes through the human-readable
667/// [`RestartStrategy::as_str`] axis — for this enum the wire format
668/// (`PascalCase`, tatara-lisp author surface `:estrategia OneForOne`)
669/// and the diagnostic byte-string share the same vocabulary by
670/// construction (unlike the sibling [`crate::CaixaKind`] enum whose two
671/// axes diverge), so the owned-[`String`] projection lands
672/// byte-identically on both the wire vocabulary the paired
673/// [`serde::Serialize`] derive emits and the diagnostic vocabulary the
674/// [`RestartStrategy::as_str`] helper returns.
675///
676/// The remaining fourteen closed-set typed enums on the caixa
677/// substrate surface (`RestartPolicy`, `CaixaKind`, `CaixaDialeto`,
678/// `DepList`, `PlacementStrategy`, `WitShape`, `RateLimitUnit`,
679/// `PathShapeViolation`, `InvariantKind`, `ArchVerdict`, `Severity`,
680/// `FixSafety`, `Semantic`, `FerriteRuntime`) are the future targets of
681/// this campaign — each carries the same paired `AsRef<str>` /
682/// `Display` / `From<Self> for &'static str` / `From<&Self> for
683/// &'static str` quadruple that this owned-[`String`] axis extends onto.
684///
685/// Pinned load-bearing by
686/// [`tests::restart_strategy_from_into_owned_string_routes_through_as_str_accessor`]
687/// (byte-parity pin against [`RestartStrategy::as_str`] across the
688/// four-arm emit-set, plus a blanket `.into::<String>()` shape witness)
689/// and
690/// [`tests::restart_strategy_from_into_owned_string_and_static_str_agree_on_every_arm`]
691/// (cross-axis partition pin against the paired owned-input
692/// [`From<RestartStrategy> for &'static str`] impl and the sibling
693/// [`ToString::to_string`] surface routed through [`std::fmt::Display`],
694/// plus a direct round-trip witness through [`TryFrom<&str>`] on the
695/// owned-[`String`]'s [`String::as_str`] borrow that closes the two-way
696/// `Self → String → Self` round-trip on the trait-idiomatic
697/// owned-[`String`] forward + reverse axis pair).
698impl From<RestartStrategy> for String {
699 fn from(strategy: RestartStrategy) -> String {
700 strategy.as_str().to_owned()
701 }
702}
703
704/// Trait-idiomatic *borrowed-input, owned-`String` output* forward
705/// projection on the M2 OTP-shape sibling-restart-strategy closed-set
706/// typed enum — the fourth (and closing) corner of the
707/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
708/// projection family. Routes byte-for-byte through the
709/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
710/// accessor (via [`str::to_owned`]) so every consumer that holds a
711/// borrowed [`&RestartStrategy`] and needs an owned [`String`] — a
712/// future `serde_json::Value::String(String::from(&strategy))`
713/// structured-payload composer over a borrowed field, a future
714/// `Iterator::map` over `&[RestartStrategy]` that projects to owned
715/// keys through `.iter().map(String::from)`, a future
716/// `HashMap::<String, RestartStrategy>::from_iter` that keys off a
717/// borrowed-iteration axis where dereferencing the strategy would force
718/// an unnecessary `Copy` at every step, the future wasm-operator's
719/// per-supervisor `strategies.iter().map(String::from).collect()`
720/// diagnostic emit whose iteration axis is borrowed by construction —
721/// reaches the same four-arm lifted
722/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
723/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
724/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
725/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const the
726/// paired [`std::fmt::Display`], [`AsRef<str>`],
727/// [`RestartStrategy::as_str`], and the three other trait-idiomatic
728/// forward-projection impls
729/// ([`From<RestartStrategy> for &'static str`],
730/// [`From<&RestartStrategy> for &'static str`],
731/// [`From<RestartStrategy> for String`]) already return.
732///
733/// Opens the trait-idiomatic *borrowed-input, owned-`String` output*
734/// forward-projection axis on closed-set fieldless typed enums —
735/// first-mover on the 2×2 completion corner, mirror of the
736/// [`crate::supervisor::RestartStrategy`] first-mover position that
737/// opened the paired owned-input owned-`String` axis (7baa18a), the
738/// owned-input owned-`&'static str` axis (523157d), and the paired
739/// [`crate::dep::DepList`] first-mover position that opened the
740/// borrowed-input `&'static str` axis (64aa742). Rust's standard
741/// library does not carry a blanket `impl<T: AsRef<str>> From<&T> for
742/// String` (nor an `impl<T: fmt::Display> From<&T> for String`), so
743/// every closed-set typed enum that carries the paired `AsRef<str>` /
744/// `Display` / `From<Self> for &'static str` / `From<&Self> for
745/// &'static str` / `From<Self> for String` quintuple but not the
746/// borrowed-input owned-[`String`] axis forces every borrowed-input
747/// owned-string call site through a `strategy.as_str().to_owned()` /
748/// `String::from(*strategy)` (with a spurious `Copy`) /
749/// `strategy.to_string()` (through `Display`) detour whose type bounds
750/// have no compile-time link to the substrate primitive.
751///
752/// Deliberately routes through the human-readable
753/// [`RestartStrategy::as_str`] axis — for this enum the wire format
754/// (`PascalCase`, tatara-lisp author surface `:estrategia OneForOne`)
755/// and the diagnostic byte-string share the same vocabulary by
756/// construction (unlike the sibling [`crate::CaixaKind`] enum whose two
757/// axes diverge), so the borrowed-input owned-[`String`] projection
758/// lands byte-identically on both the wire vocabulary the paired
759/// [`serde::Serialize`] derive emits and the diagnostic vocabulary the
760/// [`RestartStrategy::as_str`] helper returns.
761///
762/// The remaining fourteen closed-set typed enums on the caixa
763/// substrate surface (`RestartPolicy`, `CaixaKind`, `CaixaDialeto`,
764/// `DepList`, `PlacementStrategy`, `WitShape`, `RateLimitUnit`,
765/// `PathShapeViolation`, `InvariantKind`, `ArchVerdict`, `Severity`,
766/// `FixSafety`, `Semantic`, `FerriteRuntime`) are the future targets of
767/// this 2×2-completion campaign — each carries the same paired
768/// quintuple that this borrowed-input owned-[`String`] axis extends onto.
769///
770/// Pinned load-bearing by
771/// [`tests::restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
772/// (byte-parity pin against [`RestartStrategy::as_str`] across the
773/// four-arm emit-set through the borrowed-input surface) and
774/// [`tests::restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
775/// (cross-axis partition pin against the paired owned-input owned-
776/// [`String`] [`From<RestartStrategy> for String`] impl, the paired
777/// borrowed-input owned-[`&'static str`] [`From<&RestartStrategy> for
778/// &'static str`] impl, and the sibling [`ToString::to_string`] surface
779/// routed through [`std::fmt::Display`], plus a direct round-trip
780/// witness through [`TryFrom<&str>`] on the owned-[`String`]'s
781/// [`String::as_str`] borrow that closes the two-way
782/// `&Self → String → Self` round-trip on the trait-idiomatic
783/// borrowed-input owned-[`String`] forward + reverse axis pair).
784impl From<&RestartStrategy> for String {
785 fn from(strategy: &RestartStrategy) -> String {
786 strategy.as_str().to_owned()
787 }
788}
789
790/// Trait-idiomatic *owned-input, [`std::borrow::Cow<'static, str>`]
791/// output* forward projection on the M2 OTP-shape sibling-restart
792/// [`RestartStrategy`] closed-set typed enum — extends the substrate-
793/// wide [`std::borrow::Cow<'static, str>`] forward-projection family
794/// opened on [`crate::CaixaKind`] (99c1735) onto the first M2 OTP-
795/// shape closed-set fieldless typed enum peer on the caixa surface
796/// (`:supervisor :estrategia`). Routes byte-for-byte through the
797/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
798/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
799/// that binds a [`RestartStrategy`] through the trait-idiomatic
800/// [`std::borrow::Cow<'static, str>`] axis — a future
801/// `axum::response::IntoResponse` composer whose per-strategy
802/// diagnostic-body typing rules out the sibling [`AsRef<str>`]
803/// borrowed return, a future M4 admission-webhook rejection body
804/// that composes the accepted-strategy enumeration through the same
805/// `RestartStrategy::ALL.iter().map(Cow::from)` shape [`CaixaKind`]
806/// already routes through, a generic `<T: for<'a>
807/// Into<std::borrow::Cow<'static, str>>>`-bound structured-log
808/// emitter on a per-supervisor diagnostic column — reaches the same
809/// four-arm lifted [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`]
810/// / [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
811/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
812/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
813/// the paired [`std::fmt::Display`], [`AsRef<str>`],
814/// [`RestartStrategy::as_str`], and the four
815/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
816/// forward-projection corners already return.
817///
818/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
819/// [`std::borrow::Cow::Owned`] — the substrate-primitive
820/// [`RestartStrategy::as_str`] accessor's return carries the
821/// `&'static str` lifetime by construction (each `match` arm resolves
822/// to a [`crate::render::SUPERVISOR_ESTRATEGIA_*`] `pub const &str`
823/// with static lifetime), so the zero-alloc borrowed arm is the
824/// type-correct projection with no runtime allocation.
825///
826/// Rust's standard library carries no blanket `impl<T: AsRef<str>>
827/// From<T> for Cow<'static, str>` (nor an `impl<T: fmt::Display>
828/// From<T> for Cow<'static, str>`), so the paired sibling
829/// [`From<RestartStrategy> for &'static str`],
830/// [`From<RestartStrategy> for String`], [`AsRef<str>`], and
831/// [`std::fmt::Display`] surfaces do not implicitly extend to a
832/// [`Cow<'static, str>`]-bound call site — every such site is forced
833/// through a `Cow::Borrowed(strategy.as_str())` /
834/// `Cow::Owned(strategy.to_string())` open-code whose type bounds
835/// have no compile-time link back to the substrate primitive until
836/// this lift.
837///
838/// First peer to extend the substrate-wide trait-idiomatic
839/// [`std::borrow::Cow<'static, str>`] forward-projection axis off the
840/// top-level [`crate::CaixaKind`] enum (99c1735 owned-input,
841/// d45c409 borrowed-input) onto the wider substrate — the remaining
842/// twelve peers (`RestartPolicy`, `PlacementStrategy`, `RateLimitUnit`,
843/// `DepList`, `CaixaDialeto`, and the outside-`caixa-core` peers
844/// `WitShape`, `PathShapeViolation`, `InvariantKind`, `ArchVerdict`,
845/// `Severity`, `FixSafety`, `Semantic`, `FerriteRuntime`) are the
846/// future targets of this campaign.
847///
848/// Pinned load-bearing by
849/// [`tests::restart_strategy_from_into_static_cow_str_routes_through_as_str_accessor`]
850/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
851/// against [`RestartStrategy::as_str`] across the four-arm
852/// [`RestartStrategy::ALL`]) and
853/// [`tests::restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
854/// (cross-axis partition pin against the paired [`From<RestartStrategy>
855/// for &'static str`], [`From<RestartStrategy> for String`], and
856/// [`ToString`]-through-[`std::fmt::Display`] axes, plus a
857/// `.iter().copied().map(Cow::from)` pipe witness over
858/// [`RestartStrategy::ALL`] that materializes the four-arm accept-set
859/// through the [`Cow<'static, str>`] axis alone and pins the
860/// zero-alloc discipline on every element).
861impl From<RestartStrategy> for std::borrow::Cow<'static, str> {
862 fn from(strategy: RestartStrategy) -> std::borrow::Cow<'static, str> {
863 std::borrow::Cow::Borrowed(strategy.as_str())
864 }
865}
866
867/// Trait-idiomatic *borrowed-input, [`std::borrow::Cow<'static, str>`]
868/// output* forward projection on the M2 OTP-shape sibling-restart
869/// [`RestartStrategy`] closed-set typed enum — the borrowed-input
870/// companion to the paired owned-input
871/// [`From<RestartStrategy> for std::borrow::Cow<'static, str>`] impl
872/// immediately above (7dd28b3). Routes byte-for-byte through the same
873/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
874/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
875/// that holds a `&RestartStrategy` and needs a
876/// [`std::borrow::Cow<'static, str>`] — a
877/// `RestartStrategy::ALL.iter().map(std::borrow::Cow::from).collect::<Vec<_>>()`
878/// per-arm accept-set materializer (whose iterator over
879/// `&'static [RestartStrategy]` yields `&RestartStrategy`, not
880/// `RestartStrategy`, so the paired owned-input
881/// [`From<RestartStrategy> for std::borrow::Cow<'static, str>`] axis
882/// alone forces every call site through an explicit `.copied()` /
883/// dereference / [`Copy`]-bound restatement rather than the direct
884/// trait-idiomatic projection), a future generic
885/// `<T: for<'a> Into<std::borrow::Cow<'static, str>>>`-bound emitter
886/// on a per-strategy diagnostic column that walks the
887/// `iter().map(Into::into)` shape verbatim, the future M4 admission-
888/// webhook rejection body that composes the accepted-strategy
889/// enumeration from an iterated
890/// `RestartStrategy::ALL.iter().map(|s| s.into())` pipe rather than a
891/// per-arm `match s { … }` cascade — reaches the same four-arm lifted
892/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
893/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
894/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
895/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
896/// the paired [`std::fmt::Display`], [`AsRef<str>`],
897/// [`RestartStrategy::as_str`], the four
898/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
899/// forward-projection corners, and the paired owned-input
900/// [`From<RestartStrategy> for std::borrow::Cow<'static, str>`] impl
901/// already return.
902///
903/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
904/// [`std::borrow::Cow::Owned`] — the substrate-primitive
905/// [`RestartStrategy::as_str`] accessor's return carries the
906/// `&'static str` lifetime by construction (each `match` arm resolves
907/// to a [`crate::render::SUPERVISOR_ESTRATEGIA_*`] `pub const &str`
908/// with static lifetime), so the zero-alloc borrowed arm is the
909/// type-correct projection with no runtime allocation.
910///
911/// Second peer on the substrate-wide trait-idiomatic
912/// [`std::borrow::Cow<'static, str>`] forward-projection family
913/// opened one commit prior (7dd28b3) on the paired owned-input
914/// [`From<RestartStrategy> for std::borrow::Cow<'static, str>`] impl
915/// — closes the `{Self, &Self}` input-shape corner of the
916/// [`Cow<'static, str>`] axis on the first M2 OTP-shape closed-set
917/// fieldless typed enum peer on the caixa surface, exactly as
918/// d45c409 closed it on the top-level [`crate::CaixaKind`] one commit
919/// after the owning half (99c1735) landed. Rust's standard library
920/// does not carry a blanket `impl<T: AsRef<str>> From<&T> for
921/// Cow<'static, str>` (nor an `impl<T: fmt::Display> From<&T> for
922/// Cow<'static, str>`), so every closed-set fieldless typed enum peer
923/// on the substrate that carries the paired owned-input
924/// [`Cow<'static, str>`] axis but not the borrowed-input axis forces
925/// every borrowed-input [`Cow<'static, str>`]-parameterized call site
926/// through a spurious [`Copy`] deref
927/// (`std::borrow::Cow::from(*strategy)`) or a
928/// `std::borrow::Cow::Borrowed(strategy.as_str())` open-code whose
929/// type bounds have no compile-time link to the substrate primitive.
930///
931/// Pinned load-bearing by
932/// [`tests::restart_strategy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor`]
933/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
934/// against [`RestartStrategy::as_str`] across the four-arm
935/// [`RestartStrategy::ALL`] through the borrowed-input surface) and
936/// [`tests::restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
937/// (cross-axis partition pin against the paired owned-input
938/// [`From<RestartStrategy> for std::borrow::Cow<'static, str>`], the
939/// paired borrowed-input owned-`&'static str`
940/// [`From<&RestartStrategy> for &'static str`], and the paired
941/// borrowed-input owned-`String` [`From<&RestartStrategy> for String`]
942/// impls, plus a `.iter().map(std::borrow::Cow::from)` pipe witness
943/// over [`RestartStrategy::ALL`] — whose iterator yields
944/// `&RestartStrategy` by construction, so the borrowed-input
945/// [`Cow<'static, str>`] axis is what routes the pipe through the
946/// substrate-primitive [`RestartStrategy::as_str`] accessor with the
947/// zero-alloc [`Cow::Borrowed`] arm by construction and without a
948/// spurious [`Copy`] deref).
949impl From<&RestartStrategy> for std::borrow::Cow<'static, str> {
950 fn from(strategy: &RestartStrategy) -> std::borrow::Cow<'static, str> {
951 std::borrow::Cow::Borrowed(strategy.as_str())
952 }
953}
954
955/// Per-child restart policy.
956///
957/// Permanent / Temporary / Transient match Erlang/OTP semantics 1:1.
958#[derive(
959 Serialize,
960 Deserialize,
961 Debug,
962 Clone,
963 Copy,
964 PartialEq,
965 Eq,
966 Hash,
967 gen_platform::TypedDispatcher,
968 gen_platform::Discriminant,
969 gen_platform::IsVariant,
970 gen_platform::FromStrKind,
971)]
972pub enum RestartPolicy {
973 /// Always restart the child, regardless of how it died. Used for
974 /// long-running services that must always be up.
975 Permanent,
976 /// Never restart. Used for one-shot work whose completion is
977 /// itself the success signal (`oneShot` triggers map here).
978 Temporary,
979 /// Restart only when the child died *abnormally* (non-zero exit
980 /// or unhandled exception). A clean exit completes the child.
981 Transient,
982}
983
984impl Default for RestartPolicy {
985 fn default() -> Self {
986 // Route the [`Default for RestartPolicy`] impl's return arm through
987 // the substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed
988 // `pub const` rather than a raw `Self::Permanent` arm — one source
989 // of truth for the Erlang/OTP-canonical `permanent` worker-child
990 // default across the two production consumers that currently
991 // dispatch on it (this impl at the [`RestartPolicy::default`] call
992 // and the serde-side `#[serde(default)]` on
993 // [`ChildSpec::restart`] that resolves an author-omitted
994 // `:children :restart` slot through `RestartPolicy::default()`).
995 // Peer of the sibling per-`:supervisor` axis
996 // [`Default for RestartStrategy`] → [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
997 // route (95ffacc) — the two impls now share one substrate-primitive
998 // lift discipline, so any future coherent rebrand of the OTP-shape
999 // supervisor+child default set migrates through typed constants in
1000 // lockstep instead of splitting a lifted supervisor half against
1001 // an open-coded child half. Pinned by
1002 // `restart_policy_default_routes_through_lifted_default` +
1003 // `child_spec_serde_default_restart_routes_through_lifted_default`
1004 // in the tests module.
1005 SUPERVISOR_CHILD_RESTART_DEFAULT
1006 }
1007}
1008
1009impl RestartPolicy {
1010 /// Exhaustive iteration surface for every consumer that walks the
1011 /// closed three-arm [`RestartPolicy`] discriminator set (the future
1012 /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1013 /// per-child admission-webhook rejection body naming the accepted-
1014 /// `:restart` list, a future `feira supervisor --restart …` CLI
1015 /// arg-parse's "did you mean" hint via a [`Self::from_wire`]-scan
1016 /// over the slice, the future `feira app graph` per-child restart
1017 /// column, any future round-trip fuzz harness that sweeps every
1018 /// arm). A future arm addition (an OTP-`intrinsic` fourth arm the
1019 /// theory
1020 /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1021 /// might reach for once the three canonical OTP restart policies
1022 /// stop covering the substrate's discovered load-shape) extends
1023 /// this slice as one edit and every consumer picks up the new entry
1024 /// by construction; the compiler-checked exhaustiveness on the
1025 /// sibling method `match` arms ([`Self::as_str`] / [`Self::from_wire`])
1026 /// is the build-time guarantee that no arm forgets to grow.
1027 ///
1028 /// Peer of the sibling closed-set typed enums'
1029 /// [`RestartStrategy::ALL`] (4eec29c) /
1030 /// [`crate::CaixaKind::ALL`] (6b1f4fb) /
1031 /// [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
1032 /// [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
1033 /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
1034 /// surfaces — the sixth (and the third and final M2 OTP-shape)
1035 /// closed-set typed enum on the caixa surface to converge onto the
1036 /// same one-canonical-arm-list-per-enum discipline. Sibling axis to
1037 /// the peer [`RestartStrategy::ALL`] on the per-supervisor
1038 /// sibling-restart-strategy axis; this closes the per-child
1039 /// restart-decision-policy axis on the same M2 `:supervisor` slot.
1040 pub const ALL: &'static [Self] = &[Self::Permanent, Self::Temporary, Self::Transient];
1041
1042 /// Canonical PascalCase discriminator scalar this variant serializes
1043 /// as under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`]. The three
1044 /// arms return the paired
1045 /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1046 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1047 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] lifted
1048 /// constants so every substrate consumer that dispatches on the
1049 /// per-child restart-decision policy (the future wasm-operator's
1050 /// per-child post-exit restart-decision branch, the future M4
1051 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1052 /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
1053 /// reconciliation scheduler's per-child-policy fan-out) reads the
1054 /// same byte-string the `Serialize` derive emits — the pin test in
1055 /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
1056 /// asserts the two paths agree, peer of the M2
1057 /// [`RestartStrategy::as_str`] (09ffb2d) on the sibling per-supervisor
1058 /// sibling-restart-strategy axis and the M3
1059 /// [`crate::aplicacao::PlacementStrategy::as_str`] (cc8f749) on the
1060 /// per-Aplicacao distribution-strategy axis — the third of three
1061 /// OTP-shaped closed-enum discriminator axes on the caixa typed
1062 /// surface to converge onto the same three-path-convergence
1063 /// (`Serialize` derive → `as_str` helper → lifted constant)
1064 /// drift-detection posture.
1065 #[must_use]
1066 pub const fn as_str(self) -> &'static str {
1067 match self {
1068 Self::Permanent => crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
1069 Self::Temporary => crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
1070 Self::Transient => crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
1071 }
1072 }
1073
1074 /// Substrate-canonical reverse projection on the `:children :restart`
1075 /// closed-set axis — parses the `PascalCase` discriminator scalar
1076 /// back to the typed variant, or `None` when `s` is outside the
1077 /// closed-set arm-string set [`Self::as_str`] emits. Dispatches on
1078 /// the same lifted
1079 /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1080 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1081 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] constants
1082 /// the [`Self::as_str`] emitter walks, so the parse and emit halves
1083 /// of the round-trip migrate through one caixa-core edit on any
1084 /// future arm addition.
1085 ///
1086 /// Prior to this lift the substrate carried only the forward
1087 /// `Self → &str` projection on the OTP per-child restart-policy
1088 /// axis (the [`Self::as_str`] emitter, the [`std::fmt::Display`]
1089 /// impl routed through it, the `Serialize` derive that emits the
1090 /// same byte-string under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`])
1091 /// plus the kebab-case dispatcher-catalog identity via
1092 /// [`Self::discriminant`] — every non-serde consumer that wanted to
1093 /// parse a wire-form `PascalCase` policy scalar had to re-inline a
1094 /// three-arm `match s { "Permanent" => …, "Temporary" => …,
1095 /// "Transient" => …, _ => … }` cascade that expressed no
1096 /// compile-time link back to the typed variant's canonical lifted
1097 /// constant. A future variant rename or per-arm serde-attribute
1098 /// drift would silently split the wire byte-string one non-serde
1099 /// consumer parsed from the one the emitter wrote, with the failure
1100 /// surfacing at the operator's reconcile posture (a `:temporary`
1101 /// `oneShot` child being restarted on clean exit, treating the
1102 /// successful-completion signal as failure and re-running the
1103 /// completion-terminal one-shot indefinitely; a `:transient` child
1104 /// that clean-exited being restarted, masking the clean-completion
1105 /// contract) far from the rebrand commit and with no field naming
1106 /// the drift.
1107 ///
1108 /// Distinct axis from the [`std::str::FromStr`] impl the
1109 /// [`gen_platform::FromStrKind`] derive already installs on this
1110 /// enum by design, not by drift: `FromStr` parses the *kebab-case*
1111 /// dispatcher-catalog identity (`"permanent"` / `"temporary"` /
1112 /// `"transient"` — the inverse of [`Self::discriminant`]), while
1113 /// this method inverts the `PascalCase` wire byte-string
1114 /// [`Self::as_str`] emits. The two-axis split lets the dispatcher-
1115 /// catalog identity live in kebab-case (where every peer catalog
1116 /// identifier already lives) without forcing a wire-format rename
1117 /// on the tatara-lisp author surface (`:restart Permanent`,
1118 /// `PascalCase`) — the same two-axis distinction the sibling
1119 /// [`RestartStrategy::from_wire`] (4eec29c) /
1120 /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
1121 /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
1122 /// carry on their peer closed-set typed-enum wire round-trips.
1123 ///
1124 /// Same closed-set-reverse-projection discipline the sibling
1125 /// [`RestartStrategy::from_wire`] (4eec29c) /
1126 /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
1127 /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
1128 /// [`crate::aplicacao::RateLimitUnit::from_suffix`] typed enums
1129 /// carry on the peer wire-side `str → Self` axes — extended onto
1130 /// the M2 OTP-shape per-child restart-policy closed-set axis, the
1131 /// sixth substrate-side closed-set typed enum (and the third and
1132 /// final OTP-shape closed-enum discriminator axis) to converge on
1133 /// the two-way `str ↔ Self` round-trip. Method-named `from_wire`
1134 /// (not `from_str`) to match the peer [`RestartStrategy::from_wire`]
1135 /// shape verbatim and side-step the [`std::str::FromStr`] impl the
1136 /// derive already installs on the sibling kebab-case axis. Returns
1137 /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
1138 /// shapes: the caller picks the diagnostic form appropriate for
1139 /// its use site.
1140 #[must_use]
1141 pub fn from_wire(s: &str) -> Option<Self> {
1142 match s {
1143 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT => Some(Self::Permanent),
1144 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY => Some(Self::Temporary),
1145 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT => Some(Self::Transient),
1146 _ => None,
1147 }
1148 }
1149}
1150
1151/// [`std::fmt::Display`] routed through [`RestartPolicy::as_str`], so the
1152/// pretty-printed byte-string every consumer that formats the policy as
1153/// user-facing text lands on (the future wasm-operator's per-child
1154/// post-exit restart-decision diagnostic line, the future `feira app
1155/// graph` per-child restart column, the future M4
1156/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1157/// admission-webhook rejection body) reaches for the same lifted
1158/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1159/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1160/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1161/// wire-format `Serialize` derive already emits under
1162/// [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
1163/// [`RestartPolicy::as_str`] helper already returns.
1164///
1165/// Pre-convergence the two paths structurally disagreed — the
1166/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
1167/// route (now retired here) sent [`std::fmt::Display`] through the
1168/// gen-platform discriminant catalog string, which arrives kebab-case as
1169/// `"permanent"` / `"temporary"` / `"transient"` on this three-arm enum
1170/// (whose variant names each collapse to their own lowercase form under
1171/// the kebab-case transform), while the wire format ran as `PascalCase`
1172/// `"Permanent"` / `"Temporary"` / `"Transient"` through the un-`rename`d
1173/// serde derive. Every consumer that formatted the policy for a
1174/// diagnostic line, a graph column, or a rejection body under
1175/// `format!("{v}")` therefore landed under a different byte-string than
1176/// the wire format the operator's per-child-policy dispatch keyed off —
1177/// a silent split whose apply-time symptom (a `format!("{v}")`-carrying
1178/// diagnostic quoting `"permanent"` while the wire scalar the operator
1179/// probed was `"Permanent"`) surfaced as a confused correlate at
1180/// operator-log time far from the two-declaration site.
1181///
1182/// Routing `Display` through [`RestartPolicy::as_str`] closes the third
1183/// path: every `format!("{v}")` call reaches the same lifted
1184/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the wire format
1185/// and the [`RestartPolicy::as_str`] helper route through — `Debug` (the
1186/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
1187/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
1188/// byte-string per variant. A future variant rename or
1189/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
1190/// exactly one place, structurally.
1191///
1192/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
1193/// (from `#[derive(gen_platform::Discriminant)]`) still returns
1194/// `"permanent"` / `"temporary"` / `"transient"`, and the fleet-wide
1195/// [`gen_platform::register_dispatcher!("caixa.restart-policy", …)`]
1196/// registration keys the catalog off the same kebab identity. The two
1197/// naming worlds now live on separate typed methods (`Display` /
1198/// `as_str` for the wire byte-string, `discriminant` for the catalog
1199/// identity) rather than sharing one `Display` route that structurally
1200/// disagrees with the wire format.
1201///
1202/// Pin tests
1203/// [`tests::restart_policy_display_routes_through_as_str_helper`]
1204/// and
1205/// [`tests::restart_policy_display_matches_serialized_wire_byte_string`]
1206/// assert the three paths agree byte-for-byte on every variant, so a
1207/// future variant rename or per-arm serde attribute drift is a build
1208/// error visible at caixa-core test time, not a silent per-consumer
1209/// dispatch miss at apply / reconcile time.
1210///
1211/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
1212/// (aplicacao.rs:2306) on the per-Aplicacao distribution-strategy axis
1213/// and the sibling [`RestartStrategy`] `Display` impl on the
1214/// per-supervisor sibling-restart-strategy axis — same three-path-
1215/// convergence discipline, extended to close the third and final of
1216/// three OTP-shaped closed-enum discriminator axes on the caixa typed
1217/// surface.
1218impl std::fmt::Display for RestartPolicy {
1219 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1220 f.write_str(self.as_str())
1221 }
1222}
1223
1224/// Substrate-canonical [`AsRef<str>`] projection on the M2
1225/// per-child-restart-policy [`RestartPolicy`] closed-set typed enum —
1226/// routes through the same [`RestartPolicy::as_str`] `pub const fn`
1227/// scalar accessor the paired [`std::fmt::Display`] impl and the
1228/// un-`rename`d [`serde::Serialize`] derive already key off, so any
1229/// future consumer that binds a [`RestartPolicy`] through the
1230/// standard-library `impl AsRef<str>` bound (a future
1231/// [`caixa-feira`] `feira supervisor --restart <arm>` verb that
1232/// composes the emitted `PascalCase` wire scalar into a
1233/// [`std::process::Command::arg`] shell-out of the future
1234/// wasm-operator's per-child admission gate, a per-child structured-
1235/// log recorder on the future `caixa-operator`'s hierarchical
1236/// reconciliation surface that accepts `impl AsRef<str>` at the
1237/// `tracing::field::Value` `Str`-arm, a [`std::collections::HashMap`]
1238/// lookup keyed on the restart-policy wire byte through
1239/// `map.get::<str>(policy.as_ref())` on a future per-policy
1240/// dispatch table) reaches the paired
1241/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1242/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1243/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
1244/// lifted-const through one substrate-primitive dispatch rather
1245/// than an open-coded `.as_str()` projection at every wire-up.
1246///
1247/// Peer of the sibling [`std::fmt::Display`] impl on the same
1248/// primitive — both delegate to the shared [`RestartPolicy::as_str`]
1249/// `pub const fn` accessor, so [`format!("{v}")`], `v.as_str()`, and
1250/// `<RestartPolicy as AsRef<str>>::as_ref(&v)` resolve to the same
1251/// byte-string per instance by construction. A future variant rename
1252/// or `#[serde(rename_all = "kebab-case")]` attribute-drift on the
1253/// enum reaches every one of the three paths (plus the wire-format
1254/// `Serialize` derive that already routes through the same lifted
1255/// const) through exactly one caixa-core edit.
1256///
1257/// Same "route the trait impl through the substrate-primitive
1258/// accessor" discipline the sibling [`crate::CaixaVersion`]
1259/// [`AsRef<str>`] impl (16d5c7e) and the paired M2
1260/// [`RestartStrategy`] [`AsRef<str>`] impl (63eb1a4) carry — extends
1261/// the axis onto the paired per-child-restart-decision-policy
1262/// sibling on the same M2 `:supervisor` slot (the second M2
1263/// OTP-shape closed-set typed enum to converge onto the standard-
1264/// library [`AsRef<str>`] projection). Rust-side newtype/typed-enum
1265/// convention pairs [`AsRef<str>`] and [`fmt::Display`] on the same
1266/// primitive so a caller who has one has both; before this lift,
1267/// [`RestartPolicy`] carried [`fmt::Display`] but not the paired
1268/// [`AsRef<str>`] impl the convention names.
1269///
1270/// Pinned load-bearing by
1271/// [`tests::restart_policy_as_ref_str_routes_through_as_str_accessor`]
1272/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1273/// three-arm closed set) and
1274/// [`tests::restart_policy_as_ref_str_routes_through_display_via_shared_accessor`]
1275/// (three-path convergence: `AsRef<str>` + `Display` + `as_str` all
1276/// resolve to the same lifted `SUPERVISOR_CHILD_RESTART_*` const per
1277/// arm) — any future silent detour that routes the impl through a
1278/// divergent projection (a per-arm inline `match self { … }`
1279/// re-inlining that opens a compile-time link to the un-lifted
1280/// arm-literal, a swap onto the kebab-case
1281/// [`gen_platform::Discriminant`] catalog identity that would
1282/// collide the wire axis with the dispatcher-catalog axis) trips at
1283/// caixa-core test time under `assert_eq!` rather than at a
1284/// downstream `impl AsRef<str>`-bound consumer's silent split.
1285impl AsRef<str> for RestartPolicy {
1286 fn as_ref(&self) -> &str {
1287 self.as_str()
1288 }
1289}
1290
1291/// Trait-idiomatic reverse projection on the M2-OTP-shape per-child
1292/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
1293/// byte-for-byte through the paired substrate-primitive
1294/// [`RestartPolicy::from_wire`] `Option<Self>` accessor so every future
1295/// consumer that binds a `PascalCase` `:children :restart` wire
1296/// byte-string through the standard-library `.try_into()` / [`TryFrom`]
1297/// axis (a future [`caixa-feira`] `feira supervisor --restart
1298/// <Permanent|Temporary|Transient>` CLI arg-parse that composes into
1299/// `let restart: RestartPolicy = s.try_into()?`, a future
1300/// `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook that folds a
1301/// `spec.children[*].restart: String` field through
1302/// `RestartPolicy::try_from(&s)?`, a generic
1303/// `<T: TryFrom<&str>>`-bound loader over any of the substrate's closed-
1304/// set typed enums) reaches the same three-arm accept-set the sibling
1305/// [`RestartPolicy::from_wire`] resolver parses through and the sibling
1306/// [`RestartPolicy::as_str`] emits, rather than an open-coded per-arm
1307/// `match s { "Permanent" => …, "Temporary" => …, "Transient" => …, _ =>
1308/// … }` cascade whose arm-set has no compile-time link back to the
1309/// substrate primitive.
1310///
1311/// Complements the pre-existing forward-projection triple
1312/// ([`std::fmt::Display`], [`AsRef<str>`], [`RestartPolicy::as_str`])
1313/// with the paired trait-idiomatic reverse-projection axis: Rust-side
1314/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
1315/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so a
1316/// caller who can project *out to* a `&str` can also project *in from*
1317/// one. The [`TryFrom<&str>`] axis is deliberately chosen over
1318/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
1319/// lint the sibling method-named [`RestartPolicy::from_wire`] would
1320/// trigger under a `FromStr` impl and to avoid colliding with the
1321/// [`std::str::FromStr`] impl the [`gen_platform::FromStrKind`] derive
1322/// already installs on the paired *kebab-case dispatcher-catalog* axis
1323/// (which parses `"permanent"` / `"temporary"` / `"transient"`, the
1324/// inverse of [`Self::discriminant`]) — this impl closes the trait-
1325/// idiomatic reverse axis on the *`PascalCase` wire* half without
1326/// disturbing either the method-named `from_wire` shape every sibling
1327/// closed-set typed enum on the substrate already carries or the
1328/// pre-existing `FromStr` on the dispatcher-catalog half, keeping the
1329/// two-axis split the sibling [`Self::from_wire`] doc block motivates.
1330///
1331/// `type Error = ()` matches the sibling [`RestartPolicy::from_wire`]'s
1332/// `Option<Self>` return-shape's deliberate deferral of error typing: the
1333/// caller picks the diagnostic form appropriate for its use site (a
1334/// future `feira supervisor --restart` arg-parse composes its own
1335/// per-verb "unknown restart: <arg> — accepted: {…}" message enumerating
1336/// [`RestartPolicy::ALL`], a future M4 admission-webhook rejection body
1337/// wraps the `Err(())` outcome with the accepted-set enumeration for
1338/// operator diagnostics, a `Result::map_err` at the call site lifts the
1339/// unit-error to a per-verb error type). Same shape the peer
1340/// [`RestartStrategy`] (5b828ed) on the sibling per-supervisor axis,
1341/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136), and
1342/// [`crate::aplicacao::PlacementStrategy`] (6fd00cd) blocks motivate on
1343/// their peer closed-set typed enums' reverse projections.
1344///
1345/// The paired [`TryFrom<&str>`] impl reaches the same three-arm accept-
1346/// set the [`RestartPolicy::from_wire`] resolver dispatches through, so
1347/// any future arm addition (an OTP-`intrinsic` fourth arm the theory
1348/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1349/// might reach for once the three canonical OTP restart policies stop
1350/// covering the substrate's discovered load-shape) grows the trait-
1351/// idiomatic axis by construction — one caixa-core edit on
1352/// [`RestartPolicy::from_wire`] extends both the method-named reverse
1353/// projection every existing consumer keys off and the trait-idiomatic
1354/// reverse projection this impl exposes, without a coordinated rewrite
1355/// across every future `TryFrom<&str>`-bound consumer's arm-set.
1356///
1357/// Extends the substrate-wide closed-set-enum reverse-projection family
1358/// ([`crate::CaixaKind`] via 3c83606, [`crate::CaixaDialeto`] via
1359/// bf33136, [`crate::aplicacao::PlacementStrategy`] via 6fd00cd, and
1360/// [`RestartStrategy`] via 5b828ed) onto the third and final OTP-shape
1361/// closed-enum discriminator axis on the caixa surface — the paired
1362/// per-child `:children :restart` closed set the future wasm-operator's
1363/// hierarchical reconciliation scheduler's per-child post-exit
1364/// restart-decision branch keys off end-to-end.
1365///
1366/// Pinned load-bearing by
1367/// [`tests::restart_policy_try_from_str_routes_through_from_wire_accessor`]
1368/// (byte-parity pin against [`RestartPolicy::from_wire`] across the
1369/// three-arm accept-set),
1370/// [`tests::restart_policy_try_from_str_rejects_unknown_byte_strings`]
1371/// (rejection witness against silent accept-set widening), and
1372/// [`tests::restart_policy_try_from_str_and_from_wire_partition_the_accept_set`]
1373/// (cross-axis partition pin locking the trait and method-named
1374/// projections onto one accept-set).
1375impl TryFrom<&str> for RestartPolicy {
1376 type Error = ();
1377
1378 fn try_from(s: &str) -> Result<Self, Self::Error> {
1379 Self::from_wire(s).ok_or(())
1380 }
1381}
1382
1383/// Trait-idiomatic forward projection on the M2-OTP-shape per-child
1384/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
1385/// byte-for-byte through the paired substrate-primitive
1386/// [`RestartPolicy::as_str`] `pub const fn` accessor. Return type is
1387/// `&'static str` by construction — every [`RestartPolicy::as_str`] arm
1388/// resolves to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const
1389/// &str` with `'static` lifetime, so the trait's return-type promise is
1390/// upheld structurally without a [`String::leak`] cast or a per-arm inline
1391/// literal.
1392///
1393/// Every future consumer that specifically needs `&'static str` lifetime
1394/// bytes on the per-child restart-decision axis (a
1395/// [`tracing::field::valuable::Value::Str`] recording where the `Str`
1396/// arm's typing demands `&'static str`, a
1397/// [`std::borrow::Cow::Borrowed`]`::<'static, str>(policy.into())` composer
1398/// on the future M4 admission-webhook rejection body where the
1399/// `Cow<'static, str>` typing rules out the sibling [`AsRef<str>`]
1400/// borrowed return, a generic `<T: Into<&'static str>>`-bound serializer
1401/// or error formatter that requires the `'static` bound) reaches the same
1402/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1403/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1404/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] substrate-
1405/// primitive dispatch rather than an open-coded per-arm literal cascade
1406/// whose arm-set has no compile-time link back to the substrate primitive.
1407///
1408/// Peer of the sibling M2-OTP-shape [`RestartStrategy`] forward-projection
1409/// impl (523157d) on the per-supervisor sibling-restart-strategy axis —
1410/// the second (and second-of-two-in-M2) closed-set typed enum on the
1411/// caixa surface to converge onto the paired trait-idiomatic forward-
1412/// projection axis. With this lift the paired per-child
1413/// `:children :restart` closed-set typed enum carries the full sibling
1414/// quintet ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
1415/// [`TryFrom<&str>`] via 6fdd0d9, `From<Self> for &'static str` via this
1416/// lift) plus the round-trip witness through both the trait-idiomatic
1417/// (`From<Self> for &'static str` + `TryFrom<&str>`) and the method-named
1418/// (`as_str` + `from_wire`) axis pairs — mirrors the sibling
1419/// [`RestartStrategy`] surface arm-for-arm, so every future arm addition
1420/// (an OTP-`intrinsic` fourth arm the theory
1421/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1422/// might reach for once the three canonical OTP restart policies stop
1423/// covering the substrate's discovered load-shape) grows the trait-
1424/// idiomatic forward axis by construction: one caixa-core edit on
1425/// [`RestartPolicy::as_str`] extends every one of the five sibling
1426/// forward-projection paths ([`std::fmt::Display`], [`AsRef<str>`],
1427/// [`Self::as_str`] itself, this `From<Self> for &'static str`, and the
1428/// un-`rename`d [`serde::Serialize`] derive that also emits `as_str`'s
1429/// bytes) without a coordinated rewrite across every future
1430/// `Into<&'static str>`-bound consumer's arm-set.
1431///
1432/// Pinned load-bearing by
1433/// [`tests::restart_policy_from_into_static_str_routes_through_as_str_accessor`]
1434/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1435/// three-arm emit-set, plus a `const`-context materialization witness for
1436/// the `&'static str` lifetime promise) and
1437/// [`tests::restart_policy_from_into_static_str_and_as_str_partition_the_emit_set`]
1438/// (partition pin asserting `<&'static str as From<RestartPolicy>>::from`
1439/// and [`RestartPolicy::as_str`] agree on every arm, plus a two-way
1440/// round-trip witness through the paired trait-idiomatic reverse-
1441/// projection axis [`TryFrom<&str>`] (6fdd0d9): every
1442/// `policy.into::<&'static str>()` output re-parses back through
1443/// [`RestartPolicy::try_from`] to the original variant, closing the two-
1444/// way `Self ↔ &'static str` round-trip on the trait-idiomatic axis pair).
1445impl From<RestartPolicy> for &'static str {
1446 fn from(policy: RestartPolicy) -> &'static str {
1447 policy.as_str()
1448 }
1449}
1450
1451/// Trait-idiomatic *forward* projection on [`RestartPolicy`] from a
1452/// *borrowed* input onto the `&'static str` axis — the borrowed-input
1453/// companion to the paired owned-input [`From<RestartPolicy> for
1454/// &'static str`] impl immediately above. Routes byte-for-byte through
1455/// the same substrate-primitive [`RestartPolicy::as_str`] `pub const
1456/// fn` accessor so every consumer that binds a `&RestartPolicy`
1457/// through the standard-library `.into()` / [`From<&Self> for &'static
1458/// str`] axis (a `RestartPolicy::ALL.iter().map(<&'static
1459/// str>::from).collect::<Vec<_>>()` per-arm accept-set materializer —
1460/// whose iterator over `&'static [RestartPolicy]` yields
1461/// `&RestartPolicy`, not `RestartPolicy`, so the owned-input
1462/// [`From<RestartPolicy>`] axis alone forces every call site through
1463/// an explicit `.copied()` / dereference / [`Copy`]-bound restatement
1464/// rather than the direct trait-idiomatic projection; a future generic
1465/// `<T: Copy + for<'a> Into<&'static str>>`-bound diagnostic column
1466/// that walks the `iter().map(Into::into)` shape verbatim across every
1467/// substrate-wide closed-set typed enum; the future wasm-operator's
1468/// per-child post-exit restart-decision diagnostic line that composes
1469/// the accepted-set enumeration from an iterated
1470/// `RestartPolicy::ALL.iter().map(|p| p.into())` pipe rather than a
1471/// per-arm `match p { … }` cascade; a future
1472/// `HashMap::<&'static str, RestartPolicy>::from_iter(
1473/// RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
1474/// per-policy reverse-lookup table the sibling [`TryFrom<&str>`] impl
1475/// cannot compose without this borrowed-input axis in place) reaches
1476/// the same three-arm lifted
1477/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1478/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1479/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1480/// paired owned-input [`From<RestartPolicy> for &'static str`], the
1481/// sibling [`std::fmt::Display`], [`AsRef<str>`], and
1482/// [`RestartPolicy::as_str`] surfaces already return.
1483///
1484/// Fifth peer on the substrate-wide trait-idiomatic *borrowed-input*
1485/// forward-projection family opened on [`crate::dep::DepList`]
1486/// (64aa742) and extended onto [`crate::CaixaKind`] (5ab993a),
1487/// [`crate::CaixaDialeto`] (807b0b5), and the paired
1488/// per-supervisor sibling-restart-strategy [`RestartStrategy`]
1489/// (e941836). Rust's `From` trait does not auto-derive the
1490/// `From<&Self>` sibling from a `From<Self>` impl (the blanket
1491/// `impl<T, U> From<&T> for U where T: Copy, U: From<T>` does not
1492/// exist in `core`), so every closed-set typed enum that carries the
1493/// owned-input axis but not the borrowed-input axis forces every
1494/// borrowed-input call site through a `.copied()` /
1495/// `<&'static str>::from(*policy)` / `policy.as_str()` detour whose
1496/// type bounds have no compile-time link to the substrate primitive.
1497/// [`RestartPolicy`] is the second (and second-of-two-in-M2)
1498/// OTP-shape peer to converge onto this campaign — sibling of the
1499/// paired per-supervisor [`RestartStrategy`] borrowed-input axis, so
1500/// with this lift both closed-set typed enums on the M2 `:supervisor`
1501/// slot now carry the full sibling quintet ([`std::fmt::Display`],
1502/// [`AsRef<str>`], [`Self::as_str`], `From<Self> for &'static str`,
1503/// `From<&Self> for &'static str`) plus the paired trait-idiomatic
1504/// reverse projection [`TryFrom<&str>`], closing the borrowed-input
1505/// forward-projection axis on the M2 OTP-shape slot as a unit.
1506///
1507/// Same three-path convergence discipline as the paired owned-input
1508/// impl (this borrowed-input axis, the paired owned-input
1509/// [`From<RestartPolicy> for &'static str`], and
1510/// [`RestartPolicy::as_str`] all route through the same lifted
1511/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const), so a future
1512/// variant rename or per-arm serde-attribute drift reaches every one
1513/// of the six sibling forward-projection paths
1514/// ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
1515/// [`From<Self> for &'static str`], this [`From<&Self> for &'static
1516/// str`], and the un-`rename`d [`serde::Serialize`] derive that also
1517/// emits [`Self::as_str`]'s bytes) through exactly one caixa-core
1518/// edit.
1519///
1520/// The [`RestartPolicy::as_str`] emit and [`RestartPolicy::from_wire`]
1521/// parse share the same `PascalCase` vocabulary by construction, so
1522/// the borrowed-input forward axis and the reverse axis compose
1523/// directly — the round-trip witness pin below locks this direct
1524/// composition without the intermediate wire-vocab hop the peer
1525/// [`crate::CaixaKind`] axis pair requires.
1526///
1527/// Pinned load-bearing by
1528/// [`tests::restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
1529/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1530/// three-arm emit-set via a borrowed input, plus a `const`-context
1531/// materialization witness for the `&'static str` lifetime promise,
1532/// plus a blanket `.into()` shape) and
1533/// [`tests::restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
1534/// (cross-axis partition pin against the paired owned-input
1535/// [`From<RestartPolicy> for &'static str`] impl, plus a
1536/// `.iter().map(Into::into)` pipe witness over
1537/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
1538/// [`TryFrom<&str>`] that closes the two-way `&Self → &'static str →
1539/// Self` round-trip without the wire-vocab intermediate the peer
1540/// [`crate::CaixaKind`] axis pair requires).
1541impl From<&RestartPolicy> for &'static str {
1542 fn from(policy: &RestartPolicy) -> &'static str {
1543 policy.as_str()
1544 }
1545}
1546
1547/// Trait-idiomatic *owned-`String`* forward projection on the second
1548/// M2 OTP-shape closed-set typed enum ([`RestartPolicy`]) — the
1549/// owned-heap-string companion to the paired `&'static str`-returning
1550/// [`From<RestartPolicy> for &'static str`] / [`From<&RestartPolicy>
1551/// for &'static str`] impls immediately above. Routes byte-for-byte
1552/// through the substrate-primitive [`RestartPolicy::as_str`] `pub
1553/// const fn` accessor (via [`str::to_owned`]) so every consumer that
1554/// binds a [`RestartPolicy`] through the standard-library `.into()` /
1555/// [`From<Self> for String`] (equivalently [`Into<String>`]) axis — a
1556/// future `serde_json::Value::String(policy.into())` structured-payload
1557/// composer where the `Value::String` arm typing demands an owned
1558/// [`String`] and the sibling [`&'static str`]-returning axis forces
1559/// an explicit `.to_owned()` / `String::from` restatement at every
1560/// call site, a future `HashMap::<String, RestartPolicy>::from_iter(
1561/// RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))` per-policy
1562/// lookup where the map's key type is owned [`String`] rather than
1563/// [`&'static str`], a future `Cow::<'static, str>::Owned(policy.into())`
1564/// composer on the future M4 admission-webhook rejection body's
1565/// owned-arm, the future wasm-operator's per-child post-exit
1566/// diagnostic emit `serde_json::json!({ "restart": policy })` where the
1567/// JSON serializer's `Serialize` impl on [`String`] owns the emit-path
1568/// — reaches the same three-arm lifted
1569/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1570/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1571/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1572/// paired [`std::fmt::Display`], [`AsRef<str>`],
1573/// [`RestartPolicy::as_str`], and the two `&'static str`-returning
1574/// forward-projection impls already return.
1575///
1576/// Extends the trait-idiomatic *owned-`String`* forward-projection
1577/// axis onto the second-of-two M2 OTP-shape closed-set typed enums on
1578/// the caixa surface — mirror of the first-mover
1579/// [`From<RestartStrategy> for String`] (7baa18a) that opened this
1580/// axis on the sibling supervisor-level strategy enum. Rust's standard
1581/// library does not carry a blanket `impl<T: AsRef<str>> From<T> for
1582/// String` (nor an `impl<T: fmt::Display> From<T> for String`), so
1583/// every closed-set typed enum that carries the paired `AsRef<str>` /
1584/// `Display` / `From<Self> for &'static str` triple but not the
1585/// owned-[`String`] axis forces every owned-string call site through a
1586/// `.to_string()` / `.as_str().to_owned()` / `String::from(policy.as_str())`
1587/// detour whose type bounds have no compile-time link to the
1588/// substrate primitive.
1589///
1590/// Deliberately routes through the human-readable
1591/// [`RestartPolicy::as_str`] axis — for this enum the wire format
1592/// (`PascalCase`, tatara-lisp author surface `:restart Permanent`) and
1593/// the diagnostic byte-string share the same vocabulary by
1594/// construction (unlike the sibling [`crate::CaixaKind`] enum whose
1595/// two axes diverge), so the owned-[`String`] projection lands
1596/// byte-identically on both the wire vocabulary the paired
1597/// [`serde::Serialize`] derive emits and the diagnostic vocabulary the
1598/// [`RestartPolicy::as_str`] helper returns, and — because the paired
1599/// [`TryFrom<&str>`] / [`RestartPolicy::from_wire`] reverse-projection
1600/// axis parses the same `PascalCase` vocabulary — the direct two-way
1601/// `Self → String → Self` round-trip composes without the wire-vocab
1602/// intermediate hop the peer [`crate::CaixaKind`] owned-[`String`]
1603/// axis pair requires.
1604///
1605/// Pinned load-bearing by
1606/// [`tests::restart_policy_from_into_owned_string_routes_through_as_str_accessor`]
1607/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1608/// three-arm emit-set, plus a blanket `.into::<String>()` shape
1609/// witness) and
1610/// [`tests::restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm`]
1611/// (cross-axis partition pin against the paired owned-input
1612/// [`From<RestartPolicy> for &'static str`] impl and the sibling
1613/// [`ToString::to_string`] surface routed through [`std::fmt::Display`],
1614/// plus a `.iter().copied().map(String::from)` pipe witness over
1615/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
1616/// [`TryFrom<&str>`] on the owned-[`String`]'s [`String::as_str`]
1617/// borrow that closes the two-way `Self → String → Self` round-trip
1618/// on the trait-idiomatic owned-[`String`] forward + reverse axis
1619/// pair).
1620impl From<RestartPolicy> for String {
1621 fn from(policy: RestartPolicy) -> String {
1622 policy.as_str().to_owned()
1623 }
1624}
1625
1626/// Trait-idiomatic *borrowed-input, owned-`String` output* forward
1627/// projection on the second-of-two M2 OTP-shape closed-set typed enum
1628/// ([`RestartPolicy`]) — the fourth (and closing) corner of the
1629/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
1630/// projection family on this enum, mirror of the first-mover
1631/// [`From<&RestartStrategy> for String`] (579385f) that opened the
1632/// 2×2-completion corner on the sibling supervisor-level strategy
1633/// enum. Routes byte-for-byte through the substrate-primitive
1634/// [`RestartPolicy::as_str`] `pub const fn` accessor (via
1635/// [`str::to_owned`]) so every consumer that holds a borrowed
1636/// [`&RestartPolicy`] and needs an owned [`String`] — a future
1637/// `serde_json::Value::String(String::from(&policy))` structured-payload
1638/// composer over a borrowed field, a future `Iterator::map` over
1639/// `&[RestartPolicy]` that projects to owned keys through
1640/// `.iter().map(String::from)`, a future `HashMap::<String,
1641/// RestartPolicy>::from_iter` that keys off a borrowed-iteration axis
1642/// where dereferencing the policy would force an unnecessary `Copy` at
1643/// every step, the future wasm-operator's per-supervisor
1644/// `child_policies.iter().map(String::from).collect()` per-child post-
1645/// exit restart-decision diagnostic emit whose iteration axis is
1646/// borrowed by construction — reaches the same three-arm lifted
1647/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1648/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1649/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1650/// paired [`std::fmt::Display`], [`AsRef<str>`],
1651/// [`RestartPolicy::as_str`], and the three other trait-idiomatic
1652/// forward-projection impls
1653/// ([`From<RestartPolicy> for &'static str`],
1654/// [`From<&RestartPolicy> for &'static str`],
1655/// [`From<RestartPolicy> for String`]) already return.
1656///
1657/// Second peer on the substrate-wide trait-idiomatic *borrowed-input,
1658/// owned-`String` output* forward-projection family opened on
1659/// [`crate::supervisor::RestartStrategy`] (579385f) — closes the
1660/// `{Self, &Self} × {&'static str, String}` 2×2 projection corner on
1661/// both M2 OTP-shape sibling peers (the paired supervisor-level
1662/// sibling-restart-strategy axis and the per-child restart-decision-
1663/// policy axis), so the whole M2 OTP-shape axis pair now carries the
1664/// full four-corner family by construction. Rust's standard library
1665/// does not carry a blanket `impl<T: AsRef<str>> From<&T> for String`
1666/// (nor an `impl<T: fmt::Display> From<&T> for String`), so every
1667/// closed-set typed enum that carries the paired `AsRef<str>` /
1668/// `Display` / `From<Self> for &'static str` / `From<&Self> for
1669/// &'static str` / `From<Self> for String` quintuple but not the
1670/// borrowed-input owned-[`String`] axis forces every borrowed-input
1671/// owned-string call site through a `policy.as_str().to_owned()` /
1672/// `String::from(*policy)` (with a spurious `Copy`) /
1673/// `policy.to_string()` (through `Display`) detour whose type bounds
1674/// have no compile-time link to the substrate primitive.
1675///
1676/// Deliberately routes through the human-readable
1677/// [`RestartPolicy::as_str`] axis — for this enum the wire format
1678/// (`PascalCase`, tatara-lisp author surface `:restart Permanent`) and
1679/// the diagnostic byte-string share the same vocabulary by
1680/// construction (unlike the sibling [`crate::CaixaKind`] enum whose
1681/// two axes diverge), so the borrowed-input owned-[`String`]
1682/// projection lands byte-identically on both the wire vocabulary the
1683/// paired [`serde::Serialize`] derive emits and the diagnostic
1684/// vocabulary the [`RestartPolicy::as_str`] helper returns, and —
1685/// because the paired [`TryFrom<&str>`] / [`RestartPolicy::from_wire`]
1686/// reverse-projection axis parses the same `PascalCase` vocabulary —
1687/// the direct two-way `&Self → String → Self` round-trip composes
1688/// without the wire-vocab intermediate hop the peer
1689/// [`crate::CaixaKind`] axis pair requires.
1690///
1691/// The remaining thirteen closed-set typed enums on the caixa
1692/// substrate surface (`CaixaKind`, `CaixaDialeto`, `DepList`,
1693/// `PlacementStrategy`, `WitShape`, `RateLimitUnit`,
1694/// `PathShapeViolation`, `InvariantKind`, `ArchVerdict`, `Severity`,
1695/// `FixSafety`, `Semantic`, `FerriteRuntime`) are the future targets
1696/// of this 2×2-completion campaign — each carries the same paired
1697/// quintuple that this borrowed-input owned-[`String`] axis extends
1698/// onto.
1699///
1700/// Pinned load-bearing by
1701/// [`tests::restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
1702/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1703/// three-arm emit-set through the borrowed-input surface) and
1704/// [`tests::restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
1705/// (cross-axis partition pin against the paired owned-input owned-
1706/// [`String`] [`From<RestartPolicy> for String`] impl, the paired
1707/// borrowed-input owned-[`&'static str`] [`From<&RestartPolicy> for
1708/// &'static str`] impl, and the sibling [`ToString::to_string`]
1709/// surface routed through [`std::fmt::Display`], plus a direct round-
1710/// trip witness through [`TryFrom<&str>`] on the owned-[`String`]'s
1711/// [`String::as_str`] borrow that closes the two-way
1712/// `&Self → String → Self` round-trip on the trait-idiomatic
1713/// borrowed-input owned-[`String`] forward + reverse axis pair).
1714impl From<&RestartPolicy> for String {
1715 fn from(policy: &RestartPolicy) -> String {
1716 policy.as_str().to_owned()
1717 }
1718}
1719
1720// Fleet-wide dispatcher-catalog registrations for caixa's OTP
1721// supervisor surface — two more typed shadows over Erlang/OTP
1722// primitives the substrate now mechanically tracks (see
1723// theory/UNIFIED-COMPUTING-MODEL.md §VI for the roadmap +
1724// theory/TYPED-ABSORPTION.md for the absorption arc).
1725gen_platform::register_dispatcher!("caixa.restart-strategy", RestartStrategy);
1726gen_platform::register_dispatcher!("caixa.restart-policy", RestartPolicy);
1727
1728/// One child entry in the supervisor's `:children` list.
1729///
1730/// Every child references another caixa by `:caixa <nome>` + version
1731/// constraint. The supervisor materializes one ComputeUnit per entry.
1732#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1733#[serde(rename_all = "camelCase")]
1734pub struct ChildSpec {
1735 /// The child caixa's `:nome`. Must resolve via the same dependency
1736 /// resolution path as `:deps` (caixa-resolver).
1737 pub caixa: String,
1738
1739 /// Semver constraint (`"^0.1"`, `"~0.1.2"`, etc.) — same shape as
1740 /// [`crate::dep::Dep::versao`].
1741 pub versao: String,
1742
1743 /// Restart policy — an author-omitted slot degrades onto the
1744 /// substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`]
1745 /// (`permanent`, the Erlang/OTP worker-child default) through the
1746 /// [`Default for RestartPolicy`] impl this `#[serde(default)]` routes
1747 /// to.
1748 #[serde(default)]
1749 pub restart: RestartPolicy,
1750}
1751
1752impl ChildSpec {
1753 /// Substrate-canonical per-`:children` child-caixa `:nome` scalar
1754 /// accessor every consumer that reads the OTP-shape supervised
1755 /// child's identity keys off — returns the author-declared
1756 /// `:children :caixa` byte-string verbatim as a `&str`, borrowed
1757 /// from the typed slot's own [`String`] storage.
1758 ///
1759 /// The `:children :caixa` slot carries the DNS-1123 label — the
1760 /// child caixa's `:nome` — that every emitted cluster artifact
1761 /// derives its `metadata.name` from verbatim: the rendered
1762 /// `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name` per child, the
1763 /// [`crate::LABEL_PROGRAM`] label value on every child's pod
1764 /// identity, and the per-child K8s Service `metadata.name` the
1765 /// future wasm-operator (M3) provisions for inter-child supervision-
1766 /// tree wiring. Every downstream consumer that fans on the child's
1767 /// caixa-name keys off this scalar (the [`SupervisorSpec::validate`]
1768 /// per-child DNS-1123 gate at
1769 /// `require_valid_dns_1123_label(child.nome(), …)`, the per-child
1770 /// duplicate-detection [`crate::render::insert_first_seen`] key, the
1771 /// [`validate_no_self_supervision`] cross-slot equality check
1772 /// against the parent's `:nome`, every `SupervisorError` variant
1773 /// carrying the offending child caixa verbatim for `feira lint`
1774 /// rendering, the future wasm-operator's hierarchical reconciliation
1775 /// scheduler's per-child ComputeUnit-name projection, the future M4
1776 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1777 /// admission webhook).
1778 ///
1779 /// Prior to this lift the `.caixa` byte-string was accessed inline
1780 /// at seven sites in `supervisor.rs` — the DNS-1123 gate's
1781 /// `&child.caixa`, the four `SupervisorError::{ChildCaixaInvalid,
1782 /// EmptyChildVersion, ChildVersaoInvalid, DuplicateChildCaixa}`
1783 /// carriers' `child.caixa.clone()`, the dedup key's
1784 /// `child.caixa.as_str()`, and the [`validate_no_self_supervision`]
1785 /// `child.caixa == parent_nome` cross-slot check — seven open-coded
1786 /// field-accesses that expressed no compile-time link back to the
1787 /// typed slot. A future extension of the `:children :caixa` axis to
1788 /// a richer author surface (a per-cluster alias table the operator
1789 /// pins through a future `:placement`-scoped slot on the supervisor
1790 /// tree, a namespace-qualified rewrite the M4 CR materializer
1791 /// applies per-CR, a per-child overlay from the future `:children
1792 /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
1793 /// acknowledges) would have had to be threaded through every
1794 /// open-coded copy in lockstep or one consumer would silently
1795 /// disagree with the peers on which caixa a given child resolves to
1796 /// — a child-set lookup that treated the name as `"cart-worker"`
1797 /// while the peer duplicate-detector treated it as
1798 /// `"tenant-a/cart-worker"` would silently split the
1799 /// `DuplicateChildCaixa` membership-lookup diagnostic from the
1800 /// self-supervision detector's parent-equality check, a two-consumer
1801 /// split at the validator far from the source `caixa.lisp` with no
1802 /// field naming the identity-drift root cause. Lifting the resolution
1803 /// rule to a typed method on the substrate primitive means every
1804 /// downstream consumer of the Supervisor's per-`:children` identity
1805 /// surface reaches for exactly one typed dispatch — the resolver's
1806 /// accept-set migrates as a unit on any future axis addition.
1807 ///
1808 /// Sibling of the peer per-`:membros` [`crate::Membro::nome`]
1809 /// (4a32abf) member-caixa `:nome` scalar accessor on the M3
1810 /// mesh-slot surface — same "one typed dispatch on the substrate
1811 /// primitive, thin projections at each consumer" discipline extended
1812 /// onto the M2 supervisor-tree per-`:children` child-identity axis.
1813 /// The two typed axes (`Membro::nome` on the M3 Aplicacao side,
1814 /// `ChildSpec::nome` on the M2 Supervisor side) now share one
1815 /// accessor discipline for the shared substrate concept "another
1816 /// caixa referenced by `:nome`". Peer of the second M2 slot scalar
1817 /// accessor [`crate::UpgradeFromEntry::prior_versao`] (75d27a8) on
1818 /// the sibling per-`:upgrade-from :from` OTP-appup axis — the M2
1819 /// slot family's typed-accessor discipline now spans both the
1820 /// upgrade axis (`:upgrade-from`) and the supervision axis
1821 /// (`:children`), matching the closed M3 mesh-slot accessor family's
1822 /// shape. Named `nome()` to match the tatara-lisp author-surface
1823 /// term the field's docstring already reaches for ("The child
1824 /// caixa's `:nome`") and the peer [`crate::Membro::nome`] /
1825 /// [`crate::Caixa::nome`] / [`crate::dep::Dep::nome`] field-name
1826 /// discipline the substrate already carries — the accessor's name
1827 /// maps directly onto the canonical caixa-identity vocabulary rather
1828 /// than shadowing the field's storage-side `caixa` label.
1829 #[must_use]
1830 pub const fn nome(&self) -> &str {
1831 self.caixa.as_str()
1832 }
1833
1834 /// Substrate-canonical per-`:children` child-caixa `:versao` semver-
1835 /// requirement scalar accessor every consumer that reads the OTP-shape
1836 /// supervised child's version pin keys off — returns the author-declared
1837 /// `:children :versao` byte-string verbatim as a `&str`, borrowed from
1838 /// the typed slot's own [`String`] storage.
1839 ///
1840 /// The `:children :versao` slot carries the Cargo-shaped semver
1841 /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that pins
1842 /// which release of the supervised child caixa the OTP-shape supervisor
1843 /// tree materializes against — the same requirement grammar the peer
1844 /// `:deps :versao` / `:membros :versao` axes carry, resolved through the
1845 /// shared [`crate::render::require_valid_versao_requirement`] cascade
1846 /// and the shared [`crate::version::parse_requirement`] parser. Every
1847 /// downstream consumer that fans on the child's version pin keys off
1848 /// this scalar (the [`SupervisorSpec::validate`] per-child requirement
1849 /// gate at `require_valid_versao_requirement(child.versao_requirement(),
1850 /// …)`, the [`SupervisorError::ChildVersaoInvalid`] variant's carrier
1851 /// for `feira lint` rendering, every future per-cluster version-lock
1852 /// overlay the caixa-operator's hierarchical reconciliation scheduler
1853 /// pins through a future `:placement`-scoped supervisor-tree slot, the
1854 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1855 /// per-child version resolver, the future wasm-operator's per-child
1856 /// lacre BLAKE3-closure lookup at `ComputeUnit` materialization time).
1857 ///
1858 /// Prior to this lift the `.versao` byte-string was accessed inline at
1859 /// two `&str`-shaped sites in `caixa-core/src/supervisor.rs` — the
1860 /// [`SupervisorSpec::validate`] requirement-gate call
1861 /// `require_valid_versao_requirement(&child.versao, …)` and the
1862 /// [`SupervisorError::ChildVersaoInvalid`] carrier at
1863 /// `versao: child.versao.clone()` — two open-coded field-accesses that
1864 /// expressed no compile-time link back to the typed slot. A future
1865 /// extension of the `:children :versao` axis to a richer author surface
1866 /// (a per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
1867 /// flow, a lacre-projected concrete-version rewrite the operator
1868 /// materializes at CR-admission time, a future `:children :versao-lock`
1869 /// per-cluster override slot the wasm-operator's hierarchical
1870 /// reconciliation scheduler authors per-CR) would have had to be
1871 /// threaded through both open-coded copies in lockstep or one consumer
1872 /// would silently disagree with the peer on which release constraint a
1873 /// given child resolves to — the requirement-gate call reading
1874 /// `"^0.1"` while the error-body carrier read `"tenant-a-pin/^0.1"`
1875 /// would silently split the `ChildVersaoInvalid` diagnostic quote from
1876 /// the actual gate rejection input, a two-consumer split at the
1877 /// validator far from the source `caixa.lisp` with no field naming the
1878 /// version-pin drift root cause. Lifting the resolution rule to a typed
1879 /// method on the substrate primitive means every downstream
1880 /// requirement-facing consumer of the Supervisor's per-`:children`
1881 /// version-pin surface reaches for exactly one typed dispatch — the
1882 /// resolver's accept-set migrates as a unit on any future axis addition.
1883 ///
1884 /// Sibling of the peer per-`:membros` [`crate::Membro::versao_requirement`]
1885 /// (a40b0e3) member-caixa `:versao` scalar accessor on the M3 mesh-slot
1886 /// surface — same "one typed dispatch on the substrate primitive, thin
1887 /// projections at each consumer" discipline extended onto the M2
1888 /// supervisor-tree per-`:children` child-version-pin axis. The two typed
1889 /// axes (`Membro::versao_requirement` on the M3 Aplicacao side,
1890 /// `ChildSpec::versao_requirement` on the M2 Supervisor side) now share
1891 /// one accessor discipline for the shared substrate concept "another
1892 /// caixa referenced by a Cargo-shaped semver requirement". Peer of the
1893 /// sibling per-`:children` [`ChildSpec::nome`] (57c61d0) child-caixa
1894 /// `:nome` scalar accessor — the pair
1895 /// `(nome(), versao_requirement())` jointly projects the
1896 /// `(caixa, versao)` field pair every OTP-shape supervisor-tree consumer
1897 /// that fans on per-child identity + version pin keys off, closing the
1898 /// last unlifted per-`:children` `String`-carry axis so every downstream
1899 /// per-`:children` reader now routes through a typed dispatch on the
1900 /// substrate primitive. Named `versao_requirement()` rather than
1901 /// `versao()` because the field's storage-side `.versao` label is
1902 /// already the author-surface term (`:versao`); the accessor's name
1903 /// carries the semantic role — the semver *requirement* string the
1904 /// shared [`crate::version::parse_requirement`] entry-point consumes —
1905 /// so a raw field access and a typed dispatch read differently at every
1906 /// consumer site. Matches the peer [`crate::Membro::versao_requirement`]
1907 /// naming discipline verbatim.
1908 #[must_use]
1909 pub const fn versao_requirement(&self) -> &str {
1910 self.versao.as_str()
1911 }
1912
1913 /// Substrate-canonical per-`:children` `:restart` OTP-shaped
1914 /// per-child post-exit restart-decision policy scalar accessor every
1915 /// consumer that dispatches on the supervised child's post-exit
1916 /// reconcile posture keys off — returns the author-declared
1917 /// `:children :restart` variant verbatim as a [`RestartPolicy`],
1918 /// `Copy`-projected from the typed slot's own [`RestartPolicy`]
1919 /// storage.
1920 ///
1921 /// The `:children :restart` slot carries the closed-set OTP-shaped
1922 /// per-child restart-decision policy discriminator
1923 /// ([`RestartPolicy::Permanent`] — always restart, the OTP `permanent`
1924 /// worker-child default; [`RestartPolicy::Transient`] — restart only
1925 /// on abnormal exit, the OTP `transient` clean-completion-aware
1926 /// default; [`RestartPolicy::Temporary`] — never restart, the OTP
1927 /// `temporary` one-shot default) that every downstream consumer of
1928 /// the Supervisor's per-child post-exit reconcile branch keys off.
1929 /// Every future downstream consumer that fans on the per-child
1930 /// restart-decision keys off this scalar (the future `feira app
1931 /// graph` per-child restart column, the future wasm-operator's
1932 /// per-child post-exit restart-decision branch, the future M4
1933 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1934 /// admission webhook, the `caixa-operator`'s hierarchical
1935 /// reconciliation scheduler's per-child post-exit reconcile branch,
1936 /// the [`RestartPolicy::as_str`] `Serialize`-derive-pinning path the
1937 /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
1938 /// pin threads through).
1939 ///
1940 /// Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
1941 /// (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
1942 /// scalar accessor and the M3 mesh-slot
1943 /// [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
1944 /// [`crate::PlacementStrategy`] distribution-strategy scalar accessor
1945 /// — same "one typed dispatch on the substrate primitive,
1946 /// `Copy`-projected closed-set enum-arm discriminator that partitions
1947 /// the downstream renderer's per-arm fan-out" discipline extended
1948 /// onto the M2 supervisor-slot per-`:children` restart-decision-policy
1949 /// `Copy`-composite-enum scalar axis. Third axis on the per-`:children`
1950 /// [`ChildSpec`] type — companion to the sibling per-`:children`
1951 /// [`ChildSpec::nome`] (57c61d0) child-caixa `:nome` scalar accessor
1952 /// and the per-`:children` [`ChildSpec::versao_requirement`]
1953 /// (2c053c8) child-caixa `:versao` semver-requirement scalar accessor
1954 /// on the sibling `String`-carry axes. The triple
1955 /// `(nome(), versao_requirement(), restart())` jointly projects the
1956 /// `(caixa, versao, restart)` field trio every OTP-shape supervisor-
1957 /// tree consumer that fans on per-child identity + version pin +
1958 /// restart-decision keys off, closing the last unlifted per-`:children`
1959 /// axis so every downstream per-`:children` reader now routes through
1960 /// a typed dispatch on the substrate primitive. Named `restart()` to
1961 /// match the storage field's name and the author-surface
1962 /// `:children :restart` slot term verbatim; the accessor's identity
1963 /// name maps onto the canonical OTP-shape per-child restart-decision-
1964 /// policy vocabulary the [`RestartPolicy`] enum's docstring already
1965 /// carries.
1966 ///
1967 /// Declared `pub const fn` to close the last non-`const`
1968 /// `Copy`-return raw-field-getter posture on the M2
1969 /// per-`:children` [`ChildSpec`] substrate-primitive surface — peer
1970 /// of the sibling M2 per-`:supervisor`
1971 /// [`SupervisorSpec::estrategia`] (converted in this commit)
1972 /// `Copy`-composite-enum accessor, the sibling M2 per-`:supervisor`
1973 /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
1974 /// already lifted, and the peer M3 mesh-slot per-`:entrada`
1975 /// [`crate::Entrada::port`] (bafa004) / per-`:placement`
1976 /// [`crate::Placement::estrategia`] (bafa004) `Copy`-return
1977 /// `pub const fn` scalar accessors on the sibling M3 surface. Every
1978 /// downstream substrate-side `const`-context consumer of the
1979 /// per-`:children` restart-decision-policy scalar (a future
1980 /// module-scope `const _:() = assert!(matches!(child.restart(),
1981 /// RestartPolicy::Permanent))` invariant pin on a typed fixture, a
1982 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
1983 /// admission-webhook `const fn` per-child restart-decision floor
1984 /// over a typed [`ChildSpec`], any future `const fn` supervisor-tree
1985 /// composer over the substrate primitive that fans on the per-child
1986 /// restart-decision policy at compile time) now reaches through the
1987 /// same typed dispatch on the substrate primitive at const-eval
1988 /// time as at runtime. A future non-`Copy`-return promotion of the
1989 /// scalar (an `Option<RestartPolicy>`-shape migration on the
1990 /// per-child restart-decision axis once heterogeneous per-cluster
1991 /// restart-policy overlays land, a per-tenant restart-policy-alias
1992 /// table the M4 CR materializer resolves per-CR) that would drop
1993 /// the `const` qualifier fails the fail-before-pass-after pin
1994 /// [`tests::child_spec_restart_accessor_is_const_fn`] at caixa-core
1995 /// build time rather than surfacing as a downstream consumer
1996 /// regression.
1997 #[must_use]
1998 pub const fn restart(&self) -> RestartPolicy {
1999 self.restart
2000 }
2001}
2002
2003/// Supervisor-typed slots that live alongside the standard Caixa
2004/// fields when `:kind Supervisor`. Held flat in [`crate::Caixa`] so
2005/// the manifest stays a single typed form; this struct exists for
2006/// validation + conversion.
2007#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2008#[serde(rename_all = "camelCase")]
2009pub struct SupervisorSpec {
2010 /// Restart strategy. Defaults to [`RestartStrategy::OneForOne`].
2011 #[serde(default)]
2012 pub estrategia: RestartStrategy,
2013
2014 /// Max restarts within [`Self::restart_window`] before the
2015 /// supervisor itself terminates (and its parent supervisor decides
2016 /// what to do). Default 5.
2017 #[serde(default = "default_max_restarts")]
2018 pub max_restarts: u32,
2019
2020 /// Sliding window for `max_restarts`. Authored as a duration
2021 /// string (`"60s"`, `"5m"`); absent = "never reset". A `Some(0s)`
2022 /// is rejected by [`Self::validate`] — Erlang/OTP's
2023 /// `MaxIntensity / Period` invariant requires a positive window
2024 /// (a zero-period supervisor either trips on the first failure or
2025 /// never trips, depending on operator interpretation, neither of
2026 /// which is the author's intent). Omit the slot to express "no
2027 /// reset"; carry a positive duration to express the sliding window.
2028 #[serde(
2029 default,
2030 skip_serializing_if = "Option::is_none",
2031 with = "duration_codec"
2032 )]
2033 pub restart_window: Option<Duration>,
2034
2035 /// Static children. Empty for `SimpleOneForOne` (children added
2036 /// dynamically); required for the other three strategies.
2037 #[serde(default)]
2038 pub children: Vec<ChildSpec>,
2039}
2040
2041const fn default_max_restarts() -> u32 {
2042 // Route the private serde-`#[serde(default = "…")]` helper through
2043 // the substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] typed
2044 // `pub const` rather than the raw `5` literal — one source of truth
2045 // for the Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
2046 // default across the two production consumers that currently
2047 // dispatch on it (this helper via `#[serde(default = "…")]` on
2048 // `SupervisorSpec::max_restarts` and the [`Default for SupervisorSpec`]
2049 // impl at line 962). Pinned by
2050 // `default_max_restarts_helper_routes_through_lifted_default` +
2051 // `supervisor_spec_default_max_restarts_routes_through_lifted_default`
2052 // in the tests module; peer of the sibling caixa-core
2053 // [`crate::manifest::Caixa::supervisor_view`] `unwrap_or(…)` fold
2054 // that now routes its author-omitted `:max-restarts` arm through
2055 // the same lifted constant.
2056 SUPERVISOR_MAX_RESTARTS_DEFAULT
2057}
2058
2059/// Substrate-canonical Erlang/OTP-shaped `MaxIntensity` restart-budget-
2060/// count default for the `:supervisor :max-restarts` axis — the
2061/// canonical `{intensity, 5, 60}` `MaxIntensity` half of Learn You Some
2062/// Erlang's worker-supervisor default, extracted as a typed `pub const`
2063/// so every substrate-side consumer that resolves "what
2064/// [`SupervisorSpec::max_restarts`] value does an author-omitted
2065/// `:max-restarts` slot degrade onto?" reaches for exactly one
2066/// substrate-primitive `u32`.
2067///
2068/// The `:max-restarts` default axis has two production consumers on the
2069/// substrate side today (both prior to this lift folded onto raw `5`
2070/// literals with no compile-time link back to a shared truth): the
2071/// serde-`#[serde(default = "default_max_restarts")]` helper on
2072/// [`SupervisorSpec::max_restarts`] that every author-omitted
2073/// `:supervisor :max-restarts` slot lands in past the derive-macro's
2074/// wire-format compose, and the [`crate::manifest::Caixa::supervisor_view`]
2075/// `.max_restarts().unwrap_or(5)` fold that every downstream consumer of
2076/// the composed [`SupervisorSpec`] altitude reaches through
2077/// (`feira app graph`, the future wasm-operator's per-supervisor
2078/// restart-intensity counter, the future M4
2079/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2080/// webhook, the caixa-operator's hierarchical reconciliation scheduler).
2081/// A pair of open-coded `5`s across two files that expressed no
2082/// compile-time link back to the shared OTP-canonical default — a
2083/// future rebrand of the default (a tightening to Elixir's
2084/// `Supervisor.max_restarts: 3`, a widening to a per-cluster overlay
2085/// the operator pins through a future
2086/// `:supervisor :max-restarts-overrides` slot the MESH-COMPOSITION
2087/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
2088/// plain `u32` count to a richer `{MaxR, MaxT}` per-child-cohort
2089/// restart-budget-partition once the INSPIRATIONS §II.2 Erlang/OTP
2090/// per-child-cohort roadmap lands) would have had to be threaded
2091/// through both open-coded copies in lockstep or the wire-format
2092/// author-omitted arm and the view-construction author-omitted arm
2093/// would silently disagree on which restart-budget an omitted
2094/// `:max-restarts` resolves to (an author writing `:supervisor
2095/// (:max-restarts ())` would round-trip through serde with the new
2096/// default while `supervisor_view` silently continued to compose the
2097/// stale `5`, or vice versa), a two-consumer split at the composition
2098/// boundary far from the source `caixa.lisp` with no field naming the
2099/// default-drift root cause. Lifting the resolution rule to a typed
2100/// `pub const` on the substrate primitive means every downstream
2101/// consumer of the per-Supervisor default-restart-budget-count surface
2102/// reaches for exactly one substrate-primitive `u32` — the resolver's
2103/// accepted value migrates as a unit on any future axis change.
2104///
2105/// The `5` value pins Learn You Some Erlang's `{intensity, 5, 60}`
2106/// worker-supervisor default (the closest canonical OTP-shape
2107/// production reference the substrate carries, matching the sibling
2108/// `60s` `Period` default the [`Default for SupervisorSpec`] impl pairs
2109/// this constant with on the paired sliding-window axis). Two orders of
2110/// magnitude below the [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` ceiling
2111/// (the upper bracket on the same axis, sibling of this lower default;
2112/// both are typed `u32` const bounds on the `:supervisor :max-restarts`
2113/// axis and now share one accessor discipline on the substrate) and
2114/// above the OTP-`supervisor` callback-module `MaxR = 1` minimum-
2115/// restart floor — the "one restart, then escalate" default is
2116/// deliberately loose enough to absorb a short burst of transient
2117/// child failures without escalating past the supervisor's parent
2118/// while remaining tight enough to trip the `MaxIntensity / Period`
2119/// ratio's escalation on a genuinely-stuck child within the sibling
2120/// `60s` sliding window.
2121///
2122/// Lifted as a typed `pub const` so the bound has exactly one source
2123/// of truth — the serde-side wire-format author-omitted arm at
2124/// [`default_max_restarts`], the [`Default for SupervisorSpec`] impl's
2125/// struct-literal default field, and the caixa-core
2126/// [`crate::manifest::Caixa::supervisor_view`] fold's author-omitted
2127/// arm all read from one place. Same shape every other typed default
2128/// in this crate carries (the sibling
2129/// [`SUPERVISOR_MAX_RESTARTS_MAX`] upper cap on the same axis, the
2130/// paired [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the
2131/// sibling `:restart-window` axis, and the peer
2132/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
2133/// per-renderer defaults on the caixa-flux / caixa-helm rendering
2134/// axes).
2135pub const SUPERVISOR_MAX_RESTARTS_DEFAULT: u32 = 5;
2136
2137/// Upper-bound ceiling on the `:supervisor :max-restarts` axis — every
2138/// validated [`SupervisorSpec::max_restarts`] past
2139/// [`SupervisorSpec::validate`] lies in `1..=SUPERVISOR_MAX_RESTARTS_MAX`.
2140///
2141/// The typed field is `u32` (the zero-floor arm
2142/// [`SupervisorError::ZeroMaxRestarts`] already brackets the bottom edge),
2143/// so a programmatic struct literal
2144/// (`SupervisorSpec { max_restarts: u32::MAX, .. }`) and the equivalent
2145/// author-surface form (`:max-restarts 4294967295` or any
2146/// `:max-restarts 100000`-shape typo landing in the slot) both round-trip
2147/// cleanly through serde — a structurally unbounded `u32` ceiling. The
2148/// runtime substrate consuming the value (Erlang/OTP's
2149/// `MaxIntensity / Period` ratio, the future wasm-operator's
2150/// per-supervisor restart-intensity counter, the M4
2151/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook)
2152/// then turned a typed `:max-restarts` policy into a no-op supervisor: the
2153/// escalation threshold is structurally so high that no realistic
2154/// restarts-per-`:restart-window` traffic shape can reach it, the
2155/// supervisor never escalates to its parent, and a bad child can loop
2156/// inside the window indefinitely with the parent supervisor structurally
2157/// never receiving the "this subtree has exceeded its restart budget"
2158/// signal the typed slot is meant to express — the canonical
2159/// "supervisor intensity declared, no escalation" footgun, exactly the
2160/// peer of the [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap
2161/// on the `:politicas :circuit-breaker :max-failures` axis (both are
2162/// "trip the next-higher protection layer after N events in a rolling
2163/// window" counters with identical degenerate-at-the-high-end shape).
2164///
2165/// The `1000` ceiling matches the sibling
2166/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] (the closest
2167/// peer — same "events-per-window trip threshold" semantics, same `u32`
2168/// type, same no-op-at-the-high-end failure mode) so the M4
2169/// `mesh.pleme.io/v1alpha1/Supervisor` / `.../Aplicacao` CR materializers
2170/// and the future wasm-operator's per-supervisor restart-intensity
2171/// counter reach for either field knowing the value is in `1..=1000`
2172/// without re-validating at the reconciler layer. The cap sits two
2173/// orders of magnitude above every documented Erlang/OTP production
2174/// playbook recommendation (Learn You Some Erlang's
2175/// `{intensity, 5, 60}` worker-supervisor default, Elixir's `Supervisor`
2176/// `max_restarts: 3` default, OTP's `supervisor` callback module
2177/// `MaxR = 1` / `MaxT = 5` "minimal-restart" default, Riak Core's
2178/// typical `MaxR ∈ 5..=100`, RabbitMQ's broker-supervisor `MaxR = 5`
2179/// default) and below the clearly-pathological "effectively no
2180/// escalation" floor (`10_000`, `100_000`, `u32::MAX`): a value the
2181/// author can plausibly want at hyperscale (a long-running supervisor
2182/// over a very-flaky pool tolerating thousands of transient restarts
2183/// before escalating), but a hard wall above which the typed policy is
2184/// structurally a no-op carried verbatim on every emitted child-restart
2185/// reconciliation contract.
2186///
2187/// Lifted as a typed `pub const` so the bound has exactly one source of
2188/// truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
2189/// materializer's admission webhook and the wasm-operator-side
2190/// per-supervisor restart-intensity reconciler read from one place. Same
2191/// shape every other typed upper bound in this crate carries
2192/// ([`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
2193/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
2194/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
2195/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2196/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2197/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2198pub const SUPERVISOR_MAX_RESTARTS_MAX: u32 = 1000;
2199
2200/// Upper-bound ceiling on the `:supervisor :restart-window` axis —
2201/// every validated `Some(`[`SupervisorSpec::restart_window`]`)` past
2202/// [`SupervisorSpec::validate`] lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
2203/// (inclusive on both ends, integer-millisecond magnitudes by the
2204/// canonical-form gate immediately preceding).
2205///
2206/// The typed field is `Option<Duration>` (the zero-floor arm
2207/// [`SupervisorError::RestartWindowZero`] already rejects
2208/// `Some(Duration::ZERO)`, and the canonical-form arm
2209/// [`SupervisorError::RestartWindowNotCanonical`] already rejects
2210/// sub-millisecond residue), so a programmatic struct literal
2211/// (`SupervisorSpec { restart_window: Some(Duration::from_secs(86_400)),
2212/// .. }` — 24h) and the equivalent author-surface form
2213/// (`(:supervisor (:restart-window "24h"))` — the shared duration codec
2214/// emits `"<n>h"` for any integer-hour magnitude) both round-trip
2215/// cleanly through serde — a structurally unbounded `Duration` ceiling.
2216/// A `:restart-window` value far above the documented Erlang/OTP
2217/// `MaxIntensity / Period` production-playbook band (Learn You Some
2218/// Erlang's `{intensity, 5, 60}` worker-supervisor `Period = 60s`
2219/// default, Elixir's `Supervisor` `max_seconds: 5` default, OTP's
2220/// `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's
2221/// `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default)
2222/// degenerates the supervisor's restart-intensity counter into a
2223/// lifetime counter: the rolling failure-counting window is structurally
2224/// so long that transient restarts are never forgotten, so the
2225/// `MaxIntensity / Period` ratio degenerates from "trip the parent
2226/// supervisor when the child has exceeded its restart budget *within
2227/// the recent window*" to "trip the parent when the child has exceeded
2228/// its restart budget *over its lifetime*" — every transient restart
2229/// counts against the budget forever, the supervisor's reset semantic
2230/// never reaches the child, and the typed `:restart-window` slot
2231/// becomes a no-op rolling window carried on every emitted hierarchical
2232/// reconciliation contract. The canonical
2233/// rolling-window-degenerates-to-lifetime-counter footgun the sibling
2234/// [`crate::POLICY_BREAKER_WINDOW_MAX`] cap closes on the peer
2235/// `:politicas :circuit-breaker :window` axis with identical shape (both
2236/// are "rolling failure-counting window with a per-`Period` reset" Duration
2237/// axes whose lifetime-counter degenerate at the high end is the same
2238/// "the reset semantic never fires" CSE invariant violation).
2239///
2240/// The `1h` (3600s = `3_600_000` ms) ceiling matches the largest unit
2241/// the shared duration codec emits (`"<n>h"` for any integer-hour
2242/// magnitude) — every value in the canonical authoring form's
2243/// `<integer><unit>` grammar at or below this cap renders to a clean
2244/// canonical string — and matches the three sibling typed-`Duration`
2245/// caps already lifted to this surface
2246/// ([`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
2247/// [`crate::POLICY_BREAKER_WINDOW_MAX`]). All four typed-`Duration`
2248/// axes — per-process `:limits :wall-clock`, per-edge `:politicas
2249/// :timeout`, per-breaker `:politicas :circuit-breaker :window`, and
2250/// per-supervisor `:supervisor :restart-window` — now share a single
2251/// uniform top edge at the codec's largest emitted unit so the next
2252/// typed-slot wiring (the future wasm-operator's per-supervisor
2253/// `MaxIntensity / Period` reconciler, the M4
2254/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2255/// webhook, the `caixa-operator`'s hierarchical reconciliation
2256/// scheduler) reaches for any of the four knowing the value is in
2257/// `1ms..=1h` without re-validating at the renderer layer. The cap sits
2258/// two orders of magnitude above every documented Erlang/OTP / Elixir /
2259/// Riak Core / RabbitMQ production-playbook recommendation band
2260/// (`5s..=300s`) and below the clearly-pathological "rolling window
2261/// degenerates to lifetime counter" floor (`24h`, `7d`, `Duration::MAX`):
2262/// a value the author can plausibly want for a very-low-traffic
2263/// long-tail failure-restart window over a hyperscale-flaky child pool,
2264/// but a hard wall above which the rolling-window contract is
2265/// structurally a lifetime-counter contract.
2266///
2267/// Lifted as a typed `pub const` so the bound has exactly one source
2268/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
2269/// materializer's admission webhook, the wasm-operator-side
2270/// per-supervisor `MaxIntensity / Period` reconciler, and the
2271/// `caixa-operator`'s hierarchical reconciliation scheduler all read
2272/// from one place. Same shape every other typed upper bound in this
2273/// crate carries ([`SUPERVISOR_MAX_RESTARTS_MAX`],
2274/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
2275/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
2276/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
2277/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2278/// [`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
2279/// [`crate::POLICY_BREAKER_WINDOW_MAX`],
2280/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2281/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2282pub const SUPERVISOR_RESTART_WINDOW_MAX: Duration = Duration::from_secs(3600);
2283
2284/// Substrate-canonical Erlang/OTP-shaped `Period` sliding-window-duration
2285/// default for the `:supervisor :restart-window` axis — the canonical
2286/// `{intensity, 5, 60}` `Period` half of Learn You Some Erlang's
2287/// worker-supervisor default, extracted as a typed `pub const` so every
2288/// substrate-side consumer that resolves "what
2289/// [`SupervisorSpec::restart_window`] value does an author-omitted
2290/// `:restart-window` slot degrade onto?" reaches for exactly one
2291/// substrate-primitive [`Duration`].
2292///
2293/// The `:restart-window` default axis has one production consumer on the
2294/// substrate side today: the [`Default for SupervisorSpec`] impl's
2295/// struct-literal `restart_window` field, which prior to this lift folded
2296/// onto a raw `Duration::from_secs(60)` literal with no compile-time link
2297/// back to the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity`
2298/// half of the same `{intensity, 5, 60}` OTP-canonical default. The
2299/// [`crate::manifest::Caixa::supervisor_view`] fold deliberately does
2300/// *not* fall back to this default on the sibling `:restart-window` axis
2301/// — an author-omitted `:supervisor :restart-window` composes to
2302/// `restart_window: None` (the shared codec's soft-swallow shape),
2303/// keeping author-declared intent ("no reset — never escalate on rolling
2304/// window") distinct from the [`Default for SupervisorSpec`] "canonical
2305/// 60s Period" arm every programmatic `SupervisorSpec::default()` caller
2306/// resolves to. Prior to this lift the paired `{intensity, 5, 60}` OTP
2307/// default was split across two files with no compile-time link between
2308/// the halves: [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] pinned the
2309/// `MaxIntensity` half at the substrate primitive while the `Period`
2310/// half rode as an open-coded literal at the composition site, so a
2311/// future coherent rebrand of the paired canonical (a tightening to
2312/// Elixir's `{max_restarts: 3, max_seconds: 5}`, a widening to a
2313/// per-cluster overlay the operator pins through a future
2314/// `:supervisor :restart-window-overrides` slot the MESH-COMPOSITION
2315/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
2316/// paired constants to a per-child-cohort `{MaxR, MaxT}` restart-budget-
2317/// partition once the INSPIRATIONS §II.2 Erlang/OTP per-child-cohort
2318/// roadmap lands) would have had to migrate the `MaxIntensity` half
2319/// through the lifted constant and the `Period` half through a raw
2320/// literal in lockstep or the two halves of the same OTP-canonical
2321/// default would silently drift out of pairing. Lifting the resolution
2322/// rule to a typed `pub const` on the substrate primitive means the
2323/// paired OTP-canonical default migrates as one unit on any future
2324/// axis change.
2325///
2326/// The `60s` value pins Learn You Some Erlang's `{intensity, 5, 60}`
2327/// worker-supervisor default (the closest canonical OTP-shape
2328/// production reference the substrate carries, matching the paired
2329/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5` `MaxIntensity` half this
2330/// constant is the `Period` denominator of on the same
2331/// `MaxIntensity / Period` restart-intensity ratio). Two orders of
2332/// magnitude below the [`SUPERVISOR_RESTART_WINDOW_MAX`] `3600s`
2333/// (`1h`) ceiling (the upper bracket on the same axis, sibling of
2334/// this lower default; both are typed [`Duration`] const bounds on the
2335/// `:supervisor :restart-window` axis and now share one accessor
2336/// discipline on the substrate) and above the OTP-`supervisor`
2337/// callback-module `MaxT = 5` seconds "minimal-window" floor — the "60s
2338/// rolling window" default is deliberately loose enough to absorb a
2339/// short burst of transient child failures without escalating past the
2340/// supervisor's parent while remaining tight enough for the paired
2341/// `MaxIntensity / Period` ratio's escalation to trip on a genuinely-
2342/// stuck child within a human-scale observation window.
2343///
2344/// Lifted as a typed `pub const` so the paired OTP-canonical default has
2345/// exactly one source of truth on each half — the sibling
2346/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half and this
2347/// `Period` `60s` half now share the same substrate-primitive lift
2348/// discipline. Same shape every other typed default in this crate
2349/// carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] paired
2350/// `MaxIntensity` half on the same OTP-canonical `{intensity, 5, 60}`,
2351/// the sibling [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the same
2352/// axis, and the peer [`crate::render::DEFAULT_NAMESPACE`] /
2353/// [`crate::render::DEFAULT_LIBRARY_NAME`] per-renderer defaults on the
2354/// caixa-flux / caixa-helm rendering axes).
2355pub const SUPERVISOR_RESTART_WINDOW_DEFAULT: Duration = Duration::from_secs(60);
2356
2357/// Substrate-canonical Erlang/OTP-shaped sibling-restart-strategy default
2358/// for the `:supervisor :estrategia` axis — the canonical `one_for_one`
2359/// half of Learn You Some Erlang's `{one_for_one, intensity, 5, 60}`
2360/// worker-supervisor default, extracted as a typed `pub const` so every
2361/// substrate-side consumer that resolves "what
2362/// [`SupervisorSpec::estrategia`] variant does an author-omitted
2363/// `:estrategia` slot degrade onto?" reaches for exactly one substrate-
2364/// primitive [`RestartStrategy`].
2365///
2366/// The `:estrategia` default axis has three production consumers on the
2367/// substrate side today: the [`Default for RestartStrategy`] impl's
2368/// return arm, the [`Default for SupervisorSpec`] impl's struct-literal
2369/// `estrategia` field, and the
2370/// [`crate::manifest::Caixa::supervisor_view`] fold's
2371/// `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)` `Option<RestartStrategy>`
2372/// collapse arm — three entry points onto the same OTP-canonical
2373/// `one_for_one` value that prior to this lift folded onto a raw
2374/// `Self::OneForOne` arm at the [`Default for RestartStrategy`] impl and
2375/// implicit `RestartStrategy::default()` routes at the sibling consumers,
2376/// with no compile-time link back to the paired
2377/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` half + the paired
2378/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` half of the same
2379/// `{one_for_one, intensity, 5, 60}` OTP-canonical default. The paired
2380/// triple was split across three altitudes with no compile-time link
2381/// between the halves: the `MaxIntensity` half rode through the lifted
2382/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant (b698ec0) and the `Period`
2383/// half rode through the lifted [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2384/// constant (f7dcd0e) while the `one_for_one` half rode as an open-coded
2385/// discriminator at the [`Default for RestartStrategy`] impl, so a future
2386/// coherent rebrand of the triple (Elixir's `{:one_for_one,
2387/// max_restarts: 3, max_seconds: 5}` — same strategy, different
2388/// intensity/period; an OTP `rest_for_one` widening once the substrate
2389/// discovers startup-order-coupled child cohorts as the more common
2390/// worker-supervisor default; a per-cluster overlay the operator pins
2391/// through a future `:estrategia-overrides` slot the MESH-COMPOSITION
2392/// §III.2 supervision-canary roadmap acknowledges) would have had to
2393/// migrate the `MaxIntensity` + `Period` halves through the lifted
2394/// constants and the `one_for_one` half through an open-coded arm in
2395/// lockstep or the three halves of the same OTP-canonical default would
2396/// silently drift out of pairing. Lifting the resolution rule to a typed
2397/// `pub const` on the substrate primitive means the paired OTP-canonical
2398/// worker-supervisor default migrates as one unit on any future axis
2399/// change.
2400///
2401/// The [`RestartStrategy::OneForOne`] value pins Learn You Some Erlang's
2402/// `{one_for_one, intensity, 5, 60}` worker-supervisor default (the
2403/// closest canonical OTP-shape production reference the substrate
2404/// carries, matching the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5`
2405/// `MaxIntensity` half and the paired [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2406/// `60s` `Period` half). The `one_for_one` strategy — restart only the
2407/// failed child, leaving siblings untouched — is the default for tree-of-
2408/// independent-workers use cases the substrate's [`RestartStrategy`]
2409/// discriminator's own docstring already carries as the default arm; it
2410/// composes with the `{5, 60}` restart-intensity ratio to name the same
2411/// substrate-canonical "canonical worker-supervisor" shape the paired
2412/// halves close on their respective axes.
2413///
2414/// Lifted as a typed `pub const` so the paired OTP-canonical default has
2415/// exactly one source of truth on each of its three halves — the sibling
2416/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half, the
2417/// sibling [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` `60s` half, and
2418/// this `one_for_one` strategy half now share the same substrate-
2419/// primitive lift discipline. Same shape every other typed default in
2420/// this crate carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] +
2421/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] paired halves on the same OTP-
2422/// canonical `{one_for_one, intensity, 5, 60}`, the sibling
2423/// [`SUPERVISOR_MAX_RESTARTS_MAX`] + [`SUPERVISOR_RESTART_WINDOW_MAX`]
2424/// upper caps on the paired sibling axes, and the peer
2425/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
2426/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes).
2427pub const SUPERVISOR_ESTRATEGIA_DEFAULT: RestartStrategy = RestartStrategy::OneForOne;
2428
2429/// Substrate-canonical Erlang/OTP-shaped per-child restart-decision-policy
2430/// default for the `:children :restart` axis — the OTP `permanent`
2431/// worker-child default (`{ChildId, StartFunc, permanent, …}` in a
2432/// `supervisor`'s `init/1` child-spec tuple), extracted as a typed
2433/// `pub const` so every substrate-side consumer that resolves "what
2434/// [`ChildSpec::restart`] variant does an author-omitted `:children
2435/// :restart` slot degrade onto?" reaches for exactly one substrate-
2436/// primitive [`RestartPolicy`].
2437///
2438/// Completes the OTP-shape supervisor-tree default set at the substrate
2439/// primitive. The per-`:supervisor` axis already carries all three of its
2440/// halves as lifted typed constants — [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
2441/// (`one_for_one`, 95ffacc), [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
2442/// (`MaxIntensity` `5`, b698ec0), [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2443/// (`Period` `60s`, f7dcd0e) — while the per-`:children` axis's own
2444/// OTP-canonical default rode as an open-coded `Self::Permanent` arm in
2445/// the [`Default for RestartPolicy`] impl, the last un-lifted default on
2446/// the M2 `:supervisor` slot family. The split mattered because the two
2447/// axes resolve *together* on every author-omitted supervisor: a
2448/// `(defcaixa :kind Supervisor :children ((:caixa "worker" :versao
2449/// "^0.1")))` with no `:estrategia` and no per-child `:restart` degrades
2450/// onto `{one_for_one, 5, 60}` through three lifted constants and onto
2451/// `permanent` through an open-coded enum arm, so a future coherent
2452/// rebrand of the OTP-shape default set (an Elixir-shaped
2453/// `{:one_for_one, max_restarts: 3, max_seconds: 5}` tightening, a
2454/// per-cluster overlay the operator pins through the MESH-COMPOSITION
2455/// §III.2 supervision-canary roadmap slots, an OTP-`transient` widening
2456/// once the substrate discovers clean-completion-aware children as the
2457/// more common child shape) would have had to migrate three halves
2458/// through typed constants and the fourth through a raw enum arm in
2459/// lockstep or the supervisor-level and child-level defaults would
2460/// silently drift apart.
2461///
2462/// The `:children :restart` default axis has two production consumers on
2463/// the substrate side today: the [`Default for RestartPolicy`] impl's
2464/// return arm, and the serde-side `#[serde(default)]` on
2465/// [`ChildSpec::restart`] that resolves an author-omitted `:children
2466/// :restart` slot through that same impl. Both now key off this one
2467/// substrate primitive, so the future wasm-operator's per-child post-exit
2468/// restart-decision branch, the future M4
2469/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2470/// admission webhook, and the `caixa-operator`'s hierarchical
2471/// reconciliation scheduler's per-child fan-out all reach for one typed
2472/// identifier when they resolve an omitted per-child restart posture.
2473///
2474/// The [`RestartPolicy::Permanent`] value pins Erlang/OTP's `permanent`
2475/// worker-child restart type — always restart the child regardless of how
2476/// it died, the canonical posture for long-running services that must
2477/// always be up, matching the sibling [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
2478/// `one_for_one` tree-of-independent-workers strategy this constant pairs
2479/// with under the same `{one_for_one, intensity, 5, 60}` worker-supervisor
2480/// shape. The two alternatives the closed [`RestartPolicy::ALL`] accept-set
2481/// carries ([`RestartPolicy::Transient`] — restart only on abnormal exit;
2482/// [`RestartPolicy::Temporary`] — never restart) express deliberate
2483/// one-shot / clean-completion-aware postures an author declares
2484/// explicitly, never a posture an omitted slot should silently assume.
2485pub const SUPERVISOR_CHILD_RESTART_DEFAULT: RestartPolicy = RestartPolicy::Permanent;
2486
2487/// Route the manually-authored [`Default`] impl on [`SupervisorSpec`]
2488/// through the substrate-canonical [`SupervisorSpec::otp_canonical`]
2489/// `pub const fn` constructor rather than a struct-literal cascade over
2490/// the paired [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
2491/// [`default_max_restarts`] / [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2492/// lifted consts — one source of truth for the Erlang/OTP-canonical
2493/// `{one_for_one, 5, 60}` worker-supervisor baseline across the two
2494/// paths every downstream consumer already reaches through (the
2495/// hand-authored-until-now [`Default::default`] the
2496/// `..SupervisorSpec::default()` struct-update-syntax on every
2497/// one-axis-under-test fixture in this crate's test module rests on,
2498/// and the `pub const fn` [`SupervisorSpec::otp_canonical`] constructor
2499/// every `const`-context consumer reaches through).
2500///
2501/// Extends the [`Default`]-through-const-ctor fold discipline the
2502/// [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
2503/// (abd52c2), [`crate::aplicacao::MeshPolicy`]
2504/// [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`] (91641a4),
2505/// and [`crate::BehaviorSpec`]
2506/// [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c) folds
2507/// closed on the M2 / M3 `Option`-only "canonical unset baseline"
2508/// typed-slot spec family — extended here onto the M2 supervisor-slot
2509/// [`SupervisorSpec`] whose canonical baseline is not "everything
2510/// `None`" but the OTP-canonical `{one_for_one, 5, 60}` worker-
2511/// supervisor triple. The `empty()` peer's naming did not fit
2512/// (`SupervisorSpec` carries a discriminator-shaped `estrategia` field
2513/// and a non-zero `max_restarts`/`restart_window` pair whose canonical
2514/// shape is Erlang/OTP-descended, not the "no axis declared" bottom
2515/// the sibling `Option`-only slots fold to), so this peer is named
2516/// [`SupervisorSpec::otp_canonical`] instead — the same phrasing the
2517/// existing per-arm pin tests
2518/// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`] /
2519/// [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`] /
2520/// [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
2521/// already reach for. Pinned load-bearing by
2522/// [`tests::supervisor_spec_default_routes_through_otp_canonical_ctor`]
2523/// (byte-parity pin against [`SupervisorSpec::otp_canonical`] under
2524/// [`PartialEq`], sharpening the sibling
2525/// `supervisor_spec_default_*_routes_through_lifted_default` per-arm
2526/// pins from a per-field lift into a whole-struct one-source-of-truth
2527/// pin — the derived-until-now [`Default::default`] and the
2528/// [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
2529/// construction, not by coincidence).
2530impl Default for SupervisorSpec {
2531 #[inline]
2532 fn default() -> Self {
2533 Self::otp_canonical()
2534 }
2535}
2536
2537impl SupervisorSpec {
2538 /// `const`-context peer of the [`Default for SupervisorSpec`]
2539 /// impl (which routes through this constructor) — returns the
2540 /// Erlang/OTP-canonical `{one_for_one, 5, 60}` worker-supervisor
2541 /// baseline this crate reaches for in every fixture-builder
2542 /// `..SupervisorSpec::default()` struct-update expression and
2543 /// every downstream `SupervisorSpec::default()` seed.
2544 ///
2545 /// Each field routes through the same substrate-canonical
2546 /// [`SUPERVISOR_ESTRATEGIA_DEFAULT`] / [`default_max_restarts`] /
2547 /// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] lifted consts the
2548 /// per-arm pin tests
2549 /// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`]
2550 /// / [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`]
2551 /// / [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
2552 /// already assert, so a future coherent rebrand of the OTP-canonical
2553 /// triple (Elixir's `{max_restarts: 3, max_seconds: 5}`, a per-
2554 /// cluster overlay via a future `:restart-window-overrides` slot, a
2555 /// per-child-cohort promotion the INSPIRATIONS.md §II.2 Erlang/OTP
2556 /// absorption roadmap acknowledges) migrates through three typed
2557 /// constants in lockstep, and the paired [`Default`] impl inherits
2558 /// every future extension by construction.
2559 ///
2560 /// `pub const fn` rather than the derived-style `Default::default`
2561 /// or a `pub const SUPERVISOR_SPEC_DEFAULT: SupervisorSpec` item —
2562 /// [`Default::default`] is not `const` on stable Rust, and
2563 /// `SupervisorSpec` is non-`Copy` so a `pub const` item would force
2564 /// every consumer through a [`Clone::clone`]. The `pub const fn`
2565 /// discipline lets `const`-context callers construct the OTP-
2566 /// canonical baseline at compile time without runtime dispatch on
2567 /// the derived [`Default::default`], the same posture the sibling
2568 /// [`crate::LimitsSpec::empty`] (9739971) /
2569 /// [`crate::aplicacao::MeshPolicy::empty`] (6df969b) /
2570 /// [`crate::BehaviorSpec::empty`] (f9b18e3) `Option`-only typed-slot
2571 /// spec `pub const fn` constructors carry on the sibling
2572 /// "everything `None`" baseline axis.
2573 ///
2574 /// Fourth peer on the M2 / M3 typed-slot-spec "const-context peer
2575 /// of the derived-style [`Default`]" family — sibling of the
2576 /// [`crate::LimitsSpec::empty`] / [`crate::aplicacao::MeshPolicy::empty`]
2577 /// / [`crate::BehaviorSpec::empty`] `Option`-only "canonical unset
2578 /// baseline" trio, extended here onto the M2 supervisor-slot
2579 /// [`SupervisorSpec`] whose canonical baseline is not "everything
2580 /// `None`" but the Erlang/OTP-canonical `{one_for_one, 5, 60}`
2581 /// worker-supervisor triple. Named [`Self::otp_canonical`] rather
2582 /// than `empty()` to name the actual invariant the return value
2583 /// pins — the same phrasing already used in the per-arm pin tests
2584 /// on this file. Pinned load-bearing by
2585 /// [`tests::supervisor_spec_otp_canonical_byte_equals_default`] and
2586 /// [`tests::supervisor_spec_otp_canonical_is_usable_in_const_context`].
2587 #[must_use]
2588 pub const fn otp_canonical() -> Self {
2589 Self {
2590 estrategia: SUPERVISOR_ESTRATEGIA_DEFAULT,
2591 max_restarts: default_max_restarts(),
2592 restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
2593 children: Vec::new(),
2594 }
2595 }
2596
2597 /// Substrate-canonical per-`:supervisor` `:estrategia` OTP-shaped
2598 /// sibling-restart-strategy scalar accessor every consumer that
2599 /// dispatches on the supervisor's per-sibling restart-decision shape
2600 /// keys off — returns the author-declared `:supervisor :estrategia`
2601 /// variant verbatim as a [`RestartStrategy`], `Copy`-projected from
2602 /// the typed slot's own [`RestartStrategy`] storage.
2603 ///
2604 /// The `:supervisor :estrategia` slot carries the closed-set
2605 /// OTP-shaped sibling-restart-strategy discriminator ([`RestartStrategy::OneForOne`]
2606 /// — restart only the failed child, the Erlang/OTP `one_for_one` default;
2607 /// [`RestartStrategy::OneForAll`] — restart every child on any child
2608 /// failure, the Erlang/OTP `one_for_all` shared-state cohort default;
2609 /// [`RestartStrategy::RestForOne`] — restart the failed child and
2610 /// every child started after it, the Erlang/OTP `rest_for_one`
2611 /// startup-order default; [`RestartStrategy::SimpleOneForOne`] —
2612 /// dynamic children of the same shape, the Erlang/OTP
2613 /// `simple_one_for_one` per-session default) that every downstream
2614 /// consumer of the Supervisor's per-sibling restart-decision fan-out
2615 /// shape keys off. Validated by [`SupervisorSpec::validate`] to be
2616 /// paired coherently with the sibling `:children` axis
2617 /// (`SimpleOneForOne ↔ children.is_empty()` — the cross-slot
2618 /// partition the strategy-arm's [`SupervisorError::SimpleOneForOneWithStaticChildren`]
2619 /// / [`SupervisorError::NoChildren`] refusal cascade pins), and every
2620 /// downstream consumer that reads the strategy keys off this scalar
2621 /// (the [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
2622 /// partition-dispatch `match` arm, the non-`SimpleOneForOne`-arm
2623 /// declared-but-empty [`SupervisorError::NoChildren`] error carrier's
2624 /// `estrategia:` field, the future `feira app graph` per-Supervisor
2625 /// strategy print line, the future wasm-operator's per-supervisor
2626 /// sibling-restart-strategy branch, the future M4
2627 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-strategy
2628 /// admission-webhook resolver, the `caixa-operator`'s hierarchical
2629 /// reconciliation scheduler's per-strategy fan-out).
2630 ///
2631 /// Prior to this lift the `.estrategia` field was accessed inline at
2632 /// two production sites in `caixa-core/src/supervisor.rs` — the
2633 /// [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
2634 /// `match self.estrategia { … }` partition dispatch, and the
2635 /// non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
2636 /// carrier at `estrategia: self.estrategia` — two open-coded
2637 /// field-accesses that expressed no compile-time link back to the
2638 /// typed slot. A future extension of the `:supervisor :estrategia`
2639 /// axis to a richer author surface (a per-cluster strategy override
2640 /// the operator pins through a future `:supervisor :estrategia-overrides`
2641 /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
2642 /// acknowledges, a per-tenant strategy-alias table the M4 CR
2643 /// materializer resolves per-CR, a per-Supervisor dynamic strategy
2644 /// derivation the future adaptive-supervision engine computes from
2645 /// child-failure-history topology, a per-child-cohort strategy split
2646 /// the future `RestForCohort` extension acknowledged by the
2647 /// INSPIRATIONS.md §II.2 Erlang/OTP absorption roadmap acknowledges)
2648 /// would have had to be threaded through every open-coded copy in
2649 /// lockstep — one consumer reading the raw variant while a peer read
2650 /// the operator-resolved variant would silently split the
2651 /// [`SupervisorError::NoChildren`] diagnostic's quoted strategy from
2652 /// the actual partition-dispatch input the empty-children refusal
2653 /// arm reached under, a two-consumer split at the validator far from
2654 /// the source `caixa.lisp` with no field naming the strategy-drift
2655 /// root cause. Lifting the resolution rule to a typed method on the
2656 /// substrate primitive means every downstream consumer of the
2657 /// Supervisor's per-`:supervisor` sibling-restart-strategy surface
2658 /// reaches for exactly one typed dispatch — the resolver's accept-set
2659 /// migrates as a unit on any future axis addition.
2660 ///
2661 /// Peer of the sibling M3 mesh-slot [`crate::Placement::estrategia`]
2662 /// (921fe1b) `Copy`-return `PlacementStrategy` scalar accessor on the
2663 /// per-`:placement` distribution-strategy axis — same "one typed
2664 /// dispatch on the substrate primitive, thin projections at each
2665 /// consumer" discipline extended onto the M2 supervisor-slot
2666 /// per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
2667 /// scalar axis. The two typed axes (`Placement::estrategia` on the
2668 /// M3 Aplicacao side, `SupervisorSpec::estrategia` on the M2
2669 /// Supervisor side) now share one accessor discipline for the shared
2670 /// substrate concept "a `Copy`-projected closed-set enum-arm
2671 /// discriminator that partitions the downstream renderer's per-arm
2672 /// fan-out". First `Copy`-return accessor on the M2 supervisor-slot
2673 /// `SupervisorSpec` type — companion to the sibling per-`:children`
2674 /// [`crate::ChildSpec::nome`] (57c61d0) /
2675 /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
2676 /// scalar accessors on the sibling per-`:children` `String`-carry
2677 /// axes. Named `estrategia()` to match the storage field's name and
2678 /// the peer [`crate::Placement::estrategia`] method-name discipline
2679 /// verbatim; the accessor's identity name maps onto the canonical
2680 /// OTP-shape supervision vocabulary the [`RestartStrategy`] enum's
2681 /// docstring already carries.
2682 ///
2683 /// Declared `pub const fn` to close the M2 supervisor-slot
2684 /// `Copy`-return raw-field-getter `const`-eval-surface pass —
2685 /// sibling of the peer M2 per-`:children` [`ChildSpec::restart`]
2686 /// (converted in this commit) `Copy`-composite-enum accessor, peer
2687 /// of the sibling M2 per-`:supervisor`
2688 /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
2689 /// already lifted, and mirror of the peer M3 mesh-slot
2690 /// per-`:placement` [`crate::Placement::estrategia`] (bafa004)
2691 /// `Copy`-return `pub const fn` scalar accessor whose method-name
2692 /// discipline this accessor was authored to match. Every downstream
2693 /// substrate-side `const`-context consumer of the per-`:supervisor`
2694 /// sibling-restart-strategy scalar (a future module-scope `const
2695 /// _:() = assert!(matches!(sup.estrategia(),
2696 /// RestartStrategy::OneForOne))` invariant pin on a typed fixture,
2697 /// a future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
2698 /// admission-webhook `const fn` per-supervisor strategy-arm floor
2699 /// over a typed [`SupervisorSpec`], any future `const fn`
2700 /// supervisor-tree composer over the substrate primitive that fans
2701 /// on the sibling-restart-strategy at compile time) now reaches
2702 /// through the same typed dispatch on the substrate primitive at
2703 /// const-eval time as at runtime. A future non-`Copy`-return
2704 /// promotion of the scalar (an `Option<RestartStrategy>`-shape
2705 /// migration once the substrate grows per-cluster strategy overlays
2706 /// the [`SupervisorSpec`] docstring already anticipates, a
2707 /// per-tenant strategy-alias table the M4 CR materializer resolves
2708 /// per-CR) that would drop the `const` qualifier fails the
2709 /// fail-before-pass-after pin
2710 /// [`tests::supervisor_spec_estrategia_accessor_is_const_fn`] at
2711 /// caixa-core build time rather than surfacing as a downstream
2712 /// consumer regression.
2713 #[must_use]
2714 pub const fn estrategia(&self) -> RestartStrategy {
2715 self.estrategia
2716 }
2717
2718 /// Substrate-canonical per-`:supervisor` `:max-restarts` OTP-shaped
2719 /// `MaxIntensity` restart-budget scalar accessor every consumer that
2720 /// reads the supervisor's per-`:restart-window` restart-budget count
2721 /// keys off — returns the author-declared `:supervisor :max-restarts`
2722 /// typed `u32` verbatim, `Copy`-projected from the typed slot's own
2723 /// `u32` storage (`u32` is `Copy`, so the accessor returns by value; no
2724 /// borrow of `&self` past the call). Non-optional (the `u32` field
2725 /// carries the restart-budget count as a required axis with a
2726 /// [`default_max_restarts`]-supplied default; the zero-floor arm
2727 /// [`SupervisorError::ZeroMaxRestarts`] and the cap arm
2728 /// [`SupervisorError::MaxRestartsExceedsCap`] jointly bracket the
2729 /// accept-set to `1..=SUPERVISOR_MAX_RESTARTS_MAX`).
2730 ///
2731 /// The `:supervisor :max-restarts` slot carries the Erlang/OTP
2732 /// `MaxIntensity` restart-budget count that pairs with the sibling
2733 /// `:restart-window` `Period` to form the `MaxIntensity / Period`
2734 /// restart-intensity ratio the supervisor trips its own escalation on
2735 /// (`theory/RUNTIME-PATTERNS.md` §II.2, Learn You Some Erlang's
2736 /// `{intensity, 5, 60}` worker-supervisor default). Every downstream
2737 /// consumer of the Supervisor's per-`:supervisor` restart-budget count
2738 /// keys off this scalar (the [`SupervisorSpec::validate`] zero-floor +
2739 /// upper-cap bracket at
2740 /// `require_positive_bounded_u32(self.max_restarts(), …)`, the future
2741 /// wasm-operator's per-supervisor restart-intensity counter's
2742 /// budget-vs-count comparator, the future M4
2743 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2744 /// webhook, the `caixa-operator`'s hierarchical reconciliation
2745 /// scheduler's per-supervisor escalation-decision branch, every
2746 /// `SupervisorError::MaxRestartsExceedsCap` variant carrying the
2747 /// offending count verbatim for `feira lint` rendering).
2748 ///
2749 /// Prior to this lift the `.max_restarts` field was accessed inline at
2750 /// one production site in `caixa-core/src/supervisor.rs` — the
2751 /// [`SupervisorSpec::validate`] `require_positive_bounded_u32(self
2752 /// .max_restarts, …)` bracket-gate call — one open-coded field-access
2753 /// that expressed no compile-time link back to the typed slot. A
2754 /// future extension of the `:max-restarts` axis to a richer author
2755 /// surface (a per-cluster restart-budget override the operator pins
2756 /// through a future `:supervisor :max-restarts-overrides` slot the
2757 /// MESH-COMPOSITION §III.2 supervision-canary roadmap acknowledges,
2758 /// a per-tenant restart-budget-alias table the M4 CR materializer
2759 /// resolves per-CR, a per-supervisor dynamic restart-budget derivation
2760 /// the future adaptive-supervision engine computes from child-failure-
2761 /// history topology, a promotion of the plain `u32` count to a richer
2762 /// `{MaxR, MaxT}` tuple once Erlang/OTP's per-child-cohort restart-
2763 /// budget-partition slot comes into scope) would have had to be
2764 /// threaded through every open-coded copy in lockstep or the validate
2765 /// gate and the future M4 emit path would silently disagree on which
2766 /// restart-budget count a given supervisor resolves to — an author's
2767 /// `:max-restarts 5` would satisfy validate while the emit path
2768 /// silently read a drifted other value (a `:max-restarts 10000`
2769 /// no-op supervisor at the emit boundary would carry the author's
2770 /// declared `5` verbatim in `feira lint` output while the future
2771 /// wasm-operator's restart-intensity counter operated under the
2772 /// drifted count), a two-consumer split at the validator far from the
2773 /// source `caixa.lisp` with no field naming the restart-budget-drift
2774 /// root cause. Lifting the resolution rule to a typed method on the
2775 /// substrate primitive means every downstream consumer of the
2776 /// Supervisor's per-`:supervisor` restart-budget-count surface reaches
2777 /// for exactly one typed dispatch — the resolver's accept-set migrates
2778 /// as a unit on any future axis addition.
2779 ///
2780 /// Peer of the sibling M3 mesh-slot [`crate::CircuitBreaker::max_failures`]
2781 /// (3a74062) `Copy`-return `u32` sub-struct required-scalar accessor
2782 /// on the per-`:politicas :circuit-breaker :max-failures` Envoy-
2783 /// outlier-detection trip-threshold axis — same "one typed dispatch on
2784 /// the substrate primitive, thin projections at each consumer"
2785 /// discipline extended onto the M2 supervisor-slot per-`:supervisor`
2786 /// restart-budget-count `Copy`-`u32` scalar axis. The two typed axes
2787 /// (`CircuitBreaker::max_failures` on the M3 Aplicacao side,
2788 /// `SupervisorSpec::max_restarts` on the M2 Supervisor side) now share
2789 /// one accessor discipline for the shared substrate concept "a
2790 /// `Copy`-projected required `u32` count that trips the next-higher
2791 /// protection layer after N events in a rolling window" — both are
2792 /// counters with identical degenerate-at-the-high-end shape and share
2793 /// the paired [`crate::POLICY_BREAKER_MAX_FAILURES_MAX`] /
2794 /// [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` cap. Second `Copy`-return
2795 /// accessor on the M2 supervisor-slot `SupervisorSpec` type, sibling
2796 /// to the [`SupervisorSpec::estrategia`] (eafb619) `Copy`-composite-
2797 /// enum `RestartStrategy` accessor. Named `max_restarts()` to match
2798 /// the storage field's name verbatim and the peer
2799 /// [`crate::CircuitBreaker::max_failures`] method-name discipline; the
2800 /// accessor's identity maps onto the canonical OTP-shape supervision
2801 /// vocabulary the [`SupervisorSpec::max_restarts`] field's docstring
2802 /// already carries.
2803 #[must_use]
2804 pub const fn max_restarts(&self) -> u32 {
2805 self.max_restarts
2806 }
2807
2808 /// Substrate-canonical per-`:supervisor` `:restart-window` OTP-shaped
2809 /// `Period` sliding-window scalar accessor every consumer of the
2810 /// supervisor's `MaxIntensity / Period` restart-intensity denominator
2811 /// keys off — returns the author-declared `:supervisor :restart-window`
2812 /// typed [`Duration`] verbatim as an `Option<Duration>`, copied out of
2813 /// the typed slot's own `Option<Duration>` storage (`Duration` is
2814 /// `Copy`, so `Option<Duration>` is `Copy` and the accessor returns by
2815 /// value; no borrow of `&self` past the call). `None` when the slot is
2816 /// absent (the canonical "never reset — every restart across the
2817 /// supervisor's lifetime counts against the sibling `:max-restarts`
2818 /// budget" sentinel the field's own docstring names and the peer
2819 /// `validate_accepts_none_restart_window` pin locks in on the
2820 /// [`SupervisorSpec::validate`] entry-side).
2821 ///
2822 /// The `:supervisor :restart-window` slot carries the Erlang/OTP
2823 /// `Period` sliding-observation-interval that pairs with the sibling
2824 /// `:max-restarts` `MaxIntensity` restart-budget count to form the
2825 /// `MaxIntensity / Period` restart-intensity ratio the supervisor
2826 /// trips its own escalation on (`theory/RUNTIME-PATTERNS.md` §II.2,
2827 /// Learn You Some Erlang's `{intensity, 5, 60}` worker-supervisor
2828 /// default). The typed slot's `Option<Duration>` accept-set —
2829 /// zero-floor rejected through [`SupervisorError::RestartWindowZero`]
2830 /// (Erlang/OTP's `MaxIntensity / Period` invariant requires
2831 /// `Period > 0`; a zero period either trips on the first failure or
2832 /// never trips depending on operator interpretation, neither of which
2833 /// is the author's intent — omit the slot to express "no reset";
2834 /// carry a positive duration to express the sliding window),
2835 /// integer-millisecond canonical form enforced through
2836 /// [`SupervisorError::RestartWindowNotCanonical`] (the duration
2837 /// codec's canonical form emits `"1500ms"` not `"1.5s"` and the
2838 /// future wasm-operator's per-supervisor restart-intensity counter
2839 /// quantizes at milliseconds), upper-bounded by
2840 /// [`SUPERVISOR_RESTART_WINDOW_MAX`] (1h — the coarsest per-
2841 /// supervisor rolling window any operationally-reachable supervisor
2842 /// can honor without spanning multiple scheduler epochs the
2843 /// hierarchical-reconciliation scheduler treats as independent) —
2844 /// maps onto the future wasm-operator (M3) per-supervisor
2845 /// restart-intensity counter's rolling-observation-interval, the
2846 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2847 /// per-`spec.restartWindow` admission webhook, and the sibling
2848 /// `duration_codec`-serialized wire scalar every downstream consumer
2849 /// of the supervisor's per-`:supervisor` restart-intensity denominator
2850 /// keys off.
2851 ///
2852 /// Prior to this lift the `.restart_window` field was accessed inline
2853 /// at one production site in `caixa-core/src/supervisor.rs` — the
2854 /// [`SupervisorSpec::validate`] `if let Some(w) = self.restart_window {
2855 /// … }` zero-floor + canonical-form + upper-cap bracket arm — one
2856 /// open-coded field-access that expressed no compile-time link back to
2857 /// the typed slot. A future extension of the `:restart-window` axis to
2858 /// a richer author surface (a per-cluster restart-window override the
2859 /// operator pins through a future `:supervisor :restart-window-overrides`
2860 /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
2861 /// acknowledges, a per-tenant restart-window-alias table the M4 CR
2862 /// materializer resolves per-CR, a per-supervisor dynamic
2863 /// restart-window derivation the future adaptive-supervision engine
2864 /// computes from child-failure-history topology, a promotion of the
2865 /// plain `Option<Duration>` window to a richer `{observation, cooldown}`
2866 /// pair once Erlang/OTP's per-child-cohort observation-interval-
2867 /// partition slot comes into scope) would have had to be threaded
2868 /// through every open-coded copy in lockstep or the validate gate and
2869 /// the future M4 emit path would silently disagree on which
2870 /// restart-window a given supervisor resolves to — an author's
2871 /// `:restart-window "60s"` would satisfy validate while the emit path
2872 /// silently read a drifted other value (a `Some(Duration::from_secs(60))`
2873 /// authored slot at the emit boundary would carry the author's
2874 /// declared window verbatim in `feira lint` output while the future
2875 /// wasm-operator's restart-intensity counter operated under a
2876 /// drifted window, or vice versa: an author's `:restart-window ()`
2877 /// would carry the "never reset" sentinel through validate while the
2878 /// emit path silently substituted a default sliding window), a
2879 /// two-consumer split at the validator far from the source
2880 /// `caixa.lisp` with no field naming the restart-window-drift root
2881 /// cause. Lifting the resolution rule to a typed method on the
2882 /// substrate primitive means every downstream consumer of the
2883 /// Supervisor's per-`:supervisor` restart-intensity-denominator
2884 /// surface reaches for exactly one typed dispatch — the resolver's
2885 /// accept-set migrates as a unit on any future axis addition.
2886 ///
2887 /// Third `Copy`-return accessor on the M2 supervisor-slot
2888 /// `SupervisorSpec` type, closing the last unlifted per-`:supervisor`
2889 /// scalar-value axis (`children: Vec<ChildSpec>` carries a `Vec`
2890 /// payload rather than a `Copy`-scalar, and the per-`:children`
2891 /// [`crate::ChildSpec::nome`] (57c61d0) /
2892 /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
2893 /// scalar accessors already close the per-element `String`-carry
2894 /// axes). Sibling to the peer M2 [`crate::LimitsSpec::wall_clock`]
2895 /// (8cb717b) `Option<Duration>` accessor on the `:limits` slot's
2896 /// per-outermost-call wall-clock-deadline axis and the peer M3
2897 /// [`crate::MeshPolicy::timeout`] (7073d0f) `Option<Duration>`
2898 /// accessor on the `:politicas` slot's per-call-deadline axis — all
2899 /// three share the shared substrate concept "a `Copy`-projected
2900 /// optional `Duration` that carries a positive integer-millisecond
2901 /// canonical value with a `1ms..=<axis-specific>_MAX` accept-set and
2902 /// the paired zero-floor / non-canonical / above-cap refusal cascade"
2903 /// through the same [`crate::render::require_positive_canonical_bounded_duration`]
2904 /// bracket-helper the three axes each route through. Named
2905 /// `restart_window()` to match the storage field's name verbatim and
2906 /// the peer [`crate::LimitsSpec::wall_clock`] /
2907 /// [`crate::MeshPolicy::timeout`] method-name discipline; the
2908 /// accessor's identity maps onto the canonical OTP-shape supervision
2909 /// vocabulary the [`SupervisorSpec::restart_window`] field's docstring
2910 /// already carries.
2911 #[must_use]
2912 pub const fn restart_window(&self) -> Option<Duration> {
2913 self.restart_window
2914 }
2915
2916 /// Substrate-canonical per-`:supervisor` `:children` OTP-shaped
2917 /// static-child-list slice accessor every consumer that walks the
2918 /// supervisor's declared child set keys off — returns the author-
2919 /// declared `:supervisor :children` `Vec<ChildSpec>` verbatim as a
2920 /// `&[ChildSpec]` slice-view, borrowed from the typed slot's own
2921 /// `Vec<ChildSpec>` storage (a zero-copy slice-view over the same
2922 /// backing buffer the `Serialize`/`Deserialize` derives round-trip
2923 /// through). Non-optional: an empty slice is the load-bearing
2924 /// "author declared `:children ()`" sentinel every consumer of the
2925 /// cross-slot `SimpleOneForOne ↔ children.is_empty()` partition
2926 /// keys off (`SimpleOneForOne` requires the empty slice; the peer
2927 /// three strategies require a non-empty slice — the paired
2928 /// [`SupervisorError::SimpleOneForOneWithStaticChildren`] /
2929 /// [`SupervisorError::NoChildren`] refusal cascade pins the
2930 /// partition on both arms).
2931 ///
2932 /// The `:supervisor :children` slot carries the OTP-shaped static
2933 /// child list the supervisor materializes one ComputeUnit per
2934 /// entry from — the Erlang/OTP `supervisor:init/1`'s
2935 /// `{ok, {SupFlags, ChildSpecs}}` `ChildSpecs` list, projected
2936 /// through the tatara-lisp `:children` author surface onto a typed
2937 /// `Vec<ChildSpec>` whose per-element `(nome(),
2938 /// versao_requirement(), restart)` triple the per-child
2939 /// [`SupervisorSpec::validate`] loop already gates through the
2940 /// lifted [`ChildSpec::nome`] (57c61d0) /
2941 /// [`ChildSpec::versao_requirement`] (2c053c8) scalar accessors.
2942 /// Every downstream consumer that fans on the static child list
2943 /// keys off this slice (the [`SupervisorSpec::validate`]
2944 /// `SimpleOneForOne ↔ non-SimpleOneForOne` partition dispatch's
2945 /// `.is_empty()` probe on both arms, the [`SupervisorSpec::validate`]
2946 /// per-child DNS-1123 / semver-requirement / duplicate-detection
2947 /// fan-out loop, every future wasm-operator (M3) per-supervisor
2948 /// hierarchical-reconciliation scheduler's per-child ComputeUnit
2949 /// materialization loop, the future M4
2950 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2951 /// admission-webhook fan-out, the future `feira app graph`
2952 /// per-supervisor tree-print traversal).
2953 ///
2954 /// Prior to this lift the `.children` `Vec<ChildSpec>` was accessed
2955 /// inline at three production sites in `caixa-core/src/supervisor.rs`
2956 /// — the [`SupervisorSpec::validate`] `SimpleOneForOne`-arm
2957 /// `!self.children.is_empty()` cross-slot refusal probe, the peer
2958 /// non-`SimpleOneForOne`-arm `self.children.is_empty()`
2959 /// [`SupervisorError::NoChildren`] refusal probe, and the per-child
2960 /// validate loop's `for child in &self.children` traversal head —
2961 /// three open-coded field-accesses that expressed no compile-time
2962 /// link back to the typed slot. A future extension of the
2963 /// `:supervisor :children` axis to a richer author surface (a
2964 /// per-cluster child-set overlay the operator pins through a future
2965 /// `:supervisor :children-overrides` slot the MESH-COMPOSITION §III.2
2966 /// supervision-canary roadmap acknowledges, a per-tenant
2967 /// child-set-alias table the M4 CR materializer resolves per-CR,
2968 /// a per-supervisor dynamic-child derivation the future adaptive-
2969 /// supervision engine computes from child-failure-history topology,
2970 /// a promotion of the plain `Vec<ChildSpec>` to a richer
2971 /// `{static, dynamic}` partition once Erlang/OTP's
2972 /// `simple_one_for_one` dynamic-child slot comes into typed scope)
2973 /// would have had to be threaded through all three open-coded copies
2974 /// in lockstep or one consumer would silently disagree with the
2975 /// peers on which child-set a given supervisor resolves to — the
2976 /// `SimpleOneForOne`-arm probe reading the raw slot while the peer
2977 /// non-`SimpleOneForOne`-arm probe read an operator-resolved slot
2978 /// would silently split the partition-dispatch's two-arm coherence
2979 /// (a supervisor that satisfies neither arm's precondition, or that
2980 /// satisfies both, at the cost of the paired
2981 /// `SimpleOneForOneWithStaticChildren`/`NoChildren` refusal cascade
2982 /// silently drifting from the per-child validate loop's actual
2983 /// traversal input), a three-consumer split at the validator far
2984 /// from the source `caixa.lisp` with no field naming the
2985 /// child-set-drift root cause. Lifting the resolution rule to a
2986 /// typed method on the substrate primitive means every downstream
2987 /// consumer of the Supervisor's per-`:supervisor` static-child-list
2988 /// surface reaches for exactly one typed dispatch — the resolver's
2989 /// accept-set migrates as a unit on any future axis addition.
2990 ///
2991 /// First slice-return (`&[T]`) accessor on any M2 or M3 typed slot
2992 /// — the seed for the same "one typed dispatch on the substrate
2993 /// primitive, thin projections at each consumer" discipline the
2994 /// closed [`crate::LimitsSpec`] / [`BehaviorSpec`] /
2995 /// [`crate::UpgradeFromEntry`] scalar-accessor families each carry
2996 /// on their `Copy` / `Option<Copy>` / `Option<&str>` axes, extended
2997 /// onto the first `Vec`-carry axis on the substrate. The four peer
2998 /// `Vec`-carry axes still unlifted at the time of this seed —
2999 /// [`crate::Placement::clusters`] (`Vec<String>` per-cluster
3000 /// distribution-target list), [`crate::AplicacaoSpec::membros`]
3001 /// (`Vec<Membro>` per-Aplicacao member list),
3002 /// [`crate::AplicacaoSpec::contratos`] (`Vec<WitContract>`
3003 /// per-Aplicacao WIT-typed edge list),
3004 /// [`crate::UpgradeFromEntry::instructions`]
3005 /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
3006 /// — inherit this accessor's discipline as future compounding runs
3007 /// migrate their consumers onto the shared slice-return shape.
3008 /// Fourth (and final) accessor on the M2 supervisor-slot
3009 /// `SupervisorSpec` type, sibling to the three `Copy`-return
3010 /// [`SupervisorSpec::estrategia`] (eafb619) /
3011 /// [`SupervisorSpec::max_restarts`] (7844f4e) /
3012 /// [`SupervisorSpec::restart_window`] (7e7b32f) accessors — closes
3013 /// the last unlifted per-`:supervisor` field axis (the
3014 /// `Vec<ChildSpec>` static-child-list carrier) so every downstream
3015 /// per-`:supervisor` reader now routes through a typed dispatch on
3016 /// the substrate primitive. Named `children()` to match the storage
3017 /// field's name verbatim and the tatara-lisp author-surface term
3018 /// (`:children`) the field's own docstring already carries; the
3019 /// accessor's identity maps onto the canonical OTP-shape
3020 /// supervision vocabulary the [`SupervisorSpec::children`] field's
3021 /// docstring already reaches for ("Static children ..."). Returns
3022 /// `&[ChildSpec]` (not `&Vec<ChildSpec>`) because every downstream
3023 /// consumer of the child list treats it as a read-only sequence —
3024 /// the slice-view is the narrowest borrow that supports every
3025 /// present + roadmapped consumer (`.is_empty()`, `.iter()`,
3026 /// index, `.len()`) without leaking the backing `Vec`'s
3027 /// grow/push/reserve surface that no consumer of the typed view
3028 /// reaches for (the storage-side `Vec` remains reachable through
3029 /// the `pub children` field for the mutation-carrying
3030 /// `Caixa::supervisor_view` fold-in path in
3031 /// `manifest.rs:supervisor_view`).
3032 #[must_use]
3033 pub const fn children(&self) -> &[ChildSpec] {
3034 self.children.as_slice()
3035 }
3036
3037 /// Validate the supervisor's typed shape — strategy ↔ children
3038 /// invariants, max_restarts > 0, restart_window > 0 when set,
3039 /// per-child non-empty + duplicate-free names.
3040 ///
3041 /// Mirrors the value-shape discipline applied to every other
3042 /// typed slot:
3043 ///
3044 /// - `Some(Duration::ZERO)` on a Duration-bearing axis is the
3045 /// same "0 means the opposite of what you think" footgun
3046 /// closed for `:politicas :timeout` (Envoy interprets a zero
3047 /// timeout as `infinite`), `:politicas :circuit-breaker
3048 /// :window`, and `:limits :wall-clock`. The
3049 /// `MaxIntensity / Period` ratio in Erlang/OTP's
3050 /// `supervisor` requires `Period > 0`; a zero period either
3051 /// trips on the first failure or never trips depending on
3052 /// operator interpretation, neither of which is the
3053 /// author's intent. Omit `:restart-window` to express "no
3054 /// reset"; carry a positive duration to express the window.
3055 /// - duplicate `:children` `:caixa` names are the same
3056 /// graph-node-set / multiset distinction closed for
3057 /// `:membros` (4bb3f3d), `:placement :clusters` (c7c7799),
3058 /// and `:entrada :paths` (eb3456d). Two children with the
3059 /// same `:caixa` materialize as two ComputeUnits with the
3060 /// same name in the cluster's HelmRelease values, one
3061 /// silently overwriting the other. Erlang/OTP's
3062 /// `child_spec.id` is required-unique per supervisor;
3063 /// pleme-io enforces the same set-not-multiset shape on
3064 /// `:caixa` (the load-bearing identity in our renderer).
3065 pub fn validate(&self) -> Result<(), SupervisorError> {
3066 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition
3067 // dispatch and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
3068 // error carrier's `estrategia:` field through the lifted
3069 // [`SupervisorSpec::estrategia`] accessor rather than the raw
3070 // `self.estrategia` field access — the two production consumers
3071 // of the per-`:supervisor` sibling-restart-strategy scalar now
3072 // key off exactly one typed dispatch on the substrate primitive,
3073 // so any future rebrand on the axis (a per-cluster strategy
3074 // override the operator pins through a future `:supervisor
3075 // :estrategia-overrides` slot, a per-tenant strategy-alias table
3076 // the M4 CR materializer resolves per-CR) migrates as a single
3077 // caixa-core edit rather than a coordinated rewrite of the two
3078 // call sites — sibling of the peer M3 [`crate::Placement::estrategia`]
3079 // (921fe1b) four-consumer migration on the per-`:placement`
3080 // distribution-strategy axis.
3081 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition-
3082 // dispatch's paired `.is_empty()` cross-slot refusal probes
3083 // (the `SimpleOneForOne`-arm
3084 // [`SupervisorError::SimpleOneForOneWithStaticChildren`] refusal
3085 // and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
3086 // refusal) through the lifted [`SupervisorSpec::children`]
3087 // slice-return accessor rather than the raw `self.children`
3088 // field access — the two paired production consumers of the
3089 // per-`:supervisor` static-child-list scalar-shape now key off
3090 // exactly one typed dispatch on the substrate primitive, so any
3091 // future rebrand on the axis (a per-cluster child-set overlay
3092 // the operator pins through a future `:supervisor
3093 // :children-overrides` slot, a per-tenant child-set-alias table
3094 // the M4 CR materializer resolves per-CR) migrates as a single
3095 // caixa-core edit rather than a coordinated rewrite of the
3096 // paired arms — first slice-return migration on any typed slot,
3097 // seed for the peer per-`:placement :clusters`,
3098 // per-`:membros`, per-`:contratos`, and per-`:upgrade-from
3099 // :instructions` `Vec`-carry axes.
3100 match self.estrategia() {
3101 RestartStrategy::SimpleOneForOne => {
3102 // SimpleOneForOne: children added at runtime. Static
3103 // list must be empty (one shape declared elsewhere).
3104 if !self.children().is_empty() {
3105 return Err(SupervisorError::SimpleOneForOneWithStaticChildren);
3106 }
3107 }
3108 _ => {
3109 if self.children().is_empty() {
3110 return Err(SupervisorError::no_children(self.estrategia()));
3111 }
3112 }
3113 }
3114 // Zero-floor + upper-cap bracket on the typed `:max-restarts`
3115 // axis. See [`crate::render::require_positive_bounded_u32`] for
3116 // the ordering discipline (zero-floor arm strictly precedes cap
3117 // arm so `0` surfaces the self-locating `ZeroMaxRestarts`
3118 // diagnostic with its counter-axis remediation directly named,
3119 // not the misleading `0 > SUPERVISOR_MAX_RESTARTS_MAX == false`
3120 // cap-arm miss). Until this bracket landed the top edge ran all
3121 // the way to `u32::MAX` and a struct-literal
3122 // `SupervisorSpec { max_restarts: 100_000, .. }` (or the
3123 // equivalent author-surface `:max-restarts 100000` /
3124 // `:max-restarts 4294967295` typo landing in the slot) silently
3125 // passed validate. The runtime substrate consuming the value
3126 // (Erlang/OTP's `MaxIntensity / Period` ratio, the future
3127 // wasm-operator's per-supervisor restart-intensity counter, the
3128 // M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
3129 // admission webhook) then turned a typed `:max-restarts`
3130 // policy into a no-op supervisor: the escalation threshold is
3131 // structurally so high that no realistic
3132 // restarts-per-`:restart-window` traffic shape can reach it,
3133 // the supervisor never escalates to its parent, and a bad
3134 // child can loop inside the window indefinitely with the
3135 // parent supervisor structurally never receiving the "this
3136 // subtree has exceeded its restart budget" signal the typed
3137 // slot is meant to express. The bracket set is
3138 // `1..=SUPERVISOR_MAX_RESTARTS_MAX`, peer with the
3139 // [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap on
3140 // the sibling `:politicas :circuit-breaker :max-failures` axis:
3141 // both are "trip the next-higher protection layer after N
3142 // events in a rolling window" counters with identical
3143 // degenerate-at-the-high-end shape and now share one canonical
3144 // bracket helper. The bracket precedes the sibling
3145 // `:restart-window` zero-floor / canonical-millisecond arms so
3146 // an over-cap `max_restarts` paired with a structurally invalid
3147 // window surfaces the bracket diagnostic first, mirroring the
3148 // `PolicyBreakerMaxFailuresExceedsCap` / window-axis cross-arm
3149 // ordering on the peer `:politicas :circuit-breaker` slot.
3150 // Route the [`SupervisorSpec::validate`] `:max-restarts` zero-floor +
3151 // upper-cap bracket-gate through the lifted [`SupervisorSpec::max_restarts`]
3152 // accessor rather than the raw `self.max_restarts` field access —
3153 // the one production consumer of the per-`:supervisor`
3154 // restart-budget-count scalar now keys off exactly one typed
3155 // dispatch on the substrate primitive, so any future rebrand on
3156 // the axis (a per-cluster restart-budget override the operator
3157 // pins through a future `:supervisor :max-restarts-overrides`
3158 // slot, a per-tenant restart-budget-alias table the M4 CR
3159 // materializer resolves per-CR) migrates as a single caixa-core
3160 // edit rather than a coordinated rewrite — sibling of the peer M3
3161 // [`crate::CircuitBreaker::max_failures`] (3a74062) migration on
3162 // the per-`:politicas :circuit-breaker :max-failures` axis.
3163 crate::render::require_positive_bounded_u32(
3164 self.max_restarts(),
3165 SUPERVISOR_MAX_RESTARTS_MAX,
3166 || SupervisorError::ZeroMaxRestarts,
3167 SupervisorError::max_restarts_exceeds_cap,
3168 )?;
3169 // Route the [`SupervisorSpec::validate`] `:restart-window`
3170 // zero-floor + integer-millisecond canonical-form + upper-cap
3171 // bracket-gate through the lifted [`SupervisorSpec::restart_window`]
3172 // accessor rather than the raw `self.restart_window` field access —
3173 // the one production consumer of the per-`:supervisor`
3174 // restart-intensity-denominator scalar now keys off exactly one
3175 // typed dispatch on the substrate primitive, so any future rebrand
3176 // on the axis (a per-cluster restart-window override the operator
3177 // pins through a future `:supervisor :restart-window-overrides`
3178 // slot, a per-tenant restart-window-alias table the M4 CR
3179 // materializer resolves per-CR) migrates as a single caixa-core
3180 // edit rather than a coordinated rewrite — sibling of the peer M2
3181 // [`crate::LimitsSpec::wall_clock`] (8cb717b) validate-arm-route
3182 // on the per-`:limits :wall-clock` axis and the peer M3
3183 // [`crate::MeshPolicy::timeout`] (7073d0f) accessor-route on the
3184 // per-`:politicas :timeout` axis.
3185 if let Some(w) = self.restart_window() {
3186 // Zero-floor + integer-millisecond canonical-form +
3187 // upper-cap bracket on the typed `:restart-window` axis.
3188 // See
3189 // [`crate::render::require_positive_canonical_bounded_duration`]
3190 // for the full three-arm ordering discipline (zero-floor
3191 // strictly precedes canonical-form so `Duration::ZERO`
3192 // surfaces the self-locating `RestartWindowZero`
3193 // diagnostic; canonical-form strictly precedes the cap arm
3194 // so a sub-millisecond above-cap value surfaces the more
3195 // fundamental round-trip-shape diagnostic first) and the
3196 // three peer typed-`Duration` sites that share this
3197 // canonical bracket ([`crate::MeshPolicy::timeout`],
3198 // [`crate::CircuitBreaker::window`],
3199 // [`crate::LimitsSpec::wall_clock`]). Every validated
3200 // value lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
3201 // (1ms..=1h), integer-millisecond granularity.
3202 crate::render::require_positive_canonical_bounded_duration(
3203 w,
3204 SUPERVISOR_RESTART_WINDOW_MAX,
3205 || SupervisorError::RestartWindowZero,
3206 SupervisorError::restart_window_not_canonical,
3207 SupervisorError::restart_window_exceeds_cap,
3208 )?;
3209 }
3210 // Route the per-child DNS-1123 / semver-requirement / duplicate-
3211 // detection fan-out loop through the lifted named per-slot gate
3212 // [`SupervisorSpec::validate_children`] rather than an inline
3213 // three-per-child cascade — every future consumer that wants to
3214 // re-check only the `:children` slot's per-entry axes (the M4
3215 // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
3216 // admission webhook re-validating one added/renamed child, the
3217 // future wasm-operator's per-child dynamic-add re-validator on
3218 // the `SimpleOneForOne` runtime-add path once dynamic-children
3219 // graduate to a typed slot, a future partial re-validator on a
3220 // per-`:children`-entry patch) reaches every per-entry axis
3221 // through one dispatch rather than re-inlining the three-arm
3222 // cascade in lockstep with `validate` or paying the peer
3223 // `:estrategia`/`:max-restarts`/`:restart-window` gates to
3224 // reach one entry check. Sibling of the peer M3 mesh-slot
3225 // per-slot gate family (`validate_membros` — the exact peer on
3226 // the M3 side, [`crate::AplicacaoSpec::validate_membros`];
3227 // `validate_contratos` — 906a5c6; `validate_entrada` — 20cd523;
3228 // `validate_placement`; `validate_politicas` routing through
3229 // `MeshPolicy::validate` — f03a154) — the M2 supervisor-slot
3230 // per-slot gate discipline now spans both the M3 mesh-slot
3231 // family and the M2 `:children` per-child-cascade axis on one
3232 // shape: one named per-slot gate per typed per-entry loop.
3233 self.validate_children()?;
3234 Ok(())
3235 }
3236
3237 /// Named per-slot gate on the M2 `:supervisor :children` per-entry
3238 /// axis — folds the per-child DNS-1123 name gate, semver-requirement
3239 /// gate, and duplicate-`:caixa` dedup arm into one call every
3240 /// consumer that wants to re-validate one `:children` entry (or the
3241 /// whole list) against the same accept-set [`SupervisorSpec::validate`]
3242 /// admits reaches through.
3243 ///
3244 /// Peer of the M3 mesh-slot [`crate::AplicacaoSpec::validate_membros`]
3245 /// per-slot gate on the analogous per-entry axis (`:membros`) — same
3246 /// three-per-entry shape (DNS-1123 name + semver-requirement +
3247 /// duplicate-`:caixa` dedup), lifted to one named substrate
3248 /// primitive per slot. The M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
3249 /// materializer's admission webhook re-checking one added or renamed
3250 /// child, the future wasm-operator's per-child dynamic-add
3251 /// re-validator on the `SimpleOneForOne` runtime-add path once
3252 /// dynamic-children graduate to a typed slot, a future partial
3253 /// re-validator on a per-`:children`-entry patch — each reaches the
3254 /// three per-entry axes through this one dispatch rather than
3255 /// re-inlining the three-arm cascade in lockstep with `validate`
3256 /// (the duplication the PRIME DIRECTIVE names as a bug) or paying
3257 /// the peer `:estrategia`/`:max-restarts`/`:restart-window` gates to
3258 /// reach one entry check.
3259 ///
3260 /// Self-contained on `&self` — resolves its own dedup `HashSet`
3261 /// through [`SupervisorSpec::children`] rather than borrowing one
3262 /// threaded down from `validate`, the same posture the peer M3
3263 /// mesh-slot per-slot gates ([`crate::AplicacaoSpec::validate_membros`],
3264 /// [`crate::AplicacaoSpec::validate_contratos`],
3265 /// [`crate::AplicacaoSpec::validate_entrada`],
3266 /// [`crate::AplicacaoSpec::validate_placement`]) each carry, so a
3267 /// consumer that reaches this gate directly (without first calling
3268 /// `validate`) still runs the full per-child cascade — pinned by
3269 /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
3270 /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
3271 /// + `validate_children_is_self_contained_on_children_slot`.
3272 ///
3273 /// The three per-entry arms run in the same canonical order the
3274 /// pre-lift inline cascade encoded (DNS-1123 → semver → dedup), so
3275 /// the diagnostic every author-declared per-`:children` entry surfaces
3276 /// through `validate` is byte-equal to the diagnostic this gate
3277 /// surfaces when called directly — the equivalence-pin pair
3278 /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
3279 /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
3280 /// asserts the two altitudes discriminate the same set on every
3281 /// per-entry-covered input.
3282 pub fn validate_children(&self) -> Result<(), SupervisorError> {
3283 let mut seen = std::collections::HashSet::new();
3284 for child in self.children() {
3285 // Every emitted cluster artifact's `metadata.name` for a
3286 // supervised child derives from this `:children :caixa` value
3287 // verbatim — the rendered `wasm.pleme.io/v1alpha1/ComputeUnit
3288 // .metadata.name` per child, the [`crate::LABEL_PROGRAM`]
3289 // label value on every child's pod identity, and the per-
3290 // child K8s [`Service`][svc] `metadata.name` the future
3291 // wasm-operator (M3) provisions for inter-child supervision
3292 // tree wiring. Each apiserver-side schema on each landing
3293 // site enforces the DNS-1123 label rule on admission; a
3294 // structurally invalid child name (`"Worker"`, `"my_worker"`,
3295 // `"team.worker"`, `"-worker"`, `"worker-"`, the >63-byte
3296 // UUID-shaped mistaken-identity slug) silently passes the
3297 // prior empty-/duplicate-only gate and the failure surfaces
3298 // at `kubectl apply` time as a `metadata.name: Invalid value`
3299 // rejection, far from the source caixa.lisp, with no field
3300 // naming the offending `:children` entry. Lifting the gate
3301 // to caixa-build time mirrors the `:membros :caixa` value-
3302 // shape trajectory (3f9d7a0) and the `:placement :clusters`
3303 // trajectory (6cbb900) onto the third DNS-1123-label-shaped
3304 // identifier axis — the supervisor tree's child names —
3305 // through the lifted
3306 // [`crate::render::require_valid_dns_1123_label`] gate the
3307 // seven peer name axes (`:membros :caixa`, `:placement
3308 // :clusters`, `:placement :affinity`, `:contratos :de`/`:para`,
3309 // `:entrada :para`, `:nome`, `:upgrade-from :module`) each
3310 // route through, so drift between the eight axes' accepted
3311 // DNS-1123-label sets is structurally impossible.
3312 //
3313 // [svc]: https://kubernetes.io/docs/concepts/services-networking/service/
3314 crate::render::require_valid_dns_1123_label(
3315 child.nome(),
3316 || SupervisorError::EmptyChildName,
3317 |reason| SupervisorError::child_caixa_invalid(child.nome(), reason),
3318 )?;
3319 // The author surface for `:children :versao` is the same
3320 // Cargo-shaped semver requirement string `:deps :versao` and
3321 // `:membros :versao` carry — and the lacre pipeline resolves
3322 // all three axes through the same
3323 // [`crate::version::parse_requirement`] entry-point. The
3324 // shared [`crate::render::require_valid_versao_requirement`]
3325 // helper brackets the empty-first + parse cascade both peer
3326 // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
3327 // [`crate::AplicacaoSpec::validate_membros`] on `:membros
3328 // :versao`) route through, so drift between the three axes'
3329 // accepted requirement sets is structurally impossible and
3330 // the parse-side no-op the empty-first arm closes (semver's
3331 // empty parse yields an implicit `*`) lives in exactly one
3332 // predicate. Every `ChildSpec::versao` past validate is
3333 // round-trippable through [`crate::parse_requirement`]
3334 // without re-checking at the resolver layer, and the three
3335 // `:versao` typed surfaces (`:deps`, `:membros`, `:children`)
3336 // are now structurally equivalent by construction.
3337 crate::render::require_valid_versao_requirement(
3338 child.versao_requirement(),
3339 || SupervisorError::empty_child_version(child.nome()),
3340 |reason| {
3341 SupervisorError::child_versao_invalid(
3342 child.nome(),
3343 child.versao_requirement(),
3344 reason,
3345 )
3346 },
3347 )?;
3348 crate::render::insert_first_seen(&mut seen, child.nome(), || {
3349 SupervisorError::duplicate_child_caixa(child.nome())
3350 })?;
3351 }
3352 Ok(())
3353 }
3354}
3355
3356/// Cross-slot coherence gate on the supervision tree: no
3357/// `:children :caixa` entry may name the supervisor's own `:nome`.
3358///
3359/// A supervisor that lists itself as a child is a degenerate self-parent
3360/// — the supervision tree is a DAG rooted at the supervisor (OTP child
3361/// specs reference *distinct* child processes; a supervisor is never its
3362/// own child), and the wasm-operator's hierarchical reconciliation would
3363/// otherwise be handed a node that is its own parent: a one-node cycle it
3364/// either rejects far from the source `caixa.lisp` or recurses on. Because
3365/// every `:nome` is a globally-unique substrate identity (DNS-1123 label +
3366/// lacre closure root), a child whose `:caixa` equals the supervisor's
3367/// `:nome` *is* the supervisor itself, not a coincidentally-named peer.
3368///
3369/// Lives outside [`SupervisorSpec::validate`] because the typed view
3370/// carries the children but not the parent `:nome`; mirrors the
3371/// cross-slot precedence gate `validate_upgrade_from_against_versao`
3372/// (which likewise reads one slot against another at the
3373/// [`crate::layout`] wire-up site) and the mesh self-edge gate
3374/// `AplicacaoSpec`'s `ContratoSelfLoop` — the same "an edge from a graph
3375/// node to itself is structurally not a tree/mesh edge" discipline, here
3376/// on the supervision-tree axis.
3377pub fn validate_no_self_supervision(
3378 children: &[ChildSpec],
3379 parent_nome: &str,
3380) -> Result<(), SupervisorError> {
3381 for child in children {
3382 if child.nome() == parent_nome {
3383 return Err(SupervisorError::child_supervises_self(parent_nome));
3384 }
3385 }
3386 Ok(())
3387}
3388
3389#[derive(Debug, Error, PartialEq, Eq)]
3390pub enum SupervisorError {
3391 #[error("supervisor :estrategia {estrategia:?} requires at least one :children entry")]
3392 NoChildren { estrategia: RestartStrategy },
3393 #[error(
3394 "SimpleOneForOne supervisors must declare zero static children (children spawn dynamically)"
3395 )]
3396 SimpleOneForOneWithStaticChildren,
3397 #[error(":max-restarts must be > 0")]
3398 ZeroMaxRestarts,
3399 #[error(
3400 ":supervisor :max-restarts ({max_restarts}) exceeds the supervisor-policy ceiling \
3401 (SUPERVISOR_MAX_RESTARTS_MAX = 1000) — a value above this cap turns the typed \
3402 restart-intensity policy into a no-op supervisor: the escalation threshold is \
3403 structurally so high that no realistic restarts-per-:restart-window traffic shape \
3404 can reach it, so the supervisor never escalates to its parent and a bad child can \
3405 loop inside the window indefinitely. Every typed-slot consumer (Erlang/OTP's \
3406 MaxIntensity/Period ratio, the future wasm-operator's per-supervisor \
3407 restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
3408 materializer's admission webhook) emits a `:max-restarts` declaration that is \
3409 structurally never reached. Pin a value in 1..=1000 (Erlang/OTP / Elixir / Riak \
3410 Core / RabbitMQ production playbooks recommend 3..=100; the OTP `supervisor` \
3411 callback module's `MaxR = 1` minimal-restart default sits at the bottom of the \
3412 band) or restructure the supervision tree (split the flaky child into its own \
3413 sub-supervisor with a tighter budget) if you need a higher restart tolerance."
3414 )]
3415 MaxRestartsExceedsCap { max_restarts: u32 },
3416 #[error(
3417 ":restart-window must be > 0 when set — Erlang/OTP's MaxIntensity/Period \
3418 requires Period > 0; a zero window either trips on the first failure or \
3419 never trips depending on operator interpretation. Omit :restart-window to \
3420 express `never reset`; carry a positive duration to express the window."
3421 )]
3422 RestartWindowZero,
3423 #[error(
3424 ":supervisor :restart-window ({window:?}) carries a sub-millisecond residue the shared `duration_codec` cannot round-trip — \
3425 the codec truncates to `as_millis()` before picking the canonical unit, so a value with `subsec_nanos() % 1_000_000 != 0` either \
3426 truncates on first serialize (e.g. `Duration::from_micros(1500)` → \"1ms\" → `Duration::from_millis(1)` ≠ original) or renders \
3427 as \"0s\" the `RestartWindowZero` arm then rejects on re-validate. Pin an integer-millisecond magnitude in the canonical authoring form \
3428 (`<integer><unit>` for unit ∈ {{ms, s, m, h}}, e.g. `\"500ms\"`, `\"30s\"`, `\"2m\"`, `\"1h\"`) or omit the field for `never reset`"
3429 )]
3430 RestartWindowNotCanonical { window: Duration },
3431 #[error(
3432 ":supervisor :restart-window ({window:?}) exceeds the supervisor-policy ceiling \
3433 (SUPERVISOR_RESTART_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
3434 per-supervisor rolling-window restart-intensity counter into a lifetime counter: the \
3435 failure-counting window is structurally so long that transient restarts are never \
3436 forgotten, the MaxIntensity/Period ratio degenerates from `trip the parent supervisor \
3437 when the child has exceeded its restart budget within the recent window` to `trip the \
3438 parent when the child has exceeded its restart budget over its lifetime`, and the \
3439 supervisor's reset semantic never reaches the child — every typed-slot consumer \
3440 (Erlang/OTP's MaxIntensity/Period reconciler, the future wasm-operator's \
3441 per-supervisor restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
3442 materializer's admission webhook, the caixa-operator's hierarchical reconciliation \
3443 scheduler) emits a `:restart-window` declaration that is structurally a no-op rolling \
3444 window. Pin a value in 1ms..=1h (Learn You Some Erlang's `{{intensity, 5, 60}}` \
3445 worker-supervisor `Period = 60s` default, Elixir's `Supervisor` `max_seconds: 5` \
3446 default, OTP's `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's \
3447 `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default — every Erlang/OTP \
3448 / Elixir production playbook sits in the 5s..=300s band; the longest documented \
3449 per-supervisor restart-window any pleme-io substrate playbook recommends maxes at \
3450 ~30m) or omit :restart-window to express `never reset` (the supervisor's restart \
3451 budget then becomes a strict lifetime counter by design, not a degenerate one — the \
3452 author surfaces the lifetime-counter semantic explicitly at the slot, rather than \
3453 hiding it behind a rolling-window declaration the cap arm rejects)"
3454 )]
3455 RestartWindowExceedsCap { window: Duration },
3456 #[error("child entry has empty :caixa name")]
3457 EmptyChildName,
3458 #[error(
3459 "child :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
3460 (the K8s apiserver enforces this rule on every `metadata.name` / Service \
3461 name / label value the child name lands in — the per-child \
3462 `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name`, the `LABEL_PROGRAM` \
3463 label value, and the future wasm-operator per-child Service `metadata.name` \
3464 — each apiserver-side schema rejects names that don't match; use a \
3465 lowercase alphanumeric + hyphen identifier like `\"worker\"` or `\"cache-v2\"`)"
3466 )]
3467 ChildCaixaInvalid { caixa: String, reason: String },
3468 #[error("child {caixa:?} has empty :versao constraint")]
3469 EmptyChildVersion { caixa: String },
3470 #[error(
3471 "child {caixa:?} :versao {versao:?} is not a valid semver requirement: \
3472 {reason} (use Cargo-shaped forms like `\"^0.1\"`, `\"~0.1.2\"`, \
3473 `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` and \
3474 `:membros :versao` carry; the lacre pipeline resolves all three \
3475 through the same parser)"
3476 )]
3477 ChildVersaoInvalid {
3478 caixa: String,
3479 versao: String,
3480 reason: String,
3481 },
3482 #[error(
3483 "child {caixa:?} appears more than once (Erlang/OTP requires unique \
3484 child_spec.id per supervisor; duplicate children materialize as duplicate \
3485 ComputeUnits in the rendered chart, one silently overwriting the other)"
3486 )]
3487 DuplicateChildCaixa { caixa: String },
3488 #[error(
3489 "supervisor {caixa:?} lists itself as a :children entry — a supervisor is \
3490 never its own child (the supervision tree is a DAG rooted at the supervisor; \
3491 OTP child specs reference distinct child processes). Since every :nome is a \
3492 globally-unique substrate identity, a child naming the supervisor's own :nome \
3493 is a one-node reconciliation cycle, not a coincidentally-named peer; drop the \
3494 self-referential :children entry or rename it to the actual child caixa."
3495 )]
3496 ChildSupervisesSelf { caixa: String },
3497}
3498
3499// Fold the three `SupervisorError::<Variant> { caixa: <&str>.to_string() }`
3500// caixa-only struct-variant wire-up sites at [`SupervisorSpec::validate_children`]
3501// and [`validate_no_self_supervision`] onto one substrate primitive per
3502// typed variant — the sibling on `SupervisorError` of the four uniform-shape
3503// `LayoutError`-envelope constructor families the peer
3504// [`crate::layout::layout_violation_ctors!`] macro closed (131ca0d, 16
3505// variants on `{ caixa, issue }`), the [`crate::layout::layout_slot_kind_ctors!`]
3506// macro closed (0419438, 4 variants on `{ caixa, kind, slots }`), the
3507// [`crate::LayoutError::missing_entry`] one-variant ctor closed (1b09f9d,
3508// on `{ kind, path }`), and the [`crate::layout::layout_nome_only_ctors!`]
3509// macro closed (3fe3dd7, 6 variants on `<Variant>(String)`), plus the
3510// [`crate::AplicacaoError::entrada_host_invalid`] one-variant ctor
3511// (17dd504, `{ host, reason }`), the [`crate::aplicacao::contrato_target_ctors!`]
3512// macro (14b81d5, 2 variants on `{ de, para, wit, expected }`), and the
3513// [`crate::aplicacao::contrato_empty_pair_ctors!`] macro (8580068, 4
3514// variants on `{ de, para }`) already at that discipline on the peer
3515// `AplicacaoError` envelopes.
3516//
3517// Each of the three wire-up sites on this shape (`EmptyChildVersion` at
3518// the per-`:children` semver-requirement empty-first arm, `DuplicateChildCaixa`
3519// at the per-`:children` dedup arm, `ChildSupervisesSelf` at the cross-slot
3520// self-supervision arm) opened the identical
3521// `SupervisorError::<Variant> { caixa: <&str>.to_string() }` struct-literal —
3522// the exact "same block re-inlined at every consumer" shape the PRIME
3523// DIRECTIVE names as a bug, on the same altitude the peer `LayoutError` /
3524// `AplicacaoError` families each closed on their sibling envelopes. The
3525// three variants share one `{ caixa: String }` shape, so the fold routes
3526// each wire-up site through one dispatch per typed variant.
3527//
3528// The macro below generates one static constructor per variant of shape
3529// `fn <slot>(caixa: &str) -> SupervisorError`, so every wire-up site
3530// collapses onto one dispatch:
3531// `SupervisorError::<slot>(<&str>)`, byte-equal to the pre-lift
3532// struct-literal on the same `&str` fixture. The uniform one-field
3533// construction (`caixa: caixa.to_string()`) is spelled once — inside the
3534// macro — rather than at every wire-up site. Every constructor is
3535// `#[must_use]` so a caller who mistakenly discards the constructed error
3536// trips a compile warning at the wire-up site.
3537//
3538// Every future consumer that wants to construct one of these three
3539// variants outside `SupervisorSpec::validate_children` /
3540// `validate_no_self_supervision` — a deferred
3541// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3542// webhook re-checking one added/renamed child, a future
3543// `feira validate --supervisor` per-caixa admission verb, a per-child
3544// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path
3545// once dynamic-children graduate to a typed slot, a per-Supervisor
3546// overlay resolver rejecting a duplicate/self-supervising child against
3547// a cluster-local snapshot — now reaches each variant through one call
3548// rather than re-inlining the three-line struct-literal in lockstep
3549// with the three in-crate wire-up sites.
3550macro_rules! supervisor_caixa_only_ctors {
3551 ($($ctor:ident => $variant:ident),* $(,)?) => {
3552 impl SupervisorError {
3553 $(
3554 #[doc = concat!(
3555 "Construct a [`SupervisorError::",
3556 stringify!($variant),
3557 "`] naming the offending `:children :caixa` (or ",
3558 "supervisor `:nome`, on the self-supervision arm). ",
3559 "Folds the uniform `Self::",
3560 stringify!($variant),
3561 " { caixa: caixa.to_string() }` one-field ",
3562 "struct-literal onto one substrate primitive so ",
3563 "every [`SupervisorSpec::validate_children`] / ",
3564 "[`validate_no_self_supervision`] wire-up on this ",
3565 "variant reads through one dispatch rather than the ",
3566 "pre-lift open-coded struct-literal block."
3567 )]
3568 #[must_use]
3569 pub fn $ctor(caixa: &str) -> Self {
3570 Self::$variant { caixa: caixa.to_string() }
3571 }
3572 )*
3573 }
3574 };
3575}
3576
3577supervisor_caixa_only_ctors! {
3578 empty_child_version => EmptyChildVersion,
3579 duplicate_child_caixa => DuplicateChildCaixa,
3580 child_supervises_self => ChildSupervisesSelf,
3581}
3582
3583// Fold the two `SupervisorError::{ChildCaixaInvalid, ChildVersaoInvalid}`
3584// struct-variant wire-up sites at [`SupervisorSpec::validate_children`] onto
3585// one substrate primitive per typed variant — the M2 supervisor-side siblings
3586// of the peer [`crate::AplicacaoError::membro_caixa_invalid`] two-slot ctor
3587// already lifted through the sibling
3588// [`crate::aplicacao::aplicacao_field_reason_ctors!`] macro (981060b) on the
3589// peer `AplicacaoError { caixa: String, reason: String }` envelope. The
3590// `ChildCaixaInvalid` variant carries the same `{ <name>: String, reason:
3591// String }` two-slot shape the peer seven-variant
3592// [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold closed on the
3593// `AplicacaoError` envelope (`MembroCaixaInvalid`, `EntradaParaInvalid`,
3594// `EntradaHostInvalid`, `EntradaPathInvalid`, `PlacementClusterInvalid`,
3595// `PlacementAffinityInvalid`, `ShardKeyInvalid`); the `ChildVersaoInvalid`
3596// variant carries the `{ caixa: String, versao: String, reason: String }`
3597// three-slot shape the sibling `AplicacaoError::MembroVersaoInvalid` axis
3598// carries on the same `:versao` value-shape.
3599//
3600// Each of the two wire-up sites opened the same closure-shaped
3601// `|reason| SupervisorError::<Variant> { caixa: child.nome().to_string(),
3602// [versao: child.versao_requirement().to_string(),] reason }` block inside
3603// the paired [`crate::render::require_valid_dns_1123_label`] and
3604// [`crate::render::require_valid_versao_requirement`] callbacks — the exact
3605// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE names
3606// as a bug, on the same altitude the peer `AplicacaoError` /
3607// `SupervisorError` / `LayoutError` / `DepError` / `LimitsError` ctor
3608// families already closed on their sibling envelopes.
3609//
3610// The two `#[must_use]` inherent constructors below fold each wire-up onto
3611// one dispatch: `SupervisorError::child_caixa_invalid(<name>, <reason>)`
3612// and `SupervisorError::child_versao_invalid(<name>, <versao>, <reason>)`,
3613// byte-equal to the pre-lift struct-literal on the same scalar fixtures.
3614// The uniform per-field `.to_string()` / `.into()` construction is spelled
3615// once — inside each ctor body — rather than at every wire-up site. The
3616// `reason: impl Into<String>` bound accepts both `&str` literals and
3617// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
3618// diagnostic shape at the lift, matching the peer
3619// [`aplicacao_field_reason_ctors!`] and
3620// [`crate::aplicacao::contrato_pair_value_reason_ctors!`] bounds on the
3621// sibling envelopes.
3622//
3623// Every future consumer that wants to construct one of these two variants
3624// outside `SupervisorSpec::validate_children` — a deferred
3625// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook
3626// re-checking one added/renamed child's `:caixa` or `:versao`, a future
3627// `feira validate --supervisor` per-caixa admission verb, a per-child
3628// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path once
3629// dynamic-children graduate to a typed slot, a per-Supervisor overlay
3630// resolver rejecting a shape-invalid child `:caixa`/`:versao` against a
3631// cluster-local snapshot — now reaches each variant through one call rather
3632// than re-inlining the per-shape struct-literal block in lockstep with the
3633// two in-crate wire-up sites.
3634impl SupervisorError {
3635 /// Construct a [`SupervisorError::ChildCaixaInvalid`] naming the
3636 /// offending `:children :caixa` value under the given `reason`. Folds
3637 /// the uniform `Self::ChildCaixaInvalid { caixa: caixa.to_string(),
3638 /// reason: reason.into() }` two-slot struct-literal onto one substrate
3639 /// primitive so every wire-up on this variant reads through one
3640 /// dispatch, matching the peer
3641 /// [`crate::AplicacaoError::membro_caixa_invalid`] ctor's shape on the
3642 /// sibling `AplicacaoError { caixa: String, reason: String }`
3643 /// envelope. `reason` accepts both `&str` literals and `format!(…)`
3644 /// outputs through the `impl Into<String>` bound.
3645 #[must_use]
3646 pub fn child_caixa_invalid(caixa: &str, reason: impl Into<String>) -> Self {
3647 Self::ChildCaixaInvalid {
3648 caixa: caixa.to_string(),
3649 reason: reason.into(),
3650 }
3651 }
3652
3653 /// Construct a [`SupervisorError::ChildVersaoInvalid`] naming the
3654 /// offending `:children :caixa` and its `:versao` requirement under
3655 /// the given `reason`. Folds the uniform `Self::ChildVersaoInvalid {
3656 /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
3657 /// reason.into() }` three-slot struct-literal onto one substrate
3658 /// primitive so every wire-up on this variant reads through one
3659 /// dispatch, matching the sibling `AplicacaoError::MembroVersaoInvalid
3660 /// { caixa, versao, reason }` three-slot axis on the peer
3661 /// `AplicacaoError` envelope. `reason` accepts both `&str` literals
3662 /// and `format!(…)` outputs through the `impl Into<String>` bound.
3663 #[must_use]
3664 pub fn child_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
3665 Self::ChildVersaoInvalid {
3666 caixa: caixa.to_string(),
3667 versao: versao.to_string(),
3668 reason: reason.into(),
3669 }
3670 }
3671}
3672
3673// Fold the four `SupervisorError::<Variant> { <field>: <Copy> }` one-field
3674// Copy-scalar struct-variant wire-up sites at [`SupervisorSpec::validate`]'s
3675// three bracket-arms — one struct-literal at the `:children`-empty
3676// non-`SimpleOneForOne` refusal cascade (`NoChildren { estrategia }`) plus
3677// three `impl FnOnce(<ty>) -> SupervisorError` bracket-closures at the
3678// [`crate::render::require_positive_bounded_u32`] `:max-restarts` cap arm
3679// (`MaxRestartsExceedsCap { max_restarts }`) and the paired
3680// [`crate::render::require_positive_canonical_bounded_duration`]
3681// `:restart-window` canonical-form + cap arms (`RestartWindowNotCanonical
3682// { window }`, `RestartWindowExceedsCap { window }`) — onto one substrate
3683// primitive per typed variant, matching the sibling
3684// [`crate::aplicacao::aplicacao_policy_scalar_ctors!`] macro (7ef425e, 8
3685// variants on the same `{ <field>: Duration | u32 }` shape) at that
3686// discipline on the peer `AplicacaoError` envelope's per-`:politicas`
3687// scalar axis. Every variant is a one-field `Copy`-pass-through struct-
3688// literal — `RestartStrategy | u32 | Duration` — so the fold routes each
3689// wire-up site through one dispatch per typed variant without a runtime-
3690// work delta.
3691//
3692// Each of the four wire-up sites opened the identical
3693// `SupervisorError::<Variant> { <field>: <val> }` struct-literal — the
3694// exact "same block re-inlined at every consumer" shape the PRIME
3695// DIRECTIVE names as a bug, on the same altitude the peer
3696// `aplicacao_policy_scalar_ctors!` fold closed on the sibling
3697// `AplicacaoError` envelope's per-`:politicas` per-axis cap / canonical-
3698// form arms. The four variants share one `{ <field>: <Copy> }` shape, so
3699// the fold routes each wire-up site through one dispatch per typed
3700// variant.
3701//
3702// The macro below generates one static constructor per variant of shape
3703// `const fn <ctor>(<field>: <ty>) -> SupervisorError`, so every wire-up
3704// site collapses onto one dispatch: `SupervisorError::<ctor>(<val>)`,
3705// byte-equal to the pre-lift struct-literal on the same `Copy`-`<ty>`
3706// fixture — as a direct call at the [`SupervisorSpec::validate`]
3707// `:children`-empty refusal, or as a bare function pointer in the
3708// `impl FnOnce(<ty>) -> SupervisorError` bracket-closure slot every
3709// [`crate::render::require_positive_bounded_u32`] /
3710// [`crate::render::require_positive_canonical_bounded_duration`] gate
3711// carries — rather than the pre-lift open-coded one-line closure over
3712// the same one-field struct-literal. `const fn` preserves the `Copy`-
3713// pass-through's zero-runtime-work property verbatim. Every constructor
3714// is `#[must_use]` so a caller who mistakenly discards the constructed
3715// error trips a compile warning at the wire-up site.
3716//
3717// Every future consumer that wants to construct one of these four
3718// variants outside `SupervisorSpec::validate` — a deferred
3719// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3720// webhook re-checking one edited `:estrategia` / `:max-restarts` /
3721// `:restart-window` slot against the cap + canonical-form cascade, a
3722// future `feira validate --supervisor` per-caixa admission verb re-
3723// running the shape gates on demand, a per-Supervisor overlay resolver
3724// rejecting an author-supplied slot against a cluster-local snapshot —
3725// now reaches each variant through one call rather than re-inlining the
3726// per-shape struct-literal block in lockstep with the four in-crate
3727// wire-up sites.
3728macro_rules! supervisor_scalar_ctors {
3729 ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
3730 impl SupervisorError {
3731 $(
3732 #[doc = concat!(
3733 "Construct a [`SupervisorError::",
3734 stringify!($variant),
3735 "`] naming the offending per-`:supervisor` `",
3736 stringify!($field),
3737 "` scalar. Folds the uniform `Self::",
3738 stringify!($variant),
3739 " { ",
3740 stringify!($field),
3741 " }` one-field `Copy`-pass-through struct-literal onto ",
3742 "one substrate primitive so every per-axis wire-up on ",
3743 "this variant reads through one dispatch — as a direct ",
3744 "call (`SupervisorError::",
3745 stringify!($ctor),
3746 "(<val>)`, byte-equal to the pre-lift struct-literal on ",
3747 "the same `Copy`-`",
3748 stringify!($ty),
3749 "` fixture) or as a bare function pointer in the ",
3750 "`impl FnOnce(",
3751 stringify!($ty),
3752 ") -> SupervisorError` bracket-closure slot every ",
3753 "`crate::render::require_positive_bounded_*` / ",
3754 "`crate::render::require_positive_canonical_bounded_*` ",
3755 "gate carries — rather than the pre-lift open-coded ",
3756 "one-line closure over the same one-field struct-",
3757 "literal. `const fn` preserves the `Copy`-pass-through's ",
3758 "zero-runtime-work property verbatim."
3759 )]
3760 #[must_use]
3761 pub const fn $ctor($field: $ty) -> Self {
3762 Self::$variant { $field }
3763 }
3764 )*
3765 }
3766 };
3767}
3768
3769supervisor_scalar_ctors! {
3770 no_children => NoChildren { estrategia: RestartStrategy },
3771 max_restarts_exceeds_cap => MaxRestartsExceedsCap { max_restarts: u32 },
3772 restart_window_not_canonical => RestartWindowNotCanonical { window: Duration },
3773 restart_window_exceeds_cap => RestartWindowExceedsCap { window: Duration },
3774}
3775
3776/// Shared duration string codec for the typed slots that take a
3777/// duration (`restart_window`, `MeshPolicy::timeout`,
3778/// `CircuitBreaker::window`, …). Public so [`crate::aplicacao`] can
3779/// reuse it without duplicating the parser.
3780pub mod duration_codec {
3781 use super::Duration;
3782 use serde::{Deserializer, Serializer};
3783
3784 pub fn serialize<S: Serializer>(v: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
3785 // Route through the canonical [`crate::render::serialize_option_via_str`]
3786 // — the substrate-side single-owner primitive for the forward
3787 // arm of the typed-magnitude codec family. See its docstring
3788 // for the full sibling roster.
3789 crate::render::serialize_option_via_str(v, s, render)
3790 }
3791
3792 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
3793 // Route through the canonical [`crate::render::deserialize_option_via_str`]
3794 // — the substrate-side single-owner primitive for the reverse
3795 // arm of the typed-magnitude codec family. See its docstring
3796 // for the full sibling roster.
3797 crate::render::deserialize_option_via_str(d, parse)
3798 }
3799
3800 pub(crate) fn parse(s: &str) -> Result<Duration, String> {
3801 // Paired whitespace-rejection arm — same canonical-form
3802 // render-determinism discipline as the peer
3803 // `limits::parse_byte_size` / `limits::parse_duration` /
3804 // `limits::parse_millicores` /
3805 // `aplicacao::rate_limit_codec::parse` sites: the ASCII
3806 // byte-scan closes the WhatWG-conformant whitespace bytes
3807 // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
3808 // `char::is_whitespace` scan closes the strictly-complementary
3809 // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
3810 // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
3811 // codepoints) that `str::trim` at parse entry silently strips.
3812 // Either drift class would round-trip through `render` to a
3813 // *different* canonical form on next emit — breaking the
3814 // THEORY.md Part V render-determinism contract on three typed-
3815 // duration slots at once (`:supervisor :restart-window`,
3816 // `:politicas :timeout`, `:politicas :circuit-breaker :window`)
3817 // via the shared codec.
3818 //
3819 // Routed through the lifted [`crate::render::reject_whitespace`]
3820 // primitive — the substrate-side single-owner paired-arm gate
3821 // every typed-magnitude codec in caixa-core shares.
3822 crate::render::reject_whitespace::<String, _, _>(
3823 s,
3824 |b| {
3825 format!(
3826 "duration: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
3827 authoring form for the typed duration slots routed through this shared codec \
3828 (`:supervisor :restart-window`, `:politicas :timeout`, \
3829 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
3830 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no whitespace bytes \
3831 anywhere. A whitespace-carrying shape (`\" 30s\"`, `\"30s \"`, `\"30 s\"`, \
3832 `\"\\t30s\"`, `\"30s\\n\"`) round-trips through `render` to a *different* \
3833 canonical form (`\"30s\"`) on first serialize — breaking the THEORY.md \
3834 Part V render-determinism contract every typed slot carries. Strip every \
3835 whitespace byte (write `\"30s\"` verbatim)"
3836 )
3837 },
3838 |ch| {
3839 format!(
3840 "duration: value {s:?} contains non-ASCII Unicode whitespace character \
3841 {ch:?} (U+{cp:04X}) — the canonical authoring form for the typed \
3842 duration slots routed through this shared codec (`:supervisor \
3843 :restart-window`, `:politicas :timeout`, `:politicas :circuit-breaker \
3844 :window`) is `<integer><unit>` (e.g. `\"30s\"`, `\"500ms\"`, `\"2m\"`, \
3845 `\"1h\"`) with no whitespace characters anywhere (ASCII or Unicode). A \
3846 non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}30s\"`, \
3847 `\"30s\\u{{2028}}\"`, `\"30\\u{{2003}}s\"`) survives the ASCII byte-scan \
3848 but `str::trim` (which uses `char::is_whitespace` — the Unicode \
3849 `White_Space` property, strictly wider than the ASCII byte set) silently \
3850 strips it at parse entry, and the value round-trips through `render` to \
3851 a *different* canonical form (`\"30s\"`) on first serialize — breaking \
3852 the THEORY.md Part V render-determinism contract every typed slot \
3853 carries. Strip every non-ASCII whitespace character (write `\"30s\"` \
3854 verbatim with only ASCII bytes)",
3855 cp = ch as u32
3856 )
3857 },
3858 )?;
3859 let s = s.trim();
3860 // Routed through the lifted
3861 // [`crate::render::split_magnitude_and_alpha_unit`] primitive —
3862 // the single-owner split every ASCII-alphabetic-unit typed-
3863 // magnitude codec in caixa-core (`limits::parse_byte_size` /
3864 // `limits::parse_duration` / this shared duration codec) shares.
3865 // See its docstring for the full sibling roster on the same
3866 // primitive altitude.
3867 let (num_part, unit) = crate::render::split_magnitude_and_alpha_unit(s);
3868 let num_trim = num_part.trim();
3869 // The canonical authoring form for every typed slot routed
3870 // through this shared codec — `:supervisor :restart-window`,
3871 // `:politicas :timeout`, `:politicas :circuit-breaker :window`
3872 // — is `<integer><unit>`. Every magnitude [`render`] emits is a
3873 // non-negative integer with no decimal point and no leading
3874 // sign, so the parser's accepted set must match for
3875 // serialize/deserialize to round-trip without canonical-form
3876 // drift. Until this gate landed the parser accepted any
3877 // `f64`-shaped magnitude (`"1.5s"` → 1500ms, `"1.0s"` → 1s,
3878 // `"0.5m"` → 30s, `"+30s"` → 30s) and serde silently round-
3879 // tripped the value to a *different* canonical string on the
3880 // next emit (`"1.5s"` → 1500ms → `"1500ms"`, `"1.0s"` → 1s →
3881 // `"1s"`, `"0.5m"` → 30s → `"30s"`, `"+30s"` → 30s → `"30s"`)
3882 // — breaking the THEORY.md Part V render-determinism contract
3883 // on three typed slots at once. Same canonical-form discipline
3884 // `crate::limits::parse_duration` (818dd38, the immediate
3885 // predecessor on the peer `:limits :wall-clock` codec) applies;
3886 // this gate lifts the discipline onto the shared codec that
3887 // backs the remaining three typed-duration slots in caixa-core.
3888 //
3889 // Strict canonical form: every byte of the magnitude is an
3890 // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
3891 // inputs the gate distinguishes "non-canonical-but-numeric"
3892 // (parses as f64 or i64 — surfaced with a self-locating
3893 // diagnostic naming the canonical authoring form, the
3894 // round-trip drift each rejected shape would produce on first
3895 // serialize, and the canonical-form remediation) from
3896 // "garbage" (parses as neither — surfaced with the existing
3897 // narrower "bad duration magnitude" wording so its diagnostic
3898 // shape remains stable for the parser-shape footgun case).
3899 // The pre-existing `num < 0.0` arm is now unreachable — the
3900 // digit-only gate strictly precedes magnitude parsing, and a
3901 // leading `-` is not an ASCII digit, so `"-30s"` lands on the
3902 // non-canonical-but-numeric branch with the `-30` named
3903 // verbatim in the diagnostic rather than the prior
3904 // value-laundered "negative duration in \"-30s\"" wording.
3905 //
3906 // Routed through the lifted
3907 // [`crate::render::is_digit_only_magnitude`] predicate — the
3908 // same source of truth the four peer typed-magnitude codec
3909 // sites share.
3910 let digit_only = crate::render::is_digit_only_magnitude(num_trim);
3911 if !digit_only {
3912 let numeric = num_trim.parse::<f64>().is_ok() || num_trim.parse::<i64>().is_ok();
3913 if numeric {
3914 return Err(format!(
3915 "duration: magnitude {num_trim:?} is not a non-negative integer — the \
3916 canonical authoring form for the typed duration slots routed through \
3917 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
3918 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
3919 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no decimal point and \
3920 no leading `+` / `-` sign. A fractional / decimal-shaped magnitude \
3921 (`\"1.5s\"`, `\"1.0s\"`, `\"0.5m\"`, `\"+30s\"`, `\"-30s\"`) round-trips \
3922 through `render` to a *different* canonical form (`\"1500ms\"`, `\"1s\"`, \
3923 `\"30s\"`, `\"30s\"`, `\"30s\"`) on first serialize — breaking the \
3924 THEORY.md Part V render-determinism contract every typed slot carries. \
3925 Pick an integer magnitude in the unit that divides cleanly (write \
3926 `\"1500ms\"` instead of `\"1.5s\"`; `\"30s\"` instead of `\"0.5m\"`)"
3927 ));
3928 }
3929 return Err(format!("bad duration magnitude in {s:?}"));
3930 }
3931 // Leading-zero arm — peer with the `rate_limit_codec` leading-
3932 // zero arm (4f46830) on the same canonical-form render-
3933 // determinism axis. The digit-only gate accepts `"030s"`,
3934 // `"00s"`, `"01h"`, `"0500ms"` as `u64::from_str` parses them
3935 // losslessly (= 30, 0, 1, 500), but `render` emits the leading-
3936 // zero-stripped form (`"30s"`, `"0s"`, `"1h"`, `"500ms"`) — a
3937 // *different* canonical string on the next emit, breaking the
3938 // THEORY.md Part V render-determinism contract the same way
3939 // `"+30s"` did before the leading-`+` arm landed. The single-
3940 // byte magnitude `"0"` (or `"0s"` / `"0ms"`) round-trips
3941 // losslessly through `render` (`render(Duration::ZERO)` emits
3942 // `"0s"`) — the downstream semantic-zero gates (e.g.
3943 // `SupervisorError::ZeroRestartWindow` on
3944 // `:supervisor :restart-window`,
3945 // `AplicacaoError::PolicyTimeoutZero` /
3946 // `PolicyCircuitBreakerWindowZero` on the typed `:politicas`
3947 // duration slots) refuse zero-magnitude authoring at the typed-
3948 // validate layer above, so the single-byte `"0"` stays in the
3949 // accepted set at this codec layer and the diagnostic
3950 // partitioning between canonical-form drift (this arm) and
3951 // semantic-zero (the downstream gates) remains stable.
3952 // Peer with the future leading-zero arms on the two remaining
3953 // typed-magnitude codecs the trajectory acknowledges:
3954 // `limits::parse_duration` backing `:limits :wall-clock`,
3955 // `limits::parse_byte_size` backing `:limits :memory` — each
3956 // carries the same canonical-form-drift class today; this
3957 // gate lands the discipline on the shared duration codec
3958 // first because the `rate_limit_codec` predecessor on the
3959 // same canonical-form-drift axis is the closest peer on the
3960 // trajectory.
3961 //
3962 // Routed through the lifted
3963 // [`crate::render::is_leading_zero_padded_magnitude`]
3964 // predicate — the same source of truth the four peer
3965 // typed-magnitude codec sites share.
3966 if crate::render::is_leading_zero_padded_magnitude(num_trim) {
3967 return Err(format!(
3968 "duration: magnitude {num_trim:?} has a non-canonical leading zero — the \
3969 canonical authoring form for the typed duration slots routed through \
3970 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
3971 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
3972 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no leading-zero padding \
3973 on the magnitude. A leading-zero magnitude (`\"030s\"`, `\"00s\"`, \
3974 `\"01h\"`, `\"0500ms\"`) round-trips through `render` to a *different* \
3975 canonical form (`\"30s\"`, `\"0s\"`, `\"1h\"`, `\"500ms\"`) on first \
3976 serialize — breaking the THEORY.md Part V render-determinism contract \
3977 every typed slot carries. Strip the leading zeros (write \
3978 `\"30s\"` instead of `\"030s\"`)"
3979 ));
3980 }
3981 // The digit-only gate guarantees every byte is `[0-9]`, and
3982 // the leading-zero arm above guarantees the magnitude is
3983 // either the single byte `"0"` or starts with `[1-9]`, so
3984 // the only way `u64::from_str` can fail here is overflow (the
3985 // magnitude exceeds `u64::MAX`). Surface that with an
3986 // overflow-shaped wording so the diagnostic names the offending
3987 // magnitude verbatim rather than collapsing onto the
3988 // non-canonical arm. The codec now operates on `u64` end-to-end
3989 // — every accepted magnitude is integer-exact; no f64 mantissa
3990 // drift between author-supplied magnitude and the consumer's
3991 // `Duration` value. Same shape `crate::limits::parse_duration`
3992 // (818dd38) carries on the peer `:limits :wall-clock` axis.
3993 let num: u64 = num_trim.parse::<u64>().map_err(|_| {
3994 format!("bad duration magnitude in {s:?} (digit-only magnitude overflows u64)")
3995 })?;
3996 // Route the `{"ms" | "s" | "" | "m" | "h"} → Duration`
3997 // unit-arm dispatch through the canonical
3998 // [`crate::render::duration_from_integer_magnitude_and_unit`]
3999 // primitive — the substrate-side single-owner unit-dispatch
4000 // table every typed-duration codec in caixa-core routes
4001 // through (peer: `crate::limits::parse_duration` backing
4002 // `:limits :wall-clock`). Every unit conversion is integer-
4003 // exact for an integer magnitude; overflow surfaces via the
4004 // typed `DurationUnitError::Overflow { multiplier }`
4005 // discriminant so this arm reconstructs the pre-lift
4006 // `"duration <num><unit> overflows u64 (magnitude × 60 …)"`
4007 // wording verbatim from `num` / `unit_trim` / the returned
4008 // `multiplier`, and the unknown-unit arm reconstructs the
4009 // pre-lift `"unknown duration unit \"<other>\""` wording from
4010 // the caller-scoped `unit_trim`. Load-bearing pinned by
4011 // `crate::render::tests::duration_from_integer_magnitude_and_unit_matches_pre_lift_unit_dispatch_table`.
4012 let unit_trim = unit.trim();
4013 let dur = crate::render::duration_from_integer_magnitude_and_unit(num, unit_trim).map_err(
4014 |e| match e {
4015 crate::render::DurationUnitError::Overflow { multiplier } => format!(
4016 "duration {num}{unit_trim} overflows u64 (magnitude × {multiplier} > 2^64-1)"
4017 ),
4018 crate::render::DurationUnitError::UnknownUnit => {
4019 format!("unknown duration unit {unit_trim:?}")
4020 }
4021 },
4022 )?;
4023 Ok(dur)
4024 }
4025
4026 /// Render a [`Duration`] in the canonical pleme-io duration string
4027 /// form (`"30s"`, `"1m"`, `"1h"`, `"500ms"`). The same form every
4028 /// caixa typed-duration slot serializes to and the same form K8s
4029 /// Gateway API HTTPRoute `timeouts` / `backendRequest` and Cilium
4030 /// EnvoyConfig per-route timeouts both expect (an integer
4031 /// followed by `s`/`m`/`h`/`ms`, no fractional values, no leading
4032 /// `+`). Lifted to `pub` so caixa-side renderers
4033 /// (`caixa-mesh::gateway_routes`'s :politicas :timeout overlay,
4034 /// the future per-:politicas `CiliumClusterwideEnvoyConfig`
4035 /// emitter, the future caixa-otel collector pipeline emitter) can
4036 /// consume the same canonical formatter without re-inlining the
4037 /// magnitude/unit decision tree (and inheriting the same drift
4038 /// footguns: a subtly different `300ms` vs `0.3s` rendering breaks
4039 /// downstream apply-time parsing in non-obvious ways).
4040 pub fn render(d: Duration) -> String {
4041 let total_ms = d.as_millis();
4042 if total_ms == 0 {
4043 return "0s".into();
4044 }
4045 if total_ms.is_multiple_of(3600 * 1000) {
4046 return format!("{}h", total_ms / (3600 * 1000));
4047 }
4048 if total_ms.is_multiple_of(60 * 1000) {
4049 return format!("{}m", total_ms / (60 * 1000));
4050 }
4051 if total_ms.is_multiple_of(1000) {
4052 return format!("{}s", total_ms / 1000);
4053 }
4054 format!("{total_ms}ms")
4055 }
4056
4057 /// True iff `d` round-trips losslessly through [`render`] + [`parse`].
4058 ///
4059 /// [`render`] truncates a `Duration` to `as_millis()` before picking the
4060 /// largest divisor unit, so any sub-millisecond residue
4061 /// (`d.subsec_nanos() % 1_000_000 != 0`) silently breaks the THEORY.md
4062 /// §V.2.7 render-determinism contract:
4063 ///
4064 /// - `Duration::from_micros(1500)` (= `1_500_000` ns) → `as_millis() == 1`
4065 /// → renders `"1ms"` → parses back to `Duration::from_millis(1)` =
4066 /// `1_000_000` ns ≠ original `1_500_000` ns;
4067 /// - `Duration::from_nanos(1)` (= 1 ns) → `as_millis() == 0` →
4068 /// renders the literal `"0s"`, which the per-axis zero-floor gate
4069 /// on every typed-`Duration` slot then rejects on re-validate.
4070 ///
4071 /// Lifted to a `pub` predicate next to the [`render`] / [`parse`] pair so
4072 /// the codec's round-trippable accepted set lives in exactly one place —
4073 /// every typed-`Duration` slot that routes through this shared codec
4074 /// (`SupervisorSpec::restart_window` via [`super::duration_codec`],
4075 /// [`crate::MeshPolicy::timeout`] / [`crate::CircuitBreaker::window`] via
4076 /// `supervisor::duration_codec` + [`super::duration_codec_required`]) and
4077 /// every typed-`Duration` slot whose own codec shares the same
4078 /// `as_millis()`-truncation shape ([`crate::LimitsSpec::wall_clock`] via
4079 /// [`crate::limits`]'s in-module `parse_duration` / `render_duration`
4080 /// pair) calls this predicate from its `validate()` to bracket the
4081 /// accepted set against the codec's accepted set, structurally. Drift
4082 /// between the codec's granularity and any typed slot's accepted set is
4083 /// then a single-source-of-truth edit at this predicate rather than a
4084 /// silent round-trip break the next consumer discovers at apply time.
4085 ///
4086 /// Peer of [`crate::aplicacao::POLICY_RETRIES_MAX`] /
4087 /// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] and the
4088 /// `is_dns_1123_label` / `is_canonical_rate_limit_window` predicate
4089 /// family — same "typed-slot's valid set matches its codec's accepted
4090 /// set, structurally" discipline carried at the codec layer.
4091 #[must_use]
4092 pub fn is_integer_millisecond_duration(d: Duration) -> bool {
4093 d.subsec_nanos().is_multiple_of(1_000_000)
4094 }
4095}
4096
4097/// Required-Duration variant for fields that aren't Option<Duration>.
4098pub mod duration_codec_required {
4099 use super::Duration;
4100 use serde::{Deserialize, Deserializer, Serializer};
4101
4102 pub fn serialize<S: Serializer>(v: &Duration, s: S) -> Result<S::Ok, S::Error> {
4103 s.serialize_str(&super::duration_codec::render(*v))
4104 }
4105
4106 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
4107 let s = String::deserialize(d)?;
4108 super::duration_codec::parse(&s).map_err(serde::de::Error::custom)
4109 }
4110}
4111
4112#[cfg(test)]
4113mod tests {
4114 use super::*;
4115
4116 fn child(name: &str, ver: &str, restart: RestartPolicy) -> ChildSpec {
4117 ChildSpec {
4118 caixa: name.into(),
4119 versao: ver.into(),
4120 restart,
4121 }
4122 }
4123
4124 #[test]
4125 fn child_spec_string_scalar_accessor_pair_is_const_fn() {
4126 // Fail-before-pass-after pin on [`ChildSpec::nome`] +
4127 // [`ChildSpec::versao_requirement`]'s `const`-eval-surface
4128 // posture. Each accessor projects the per-`:children :caixa`
4129 // / per-`:children :versao` [`String`] storage through the
4130 // `pub const fn` [`String::as_str`] (const-stable since Rust
4131 // 1.87, well within the workspace MSRV) — any future
4132 // accidental downgrade to non-`const` fails the corresponding
4133 // `<name>_via_const_fn` wrapper at caixa-core build time with
4134 // E0015 (`cannot call non-const method`), strictly stronger
4135 // than a runtime `assert!`. Sibling of the peer
4136 // per-M2/M3/universal-axis `String → &str` scalar-accessor
4137 // family pins on the sibling `const`-eval-surface passes
4138 // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
4139 // top-level manifest, [`crate::CaixaVersion::as_str`] at the
4140 // typed-newtype wrapper, [`crate::aplicacao::Membro::nome`] /
4141 // [`crate::aplicacao::Membro::versao_requirement`] at the M3
4142 // membership axis, [`crate::aplicacao::Entrada::hostname`] /
4143 // [`crate::aplicacao::Entrada::destination`] at the M3
4144 // ingress axis,
4145 // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
4146 // M2 upgrade axis, [`crate::dep::Dep::nome`] /
4147 // [`crate::dep::Dep::versao_requirement`] at the dep-graph
4148 // axis, and the per-`:contratos`
4149 // [`crate::aplicacao::WitContract::source`] /
4150 // [`crate::aplicacao::WitContract::destination`] /
4151 // [`crate::aplicacao::WitContract::world_ref`] trio the
4152 // sibling pin at 279823b already anchors).
4153 const fn nome_via_const_fn(c: &ChildSpec) -> &str {
4154 c.nome()
4155 }
4156 const fn versao_via_const_fn(c: &ChildSpec) -> &str {
4157 c.versao_requirement()
4158 }
4159 for (caixa, versao) in [
4160 ("worker-a", "^0.1"),
4161 ("worker-b", "~0.2.3"),
4162 ("collector", "*"),
4163 ] {
4164 let c = child(caixa, versao, RestartPolicy::Permanent);
4165 assert_eq!(nome_via_const_fn(&c), c.nome());
4166 assert_eq!(versao_via_const_fn(&c), c.versao_requirement());
4167 assert_eq!(c.nome(), caixa);
4168 assert_eq!(c.versao_requirement(), versao);
4169 }
4170 }
4171
4172 #[test]
4173 fn supervisor_children_slice_return_accessor_is_const_fn() {
4174 // Fail-before-pass-after pin on [`SupervisorSpec::children`]'s
4175 // `const`-eval-surface posture. The accessor destructures the
4176 // per-`:children` `Vec<ChildSpec>` storage through the
4177 // `pub const fn` [`Vec::as_slice`] (const-stable since Rust
4178 // 1.66, well within the workspace MSRV) — any future
4179 // accidental downgrade to non-`const` fails
4180 // `children_via_const_fn` at caixa-core build time with E0015
4181 // (`cannot call non-const method`), strictly stronger than a
4182 // runtime `assert!`. Sibling of the peer per-M3-mesh-slot
4183 // `Vec → &[T]` slice-return accessor family pin
4184 // [`crate::aplicacao::tests::m3_reference_return_accessor_family_is_const_fn`]
4185 // on the M3 mesh-slot per-`:clusters` / per-`:paths` /
4186 // per-`:membros` / per-`:contratos` slice-return axes, and of
4187 // the peer M2 upgrade-appup axis pin
4188 // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
4189 // on the per-`:upgrade-from :instructions` slice-return axis.
4190 const fn children_via_const_fn(s: &SupervisorSpec) -> &[ChildSpec] {
4191 s.children()
4192 }
4193 // Sweep both the empty-children (leaf-supervisor with no
4194 // static children — the `SimpleOneForOne` dynamic-child
4195 // arm's canonical shape) and the populated-children
4196 // (`OneForOne` / `OneForAll` / `RestForOne` static-child
4197 // arm's canonical shape) axes so the accessor carries a
4198 // const-dispatch pin on both arms.
4199 let s_empty = SupervisorSpec {
4200 estrategia: RestartStrategy::SimpleOneForOne,
4201 max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
4202 restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4203 children: vec![],
4204 };
4205 assert!(children_via_const_fn(&s_empty).is_empty());
4206 assert_eq!(children_via_const_fn(&s_empty), s_empty.children());
4207 let s_full = SupervisorSpec {
4208 estrategia: RestartStrategy::OneForOne,
4209 max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
4210 restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4211 children: vec![
4212 child("worker-a", "^0.1", RestartPolicy::Permanent),
4213 child("worker-b", "~0.2.3", RestartPolicy::Transient),
4214 child("collector", "*", RestartPolicy::Temporary),
4215 ],
4216 };
4217 assert_eq!(children_via_const_fn(&s_full).len(), 3);
4218 assert_eq!(children_via_const_fn(&s_full), s_full.children());
4219 }
4220
4221 #[test]
4222 fn default_has_one_for_one_and_5_restarts_in_60s() {
4223 let s = SupervisorSpec::default();
4224 assert_eq!(s.estrategia, RestartStrategy::OneForOne);
4225 assert_eq!(s.max_restarts, 5);
4226 assert_eq!(s.restart_window, Some(Duration::from_secs(60)));
4227 assert!(s.children.is_empty());
4228 }
4229
4230 #[test]
4231 fn validate_one_for_one_requires_children() {
4232 let mut s = SupervisorSpec::default();
4233 s.children = vec![];
4234 assert!(matches!(
4235 s.validate().unwrap_err(),
4236 SupervisorError::NoChildren { .. }
4237 ));
4238 s.children = vec![child("worker", "^0.1", RestartPolicy::Permanent)];
4239 s.validate().unwrap();
4240 }
4241
4242 #[test]
4243 fn validate_simple_one_for_one_forbids_static_children() {
4244 let mut s = SupervisorSpec {
4245 estrategia: RestartStrategy::SimpleOneForOne,
4246 ..SupervisorSpec::default()
4247 };
4248 s.children
4249 .push(child("w", "^0.1", RestartPolicy::Permanent));
4250 assert_eq!(
4251 s.validate().unwrap_err(),
4252 SupervisorError::SimpleOneForOneWithStaticChildren
4253 );
4254 s.children.clear();
4255 s.validate().unwrap();
4256 }
4257
4258 #[test]
4259 fn validate_rejects_zero_max_restarts() {
4260 let s = SupervisorSpec {
4261 max_restarts: 0,
4262 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4263 ..SupervisorSpec::default()
4264 };
4265 assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
4266 }
4267
4268 // ── upper-cap: SUPERVISOR_MAX_RESTARTS_MAX brackets the typed slot ─────
4269 //
4270 // The cap arm lifts the `:politicas :circuit-breaker :max-failures` /
4271 // `POLICY_BREAKER_MAX_FAILURES_MAX` (2b51ace) discipline onto the peer
4272 // `:supervisor :max-restarts` axis — both fields are "trip the
4273 // next-higher protection layer after N events in a rolling window"
4274 // counters with identical degenerate-at-the-high-end shape, so the
4275 // typed-slot's accepted set lies in `1..=1000` on the supervisor side
4276 // exactly as it lies in `1..=1000` on the breaker side.
4277
4278 #[test]
4279 fn validate_rejects_max_restarts_above_cap() {
4280 // The fail-before-pass-after pin: `SUPERVISOR_MAX_RESTARTS_MAX +
4281 // 1` is structurally one past the cap and silently passed
4282 // validate on every pre-gate codebase because the typed slot's
4283 // only check was the zero-floor arm. The no-op-supervisor vector
4284 // only surfaced at the runtime substrate (Erlang/OTP
4285 // MaxIntensity/Period ratio, the future wasm-operator's
4286 // per-supervisor restart-intensity counter) far from the source
4287 // caixa.lisp with no field naming the offending supervisor.
4288 let s = SupervisorSpec {
4289 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4290 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4291 ..SupervisorSpec::default()
4292 };
4293 assert_eq!(
4294 s.validate().unwrap_err(),
4295 SupervisorError::MaxRestartsExceedsCap {
4296 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4297 }
4298 );
4299 }
4300
4301 #[test]
4302 fn validate_rejects_max_restarts_far_above_cap() {
4303 // The `u32::MAX` worst case — the four-billion-restart
4304 // threshold a typo (`:max-restarts 4294967295`) or a
4305 // struct-literal copy-paste lands in the slot. Pin the cap
4306 // arm's coverage explicitly across the full `u32` overflow so
4307 // a future relaxation that drops the upper bound surfaces
4308 // here. Same shape every other typed-cap arm on this surface
4309 // carries (POLICY_BREAKER_MAX_FAILURES_MAX,
4310 // POLICY_RETRIES_MAX, POLICY_RATE_LIMIT_MAX).
4311 let s = SupervisorSpec {
4312 max_restarts: u32::MAX,
4313 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4314 ..SupervisorSpec::default()
4315 };
4316 assert_eq!(
4317 s.validate().unwrap_err(),
4318 SupervisorError::MaxRestartsExceedsCap {
4319 max_restarts: u32::MAX,
4320 }
4321 );
4322 }
4323
4324 #[test]
4325 fn validate_accepts_max_restarts_at_cap() {
4326 // The boundary value — exactly SUPERVISOR_MAX_RESTARTS_MAX —
4327 // must validate. The cap is inclusive on the top edge,
4328 // matching the POLICY_BREAKER_MAX_FAILURES_MAX /
4329 // POLICY_RETRIES_MAX / LIMITS_MEMORY_WASM32_MAX_BYTES
4330 // discipline on the sibling capped axes. Pin the boundary
4331 // explicitly so a future off-by-one tightening
4332 // (`>= SUPERVISOR_MAX_RESTARTS_MAX` instead of `>`) surfaces
4333 // here as a test failure rather than a silent contract
4334 // narrowing.
4335 let s = SupervisorSpec {
4336 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX,
4337 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4338 ..SupervisorSpec::default()
4339 };
4340 s.validate()
4341 .expect("max_restarts == SUPERVISOR_MAX_RESTARTS_MAX must validate");
4342 }
4343
4344 #[test]
4345 fn validate_accepts_max_restarts_typical_values() {
4346 // The documented production-playbook band positive-control
4347 // sweep — every value Erlang/OTP / Elixir / Riak Core /
4348 // RabbitMQ recommend (1..=100) must pass, plus a sweep
4349 // through the hyperscale band (200, 500, 1000) the cap
4350 // accepts. Pin the inclusive validated set explicitly so a
4351 // future tightening of the ceiling surfaces here.
4352 for n in [1u32, 3, 5, 10, 20, 50, 100, 200, 500, 1000] {
4353 let s = SupervisorSpec {
4354 max_restarts: n,
4355 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4356 ..SupervisorSpec::default()
4357 };
4358 s.validate()
4359 .unwrap_or_else(|e| panic!("max_restarts={n} must validate; got {e:?}"));
4360 }
4361 }
4362
4363 #[test]
4364 fn zero_max_restarts_takes_precedence_over_cap() {
4365 // The cross-arm ordering pin: `0` is structurally outside
4366 // both `1..` (zero-floor) and `..=SUPERVISOR_MAX_RESTARTS_MAX`
4367 // (cap), but the zero-floor diagnostic is the more
4368 // self-locating one (it directly names the counter-axis
4369 // remediation), so the validate gate must fire on zero first.
4370 // Same shape every other zero-then-shape ordering on this
4371 // surface uses (PolicyRetriesZero then
4372 // PolicyRetriesExceedsCap; PolicyBreakerZeroFailures then
4373 // PolicyBreakerMaxFailuresExceedsCap).
4374 let s = SupervisorSpec {
4375 max_restarts: 0,
4376 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4377 ..SupervisorSpec::default()
4378 };
4379 assert_eq!(
4380 s.validate().unwrap_err(),
4381 SupervisorError::ZeroMaxRestarts,
4382 "max_restarts == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
4383 );
4384 }
4385
4386 #[test]
4387 fn max_restarts_cap_takes_precedence_over_restart_window_gates() {
4388 // The cross-arm ordering pin between the cap and the sibling
4389 // `:restart-window` gates (zero-window, canonical-window). A
4390 // supervisor carrying both an over-cap `max_restarts` AND a
4391 // structurally invalid window (zero, sub-ms) must surface the
4392 // cap diagnostic first — the cap arm is wired immediately
4393 // after the zero-restart arm and strictly before the window
4394 // arms, so the offending value the diagnostic names matches
4395 // the order the author would discover the gates by reading
4396 // top-to-bottom through `SupervisorSpec::validate`. Pin the
4397 // order so a future refactor that reorders the arms surfaces
4398 // here as a test failure rather than a silent diagnostic
4399 // regression. Peer of
4400 // `circuit_breaker_max_failures_cap_takes_precedence_over_window_gates`
4401 // on the sibling `:politicas :circuit-breaker` slot.
4402 let s = SupervisorSpec {
4403 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4404 restart_window: Some(Duration::ZERO),
4405 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4406 ..SupervisorSpec::default()
4407 };
4408 assert_eq!(
4409 s.validate().unwrap_err(),
4410 SupervisorError::MaxRestartsExceedsCap {
4411 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4412 },
4413 "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
4414 );
4415 }
4416
4417 #[test]
4418 fn max_restarts_cap_diagnostic_carries_offending_value() {
4419 // The diagnostic-shape pin: the offending `u32` is carried
4420 // verbatim into the `SupervisorError::MaxRestartsExceedsCap`
4421 // variant so the surfaced error message names the value the
4422 // author wrote (`":supervisor :max-restarts (50000) exceeds the
4423 // supervisor-policy ceiling …"`), not just the cap. Same
4424 // self-locating diagnostic shape every other typed-cap arm on
4425 // this surface carries
4426 // (`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` carries
4427 // the offending failure count verbatim,
4428 // `AplicacaoError::PolicyRetriesExceedsCap` carries the offending
4429 // retries count verbatim).
4430 let s = SupervisorSpec {
4431 max_restarts: 50_000,
4432 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4433 ..SupervisorSpec::default()
4434 };
4435 let err = s.validate().unwrap_err();
4436 assert!(
4437 matches!(
4438 err,
4439 SupervisorError::MaxRestartsExceedsCap {
4440 max_restarts: 50_000
4441 }
4442 ),
4443 "got {err:?}"
4444 );
4445 let msg = err.to_string();
4446 assert!(
4447 msg.contains("50000"),
4448 ":supervisor :max-restarts cap diagnostic must carry the offending value verbatim (got: {msg})"
4449 );
4450 }
4451
4452 #[test]
4453 fn supervisor_max_restarts_default_pins_otp_canonical_value() {
4454 // Pin [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] at `5` — the
4455 // Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
4456 // half of Learn You Some Erlang's worker-supervisor default,
4457 // sibling of the `60s` `Period` half that the paired
4458 // [`Default for SupervisorSpec`] impl already pins on the
4459 // sibling `restart_window` axis. Pinning the literal here
4460 // surfaces a future rebrand (a tightening to Elixir's `3`,
4461 // a widening to a per-cluster overlay the operator pins
4462 // through a future `:max-restarts-overrides` slot) as a
4463 // deliberate test edit, not a silent contract migration.
4464 // Peer of the sibling
4465 // [`supervisor_max_restarts_cap_pins_canonical_value`]
4466 // upper-bracket pin on the same axis.
4467 assert_eq!(SUPERVISOR_MAX_RESTARTS_DEFAULT, 5);
4468 }
4469
4470 #[test]
4471 fn default_max_restarts_helper_routes_through_lifted_default() {
4472 // Composition pin: the private `default_max_restarts()`
4473 // serde-`#[serde(default = "…")]` helper on
4474 // [`SupervisorSpec::max_restarts`] must route through the
4475 // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
4476 // typed `pub const` rather than a raw `5` literal. Prior to
4477 // the lift the helper carried an inline `5` with no compile-
4478 // time link back to the shared default, so the wire-format
4479 // author-omitted arm and the caixa-core
4480 // [`crate::manifest::Caixa::supervisor_view`] fold's `unwrap_or(5)`
4481 // arm could silently split on any future default rebrand.
4482 // Byte-parity against the lifted constant closes the split.
4483 assert_eq!(default_max_restarts(), SUPERVISOR_MAX_RESTARTS_DEFAULT);
4484 }
4485
4486 #[test]
4487 fn supervisor_spec_default_max_restarts_routes_through_lifted_default() {
4488 // Composition pin: the [`Default for SupervisorSpec`] impl's
4489 // struct-literal `max_restarts` field must route through the
4490 // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
4491 // typed `pub const` (via the private helper this test's
4492 // sibling `default_max_restarts_helper_routes_through_lifted_default`
4493 // already pins onto the constant). Structurally: every
4494 // `SupervisorSpec::default()` call must yield a
4495 // `max_restarts` field byte-equal to the lifted constant
4496 // (the two paired defaults — the serde-side wire-format arm
4497 // and the struct-literal default arm — cannot silently split
4498 // on any future default rebrand). Peer of the sibling
4499 // `default_has_one_for_one_and_5_restarts_in_60s` shape pin
4500 // — this pin closes the byte-parity arm on the two paired
4501 // altitude entry points onto the shared substrate constant.
4502 assert_eq!(
4503 SupervisorSpec::default().max_restarts(),
4504 SUPERVISOR_MAX_RESTARTS_DEFAULT,
4505 );
4506 }
4507
4508 #[test]
4509 fn supervisor_restart_window_default_pins_otp_canonical_value() {
4510 // Pin [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] at `60s` — the
4511 // Erlang/OTP-canonical `{intensity, 5, 60}` `Period` half of
4512 // Learn You Some Erlang's worker-supervisor default, paired
4513 // with the sibling `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5`
4514 // `MaxIntensity` half this constant is the sliding-window
4515 // denominator of on the same `MaxIntensity / Period`
4516 // restart-intensity ratio. Pinning the literal here surfaces a
4517 // future coherent rebrand of the paired default (Elixir's
4518 // `{max_restarts: 3, max_seconds: 5}`, a per-cluster overlay
4519 // the operator pins through a future
4520 // `:restart-window-overrides` slot) as a deliberate test edit,
4521 // not a silent contract migration. Peer of the sibling
4522 // [`supervisor_max_restarts_default_pins_otp_canonical_value`]
4523 // paired-half pin on the same OTP-canonical default and the
4524 // [`supervisor_restart_window_cap_pins_canonical_value`]
4525 // upper-bracket pin on the same axis.
4526 assert_eq!(SUPERVISOR_RESTART_WINDOW_DEFAULT, Duration::from_secs(60),);
4527 }
4528
4529 #[test]
4530 fn supervisor_spec_default_restart_window_routes_through_lifted_default() {
4531 // Composition pin: the [`Default for SupervisorSpec`] impl's
4532 // struct-literal `restart_window` field must route through the
4533 // substrate-canonical [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
4534 // typed `pub const` rather than a raw
4535 // `Duration::from_secs(60)` literal. Prior to this lift the
4536 // paired `{intensity, 5, 60}` OTP-canonical default was split
4537 // across two altitudes with no compile-time link between the
4538 // halves — the `MaxIntensity` half rode through the lifted
4539 // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant while the
4540 // `Period` half rode as an open-coded literal at the
4541 // composition site, so a future coherent rebrand of the paired
4542 // canonical would have had to migrate one half through the
4543 // constant and the other through a raw literal in lockstep.
4544 // Byte-parity against the lifted constant on the `Period` half
4545 // closes the split — the paired OTP-canonical default now
4546 // migrates as one unit on any future axis change. Peer of the
4547 // sibling
4548 // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
4549 // byte-parity pin on the paired `MaxIntensity` half.
4550 assert_eq!(
4551 SupervisorSpec::default().restart_window(),
4552 Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4553 );
4554 }
4555
4556 #[test]
4557 fn supervisor_estrategia_default_pins_otp_canonical_value() {
4558 // Pin [`SUPERVISOR_ESTRATEGIA_DEFAULT`] at [`RestartStrategy::OneForOne`]
4559 // — the Erlang/OTP-canonical `one_for_one` half of Learn You Some
4560 // Erlang's `{one_for_one, intensity, 5, 60}` worker-supervisor
4561 // canonical default, paired with the sibling
4562 // `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5` `MaxIntensity` half and the
4563 // sibling `SUPERVISOR_RESTART_WINDOW_DEFAULT` `60s` `Period` half
4564 // this constant is the strategy discriminator of on the same
4565 // OTP-canonical worker-supervisor default. Pinning the arm here
4566 // surfaces a future coherent rebrand of the paired triple (Elixir's
4567 // `{:one_for_one, max_restarts: 3, max_seconds: 5}` on the sibling
4568 // intensity/period axes leaving this strategy arm untouched, an OTP
4569 // `rest_for_one` widening once the substrate discovers startup-
4570 // order-coupled child cohorts as the more common worker-supervisor
4571 // shape, a per-cluster overlay the operator pins through a future
4572 // `:estrategia-overrides` slot the MESH-COMPOSITION §III.2
4573 // supervision-canary roadmap acknowledges) as a deliberate test
4574 // edit, not a silent contract migration. Peer of the sibling
4575 // [`supervisor_max_restarts_default_pins_otp_canonical_value`] +
4576 // [`supervisor_restart_window_default_pins_otp_canonical_value`]
4577 // paired-half pins on the same OTP-canonical default.
4578 assert_eq!(SUPERVISOR_ESTRATEGIA_DEFAULT, RestartStrategy::OneForOne);
4579 }
4580
4581 #[test]
4582 fn restart_strategy_default_routes_through_lifted_default() {
4583 // Composition pin: the [`Default for RestartStrategy`] impl's
4584 // return arm must route through the substrate-canonical
4585 // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
4586 // a raw `Self::OneForOne` arm. Prior to the lift the impl carried
4587 // an inline `Self::OneForOne` with no compile-time link back to
4588 // the shared OTP-canonical `one_for_one` strategy the paired
4589 // [`Default for SupervisorSpec`] impl's struct-literal `estrategia`
4590 // field and the [`crate::manifest::Caixa::supervisor_view`] fold's
4591 // `.unwrap_or_default()` (now
4592 // `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)`) arm both key off —
4593 // so a future rebrand of the OTP-canonical strategy default (an
4594 // OTP `rest_for_one` widening once the substrate discovers
4595 // startup-order-coupled child cohorts as the more common worker-
4596 // supervisor shape, a per-cluster overlay the operator pins
4597 // through a future `:estrategia-overrides` slot) would have had to
4598 // be threaded through the `Default` impl and the two peer routes
4599 // in lockstep or the three consumers would silently split. Byte-
4600 // parity against the lifted constant closes the split. Peer of
4601 // the sibling
4602 // [`default_max_restarts_helper_routes_through_lifted_default`] +
4603 // [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
4604 // composition pins on the paired `MaxIntensity` + `Period` halves.
4605 assert_eq!(RestartStrategy::default(), SUPERVISOR_ESTRATEGIA_DEFAULT,);
4606 }
4607
4608 #[test]
4609 fn supervisor_spec_default_estrategia_routes_through_lifted_default() {
4610 // Composition pin: the [`Default for SupervisorSpec`] impl's
4611 // struct-literal `estrategia` field must route through the
4612 // substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed
4613 // `pub const` (either directly, or via the
4614 // [`RestartStrategy::default`] impl that the sibling
4615 // `restart_strategy_default_routes_through_lifted_default` pin
4616 // already routes onto the constant). Structurally: every
4617 // `SupervisorSpec::default()` call must yield an `estrategia`
4618 // field byte-equal to the lifted constant (the three paired
4619 // defaults — the [`Default for RestartStrategy`] impl arm, the
4620 // struct-literal default arm here, and the
4621 // [`crate::manifest::Caixa::supervisor_view`] fold arm — cannot
4622 // silently split on any future default rebrand). Peer of the
4623 // sibling
4624 // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
4625 // + [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
4626 // byte-parity pins on the paired `MaxIntensity` + `Period` halves
4627 // of the same `SupervisorSpec::default()` composed altitude.
4628 assert_eq!(
4629 SupervisorSpec::default().estrategia(),
4630 SUPERVISOR_ESTRATEGIA_DEFAULT,
4631 );
4632 }
4633
4634 #[test]
4635 fn supervisor_spec_default_routes_through_otp_canonical_ctor() {
4636 // Composition pin: the [`Default for SupervisorSpec`] impl must
4637 // route through the substrate-canonical
4638 // [`SupervisorSpec::otp_canonical`] `pub const fn` constructor
4639 // rather than a re-hand-authored struct-literal cascade. Sharpens
4640 // the sibling per-arm
4641 // `supervisor_spec_default_*_routes_through_lifted_default` pins
4642 // from a per-field lift into a whole-struct one-source-of-truth
4643 // pin — the derived-until-now [`Default::default`] and the
4644 // [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
4645 // construction, not by coincidence.
4646 //
4647 // A future extension of the OTP-canonical baseline (a fifth
4648 // `restart_intensity` field the Erlang/OTP `#supervisor` record
4649 // grows, a per-child-cohort split of the `restart_window` /
4650 // `max_restarts` pair, an M4 `mesh.pleme.io/v1alpha1/Supervisor`
4651 // CR materializer's admission-time overlay pass) reaches both
4652 // paths through exactly one edit on
4653 // [`SupervisorSpec::otp_canonical`] — the derived path could
4654 // silently disagree with the constructor's shape on any new
4655 // field whose [`Default::default`] resolves to a different arm
4656 // than the OTP-canonical baseline the constructor names, while
4657 // this delegated impl reaches the constructor directly and
4658 // picks up every future extension by construction.
4659 //
4660 // Fourth peer on the M2 / M3 typed-slot-spec
4661 // [`Default`]-through-const-ctor fold family — sibling of the
4662 // [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
4663 // (abd52c2), [`crate::aplicacao::MeshPolicy`]
4664 // [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`]
4665 // (91641a4), and [`crate::BehaviorSpec`]
4666 // [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c)
4667 // per-`Option`-only-typed-slot folds — extended here onto the
4668 // M2 supervisor-slot [`SupervisorSpec`] whose canonical baseline
4669 // is not "everything `None`" but the Erlang/OTP-canonical
4670 // `{one_for_one, 5, 60}` worker-supervisor triple.
4671 assert_eq!(SupervisorSpec::default(), SupervisorSpec::otp_canonical());
4672 }
4673
4674 #[test]
4675 fn supervisor_spec_otp_canonical_byte_equals_default() {
4676 // Value pin: [`SupervisorSpec::otp_canonical`] must byte-equal
4677 // the hand-authored `{one_for_one, 5, 60, []}` OTP-canonical
4678 // baseline the sibling `default_has_one_for_one_and_5_restarts_in_60s`
4679 // pin already asserts against the [`Default::default`] path.
4680 // Sharpens the pair-invariant into a per-constructor pin so a
4681 // future extension of [`SupervisorSpec`] with a fifth field
4682 // whose OTP-canonical shape is non-`Default::default`-equivalent
4683 // trips at caixa-core test time rather than at a downstream
4684 // consumer that composed [`SupervisorSpec::otp_canonical`] with
4685 // [`SupervisorSpec::validate`] as its "canonical baseline
4686 // seed".
4687 let canonical = SupervisorSpec::otp_canonical();
4688 assert_eq!(canonical.estrategia, RestartStrategy::OneForOne);
4689 assert_eq!(canonical.max_restarts, 5);
4690 assert_eq!(canonical.restart_window, Some(Duration::from_secs(60)));
4691 assert!(canonical.children.is_empty());
4692 }
4693
4694 #[test]
4695 fn supervisor_spec_otp_canonical_is_usable_in_const_context() {
4696 // Const-context pin: [`SupervisorSpec::otp_canonical`] must
4697 // remain callable from a `const`-bound position so downstream
4698 // `const`-context callers wanting a canonical OTP-baseline seed
4699 // can construct one at compile time without runtime dispatch on
4700 // the derived [`Default::default`]. Peer of the sibling
4701 // `pub const fn` [`crate::LimitsSpec::empty`] /
4702 // [`crate::aplicacao::MeshPolicy::empty`] /
4703 // [`crate::BehaviorSpec::empty`] constructors on the sibling
4704 // typed-slot-spec `pub const fn` axis. If a future edit breaks
4705 // the `const`-eligibility of [`SupervisorSpec::otp_canonical`]
4706 // (a non-`const` field-default helper, a non-`const`-stable
4707 // container type promotion), this evaluation fails at
4708 // build time on this file rather than at a downstream
4709 // `const`-context call site.
4710 const CANONICAL: SupervisorSpec = SupervisorSpec::otp_canonical();
4711 assert_eq!(CANONICAL.estrategia, SUPERVISOR_ESTRATEGIA_DEFAULT);
4712 assert_eq!(CANONICAL.max_restarts, SUPERVISOR_MAX_RESTARTS_DEFAULT);
4713 assert_eq!(
4714 CANONICAL.restart_window,
4715 Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4716 );
4717 assert!(CANONICAL.children.is_empty());
4718 }
4719
4720 #[test]
4721 fn supervisor_child_restart_default_pins_otp_canonical_value() {
4722 // Pin [`SUPERVISOR_CHILD_RESTART_DEFAULT`] at
4723 // [`RestartPolicy::Permanent`] — Erlang/OTP's `permanent`
4724 // worker-child restart type (`{ChildId, StartFunc, permanent, …}`
4725 // in a `supervisor`'s `init/1` child-spec tuple), the per-child
4726 // half of the same OTP-shape supervisor-tree default set whose
4727 // per-`:supervisor` halves the sibling
4728 // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
4729 // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] /
4730 // [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] constants pin. Pinning the
4731 // arm here surfaces a future rebrand of the per-child default (an
4732 // OTP-`transient` widening once the substrate discovers clean-
4733 // completion-aware children as the more common child shape, a
4734 // per-cluster overlay the operator pins through a future
4735 // `:restart-overrides` slot the MESH-COMPOSITION §III.2
4736 // supervision-canary roadmap acknowledges) as a deliberate test
4737 // edit, not a silent contract migration. Peer of the sibling
4738 // [`supervisor_estrategia_default_pins_otp_canonical_value`] /
4739 // [`supervisor_max_restarts_default_pins_otp_canonical_value`] /
4740 // [`supervisor_restart_window_default_pins_otp_canonical_value`]
4741 // value pins on the per-`:supervisor` halves.
4742 assert_eq!(SUPERVISOR_CHILD_RESTART_DEFAULT, RestartPolicy::Permanent);
4743 }
4744
4745 #[test]
4746 fn restart_policy_default_routes_through_lifted_default() {
4747 // Composition pin: the [`Default for RestartPolicy`] impl's return
4748 // arm must route through the substrate-canonical
4749 // [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const` rather
4750 // than a raw `Self::Permanent` arm. Prior to the lift the impl
4751 // carried an inline `Self::Permanent` with no compile-time link
4752 // back to the OTP-shape supervisor-tree default set whose three
4753 // per-`:supervisor` halves already rode through lifted constants
4754 // — so a future coherent rebrand of the set would have had to
4755 // migrate three halves through typed constants and this fourth
4756 // through a raw enum arm in lockstep or the supervisor-level and
4757 // child-level defaults would silently drift apart. Byte-parity
4758 // against the lifted constant closes the split. Peer of the
4759 // sibling
4760 // [`restart_strategy_default_routes_through_lifted_default`]
4761 // composition pin on the per-`:supervisor` `:estrategia` axis.
4762 assert_eq!(RestartPolicy::default(), SUPERVISOR_CHILD_RESTART_DEFAULT);
4763 }
4764
4765 #[test]
4766 fn child_spec_serde_default_restart_routes_through_lifted_default() {
4767 // Composition pin: the serde-side `#[serde(default)]` on
4768 // [`ChildSpec::restart`] — the wire-format author-omitted
4769 // `:children :restart` arm — must resolve onto the substrate-
4770 // canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const`
4771 // (via the [`Default for RestartPolicy`] impl the sibling
4772 // `restart_policy_default_routes_through_lifted_default` pin
4773 // already routes onto the constant). Structurally: a `ChildSpec`
4774 // deserialized from a payload that omits the `restart` key must
4775 // yield a `restart` field byte-equal to the lifted constant, so
4776 // the wire-format author-omitted arm and the
4777 // [`RestartPolicy::default`] impl arm cannot silently split on any
4778 // future default rebrand. Peer of the sibling
4779 // [`supervisor_spec_default_estrategia_routes_through_lifted_default`]
4780 // / [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
4781 // / [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
4782 // byte-parity pins on the per-`:supervisor` halves of the same
4783 // author-omitted-slot resolution surface.
4784 let omitted: ChildSpec = serde_json::from_str(r#"{"caixa":"worker","versao":"^0.1"}"#)
4785 .expect("ChildSpec must deserialize with the restart key omitted");
4786 assert_eq!(
4787 omitted.restart(),
4788 SUPERVISOR_CHILD_RESTART_DEFAULT,
4789 "an author-omitted :children :restart slot must degrade onto \
4790 the SUPERVISOR_CHILD_RESTART_DEFAULT typed pub const (got \
4791 {:?}, expected {:?})",
4792 omitted.restart(),
4793 SUPERVISOR_CHILD_RESTART_DEFAULT,
4794 );
4795 }
4796
4797 #[test]
4798 fn supervisor_max_restarts_cap_pins_canonical_value() {
4799 // The SUPERVISOR_MAX_RESTARTS_MAX constant pins the value at
4800 // 1000 — the same ceiling the peer
4801 // POLICY_BREAKER_MAX_FAILURES_MAX cap carries on the
4802 // `:politicas :circuit-breaker :max-failures` axis (both are
4803 // "trip the next-higher protection layer after N events in a
4804 // rolling window" counters with identical
4805 // degenerate-at-the-high-end shape; uniform top edge so the
4806 // M4 CR materializers and the wasm-operator reconciler reach
4807 // for either field knowing the value is in `1..=1000`). Two
4808 // orders of magnitude above every documented Erlang/OTP /
4809 // Elixir / Riak Core / RabbitMQ production-playbook
4810 // recommendation band and below the clearly-pathological
4811 // "effectively no escalation" floor (10_000, 100_000,
4812 // u32::MAX). Pinning the literal value here surfaces a future
4813 // drift (a relaxation to 10_000, a tightening to 100) as a
4814 // deliberate test edit, not a silent contract narrowing.
4815 assert_eq!(SUPERVISOR_MAX_RESTARTS_MAX, 1000);
4816 }
4817
4818 #[test]
4819 fn validate_rejects_empty_child_name() {
4820 let s = SupervisorSpec {
4821 children: vec![child("", "^0.1", RestartPolicy::Permanent)],
4822 ..SupervisorSpec::default()
4823 };
4824 assert_eq!(s.validate().unwrap_err(), SupervisorError::EmptyChildName);
4825 }
4826
4827 #[test]
4828 fn validate_rejects_empty_child_version() {
4829 let s = SupervisorSpec {
4830 children: vec![child("w", "", RestartPolicy::Permanent)],
4831 ..SupervisorSpec::default()
4832 };
4833 assert!(matches!(
4834 s.validate().unwrap_err(),
4835 SupervisorError::EmptyChildVersion { .. }
4836 ));
4837 }
4838
4839 // ── value-shape: parse-as-VersionReq on :children :versao ─────────────
4840
4841 #[test]
4842 fn validate_rejects_invalid_child_versao_requirement() {
4843 // The fail-before-pass-after pin: a non-empty but malformed
4844 // semver requirement (`"^bad-version"`) silently passed
4845 // `validate()` on every pre-gate codebase because the prior
4846 // shape only refused the empty string. The parse failure
4847 // surfaced far downstream at lacre-resolve time with a
4848 // `semver::Error` that didn't name which `:children` entry
4849 // carried the typo. The new gate moves the check to caixa-build
4850 // time at the source caixa.lisp — the third `:versao` typed
4851 // axis (`:children`) joins `:deps` and `:membros` (9888b13) at
4852 // structural parity.
4853 let s = SupervisorSpec {
4854 children: vec![
4855 child("worker", "^0.1", RestartPolicy::Permanent),
4856 child("cache", "^bad-version", RestartPolicy::Transient),
4857 ],
4858 ..SupervisorSpec::default()
4859 };
4860 let err = s.validate().unwrap_err();
4861 assert!(
4862 matches!(
4863 err,
4864 SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
4865 if caixa == "cache" && versao == "^bad-version"
4866 ),
4867 "got {err:?}"
4868 );
4869 }
4870
4871 #[test]
4872 fn validate_rejects_child_versao_with_double_caret_typo() {
4873 // `"^^0.1"` is the canonical doubled-caret typo — looks
4874 // Cargo-shaped on first glance but fails the parser because
4875 // semver doesn't accept stacked operators. Pin this
4876 // adjacent-shape footgun explicitly so a future relaxation that
4877 // accepts "looks-canonical-but-isn't" forms surfaces here.
4878 let s = SupervisorSpec {
4879 children: vec![child("worker", "^^0.1", RestartPolicy::Permanent)],
4880 ..SupervisorSpec::default()
4881 };
4882 let err = s.validate().unwrap_err();
4883 assert!(
4884 matches!(
4885 err,
4886 SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
4887 if caixa == "worker" && versao == "^^0.1"
4888 ),
4889 "got {err:?}"
4890 );
4891 }
4892
4893 #[test]
4894 fn validate_rejects_child_versao_with_v_prefixed_tag() {
4895 // `"v0.1"` is the canonical "git-tag-shape leaking into the
4896 // semver requirement slot" typo — an author copies the
4897 // publish-side git-tag string verbatim into `:versao`, but
4898 // Cargo's semver parser rejects the leading `v`. Same
4899 // adjacent-shape footgun pinned for `:membros :versao`
4900 // (9888b13).
4901 let s = SupervisorSpec {
4902 children: vec![child("worker", "v0.1", RestartPolicy::Permanent)],
4903 ..SupervisorSpec::default()
4904 };
4905 let err = s.validate().unwrap_err();
4906 assert!(
4907 matches!(
4908 err,
4909 SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
4910 if caixa == "worker" && versao == "v0.1"
4911 ),
4912 "got {err:?}"
4913 );
4914 }
4915
4916 #[test]
4917 fn validate_accepts_canonical_child_versao_forms() {
4918 // The Cargo-shaped requirement forms `:deps :versao` and
4919 // `:membros :versao` already accept via
4920 // `crate::parse_requirement` must pass the children gate
4921 // without re-validating at the resolver layer. Pin every leg so
4922 // a future tightening of the canonical set surfaces here as a
4923 // test failure.
4924 for form in [
4925 "^0.1", // caret — minor-range pin (the most common shape)
4926 "~0.1.2", // tilde — patch-range pin
4927 "0.1.0", // exact — single-version pin
4928 "*", // wildcard — any version (semver::VersionReq::STAR)
4929 ">=0.1, <2", // multi-range — comma-separated comparators
4930 ] {
4931 let s = SupervisorSpec {
4932 children: vec![child("worker", form, RestartPolicy::Permanent)],
4933 ..SupervisorSpec::default()
4934 };
4935 s.validate()
4936 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
4937 }
4938 }
4939
4940 #[test]
4941 fn child_versao_empty_takes_precedence_over_invalid() {
4942 // Order pin: the existing `EmptyChildVersion` diagnostic (which
4943 // doesn't try to parse) fires before the new
4944 // `ChildVersaoInvalid` parse-side diagnostic, so an empty
4945 // `:versao` keeps its narrower error message —
4946 // `parse_requirement` would also reject `""`, but the
4947 // empty-string arm is the more self-locating diagnostic for the
4948 // author. Same ordering discipline as
4949 // `membro_versao_empty_takes_precedence_over_invalid` in
4950 // aplicacao.rs.
4951 let s = SupervisorSpec {
4952 children: vec![child("worker", "", RestartPolicy::Permanent)],
4953 ..SupervisorSpec::default()
4954 };
4955 let err = s.validate().unwrap_err();
4956 assert!(
4957 matches!(err, SupervisorError::EmptyChildVersion { ref caixa } if caixa == "worker"),
4958 "got {err:?}"
4959 );
4960 }
4961
4962 #[test]
4963 fn child_versao_invalid_fires_before_duplicate_check() {
4964 // Order pin: a malformed requirement on a non-duplicate entry
4965 // surfaces *its own* diagnostic (which names the offending
4966 // `:versao` string), even when a later entry would otherwise
4967 // collapse onto an earlier name. The per-entry shape gate runs
4968 // inline before the duplicate-key insert — parallel to
4969 // `membro_versao_invalid_fires_before_duplicate_check` in
4970 // aplicacao.rs and the b0c8389 / c4213a4 ordering discipline.
4971 let s = SupervisorSpec {
4972 children: vec![
4973 child("worker", "^bad", RestartPolicy::Permanent),
4974 child("cache", "^0.1", RestartPolicy::Transient),
4975 child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
4976 ],
4977 ..SupervisorSpec::default()
4978 };
4979 let err = s.validate().unwrap_err();
4980 assert!(
4981 matches!(
4982 err,
4983 SupervisorError::ChildVersaoInvalid { ref caixa, .. } if caixa == "worker"
4984 ),
4985 "got {err:?}"
4986 );
4987 }
4988
4989 #[test]
4990 fn child_versao_invalid_diagnostic_carries_offending_versao() {
4991 // The diagnostic-shape pin: the error names the offending
4992 // `:versao` value verbatim so the author can grep their
4993 // caixa.lisp without re-running the build, and carries a
4994 // non-empty `reason` from `semver::VersionReq::parse` so the
4995 // parser's own wording flows through to the diagnostic.
4996 let s = SupervisorSpec {
4997 children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
4998 ..SupervisorSpec::default()
4999 };
5000 let err = s.validate().unwrap_err();
5001 let SupervisorError::ChildVersaoInvalid {
5002 caixa,
5003 versao,
5004 reason,
5005 } = err
5006 else {
5007 panic!("expected ChildVersaoInvalid, got other variant");
5008 };
5009 assert_eq!(caixa, "worker");
5010 assert_eq!(versao, "not-a-req");
5011 assert!(
5012 !reason.is_empty(),
5013 "ChildVersaoInvalid `reason` must carry the parser's wording verbatim"
5014 );
5015 }
5016
5017 // ── value-shape: DNS-1123 label rule on :children :caixa ──────────────
5018
5019 #[test]
5020 fn validate_rejects_child_caixa_with_uppercase() {
5021 // The canonical "I copied the Servico's display name verbatim"
5022 // typo — child caixa names are lowercase per K8s DNS-1123 label
5023 // rule. The diagnostic names the offending name and suggests the
5024 // lower-cased fix in one edit, mirroring the
5025 // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0).
5026 let s = SupervisorSpec {
5027 children: vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
5028 ..SupervisorSpec::default()
5029 };
5030 let err = s.validate().unwrap_err();
5031 let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
5032 panic!("expected ChildCaixaInvalid, got other variant");
5033 };
5034 assert_eq!(caixa, "Worker");
5035 assert!(
5036 reason.contains("uppercase"),
5037 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
5038 );
5039 assert!(
5040 reason.contains("\"worker\""),
5041 "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
5042 );
5043 }
5044
5045 #[test]
5046 fn validate_rejects_child_caixa_with_underscore() {
5047 // The canonical "I'm thinking of a Python module / Postgres
5048 // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
5049 // label schema. K8s rejects `metadata.name: my_worker` at
5050 // admission time with an opaque `field is invalid` (no source-
5051 // citing diagnostic). The gate moves it to caixa-build time.
5052 let s = SupervisorSpec {
5053 children: vec![child("my_worker", "^0.1", RestartPolicy::Permanent)],
5054 ..SupervisorSpec::default()
5055 };
5056 let err = s.validate().unwrap_err();
5057 assert!(
5058 matches!(
5059 err,
5060 SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
5061 if caixa == "my_worker" && reason.contains('_')
5062 ),
5063 "got {err:?}"
5064 );
5065 }
5066
5067 #[test]
5068 fn validate_rejects_child_caixa_with_dot() {
5069 // A `:children :caixa` entry is a single DNS-1123 label, not a
5070 // subdomain. The K8s Service / ComputeUnit `metadata.name` rules
5071 // forbid dots. Same shape as `rejects_membro_caixa_with_dot`
5072 // (3f9d7a0) on the peer name axis.
5073 let s = SupervisorSpec {
5074 children: vec![child("team.worker", "^0.1", RestartPolicy::Permanent)],
5075 ..SupervisorSpec::default()
5076 };
5077 let err = s.validate().unwrap_err();
5078 assert!(
5079 matches!(
5080 err,
5081 SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
5082 if caixa == "team.worker" && reason.contains('.')
5083 ),
5084 "got {err:?}"
5085 );
5086 }
5087
5088 #[test]
5089 fn validate_rejects_child_caixa_with_leading_hyphen() {
5090 // DNS-1123 / DNS-1035 boundary rule: labels must start and end
5091 // with an alphanumeric. The K8s apiserver rejects `-worker`
5092 // outright; the renderer would emit a `metadata.name: "-worker"`
5093 // that fails admission far from the source caixa.lisp.
5094 let s = SupervisorSpec {
5095 children: vec![child("-worker", "^0.1", RestartPolicy::Permanent)],
5096 ..SupervisorSpec::default()
5097 };
5098 let err = s.validate().unwrap_err();
5099 assert!(
5100 matches!(
5101 err,
5102 SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
5103 if caixa == "-worker" && reason.contains("start and end")
5104 ),
5105 "got {err:?}"
5106 );
5107 }
5108
5109 #[test]
5110 fn validate_rejects_child_caixa_with_trailing_hyphen() {
5111 // The symmetric arm of the boundary rule. Pin separately so
5112 // both ends of the label are covered against a future relaxation
5113 // that only checks one boundary.
5114 let s = SupervisorSpec {
5115 children: vec![child("worker-", "^0.1", RestartPolicy::Permanent)],
5116 ..SupervisorSpec::default()
5117 };
5118 let err = s.validate().unwrap_err();
5119 assert!(
5120 matches!(
5121 err,
5122 SupervisorError::ChildCaixaInvalid { ref caixa, .. }
5123 if caixa == "worker-"
5124 ),
5125 "got {err:?}"
5126 );
5127 }
5128
5129 #[test]
5130 fn validate_rejects_child_caixa_with_unicode() {
5131 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
5132 // (`xn--…`) by the author before it reaches K8s. The byte-by-
5133 // byte ASCII validity check rejects multi-byte UTF-8 sequences
5134 // by the first byte that fails the `[a-z0-9-]` predicate.
5135 let s = SupervisorSpec {
5136 children: vec![child("café", "^0.1", RestartPolicy::Permanent)],
5137 ..SupervisorSpec::default()
5138 };
5139 let err = s.validate().unwrap_err();
5140 assert!(
5141 matches!(
5142 err,
5143 SupervisorError::ChildCaixaInvalid { ref caixa, .. }
5144 if caixa == "café"
5145 ),
5146 "got {err:?}"
5147 );
5148 }
5149
5150 #[test]
5151 fn validate_rejects_child_caixa_with_whitespace() {
5152 // Whitespace is the canonical "I pasted from a sketch / doc"
5153 // footgun. The apiserver rejects every `metadata.name` value
5154 // carrying whitespace; pin the gate fires at the right boundary.
5155 let s = SupervisorSpec {
5156 children: vec![child("my worker", "^0.1", RestartPolicy::Permanent)],
5157 ..SupervisorSpec::default()
5158 };
5159 let err = s.validate().unwrap_err();
5160 assert!(
5161 matches!(
5162 err,
5163 SupervisorError::ChildCaixaInvalid { ref caixa, .. }
5164 if caixa == "my worker"
5165 ),
5166 "got {err:?}"
5167 );
5168 }
5169
5170 #[test]
5171 fn validate_rejects_child_caixa_too_long() {
5172 // The 64-byte boundary pin. DNS-1123 / DNS-1035 cap labels at
5173 // 63 bytes; the K8s apiserver rejects every `metadata.name`
5174 // axis over the limit at admission time. The diagnostic names
5175 // both the cap and the actual length so the author can shorten
5176 // in one edit, mirroring `rejects_membro_caixa_too_long`
5177 // (3f9d7a0) and `rejects_placement_cluster_too_long` (6cbb900).
5178 let too_long = "a".repeat(64);
5179 let s = SupervisorSpec {
5180 children: vec![child(&too_long, "^0.1", RestartPolicy::Permanent)],
5181 ..SupervisorSpec::default()
5182 };
5183 let err = s.validate().unwrap_err();
5184 let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
5185 panic!("expected ChildCaixaInvalid, got other variant");
5186 };
5187 assert_eq!(caixa, too_long);
5188 assert!(
5189 reason.contains("63"),
5190 "diagnostic must name the 63-byte cap (got: {reason:?})"
5191 );
5192 assert!(
5193 reason.contains("64"),
5194 "diagnostic must name the actual length (got: {reason:?})"
5195 );
5196 }
5197
5198 #[test]
5199 fn child_caixa_max_length_validates() {
5200 // The 63-byte boundary control pin — exactly-at-the-cap is
5201 // accepted, mirroring `membro_caixa_max_length_validates`
5202 // (3f9d7a0) and `placement_cluster_max_length_validates`
5203 // (6cbb900). Pinned separately so a future off-by-one tightening
5204 // surfaces here.
5205 let max_label = "a".repeat(63);
5206 let s = SupervisorSpec {
5207 children: vec![child(&max_label, "^0.1", RestartPolicy::Permanent)],
5208 ..SupervisorSpec::default()
5209 };
5210 s.validate().unwrap();
5211 }
5212
5213 #[test]
5214 fn validate_accepts_canonical_child_caixa_forms() {
5215 // The realistic shapes a supervised child's `:caixa` carries —
5216 // single-word `worker`, version-suffixed `cache-v2`, single-char
5217 // `a`, two-char `db`, digit-start `2-pool`, longer hyphen-joined
5218 // `payment-retry`, all-digit `0`. Pin every leg so a future
5219 // tightening (e.g. requiring a leading lowercase letter) surfaces
5220 // here as a test failure. Mirrors `accepts_canonical_membro_caixa_forms`
5221 // (3f9d7a0) and `accepts_canonical_placement_cluster_forms`
5222 // (6cbb900).
5223 for form in [
5224 "worker",
5225 "cache-v2",
5226 "a",
5227 "db",
5228 "2-pool",
5229 "payment-retry",
5230 "0",
5231 ] {
5232 let s = SupervisorSpec {
5233 children: vec![child(form, "^0.1", RestartPolicy::Permanent)],
5234 ..SupervisorSpec::default()
5235 };
5236 s.validate()
5237 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
5238 }
5239 }
5240
5241 #[test]
5242 fn child_caixa_empty_takes_precedence_over_invalid() {
5243 // Order pin: the existing `EmptyChildName` diagnostic (which
5244 // doesn't try to parse the DNS-1123 shape) fires before the new
5245 // `ChildCaixaInvalid` per-axis gate, so an empty `:caixa` keeps
5246 // its narrower error message — `is_dns_1123_label` would reject
5247 // the empty string too (boundary check on the first byte), but
5248 // the empty-string arm is the more self-locating diagnostic for
5249 // the author. Same ordering discipline as
5250 // `membro_caixa_empty_takes_precedence_over_invalid` in
5251 // aplicacao.rs.
5252 let s = SupervisorSpec {
5253 children: vec![child("", "^0.1", RestartPolicy::Permanent)],
5254 ..SupervisorSpec::default()
5255 };
5256 let err = s.validate().unwrap_err();
5257 assert_eq!(err, SupervisorError::EmptyChildName);
5258 }
5259
5260 #[test]
5261 fn child_caixa_invalid_fires_before_versao_check() {
5262 // Order pin: the per-axis shape gate runs inline before the
5263 // per-entry versao check, so a malformed `:caixa` on an entry
5264 // whose `:versao` would also fail surfaces the more self-
5265 // locating name-axis diagnostic first. Parallel to
5266 // `membro_versao_invalid_fires_before_duplicate_check` (9888b13)
5267 // and `placement_cluster_invalid_fires_before_duplicate_check`
5268 // (6cbb900).
5269 let s = SupervisorSpec {
5270 children: vec![child("My_Worker", "", RestartPolicy::Permanent)],
5271 ..SupervisorSpec::default()
5272 };
5273 let err = s.validate().unwrap_err();
5274 assert!(
5275 matches!(
5276 err,
5277 SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "My_Worker"
5278 ),
5279 "got {err:?}"
5280 );
5281 }
5282
5283 #[test]
5284 fn child_caixa_invalid_fires_before_duplicate_check() {
5285 // Order pin: a malformed name on a non-duplicate entry surfaces
5286 // its own diagnostic, even when a later entry would otherwise
5287 // collapse onto an earlier name. The per-entry shape gate runs
5288 // inline before the duplicate-key HashSet insert, mirroring
5289 // `placement_cluster_invalid_fires_before_duplicate_check`
5290 // (6cbb900).
5291 let s = SupervisorSpec {
5292 children: vec![
5293 child("Worker", "^0.1", RestartPolicy::Permanent),
5294 child("cache", "^0.1", RestartPolicy::Transient),
5295 child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
5296 ],
5297 ..SupervisorSpec::default()
5298 };
5299 let err = s.validate().unwrap_err();
5300 assert!(
5301 matches!(
5302 err,
5303 SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "Worker"
5304 ),
5305 "got {err:?}"
5306 );
5307 }
5308
5309 #[test]
5310 fn child_caixa_invalid_diagnostic_carries_offending_caixa() {
5311 // The diagnostic-shape pin: the error names the offending
5312 // `:caixa` verbatim plus a non-empty parser-shaped `reason` so
5313 // the author can grep their caixa.lisp without re-running the
5314 // build. Mirrors the diagnostic-shape sweep on every prior
5315 // value-shape gate (3f9d7a0, 6cbb900, c7d05ec).
5316 let s = SupervisorSpec {
5317 children: vec![child("My_Worker", "^0.1", RestartPolicy::Permanent)],
5318 ..SupervisorSpec::default()
5319 };
5320 let err = s.validate().unwrap_err();
5321 let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
5322 panic!("expected ChildCaixaInvalid, got other variant");
5323 };
5324 assert_eq!(caixa, "My_Worker");
5325 assert!(
5326 !reason.is_empty(),
5327 "ChildCaixaInvalid `reason` must carry the parser's wording verbatim"
5328 );
5329 }
5330
5331 // ── value-shape: zero restart_window + duplicate child names ──────────
5332
5333 #[test]
5334 fn validate_accepts_none_restart_window() {
5335 // Omitted `:restart-window` is the "never reset" sentinel —
5336 // valid by design. Mirrors :limits axes where None = unbounded.
5337 let s = SupervisorSpec {
5338 restart_window: None,
5339 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5340 ..SupervisorSpec::default()
5341 };
5342 s.validate().unwrap();
5343 }
5344
5345 #[test]
5346 fn validate_rejects_zero_restart_window() {
5347 // Same "0 means the opposite of what you think" footgun closed
5348 // for :politicas :timeout (Envoy treats 0s as infinite) and
5349 // :limits :wall-clock (wasmtime traps before the call starts).
5350 // Erlang/OTP's MaxIntensity/Period requires Period > 0.
5351 let s = SupervisorSpec {
5352 restart_window: Some(Duration::ZERO),
5353 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5354 ..SupervisorSpec::default()
5355 };
5356 assert_eq!(
5357 s.validate().unwrap_err(),
5358 SupervisorError::RestartWindowZero
5359 );
5360 }
5361
5362 // ── value-shape: integer-ms canonical-form on :restart-window ─────────
5363 //
5364 // The fourth (and last) typed-`Duration` axis in caixa-core to get
5365 // the integer-millisecond canonical-form gate — peer with
5366 // `:limits :wall-clock` (82fc3ef), `:politicas :timeout` (a4ae535),
5367 // and `:politicas :circuit-breaker :window` (a4ae535). The serde
5368 // path is already gated at the shared codec layer (see
5369 // `restart_window_serde_rejects_fractional_seconds`); this arm
5370 // closes the programmatic-struct-literal path the codec gate can't
5371 // see.
5372
5373 #[test]
5374 fn validate_rejects_sub_millisecond_restart_window() {
5375 // The fail-before-pass-after pin: a programmatic
5376 // `Duration::from_micros(1500)` (= 1_500_000 ns) silently passed
5377 // `validate` on every pre-gate codebase, then truncated to
5378 // `as_millis() == 1` on first serialize — the shared codec
5379 // emits `"1ms"`, parses it back to `Duration::from_millis(1)` =
5380 // 1_000_000 ns, the typed `restart_window` no longer matches
5381 // its rendered form.
5382 let s = SupervisorSpec {
5383 restart_window: Some(Duration::from_micros(1500)),
5384 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5385 ..SupervisorSpec::default()
5386 };
5387 match s.validate().unwrap_err() {
5388 SupervisorError::RestartWindowNotCanonical { window } => {
5389 assert_eq!(window, Duration::from_micros(1500));
5390 }
5391 other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
5392 }
5393 }
5394
5395 #[test]
5396 fn validate_rejects_one_nanosecond_restart_window() {
5397 // The far-sub-ms case: `Duration::from_nanos(1)` is non-zero
5398 // (so `RestartWindowZero` doesn't fire) but `as_millis() == 0`,
5399 // so the shared codec emits the literal `"0s"` — the next
5400 // serde round-trip would parse back to `Duration::ZERO`, which
5401 // the `RestartWindowZero` arm then rejects on re-validate. The
5402 // canonical-form gate at this layer surfaces a self-locating
5403 // diagnostic naming the offending Duration verbatim rather
5404 // than a downstream `RestartWindowZero` whose remediation
5405 // points at omitting the slot.
5406 let s = SupervisorSpec {
5407 restart_window: Some(Duration::from_nanos(1)),
5408 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5409 ..SupervisorSpec::default()
5410 };
5411 match s.validate().unwrap_err() {
5412 SupervisorError::RestartWindowNotCanonical { window } => {
5413 assert_eq!(window, Duration::from_nanos(1));
5414 }
5415 other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
5416 }
5417 }
5418
5419 #[test]
5420 fn validate_rejects_nanosecond_past_canonical_boundary_restart_window() {
5421 // The 1-ns-past-1ms boundary case: a `Duration` carrying
5422 // 1_000_001 ns is structurally past the integer-ms granularity
5423 // floor — `subsec_nanos() % 1_000_000 == 1`. The codec round-
5424 // trip would truncate to `1ms` and the consumer would observe
5425 // a 1-ns drift on every emit. Same boundary the peer
5426 // `validate_rejects_nanosecond_past_canonical_boundary` test
5427 // in limits.rs pins for the `:limits :wall-clock` axis.
5428 let w = Duration::from_nanos(1_000_001);
5429 let s = SupervisorSpec {
5430 restart_window: Some(w),
5431 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5432 ..SupervisorSpec::default()
5433 };
5434 assert_eq!(
5435 s.validate().unwrap_err(),
5436 SupervisorError::RestartWindowNotCanonical { window: w }
5437 );
5438 }
5439
5440 #[test]
5441 fn validate_accepts_integer_millisecond_restart_window_values() {
5442 // The positive-control sweep: every `Duration` the shared
5443 // codec can round-trip losslessly — the canonical
5444 // `<integer>{ms,s,m,h}` set the codec's `render` / `parse`
5445 // pair emits and accepts — passes `validate` without
5446 // surfacing the new canonical-form arm. Mirrors
5447 // `validate_accepts_integer_millisecond_wall_clock_values` on
5448 // the sibling `:limits :wall-clock` axis.
5449 for w in [
5450 Duration::from_millis(1),
5451 Duration::from_millis(500),
5452 Duration::from_millis(1500),
5453 Duration::from_secs(1),
5454 Duration::from_secs(30),
5455 Duration::from_secs(60),
5456 Duration::from_secs(120),
5457 Duration::from_secs(3600),
5458 ] {
5459 let s = SupervisorSpec {
5460 restart_window: Some(w),
5461 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5462 ..SupervisorSpec::default()
5463 };
5464 s.validate()
5465 .unwrap_or_else(|e| panic!("integer-ms {w:?} must validate, got {e:?}"));
5466 }
5467 }
5468
5469 #[test]
5470 fn validate_restart_window_zero_takes_precedence_over_canonical_gate() {
5471 // Cross-arm ordering pin: `Duration::ZERO` has
5472 // `subsec_nanos() == 0` and would otherwise pass the
5473 // canonical-form arm — the zero-floor arm must fire first so
5474 // the more self-locating `RestartWindowZero` diagnostic (with
5475 // its omit-axis remediation directly named) leads. Same
5476 // posture every peer zero-then-shape gate uses
5477 // (`WallClockZero` → `WallClockNotCanonical`,
5478 // `PolicyTimeoutZero` → `PolicyTimeoutNotCanonical`,
5479 // `PolicyBreakerZeroWindow` → `PolicyBreakerWindowNotCanonical`).
5480 let s = SupervisorSpec {
5481 restart_window: Some(Duration::ZERO),
5482 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5483 ..SupervisorSpec::default()
5484 };
5485 assert_eq!(
5486 s.validate().unwrap_err(),
5487 SupervisorError::RestartWindowZero
5488 );
5489 }
5490
5491 #[test]
5492 fn restart_window_canonical_diagnostic_carries_offending_duration() {
5493 // Diagnostic-shape pin: the canonical-form arm names the
5494 // offending `Duration` verbatim so the author's grep lands on
5495 // the field's value, not a generic "duration not canonical"
5496 // message. Same shape every other typed-canonical-form arm
5497 // on this surface carries (`WallClockNotCanonical` carries
5498 // the offending `Duration` verbatim,
5499 // `PolicyTimeoutNotCanonical` carries the offending
5500 // `Duration` verbatim).
5501 let w = Duration::from_micros(500);
5502 let s = SupervisorSpec {
5503 restart_window: Some(w),
5504 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5505 ..SupervisorSpec::default()
5506 };
5507 let err = s.validate().unwrap_err();
5508 let msg = err.to_string();
5509 assert!(
5510 msg.contains("500"),
5511 "diagnostic must carry the offending magnitude verbatim (got {msg:?})"
5512 );
5513 assert!(
5514 msg.contains("sub-millisecond"),
5515 "diagnostic must name the sub-millisecond residue class (got {msg:?})"
5516 );
5517 }
5518
5519 #[test]
5520 fn restart_window_validated_value_round_trips_through_codec() {
5521 // The structural property the canonical-ms gate enforces:
5522 // every `SupervisorSpec::restart_window` past
5523 // `SupervisorSpec::validate` round-trips losslessly through
5524 // the shared duration codec (serialize → string →
5525 // deserialize → equal value). Pin this end-to-end so a future
5526 // change to either side (the validate gate's accepted
5527 // granularity, the codec's parse/render unit set) that breaks
5528 // the alignment surfaces here. Peer of
5529 // `wall_clock_validated_value_round_trips_through_codec` on
5530 // the sibling `:limits :wall-clock` axis.
5531 for w in [
5532 Duration::from_millis(1),
5533 Duration::from_millis(1500),
5534 Duration::from_secs(30),
5535 Duration::from_secs(3600),
5536 ] {
5537 let s = SupervisorSpec {
5538 restart_window: Some(w),
5539 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5540 ..SupervisorSpec::default()
5541 };
5542 s.validate().unwrap();
5543 let json = serde_json::to_string(&s).unwrap();
5544 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5545 assert_eq!(back.restart_window, Some(w));
5546 }
5547 }
5548
5549 // ── value-shape: upper cap on :restart-window ─────────────────────────
5550 //
5551 // The fourth (and last) typed-`Duration` axis in caixa-core to get
5552 // the 1h upper cap — peer with `:limits :wall-clock` (51e0dbd),
5553 // `:politicas :timeout` (2e8ee7e), and `:politicas
5554 // :circuit-breaker :window` (379a814). Brackets the typed
5555 // `:restart-window` axis structurally: every validated value lies
5556 // in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`, integer-millisecond
5557 // granularity, closing the
5558 // rolling-window-degenerates-to-lifetime-counter footgun the prior
5559 // zero-floor-and-canonical-form-only checks left open.
5560
5561 #[test]
5562 fn validate_rejects_restart_window_above_cap() {
5563 // The fail-before-pass-after pin: 3601s = 1h + 1s is
5564 // structurally one canonical-tick past the
5565 // [`SUPERVISOR_RESTART_WINDOW_MAX`] ceiling (1h = 3600s) — an
5566 // integer-millisecond magnitude the canonical-form arm above
5567 // accepts cleanly, that the shared duration codec round-trips
5568 // losslessly as `"3601s"`, and that silently passed validate on
5569 // every pre-gate codebase because the typed slot's only checks
5570 // were the zero-floor and canonical-form arms. The runtime
5571 // substrate consuming the value (Erlang/OTP's MaxIntensity/
5572 // Period reconciler, the future wasm-operator's per-supervisor
5573 // restart-intensity counter) reaches for a `Duration` so long
5574 // no realistic restart-recovery pattern resets the counter,
5575 // far from the source caixa.lisp.
5576 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
5577 let s = SupervisorSpec {
5578 restart_window: Some(w),
5579 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5580 ..SupervisorSpec::default()
5581 };
5582 assert_eq!(
5583 s.validate().unwrap_err(),
5584 SupervisorError::RestartWindowExceedsCap { window: w }
5585 );
5586 }
5587
5588 #[test]
5589 fn validate_rejects_restart_window_one_millisecond_above_cap() {
5590 // Boundary case: exactly 1ms past the cap (the granularity the
5591 // canonical-form gate enforces). Catches a future "strictly
5592 // less than" half-measure and pins the diagnostic to name the
5593 // offending `Duration` verbatim. Peer of
5594 // `validate_rejects_wall_clock_one_millisecond_above_cap` /
5595 // `rejects_policy_timeout_one_millisecond_above_cap` /
5596 // `rejects_circuit_breaker_window_one_millisecond_above_cap`
5597 // on the sibling typed-`Duration` axes' top edges.
5598 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
5599 let s = SupervisorSpec {
5600 restart_window: Some(w),
5601 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5602 ..SupervisorSpec::default()
5603 };
5604 assert_eq!(
5605 s.validate().unwrap_err(),
5606 SupervisorError::RestartWindowExceedsCap { window: w }
5607 );
5608 }
5609
5610 #[test]
5611 fn validate_rejects_restart_window_far_above_cap() {
5612 // The "obvious authoring footgun" case: a `(:restart-window "24h")`,
5613 // `(:restart-window "7d")`, or any "I want a lifetime counter
5614 // but wrote a `<integer>h` magnitude anyway" typo — values the
5615 // canonical-form arm accepts as integer-millisecond magnitudes,
5616 // the codec round-trips losslessly through serde, but the
5617 // operator's `MaxIntensity / Period` reconciler cannot honor
5618 // as a meaningful rolling window. Until this gate landed
5619 // validate accepted them. Pin the common above-cap values (24h,
5620 // 7d, ~11.5d) so a future relaxation that drops the upper bound
5621 // surfaces here.
5622 for w in [
5623 Duration::from_secs(86_400), // 24h
5624 Duration::from_secs(604_800), // 7d
5625 Duration::from_secs(1_000_000), // ~11.5 days
5626 ] {
5627 let s = SupervisorSpec {
5628 restart_window: Some(w),
5629 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5630 ..SupervisorSpec::default()
5631 };
5632 assert_eq!(
5633 s.validate().unwrap_err(),
5634 SupervisorError::RestartWindowExceedsCap { window: w }
5635 );
5636 }
5637 }
5638
5639 #[test]
5640 fn validate_accepts_restart_window_at_cap() {
5641 // The boundary value — exactly [`SUPERVISOR_RESTART_WINDOW_MAX`]
5642 // (1h) — must validate. The cap is inclusive on the top edge,
5643 // matching the [`crate::LIMITS_WALL_CLOCK_MAX`] /
5644 // [`crate::POLICY_TIMEOUT_MAX`] /
5645 // [`crate::POLICY_BREAKER_WINDOW_MAX`] discipline on the sibling
5646 // capped axes. Pin the boundary explicitly so a future
5647 // off-by-one tightening (`>= SUPERVISOR_RESTART_WINDOW_MAX`
5648 // instead of `>`) surfaces here as a test failure rather than a
5649 // silent contract narrowing.
5650 let s = SupervisorSpec {
5651 restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
5652 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5653 ..SupervisorSpec::default()
5654 };
5655 s.validate()
5656 .expect("restart_window == SUPERVISOR_RESTART_WINDOW_MAX must validate");
5657 }
5658
5659 #[test]
5660 fn validate_accepts_restart_window_typical_values() {
5661 // The documented Erlang/OTP / Elixir / Riak Core / RabbitMQ
5662 // per-supervisor production-playbook band positive-control
5663 // sweep — every value Learn You Some Erlang's `{intensity, 5,
5664 // 60}` worker-supervisor `Period = 60s` default, Elixir's
5665 // `Supervisor` `max_seconds: 5` default, OTP's `supervisor`
5666 // callback module `MaxT = 5..=60` typical, Riak Core's `MaxT ∈
5667 // 10s..=300s`, and RabbitMQ broker-supervisor `MaxT = 5s`
5668 // default recommend (5s..=300s) must pass, plus a sweep
5669 // through the long-tail-flaky-pool band (5m, 15m, 30m, 1h) the
5670 // cap accepts. Mirrors `validate_accepts_wall_clock_typical_values`
5671 // on the sibling `:limits :wall-clock` axis.
5672 for w in [
5673 Duration::from_millis(1),
5674 Duration::from_millis(500),
5675 Duration::from_secs(1),
5676 Duration::from_secs(5), // RabbitMQ broker-supervisor default
5677 Duration::from_secs(10), // Riak Core lower
5678 Duration::from_secs(30),
5679 Duration::from_secs(60), // Learn You Some Erlang default
5680 Duration::from_secs(120), // OTP supervisor MaxT typical
5681 Duration::from_secs(300), // Riak Core upper
5682 Duration::from_secs(900), // 15m
5683 Duration::from_secs(1800),
5684 Duration::from_secs(3600), // exactly 1h, the cap
5685 ] {
5686 let s = SupervisorSpec {
5687 restart_window: Some(w),
5688 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5689 ..SupervisorSpec::default()
5690 };
5691 s.validate()
5692 .unwrap_or_else(|e| panic!("restart_window={w:?} must validate; got {e:?}"));
5693 }
5694 }
5695
5696 #[test]
5697 fn restart_window_zero_takes_precedence_over_cap() {
5698 // The cross-arm ordering pin: `Duration::ZERO` is structurally
5699 // outside both `>= 1ms` (zero-floor) and `<=
5700 // SUPERVISOR_RESTART_WINDOW_MAX` (cap), but the zero-floor
5701 // diagnostic is the more self-locating one (it directly names
5702 // the omit-axis remediation), so the validate gate must fire
5703 // on zero first. Same shape every other zero-then-cap ordering
5704 // on this surface uses (`WallClockZero` then
5705 // `WallClockExceedsCap`, `PolicyTimeoutZero` then
5706 // `PolicyTimeoutExceedsCap`, `PolicyBreakerZeroWindow` then
5707 // `PolicyBreakerWindowExceedsCap`).
5708 let s = SupervisorSpec {
5709 restart_window: Some(Duration::ZERO),
5710 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5711 ..SupervisorSpec::default()
5712 };
5713 assert_eq!(
5714 s.validate().unwrap_err(),
5715 SupervisorError::RestartWindowZero,
5716 "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
5717 );
5718 }
5719
5720 #[test]
5721 fn restart_window_canonical_takes_precedence_over_cap() {
5722 // The cross-arm ordering pin: a `Duration` that is *both*
5723 // sub-millisecond (non-canonical-form) and structurally above
5724 // the cap surfaces the canonical-form diagnostic first,
5725 // because the round-trip-shape break is the more fundamental
5726 // issue (the value can't even round-trip through the codec,
5727 // so the cap diagnostic naming `1ms..=1h` would be misleading
5728 // — there's no integer-ms form of the offending value). Pin
5729 // the order so a future refactor that reorders the arms
5730 // surfaces here as a test failure rather than a silent
5731 // diagnostic regression. Peer of
5732 // `wall_clock_canonical_takes_precedence_over_cap` /
5733 // `policy_timeout_canonical_takes_precedence_over_cap`.
5734 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_nanos(1);
5735 let s = SupervisorSpec {
5736 restart_window: Some(w),
5737 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5738 ..SupervisorSpec::default()
5739 };
5740 assert_eq!(
5741 s.validate().unwrap_err(),
5742 SupervisorError::RestartWindowNotCanonical { window: w },
5743 "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
5744 );
5745 }
5746
5747 #[test]
5748 fn max_restarts_cap_takes_precedence_over_restart_window_cap() {
5749 // The cross-arm ordering pin between the `:max-restarts` cap
5750 // and the sibling `:restart-window` cap. A supervisor carrying
5751 // both an over-cap `max_restarts` AND an over-cap window must
5752 // surface the `MaxRestartsExceedsCap` diagnostic first — the
5753 // cap arm is wired immediately after the zero-restart arm and
5754 // strictly before every window-axis arm (zero / canonical /
5755 // cap), so the offending value the diagnostic names matches
5756 // the order the author would discover the gates by reading
5757 // top-to-bottom through `SupervisorSpec::validate`. Pin the
5758 // order so a future refactor that reorders the arms surfaces
5759 // here as a test failure rather than a silent diagnostic
5760 // regression. Peer of
5761 // `max_restarts_cap_takes_precedence_over_restart_window_gates`
5762 // on the sibling zero / canonical window arms.
5763 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
5764 let s = SupervisorSpec {
5765 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5766 restart_window: Some(w),
5767 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5768 ..SupervisorSpec::default()
5769 };
5770 assert_eq!(
5771 s.validate().unwrap_err(),
5772 SupervisorError::MaxRestartsExceedsCap {
5773 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5774 },
5775 "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
5776 );
5777 }
5778
5779 #[test]
5780 fn restart_window_cap_diagnostic_carries_offending_value() {
5781 // The diagnostic-shape pin: the offending `Duration` is
5782 // carried verbatim into the
5783 // [`SupervisorError::RestartWindowExceedsCap`] variant so the
5784 // surfaced error message names the value the author wrote,
5785 // not just the cap. Same self-locating diagnostic shape every
5786 // other typed-cap arm on this surface carries
5787 // (`WallClockExceedsCap` carries the offending `Duration`
5788 // verbatim, `PolicyTimeoutExceedsCap` carries the offending
5789 // `Duration` verbatim, `PolicyBreakerWindowExceedsCap` carries
5790 // the offending `Duration` verbatim).
5791 let w = Duration::from_secs(7200); // 2h
5792 let s = SupervisorSpec {
5793 restart_window: Some(w),
5794 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5795 ..SupervisorSpec::default()
5796 };
5797 let err = s.validate().unwrap_err();
5798 assert!(
5799 matches!(err, SupervisorError::RestartWindowExceedsCap { window } if window == w),
5800 "got {err:?}"
5801 );
5802 let msg = err.to_string();
5803 assert!(
5804 msg.contains("7200"),
5805 ":supervisor :restart-window cap diagnostic must carry the offending value verbatim (got: {msg})"
5806 );
5807 }
5808
5809 #[test]
5810 fn supervisor_restart_window_cap_pins_canonical_value() {
5811 // The SUPERVISOR_RESTART_WINDOW_MAX constant pins the value at
5812 // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
5813 // shared duration codec emits as a clean canonical string
5814 // (`"<n>h"`). Pinning the literal value here surfaces a future
5815 // drift (a relaxation to 24h, a tightening to 5m) as a
5816 // deliberate test edit, not a silent contract narrowing.
5817 //
5818 // The four typed-`Duration` caps on the validation surface
5819 // (`LIMITS_WALL_CLOCK_MAX` per-process, `POLICY_TIMEOUT_MAX`
5820 // per-edge, `POLICY_BREAKER_WINDOW_MAX` per-breaker,
5821 // `SUPERVISOR_RESTART_WINDOW_MAX` per-supervisor) share a
5822 // single uniform top edge at the codec's largest emitted unit
5823 // — a structural-property invariant the equality assertions
5824 // here enshrine, so a future drift on any of the four
5825 // surfaces as a deliberate test edit. Same shape every other
5826 // typed-cap value pin uses
5827 // (`wall_clock_cap_pins_canonical_value`,
5828 // `policy_timeout_cap_pins_canonical_value`,
5829 // `circuit_breaker_window_cap_pins_canonical_value`).
5830 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, Duration::from_secs(3600));
5831 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX.as_millis(), 3_600_000);
5832 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::LIMITS_WALL_CLOCK_MAX);
5833 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::POLICY_TIMEOUT_MAX);
5834 assert_eq!(
5835 SUPERVISOR_RESTART_WINDOW_MAX,
5836 crate::POLICY_BREAKER_WINDOW_MAX
5837 );
5838 }
5839
5840 #[test]
5841 fn restart_window_cap_value_round_trips_through_codec() {
5842 // The codec round-trip property the cap arm preserves: the
5843 // [`SUPERVISOR_RESTART_WINDOW_MAX`] constant itself round-trips
5844 // through the shared duration codec — every value at the cap
5845 // serializes to the canonical `"1h"` form and parses back
5846 // identically. Pin the round-trip so a future change to the
5847 // codec's unit set or to the cap's magnitude that breaks the
5848 // round-trip property surfaces here. Peer of
5849 // `wall_clock_cap_value_round_trips_through_codec` on the
5850 // sibling `:limits :wall-clock` axis.
5851 let s = SupervisorSpec {
5852 restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
5853 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5854 ..SupervisorSpec::default()
5855 };
5856 s.validate().unwrap();
5857 let json = serde_json::to_string(&s).unwrap();
5858 assert!(
5859 json.contains("\"1h\""),
5860 "SUPERVISOR_RESTART_WINDOW_MAX must serialize to the canonical `\"1h\"` form (got {json})"
5861 );
5862 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5863 assert_eq!(back.restart_window, Some(SUPERVISOR_RESTART_WINDOW_MAX));
5864 }
5865
5866 #[test]
5867 fn validate_rejects_duplicate_child_caixa() {
5868 // Two children with the same :caixa render to two ComputeUnits
5869 // with the same name in the cluster's HelmRelease values —
5870 // one silently overwrites the other. Erlang/OTP's child_spec.id
5871 // is required-unique per supervisor; same set-not-multiset
5872 // discipline applied here as for :membros / :placement
5873 // :clusters / :entrada :paths.
5874 let s = SupervisorSpec {
5875 children: vec![
5876 child("worker", "^0.1", RestartPolicy::Permanent),
5877 child("cache", "^0.1", RestartPolicy::Transient),
5878 child("worker", "^0.2", RestartPolicy::Permanent),
5879 ],
5880 ..SupervisorSpec::default()
5881 };
5882 let err = s.validate().unwrap_err();
5883 assert!(
5884 matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "worker"),
5885 "got {err:?}"
5886 );
5887 }
5888
5889 #[test]
5890 fn validate_duplicate_child_diagnostic_names_first_collision() {
5891 // Iteration walks the :children list in declaration order —
5892 // the diagnostic names the first repeat, deterministically,
5893 // even when multiple names duplicate.
5894 let s = SupervisorSpec {
5895 children: vec![
5896 child("a", "^0.1", RestartPolicy::Permanent),
5897 child("b", "^0.1", RestartPolicy::Permanent),
5898 child("a", "^0.1", RestartPolicy::Permanent),
5899 child("b", "^0.1", RestartPolicy::Permanent),
5900 ],
5901 ..SupervisorSpec::default()
5902 };
5903 let err = s.validate().unwrap_err();
5904 assert!(
5905 matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "a"),
5906 "got {err:?}"
5907 );
5908 }
5909
5910 // ── self-supervision cross-slot gate ──────────────────────────
5911
5912 #[test]
5913 fn validate_no_self_supervision_rejects_self_referential_child() {
5914 // A supervisor whose `:children` lists its own `:nome` is a
5915 // one-node reconciliation cycle — rejected, naming the parent.
5916 let children = vec![
5917 child("worker", "^0.1", RestartPolicy::Permanent),
5918 child("orquestra", "^0.1", RestartPolicy::Permanent),
5919 ];
5920 let err = validate_no_self_supervision(&children, "orquestra").unwrap_err();
5921 assert!(
5922 matches!(err, SupervisorError::ChildSupervisesSelf { ref caixa } if caixa == "orquestra"),
5923 "got {err:?}"
5924 );
5925 }
5926
5927 #[test]
5928 fn validate_no_self_supervision_accepts_distinct_children() {
5929 // Positive control: distinct child names (including a child that
5930 // is itself a supervisor — nested trees are valid OTP) pass.
5931 let children = vec![
5932 child("worker", "^0.1", RestartPolicy::Permanent),
5933 child("sub-tree", "^0.1", RestartPolicy::Permanent),
5934 ];
5935 validate_no_self_supervision(&children, "orquestra").unwrap();
5936 }
5937
5938 #[test]
5939 fn validate_no_self_supervision_empty_children_is_ok() {
5940 // SimpleOneForOne / no-static-children supervisors have nothing
5941 // to self-reference — the gate is vacuously satisfied.
5942 validate_no_self_supervision(&[], "orquestra").unwrap();
5943 }
5944
5945 #[test]
5946 fn validate_simple_one_for_one_skips_uniqueness_check() {
5947 // SimpleOneForOne supervisors carry no static children — the
5948 // duplicate-child loop never runs. A zero-window declaration
5949 // on a SimpleOneForOne supervisor still trips the window check
5950 // (window applies to dynamic children too).
5951 let s = SupervisorSpec {
5952 estrategia: RestartStrategy::SimpleOneForOne,
5953 restart_window: None,
5954 children: vec![],
5955 ..SupervisorSpec::default()
5956 };
5957 s.validate().unwrap();
5958 let s_zero = SupervisorSpec {
5959 estrategia: RestartStrategy::SimpleOneForOne,
5960 restart_window: Some(Duration::ZERO),
5961 children: vec![],
5962 ..SupervisorSpec::default()
5963 };
5964 assert_eq!(
5965 s_zero.validate().unwrap_err(),
5966 SupervisorError::RestartWindowZero
5967 );
5968 }
5969
5970 #[test]
5971 fn validate_zero_window_runs_after_max_restarts_check() {
5972 // Pin the order: max_restarts == 0 fires before
5973 // restart_window == 0s, so an author with both wrong sees the
5974 // counter-axis diagnostic first (matches the order in the
5975 // struct and in the doc comment).
5976 let s = SupervisorSpec {
5977 max_restarts: 0,
5978 restart_window: Some(Duration::ZERO),
5979 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5980 ..SupervisorSpec::default()
5981 };
5982 assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
5983 }
5984
5985 #[test]
5986 fn round_trip_all_strategies() {
5987 for &strat in RestartStrategy::ALL {
5988 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
5989 // shape partition through the [`gen_platform::IsVariant`]
5990 // derive-generated [`RestartStrategy::is_simple_one_for_one`]
5991 // predicate rather than the raw
5992 // `matches!(strat, RestartStrategy::SimpleOneForOne)`
5993 // open-coded pattern-match — same closed-set-typed-enum
5994 // arm-discriminator dispatch discipline the sibling
5995 // [`crate::upgrade::UpgradeInstruction::is_restart`] convergence
5996 // (915a934) extended onto its two paired positive / negated
5997 // `matches!` filter sites, and the sibling
5998 // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
5999 // predicate convergence (766ec63) extended onto the M3 mesh-
6000 // slot per-`:placement` distribution-strategy `matches!`
6001 // discriminator axis. See the sibling
6002 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
6003 // fixture and the peer `manifest::tests::
6004 // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
6005 // fixture — all three sites (the last unlifted
6006 // `matches!`-based arm-discriminator axis on the OTP-shape
6007 // supervisor sibling-restart-strategy closed-set typed enum,
6008 // acknowledged in 915a934's Prior-commits footnote as the
6009 // outstanding follow-up) now consult one typed dispatch on
6010 // the substrate primitive.
6011 let s = SupervisorSpec {
6012 estrategia: strat,
6013 children: if strat.is_simple_one_for_one() {
6014 vec![]
6015 } else {
6016 vec![child("w", "^0.1", RestartPolicy::Permanent)]
6017 },
6018 ..SupervisorSpec::default()
6019 };
6020 let json = serde_json::to_string(&s).unwrap();
6021 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6022 assert_eq!(s, back);
6023 }
6024 }
6025
6026 #[test]
6027 fn round_trip_all_restart_policies() {
6028 for policy in [
6029 RestartPolicy::Permanent,
6030 RestartPolicy::Temporary,
6031 RestartPolicy::Transient,
6032 ] {
6033 let c = child("w", "^0.1", policy);
6034 let json = serde_json::to_string(&c).unwrap();
6035 let back: ChildSpec = serde_json::from_str(&json).unwrap();
6036 assert_eq!(c, back);
6037 }
6038 }
6039
6040 #[test]
6041 fn restart_strategy_is_simple_one_for_one_predicate_partitions_the_arm_set() {
6042 // The fail-before-pass-after pin on the `gen_platform::IsVariant`
6043 // derive's [`RestartStrategy::is_simple_one_for_one`] arm-
6044 // discriminator predicate: [`RestartStrategy::SimpleOneForOne`]
6045 // is the only variant that satisfies `.is_simple_one_for_one()`;
6046 // every static-children-bearing arm (`OneForOne` / `OneForAll`
6047 // / `RestForOne`) returns `false`. This pin makes the partition
6048 // invariant load-bearing at caixa-core test time so a future
6049 // derive regression (a hole that returns `false` for
6050 // `SimpleOneForOne` too, or a byte-collision that flips a second
6051 // variant to `true`) trips here rather than laundering the arm
6052 // at the three test-fixture builder sites (a hole flips the
6053 // `SimpleOneForOne` fixture to carry a non-empty children list
6054 // and the subsequent `SupervisorSpec::validate` would refuse the
6055 // fixture with [`SupervisorError::SimpleOneForOneWithStaticChildren`];
6056 // a collision flips a peer strategy's fixture to carry an empty
6057 // children list and the subsequent `validate` would refuse with
6058 // [`SupervisorError::NoChildren`] — either way, the pin fires
6059 // here, at the derive site, rather than at the fixture-refusal
6060 // site far away). Peer of the sibling
6061 // [`crate::upgrade::tests::upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
6062 // (915a934) pin on the M2 OTP-appup axis and the sibling
6063 // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
6064 // pin on the M0 `:kind` axis.
6065 let cases: &[(RestartStrategy, bool)] = &[
6066 (RestartStrategy::OneForOne, false),
6067 (RestartStrategy::OneForAll, false),
6068 (RestartStrategy::RestForOne, false),
6069 (RestartStrategy::SimpleOneForOne, true),
6070 ];
6071 for (variant, expected) in cases {
6072 assert_eq!(
6073 variant.is_simple_one_for_one(),
6074 *expected,
6075 "RestartStrategy::{variant:?}.is_simple_one_for_one() must \
6076 return {expected} (partition invariant on the \
6077 IsVariant-derived arm-discriminator predicate — every \
6078 test-fixture site that partitions the `:children` slot \
6079 shape on `SimpleOneForOne ↔ non-SimpleOneForOne` keys \
6080 off this typed dispatch, so a derive regression must \
6081 surface here rather than at the fixture-refusal site)"
6082 );
6083 }
6084 }
6085
6086 #[test]
6087 fn restart_strategy_fixture_partition_routes_through_is_simple_one_for_one_predicate() {
6088 // Byte-identity pin on the `SimpleOneForOne ↔ non-SimpleOneForOne`
6089 // fixture-shape partition against the pre-lift
6090 // `matches!(strat, RestartStrategy::SimpleOneForOne)` open-coded
6091 // pattern-match every test-fixture builder site previously
6092 // coupled to inline. Asserts the two projections agree byte-for-
6093 // byte on every arm of the enum, so a future derive regression
6094 // that flipped either predicate's arm-set would surface here at
6095 // caixa-core test time rather than at the three fixture-builder
6096 // sites (`supervisor::tests::round_trip_all_strategies`,
6097 // `supervisor::tests::supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`,
6098 // `manifest::tests::caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`)
6099 // far from the derive site. Same peer-shape byte-identity pin
6100 // every sibling `IsVariant`-derive-routed convergence carries on
6101 // the substrate's closed-set typed-enum surface (peer of
6102 // [`crate::upgrade::tests::validate_restart_exclusive_routes_through_is_restart_predicate`]
6103 // on the M2 OTP-appup axis).
6104 for &strat in RestartStrategy::ALL {
6105 let via_predicate = strat.is_simple_one_for_one();
6106 let via_matches = matches!(strat, RestartStrategy::SimpleOneForOne);
6107 assert_eq!(
6108 via_predicate, via_matches,
6109 "RestartStrategy::{strat:?}: is_simple_one_for_one() must \
6110 byte-equal matches!(_, RestartStrategy::SimpleOneForOne) — \
6111 the pre-lift open-coded pattern and the \
6112 IsVariant-derived predicate are the same axis, \
6113 one typed dispatch"
6114 );
6115 }
6116 }
6117
6118 #[test]
6119 fn duration_codec_round_trip_canonical_units() {
6120 // Note the canonical-form rule: durations serialize to the
6121 // *largest* unit that divides cleanly, so 60s ↔ "1m" and not
6122 // "60s" — but the round-trip preserves the underlying Duration.
6123 let cases = [
6124 ("30s", Duration::from_secs(30)),
6125 ("5m", Duration::from_secs(300)),
6126 ("1h", Duration::from_secs(3600)),
6127 ("500ms", Duration::from_millis(500)),
6128 ];
6129 for (lit, dur) in cases {
6130 let s = SupervisorSpec {
6131 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6132 restart_window: Some(dur),
6133 ..SupervisorSpec::default()
6134 };
6135 let json = serde_json::to_string(&s).unwrap();
6136 assert!(
6137 json.contains(&format!("\"{lit}\"")),
6138 "expected \"{lit}\" in {json}"
6139 );
6140 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6141 assert_eq!(back.restart_window, Some(dur));
6142 }
6143 }
6144
6145 #[test]
6146 fn duration_canonicalizes_to_largest_unit() {
6147 // 60 seconds → "1m" (largest cleanly-divisible unit), but the
6148 // typed Duration still equals 60s on the way back.
6149 let s = SupervisorSpec {
6150 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6151 restart_window: Some(Duration::from_secs(60)),
6152 ..SupervisorSpec::default()
6153 };
6154 let json = serde_json::to_string(&s).unwrap();
6155 assert!(json.contains("\"1m\""), "{json}");
6156 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6157 assert_eq!(back.restart_window, Some(Duration::from_secs(60)));
6158 }
6159
6160 #[test]
6161 fn three_child_one_for_one_validates() {
6162 let s = SupervisorSpec {
6163 estrategia: RestartStrategy::OneForOne,
6164 max_restarts: 5,
6165 restart_window: Some(Duration::from_secs(60)),
6166 children: vec![
6167 child("worker", "^0.1", RestartPolicy::Permanent),
6168 child("cache", "^0.1", RestartPolicy::Transient),
6169 child("scratch", "^0.1", RestartPolicy::Temporary),
6170 ],
6171 };
6172 s.validate().unwrap();
6173 }
6174
6175 #[test]
6176 fn json_uses_pascal_case_for_strategy_and_policy() {
6177 // Variant names are PascalCase by default in serde, matching
6178 // tatara-lisp's enum convention (`:estrategia OneForOne`).
6179 let c = child("w", "^0.1", RestartPolicy::Permanent);
6180 let json = serde_json::to_string(&c).unwrap();
6181 assert!(json.contains("\"Permanent\""));
6182 assert!(!json.contains("\"permanent\""));
6183
6184 let s = SupervisorSpec {
6185 estrategia: RestartStrategy::OneForOne,
6186 children: vec![c],
6187 ..SupervisorSpec::default()
6188 };
6189 let json = serde_json::to_string(&s).unwrap();
6190 assert!(json.contains("\"estrategia\":\"OneForOne\""));
6191 }
6192
6193 // ── shared duration codec: integer-magnitude canonical-form gate ──
6194 //
6195 // The gate lifts the discipline `crate::limits::parse_duration`
6196 // (818dd38) carries on the peer `:limits :wall-clock` codec onto
6197 // the shared codec backing the remaining three typed-duration
6198 // slots: `:supervisor :restart-window`, `:politicas :timeout`, and
6199 // `:politicas :circuit-breaker :window`. Every magnitude `render`
6200 // emits is a non-negative integer with no decimal point and no
6201 // leading sign, so the codec's accepted set must match for
6202 // serialize/deserialize to round-trip without canonical-form
6203 // drift.
6204
6205 #[test]
6206 fn parse_accepts_integer_canonical_units() {
6207 // Pin the happy-path: every canonical author shape `render`
6208 // ever emits parses to the same `Duration` value, so the
6209 // codec's accepted set is at least a superset of its emitted
6210 // set on the canonical-unit axis.
6211 for (lit, dur) in [
6212 ("30s", Duration::from_secs(30)),
6213 ("500ms", Duration::from_millis(500)),
6214 ("2m", Duration::from_secs(120)),
6215 ("1h", Duration::from_secs(3600)),
6216 ("0s", Duration::ZERO),
6217 ] {
6218 assert_eq!(
6219 duration_codec::parse(lit).unwrap(),
6220 dur,
6221 "parse({lit:?}) should be {dur:?}"
6222 );
6223 }
6224 }
6225
6226 #[test]
6227 fn parse_accepts_bare_integer_as_seconds() {
6228 // The `"s" | ""` arm: a bare integer with no unit is read as
6229 // seconds. Pin this so the unit-empty form keeps parsing (it
6230 // renders to `"<n>s"` on serialize — that's a unit-choice
6231 // drift the integer-magnitude gate does NOT close, matching
6232 // the `parse_byte_size` `"1024"` → `"1KiB"` scope decision in
6233 // the peer `:limits :memory` codec).
6234 assert_eq!(
6235 duration_codec::parse("30").unwrap(),
6236 Duration::from_secs(30)
6237 );
6238 }
6239
6240 #[test]
6241 fn parse_rejects_fractional_seconds_with_canonical_form_diagnostic() {
6242 // `"1.5s"` parses as f64 to 1.5 → renders back as `"1500ms"`
6243 // on first serialize — DRIFT. The integer-magnitude gate names
6244 // the offending `"1.5"` verbatim and points at the canonical
6245 // remediation `"1500ms"`.
6246 let err = duration_codec::parse("1.5s").unwrap_err();
6247 assert!(err.contains("\"1.5\""), "missing magnitude in {err:?}");
6248 assert!(
6249 err.contains("not a non-negative integer"),
6250 "missing canonical-form reason in {err:?}"
6251 );
6252 assert!(
6253 err.contains("\"1500ms\""),
6254 "missing canonical-form remediation in {err:?}"
6255 );
6256 }
6257
6258 #[test]
6259 fn parse_rejects_decimal_shaped_integer_seconds() {
6260 // `"1.0s"` is the trickiest drift class: numerically `1.0s` is
6261 // `1s` exactly, so the round-trip looks correct — but the
6262 // emitted canonical form is `"1s"`, not `"1.0s"`. Gate the
6263 // decimal-shape-with-integer-value form so author intent is
6264 // never silently rewritten.
6265 let err = duration_codec::parse("1.0s").unwrap_err();
6266 assert!(err.contains("\"1.0\""), "missing magnitude in {err:?}");
6267 assert!(
6268 err.contains("not a non-negative integer"),
6269 "missing canonical-form reason in {err:?}"
6270 );
6271 }
6272
6273 #[test]
6274 fn parse_rejects_half_unit_minute() {
6275 // `"0.5m"` is the unit-fraction footgun — author writes a
6276 // human-readable half-minute, serde silently rewrites to
6277 // `"30s"` on next emit. The gate names the offending
6278 // magnitude `"0.5"` and points at the integer-in-smaller-unit
6279 // form.
6280 let err = duration_codec::parse("0.5m").unwrap_err();
6281 assert!(err.contains("\"0.5\""), "missing magnitude in {err:?}");
6282 assert!(
6283 err.contains("\"30s\""),
6284 "missing canonical-form remediation in {err:?}"
6285 );
6286 }
6287
6288 #[test]
6289 fn parse_rejects_leading_plus_sign() {
6290 // `u64::from_str` rejects `"+30"` but `f64::from_str` accepts
6291 // it as `30.0` — the prior parser used f64 so `"+30s"` parsed
6292 // cleanly to 30s and round-tripped to `"30s"` on next emit
6293 // (DRIFT). The digit-only gate closes the leading-sign class
6294 // first; the diagnostic names `"+30"` verbatim.
6295 let err = duration_codec::parse("+30s").unwrap_err();
6296 assert!(err.contains("\"+30\""), "missing magnitude in {err:?}");
6297 assert!(
6298 err.contains("not a non-negative integer"),
6299 "missing canonical-form reason in {err:?}"
6300 );
6301 }
6302
6303 #[test]
6304 fn parse_rejects_leading_minus_sign() {
6305 // The former `num < 0.0` arm: `"-30s"` parsed as f64 to -30,
6306 // rejected with `"negative duration in \"-30s\""`. Under the
6307 // integer-magnitude gate the diagnostic is unified — `-30` is
6308 // non-digit-only, f64-numeric, and surfaces with the canonical-
6309 // form reason (no leading `+` / `-` sign) naming the offending
6310 // `"-30"` verbatim. Same diagnostic shape as every other
6311 // rejected non-integer magnitude.
6312 let err = duration_codec::parse("-30s").unwrap_err();
6313 assert!(err.contains("\"-30\""), "missing magnitude in {err:?}");
6314 assert!(
6315 err.contains("not a non-negative integer"),
6316 "missing canonical-form reason in {err:?}"
6317 );
6318 }
6319
6320 #[test]
6321 fn parse_garbage_still_falls_through_to_bad_magnitude() {
6322 // Non-digit-only AND non-numeric (`"--1s"`, `"abc"`) falls
6323 // through to the narrower "bad duration magnitude" arm — the
6324 // canonical-form diagnostic is reserved for the parser-shape
6325 // footgun case, not the "not a number at all" case. Same
6326 // shape `parse_byte_size`'s `BadByteMagnitude` arm carries on
6327 // the peer `:limits :memory` codec.
6328 let err = duration_codec::parse("--1s").unwrap_err();
6329 assert!(
6330 err.contains("bad duration magnitude"),
6331 "expected bad-magnitude wording in {err:?}"
6332 );
6333 }
6334
6335 #[test]
6336 fn parse_digit_only_magnitude_carries_zero_f64_drift() {
6337 // The accepted set is now closed under `u64`-exact integer
6338 // arithmetic: `"500ms"` → `Duration::from_millis(500)` exactly,
6339 // `"3600s"` → `Duration::from_secs(3600)` exactly, `"1h"` →
6340 // `Duration::from_secs(3600)` exactly, no f64 mantissa drift
6341 // possible. Pin the integer-exact arms across the four unit
6342 // suffixes so a future refactor that reaches back for f64
6343 // (`from_secs_f64`, `mul_f64`) surfaces here.
6344 assert_eq!(
6345 duration_codec::parse("3600s").unwrap(),
6346 Duration::from_secs(3600)
6347 );
6348 assert_eq!(
6349 duration_codec::parse("60m").unwrap(),
6350 Duration::from_secs(3600)
6351 );
6352 assert_eq!(
6353 duration_codec::parse("1h").unwrap(),
6354 Duration::from_secs(3600)
6355 );
6356 assert_eq!(
6357 duration_codec::parse("999ms").unwrap(),
6358 Duration::from_millis(999)
6359 );
6360 }
6361
6362 #[test]
6363 fn restart_window_serde_rejects_fractional_seconds() {
6364 // The shared codec backs `SupervisorSpec::restart_window`
6365 // (`with = "duration_codec"`) — so the gate applies on serde
6366 // deserialize for the typed Supervisor slot. A
6367 // `{"restartWindow":"1.5s"}` payload that previously round-
6368 // tripped to a different canonical string on next serialize
6369 // is now refused at deserialize with the integer-magnitude
6370 // diagnostic.
6371 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6372 "restartWindow":"1.5s",
6373 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6374 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6375 let msg = err.to_string();
6376 assert!(
6377 msg.contains("not a non-negative integer"),
6378 "expected integer-magnitude diagnostic in {msg:?}"
6379 );
6380 assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
6381 }
6382
6383 #[test]
6384 fn restart_window_serde_rejects_leading_plus() {
6385 // The `u64::from_str` leading-`+` permissiveness gap that
6386 // motivated the digit-only gate (the `f64`-side accepted
6387 // `"+30"`, the prior parser silently round-tripped to `"30s"`)
6388 // is now closed on the shared codec — surfaces as a structured
6389 // diagnostic at the serde layer for every typed-duration slot.
6390 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6391 "restartWindow":"+30s",
6392 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6393 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6394 let msg = err.to_string();
6395 assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
6396 assert!(
6397 msg.contains("not a non-negative integer"),
6398 "missing canonical-form reason in {msg:?}"
6399 );
6400 }
6401
6402 #[test]
6403 fn parse_rejects_leading_zero_magnitude() {
6404 // `"030s"` is digit-only, so the existing non-digit-only / sign
6405 // / fractional arm doesn't catch it — `u64::from_str("030")`
6406 // returns `Ok(30)`, so before this gate `"030s"` parsed to
6407 // `Duration::from_secs(30)` and round-tripped through `render`
6408 // to `"30s"` — a *different* canonical string on the next emit,
6409 // breaking the THEORY.md Part V render-determinism contract
6410 // exactly the way `"+30s"` did before the leading-`+` arm
6411 // landed. Peer with the `rate_limit_codec` leading-zero arm
6412 // (4f46830) on the same canonical-form-drift axis.
6413 let err = duration_codec::parse("030s").unwrap_err();
6414 assert!(
6415 err.contains("non-canonical leading zero"),
6416 "expected leading-zero diagnostic in {err:?}"
6417 );
6418 assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
6419 assert!(
6420 err.contains("\"30s\""),
6421 "missing canonical-form remediation in {err:?}"
6422 );
6423 assert!(
6424 err.contains("THEORY.md"),
6425 "missing render-determinism citation in {err:?}"
6426 );
6427 }
6428
6429 #[test]
6430 fn parse_rejects_multi_digit_zero_magnitude() {
6431 // `"00s"` and `"00ms"` are the all-zero leading-zero footgun —
6432 // digit-only, parse losslessly to `Duration::ZERO`, but render
6433 // back to `"0s"` (the single-byte canonical form) on the next
6434 // emit. The leading-zero arm refuses the drift class at the
6435 // codec layer; the semantic-zero gate downstream
6436 // (`SupervisorError::ZeroRestartWindow`, etc.) would refuse
6437 // the single-byte canonical form `"0s"` separately on the
6438 // typed-validate layer.
6439 let err = duration_codec::parse("00s").unwrap_err();
6440 assert!(
6441 err.contains("non-canonical leading zero"),
6442 "expected leading-zero diagnostic in {err:?}"
6443 );
6444 assert!(err.contains("\"00\""), "missing magnitude in {err:?}");
6445 }
6446
6447 #[test]
6448 fn parse_rejects_leading_zero_per_hour_window() {
6449 // `"01h"` is the per-hour-window footgun — multi-byte magnitude
6450 // starting with `0`, parses losslessly to `Duration::from_secs(3600)`,
6451 // renders to `"1h"` (DRIFT). The arm is unit-agnostic: every
6452 // canonical unit suffix the codec accepts (`ms` / `s` / `m` /
6453 // `h` / bare-integer-as-seconds) inherits the same gate.
6454 let err = duration_codec::parse("01h").unwrap_err();
6455 assert!(
6456 err.contains("non-canonical leading zero"),
6457 "expected leading-zero diagnostic in {err:?}"
6458 );
6459 assert!(err.contains("\"01\""), "missing magnitude in {err:?}");
6460 }
6461
6462 #[test]
6463 fn parse_rejects_leading_zero_bare_integer_as_seconds() {
6464 // The `parse_accepts_bare_integer_as_seconds` happy-path
6465 // (`"30"` → 30s) inherits the leading-zero arm: `"030"` is
6466 // multi-byte starts-with-`0`, parses losslessly to
6467 // `Duration::from_secs(30)`, renders to `"30s"` (DRIFT). The
6468 // bare-integer surface accepts permissive unit-empty
6469 // shorthand but still must reject leading-zero padding.
6470 let err = duration_codec::parse("030").unwrap_err();
6471 assert!(
6472 err.contains("non-canonical leading zero"),
6473 "expected leading-zero diagnostic in {err:?}"
6474 );
6475 assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
6476 }
6477
6478 #[test]
6479 fn parse_accepts_single_zero_magnitude_at_codec_layer() {
6480 // The codec-layer / typed-validate-layer boundary: `"0s"` /
6481 // `"0ms"` / `"0"` are the single-byte canonical-zero forms —
6482 // each round-trips losslessly through `render`
6483 // (`render(Duration::ZERO)` → `"0s"`), so the codec layer
6484 // accepts them. The downstream semantic-zero gates
6485 // (`SupervisorError::ZeroRestartWindow`,
6486 // `AplicacaoError::PolicyTimeoutZero`,
6487 // `AplicacaoError::PolicyCircuitBreakerWindowZero`) refuse
6488 // zero-magnitude authoring at the typed-validate layer above,
6489 // peer with the `rate_limit_codec` codec-layer / typed-
6490 // validate-layer partition for `"0/s"`.
6491 assert_eq!(duration_codec::parse("0s").unwrap(), Duration::ZERO);
6492 assert_eq!(duration_codec::parse("0ms").unwrap(), Duration::ZERO);
6493 assert_eq!(duration_codec::parse("0").unwrap(), Duration::ZERO);
6494 }
6495
6496 #[test]
6497 fn parse_accepts_canonical_magnitude_with_leading_one() {
6498 // The complementary boundary: a future tightening cannot
6499 // drift into rejecting valid canonical magnitudes that
6500 // happen to start with `1` (or any digit `[1-9]`). Pin
6501 // every canonical-unit suffix so the leading-zero arm
6502 // remains strictly narrower than the digit-only arm.
6503 assert_eq!(
6504 duration_codec::parse("100ms").unwrap(),
6505 Duration::from_millis(100)
6506 );
6507 assert_eq!(
6508 duration_codec::parse("100s").unwrap(),
6509 Duration::from_secs(100)
6510 );
6511 assert_eq!(
6512 duration_codec::parse("10m").unwrap(),
6513 Duration::from_secs(600)
6514 );
6515 assert_eq!(
6516 duration_codec::parse("10h").unwrap(),
6517 Duration::from_secs(36_000)
6518 );
6519 }
6520
6521 #[test]
6522 fn restart_window_serde_rejects_leading_zero() {
6523 // The shared codec backs `SupervisorSpec::restart_window`
6524 // (`with = "duration_codec"`) — so the leading-zero arm
6525 // applies on serde deserialize for the typed Supervisor slot.
6526 // A `{"restartWindow":"030s"}` payload that previously round-
6527 // tripped to a different canonical string on next serialize
6528 // is now refused at deserialize with the leading-zero
6529 // diagnostic. Peer with `restart_window_serde_rejects_leading_plus`
6530 // / `restart_window_serde_rejects_fractional_seconds` on the
6531 // same canonical-form-drift axis.
6532 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6533 "restartWindow":"030s",
6534 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6535 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6536 let msg = err.to_string();
6537 assert!(
6538 msg.contains("non-canonical leading zero"),
6539 "expected leading-zero diagnostic in {msg:?}"
6540 );
6541 assert!(msg.contains("\"030\""), "missing magnitude in {msg:?}");
6542 }
6543
6544 #[test]
6545 fn parse_rejects_leading_whitespace() {
6546 // `" 30s"` — the canonical paste-from-aligned-doc /
6547 // paste-from-YAML-quoted-plain-scalar footgun. Before this
6548 // gate the top-level `s.trim()` at parse entry silently ate
6549 // the leading space and parsed the value to
6550 // `Duration::from_secs(30)`, which then round-tripped through
6551 // `render` to `"30s"` (a *different* canonical string on the
6552 // next emit) — the exact canonical-form-drift class the
6553 // leading-`+` / leading-zero arms already close, extended
6554 // to the whitespace-byte class. Peer with the sibling
6555 // `rate_limit_codec` whitespace-rejection arm (1ad7755) on
6556 // the M3 `:politicas` axis.
6557 let err = duration_codec::parse(" 30s").unwrap_err();
6558 assert!(
6559 err.contains("contains whitespace byte"),
6560 "expected whitespace diagnostic in {err:?}"
6561 );
6562 assert!(err.contains("0x20"), "missing offending byte in {err:?}");
6563 assert!(
6564 err.contains("THEORY.md"),
6565 "missing render-determinism contract citation in {err:?}"
6566 );
6567 }
6568
6569 #[test]
6570 fn parse_rejects_trailing_whitespace() {
6571 // `"30s "` — the canonical shell-history / trailing-space
6572 // paste footgun. Before this gate the top-level `s.trim()`
6573 // silently ate the trailing space and parsed to
6574 // `Duration::from_secs(30)`, round-tripping to `"30s"` on the
6575 // next emit — same canonical-form drift as the leading-space
6576 // sibling, closed on the same whitespace-byte arm.
6577 let err = duration_codec::parse("30s ").unwrap_err();
6578 assert!(
6579 err.contains("contains whitespace byte"),
6580 "expected whitespace diagnostic in {err:?}"
6581 );
6582 assert!(err.contains("0x20"), "missing offending byte in {err:?}");
6583 }
6584
6585 #[test]
6586 fn parse_rejects_internal_whitespace_between_magnitude_and_unit() {
6587 // `"30 s"` — the canonical typographically-spaced author
6588 // shape (the same idiom every prose reference to a duration
6589 // renders as, mistakenly retained when the value is pasted
6590 // into a codec-shaped slot). Before this gate the per-part
6591 // `num_part.trim()` / `unit.trim()` calls silently ate the
6592 // whitespace between the magnitude and the unit and parsed
6593 // the value to `Duration::from_secs(30)`, round-tripping to
6594 // `"30s"` — the codec's *internal* whitespace-tolerance
6595 // vector, orthogonal to the leading / trailing surface but
6596 // the same canonical-form-drift class. Pins the arm as
6597 // strictly stronger than the pre-existing top-level
6598 // `s.trim()` behavior: it fires on whitespace anywhere in
6599 // the value, not just at the string boundary.
6600 let err = duration_codec::parse("30 s").unwrap_err();
6601 assert!(
6602 err.contains("contains whitespace byte"),
6603 "expected whitespace diagnostic in {err:?}"
6604 );
6605 assert!(err.contains("0x20"), "missing offending byte in {err:?}");
6606 }
6607
6608 #[test]
6609 fn parse_rejects_tab_byte() {
6610 // `"\t30s"` — the canonical paste-from-indented-doc /
6611 // paste-from-YAML-block-scalar footgun where a tab byte leads
6612 // the magnitude. Pins that the gate covers tab (`0x09`) as
6613 // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
6614 // members and both would be silently swallowed by `s.trim()`
6615 // pre-gate. The `is_ascii_whitespace` coverage extends beyond
6616 // space alone to the full ASCII-whitespace set (space `0x20`,
6617 // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
6618 // the tab arm as a representative of the non-space members.
6619 let err = duration_codec::parse("\t30s").unwrap_err();
6620 assert!(
6621 err.contains("contains whitespace byte"),
6622 "expected whitespace diagnostic in {err:?}"
6623 );
6624 assert!(
6625 err.contains("0x09"),
6626 "missing offending tab byte in {err:?}"
6627 );
6628 }
6629
6630 #[test]
6631 fn restart_window_serde_rejects_whitespace() {
6632 // The shared codec backs `SupervisorSpec::restart_window`
6633 // (`with = "duration_codec"`) — so the whitespace arm
6634 // applies on serde deserialize for the typed Supervisor slot.
6635 // A `{"restartWindow":" 30s"}` payload that previously round-
6636 // tripped to a different canonical string on next serialize
6637 // is now refused at deserialize with the whitespace-byte
6638 // diagnostic. Peer with `restart_window_serde_rejects_leading_zero`
6639 // / `restart_window_serde_rejects_leading_plus` /
6640 // `restart_window_serde_rejects_fractional_seconds` on the
6641 // same canonical-form-drift axis.
6642 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6643 "restartWindow":" 30s",
6644 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6645 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6646 let msg = err.to_string();
6647 assert!(
6648 msg.contains("contains whitespace byte"),
6649 "expected whitespace diagnostic in {msg:?}"
6650 );
6651 assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
6652 }
6653
6654 // ── canonical-form: non-ASCII Unicode `White_Space` duration gate ─────
6655 //
6656 // Successor to the ASCII-whitespace arm (a7ae622) on the shared
6657 // duration codec — closes the strictly-complementary class the
6658 // byte-scan cannot see, through the lifted
6659 // [`crate::render::find_non_ascii_whitespace_char`] predicate.
6660 // Applies to `:supervisor :restart-window`, `:politicas :timeout`,
6661 // and `:politicas :circuit-breaker :window` simultaneously via
6662 // this shared codec.
6663
6664 #[test]
6665 fn duration_codec_parse_rejects_leading_nbsp() {
6666 // NBSP prefix — the strictly-complementary drift class the
6667 // ASCII byte-scan cannot see. `str::trim` strips it silently
6668 // and the value drifts to `"30s"` on next serialize.
6669 let err = duration_codec::parse("\u{00A0}30s").unwrap_err();
6670 assert!(
6671 err.contains("non-ASCII Unicode whitespace character"),
6672 "expected non-ASCII whitespace diagnostic in {err:?}"
6673 );
6674 assert!(err.contains("U+00A0"), "missing codepoint in {err:?}");
6675 }
6676
6677 #[test]
6678 fn duration_codec_parse_rejects_trailing_line_separator() {
6679 // LINE SEPARATOR (`\u{2028}`) trailing — paste-from-web-doc
6680 // footgun.
6681 let err = duration_codec::parse("30s\u{2028}").unwrap_err();
6682 assert!(
6683 err.contains("non-ASCII Unicode whitespace character"),
6684 "expected non-ASCII whitespace diagnostic in {err:?}"
6685 );
6686 assert!(err.contains("U+2028"), "missing codepoint in {err:?}");
6687 }
6688
6689 #[test]
6690 fn duration_codec_parse_accepts_ascii_only_forms_after_unicode_arm() {
6691 // Positive-control pin: every ASCII-only canonical form the
6692 // renderer emits stays accepted through the new arm.
6693 assert_eq!(
6694 duration_codec::parse("30s").unwrap(),
6695 Duration::from_secs(30)
6696 );
6697 assert_eq!(
6698 duration_codec::parse("500ms").unwrap(),
6699 Duration::from_millis(500)
6700 );
6701 assert_eq!(
6702 duration_codec::parse("1h").unwrap(),
6703 Duration::from_secs(3600)
6704 );
6705 }
6706
6707 #[test]
6708 fn restart_window_serde_rejects_non_ascii_whitespace() {
6709 // The shared codec backs `SupervisorSpec::restart_window` — so
6710 // the new non-ASCII Unicode whitespace arm applies on serde
6711 // deserialize for the typed Supervisor slot. A
6712 // `{"restartWindow":" 30s"}` payload that previously
6713 // survived the ASCII byte-scan (only ASCII whitespace was
6714 // refused) is now refused at deserialize with the
6715 // non-ASCII-whitespace-and-codepoint diagnostic.
6716 let payload = "{\"estrategia\":\"OneForOne\",\"maxRestarts\":5,\
6717 \"restartWindow\":\"\u{00A0}30s\",\
6718 \"children\":[{\"caixa\":\"w\",\"versao\":\"^0.1\",\"restart\":\"Permanent\"}]}";
6719 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6720 let msg = err.to_string();
6721 assert!(
6722 msg.contains("non-ASCII Unicode whitespace character"),
6723 "expected non-ASCII whitespace diagnostic in {msg:?}"
6724 );
6725 assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
6726 }
6727
6728 // ── drift-detection: serde-derive-to-SUPERVISOR_KEY_* identity ────────
6729
6730 #[test]
6731 fn supervisor_spec_serde_keys_match_lifted_supervisor_key_consts() {
6732 // Load-bearing invariant: the four `SUPERVISOR_KEY_*` consts
6733 // (`SUPERVISOR_KEY_ESTRATEGIA` / `SUPERVISOR_KEY_MAX_RESTARTS` /
6734 // `SUPERVISOR_KEY_RESTART_WINDOW` / `SUPERVISOR_KEY_CHILDREN`)
6735 // name the exact camelCase JSON keys the
6736 // `#[serde(rename_all = "camelCase")]` attribute on
6737 // `SupervisorSpec` emits. Serialize a fully-populated spec (each
6738 // field carries `Some(_)` / non-empty) and pin that each canonical
6739 // byte-sequence appears verbatim in the JSON — a future accidental
6740 // `rename_all = "snake_case"` / `"kebab-case"` / verbatim-field-
6741 // name flip at the derive attribute (any of which would silently
6742 // break every downstream JSON consumer that reaches for one of the
6743 // four consts via `Value::get(...)`) surfaces here as a build-time
6744 // test failure at `supervisor.rs`, not as an apply-time
6745 // `.get(<stale-canonical-const>)` returning `None` far from the
6746 // derive-attr drift's commit. Peer with the sibling
6747 // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
6748 // (d8b8b4f) pin on the M2 `:limits` axis — same discipline the
6749 // M2 typed-slot family established, extended here to close the
6750 // top-level Supervisor axis.
6751 let spec = SupervisorSpec {
6752 estrategia: RestartStrategy::OneForOne,
6753 max_restarts: 5,
6754 restart_window: Some(Duration::from_secs(60)),
6755 children: vec![ChildSpec {
6756 caixa: "w".into(),
6757 versao: "^0.1".into(),
6758 restart: RestartPolicy::Permanent,
6759 }],
6760 };
6761 let json = serde_json::to_string(&spec).unwrap();
6762 for key in [
6763 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6764 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6765 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6766 crate::render::SUPERVISOR_KEY_CHILDREN,
6767 ] {
6768 let quoted = format!("\"{key}\"");
6769 assert!(
6770 json.contains("ed),
6771 "serialized SupervisorSpec must carry the lifted \
6772 SUPERVISOR_KEY_* byte-sequence {quoted} verbatim in \
6773 the JSON emission (got: {json})",
6774 );
6775 }
6776 }
6777
6778 #[test]
6779 fn supervisor_key_consts_are_pairwise_distinct() {
6780 // Cross-axis drift-detection pin: a future collapse of two
6781 // canonical top-level byte-strings onto the same value (e.g. an
6782 // accidental copy-paste flip of `SUPERVISOR_KEY_CHILDREN` to
6783 // also read `"estrategia"`) would silently reroute every
6784 // downstream probe on one axis onto the sibling axis's overlay
6785 // entry and pass every propagation-probe test that expected only
6786 // the stale axis's value. Peer of the sibling four-way distinct
6787 // pin on the `M2_LIMITS_KEY_*` tetrad (d8b8b4f).
6788 let all = [
6789 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6790 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6791 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6792 crate::render::SUPERVISOR_KEY_CHILDREN,
6793 ];
6794 for (i, a) in all.iter().enumerate() {
6795 for b in all.iter().skip(i + 1) {
6796 assert_ne!(
6797 a, b,
6798 "SUPERVISOR_KEY_* consts must be pairwise-distinct \
6799 canonical byte-sequences — got `{a}` == `{b}`",
6800 );
6801 }
6802 }
6803 }
6804
6805 #[test]
6806 fn supervisor_key_consts_are_lower_camel_case_shape() {
6807 // Shape-pin: every `SUPERVISOR_KEY_*` const must be a
6808 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
6809 // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
6810 // capital, no whitespace / dots) — the canonical shape the
6811 // `#[serde(rename_all = "camelCase")]` derive produces on
6812 // `SupervisorSpec`. A future flip to a non-camelCase attribute
6813 // at the derive surfaces both here (this test fails on the
6814 // stale-constant shape) and at
6815 // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
6816 // (that test fails on the mismatch between const and derive).
6817 // Peer with `m2_limits_key_consts_are_lower_camel_case_shape`
6818 // (d8b8b4f) on the sibling M2 `:limits` axis.
6819 for key in [
6820 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6821 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6822 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6823 crate::render::SUPERVISOR_KEY_CHILDREN,
6824 ] {
6825 assert!(
6826 !key.is_empty(),
6827 "SUPERVISOR_KEY_* must be non-empty (got {key:?})"
6828 );
6829 let first = key.chars().next().unwrap();
6830 assert!(
6831 first.is_ascii_lowercase(),
6832 "SUPERVISOR_KEY_* must lead with an ASCII-lowercase byte \
6833 (got {key:?}, leads with {first:?})",
6834 );
6835 assert!(
6836 key.chars().all(|c| c.is_ascii_alphanumeric()),
6837 "SUPERVISOR_KEY_* must be ASCII-alphanumeric only \
6838 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
6839 );
6840 }
6841 }
6842
6843 #[test]
6844 fn supervisor_key_consts_are_byte_distinct_from_supervisor_author_key_peers() {
6845 // Cross-axis drift pin: the four `SUPERVISOR_KEY_*` consts
6846 // (camelCase JSON keys, no leading colon) must never collide
6847 // byte-for-byte with the four peer `SUPERVISOR_AUTHOR_KEY_*`
6848 // consts (kebab-case author-facing labels with leading colon)
6849 // that sit next to them at `caixa_core::render`. Both families
6850 // cover the same four typed Supervisor slots on two distinct
6851 // axes (author-side kebab vs renderer-side camelCase);
6852 // collapsing either family onto the other's byte-shape would
6853 // silently reroute the render-side probe onto the author-facing
6854 // surface, or vice versa. Peer of the byte-distinctness
6855 // discipline the `M3_PLACEMENT_KEY_ESTRATEGIA` docstring names
6856 // against the peer `M3_AUTHOR_KEY_PLACEMENT`.
6857 let pairs = [
6858 (
6859 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6860 crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA,
6861 ),
6862 (
6863 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6864 crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS,
6865 ),
6866 (
6867 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6868 crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW,
6869 ),
6870 (
6871 crate::render::SUPERVISOR_KEY_CHILDREN,
6872 crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN,
6873 ),
6874 ];
6875 for (json_key, author_key) in pairs {
6876 assert_ne!(
6877 json_key, author_key,
6878 "SUPERVISOR_KEY_* (JSON side) must differ byte-for-byte \
6879 from the peer SUPERVISOR_AUTHOR_KEY_* (author side); \
6880 got JSON `{json_key}` == author `{author_key}`",
6881 );
6882 }
6883 }
6884
6885 // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_KEY_* identity ──
6886
6887 #[test]
6888 fn child_spec_serde_keys_match_lifted_supervisor_child_key_consts() {
6889 // Load-bearing invariant: the three `SUPERVISOR_CHILD_KEY_*` consts
6890 // (`SUPERVISOR_CHILD_KEY_CAIXA` / `SUPERVISOR_CHILD_KEY_VERSAO` /
6891 // `SUPERVISOR_CHILD_KEY_RESTART`) name the exact camelCase JSON
6892 // keys the `#[serde(rename_all = "camelCase")]` attribute on
6893 // `ChildSpec` emits. Serialize a fully-populated `ChildSpec` and
6894 // pin that each canonical byte-sequence appears verbatim in the
6895 // JSON — a future accidental `rename_all = "snake_case"` /
6896 // `"kebab-case"` / verbatim-field-name flip at the derive
6897 // attribute (any of which would silently break every downstream
6898 // JSON consumer that reaches for one of the three consts via
6899 // `Value::get(...)`) surfaces here as a build-time test failure at
6900 // `supervisor.rs`, not as an apply-time
6901 // `.get(<stale-canonical-const>)` returning `None` far from the
6902 // derive-attr drift's commit. Peer with the enclosing
6903 // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
6904 // (40cc4e5) pin on the M2 supervision-tree top-level axis — same
6905 // discipline the SupervisorSpec top-level lift established,
6906 // extended here to the sibling per-`:children` entry `ChildSpec`
6907 // derive so the last M2 typed-struct sub-block
6908 // `#[serde(rename_all = "camelCase")]` axis on the Supervisor
6909 // surface without a lifted serde-key peer joins the substrate's
6910 // "one canonical byte-string per typed serialized-key axis"
6911 // discipline.
6912 let c = ChildSpec {
6913 caixa: "worker".into(),
6914 versao: "^0.1".into(),
6915 restart: RestartPolicy::Permanent,
6916 };
6917 let json = serde_json::to_string(&c).unwrap();
6918 for key in [
6919 crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
6920 crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
6921 crate::render::SUPERVISOR_CHILD_KEY_RESTART,
6922 ] {
6923 let quoted = format!("\"{key}\"");
6924 assert!(
6925 json.contains("ed),
6926 "serialized ChildSpec must carry the lifted \
6927 SUPERVISOR_CHILD_KEY_* byte-sequence {quoted} verbatim \
6928 in the JSON emission (got: {json})",
6929 );
6930 }
6931 }
6932
6933 #[test]
6934 fn supervisor_child_key_consts_are_pairwise_distinct() {
6935 // Cross-axis drift-detection pin: a future collapse of two
6936 // canonical `ChildSpec` per-entry byte-strings onto the same
6937 // value (e.g. an accidental copy-paste flip of
6938 // `SUPERVISOR_CHILD_KEY_RESTART` to also read `"caixa"`) would
6939 // silently reroute every downstream probe on one axis onto the
6940 // sibling axis's overlay entry and pass every propagation-probe
6941 // test that expected only the stale axis's value. Peer of the
6942 // sibling three-way distinct pin on the `CONTRATO_KEY_*` triad
6943 // (ca463a4) and the two-way distinct pin on the `MEMBRO_KEY_*`
6944 // pair (ce80ca0).
6945 let all = [
6946 crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
6947 crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
6948 crate::render::SUPERVISOR_CHILD_KEY_RESTART,
6949 ];
6950 for (i, a) in all.iter().enumerate() {
6951 for b in all.iter().skip(i + 1) {
6952 assert_ne!(
6953 a, b,
6954 "SUPERVISOR_CHILD_KEY_* consts must be pairwise-\
6955 distinct canonical byte-sequences — got `{a}` == `{b}`",
6956 );
6957 }
6958 }
6959 }
6960
6961 #[test]
6962 fn supervisor_child_key_consts_are_lower_camel_case_shape() {
6963 // Shape-pin: every `SUPERVISOR_CHILD_KEY_*` const must be a
6964 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
6965 // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
6966 // capital, no whitespace / dots) — the canonical shape the
6967 // `#[serde(rename_all = "camelCase")]` derive produces on
6968 // `ChildSpec`. A future flip to a non-camelCase attribute at the
6969 // derive surfaces both here (this test fails on the
6970 // stale-constant shape) and at
6971 // `child_spec_serde_keys_match_lifted_supervisor_child_key_consts`
6972 // (that test fails on the mismatch between const and derive).
6973 // Peer with `supervisor_key_consts_are_lower_camel_case_shape`
6974 // (40cc4e5) on the sibling `SupervisorSpec` top-level axis.
6975 for key in [
6976 crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
6977 crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
6978 crate::render::SUPERVISOR_CHILD_KEY_RESTART,
6979 ] {
6980 assert!(
6981 !key.is_empty(),
6982 "SUPERVISOR_CHILD_KEY_* must be non-empty (got {key:?})"
6983 );
6984 let first = key.chars().next().unwrap();
6985 assert!(
6986 first.is_ascii_lowercase(),
6987 "SUPERVISOR_CHILD_KEY_* must lead with an ASCII-lowercase \
6988 byte (got {key:?}, leads with {first:?})",
6989 );
6990 assert!(
6991 key.chars().all(|c| c.is_ascii_alphanumeric()),
6992 "SUPERVISOR_CHILD_KEY_* must be ASCII-alphanumeric only \
6993 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
6994 );
6995 }
6996 }
6997
6998 // ── drift-detection: serde-derive-to-SUPERVISOR_ESTRATEGIA_* identity ────
6999
7000 #[test]
7001 fn restart_strategy_variants_serialize_to_lifted_scalar_values() {
7002 // The fail-before-pass-after pin: pre-lift there was no
7003 // single-source binding between the [`RestartStrategy`] variant
7004 // name the un-`rename`d `Serialize` derive emits under
7005 // [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the byte-string
7006 // every downstream cluster-side dispatcher (the future
7007 // wasm-operator's per-supervisor sibling-restart branch, the
7008 // future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
7009 // admission-time enum-arm bind, the `caixa-operator`'s
7010 // hierarchical reconciliation scheduler's per-strategy fan-out)
7011 // probes verbatim. A future `#[serde(rename_all = "kebab-case")]`
7012 // attribute on the enum — or a per-variant `#[serde(rename = "…")]`
7013 // override, or a variant rename in the source — would silently
7014 // rebrand the emitted scalar under one spelling while every
7015 // downstream dispatcher still probed the other, with the failure
7016 // surfacing at the operator's reconcile posture (subtrees coming
7017 // up under the `default()` `OneForOne` arm rather than the typed
7018 // slot's declared strategy — a bad child would then only take
7019 // itself down instead of the sibling set the author intended, so
7020 // shared-state children fall out of sync) far from the source
7021 // rebrand commit and with no field naming the drift. Pinning the
7022 // two paths (the `Serialize` derive's serialized string AND the
7023 // [`RestartStrategy::as_str`] helper) to the same four lifted
7024 // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
7025 // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
7026 // [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
7027 // [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
7028 // byte-strings makes any future drift on either endpoint fail
7029 // here at caixa-core build time. Peer of the M3
7030 // `placement_strategy_variants_serialize_to_lifted_scalar_values`
7031 // (3f0e21c) on the sibling `PlacementStrategy` axis — same
7032 // three-path-convergence discipline, extended to close the
7033 // OTP-shaped per-supervisor sibling-restart axis.
7034 for (variant, expected) in [
7035 (
7036 RestartStrategy::OneForOne,
7037 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7038 ),
7039 (
7040 RestartStrategy::OneForAll,
7041 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7042 ),
7043 (
7044 RestartStrategy::RestForOne,
7045 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7046 ),
7047 (
7048 RestartStrategy::SimpleOneForOne,
7049 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7050 ),
7051 ] {
7052 let json = serde_json::to_string(&variant).unwrap();
7053 assert_eq!(
7054 json,
7055 format!("\"{expected}\""),
7056 "RestartStrategy::{variant:?} must serialize to {expected:?}"
7057 );
7058 assert_eq!(
7059 variant.as_str(),
7060 expected,
7061 "RestartStrategy::{variant:?}.as_str() must return the lifted \
7062 SUPERVISOR_ESTRATEGIA_* constant"
7063 );
7064 }
7065 }
7066
7067 #[test]
7068 fn supervisor_estrategia_consts_are_pairwise_distinct() {
7069 // Cross-arm drift-detection pin: a future collapse of two
7070 // canonical variant byte-strings onto the same value (e.g. an
7071 // accidental copy-paste flip of `SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`
7072 // to also read `"OneForOne"`) would silently reroute every
7073 // downstream operator's per-strategy dispatch onto the sibling
7074 // arm's reconcile branch and pass every propagation-probe test
7075 // that expected only the stale arm's value — the mis-strategied
7076 // subtree would come up with the wrong sibling-restart posture
7077 // on every subsequent failure. Peer of the sibling four-way
7078 // distinct pin `supervisor_key_consts_are_pairwise_distinct`
7079 // (40cc4e5) on the top-level `SUPERVISOR_KEY_*` axis.
7080 let all = [
7081 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7082 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7083 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7084 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7085 ];
7086 for (i, a) in all.iter().enumerate() {
7087 for (j, b) in all.iter().enumerate() {
7088 if i != j {
7089 assert_ne!(
7090 a, b,
7091 "SUPERVISOR_ESTRATEGIA_* consts must be pairwise distinct \
7092 — got duplicate {a:?} at indices {i} and {j}",
7093 );
7094 }
7095 }
7096 }
7097 }
7098
7099 #[test]
7100 fn restart_strategy_display_routes_through_as_str_helper() {
7101 // The fail-before-pass-after pin on the first half of the
7102 // three-path convergence: pre-convergence the sibling
7103 // OTP-shape typed enum [`RestartStrategy`] carried a
7104 // [`std::fmt::Display`] surface via its
7105 // `#[discriminant(also_display)]` gen-platform derive route,
7106 // which arrived kebab-case as `"one-for-one"` /
7107 // `"one-for-all"` / `"rest-for-one"` /
7108 // `"simple-one-for-one"` while the wire format ran as
7109 // PascalCase `"OneForOne"` / `"OneForAll"` / `"RestForOne"` /
7110 // `"SimpleOneForOne"` through the un-`rename`d serde derive.
7111 // Every consumer reaching for a strategy byte-string past the
7112 // wire format had to pick between three paths
7113 // ([`RestartStrategy::as_str`], the `Serialize` derive's
7114 // serialized string, or `format!("{v}")` on the
7115 // discriminant-Display route), any two of which a future
7116 // variant rename or `#[serde(rename_all = "kebab-case")]`
7117 // attribute would silently desynchronize. Wiring
7118 // [`std::fmt::Display`] through [`RestartStrategy::as_str`]
7119 // closes the third path: every `format!("{v}")` call reaches
7120 // the same lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
7121 // const the wire format and the [`RestartStrategy::as_str`]
7122 // helper already route through, so a future variant rename
7123 // lands at exactly one place. Pin the routing here so a future
7124 // `impl std::fmt::Display for RestartStrategy`
7125 // reimplementation that hand-rolls the arms instead of
7126 // delegating to [`RestartStrategy::as_str`] fails at
7127 // caixa-core build time. Peer of the M3
7128 // `placement_strategy_display_routes_through_as_str_helper`
7129 // (cc8f749) which the M3 axis converged first.
7130 for &variant in RestartStrategy::ALL {
7131 assert_eq!(
7132 variant.to_string(),
7133 variant.as_str(),
7134 "RestartStrategy::{variant:?} Display must route through \
7135 RestartStrategy::as_str (single source of truth: the lifted \
7136 SUPERVISOR_ESTRATEGIA_* const the wire format also emits)"
7137 );
7138 }
7139 }
7140
7141 #[test]
7142 fn restart_strategy_display_matches_serialized_wire_byte_string() {
7143 // The fail-before-pass-after pin on the second half of the
7144 // three-path convergence: `Display` (user-facing text) agrees
7145 // byte-for-byte with the `Serialize` derive's wire format
7146 // (canonical camelCase-schema `SUPERVISOR_KEY_ESTRATEGIA`
7147 // scalar) on every variant. Pre-convergence the two paths
7148 // were structurally independent — a future
7149 // `#[serde(rename_all = "kebab-case")]` attribute on the
7150 // enum would silently rebrand the emitted wire scalar
7151 // (`one-for-one`, `one-for-all`, `rest-for-one`,
7152 // `simple-one-for-one`) while every consumer that
7153 // pretty-prints the strategy (the future wasm-operator's
7154 // per-supervisor sibling-restart-strategy diagnostic line,
7155 // the future `feira app graph` per-supervisor strategy line,
7156 // the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
7157 // materializer's admission-webhook rejection body) would
7158 // still emit the PascalCase form the `as_str` / `Display`
7159 // route returns, with the mismatch surfacing at consumer
7160 // parse time / operator dispatch time far from the source
7161 // rebrand commit. Pin the two paths byte-for-byte here so any
7162 // future serde-attribute or variant-rename drift is a
7163 // caixa-core-build-time test failure at this call, not a
7164 // silent per-consumer dispatch miss. Peer of the M3
7165 // `placement_strategy_display_matches_serialized_wire_byte_string`
7166 // (cc8f749) which the M3 axis converged first.
7167 for &variant in RestartStrategy::ALL {
7168 let wire = serde_json::to_string(&variant).unwrap();
7169 let unquoted = wire
7170 .strip_prefix('"')
7171 .and_then(|s| s.strip_suffix('"'))
7172 .expect("serialized RestartStrategy is a JSON string");
7173 assert_eq!(
7174 variant.to_string(),
7175 unquoted,
7176 "RestartStrategy::{variant:?} Display byte-string must match the \
7177 Serialize derive's wire byte-string (three-path convergence: \
7178 Display + as_str + Serialize all resolve to the same \
7179 SUPERVISOR_ESTRATEGIA_* const)"
7180 );
7181 }
7182 }
7183
7184 #[test]
7185 fn restart_strategy_as_ref_str_routes_through_as_str_accessor() {
7186 // Fail-before-pass-after byte-parity pin on the lifted
7187 // `impl AsRef<str> for RestartStrategy` — asserts the
7188 // standard-library trait impl and the substrate-primitive
7189 // [`RestartStrategy::as_str`] `pub const fn` accessor resolve
7190 // to the same `&str` per instance across the four-arm
7191 // closed set, so any future silent detour that routes the
7192 // impl through a divergent projection (a per-arm inline
7193 // `match self { RestartStrategy::OneForOne => "OneForOne", … }`
7194 // re-inlining that opens a compile-time link to the un-lifted
7195 // arm-literal, a swap onto the kebab-case
7196 // [`gen_platform::Discriminant`] catalog identity that would
7197 // collide the wire axis with the dispatcher-catalog axis) trips
7198 // at caixa-core test time under `PartialEq` rather than at a
7199 // downstream `impl AsRef<str>`-bound consumer's silent split.
7200 // Sweeps every one of the four arms
7201 // [`RestartStrategy::ALL`] carries so no arm's projection is
7202 // covered only by the sibling wire-format `Serialize` derive
7203 // path. Peer of the sibling
7204 // [`crate::version::tests::caixa_version_as_ref_str_routes_through_as_str_accessor`]
7205 // (16d5c7e) `AsRef<str>`-byte-parity pin on the paired
7206 // top-level `:versao` typed newtype — the two pins together
7207 // cover the substrate primitive's `AsRef<str>` projection axis
7208 // on the paired newtype + closed-set-typed-enum surface.
7209 for &variant in RestartStrategy::ALL {
7210 assert_eq!(
7211 <RestartStrategy as AsRef<str>>::as_ref(&variant),
7212 variant.as_str(),
7213 "AsRef<str> impl on RestartStrategy::{variant:?} must \
7214 byte-equal RestartStrategy::as_str on the same instance \
7215 — divergence signals a silent detour off the substrate-\
7216 primitive accessor"
7217 );
7218 }
7219 }
7220
7221 #[test]
7222 fn restart_strategy_as_ref_str_routes_through_display_via_shared_accessor() {
7223 // Fail-before-pass-after byte-parity pin on the three-path
7224 // convergence discipline the M2 sibling-restart primitive now
7225 // carries on the `&str`-projection axis:
7226 // `<RestartStrategy as AsRef<str>>::as_ref(&s)` (the newly
7227 // lifted impl), `format!("{s}")` (the pre-existing
7228 // [`fmt::Display`] impl), and `s.as_str()` (the substrate-
7229 // primitive `pub const fn` accessor both trait impls delegate
7230 // through) must resolve to the same byte-string on every
7231 // instance across the four-arm closed set. Refuses any future
7232 // divergence between the two trait impls (a stray
7233 // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
7234 // rather than delegating through the shared accessor; a
7235 // hypothetical `AsRef<str>` rewrite that inlines a per-arm
7236 // literal cascade) that would silently split the two
7237 // projection paths of the same closed-set typed enum. Mirrors
7238 // the sibling three-path-convergence discipline the peer
7239 // [`crate::CaixaVersion`] typed newtype carries on its
7240 // `AsRef<str>` / `Display` / `as_str` triple
7241 // (version.rs pin
7242 // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
7243 // 16d5c7e).
7244 for &variant in RestartStrategy::ALL {
7245 let via_as_ref: &str = <RestartStrategy as AsRef<str>>::as_ref(&variant);
7246 let via_display: String = format!("{variant}");
7247 let via_accessor: &str = variant.as_str();
7248 assert_eq!(via_as_ref, via_accessor);
7249 assert_eq!(via_display, via_accessor);
7250 assert_eq!(via_as_ref, via_display.as_str());
7251 }
7252 }
7253
7254 #[test]
7255 fn restart_strategy_all_enumerates_every_variant_exactly_once() {
7256 // Fail-before-pass-after pin on the [`RestartStrategy::ALL`]
7257 // exhaustive-iteration surface: every variant appears exactly
7258 // once, and the slice length matches the arm count of the
7259 // closed set. Every consumer that walks the accepted-strategy
7260 // set (a future `feira supervisor --estrategia …` CLI-side
7261 // arg-parse's "did you mean" hint, a future M4 admission-
7262 // webhook's rejection body naming the accepted-`:estrategia`
7263 // list, the [`RestartStrategy::from_wire`] reverse-projection
7264 // consumers that iterate the accept-set for diagnostic
7265 // rendering) reads through this slice, so a future arm addition
7266 // that grows the enum but forgets to grow [`Self::ALL`]
7267 // silently truncates every downstream consumer's accept-set at
7268 // the same pre-addition boundary — this pin fails at caixa-core
7269 // build time on the pairwise-distinct + arm-count invariants.
7270 //
7271 // Peer of the sibling [`crate::CaixaKind::ALL`] (6b1f4fb) /
7272 // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
7273 // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
7274 // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
7275 // pins on the peer closed-set typed-enum axes.
7276 let all: &[RestartStrategy] = RestartStrategy::ALL;
7277 assert_eq!(
7278 all.len(),
7279 4,
7280 "RestartStrategy::ALL must enumerate every variant of the \
7281 four-arm closed set (OneForOne, OneForAll, RestForOne, \
7282 SimpleOneForOne); got {all:?}"
7283 );
7284 for (i, a) in all.iter().enumerate() {
7285 for (j, b) in all.iter().enumerate() {
7286 if i != j {
7287 assert_ne!(
7288 a, b,
7289 "RestartStrategy::ALL must carry every variant exactly \
7290 once — got duplicate {a:?} at indices {i} and {j}"
7291 );
7292 }
7293 }
7294 }
7295 for variant in [
7296 RestartStrategy::OneForOne,
7297 RestartStrategy::OneForAll,
7298 RestartStrategy::RestForOne,
7299 RestartStrategy::SimpleOneForOne,
7300 ] {
7301 assert!(
7302 all.contains(&variant),
7303 "RestartStrategy::ALL must contain {variant:?} — a future arm \
7304 addition that grows the enum but forgets to grow the ALL slice \
7305 silently truncates every downstream consumer's accept-set at \
7306 the pre-addition boundary"
7307 );
7308 }
7309 }
7310
7311 #[test]
7312 fn restart_strategy_from_wire_accepts_every_lifted_constant() {
7313 // Fail-before-pass-after pin on the forward accept-set of the
7314 // [`RestartStrategy::from_wire`] reverse projection: every
7315 // canonical [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
7316 // constant the [`RestartStrategy::as_str`] emitter walks parses
7317 // back to its paired variant. Any future arm addition that
7318 // grows the emitter's `as_str` match but forgets to grow the
7319 // parser's `from_wire` match silently splits the two halves of
7320 // the round-trip — the wire byte-string one non-serde consumer
7321 // parses from the one the emitter wrote — with the failure
7322 // surfacing at parse time far from the rebrand commit. Pinning
7323 // the four-arm accept-set here catches the drift at caixa-core
7324 // build time.
7325 //
7326 // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
7327 // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
7328 // accept-set pins on the peer closed-set typed-enum `str → Self`
7329 // axes.
7330 for (wire, expected) in [
7331 (
7332 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7333 RestartStrategy::OneForOne,
7334 ),
7335 (
7336 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7337 RestartStrategy::OneForAll,
7338 ),
7339 (
7340 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7341 RestartStrategy::RestForOne,
7342 ),
7343 (
7344 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7345 RestartStrategy::SimpleOneForOne,
7346 ),
7347 ] {
7348 let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
7349 panic!(
7350 "RestartStrategy::from_wire({wire:?}) must accept every \
7351 SUPERVISOR_ESTRATEGIA_* constant — got None for the \
7352 lifted canonical byte-string that RestartStrategy::{expected:?} \
7353 serializes as under SUPERVISOR_KEY_ESTRATEGIA"
7354 )
7355 });
7356 assert_eq!(
7357 parsed, expected,
7358 "RestartStrategy::from_wire({wire:?}) must return \
7359 RestartStrategy::{expected:?}; got RestartStrategy::{parsed:?}"
7360 );
7361 }
7362 }
7363
7364 #[test]
7365 fn restart_strategy_from_wire_round_trips_through_as_str() {
7366 // Fail-before-pass-after pin on the closed round-trip between
7367 // the forward [`RestartStrategy::as_str`] emitter and the
7368 // reverse [`RestartStrategy::from_wire`] parser: for every
7369 // variant in [`RestartStrategy::ALL`], parsing the emitter's
7370 // output must return exactly the same variant. Any per-arm
7371 // divergence — a future arm added to `as_str` but not
7372 // `from_wire`, an accidental copy-paste flip in one but not
7373 // the other — silently splits the emit and parse halves and
7374 // the failure surfaces at consumer parse time far from the
7375 // drift site. The `ALL`-iterating shape means a future arm
7376 // addition picks up the coverage by construction.
7377 //
7378 // Peer of the sibling
7379 // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
7380 // (18c7342) round-trip pin on
7381 // [`crate::aplicacao::PlacementStrategy::from_wire`] and
7382 // [`crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`]
7383 // (6b1f4fb) round-trip pin on [`crate::CaixaKind::from_wire`].
7384 for &variant in RestartStrategy::ALL {
7385 let wire = variant.as_str();
7386 let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
7387 panic!(
7388 "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
7389 must be Some({variant:?}) — the two halves of the round-trip \
7390 dispatch on the same lifted SUPERVISOR_ESTRATEGIA_* consts; \
7391 got None on wire byte-string {wire:?}"
7392 )
7393 });
7394 assert_eq!(
7395 parsed, variant,
7396 "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
7397 must round-trip to the same variant; got {parsed:?}"
7398 );
7399 }
7400 }
7401
7402 #[test]
7403 fn restart_strategy_from_wire_rejects_unknown_byte_strings() {
7404 // Fail-before-pass-after pin on the closed-set refusal
7405 // discipline of [`RestartStrategy::from_wire`]: every
7406 // byte-string outside the four-arm accept-set returns `None`
7407 // rather than silently collapsing onto the [`Default`]
7408 // (`OneForOne`) arm or an arbitrary neighbor. The refusal set
7409 // exercised here sweeps the load-bearing drift shapes: the
7410 // empty string (a stripped serde-attribute drift), all-
7411 // whitespace strings (the canonical text-editor accidental
7412 // padding shape), the kebab-case dispatcher-catalog identities
7413 // (`"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
7414 // `"simple-one-for-one"` — the [`gen_platform::FromStrKind`]-
7415 // derived [`std::str::FromStr`] accept-set, which parses the
7416 // *other* axis of this enum's two-axis split and must not leak
7417 // into the `from_wire` PascalCase-wire accept-set), the
7418 // lowercased single-word forms (`"oneforone"`), the padded
7419 // canonical scalar (`" OneForOne "`), the trailing-newline
7420 // shapes (`"OneForOne\n"`), and neighboring-but-unknown arms
7421 // (`"AllForOne"` — the canonical typo direction).
7422 //
7423 // Peer of the sibling
7424 // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
7425 // (2aa6d23) +
7426 // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
7427 // (18c7342) refusal pins on the peer closed-set typed-enum
7428 // axes.
7429 for bad in [
7430 "",
7431 " ",
7432 "\n",
7433 "\t",
7434 "one-for-one",
7435 "one-for-all",
7436 "rest-for-one",
7437 "simple-one-for-one",
7438 "oneforone",
7439 "OneForOnes",
7440 "one_for_one",
7441 "one for one",
7442 "ONEFORONE",
7443 "OneForOne ",
7444 " OneForOne",
7445 " SimpleOneForOne ",
7446 "OneForOne\n",
7447 "restforone",
7448 "REST_FOR_ONE",
7449 "AllForOne",
7450 "Simple",
7451 "?",
7452 ] {
7453 assert!(
7454 RestartStrategy::from_wire(bad).is_none(),
7455 "RestartStrategy::from_wire({bad:?}) must return None — the \
7456 parser's accept-set is exactly the four RestartStrategy::as_str \
7457 outputs (OneForOne, OneForAll, RestForOne, SimpleOneForOne), \
7458 and this byte-string is outside that closed set"
7459 );
7460 }
7461 }
7462
7463 #[test]
7464 fn restart_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
7465 // Fail-before-pass-after pin on the fourth path of the four-path
7466 // convergence: `from_wire` (the reverse projection) inverts the
7467 // `Serialize` derive's wire byte-string on every variant.
7468 // Together with the pre-existing three-path convergence
7469 // (`Display` + `as_str` + `Serialize` all resolve to the same
7470 // lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const,
7471 // pinned by
7472 // [`restart_strategy_display_matches_serialized_wire_byte_string`])
7473 // this closes the round-trip: the wire byte-string the
7474 // `Serialize` derive emits parses back to the same variant
7475 // through `from_wire`, so any future serde-attribute or variant-
7476 // rename drift on the emit half now surfaces as a matched drift
7477 // on the parse half at caixa-core build time — the two halves
7478 // migrate as a unit through the lifted consts on any future
7479 // rename, and the round-trip cannot silently split.
7480 //
7481 // Peer of the sibling
7482 // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
7483 // (18c7342) wire-format pin on
7484 // [`crate::aplicacao::PlacementStrategy::from_wire`].
7485 for &variant in RestartStrategy::ALL {
7486 let wire = serde_json::to_string(&variant).unwrap();
7487 let unquoted = wire
7488 .strip_prefix('"')
7489 .and_then(|s| s.strip_suffix('"'))
7490 .expect("serialized RestartStrategy is a JSON string");
7491 let parsed = RestartStrategy::from_wire(unquoted).unwrap_or_else(|| {
7492 panic!(
7493 "RestartStrategy::from_wire({unquoted:?}) must accept the \
7494 Serialize derive's wire byte-string for \
7495 RestartStrategy::{variant:?} — the four-path convergence \
7496 (Display + as_str + Serialize + from_wire) resolves through \
7497 the same lifted SUPERVISOR_ESTRATEGIA_* const; got None"
7498 )
7499 });
7500 assert_eq!(
7501 parsed, variant,
7502 "RestartStrategy::from_wire of the Serialize derive's wire \
7503 byte-string for RestartStrategy::{variant:?} must round-trip \
7504 to the same variant; got {parsed:?}"
7505 );
7506 }
7507 }
7508
7509 #[test]
7510 fn restart_strategy_try_from_str_routes_through_from_wire_accessor() {
7511 // Fail-before-pass-after byte-parity pin on the newly lifted
7512 // `impl TryFrom<&str> for RestartStrategy` — asserts the standard-
7513 // library trait impl and the substrate-primitive
7514 // [`RestartStrategy::from_wire`] `Option<Self>` accessor resolve to
7515 // the same four-arm accept-set across every arm the exhaustive
7516 // [`RestartStrategy::ALL`] slice enumerates. Any future silent
7517 // detour that routes the trait impl through a divergent projection
7518 // (a per-arm inline `match s { "OneForOne" => Ok(Self::OneForOne),
7519 // … }` re-inlining that opens a compile-time link to the un-
7520 // lifted arm-literal, a hypothetical `#[serde(rename_all = "…")]`
7521 // attribute drift that silently splits the wire byte-string from
7522 // every consumer that reaches for this typed dispatch, an
7523 // accidental swap onto the kebab-case dispatcher-catalog axis the
7524 // pre-existing [`std::str::FromStr`] impl parses through and which
7525 // would collide the two-axis wire/catalog split the sibling
7526 // [`RestartStrategy::from_wire`] doc block makes load-bearing)
7527 // trips at caixa-core test time under `assert_eq!` rather than at
7528 // a downstream `impl TryFrom<&str>`-bound consumer's silent split.
7529 // Sweeps every one of the four arms [`RestartStrategy::ALL`]
7530 // carries so no arm's projection is covered only by the sibling
7531 // method-named `from_wire` path. Peer of the sibling
7532 // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
7533 // (3c83606),
7534 // [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
7535 // (bf33136), and the M3
7536 // [`crate::aplicacao::tests::placement_strategy_try_from_str_routes_through_from_wire_accessor`]
7537 // (6fd00cd) — extends the trait-idiomatic reverse-projection axis
7538 // onto the first M2-OTP-shape closed-set typed enum on the caixa
7539 // surface.
7540 for &variant in RestartStrategy::ALL {
7541 let wire = variant.as_str();
7542 assert_eq!(
7543 <RestartStrategy as TryFrom<&str>>::try_from(wire),
7544 Ok(variant),
7545 "TryFrom<&str> impl on RestartStrategy must round-trip \
7546 RestartStrategy::{variant:?}.as_str() = {wire:?} back to \
7547 Ok(RestartStrategy::{variant:?}) — divergence from \
7548 RestartStrategy::from_wire signals a silent detour off \
7549 the substrate-primitive accessor"
7550 );
7551 assert_eq!(
7552 <RestartStrategy as TryFrom<&str>>::try_from(wire).ok(),
7553 RestartStrategy::from_wire(wire),
7554 "TryFrom<&str> ok()-projection on {wire:?} must byte-equal \
7555 RestartStrategy::from_wire on the same input"
7556 );
7557 }
7558 }
7559
7560 #[test]
7561 fn restart_strategy_try_from_str_rejects_unknown_byte_strings() {
7562 // Rejection witness on the `impl TryFrom<&str> for
7563 // RestartStrategy` — sweeps a candidate set of byte-strings
7564 // outside the four-arm PascalCase wire accept-set the sibling
7565 // [`RestartStrategy::as_str`] emits and asserts every one lands on
7566 // `Err(())`, so a future accidental widening of the trait impl's
7567 // accept-set (a stray additional
7568 // `_ if s.eq_ignore_ascii_case("OneForOne") => Ok(…)` case-fold
7569 // path, a silent inclusion of the kebab-case dispatcher-catalog
7570 // byte-string the pre-existing [`std::str::FromStr`] impl the
7571 // [`gen_platform::FromStrKind`] derive installs parses onto the
7572 // wire axis — which would collide the two-axis
7573 // wire/dispatcher-catalog split the sibling
7574 // [`RestartStrategy::from_wire`] doc block makes load-bearing —
7575 // an English-rebrand or plural-arm silent alias that would
7576 // widen the wire accept-set past the OTP-canonical four) trips at
7577 // caixa-core test time. The candidate set includes the empty
7578 // string, whitespace-only padding, the kebab-case dispatcher-
7579 // catalog byte-strings on the sibling axis (a caller who confuses
7580 // the two axes trips here rather than at a downstream consumer's
7581 // silent reject), a lowercase / uppercase / mixed-case fold of
7582 // each PascalCase arm (a caller who assumes case-fold acceptance
7583 // trips here), leading/trailing whitespace padding, the trailing-
7584 // newline shape, quote-wrapped candidates, and a residual set of
7585 // plausible-but-wrong English rebrand candidates. Peer of the
7586 // sibling
7587 // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
7588 // (3c83606) and
7589 // [`crate::aplicacao::tests::placement_strategy_try_from_str_rejects_unknown_byte_strings`]
7590 // (6fd00cd) rejection witnesses.
7591 let rejected: &[&str] = &[
7592 "",
7593 " ",
7594 "\n",
7595 "\t",
7596 "one-for-one",
7597 "one-for-all",
7598 "rest-for-one",
7599 "simple-one-for-one",
7600 "oneforone",
7601 "one_for_one",
7602 "OneForOnes",
7603 "ONEFORONE",
7604 "oneforall",
7605 "restforone",
7606 "simpleoneforone",
7607 "OneForOne ",
7608 " OneForOne",
7609 " OneForAll ",
7610 "OneForOne\n",
7611 "RestForOne\t",
7612 "OneForEach",
7613 "AllForOne",
7614 "one for one",
7615 "\"OneForOne\"",
7616 "?",
7617 ];
7618 for &input in rejected {
7619 assert_eq!(
7620 <RestartStrategy as TryFrom<&str>>::try_from(input),
7621 Err(()),
7622 "TryFrom<&str> impl on RestartStrategy must reject the \
7623 non-wire byte-string {input:?} — silent acceptance signals \
7624 an accept-set widening off the paired \
7625 RestartStrategy::from_wire resolver"
7626 );
7627 }
7628 }
7629
7630 #[test]
7631 fn restart_strategy_try_from_str_and_from_wire_partition_the_accept_set() {
7632 // Cross-axis partition pin: the paired `TryFrom<&str>` and
7633 // `from_wire` reverse projections must resolve identically on
7634 // *every* input, not just the ones [`RestartStrategy::ALL`]
7635 // enumerates. Sweeps a mixed candidate set spanning accepted
7636 // (four-arm PascalCase wire byte-strings) and rejected (kebab-case
7637 // dispatcher-catalog byte-strings, empty, whitespace-padded,
7638 // quoted, English-rebrand candidates) inputs and asserts the
7639 // trait's `Result::ok()` projection byte-equals the method-named
7640 // resolver's `Option<Self>` return-shape on each, locking the two
7641 // paths together by construction so any future detour (a stray
7642 // `try_from` special-case that widens or narrows the accept-set
7643 // outside the paired `from_wire` resolver, an accidental swap
7644 // onto the kebab-case [`std::str::FromStr`] impl the
7645 // [`gen_platform::FromStrKind`] derive installs on the sibling
7646 // dispatcher-catalog axis) trips at caixa-core test time. Peer of
7647 // the sibling
7648 // [`crate::kind::tests::caixa_kind_try_from_str_and_from_wire_partition_the_accept_set`]
7649 // pin — extends the round-trip discipline onto the M2-OTP-shape
7650 // sibling-restart axis.
7651 let candidates: &[&str] = &[
7652 "OneForOne",
7653 "OneForAll",
7654 "RestForOne",
7655 "SimpleOneForOne",
7656 "",
7657 "one-for-one",
7658 "one-for-all",
7659 "rest-for-one",
7660 "simple-one-for-one",
7661 "oneforone",
7662 "unknown",
7663 "OneForOne ",
7664 " OneForOne",
7665 "\"OneForOne\"",
7666 "OneForEach",
7667 "?",
7668 ];
7669 for &input in candidates {
7670 let via_trait: Option<RestartStrategy> =
7671 <RestartStrategy as TryFrom<&str>>::try_from(input).ok();
7672 let via_method: Option<RestartStrategy> = RestartStrategy::from_wire(input);
7673 assert_eq!(
7674 via_trait, via_method,
7675 "TryFrom<&str> and from_wire must resolve identically on \
7676 input {input:?} — divergence signals the two reverse-\
7677 projection paths have drifted onto different accept-sets"
7678 );
7679 }
7680 }
7681
7682 #[test]
7683 fn restart_strategy_from_into_static_str_routes_through_as_str_accessor() {
7684 // Fail-before-pass-after byte-parity pin on the newly lifted
7685 // `impl From<RestartStrategy> for &'static str` — asserts the
7686 // standard-library trait impl and the substrate-primitive
7687 // [`RestartStrategy::as_str`] `pub const fn` accessor resolve to
7688 // the same four-arm emit-set across every arm the exhaustive
7689 // [`RestartStrategy::ALL`] slice enumerates. Any future silent
7690 // detour that routes the trait impl through a divergent
7691 // projection (a per-arm inline `match strategy { OneForOne =>
7692 // "OneForOne", … }` re-inlining that opens a compile-time link to
7693 // the un-lifted arm-literal, an accidental swap onto the sibling
7694 // kebab-case [`Self::discriminant`] dispatcher-catalog axis that
7695 // would collide the two-axis wire/catalog split the sibling
7696 // [`RestartStrategy::from_wire`] doc block makes load-bearing) trips
7697 // at caixa-core test time under `assert_eq!` rather than at a
7698 // downstream `impl Into<&'static str>`-bound consumer's silent
7699 // split. Sweeps every one of the four arms
7700 // [`RestartStrategy::ALL`] carries so no arm's projection is
7701 // covered only by the sibling method-named `as_str` /
7702 // [`std::fmt::Display`] / [`AsRef<str>`] paths. Materializes the
7703 // `<&'static str as From<RestartStrategy>>::from` output in a
7704 // `const`-shape binding to make the `'static` lifetime promise a
7705 // build-time invariant — a future accidental downgrade of any of
7706 // the four arms' [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
7707 // constants to a non-`&'static str` (a `String::leak()`-produced
7708 // return, a `Box::leak`-cast) trips at caixa-core build time
7709 // rather than at a downstream `'static`-bound consumer.
7710 const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
7711 const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
7712 const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
7713 const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
7714 for &variant in RestartStrategy::ALL {
7715 let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
7716 let via_method: &'static str = variant.as_str();
7717 assert_eq!(
7718 via_trait, via_method,
7719 "From<RestartStrategy> for &'static str impl must round-trip \
7720 RestartStrategy::{variant:?} to the same lifted \
7721 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str returns — \
7722 divergence signals a silent detour off the substrate-primitive \
7723 accessor"
7724 );
7725 let via_into: &'static str = variant.into();
7726 assert_eq!(
7727 via_into, via_method,
7728 "Into<&'static str>::into on RestartStrategy::{variant:?} must \
7729 byte-equal RestartStrategy::as_str on the same input — the \
7730 blanket-derived Into shape must resolve to the same as_str \
7731 dispatch as the explicit From impl"
7732 );
7733 }
7734 assert_eq!(
7735 [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
7736 [
7737 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7738 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7739 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7740 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7741 ],
7742 "const-context RestartStrategy::as_str must resolve to the four \
7743 lifted SUPERVISOR_ESTRATEGIA_* consts — a future accidental \
7744 downgrade of any arm to a non-const or non-static byte-string \
7745 breaks the `&'static str`-lifetime promise the paired \
7746 From<RestartStrategy> for &'static str impl carries by \
7747 construction"
7748 );
7749 }
7750
7751 #[test]
7752 fn restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set() {
7753 // Cross-axis partition pin: the paired trait-idiomatic
7754 // `From<RestartStrategy> for &'static str` forward projection and
7755 // the method-named [`RestartStrategy::as_str`] forward projection
7756 // must resolve identically on *every* arm, not just the ones
7757 // named in the primary byte-parity pin above. Sweeps every
7758 // [`RestartStrategy::ALL`] arm and asserts the trait's `From::from`
7759 // output byte-equals the method-named accessor's return-value on
7760 // each, locking the two forward-projection paths together by
7761 // construction so any future detour (a stray `From` special-case
7762 // that lands on a divergent per-arm literal outside the paired
7763 // `as_str` dispatch, a hypothetical rebrand touching one axis
7764 // without the other) trips at caixa-core test time. Peer of the
7765 // sibling reverse-projection partition pin
7766 // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
7767 // — extends the round-trip discipline onto the trait-idiomatic
7768 // *forward* axis, closing the two-way `Self ↔ &'static str`
7769 // round-trip on the trait-idiomatic pair
7770 // (`From<Self> for &'static str` + `TryFrom<&str> for Self`) as
7771 // well as the pre-existing method-named pair
7772 // (`as_str` + `from_wire`).
7773 for &variant in RestartStrategy::ALL {
7774 let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
7775 let via_method: &'static str = variant.as_str();
7776 assert_eq!(
7777 via_trait, via_method,
7778 "From<RestartStrategy> for &'static str and \
7779 RestartStrategy::as_str must resolve identically on \
7780 RestartStrategy::{variant:?} — divergence signals the \
7781 two forward-projection paths have drifted onto different \
7782 emit-sets"
7783 );
7784 }
7785 // Round-trip witness: every arm's forward `From` output re-parses
7786 // through the paired trait-idiomatic reverse `TryFrom<&str>` back
7787 // to the original variant. Closes the two-way `RestartStrategy ↔
7788 // &'static str` round-trip on the trait-idiomatic axis pair,
7789 // mirroring the pre-existing method-named `as_str` + `from_wire`
7790 // round-trip on the substrate-primitive axis pair.
7791 for &variant in RestartStrategy::ALL {
7792 let emitted: &'static str = variant.into();
7793 let re_parsed: Result<RestartStrategy, ()> =
7794 <RestartStrategy as TryFrom<&str>>::try_from(emitted);
7795 assert_eq!(
7796 re_parsed,
7797 Ok(variant),
7798 "trait-idiomatic axis pair must round-trip \
7799 RestartStrategy::{variant:?} through `.into::<&'static \
7800 str>()` and back through `TryFrom<&str>` — a break signals \
7801 the forward-emit and reverse-parse axes have drifted onto \
7802 different vocabularies"
7803 );
7804 }
7805 }
7806
7807 #[test]
7808 fn restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
7809 // Fail-before-pass-after byte-parity pin on the newly lifted
7810 // `impl From<&RestartStrategy> for &'static str` — asserts the
7811 // borrowed-input standard-library trait impl and the substrate-
7812 // primitive [`RestartStrategy::as_str`] `pub const fn` accessor
7813 // resolve to the same four-arm emit-set across every arm the
7814 // exhaustive [`RestartStrategy::ALL`] slice enumerates. Rust's
7815 // `From` trait does not auto-derive the borrowed-input sibling
7816 // from a paired owned-input impl (no `impl<T, U> From<&T> for U
7817 // where T: Copy, U: From<T>` blanket in `core`), so the
7818 // borrowed-input axis is a distinct trait-idiomatic surface
7819 // that a `.iter().map(Into::into)` shape over
7820 // [`RestartStrategy::ALL`] (whose iterator yields
7821 // `&RestartStrategy`, not `RestartStrategy`) reaches through
7822 // this impl and no other — the paired owned-input
7823 // [`From<RestartStrategy>`] impl requires an explicit
7824 // `.copied()` / dereference before the trait fires.
7825 // Materializes the `<&'static str as
7826 // From<&RestartStrategy>>::from` output in a `const`-shape
7827 // binding to make the `'static` lifetime promise a build-time
7828 // invariant.
7829 const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
7830 const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
7831 const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
7832 const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
7833 for variant in RestartStrategy::ALL {
7834 let via_trait: &'static str = <&'static str as From<&RestartStrategy>>::from(variant);
7835 let via_method: &'static str = variant.as_str();
7836 assert_eq!(
7837 via_trait, via_method,
7838 "From<&RestartStrategy> for &'static str impl must \
7839 round-trip &RestartStrategy::{variant:?} to the same \
7840 lifted SUPERVISOR_ESTRATEGIA_* const \
7841 RestartStrategy::as_str returns — divergence signals a \
7842 silent detour off the substrate-primitive accessor"
7843 );
7844 let via_into: &'static str = variant.into();
7845 assert_eq!(
7846 via_into, via_method,
7847 "Into<&'static str>::into on &RestartStrategy::{variant:?} \
7848 must byte-equal RestartStrategy::as_str on the same input — \
7849 the blanket-derived Into shape must resolve to the same \
7850 as_str dispatch as the explicit From impl"
7851 );
7852 }
7853 assert_eq!(
7854 [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
7855 [
7856 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7857 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7858 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7859 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7860 ],
7861 "const-context RestartStrategy::as_str must resolve to the \
7862 four lifted SUPERVISOR_ESTRATEGIA_* consts — the borrowed-\
7863 input From<&RestartStrategy> for &'static str impl inherits \
7864 its `'static` lifetime promise from the same accessor the \
7865 owned-input sibling routes through"
7866 );
7867 }
7868
7869 #[test]
7870 fn restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
7871 // Cross-axis partition pin: the paired trait-idiomatic
7872 // owned-input `From<RestartStrategy> for &'static str` (523157d
7873 // campaign-shape) and borrowed-input `From<&RestartStrategy> for
7874 // &'static str` (this lift) forward projections must resolve
7875 // identically on every arm, locking the two input-shape paths
7876 // together so any future detour trips at caixa-core test time.
7877 // Then a witness that a `.iter().map(Into::into)` pipe over
7878 // [`RestartStrategy::ALL`] (whose iterator yields
7879 // `&RestartStrategy`) materializes the four-arm accept-set
7880 // through the borrowed-input axis alone — the exact shape a
7881 // future wasm-operator per-supervisor sibling-restart-strategy
7882 // diagnostic line, a future substrate-wide per-arm diagnostic
7883 // column, or a
7884 // `HashMap::<&'static str, RestartStrategy>::from_iter(
7885 // RestartStrategy::ALL.iter().map(|s| (s.into(), *s)))`-style
7886 // per-strategy lookup reaches through — closing the two-way
7887 // owned/borrowed input-shape symmetry on the forward-projection
7888 // trait-idiomatic axis. Peer of the sibling
7889 // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
7890 // (64aa742) /
7891 // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
7892 // (5ab993a) /
7893 // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
7894 // (807b0b5) partition pins on the sibling closed-set typed-enum
7895 // discriminator axes — extends the borrowed-input axis
7896 // discipline onto the first M2 OTP-shape sibling-restart
7897 // closed-set typed enum on the caixa surface. Also closes the
7898 // direct two-way `&Self → &'static str → Self` round-trip via
7899 // the paired [`TryFrom<&str>`] axis — unlike the peer
7900 // [`crate::CaixaKind`] axis pair (whose forward `From` emits
7901 // lowercase Portuguese diagnostic bytes while the reverse
7902 // `TryFrom` parses `PascalCase` wire bytes, forcing the round-
7903 // trip through an intermediate wire-vocab hop), the
7904 // [`RestartStrategy::as_str`] emit and
7905 // [`RestartStrategy::from_wire`] parse share the same
7906 // `PascalCase` vocabulary by construction, so the borrowed-
7907 // input forward axis and the reverse axis compose directly.
7908 for &variant in RestartStrategy::ALL {
7909 let owned: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
7910 let borrowed: &'static str = <&'static str as From<&RestartStrategy>>::from(&variant);
7911 assert_eq!(
7912 owned, borrowed,
7913 "From<RestartStrategy> and From<&RestartStrategy> for \
7914 &'static str must resolve identically on \
7915 RestartStrategy::{variant:?} — divergence signals the \
7916 owned-input and borrowed-input forward-projection paths \
7917 have drifted onto different emit-sets"
7918 );
7919 }
7920 let via_iter: Vec<&'static str> = RestartStrategy::ALL.iter().map(Into::into).collect();
7921 let via_method: Vec<&'static str> =
7922 RestartStrategy::ALL.iter().map(|s| s.as_str()).collect();
7923 assert_eq!(
7924 via_iter, via_method,
7925 "`.iter().map(Into::into)` over RestartStrategy::ALL must \
7926 byte-equal `.iter().map(|s| s.as_str())` on every arm — the \
7927 borrowed-input `From<&RestartStrategy> for &'static str` \
7928 axis is what makes the `.iter().map(Into::into)` shape route \
7929 through the substrate-primitive `RestartStrategy::as_str` \
7930 accessor rather than through a per-call-site `.copied()` / \
7931 dereference detour"
7932 );
7933 for variant in RestartStrategy::ALL {
7934 let emitted: &'static str = variant.into();
7935 let re_parsed: Result<RestartStrategy, ()> =
7936 <RestartStrategy as TryFrom<&str>>::try_from(emitted);
7937 assert_eq!(
7938 re_parsed,
7939 Ok(*variant),
7940 "trait-idiomatic borrowed-input forward-projection + \
7941 reverse-projection axis pair must round-trip \
7942 &RestartStrategy::{variant:?} through `.into::<&'static \
7943 str>()` (via the borrowed-input axis) and back through \
7944 `TryFrom<&str>` — a break signals the borrowed-input \
7945 forward-emit and reverse-parse axes have drifted onto \
7946 different vocabularies"
7947 );
7948 }
7949 }
7950
7951 #[test]
7952 fn restart_strategy_from_into_owned_string_routes_through_as_str_accessor() {
7953 // Fail-before-pass-after byte-parity pin on the newly lifted
7954 // `impl From<RestartStrategy> for String` — asserts the
7955 // owned-`String`-returning standard-library trait impl and the
7956 // substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
7957 // accessor resolve to the same four-arm emit-set across every
7958 // arm the exhaustive [`RestartStrategy::ALL`] slice enumerates.
7959 // Rust's standard library does not carry a blanket
7960 // `impl<T: AsRef<str>> From<T> for String` (nor an
7961 // `impl<T: fmt::Display> From<T> for String`), so the
7962 // owned-`String` forward-projection axis is a distinct
7963 // trait-idiomatic surface that a
7964 // `let key: String = strategy.into();`-shaped call site
7965 // reaches through this impl and no other — the paired sibling
7966 // `From<RestartStrategy> for &'static str` impl forces every
7967 // owned-`String` call site through an explicit
7968 // `.to_owned()` / `String::from` restatement.
7969 for &variant in RestartStrategy::ALL {
7970 let via_trait: String = <String as From<RestartStrategy>>::from(variant);
7971 let via_method: &'static str = variant.as_str();
7972 assert_eq!(
7973 via_trait.as_str(),
7974 via_method,
7975 "From<RestartStrategy> for String impl must round-trip \
7976 RestartStrategy::{variant:?} to the same lifted \
7977 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
7978 returns — divergence signals a silent detour off the \
7979 substrate-primitive accessor"
7980 );
7981 let via_into: String = variant.into();
7982 assert_eq!(
7983 via_into.as_str(),
7984 via_method,
7985 "Into<String>::into on RestartStrategy::{variant:?} must \
7986 byte-equal RestartStrategy::as_str on the same input — the \
7987 blanket-derived Into shape must resolve to the same as_str \
7988 dispatch as the explicit From impl"
7989 );
7990 }
7991 }
7992
7993 #[test]
7994 fn restart_strategy_from_into_owned_string_and_static_str_agree_on_every_arm() {
7995 // Cross-axis partition pin: the paired trait-idiomatic
7996 // owned-`String` `From<RestartStrategy> for String` (this lift)
7997 // and owned-`&'static str` `From<RestartStrategy> for &'static
7998 // str` (523157d) forward projections must resolve identically
7999 // on every arm, locking the two return-type-shape paths
8000 // together so any future detour trips at caixa-core test time.
8001 // Also byte-parity witness against the sibling
8002 // [`ToString::to_string`] surface routed through
8003 // [`std::fmt::Display`] — the three owned-heap-string paths
8004 // (`.into::<String>()`, `String::from`, `.to_string()`) must
8005 // resolve identically on every arm so a future consumer that
8006 // picks any of the three lands on the same lifted
8007 // SUPERVISOR_ESTRATEGIA_* const. Then a direct round-trip
8008 // witness through the paired trait-idiomatic reverse
8009 // [`TryFrom<&str>`] axis on the owned-`String`'s
8010 // [`String::as_str`] borrow that closes the two-way
8011 // `Self → String → Self` round-trip on the trait-idiomatic
8012 // owned-`String` forward + reverse axis pair.
8013 for &variant in RestartStrategy::ALL {
8014 let owned_string: String = <String as From<RestartStrategy>>::from(variant);
8015 let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8016 assert_eq!(
8017 owned_string.as_str(),
8018 owned_static,
8019 "From<RestartStrategy> for String and From<RestartStrategy> \
8020 for &'static str must resolve identically on \
8021 RestartStrategy::{variant:?} — divergence signals the \
8022 owned-`String` and owned-`&'static str` forward-projection \
8023 return-type-shape paths have drifted onto different \
8024 emit-sets"
8025 );
8026 let via_to_string: String = variant.to_string();
8027 assert_eq!(
8028 owned_string, via_to_string,
8029 "From<RestartStrategy> for String must byte-equal \
8030 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
8031 divergence signals the trait-idiomatic owned-`String` \
8032 forward-projection axis and the ToString-through-Display \
8033 axis have drifted onto different emit-sets"
8034 );
8035 }
8036 let via_iter: Vec<String> = RestartStrategy::ALL
8037 .iter()
8038 .copied()
8039 .map(String::from)
8040 .collect();
8041 let via_method: Vec<String> = RestartStrategy::ALL
8042 .iter()
8043 .map(|s| s.as_str().to_owned())
8044 .collect();
8045 assert_eq!(
8046 via_iter, via_method,
8047 "`.iter().copied().map(String::from)` over RestartStrategy::ALL \
8048 must byte-equal `.iter().map(|s| s.as_str().to_owned())` on \
8049 every arm — the owned-`String` `From<RestartStrategy> for \
8050 String` axis is what makes the `String::from` composition \
8051 route through the substrate-primitive `RestartStrategy::as_str` \
8052 accessor rather than through a per-call-site `.to_owned()` / \
8053 `String::from(strategy.as_str())` detour"
8054 );
8055 for &variant in RestartStrategy::ALL {
8056 let emitted: String = variant.into();
8057 let re_parsed: Result<RestartStrategy, ()> =
8058 <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
8059 assert_eq!(
8060 re_parsed,
8061 Ok(variant),
8062 "trait-idiomatic owned-`String` forward-projection + \
8063 reverse-projection axis pair must round-trip \
8064 RestartStrategy::{variant:?} through `.into::<String>()` \
8065 and back through `TryFrom<&str>` on the owned-`String`'s \
8066 String::as_str borrow — a break signals the owned-`String` \
8067 forward-emit and reverse-parse axes have drifted onto \
8068 different vocabularies"
8069 );
8070 }
8071 }
8072
8073 #[test]
8074 fn restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
8075 // Fail-before-pass-after byte-parity pin on the newly lifted
8076 // `impl From<&RestartStrategy> for String` — asserts the
8077 // borrowed-input owned-`String`-returning standard-library trait
8078 // impl and the substrate-primitive [`RestartStrategy::as_str`]
8079 // `pub const fn` accessor resolve to the same four-arm emit-set
8080 // across every arm the exhaustive [`RestartStrategy::ALL`] slice
8081 // enumerates. Rust's standard library does not carry a blanket
8082 // `impl<T: AsRef<str>> From<&T> for String` (nor an
8083 // `impl<T: fmt::Display> From<&T> for String`), so the
8084 // borrowed-input owned-`String` forward-projection axis is a
8085 // distinct trait-idiomatic surface that a
8086 // `let key: String = (&strategy).into();`-shaped call site
8087 // reaches through this impl and no other — the paired sibling
8088 // `From<RestartStrategy> for String` impl forces every
8089 // borrowed-input call site through an explicit `Copy` deref
8090 // (`String::from(*strategy)`) or an `.as_str().to_owned()` /
8091 // `.to_string()` detour.
8092 for &variant in RestartStrategy::ALL {
8093 let via_trait: String = <String as From<&RestartStrategy>>::from(&variant);
8094 let via_method: &'static str = variant.as_str();
8095 assert_eq!(
8096 via_trait.as_str(),
8097 via_method,
8098 "From<&RestartStrategy> for String impl must round-trip \
8099 &RestartStrategy::{variant:?} to the same lifted \
8100 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
8101 returns — divergence signals a silent detour off the \
8102 substrate-primitive accessor"
8103 );
8104 let via_into: String = (&variant).into();
8105 assert_eq!(
8106 via_into.as_str(),
8107 via_method,
8108 "Into<String>::into on &RestartStrategy::{variant:?} must \
8109 byte-equal RestartStrategy::as_str on the same input — the \
8110 blanket-derived Into shape must resolve to the same as_str \
8111 dispatch as the explicit From impl"
8112 );
8113 }
8114 }
8115
8116 #[test]
8117 fn restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
8118 // Cross-axis partition pin: the newly lifted trait-idiomatic
8119 // borrowed-input owned-`String` `From<&RestartStrategy> for
8120 // String` (this lift), the paired owned-input owned-`String`
8121 // `From<RestartStrategy> for String` (7baa18a), the paired
8122 // borrowed-input owned-`&'static str` `From<&RestartStrategy>
8123 // for &'static str` (e941836), and the paired owned-input
8124 // owned-`&'static str` `From<RestartStrategy> for &'static str`
8125 // (523157d) — every corner of the `{Self, &Self} × {&'static
8126 // str, String}` 2×2 trait-idiomatic projection family — must
8127 // resolve identically on every arm, locking the four
8128 // return-shape × input-shape paths together so any future
8129 // detour trips at caixa-core test time. Also byte-parity
8130 // witness against the sibling [`ToString::to_string`] surface
8131 // routed through [`std::fmt::Display`] and a direct round-trip
8132 // witness through the paired trait-idiomatic reverse
8133 // [`TryFrom<&str>`] axis on the owned-`String`'s
8134 // [`String::as_str`] borrow that closes the two-way
8135 // `&Self → String → Self` round-trip on the trait-idiomatic
8136 // borrowed-input owned-`String` forward + reverse axis pair.
8137 for &variant in RestartStrategy::ALL {
8138 let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
8139 let owned_string: String = <String as From<RestartStrategy>>::from(variant);
8140 let borrowed_static: &'static str =
8141 <&'static str as From<&RestartStrategy>>::from(&variant);
8142 let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8143 assert_eq!(
8144 borrowed_string, owned_string,
8145 "From<&RestartStrategy> for String and From<RestartStrategy> \
8146 for String must resolve identically on \
8147 RestartStrategy::{variant:?} — divergence signals the \
8148 borrowed-input and owned-input owned-`String` \
8149 forward-projection input-shape paths have drifted onto \
8150 different emit-sets"
8151 );
8152 assert_eq!(
8153 borrowed_string.as_str(),
8154 borrowed_static,
8155 "From<&RestartStrategy> for String and From<&RestartStrategy> \
8156 for &'static str must resolve identically on \
8157 RestartStrategy::{variant:?} — divergence signals the \
8158 borrowed-input `&'static str` and owned-`String` \
8159 return-shape paths have drifted onto different emit-sets"
8160 );
8161 assert_eq!(
8162 borrowed_string.as_str(),
8163 owned_static,
8164 "From<&RestartStrategy> for String and From<RestartStrategy> \
8165 for &'static str must resolve identically on \
8166 RestartStrategy::{variant:?} — divergence signals a break \
8167 in the diagonal corner of the {{Self, &Self}} × \
8168 {{&'static str, String}} 2×2 trait-idiomatic \
8169 projection family"
8170 );
8171 let via_to_string: String = variant.to_string();
8172 assert_eq!(
8173 borrowed_string, via_to_string,
8174 "From<&RestartStrategy> for String must byte-equal \
8175 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
8176 divergence signals the trait-idiomatic borrowed-input \
8177 owned-`String` forward-projection axis and the \
8178 ToString-through-Display axis have drifted onto different \
8179 emit-sets"
8180 );
8181 }
8182 let via_iter: Vec<String> = RestartStrategy::ALL.iter().map(String::from).collect();
8183 let via_method: Vec<String> = RestartStrategy::ALL
8184 .iter()
8185 .map(|s| s.as_str().to_owned())
8186 .collect();
8187 assert_eq!(
8188 via_iter, via_method,
8189 "`.iter().map(String::from)` over RestartStrategy::ALL — a \
8190 call site whose iteration axis holds `&RestartStrategy` by \
8191 construction — must byte-equal `.iter().map(|s| \
8192 s.as_str().to_owned())` on every arm — the borrowed-input \
8193 owned-`String` `From<&RestartStrategy> for String` axis is \
8194 what makes the `String::from` composition route through the \
8195 substrate-primitive `RestartStrategy::as_str` accessor \
8196 without a spurious `Copy` deref (which would only be \
8197 reachable through the owned-input `From<RestartStrategy> for \
8198 String` axis by first calling `.copied()` on the iterator)"
8199 );
8200 for &variant in RestartStrategy::ALL {
8201 let emitted: String = (&variant).into();
8202 let re_parsed: Result<RestartStrategy, ()> =
8203 <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
8204 assert_eq!(
8205 re_parsed,
8206 Ok(variant),
8207 "trait-idiomatic borrowed-input owned-`String` \
8208 forward-projection + reverse-projection axis pair must \
8209 round-trip &RestartStrategy::{variant:?} through \
8210 `.into::<String>()` on the borrowed-input surface and \
8211 back through `TryFrom<&str>` on the owned-`String`'s \
8212 String::as_str borrow — a break signals the \
8213 borrowed-input owned-`String` forward-emit and \
8214 reverse-parse axes have drifted onto different \
8215 vocabularies"
8216 );
8217 }
8218 }
8219
8220 #[test]
8221 fn restart_strategy_from_into_static_cow_str_routes_through_as_str_accessor() {
8222 // Fail-before-pass-after byte-parity pin on the newly lifted
8223 // `impl From<RestartStrategy> for std::borrow::Cow<'static, str>` —
8224 // asserts the standard-library trait impl and the substrate-
8225 // primitive [`super::RestartStrategy::as_str`] `pub const fn`
8226 // accessor resolve to the same four-arm emit-set across every
8227 // arm the exhaustive [`super::RestartStrategy::ALL`] slice
8228 // enumerates. Rust's standard library does not carry a blanket
8229 // `impl<T: AsRef<str>> From<T> for Cow<'static, str>` (nor an
8230 // `impl<T: fmt::Display> From<T> for Cow<'static, str>`), so
8231 // the `Cow<'static, str>` forward-projection axis is a
8232 // distinct trait-idiomatic surface that a
8233 // `let key: Cow<'static, str> = strategy.into();`-shaped call
8234 // site reaches through this impl and no other — the paired
8235 // sibling `From<RestartStrategy> for &'static str` and
8236 // `From<RestartStrategy> for String` impls force every
8237 // `Cow<'static, str>`-parameterized call site through a
8238 // `Cow::Borrowed(strategy.as_str())` /
8239 // `Cow::Owned(strategy.to_string())` composition whose type
8240 // bounds have no compile-time link back to the substrate
8241 // primitive.
8242 //
8243 // Also asserts the projection lands on the zero-alloc
8244 // [`std::borrow::Cow::Borrowed`] arm (not the
8245 // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
8246 // [`super::RestartStrategy::as_str`] accessor's `&'static str`
8247 // return lifetime by construction makes the borrowed arm the
8248 // type-correct projection with no runtime allocation. Any
8249 // future silent detour that routes the impl through the owned
8250 // arm (an accidental `Cow::Owned(strategy.to_string())` rewrite
8251 // that would allocate on every call site where the
8252 // `&'static str` return of [`super::RestartStrategy::as_str`]
8253 // makes the zero-alloc borrowed projection type-correct) trips
8254 // at caixa-core test time under the
8255 // [`std::borrow::Cow::Borrowed`] discriminator witness rather
8256 // than at a downstream `Cow<'static, str>`-bound consumer's
8257 // silent allocation.
8258 //
8259 // First peer on the substrate-wide trait-idiomatic
8260 // [`std::borrow::Cow<'static, str>`] forward-projection family
8261 // to extend the axis off the top-level [`super::CaixaKind`]
8262 // enum (99c1735 owned-input, d45c409 borrowed-input) onto the
8263 // first M2 OTP-shape closed-set fieldless typed enum on the
8264 // caixa surface.
8265 for &variant in RestartStrategy::ALL {
8266 let via_trait: std::borrow::Cow<'static, str> =
8267 <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
8268 let via_method: &'static str = variant.as_str();
8269 assert_eq!(
8270 via_trait.as_ref(),
8271 via_method,
8272 "From<RestartStrategy> for Cow<'static, str> impl must \
8273 round-trip RestartStrategy::{variant:?} to the same \
8274 lifted SUPERVISOR_ESTRATEGIA_* const \
8275 RestartStrategy::as_str returns — divergence signals a \
8276 silent detour off the substrate-primitive accessor"
8277 );
8278 assert!(
8279 matches!(via_trait, std::borrow::Cow::Borrowed(_)),
8280 "From<RestartStrategy> for Cow<'static, str> impl must \
8281 land on the zero-alloc Cow::Borrowed arm on \
8282 RestartStrategy::{variant:?} — a Cow::Owned outcome \
8283 signals the projection has silently allocated where \
8284 the substrate-primitive RestartStrategy::as_str \
8285 `&'static str` return makes the borrowed arm the \
8286 type-correct projection"
8287 );
8288 let via_into: std::borrow::Cow<'static, str> = variant.into();
8289 assert_eq!(
8290 via_into.as_ref(),
8291 via_method,
8292 "Into<Cow<'static, str>>::into on \
8293 RestartStrategy::{variant:?} must byte-equal \
8294 RestartStrategy::as_str on the same input — the \
8295 blanket-derived Into shape must resolve to the same \
8296 as_str dispatch as the explicit From impl"
8297 );
8298 assert!(
8299 matches!(via_into, std::borrow::Cow::Borrowed(_)),
8300 "Into<Cow<'static, str>>::into on \
8301 RestartStrategy::{variant:?} must land on the \
8302 zero-alloc Cow::Borrowed arm — the blanket-derived \
8303 Into shape must resolve to the same Cow::Borrowed \
8304 dispatch as the explicit From impl"
8305 );
8306 }
8307 }
8308
8309 #[test]
8310 fn restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
8311 // Cross-axis partition pin: the newly lifted trait-idiomatic
8312 // `From<RestartStrategy> for std::borrow::Cow<'static, str>`
8313 // (this lift), the paired owned-input `From<RestartStrategy>
8314 // for &'static str` (523157d), and the paired owned-input
8315 // `From<RestartStrategy> for String` (7baa18a) forward
8316 // projections must resolve identically on every arm, locking
8317 // the three return-shape paths together by construction so any
8318 // future detour trips at caixa-core test time. Also byte-parity
8319 // witness against the sibling [`ToString::to_string`] surface
8320 // routed through [`std::fmt::Display`] — every owned-heap-
8321 // string path (the `Cow::Owned` promotion of this axis's
8322 // `.into_owned()`, `From<RestartStrategy> for String`, and
8323 // `.to_string()`) resolves to the same lifted
8324 // [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const per arm.
8325 //
8326 // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
8327 // witness over [`super::RestartStrategy::ALL`] that
8328 // materializes the four-arm accept-set through the
8329 // [`std::borrow::Cow<'static, str>`] axis alone — the exact
8330 // shape a future `axum::response::IntoResponse` per-strategy
8331 // rejection-body composer, a future M4 admission-webhook
8332 // per-strategy rejection-reason emitter whose typing rules out
8333 // the sibling [`AsRef<str>`] borrowed return, or a future
8334 // substrate-wide per-strategy diagnostic surface that binds
8335 // through a [`Cow<'static, str>`] boundary reaches through.
8336 // The pipe witness also pins the zero-alloc discipline: every
8337 // element in the collected vector satisfies the
8338 // [`std::borrow::Cow::Borrowed`] arm predicate, so a future
8339 // accidental silent-allocation regression on the pipe's
8340 // iteration axis is a caixa-core-test-time failure.
8341 for &variant in RestartStrategy::ALL {
8342 let via_cow: std::borrow::Cow<'static, str> =
8343 <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
8344 let via_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8345 let via_string: String = <String as From<RestartStrategy>>::from(variant);
8346 assert_eq!(
8347 via_cow.as_ref(),
8348 via_static,
8349 "From<RestartStrategy> for Cow<'static, str> and \
8350 From<RestartStrategy> for &'static str must resolve \
8351 identically on RestartStrategy::{variant:?} — \
8352 divergence signals the Cow<'static, str> and \
8353 &'static str return-shape paths have drifted onto \
8354 different emit-sets"
8355 );
8356 assert_eq!(
8357 via_cow.as_ref(),
8358 via_string.as_str(),
8359 "From<RestartStrategy> for Cow<'static, str> and \
8360 From<RestartStrategy> for String must resolve \
8361 identically on RestartStrategy::{variant:?} — \
8362 divergence signals the Cow<'static, str> and String \
8363 return-shape paths have drifted onto different \
8364 emit-sets"
8365 );
8366 let via_to_string: String = variant.to_string();
8367 assert_eq!(
8368 via_cow.as_ref(),
8369 via_to_string.as_str(),
8370 "From<RestartStrategy> for Cow<'static, str> must \
8371 byte-equal RestartStrategy::to_string on \
8372 RestartStrategy::{variant:?} — divergence signals the \
8373 trait-idiomatic Cow<'static, str> forward-projection \
8374 axis and the ToString-through-Display axis have \
8375 drifted onto different emit-sets"
8376 );
8377 }
8378 let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
8379 .iter()
8380 .copied()
8381 .map(std::borrow::Cow::from)
8382 .collect();
8383 let via_method: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
8384 .iter()
8385 .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
8386 .collect();
8387 assert_eq!(
8388 via_iter, via_method,
8389 "`.iter().copied().map(Cow::from)` over \
8390 RestartStrategy::ALL must byte-equal `.iter().map(|s| \
8391 Cow::Borrowed(s.as_str()))` on every arm — the \
8392 trait-idiomatic `From<RestartStrategy> for Cow<'static, \
8393 str>` axis is what makes the `Cow::from` composition \
8394 route through the substrate-primitive \
8395 `RestartStrategy::as_str` accessor with the zero-alloc \
8396 Cow::Borrowed arm by construction, rather than a \
8397 per-call-site `Cow::Owned(strategy.to_string())` \
8398 allocation"
8399 );
8400 for cow in &via_iter {
8401 assert!(
8402 matches!(cow, std::borrow::Cow::Borrowed(_)),
8403 "every element of the \
8404 .iter().copied().map(Cow::from) pipe over \
8405 RestartStrategy::ALL must land on the zero-alloc \
8406 Cow::Borrowed arm — a Cow::Owned outcome on any arm \
8407 signals the pipe's iteration axis has silently \
8408 allocated where the substrate-primitive \
8409 RestartStrategy::as_str `&'static str` return makes \
8410 the borrowed arm the type-correct projection"
8411 );
8412 }
8413 }
8414
8415 #[test]
8416 fn restart_strategy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
8417 // Fail-before-pass-after byte-parity pin on the newly lifted
8418 // `impl From<&RestartStrategy> for std::borrow::Cow<'static, str>` —
8419 // asserts the borrowed-input standard-library trait impl and
8420 // the substrate-primitive [`super::RestartStrategy::as_str`]
8421 // `pub const fn` accessor resolve to the same four-arm emit-
8422 // set across every arm the exhaustive
8423 // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
8424 // standard library does not carry a blanket
8425 // `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor a
8426 // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
8427 // the borrowed-input `Cow<'static, str>` forward-projection
8428 // axis is a distinct trait-idiomatic surface that a
8429 // `let key: Cow<'static, str> = (&strategy).into();`-shaped
8430 // call site or a
8431 // `RestartStrategy::ALL.iter().map(Cow::from)`-shaped pipe
8432 // reaches through this impl and no other — the paired owned-
8433 // input `From<RestartStrategy> for Cow<'static, str>` impl
8434 // (7dd28b3) forces every borrowed-input call site through an
8435 // explicit `Copy` deref (`Cow::from(*strategy)`) or a
8436 // `Cow::Borrowed(strategy.as_str())` open-code whose type
8437 // bounds have no compile-time link back to the substrate
8438 // primitive.
8439 //
8440 // Also asserts the projection lands on the zero-alloc
8441 // [`std::borrow::Cow::Borrowed`] arm (not the
8442 // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
8443 // [`super::RestartStrategy::as_str`] accessor's `&'static str`
8444 // return lifetime by construction makes the borrowed arm the
8445 // type-correct projection with no runtime allocation on the
8446 // borrowed-input surface just as on the paired owned-input
8447 // surface.
8448 //
8449 // Second peer on the substrate-wide trait-idiomatic
8450 // [`std::borrow::Cow<'static, str>`] forward-projection family
8451 // on this enum — closes the `{Self, &Self}` input-shape
8452 // corner of the [`Cow<'static, str>`] axis on the first M2
8453 // OTP-shape closed-set fieldless typed enum peer on the caixa
8454 // surface (`:supervisor :estrategia`), exactly as d45c409
8455 // closed it on the top-level [`super::CaixaKind`] one commit
8456 // after the owning half (99c1735) landed. Every future
8457 // closed-set fieldless typed enum peer on the substrate is a
8458 // future target of the campaign.
8459 for &variant in RestartStrategy::ALL {
8460 let via_trait: std::borrow::Cow<'static, str> =
8461 <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
8462 let via_method: &'static str = variant.as_str();
8463 assert_eq!(
8464 via_trait.as_ref(),
8465 via_method,
8466 "From<&RestartStrategy> for Cow<'static, str> impl must \
8467 round-trip &RestartStrategy::{variant:?} to the same \
8468 lifted SUPERVISOR_ESTRATEGIA_* const \
8469 RestartStrategy::as_str returns — divergence signals a \
8470 silent detour off the substrate-primitive accessor"
8471 );
8472 assert!(
8473 matches!(via_trait, std::borrow::Cow::Borrowed(_)),
8474 "From<&RestartStrategy> for Cow<'static, str> impl must \
8475 land on the zero-alloc Cow::Borrowed arm on \
8476 &RestartStrategy::{variant:?} — a Cow::Owned outcome \
8477 signals the projection has silently allocated where \
8478 the substrate-primitive RestartStrategy::as_str \
8479 `&'static str` return makes the borrowed arm the \
8480 type-correct projection"
8481 );
8482 let via_into: std::borrow::Cow<'static, str> = (&variant).into();
8483 assert_eq!(
8484 via_into.as_ref(),
8485 via_method,
8486 "Into<Cow<'static, str>>::into on \
8487 &RestartStrategy::{variant:?} must byte-equal \
8488 RestartStrategy::as_str on the same input — the \
8489 blanket-derived Into shape must resolve to the same \
8490 as_str dispatch as the explicit From impl"
8491 );
8492 assert!(
8493 matches!(via_into, std::borrow::Cow::Borrowed(_)),
8494 "Into<Cow<'static, str>>::into on \
8495 &RestartStrategy::{variant:?} must land on the \
8496 zero-alloc Cow::Borrowed arm — the blanket-derived \
8497 Into shape must resolve to the same Cow::Borrowed \
8498 dispatch as the explicit From impl"
8499 );
8500 }
8501 }
8502
8503 #[test]
8504 fn restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
8505 // Cross-axis partition pin: the newly lifted trait-idiomatic
8506 // borrowed-input `From<&RestartStrategy> for
8507 // std::borrow::Cow<'static, str>` (this lift), the paired
8508 // owned-input `From<RestartStrategy> for
8509 // std::borrow::Cow<'static, str>` (7dd28b3), the paired
8510 // borrowed-input owned-`&'static str` `From<&RestartStrategy>
8511 // for &'static str`, and the paired borrowed-input owned-
8512 // `String` `From<&RestartStrategy> for String` must resolve
8513 // identically on every arm, locking the four
8514 // return-shape × input-shape paths together by construction so
8515 // any future detour trips at caixa-core test time. Also byte-
8516 // parity witness against the sibling [`ToString::to_string`]
8517 // surface routed through [`std::fmt::Display`] — every owned-
8518 // heap-string path (this axis's `.into_owned()` promotion, the
8519 // paired [`From<&RestartStrategy> for String`], and
8520 // `.to_string()`) resolves to the same lifted
8521 // [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const per arm.
8522 //
8523 // Then a `.iter().map(std::borrow::Cow::from)` pipe witness
8524 // over [`super::RestartStrategy::ALL`] — whose iterator yields
8525 // `&RestartStrategy` by construction, so the borrowed-input
8526 // [`Cow<'static, str>`] axis is what routes the pipe through
8527 // the substrate-primitive [`super::RestartStrategy::as_str`]
8528 // accessor without a spurious [`Copy`] deref (which would only
8529 // be reachable through the owned-input
8530 // [`From<RestartStrategy> for Cow<'static, str>`] axis by
8531 // first calling `.copied()` on the iterator). The pipe witness
8532 // also pins the zero-alloc discipline: every element in the
8533 // collected vector satisfies the [`std::borrow::Cow::Borrowed`]
8534 // arm predicate, so a future accidental silent-allocation
8535 // regression on the pipe's iteration axis is a caixa-core-
8536 // test-time failure.
8537 for &strategy in RestartStrategy::ALL {
8538 let borrowed_cow: std::borrow::Cow<'static, str> =
8539 <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&strategy);
8540 let owned_cow: std::borrow::Cow<'static, str> =
8541 <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(strategy);
8542 let borrowed_static: &'static str =
8543 <&'static str as From<&RestartStrategy>>::from(&strategy);
8544 let borrowed_string: String = <String as From<&RestartStrategy>>::from(&strategy);
8545 assert_eq!(
8546 borrowed_cow, owned_cow,
8547 "From<&RestartStrategy> for Cow<'static, str> and \
8548 From<RestartStrategy> for Cow<'static, str> must \
8549 resolve identically on RestartStrategy::{strategy:?} — \
8550 divergence signals the borrowed-input and owned-input \
8551 Cow<'static, str> forward-projection input-shape \
8552 paths have drifted onto different emit-sets"
8553 );
8554 assert_eq!(
8555 borrowed_cow.as_ref(),
8556 borrowed_static,
8557 "From<&RestartStrategy> for Cow<'static, str> and \
8558 From<&RestartStrategy> for &'static str must resolve \
8559 identically on RestartStrategy::{strategy:?} — \
8560 divergence signals the borrowed-input Cow<'static, \
8561 str> and &'static str return-shape paths have drifted \
8562 onto different emit-sets"
8563 );
8564 assert_eq!(
8565 borrowed_cow.as_ref(),
8566 borrowed_string.as_str(),
8567 "From<&RestartStrategy> for Cow<'static, str> and \
8568 From<&RestartStrategy> for String must resolve \
8569 identically on RestartStrategy::{strategy:?} — \
8570 divergence signals the borrowed-input Cow<'static, \
8571 str> and owned-`String` return-shape paths have \
8572 drifted onto different emit-sets"
8573 );
8574 let via_to_string: String = strategy.to_string();
8575 assert_eq!(
8576 borrowed_cow.as_ref(),
8577 via_to_string.as_str(),
8578 "From<&RestartStrategy> for Cow<'static, str> must \
8579 byte-equal RestartStrategy::to_string on \
8580 RestartStrategy::{strategy:?} — divergence signals \
8581 the trait-idiomatic borrowed-input Cow<'static, str> \
8582 forward-projection axis and the ToString-through-\
8583 Display axis have drifted onto different emit-sets"
8584 );
8585 }
8586 let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
8587 .iter()
8588 .map(std::borrow::Cow::from)
8589 .collect();
8590 let via_method: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
8591 .iter()
8592 .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
8593 .collect();
8594 assert_eq!(
8595 via_iter, via_method,
8596 "`.iter().map(Cow::from)` over RestartStrategy::ALL — a \
8597 call site whose iteration axis holds `&RestartStrategy` \
8598 by construction — must byte-equal `.iter().map(|s| \
8599 Cow::Borrowed(s.as_str()))` on every arm — the borrowed-\
8600 input Cow<'static, str> `From<&RestartStrategy> for \
8601 Cow<'static, str>` axis is what makes the `Cow::from` \
8602 composition route through the substrate-primitive \
8603 `RestartStrategy::as_str` accessor with the zero-alloc \
8604 Cow::Borrowed arm by construction and without a spurious \
8605 `Copy` deref (which would only be reachable through the \
8606 owned-input `From<RestartStrategy> for Cow<'static, str>` \
8607 axis by first calling `.copied()` on the iterator)"
8608 );
8609 for cow in &via_iter {
8610 assert!(
8611 matches!(cow, std::borrow::Cow::Borrowed(_)),
8612 "every element of the .iter().map(Cow::from) pipe \
8613 over RestartStrategy::ALL must land on the zero-\
8614 alloc Cow::Borrowed arm — a Cow::Owned outcome on \
8615 any arm signals the pipe's iteration axis has \
8616 silently allocated where the substrate-primitive \
8617 RestartStrategy::as_str `&'static str` return makes \
8618 the borrowed arm the type-correct projection"
8619 );
8620 }
8621 }
8622
8623 #[test]
8624 fn restart_policy_try_from_str_routes_through_from_wire_accessor() {
8625 // Fail-before-pass-after byte-parity pin on the newly lifted
8626 // `impl TryFrom<&str> for RestartPolicy` — asserts the standard-
8627 // library trait impl and the substrate-primitive
8628 // [`RestartPolicy::from_wire`] `Option<Self>` accessor resolve to
8629 // the same three-arm accept-set across every arm the exhaustive
8630 // [`RestartPolicy::ALL`] slice enumerates. Any future silent
8631 // detour that routes the trait impl through a divergent
8632 // projection (a per-arm inline `match s { "Permanent" =>
8633 // Ok(Self::Permanent), … }` re-inlining that opens a compile-time
8634 // link to the un-lifted arm-literal, a hypothetical
8635 // `#[serde(rename_all = "…")]` attribute drift that silently
8636 // splits the wire byte-string from every consumer that reaches
8637 // for this typed dispatch, an accidental swap onto the kebab-case
8638 // dispatcher-catalog axis the pre-existing [`std::str::FromStr`]
8639 // impl parses through and which would collide the two-axis
8640 // wire/catalog split the sibling [`RestartPolicy::from_wire`]
8641 // doc block makes load-bearing) trips at caixa-core test time
8642 // under `assert_eq!` rather than at a downstream
8643 // `impl TryFrom<&str>`-bound consumer's silent split. Sweeps
8644 // every one of the three arms [`RestartPolicy::ALL`] carries so
8645 // no arm's projection is covered only by the sibling method-
8646 // named `from_wire` path. Peer of the sibling
8647 // [`restart_strategy_try_from_str_routes_through_from_wire_accessor`]
8648 // (5b828ed) — extends the trait-idiomatic reverse-projection
8649 // axis onto the third and final M2-OTP-shape closed-set typed
8650 // enum on the caixa surface (the paired per-child restart-
8651 // decision-policy sibling on the same M2 `:supervisor` slot).
8652 for &variant in RestartPolicy::ALL {
8653 let wire = variant.as_str();
8654 assert_eq!(
8655 <RestartPolicy as TryFrom<&str>>::try_from(wire),
8656 Ok(variant),
8657 "TryFrom<&str> impl on RestartPolicy must round-trip \
8658 RestartPolicy::{variant:?}.as_str() = {wire:?} back to \
8659 Ok(RestartPolicy::{variant:?}) — divergence from \
8660 RestartPolicy::from_wire signals a silent detour off \
8661 the substrate-primitive accessor"
8662 );
8663 assert_eq!(
8664 <RestartPolicy as TryFrom<&str>>::try_from(wire).ok(),
8665 RestartPolicy::from_wire(wire),
8666 "TryFrom<&str> ok()-projection on {wire:?} must byte-\
8667 equal RestartPolicy::from_wire on the same input"
8668 );
8669 }
8670 }
8671
8672 #[test]
8673 fn restart_policy_try_from_str_rejects_unknown_byte_strings() {
8674 // Rejection witness on the `impl TryFrom<&str> for
8675 // RestartPolicy` — sweeps a candidate set of byte-strings
8676 // outside the three-arm PascalCase wire accept-set the sibling
8677 // [`RestartPolicy::as_str`] emits and asserts every one lands on
8678 // `Err(())`, so a future accidental widening of the trait impl's
8679 // accept-set (a stray additional
8680 // `_ if s.eq_ignore_ascii_case("Permanent") => Ok(…)` case-fold
8681 // path, a silent inclusion of the kebab-case dispatcher-catalog
8682 // byte-string the pre-existing [`std::str::FromStr`] impl the
8683 // [`gen_platform::FromStrKind`] derive installs parses onto the
8684 // wire axis — which would collide the two-axis
8685 // wire/dispatcher-catalog split the sibling
8686 // [`RestartPolicy::from_wire`] doc block makes load-bearing —
8687 // an English-rebrand or plural-arm silent alias that would widen
8688 // the wire accept-set past the OTP-canonical three) trips at
8689 // caixa-core test time. The candidate set includes the empty
8690 // string, whitespace-only padding, the kebab-case dispatcher-
8691 // catalog byte-strings on the sibling axis (a caller who
8692 // confuses the two axes trips here rather than at a downstream
8693 // consumer's silent reject), a lowercase / uppercase / mixed-case
8694 // fold of each PascalCase arm (a caller who assumes case-fold
8695 // acceptance trips here), leading/trailing whitespace padding,
8696 // the trailing-newline shape, quote-wrapped candidates, and a
8697 // residual set of plausible-but-wrong English rebrand
8698 // candidates. Peer of the sibling
8699 // [`restart_strategy_try_from_str_rejects_unknown_byte_strings`]
8700 // (5b828ed) rejection witness.
8701 let rejected: &[&str] = &[
8702 "",
8703 " ",
8704 "\n",
8705 "\t",
8706 "permanent",
8707 "temporary",
8708 "transient",
8709 "PERMANENT",
8710 "TEMPORARY",
8711 "TRANSIENT",
8712 "Permanents",
8713 "Permanent ",
8714 " Permanent",
8715 " Temporary ",
8716 "Permanent\n",
8717 "Transient\t",
8718 "\"Permanent\"",
8719 "Ephemeral",
8720 "Always",
8721 "Never",
8722 "OnAbnormalExit",
8723 "intrinsic",
8724 "?",
8725 ];
8726 for &input in rejected {
8727 assert_eq!(
8728 <RestartPolicy as TryFrom<&str>>::try_from(input),
8729 Err(()),
8730 "TryFrom<&str> impl on RestartPolicy must reject the \
8731 non-wire byte-string {input:?} — silent acceptance \
8732 signals an accept-set widening off the paired \
8733 RestartPolicy::from_wire resolver"
8734 );
8735 }
8736 }
8737
8738 #[test]
8739 fn restart_policy_try_from_str_and_from_wire_partition_the_accept_set() {
8740 // Cross-axis partition pin: the paired `TryFrom<&str>` and
8741 // `from_wire` reverse projections must resolve identically on
8742 // *every* input, not just the ones [`RestartPolicy::ALL`]
8743 // enumerates. Sweeps a mixed candidate set spanning accepted
8744 // (three-arm PascalCase wire byte-strings) and rejected (kebab-
8745 // case dispatcher-catalog byte-strings, empty, whitespace-
8746 // padded, quoted, English-rebrand candidates) inputs and asserts
8747 // the trait's `Result::ok()` projection byte-equals the method-
8748 // named resolver's `Option<Self>` return-shape on each, locking
8749 // the two paths together by construction so any future detour
8750 // (a stray `try_from` special-case that widens or narrows the
8751 // accept-set outside the paired `from_wire` resolver, an
8752 // accidental swap onto the kebab-case [`std::str::FromStr`]
8753 // impl the [`gen_platform::FromStrKind`] derive installs on the
8754 // sibling dispatcher-catalog axis) trips at caixa-core test
8755 // time. Peer of the sibling
8756 // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
8757 // pin — extends the round-trip discipline onto the M2-OTP-shape
8758 // per-child restart-policy axis.
8759 let candidates: &[&str] = &[
8760 "Permanent",
8761 "Temporary",
8762 "Transient",
8763 "",
8764 "permanent",
8765 "temporary",
8766 "transient",
8767 "PERMANENT",
8768 "unknown",
8769 "Permanent ",
8770 " Permanent",
8771 "\"Permanent\"",
8772 "Ephemeral",
8773 "OnAbnormalExit",
8774 "?",
8775 ];
8776 for &input in candidates {
8777 let via_trait: Option<RestartPolicy> =
8778 <RestartPolicy as TryFrom<&str>>::try_from(input).ok();
8779 let via_method: Option<RestartPolicy> = RestartPolicy::from_wire(input);
8780 assert_eq!(
8781 via_trait, via_method,
8782 "TryFrom<&str> and from_wire must resolve identically on \
8783 input {input:?} — divergence signals the two reverse-\
8784 projection paths have drifted onto different accept-sets"
8785 );
8786 }
8787 }
8788
8789 #[test]
8790 fn restart_policy_from_into_static_str_routes_through_as_str_accessor() {
8791 // Fail-before-pass-after byte-parity pin on the newly lifted
8792 // `impl From<RestartPolicy> for &'static str` — asserts the
8793 // standard-library trait impl and the substrate-primitive
8794 // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
8795 // the same three-arm emit-set across every arm the exhaustive
8796 // [`RestartPolicy::ALL`] slice enumerates. Any future silent
8797 // detour that routes the trait impl through a divergent
8798 // projection (a per-arm inline `match policy { Permanent =>
8799 // "Permanent", … }` re-inlining that opens a compile-time link
8800 // to the un-lifted arm-literal, an accidental swap onto the
8801 // sibling kebab-case [`Self::discriminant`] dispatcher-catalog
8802 // axis that would collide the two-axis wire/catalog split the
8803 // sibling [`RestartPolicy::from_wire`] doc block makes
8804 // load-bearing) trips at caixa-core test time under
8805 // `assert_eq!` rather than at a downstream
8806 // `impl Into<&'static str>`-bound consumer's silent split.
8807 // Sweeps every one of the three arms [`RestartPolicy::ALL`]
8808 // carries so no arm's projection is covered only by the sibling
8809 // method-named `as_str` / [`std::fmt::Display`] / [`AsRef<str>`]
8810 // paths. Materializes the `<&'static str as
8811 // From<RestartPolicy>>::from` output in a `const`-shape binding
8812 // to make the `'static` lifetime promise a build-time invariant
8813 // — a future accidental downgrade of any of the three arms'
8814 // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] constants to a
8815 // non-`&'static str` (a `String::leak()`-produced return, a
8816 // `Box::leak`-cast) trips at caixa-core build time rather than
8817 // at a downstream `'static`-bound consumer. Peer of the sibling
8818 // [`restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
8819 // (523157d) — extends the trait-idiomatic forward-projection
8820 // axis onto the second (and second-of-two-in-M2) closed-set
8821 // typed enum on the caixa surface (the paired per-child
8822 // restart-decision-policy sibling on the same M2 `:supervisor`
8823 // slot).
8824 const PERMANENT: &str = RestartPolicy::Permanent.as_str();
8825 const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
8826 const TRANSIENT: &str = RestartPolicy::Transient.as_str();
8827 for &variant in RestartPolicy::ALL {
8828 let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
8829 let via_method: &'static str = variant.as_str();
8830 assert_eq!(
8831 via_trait, via_method,
8832 "From<RestartPolicy> for &'static str impl must round-trip \
8833 RestartPolicy::{variant:?} to the same lifted \
8834 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str returns — \
8835 divergence signals a silent detour off the substrate-primitive \
8836 accessor"
8837 );
8838 let via_into: &'static str = variant.into();
8839 assert_eq!(
8840 via_into, via_method,
8841 "Into<&'static str>::into on RestartPolicy::{variant:?} must \
8842 byte-equal RestartPolicy::as_str on the same input — the \
8843 blanket-derived Into shape must resolve to the same as_str \
8844 dispatch as the explicit From impl"
8845 );
8846 }
8847 assert_eq!(
8848 [PERMANENT, TEMPORARY, TRANSIENT],
8849 [
8850 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
8851 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
8852 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
8853 ],
8854 "const-context RestartPolicy::as_str must resolve to the three \
8855 lifted SUPERVISOR_CHILD_RESTART_* consts — a future accidental \
8856 downgrade of any arm to a non-const or non-static byte-string \
8857 breaks the `&'static str`-lifetime promise the paired \
8858 From<RestartPolicy> for &'static str impl carries by \
8859 construction"
8860 );
8861 }
8862
8863 #[test]
8864 fn restart_policy_from_into_static_str_and_as_str_partition_the_emit_set() {
8865 // Cross-axis partition pin: the paired trait-idiomatic
8866 // `From<RestartPolicy> for &'static str` forward projection and
8867 // the method-named [`RestartPolicy::as_str`] forward projection
8868 // must resolve identically on *every* arm, not just the ones
8869 // named in the primary byte-parity pin above. Sweeps every
8870 // [`RestartPolicy::ALL`] arm and asserts the trait's `From::from`
8871 // output byte-equals the method-named accessor's return-value on
8872 // each, locking the two forward-projection paths together by
8873 // construction so any future detour (a stray `From` special-case
8874 // that lands on a divergent per-arm literal outside the paired
8875 // `as_str` dispatch, a hypothetical rebrand touching one axis
8876 // without the other) trips at caixa-core test time. Peer of the
8877 // sibling forward-projection partition pin
8878 // [`restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
8879 // (523157d) — extends the round-trip discipline onto the
8880 // second-of-two M2-OTP-shape closed-set typed enum on the caixa
8881 // surface, closing the two-way `Self ↔ &'static str` round-trip
8882 // on the trait-idiomatic pair (`From<Self> for &'static str` +
8883 // `TryFrom<&str> for Self`) as well as the pre-existing method-
8884 // named pair (`as_str` + `from_wire`).
8885 for &variant in RestartPolicy::ALL {
8886 let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
8887 let via_method: &'static str = variant.as_str();
8888 assert_eq!(
8889 via_trait, via_method,
8890 "From<RestartPolicy> for &'static str and \
8891 RestartPolicy::as_str must resolve identically on \
8892 RestartPolicy::{variant:?} — divergence signals the \
8893 two forward-projection paths have drifted onto different \
8894 emit-sets"
8895 );
8896 }
8897 // Round-trip witness: every arm's forward `From` output re-parses
8898 // through the paired trait-idiomatic reverse `TryFrom<&str>` back
8899 // to the original variant. Closes the two-way `RestartPolicy ↔
8900 // &'static str` round-trip on the trait-idiomatic axis pair,
8901 // mirroring the pre-existing method-named `as_str` + `from_wire`
8902 // round-trip on the substrate-primitive axis pair.
8903 for &variant in RestartPolicy::ALL {
8904 let emitted: &'static str = variant.into();
8905 let re_parsed: Result<RestartPolicy, ()> =
8906 <RestartPolicy as TryFrom<&str>>::try_from(emitted);
8907 assert_eq!(
8908 re_parsed,
8909 Ok(variant),
8910 "trait-idiomatic axis pair must round-trip \
8911 RestartPolicy::{variant:?} through `.into::<&'static \
8912 str>()` and back through `TryFrom<&str>` — a break signals \
8913 the forward-emit and reverse-parse axes have drifted onto \
8914 different vocabularies"
8915 );
8916 }
8917 }
8918
8919 #[test]
8920 fn restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
8921 // Fail-before-pass-after byte-parity pin on the newly lifted
8922 // `impl From<&RestartPolicy> for &'static str` — asserts the
8923 // borrowed-input standard-library trait impl and the substrate-
8924 // primitive [`RestartPolicy::as_str`] `pub const fn` accessor
8925 // resolve to the same three-arm emit-set across every arm the
8926 // exhaustive [`RestartPolicy::ALL`] slice enumerates. Rust's
8927 // `From` trait does not auto-derive the borrowed-input sibling
8928 // from a paired owned-input impl (no `impl<T, U> From<&T> for U
8929 // where T: Copy, U: From<T>` blanket in `core`), so the
8930 // borrowed-input axis is a distinct trait-idiomatic surface
8931 // that a `.iter().map(Into::into)` shape over
8932 // [`RestartPolicy::ALL`] (whose iterator yields
8933 // `&RestartPolicy`, not `RestartPolicy`) reaches through this
8934 // impl and no other — the paired owned-input
8935 // [`From<RestartPolicy>`] impl requires an explicit `.copied()`
8936 // / dereference before the trait fires. Materializes the
8937 // `<&'static str as From<&RestartPolicy>>::from` output in a
8938 // `const`-shape binding to make the `'static` lifetime promise
8939 // a build-time invariant.
8940 const PERMANENT: &str = RestartPolicy::Permanent.as_str();
8941 const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
8942 const TRANSIENT: &str = RestartPolicy::Transient.as_str();
8943 for variant in RestartPolicy::ALL {
8944 let via_trait: &'static str = <&'static str as From<&RestartPolicy>>::from(variant);
8945 let via_method: &'static str = variant.as_str();
8946 assert_eq!(
8947 via_trait, via_method,
8948 "From<&RestartPolicy> for &'static str impl must round-trip \
8949 &RestartPolicy::{variant:?} to the same lifted \
8950 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
8951 returns — divergence signals a silent detour off the \
8952 substrate-primitive accessor"
8953 );
8954 let via_into: &'static str = variant.into();
8955 assert_eq!(
8956 via_into, via_method,
8957 "Into<&'static str>::into on &RestartPolicy::{variant:?} \
8958 must byte-equal RestartPolicy::as_str on the same input — \
8959 the blanket-derived Into shape must resolve to the same \
8960 as_str dispatch as the explicit From impl"
8961 );
8962 }
8963 assert_eq!(
8964 [PERMANENT, TEMPORARY, TRANSIENT],
8965 [
8966 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
8967 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
8968 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
8969 ],
8970 "const-context RestartPolicy::as_str must resolve to the three \
8971 lifted SUPERVISOR_CHILD_RESTART_* consts — the borrowed-input \
8972 From<&RestartPolicy> for &'static str impl inherits its \
8973 `'static` lifetime promise from the same accessor the \
8974 owned-input sibling routes through"
8975 );
8976 }
8977
8978 #[test]
8979 fn restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
8980 // Cross-axis partition pin: the paired trait-idiomatic
8981 // owned-input `From<RestartPolicy> for &'static str` (9fb37d0
8982 // campaign-shape) and borrowed-input `From<&RestartPolicy> for
8983 // &'static str` (this lift) forward projections must resolve
8984 // identically on every arm, locking the two input-shape paths
8985 // together so any future detour trips at caixa-core test time.
8986 // Then a witness that a `.iter().map(Into::into)` pipe over
8987 // [`RestartPolicy::ALL`] (whose iterator yields
8988 // `&RestartPolicy`) materializes the three-arm accept-set
8989 // through the borrowed-input axis alone — the exact shape a
8990 // future wasm-operator per-child post-exit restart-decision
8991 // diagnostic line, a future substrate-wide per-arm diagnostic
8992 // column, or a
8993 // `HashMap::<&'static str, RestartPolicy>::from_iter(
8994 // RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
8995 // per-policy lookup reaches through — closing the two-way
8996 // owned/borrowed input-shape symmetry on the forward-projection
8997 // trait-idiomatic axis. Peer of the sibling
8998 // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8999 // (64aa742) /
9000 // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9001 // (5ab993a) /
9002 // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9003 // (807b0b5) /
9004 // [`restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9005 // (e941836) partition pins on the sibling closed-set typed-enum
9006 // discriminator axes — extends the borrowed-input axis
9007 // discipline onto the second-of-two M2 OTP-shape closed-set
9008 // typed enum on the caixa surface (per-child restart-decision
9009 // policy). Also closes the direct two-way `&Self → &'static
9010 // str → Self` round-trip via the paired [`TryFrom<&str>`] axis
9011 // — unlike the peer [`crate::CaixaKind`] axis pair (whose
9012 // forward `From` emits lowercase Portuguese diagnostic bytes
9013 // while the reverse `TryFrom` parses `PascalCase` wire bytes,
9014 // forcing the round-trip through an intermediate wire-vocab
9015 // hop), the [`RestartPolicy::as_str`] emit and
9016 // [`RestartPolicy::from_wire`] parse share the same
9017 // `PascalCase` vocabulary by construction, so the borrowed-
9018 // input forward axis and the reverse axis compose directly.
9019 for &variant in RestartPolicy::ALL {
9020 let owned: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
9021 let borrowed: &'static str = <&'static str as From<&RestartPolicy>>::from(&variant);
9022 assert_eq!(
9023 owned, borrowed,
9024 "From<RestartPolicy> and From<&RestartPolicy> for \
9025 &'static str must resolve identically on \
9026 RestartPolicy::{variant:?} — divergence signals the \
9027 owned-input and borrowed-input forward-projection paths \
9028 have drifted onto different emit-sets"
9029 );
9030 }
9031 let via_iter: Vec<&'static str> = RestartPolicy::ALL.iter().map(Into::into).collect();
9032 let via_method: Vec<&'static str> = RestartPolicy::ALL.iter().map(|p| p.as_str()).collect();
9033 assert_eq!(
9034 via_iter, via_method,
9035 "`.iter().map(Into::into)` over RestartPolicy::ALL must \
9036 byte-equal `.iter().map(|p| p.as_str())` on every arm — the \
9037 borrowed-input `From<&RestartPolicy> for &'static str` axis \
9038 is what makes the `.iter().map(Into::into)` shape route \
9039 through the substrate-primitive `RestartPolicy::as_str` \
9040 accessor rather than through a per-call-site `.copied()` / \
9041 dereference detour"
9042 );
9043 for variant in RestartPolicy::ALL {
9044 let emitted: &'static str = variant.into();
9045 let re_parsed: Result<RestartPolicy, ()> =
9046 <RestartPolicy as TryFrom<&str>>::try_from(emitted);
9047 assert_eq!(
9048 re_parsed,
9049 Ok(*variant),
9050 "trait-idiomatic borrowed-input forward-projection + \
9051 reverse-projection axis pair must round-trip \
9052 &RestartPolicy::{variant:?} through `.into::<&'static \
9053 str>()` (via the borrowed-input axis) and back through \
9054 `TryFrom<&str>` — a break signals the borrowed-input \
9055 forward-emit and reverse-parse axes have drifted onto \
9056 different vocabularies"
9057 );
9058 }
9059 }
9060
9061 #[test]
9062 fn restart_policy_from_into_owned_string_routes_through_as_str_accessor() {
9063 // Fail-before-pass-after byte-parity pin on the newly lifted
9064 // `impl From<RestartPolicy> for String` — asserts the
9065 // owned-`String`-returning standard-library trait impl and the
9066 // substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
9067 // accessor resolve to the same three-arm emit-set across every
9068 // arm the exhaustive [`RestartPolicy::ALL`] slice enumerates.
9069 // Rust's standard library does not carry a blanket
9070 // `impl<T: AsRef<str>> From<T> for String` (nor an
9071 // `impl<T: fmt::Display> From<T> for String`), so the
9072 // owned-`String` forward-projection axis is a distinct
9073 // trait-idiomatic surface that a `let key: String =
9074 // policy.into();`-shaped call site reaches through this impl
9075 // and no other — the paired sibling `From<RestartPolicy> for
9076 // &'static str` impl forces every owned-`String` call site
9077 // through an explicit `.to_owned()` / `String::from`
9078 // restatement. Peer of the first-mover
9079 // [`restart_strategy_from_into_owned_string_routes_through_as_str_accessor`]
9080 // (7baa18a) — extends the trait-idiomatic owned-`String`
9081 // forward-projection axis onto the second-of-two M2 OTP-shape
9082 // closed-set typed enums on the caixa surface (per-child
9083 // restart-decision-policy sibling on the same M2 `:supervisor`
9084 // slot).
9085 for &variant in RestartPolicy::ALL {
9086 let via_trait: String = <String as From<RestartPolicy>>::from(variant);
9087 let via_method: &'static str = variant.as_str();
9088 assert_eq!(
9089 via_trait.as_str(),
9090 via_method,
9091 "From<RestartPolicy> for String impl must round-trip \
9092 RestartPolicy::{variant:?} to the same lifted \
9093 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
9094 returns — divergence signals a silent detour off the \
9095 substrate-primitive accessor"
9096 );
9097 let via_into: String = variant.into();
9098 assert_eq!(
9099 via_into.as_str(),
9100 via_method,
9101 "Into<String>::into on RestartPolicy::{variant:?} must \
9102 byte-equal RestartPolicy::as_str on the same input — the \
9103 blanket-derived Into shape must resolve to the same as_str \
9104 dispatch as the explicit From impl"
9105 );
9106 }
9107 }
9108
9109 #[test]
9110 fn restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm() {
9111 // Cross-axis partition pin: the paired trait-idiomatic
9112 // owned-`String` `From<RestartPolicy> for String` (this lift)
9113 // and owned-`&'static str` `From<RestartPolicy> for &'static
9114 // str` (9fb37d0) forward projections must resolve identically
9115 // on every arm, locking the two return-type-shape paths
9116 // together so any future detour trips at caixa-core test time.
9117 // Also byte-parity witness against the sibling
9118 // [`ToString::to_string`] surface routed through
9119 // [`std::fmt::Display`] — the three owned-heap-string paths
9120 // (`.into::<String>()`, `String::from`, `.to_string()`) must
9121 // resolve identically on every arm so a future consumer that
9122 // picks any of the three lands on the same lifted
9123 // SUPERVISOR_CHILD_RESTART_* const. Then a `.iter().copied()
9124 // .map(String::from)` pipe witness over [`RestartPolicy::ALL`]
9125 // that materializes the three-arm accept-set through the
9126 // owned-`String` axis alone — the exact shape a future
9127 // wasm-operator per-child post-exit restart-decision
9128 // diagnostic line composer or a
9129 // `HashMap::<String, RestartPolicy>::from_iter(
9130 // RestartPolicy::ALL.iter().copied().map(|p| (p.into(), p)))`-style
9131 // owned-key per-policy lookup reaches through — closing the
9132 // owned-`String` forward-projection axis's iterator-pipe
9133 // shape. Then a direct round-trip witness through the paired
9134 // trait-idiomatic reverse [`TryFrom<&str>`] axis on the
9135 // owned-`String`'s [`String::as_str`] borrow that closes the
9136 // two-way `Self → String → Self` round-trip on the trait-
9137 // idiomatic owned-`String` forward + reverse axis pair —
9138 // unlike the peer [`crate::CaixaKind`] axis pair (whose
9139 // forward `From` emits lowercase Portuguese diagnostic bytes
9140 // while the reverse `TryFrom` parses `PascalCase` wire bytes,
9141 // forcing the round-trip through an intermediate wire-vocab
9142 // hop), the [`RestartPolicy::as_str`] emit and
9143 // [`RestartPolicy::from_wire`] parse share the same
9144 // `PascalCase` vocabulary by construction, so the owned-
9145 // `String` forward axis and the reverse axis compose directly.
9146 for &variant in RestartPolicy::ALL {
9147 let owned_string: String = <String as From<RestartPolicy>>::from(variant);
9148 let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
9149 assert_eq!(
9150 owned_string.as_str(),
9151 owned_static,
9152 "From<RestartPolicy> for String and From<RestartPolicy> \
9153 for &'static str must resolve identically on \
9154 RestartPolicy::{variant:?} — divergence signals the \
9155 owned-`String` and owned-`&'static str` forward-projection \
9156 return-type-shape paths have drifted onto different \
9157 emit-sets"
9158 );
9159 let via_to_string: String = variant.to_string();
9160 assert_eq!(
9161 owned_string, via_to_string,
9162 "From<RestartPolicy> for String must byte-equal \
9163 RestartPolicy::to_string on RestartPolicy::{variant:?} — \
9164 divergence signals the trait-idiomatic owned-`String` \
9165 forward-projection axis and the ToString-through-Display \
9166 axis have drifted onto different emit-sets"
9167 );
9168 }
9169 let via_iter: Vec<String> = RestartPolicy::ALL
9170 .iter()
9171 .copied()
9172 .map(String::from)
9173 .collect();
9174 let via_method: Vec<String> = RestartPolicy::ALL
9175 .iter()
9176 .map(|p| p.as_str().to_owned())
9177 .collect();
9178 assert_eq!(
9179 via_iter, via_method,
9180 "`.iter().copied().map(String::from)` over RestartPolicy::ALL \
9181 must byte-equal `.iter().map(|p| p.as_str().to_owned())` on \
9182 every arm — the owned-`String` `From<RestartPolicy> for \
9183 String` axis is what makes the `String::from` composition \
9184 route through the substrate-primitive `RestartPolicy::as_str` \
9185 accessor rather than through a per-call-site `.to_owned()` / \
9186 `String::from(policy.as_str())` detour"
9187 );
9188 for &variant in RestartPolicy::ALL {
9189 let emitted: String = variant.into();
9190 let re_parsed: Result<RestartPolicy, ()> =
9191 <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
9192 assert_eq!(
9193 re_parsed,
9194 Ok(variant),
9195 "trait-idiomatic owned-`String` forward-projection + \
9196 reverse-projection axis pair must round-trip \
9197 RestartPolicy::{variant:?} through `.into::<String>()` \
9198 and back through `TryFrom<&str>` on the owned-`String`'s \
9199 String::as_str borrow — a break signals the owned-`String` \
9200 forward-emit and reverse-parse axes have drifted onto \
9201 different vocabularies"
9202 );
9203 }
9204 }
9205
9206 #[test]
9207 fn restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
9208 // Fail-before-pass-after byte-parity pin on the newly lifted
9209 // `impl From<&RestartPolicy> for String` — asserts the
9210 // borrowed-input owned-`String`-returning standard-library
9211 // trait impl and the substrate-primitive
9212 // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
9213 // the same three-arm emit-set across every arm the exhaustive
9214 // [`RestartPolicy::ALL`] slice enumerates. Rust's standard
9215 // library does not carry a blanket `impl<T: AsRef<str>>
9216 // From<&T> for String` (nor an `impl<T: fmt::Display> From<&T>
9217 // for String`), so the borrowed-input owned-`String` forward-
9218 // projection axis is a distinct trait-idiomatic surface that a
9219 // `let key: String = (&policy).into();`-shaped call site
9220 // reaches through this impl and no other — the paired sibling
9221 // `From<RestartPolicy> for String` impl forces every borrowed-
9222 // input call site through an explicit `Copy` deref
9223 // (`String::from(*policy)`) or an `.as_str().to_owned()` /
9224 // `.to_string()` detour. Peer of the first-mover
9225 // [`restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
9226 // (579385f) — extends the trait-idiomatic borrowed-input
9227 // owned-`String` forward-projection axis onto the second-of-
9228 // two M2 OTP-shape closed-set typed enums on the caixa surface
9229 // (per-child restart-decision-policy sibling on the same M2
9230 // `:supervisor` slot).
9231 for &variant in RestartPolicy::ALL {
9232 let via_trait: String = <String as From<&RestartPolicy>>::from(&variant);
9233 let via_method: &'static str = variant.as_str();
9234 assert_eq!(
9235 via_trait.as_str(),
9236 via_method,
9237 "From<&RestartPolicy> for String impl must round-trip \
9238 &RestartPolicy::{variant:?} to the same lifted \
9239 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
9240 returns — divergence signals a silent detour off the \
9241 substrate-primitive accessor"
9242 );
9243 let via_into: String = (&variant).into();
9244 assert_eq!(
9245 via_into.as_str(),
9246 via_method,
9247 "Into<String>::into on &RestartPolicy::{variant:?} must \
9248 byte-equal RestartPolicy::as_str on the same input — \
9249 the blanket-derived Into shape must resolve to the \
9250 same as_str dispatch as the explicit From impl"
9251 );
9252 }
9253 }
9254
9255 #[test]
9256 fn restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
9257 // Cross-axis partition pin: the newly lifted trait-idiomatic
9258 // borrowed-input owned-`String` `From<&RestartPolicy> for
9259 // String` (this lift), the paired owned-input owned-`String`
9260 // `From<RestartPolicy> for String` (7851725), the paired
9261 // borrowed-input owned-`&'static str` `From<&RestartPolicy>
9262 // for &'static str` (842c7f3), and the paired owned-input
9263 // owned-`&'static str` `From<RestartPolicy> for &'static str`
9264 // (9fb37d0) — every corner of the `{Self, &Self} × {&'static
9265 // str, String}` 2×2 trait-idiomatic projection family — must
9266 // resolve identically on every arm, locking the four
9267 // return-shape × input-shape paths together so any future
9268 // detour trips at caixa-core test time. Also byte-parity
9269 // witness against the sibling [`ToString::to_string`] surface
9270 // routed through [`std::fmt::Display`] and a direct round-trip
9271 // witness through the paired trait-idiomatic reverse
9272 // [`TryFrom<&str>`] axis on the owned-`String`'s
9273 // [`String::as_str`] borrow that closes the two-way
9274 // `&Self → String → Self` round-trip on the trait-idiomatic
9275 // borrowed-input owned-`String` forward + reverse axis pair.
9276 // Peer of the first-mover
9277 // [`restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
9278 // (579385f) — closes the whole `{Self, &Self} × {&'static str,
9279 // String}` 2×2 projection corner on both M2 OTP-shape sibling
9280 // peers.
9281 for &variant in RestartPolicy::ALL {
9282 let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
9283 let owned_string: String = <String as From<RestartPolicy>>::from(variant);
9284 let borrowed_static: &'static str =
9285 <&'static str as From<&RestartPolicy>>::from(&variant);
9286 let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
9287 assert_eq!(
9288 borrowed_string, owned_string,
9289 "From<&RestartPolicy> for String and From<RestartPolicy> \
9290 for String must resolve identically on \
9291 RestartPolicy::{variant:?} — divergence signals the \
9292 borrowed-input and owned-input owned-`String` \
9293 forward-projection input-shape paths have drifted onto \
9294 different emit-sets"
9295 );
9296 assert_eq!(
9297 borrowed_string.as_str(),
9298 borrowed_static,
9299 "From<&RestartPolicy> for String and From<&RestartPolicy> \
9300 for &'static str must resolve identically on \
9301 RestartPolicy::{variant:?} — divergence signals the \
9302 borrowed-input `&'static str` and owned-`String` \
9303 return-shape paths have drifted onto different \
9304 emit-sets"
9305 );
9306 assert_eq!(
9307 borrowed_string.as_str(),
9308 owned_static,
9309 "From<&RestartPolicy> for String and From<RestartPolicy> \
9310 for &'static str must resolve identically on \
9311 RestartPolicy::{variant:?} — divergence signals a \
9312 break in the diagonal corner of the {{Self, &Self}} × \
9313 {{&'static str, String}} 2×2 trait-idiomatic \
9314 projection family"
9315 );
9316 let via_to_string: String = variant.to_string();
9317 assert_eq!(
9318 borrowed_string, via_to_string,
9319 "From<&RestartPolicy> for String must byte-equal \
9320 RestartPolicy::to_string on RestartPolicy::{variant:?} \
9321 — divergence signals the trait-idiomatic borrowed-input \
9322 owned-`String` forward-projection axis and the \
9323 ToString-through-Display axis have drifted onto \
9324 different emit-sets"
9325 );
9326 }
9327 let via_iter: Vec<String> = RestartPolicy::ALL.iter().map(String::from).collect();
9328 let via_method: Vec<String> = RestartPolicy::ALL
9329 .iter()
9330 .map(|p| p.as_str().to_owned())
9331 .collect();
9332 assert_eq!(
9333 via_iter, via_method,
9334 "`.iter().map(String::from)` over RestartPolicy::ALL — a \
9335 call site whose iteration axis holds `&RestartPolicy` by \
9336 construction — must byte-equal `.iter().map(|p| \
9337 p.as_str().to_owned())` on every arm — the borrowed-input \
9338 owned-`String` `From<&RestartPolicy> for String` axis is \
9339 what makes the `String::from` composition route through \
9340 the substrate-primitive `RestartPolicy::as_str` accessor \
9341 without a spurious `Copy` deref (which would only be \
9342 reachable through the owned-input `From<RestartPolicy> \
9343 for String` axis by first calling `.copied()` on the \
9344 iterator)"
9345 );
9346 for &variant in RestartPolicy::ALL {
9347 let emitted: String = (&variant).into();
9348 let re_parsed: Result<RestartPolicy, ()> =
9349 <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
9350 assert_eq!(
9351 re_parsed,
9352 Ok(variant),
9353 "trait-idiomatic borrowed-input owned-`String` \
9354 forward-projection + reverse-projection axis pair must \
9355 round-trip &RestartPolicy::{variant:?} through \
9356 `.into::<String>()` on the borrowed-input surface and \
9357 back through `TryFrom<&str>` on the owned-`String`'s \
9358 String::as_str borrow — a break signals the \
9359 borrowed-input owned-`String` forward-emit and \
9360 reverse-parse axes have drifted onto different \
9361 vocabularies"
9362 );
9363 }
9364 }
9365
9366 // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_RESTART_* identity ─
9367
9368 #[test]
9369 fn restart_policy_variants_serialize_to_lifted_scalar_values() {
9370 // The fail-before-pass-after pin: pre-lift there was no
9371 // single-source binding between the [`RestartPolicy`] variant
9372 // name the un-`rename`d `Serialize` derive emits under
9373 // [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
9374 // byte-string every downstream cluster-side dispatcher (the
9375 // future wasm-operator's per-child post-exit restart-decision
9376 // branch, the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
9377 // materializer's admission-time enum-arm bind, the
9378 // `caixa-operator`'s hierarchical reconciliation scheduler's
9379 // per-child-policy fan-out) probes verbatim. A future
9380 // `#[serde(rename_all = "kebab-case")]` attribute on the enum —
9381 // or a per-variant `#[serde(rename = "…")]` override, or a
9382 // variant rename in the source — would silently rebrand the
9383 // emitted scalar under one spelling while every downstream
9384 // dispatcher still probed the other, with the failure surfacing
9385 // at the operator's reconcile posture (children coming up under
9386 // the `default()` `Permanent` arm rather than the typed slot's
9387 // declared policy — a `:temporary` `oneShot` child would be
9388 // restarted on clean exit, treating the successful-completion
9389 // signal as failure and re-running the completion-terminal
9390 // one-shot indefinitely; a `:transient` child that clean-exited
9391 // would be restarted, masking the clean-completion contract)
9392 // far from the source rebrand commit and with no field naming
9393 // the drift. Pinning the two paths (the `Serialize` derive's
9394 // serialized string AND the [`RestartPolicy::as_str`] helper)
9395 // to the same three lifted
9396 // [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
9397 // [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
9398 // [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
9399 // byte-strings makes any future drift on either endpoint fail
9400 // here at caixa-core build time. Peer of the sibling
9401 // [`restart_strategy_variants_serialize_to_lifted_scalar_values`]
9402 // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
9403 // and the M3
9404 // `placement_strategy_variants_serialize_to_lifted_scalar_values`
9405 // (3f0e21c) on the per-Aplicacao distribution-strategy axis —
9406 // same three-path-convergence discipline, extended to close the
9407 // third OTP-shaped closed-enum discriminator axis on the caixa
9408 // typed surface (per-child restart-decision policy).
9409 for (variant, expected) in [
9410 (
9411 RestartPolicy::Permanent,
9412 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
9413 ),
9414 (
9415 RestartPolicy::Temporary,
9416 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
9417 ),
9418 (
9419 RestartPolicy::Transient,
9420 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
9421 ),
9422 ] {
9423 let json = serde_json::to_string(&variant).unwrap();
9424 assert_eq!(
9425 json,
9426 format!("\"{expected}\""),
9427 "RestartPolicy::{variant:?} must serialize to {expected:?}"
9428 );
9429 assert_eq!(
9430 variant.as_str(),
9431 expected,
9432 "RestartPolicy::{variant:?}.as_str() must return the lifted \
9433 SUPERVISOR_CHILD_RESTART_* constant"
9434 );
9435 }
9436 }
9437
9438 #[test]
9439 fn supervisor_child_restart_consts_are_pairwise_distinct() {
9440 // Cross-arm drift-detection pin: a future collapse of two
9441 // canonical variant byte-strings onto the same value (e.g. an
9442 // accidental copy-paste flip of `SUPERVISOR_CHILD_RESTART_TRANSIENT`
9443 // to also read `"Permanent"`) would silently reroute every
9444 // downstream operator's per-child-policy dispatch onto the
9445 // sibling arm's reconcile branch and pass every propagation-probe
9446 // test that expected only the stale arm's value — a `:transient`
9447 // child would come up under the `:permanent` restart-decision
9448 // posture on every subsequent clean exit, so a completion-terminal
9449 // child would be restarted indefinitely against its declared
9450 // policy. Peer of the sibling
9451 // [`supervisor_estrategia_consts_are_pairwise_distinct`]
9452 // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
9453 // and the four-way distinct pin
9454 // `supervisor_key_consts_are_pairwise_distinct` (40cc4e5) on the
9455 // top-level `SUPERVISOR_KEY_*` axis.
9456 let all = [
9457 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
9458 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
9459 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
9460 ];
9461 for (i, a) in all.iter().enumerate() {
9462 for (j, b) in all.iter().enumerate() {
9463 if i != j {
9464 assert_ne!(
9465 a, b,
9466 "SUPERVISOR_CHILD_RESTART_* consts must be pairwise distinct \
9467 — got duplicate {a:?} at indices {i} and {j}",
9468 );
9469 }
9470 }
9471 }
9472 }
9473
9474 #[test]
9475 fn restart_policy_display_routes_through_as_str_helper() {
9476 // The fail-before-pass-after pin on the first half of the
9477 // three-path convergence: pre-convergence [`RestartPolicy`]
9478 // carried a [`std::fmt::Display`] surface via its
9479 // `#[discriminant(also_display)]` gen-platform derive route,
9480 // which arrived kebab-case as `"permanent"` / `"temporary"`
9481 // / `"transient"` on this three-arm enum (whose variant
9482 // names each collapse to their own lowercase form under the
9483 // kebab-case transform) while the wire format ran as
9484 // PascalCase `"Permanent"` / `"Temporary"` / `"Transient"`
9485 // through the un-`rename`d serde derive. Every consumer
9486 // reaching for a policy byte-string past the wire format had
9487 // to pick between three paths ([`RestartPolicy::as_str`],
9488 // the `Serialize` derive's serialized string, or
9489 // `format!("{v}")` on the discriminant-Display route), any
9490 // two of which a future variant rename or
9491 // `#[serde(rename_all = "kebab-case")]` attribute would
9492 // silently desynchronize. Wiring [`std::fmt::Display`]
9493 // through [`RestartPolicy::as_str`] closes the third path:
9494 // every `format!("{v}")` call reaches the same lifted
9495 // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the
9496 // wire format and the [`RestartPolicy::as_str`] helper
9497 // already route through, so a future variant rename lands at
9498 // exactly one place. Pin the routing here so a future
9499 // `impl std::fmt::Display for RestartPolicy`
9500 // reimplementation that hand-rolls the arms instead of
9501 // delegating to [`RestartPolicy::as_str`] fails at
9502 // caixa-core build time. Peer of the sibling
9503 // [`restart_strategy_display_routes_through_as_str_helper`]
9504 // on the per-supervisor sibling-restart-strategy axis and
9505 // the M3
9506 // `placement_strategy_display_routes_through_as_str_helper`
9507 // (cc8f749) — the third of three OTP-shape closed-enum
9508 // discriminator axes on the caixa typed surface now
9509 // converged onto the same three-path
9510 // (Display → as_str → lifted const) discipline.
9511 for variant in [
9512 RestartPolicy::Permanent,
9513 RestartPolicy::Temporary,
9514 RestartPolicy::Transient,
9515 ] {
9516 assert_eq!(
9517 variant.to_string(),
9518 variant.as_str(),
9519 "RestartPolicy::{variant:?} Display must route through \
9520 RestartPolicy::as_str (single source of truth: the lifted \
9521 SUPERVISOR_CHILD_RESTART_* const the wire format also emits)"
9522 );
9523 }
9524 }
9525
9526 #[test]
9527 fn restart_policy_display_matches_serialized_wire_byte_string() {
9528 // The fail-before-pass-after pin on the second half of the
9529 // three-path convergence: `Display` (user-facing text) agrees
9530 // byte-for-byte with the `Serialize` derive's wire format
9531 // (canonical camelCase-schema `SUPERVISOR_CHILD_KEY_RESTART`
9532 // scalar) on every variant. Pre-convergence the two paths
9533 // were structurally independent — a future
9534 // `#[serde(rename_all = "kebab-case")]` attribute on the
9535 // enum would silently rebrand the emitted wire scalar
9536 // (`permanent`, `temporary`, `transient`) while every
9537 // consumer that pretty-prints the policy (the future
9538 // wasm-operator's per-child post-exit restart-decision
9539 // diagnostic line, the future `feira app graph` per-child
9540 // restart column, the future M4
9541 // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
9542 // per-child admission-webhook rejection body) would still
9543 // emit the PascalCase form the `as_str` / `Display` route
9544 // returns, with the mismatch surfacing at consumer parse
9545 // time / operator dispatch time far from the source rebrand
9546 // commit. Pin the two paths byte-for-byte here so any future
9547 // serde-attribute or variant-rename drift is a
9548 // caixa-core-build-time test failure at this call, not a
9549 // silent per-consumer dispatch miss. Peer of the sibling
9550 // [`restart_strategy_display_matches_serialized_wire_byte_string`]
9551 // on the per-supervisor sibling-restart-strategy axis and
9552 // the M3
9553 // `placement_strategy_display_matches_serialized_wire_byte_string`
9554 // (cc8f749).
9555 for variant in [
9556 RestartPolicy::Permanent,
9557 RestartPolicy::Temporary,
9558 RestartPolicy::Transient,
9559 ] {
9560 let wire = serde_json::to_string(&variant).unwrap();
9561 let unquoted = wire
9562 .strip_prefix('"')
9563 .and_then(|s| s.strip_suffix('"'))
9564 .expect("serialized RestartPolicy is a JSON string");
9565 assert_eq!(
9566 variant.to_string(),
9567 unquoted,
9568 "RestartPolicy::{variant:?} Display byte-string must match the \
9569 Serialize derive's wire byte-string (three-path convergence: \
9570 Display + as_str + Serialize all resolve to the same \
9571 SUPERVISOR_CHILD_RESTART_* const)"
9572 );
9573 }
9574 }
9575
9576 #[test]
9577 fn restart_policy_as_ref_str_routes_through_as_str_accessor() {
9578 // Fail-before-pass-after byte-parity pin on the lifted
9579 // `impl AsRef<str> for RestartPolicy` — asserts the
9580 // standard-library trait impl and the substrate-primitive
9581 // [`RestartPolicy::as_str`] `pub const fn` accessor resolve
9582 // to the same `&str` per instance across the three-arm
9583 // closed set, so any future silent detour that routes the
9584 // impl through a divergent projection (a per-arm inline
9585 // `match self { RestartPolicy::Permanent => "Permanent", … }`
9586 // re-inlining that opens a compile-time link to the un-lifted
9587 // arm-literal, a swap onto the kebab-case
9588 // [`gen_platform::Discriminant`] catalog identity that would
9589 // collide the wire axis with the dispatcher-catalog axis) trips
9590 // at caixa-core test time under `PartialEq` rather than at a
9591 // downstream `impl AsRef<str>`-bound consumer's silent split.
9592 // Sweeps every one of the three arms
9593 // [`RestartPolicy::ALL`] carries so no arm's projection is
9594 // covered only by the sibling wire-format `Serialize` derive
9595 // path. Peer of the sibling
9596 // [`restart_strategy_as_ref_str_routes_through_as_str_accessor`]
9597 // (63eb1a4) on the paired per-supervisor sibling-restart-
9598 // strategy axis and the [`crate::CaixaVersion`]
9599 // `AsRef<str>`-byte-parity pin (16d5c7e) on the paired
9600 // top-level `:versao` typed newtype — the three pins together
9601 // cover the substrate primitive's `AsRef<str>` projection axis
9602 // on the paired newtype + M2 closed-set-typed-enum surface.
9603 for &variant in RestartPolicy::ALL {
9604 assert_eq!(
9605 <RestartPolicy as AsRef<str>>::as_ref(&variant),
9606 variant.as_str(),
9607 "AsRef<str> impl on RestartPolicy::{variant:?} must \
9608 byte-equal RestartPolicy::as_str on the same instance \
9609 — divergence signals a silent detour off the substrate-\
9610 primitive accessor"
9611 );
9612 }
9613 }
9614
9615 #[test]
9616 fn restart_policy_as_ref_str_routes_through_display_via_shared_accessor() {
9617 // Fail-before-pass-after byte-parity pin on the three-path
9618 // convergence discipline the M2 per-child-restart-policy
9619 // primitive now carries on the `&str`-projection axis:
9620 // `<RestartPolicy as AsRef<str>>::as_ref(&v)` (the newly
9621 // lifted impl), `format!("{v}")` (the pre-existing
9622 // [`fmt::Display`] impl), and `v.as_str()` (the substrate-
9623 // primitive `pub const fn` accessor both trait impls delegate
9624 // through) must resolve to the same byte-string on every
9625 // instance across the three-arm closed set. Refuses any future
9626 // divergence between the two trait impls (a stray
9627 // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
9628 // rather than delegating through the shared accessor; a
9629 // hypothetical `AsRef<str>` rewrite that inlines a per-arm
9630 // literal cascade) that would silently split the two
9631 // projection paths of the same closed-set typed enum. Mirrors
9632 // the sibling three-path-convergence discipline the peer
9633 // [`RestartStrategy`] typed enum carries on its
9634 // `AsRef<str>` / `Display` / `as_str` triple
9635 // (supervisor.rs pin
9636 // `restart_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
9637 // 63eb1a4) and the [`crate::CaixaVersion`] typed newtype
9638 // carries on the same triple (version.rs pin
9639 // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
9640 // 16d5c7e).
9641 for &variant in RestartPolicy::ALL {
9642 let via_as_ref: &str = <RestartPolicy as AsRef<str>>::as_ref(&variant);
9643 let via_display: String = format!("{variant}");
9644 let via_accessor: &str = variant.as_str();
9645 assert_eq!(via_as_ref, via_accessor);
9646 assert_eq!(via_display, via_accessor);
9647 assert_eq!(via_as_ref, via_display.as_str());
9648 }
9649 }
9650
9651 #[test]
9652 fn restart_policy_all_enumerates_every_variant_exactly_once() {
9653 // Fail-before-pass-after pin on the [`RestartPolicy::ALL`]
9654 // exhaustive-iteration surface: every variant appears exactly
9655 // once, and the slice length matches the arm count of the
9656 // closed set. Every consumer that walks the accepted-policy
9657 // set (a future `feira supervisor --restart …` CLI-side
9658 // arg-parse's "did you mean" hint, a future M4 admission-
9659 // webhook's per-child rejection body naming the accepted-
9660 // `:restart` list, the [`RestartPolicy::from_wire`] reverse-
9661 // projection consumers that iterate the accept-set for
9662 // diagnostic rendering) reads through this slice, so a future
9663 // arm addition that grows the enum but forgets to grow
9664 // [`Self::ALL`] silently truncates every downstream consumer's
9665 // accept-set at the same pre-addition boundary — this pin
9666 // fails at caixa-core build time on the pairwise-distinct +
9667 // arm-count invariants.
9668 //
9669 // Peer of the sibling [`RestartStrategy::ALL`] (4eec29c) /
9670 // [`crate::CaixaKind::ALL`] (6b1f4fb) /
9671 // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
9672 // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
9673 // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
9674 // pins on the peer closed-set typed-enum axes.
9675 let all: &[RestartPolicy] = RestartPolicy::ALL;
9676 assert_eq!(
9677 all.len(),
9678 3,
9679 "RestartPolicy::ALL must enumerate every variant of the \
9680 three-arm closed set (Permanent, Temporary, Transient); \
9681 got {all:?}"
9682 );
9683 for (i, a) in all.iter().enumerate() {
9684 for (j, b) in all.iter().enumerate() {
9685 if i != j {
9686 assert_ne!(
9687 a, b,
9688 "RestartPolicy::ALL must carry every variant exactly \
9689 once — got duplicate {a:?} at indices {i} and {j}"
9690 );
9691 }
9692 }
9693 }
9694 for variant in [
9695 RestartPolicy::Permanent,
9696 RestartPolicy::Temporary,
9697 RestartPolicy::Transient,
9698 ] {
9699 assert!(
9700 all.contains(&variant),
9701 "RestartPolicy::ALL must contain {variant:?} — a future arm \
9702 addition that grows the enum but forgets to grow the ALL slice \
9703 silently truncates every downstream consumer's accept-set at \
9704 the pre-addition boundary"
9705 );
9706 }
9707 }
9708
9709 #[test]
9710 fn restart_policy_from_wire_accepts_every_lifted_constant() {
9711 // Fail-before-pass-after pin on the forward accept-set of the
9712 // [`RestartPolicy::from_wire`] reverse projection: every
9713 // canonical [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
9714 // constant the [`RestartPolicy::as_str`] emitter walks parses
9715 // back to its paired variant. Any future arm addition that
9716 // grows the emitter's `as_str` match but forgets to grow the
9717 // parser's `from_wire` match silently splits the two halves of
9718 // the round-trip — the wire byte-string one non-serde consumer
9719 // parses from the one the emitter wrote — with the failure
9720 // surfacing at the operator's reconcile posture (a `:temporary`
9721 // `oneShot` child restarted on clean exit, a `:transient` child
9722 // restarted after clean completion) far from the rebrand
9723 // commit. Pinning the three-arm accept-set here catches the
9724 // drift at caixa-core build time.
9725 //
9726 // Peer of the sibling [`RestartStrategy::from_wire`] (4eec29c)
9727 // + [`crate::CaixaKind::from_wire`] (2aa6d23)
9728 // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
9729 // accept-set pins on the peer closed-set typed-enum `str → Self`
9730 // axes.
9731 for (wire, expected) in [
9732 (
9733 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
9734 RestartPolicy::Permanent,
9735 ),
9736 (
9737 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
9738 RestartPolicy::Temporary,
9739 ),
9740 (
9741 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
9742 RestartPolicy::Transient,
9743 ),
9744 ] {
9745 let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
9746 panic!(
9747 "RestartPolicy::from_wire({wire:?}) must accept every \
9748 SUPERVISOR_CHILD_RESTART_* constant — got None for the \
9749 lifted canonical byte-string that RestartPolicy::{expected:?} \
9750 serializes as under SUPERVISOR_CHILD_KEY_RESTART"
9751 )
9752 });
9753 assert_eq!(
9754 parsed, expected,
9755 "RestartPolicy::from_wire({wire:?}) must return \
9756 RestartPolicy::{expected:?}; got RestartPolicy::{parsed:?}"
9757 );
9758 }
9759 }
9760
9761 #[test]
9762 fn restart_policy_from_wire_round_trips_through_as_str() {
9763 // Fail-before-pass-after pin on the closed round-trip between
9764 // the forward [`RestartPolicy::as_str`] emitter and the
9765 // reverse [`RestartPolicy::from_wire`] parser: for every
9766 // variant in [`RestartPolicy::ALL`], parsing the emitter's
9767 // output must return exactly the same variant. Any per-arm
9768 // divergence — a future arm added to `as_str` but not
9769 // `from_wire`, an accidental copy-paste flip in one but not
9770 // the other — silently splits the emit and parse halves and
9771 // the failure surfaces at consumer parse time far from the
9772 // drift site. The `ALL`-iterating shape means a future arm
9773 // addition picks up the coverage by construction.
9774 //
9775 // Peer of the sibling
9776 // [`restart_strategy_from_wire_round_trips_through_as_str`]
9777 // (4eec29c) round-trip pin on
9778 // [`RestartStrategy::from_wire`] and the M3
9779 // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
9780 // (18c7342) round-trip pin on
9781 // [`crate::aplicacao::PlacementStrategy::from_wire`].
9782 for &variant in RestartPolicy::ALL {
9783 let wire = variant.as_str();
9784 let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
9785 panic!(
9786 "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
9787 must be Some({variant:?}) — the two halves of the round-trip \
9788 dispatch on the same lifted SUPERVISOR_CHILD_RESTART_* consts; \
9789 got None on wire byte-string {wire:?}"
9790 )
9791 });
9792 assert_eq!(
9793 parsed, variant,
9794 "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
9795 must round-trip to the same variant; got {parsed:?}"
9796 );
9797 }
9798 }
9799
9800 #[test]
9801 fn restart_policy_from_wire_rejects_unknown_byte_strings() {
9802 // Fail-before-pass-after pin on the closed-set refusal
9803 // discipline of [`RestartPolicy::from_wire`]: every
9804 // byte-string outside the three-arm accept-set returns `None`
9805 // rather than silently collapsing onto the [`Default`]
9806 // (`Permanent`) arm or an arbitrary neighbor. The refusal set
9807 // exercised here sweeps the load-bearing drift shapes: the
9808 // empty string (a stripped serde-attribute drift), all-
9809 // whitespace strings (the canonical text-editor accidental
9810 // padding shape), the kebab-case dispatcher-catalog identities
9811 // (`"permanent"` / `"temporary"` / `"transient"` — the
9812 // [`gen_platform::FromStrKind`]-derived [`std::str::FromStr`]
9813 // accept-set, which parses the *other* axis of this enum's
9814 // two-axis split and must not leak into the `from_wire`
9815 // PascalCase-wire accept-set — a lowercase leak here would
9816 // silently accept the operator's kebab-case
9817 // dispatcher-catalog probe under the wire-axis parser and mis-
9818 // route a `:permanent` intent), the padded canonical scalar
9819 // (`" Permanent "`), the trailing-newline shapes
9820 // (`"Permanent\n"`), the uppercase-single-word forms
9821 // (`"PERMANENT"`), and neighboring-but-unknown arms
9822 // (`"Restart"` — the canonical typo direction toward the
9823 // sibling [`RestartStrategy`] enum's own wire-arm namespace).
9824 //
9825 // Peer of the sibling
9826 // [`restart_strategy_from_wire_rejects_unknown_byte_strings`]
9827 // (4eec29c) +
9828 // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
9829 // (2aa6d23) +
9830 // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
9831 // (18c7342) refusal pins on the peer closed-set typed-enum
9832 // axes.
9833 for bad in [
9834 "",
9835 " ",
9836 "\n",
9837 "\t",
9838 "permanent",
9839 "temporary",
9840 "transient",
9841 "PERMANENT",
9842 "TEMPORARY",
9843 "TRANSIENT",
9844 "Permanents",
9845 "Permanent ",
9846 " Permanent",
9847 " Transient ",
9848 "Permanent\n",
9849 "perma",
9850 "Trans",
9851 "OneForOne",
9852 "Restart",
9853 "?",
9854 ] {
9855 assert!(
9856 RestartPolicy::from_wire(bad).is_none(),
9857 "RestartPolicy::from_wire({bad:?}) must return None — the \
9858 parser's accept-set is exactly the three RestartPolicy::as_str \
9859 outputs (Permanent, Temporary, Transient), and this \
9860 byte-string is outside that closed set"
9861 );
9862 }
9863 }
9864
9865 #[test]
9866 fn restart_policy_from_wire_matches_serialize_derive_wire_byte_string() {
9867 // Fail-before-pass-after pin on the fourth path of the four-path
9868 // convergence: `from_wire` (the reverse projection) inverts the
9869 // `Serialize` derive's wire byte-string on every variant.
9870 // Together with the pre-existing three-path convergence
9871 // (`Display` + `as_str` + `Serialize` all resolve to the same
9872 // lifted [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const,
9873 // pinned by
9874 // [`restart_policy_display_matches_serialized_wire_byte_string`])
9875 // this closes the round-trip: the wire byte-string the
9876 // `Serialize` derive emits parses back to the same variant
9877 // through `from_wire`, so any future serde-attribute or variant-
9878 // rename drift on the emit half now surfaces as a matched drift
9879 // on the parse half at caixa-core build time — the two halves
9880 // migrate as a unit through the lifted consts on any future
9881 // rename, and the round-trip cannot silently split.
9882 //
9883 // Peer of the sibling
9884 // [`restart_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
9885 // (4eec29c) wire-format pin on
9886 // [`RestartStrategy::from_wire`] and the M3
9887 // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
9888 // (18c7342) wire-format pin on
9889 // [`crate::aplicacao::PlacementStrategy::from_wire`].
9890 for &variant in RestartPolicy::ALL {
9891 let wire = serde_json::to_string(&variant).unwrap();
9892 let unquoted = wire
9893 .strip_prefix('"')
9894 .and_then(|s| s.strip_suffix('"'))
9895 .expect("serialized RestartPolicy is a JSON string");
9896 let parsed = RestartPolicy::from_wire(unquoted).unwrap_or_else(|| {
9897 panic!(
9898 "RestartPolicy::from_wire({unquoted:?}) must accept the \
9899 Serialize derive's wire byte-string for \
9900 RestartPolicy::{variant:?} — the four-path convergence \
9901 (Display + as_str + Serialize + from_wire) resolves through \
9902 the same lifted SUPERVISOR_CHILD_RESTART_* const; got None"
9903 )
9904 });
9905 assert_eq!(
9906 parsed, variant,
9907 "RestartPolicy::from_wire of the Serialize derive's wire \
9908 byte-string for RestartPolicy::{variant:?} must round-trip \
9909 to the same variant; got {parsed:?}"
9910 );
9911 }
9912 }
9913
9914 // ── drift-detection: ChildSpec::nome accessor pins ────────────────────
9915 //
9916 // The M2 supervisor-tree sibling of the M3 `Membro::nome` (4a32abf) pin
9917 // pair (`membro_nome_returns_caixa_byte_equal_across_permutations` +
9918 // `membro_nome_borrows_from_caixa_storage`) — extended here to the M2
9919 // per-`:children` child-caixa `:nome` axis, sibling to the first M2
9920 // slot scalar accessor `UpgradeFromEntry::prior_versao` (75d27a8) on
9921 // the peer per-`:upgrade-from :from` axis. The three pins jointly
9922 // brace the accessor against every future silent detour that would
9923 // desynchronize it from the raw `.caixa` field access every consumer
9924 // previously open-coded.
9925
9926 #[test]
9927 fn child_spec_nome_returns_caixa_byte_equal_across_permutations() {
9928 // The canonical per-`:children` child-caixa `:nome`-scalar pin:
9929 // [`ChildSpec::nome`] must return the `:children :caixa` field
9930 // byte-for-byte across every DNS-1123-label value the upstream
9931 // [`crate::render::require_valid_dns_1123_label`] gate at
9932 // `SupervisorSpec::validate` admits. Peer of the sibling
9933 // `membro_nome_returns_caixa_byte_equal_across_permutations`
9934 // (4a32abf) pin on the M3 per-`:membros` axis — same "the
9935 // substrate-primitive accessor must byte-equal the raw field
9936 // access verbatim across every author-declared value" discipline
9937 // extended to the M2 supervisor-tree per-`:children` arm. Pins
9938 // against a future silent detour that re-normalized the child
9939 // identity (an accidental `.to_lowercase()` — every `:children
9940 // :caixa` is validated as a DNS-1123 label upstream, so any
9941 // re-normalization is redundant + a drift surface between the
9942 // validator and the accessor), a namespace-prefix rewrite (an
9943 // accidental `format!("{namespace}/{caixa}")` per-CR
9944 // fully-qualified rewrite that didn't land on the peer axes), or
9945 // a per-cluster alias stamp the future wasm-operator's
9946 // hierarchical reconciliation scheduler authors on one consumer
9947 // without the others. Five values sweep the accept-set the
9948 // DNS-1123 gate upstream admits (short single-word / dashed /
9949 // v-suffixed / mixed-digit child names).
9950 for name in [
9951 "worker",
9952 "cache-server",
9953 "scratch-job",
9954 "orders-v2",
9955 "session-8080",
9956 ] {
9957 let c = ChildSpec {
9958 caixa: name.into(),
9959 versao: "^0.1".into(),
9960 restart: RestartPolicy::Permanent,
9961 };
9962 assert_eq!(
9963 c.nome(),
9964 name,
9965 "ChildSpec::nome must return :children :caixa verbatim \
9966 (got {:?}, expected {name:?})",
9967 c.nome(),
9968 );
9969 assert_eq!(
9970 c.nome(),
9971 c.caixa.as_str(),
9972 "ChildSpec::nome must byte-equal the .caixa field access",
9973 );
9974 }
9975 }
9976
9977 #[test]
9978 fn child_spec_nome_borrows_from_caixa_storage() {
9979 // The borrow-not-copy pin: [`ChildSpec::nome`] must return a
9980 // `&str` slice that borrows from the typed slot's own [`String`]
9981 // storage — same-address invariant with `c.caixa.as_str()`. Pins
9982 // against a future silent detour that allocated a fresh `String`
9983 // (`self.caixa.clone()` in the body would type-check but silently
9984 // drop the borrow, and every downstream consumer that assumed
9985 // the returned slice outlives `&self` would break on a stale-
9986 // reference use-after-free — the [`crate::render::insert_first_seen`]
9987 // dedup key at [`SupervisorSpec::validate`], the
9988 // [`validate_no_self_supervision`] equality check against the
9989 // parent's `:nome` string slice, the DNS-1123 gate's `&str`
9990 // borrow — each would silently misbehave if this accessor
9991 // produced a detached copy). Peer of the sibling
9992 // `membro_nome_borrows_from_caixa_storage` (4a32abf) pin on the
9993 // M3 per-`:membros` axis and the
9994 // `prior_versao_borrows_from_from_storage` (75d27a8) pin on the
9995 // first M2 slot scalar accessor.
9996 let c = ChildSpec {
9997 caixa: "worker".into(),
9998 versao: "^0.1".into(),
9999 restart: RestartPolicy::Permanent,
10000 };
10001 let name = c.nome();
10002 let caixa_slice = c.caixa.as_str();
10003 assert_eq!(
10004 name.as_ptr(),
10005 caixa_slice.as_ptr(),
10006 "ChildSpec::nome must borrow from the .caixa String's backing \
10007 storage — a fresh allocation here means the accessor no \
10008 longer names the substrate-primitive typed dispatch and \
10009 every downstream consumer would silently carry a detached \
10010 copy",
10011 );
10012 assert_eq!(
10013 name.len(),
10014 caixa_slice.len(),
10015 "ChildSpec::nome and .caixa.as_str() must byte-equal in length \
10016 as well as in address",
10017 );
10018 }
10019
10020 #[test]
10021 fn validate_gates_child_nome_through_lifted_accessor() {
10022 // Bilateral coherence pin: every `:children :caixa` that
10023 // [`SupervisorSpec::validate`] accepts is one
10024 // [`crate::render::require_valid_dns_1123_label`] accepts on the
10025 // accessor-projected value, and vice versa on the reject side.
10026 // This closes the "the validator reads through the accessor"
10027 // contract structurally — a future silent detour that made the
10028 // accessor return a different byte-string than the validator
10029 // gates against would surface here as a coverage mismatch, not
10030 // as an apply-time DNS-1123 rejection at
10031 // `metadata.name: Invalid value` far from the caixa.lisp source.
10032 // Peer of the M2 sibling
10033 // `validate_parses_prior_versao_through_lifted_accessor`
10034 // (75d27a8) on the per-`:upgrade-from :from` axis and the M3
10035 // `validate_membros` peer discipline.
10036 //
10037 // Accept-set sweep: five DNS-1123-label values the upstream gate
10038 // admits.
10039 for ok_name in ["a", "worker", "cache-server", "orders-v2", "svc-8080"] {
10040 let s = SupervisorSpec {
10041 children: vec![ChildSpec {
10042 caixa: ok_name.into(),
10043 versao: "^0.1".into(),
10044 restart: RestartPolicy::Permanent,
10045 }],
10046 ..SupervisorSpec::default()
10047 };
10048 s.validate().unwrap_or_else(|e| {
10049 panic!(
10050 "SupervisorSpec::validate must accept :children :caixa {ok_name:?} \
10051 (upstream DNS-1123 gate accepts it): got {e:?}",
10052 );
10053 });
10054 let c = ChildSpec {
10055 caixa: ok_name.into(),
10056 versao: "^0.1".into(),
10057 restart: RestartPolicy::Permanent,
10058 };
10059 crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| ())
10060 .unwrap_or_else(|()| {
10061 panic!(
10062 "require_valid_dns_1123_label must accept the accessor-projected \
10063 :children :caixa {ok_name:?}",
10064 );
10065 });
10066 }
10067 // Reject-set sweep: five DNS-1123-label-violating shapes the
10068 // upstream gate refuses (empty / uppercase / underscore / dot /
10069 // leading-hyphen). Every rejection at the validator must
10070 // correspond to a rejection when the accessor's projected value
10071 // is fed back through the shared gate.
10072 for bad_name in ["", "Worker", "my_worker", "team.worker", "-worker"] {
10073 let s = SupervisorSpec {
10074 children: vec![ChildSpec {
10075 caixa: bad_name.into(),
10076 versao: "^0.1".into(),
10077 restart: RestartPolicy::Permanent,
10078 }],
10079 ..SupervisorSpec::default()
10080 };
10081 let err = s.validate().unwrap_err();
10082 assert!(
10083 matches!(
10084 err,
10085 SupervisorError::EmptyChildName | SupervisorError::ChildCaixaInvalid { .. }
10086 ),
10087 "SupervisorSpec::validate must reject :children :caixa {bad_name:?} \
10088 via the DNS-1123 gate: got {err:?}",
10089 );
10090 let c = ChildSpec {
10091 caixa: bad_name.into(),
10092 versao: "^0.1".into(),
10093 restart: RestartPolicy::Permanent,
10094 };
10095 assert!(
10096 crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| (),)
10097 .is_err(),
10098 "require_valid_dns_1123_label must reject the accessor-projected \
10099 :children :caixa {bad_name:?}",
10100 );
10101 }
10102 }
10103
10104 // ── drift-detection: ChildSpec::versao_requirement accessor pins ──────
10105 //
10106 // Sibling of the peer per-`:membros` `membro_versao_requirement_*`
10107 // (a40b0e3) pin pair on the M3 mesh-slot surface — extended here to the
10108 // M2 supervisor-tree per-`:children` child-`:versao` axis, sibling to
10109 // the just-landed [`ChildSpec::nome`] (57c61d0) child-`:nome` pin
10110 // trio on the peer per-`:children` `String`-carry axis. The three pins
10111 // jointly brace the accessor against every future silent detour that
10112 // would desynchronize it from the raw `.versao` field access the
10113 // requirement gate + error carrier previously open-coded.
10114 //
10115 // Closes the last unlifted per-`:children` `String`-carry axis: the
10116 // pair (`nome`, `versao_requirement`) now jointly projects the
10117 // (`.caixa`, `.versao`) field pair every OTP-shape supervisor-tree
10118 // consumer that fans on per-child identity + version pin reads,
10119 // matching the peer M3 (`Membro::nome`, `Membro::versao_requirement`)
10120 // pair discipline verbatim.
10121 #[test]
10122 fn child_spec_versao_requirement_returns_versao_byte_equal_across_permutations() {
10123 // The canonical per-`:children` child-`:versao`-scalar pin:
10124 // [`ChildSpec::versao_requirement`] must return the `:children
10125 // :versao` field byte-for-byte across every Cargo-shaped semver
10126 // requirement value the upstream
10127 // [`crate::render::require_valid_versao_requirement`] gate admits.
10128 // Peer of the sibling
10129 // `membro_versao_requirement_returns_versao_byte_equal_across_permutations`
10130 // (a40b0e3) pin on the M3 per-`:membros` axis — same "the
10131 // substrate-primitive accessor must byte-equal the raw field
10132 // access verbatim across every author-declared value" discipline
10133 // extended to the M2 supervisor-tree per-`:children` arm. Pins
10134 // against a future silent detour that re-canonicalized the
10135 // requirement (an accidental `.to_string()` via
10136 // [`crate::version::parse_requirement`] → [`std::fmt::Display`]
10137 // round-trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and
10138 // silently drifted the error carrier's quoted requirement away
10139 // from the source `caixa.lisp`, an accidental whitespace trim on
10140 // `"^ 0.1"` that no consumer ever produced from the field-access
10141 // side, an accidental per-cluster lacre-projected concrete-version
10142 // rewrite that didn't land on the peer requirement-gate call).
10143 // Five values sweep the accept-set the shared
10144 // [`crate::render::require_valid_versao_requirement`] gate admits
10145 // (caret / tilde / exact / wildcard / bare-major).
10146 for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
10147 let c = ChildSpec {
10148 caixa: "worker".into(),
10149 versao: req.into(),
10150 restart: RestartPolicy::Permanent,
10151 };
10152 assert_eq!(
10153 c.versao_requirement(),
10154 req,
10155 "ChildSpec::versao_requirement must return :children :versao \
10156 verbatim (got {:?}, expected {req:?})",
10157 c.versao_requirement(),
10158 );
10159 assert_eq!(
10160 c.versao_requirement(),
10161 c.versao.as_str(),
10162 "ChildSpec::versao_requirement must byte-equal the .versao \
10163 field access",
10164 );
10165 }
10166 }
10167
10168 #[test]
10169 fn child_spec_versao_requirement_borrows_from_versao_storage() {
10170 // The borrow-not-copy pin: [`ChildSpec::versao_requirement`] must
10171 // return a `&str` slice that borrows from the typed slot's own
10172 // [`String`] storage — same-address invariant with
10173 // `c.versao.as_str()`. Pins against a future silent detour that
10174 // allocated a fresh `String` (`self.versao.clone()` in the body
10175 // would type-check but silently drop the borrow, and every
10176 // downstream consumer that assumed the returned slice outlives
10177 // `&self` — the [`crate::render::require_valid_versao_requirement`]
10178 // gate's `&str` borrow, the [`SupervisorError::ChildVersaoInvalid`]
10179 // `.to_string()` carrier's byte-length assumption — would silently
10180 // misbehave if this accessor produced a detached copy). Peer of
10181 // the sibling `child_spec_nome_borrows_from_caixa_storage`
10182 // (57c61d0) pin on the per-`:children` `:nome` axis and the M3
10183 // `membro_versao_requirement_borrows_from_versao_storage` (a40b0e3)
10184 // pin on the peer per-`:membros` `:versao` axis.
10185 let c = ChildSpec {
10186 caixa: "worker".into(),
10187 versao: "^0.1".into(),
10188 restart: RestartPolicy::Permanent,
10189 };
10190 let req = c.versao_requirement();
10191 let versao_slice = c.versao.as_str();
10192 assert_eq!(
10193 req.as_ptr(),
10194 versao_slice.as_ptr(),
10195 "ChildSpec::versao_requirement must borrow from the .versao \
10196 String's backing storage — a fresh allocation here means the \
10197 accessor no longer names the substrate-primitive typed \
10198 dispatch and every downstream consumer would silently carry \
10199 a detached copy",
10200 );
10201 assert_eq!(
10202 req.len(),
10203 versao_slice.len(),
10204 "ChildSpec::versao_requirement and .versao.as_str() must \
10205 byte-equal in length as well as in address",
10206 );
10207 }
10208
10209 #[test]
10210 fn validate_gates_child_versao_through_lifted_accessor() {
10211 // Bilateral coherence pin: every `:children :versao` that
10212 // [`SupervisorSpec::validate`] accepts is one
10213 // [`crate::render::require_valid_versao_requirement`] accepts on
10214 // the accessor-projected value, and vice versa on the reject side.
10215 // This closes the "the validator reads through the accessor"
10216 // contract structurally — a future silent detour that made the
10217 // accessor return a different byte-string than the validator gates
10218 // against would surface here as a coverage mismatch, not as a
10219 // resolver-time semver-parse rejection at lacre-closure time far
10220 // from the caixa.lisp source. Peer of the sibling
10221 // `validate_gates_child_nome_through_lifted_accessor` (57c61d0) on
10222 // the per-`:children :caixa` axis and the M2
10223 // `validate_parses_prior_versao_through_lifted_accessor` (75d27a8)
10224 // on the peer per-`:upgrade-from :from` axis.
10225 //
10226 // Accept-set sweep: five Cargo-shaped semver requirement values
10227 // the upstream gate admits (caret / tilde / exact / wildcard /
10228 // bare-major).
10229 for ok_req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
10230 let s = SupervisorSpec {
10231 children: vec![ChildSpec {
10232 caixa: "worker".into(),
10233 versao: ok_req.into(),
10234 restart: RestartPolicy::Permanent,
10235 }],
10236 ..SupervisorSpec::default()
10237 };
10238 s.validate().unwrap_or_else(|e| {
10239 panic!(
10240 "SupervisorSpec::validate must accept :children :versao {ok_req:?} \
10241 (upstream versao-requirement gate accepts it): got {e:?}",
10242 );
10243 });
10244 let c = ChildSpec {
10245 caixa: "worker".into(),
10246 versao: ok_req.into(),
10247 restart: RestartPolicy::Permanent,
10248 };
10249 crate::render::require_valid_versao_requirement(
10250 c.versao_requirement(),
10251 || (),
10252 |_reason| (),
10253 )
10254 .unwrap_or_else(|()| {
10255 panic!(
10256 "require_valid_versao_requirement must accept the accessor-projected \
10257 :children :versao {ok_req:?}",
10258 );
10259 });
10260 }
10261 // Reject-set sweep: five requirement-violating shapes the upstream
10262 // gate refuses. The empty string closes the empty-first arm of the
10263 // shared [`crate::render::require_valid_versao_requirement`]
10264 // cascade; the four non-empty arms exercise distinct semver-parse
10265 // failure modes the M3 peer per-`:membros` reject-set already pins
10266 // (`rejects_invalid_membro_versao_requirement` on `^bad-version`,
10267 // `rejects_membro_versao_with_double_caret_typo` on `^^0.1`,
10268 // `rejects_membro_versao_with_v_prefixed_tag` on `v0.1`) — the
10269 // shared parser routing means the same reject-set must fail
10270 // identically at the M2 supervisor-tree per-`:children` accessor
10271 // arm here. Every rejection at the validator must correspond to a
10272 // rejection when the accessor's projected value is fed back
10273 // through the shared gate.
10274 //
10275 // (Bare partial magnitudes like `"0.1"` and bare identifiers like
10276 // `"not-a-semver"` are intentionally *not* in the reject-set: the
10277 // semver crate accepts `"0.1"` as an implicit `^0.1` requirement,
10278 // and the identifier-tail arm's grammar admits some non-canonical
10279 // shapes — matching what the M3 peer test suite already documents
10280 // as the shared parser's accept-set edges.)
10281 for bad_req in ["", "v0.1.0", "^bad-version", "^^0.1", "v0.1"] {
10282 let s = SupervisorSpec {
10283 children: vec![ChildSpec {
10284 caixa: "worker".into(),
10285 versao: bad_req.into(),
10286 restart: RestartPolicy::Permanent,
10287 }],
10288 ..SupervisorSpec::default()
10289 };
10290 let err = s.validate().unwrap_err();
10291 assert!(
10292 matches!(
10293 err,
10294 SupervisorError::EmptyChildVersion { .. }
10295 | SupervisorError::ChildVersaoInvalid { .. }
10296 ),
10297 "SupervisorSpec::validate must reject :children :versao {bad_req:?} \
10298 via the versao-requirement gate: got {err:?}",
10299 );
10300 let c = ChildSpec {
10301 caixa: "worker".into(),
10302 versao: bad_req.into(),
10303 restart: RestartPolicy::Permanent,
10304 };
10305 assert!(
10306 crate::render::require_valid_versao_requirement(
10307 c.versao_requirement(),
10308 || (),
10309 |_reason| (),
10310 )
10311 .is_err(),
10312 "require_valid_versao_requirement must reject the accessor-projected \
10313 :children :versao {bad_req:?}",
10314 );
10315 }
10316 }
10317
10318 // ── per-`:children` `:restart` typed-accessor coherence pins ──────────
10319 //
10320 // The [`ChildSpec::restart`] accessor lift closes the last unlifted
10321 // per-`:children` axis (the pair `nome()` + `versao_requirement()`
10322 // already project the `String`-carry `(caixa, versao)` fields; the
10323 // `Copy`-composite-enum `restart` field is the third and final axis).
10324 // Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
10325 // (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
10326 // scalar accessor and the M3 mesh-slot [`crate::Placement::estrategia`]
10327 // (921fe1b) `Copy`-return [`crate::PlacementStrategy`] distribution-
10328 // strategy scalar accessor — same "one typed dispatch on the substrate
10329 // primitive, `Copy`-projected closed-set enum-arm discriminator" shape
10330 // extended onto the M2 supervisor-slot per-`:children` restart-decision
10331 // axis. The pin below covers the accessor's byte-equal projection
10332 // against the raw field access across every variant in the closed
10333 // accept-set (`Permanent`, `Transient`, `Temporary`).
10334
10335 #[test]
10336 fn child_spec_restart_returns_restart_verbatim_across_permutations() {
10337 // The canonical per-`:children` restart-decision-policy-scalar
10338 // pin: [`ChildSpec::restart`] must return the `:children :restart`
10339 // field verbatim as a [`RestartPolicy`], `Copy`-projected from the
10340 // typed slot's own [`RestartPolicy`] storage across every variant
10341 // in the closed accept-set (`Permanent`, `Transient`, `Temporary`).
10342 // Pins against a future silent detour that re-derived the policy
10343 // from a peer axis (an accidental fallback to
10344 // `if is_supervisor_child { Permanent } else { Temporary }` that
10345 // collapsed the child's kind axis into the restart discriminator),
10346 // a variant remap the operator authors on one consumer without the
10347 // other, or a stale-derive detour that substituted
10348 // [`RestartPolicy::default`] when the field held any explicit
10349 // variant (which would silently collapse the distinction between
10350 // "author explicitly declared `:restart Permanent`" and "author
10351 // omitted the slot and inherited the default" the future
10352 // per-cluster restart-decision override slot depends on).
10353 //
10354 // Peer of the sibling per-`:supervisor`
10355 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
10356 // (eafb619) pin on the M2 supervisor-slot sibling-restart-strategy
10357 // axis and the M3
10358 // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
10359 // (921fe1b) pin on the per-`:placement` distribution-strategy axis
10360 // — same "the substrate-primitive accessor must byte-equal the raw
10361 // field access verbatim across every author-declared value"
10362 // discipline extended onto the M2 supervisor-slot per-`:children`
10363 // restart-decision-policy axis, closing the last unlifted axis on
10364 // the per-`:children` [`ChildSpec`] type.
10365 for restart in [
10366 RestartPolicy::Permanent,
10367 RestartPolicy::Transient,
10368 RestartPolicy::Temporary,
10369 ] {
10370 let c = ChildSpec {
10371 caixa: "worker".into(),
10372 versao: "^0.1".into(),
10373 restart,
10374 };
10375 assert_eq!(
10376 c.restart(),
10377 restart,
10378 "ChildSpec::restart must return :children :restart \
10379 verbatim (got {:?}, expected {restart:?})",
10380 c.restart(),
10381 );
10382 assert_eq!(
10383 c.restart(),
10384 c.restart,
10385 "ChildSpec::restart accessor and .restart field access \
10386 must byte-equal — the accessor is the substrate-primitive \
10387 typed dispatch every downstream per-child restart-\
10388 decision consumer must route through",
10389 );
10390 }
10391 }
10392
10393 // ── per-`:supervisor` `:estrategia` typed-accessor coherence pins ─────
10394 //
10395 // The [`SupervisorSpec::estrategia`] accessor lift extends the peer M3
10396 // [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
10397 // distribution-strategy accessor discipline onto the M2 supervisor-slot
10398 // per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
10399 // scalar axis. The two pins below cover (1) the accessor's byte-equal
10400 // projection against the raw field access across every variant in the
10401 // closed accept-set, and (2) the two-consumer coherence between the
10402 // [`SupervisorSpec::validate`] partition-dispatch `match` arm and the
10403 // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
10404 // carrier's `estrategia:` field — peer of the sibling M3
10405 // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
10406 // / `validate_placement_reads_through_lifted_estrategia_accessor` pin
10407 // pair on the per-`:placement` distribution-strategy axis.
10408
10409 #[test]
10410 fn supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations() {
10411 // The canonical per-`:supervisor` sibling-restart-strategy-scalar
10412 // pin: [`SupervisorSpec::estrategia`] must return the
10413 // `:supervisor :estrategia` field verbatim as a
10414 // [`RestartStrategy`], `Copy`-projected from the typed slot's own
10415 // [`RestartStrategy`] storage across every variant in the closed
10416 // accept-set (`OneForOne`, `OneForAll`, `RestForOne`,
10417 // `SimpleOneForOne`). Pins against a future silent detour that
10418 // re-derived the strategy from a peer axis (an accidental
10419 // fallback to `if children.is_empty() { SimpleOneForOne } else {
10420 // OneForOne }` collapse that read the children-count axis into
10421 // the strategy discriminator), a variant remap the operator
10422 // authors on one consumer without the other, or a stale-derive
10423 // detour that substituted [`RestartStrategy::default`] when the
10424 // field held any explicit variant (which would silently collapse
10425 // the distinction between "author explicitly declared
10426 // `:estrategia OneForOne`" and "author omitted the slot and
10427 // inherited the default" the future per-cluster strategy override
10428 // slot depends on). Peer of the sibling M3
10429 // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
10430 // (921fe1b) pin on the M3 mesh-slot `Copy`-composite-enum scalar
10431 // axis — same "the substrate-primitive accessor must byte-equal
10432 // the raw field access verbatim across every author-declared
10433 // value" discipline extended onto the M2 supervisor-slot
10434 // per-`:supervisor` sibling-restart-strategy axis.
10435 for &estrategia in RestartStrategy::ALL {
10436 // `SimpleOneForOne` requires `children.is_empty()`; the peer
10437 // three strategies require a non-empty static children list.
10438 // Build each shape coherently so the pin's fixture would
10439 // itself pass [`SupervisorSpec::validate`] once fed through
10440 // the sibling coherence pin below — the byte-equal projection
10441 // asserted here is a strictly weaker property (a `Copy` field
10442 // read) that does not depend on `validate` running, but
10443 // keeping the fixture validate-clean means a future extension
10444 // of the pin to exercise `validate` end-to-end does not have
10445 // to re-author the children shape.
10446 //
10447 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
10448 // shape partition through the [`gen_platform::IsVariant`]
10449 // derive-generated
10450 // [`RestartStrategy::is_simple_one_for_one`] predicate rather
10451 // than the raw `matches!(estrategia, RestartStrategy::
10452 // SimpleOneForOne)` open-coded pattern-match — same closed-
10453 // set-typed-enum arm-discriminator dispatch discipline the
10454 // sibling [`crate::upgrade::UpgradeInstruction::is_restart`]
10455 // convergence (915a934) extended onto its two paired positive
10456 // / negated `matches!` sites and the peer
10457 // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
10458 // predicate convergence (766ec63) extended onto the M3 mesh-
10459 // slot per-`:placement` distribution-strategy discriminator
10460 // axis. See the sibling `round_trip_all_strategies` and the
10461 // peer `manifest::tests::
10462 // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
10463 // fixture for the two peer sites the same lift closes on.
10464 let children = if estrategia.is_simple_one_for_one() {
10465 Vec::new()
10466 } else {
10467 vec![ChildSpec {
10468 caixa: "worker".into(),
10469 versao: "^0.1".into(),
10470 restart: RestartPolicy::Permanent,
10471 }]
10472 };
10473 let s = SupervisorSpec {
10474 estrategia,
10475 children,
10476 ..SupervisorSpec::default()
10477 };
10478 assert_eq!(
10479 s.estrategia(),
10480 estrategia,
10481 "SupervisorSpec::estrategia must return :supervisor :estrategia \
10482 verbatim (got {:?}, expected {estrategia:?})",
10483 s.estrategia(),
10484 );
10485 assert_eq!(
10486 s.estrategia(),
10487 s.estrategia,
10488 "SupervisorSpec::estrategia accessor and .estrategia field \
10489 access must byte-equal — the accessor is the substrate-\
10490 primitive typed dispatch every downstream sibling-restart-\
10491 strategy consumer must route through",
10492 );
10493 }
10494 }
10495
10496 #[test]
10497 fn validate_reads_through_lifted_estrategia_accessor() {
10498 // Two-consumer coherence pin: the [`SupervisorSpec::validate`]
10499 // `SimpleOneForOne ↔ non-SimpleOneForOne` `match` partition
10500 // dispatch (which reads through [`SupervisorSpec::estrategia`]
10501 // to fan across the strategy-arm shape-gate cascades) and the
10502 // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
10503 // error carrier's `estrategia:` field (which reads through
10504 // [`SupervisorSpec::estrategia`] to name the strategy the empty
10505 // `:children` list was declared against) must both key off the
10506 // lifted accessor, so any future rebrand on the typed slot's
10507 // reader shape lands at exactly one place. Pins the two-site
10508 // coherence by exercising the `NoChildren` error surface end-to-
10509 // end across every non-`SimpleOneForOne` variant and asserting
10510 // the surfaced `estrategia:` field byte-equals the accessor's
10511 // return. Peer of the sibling M3
10512 // `validate_placement_reads_through_lifted_estrategia_accessor`
10513 // (921fe1b) three-consumer coherence pin on the per-`:placement`
10514 // distribution-strategy axis.
10515 for estrategia in [
10516 RestartStrategy::OneForOne,
10517 RestartStrategy::OneForAll,
10518 RestartStrategy::RestForOne,
10519 ] {
10520 let s = SupervisorSpec {
10521 estrategia,
10522 children: Vec::new(),
10523 ..SupervisorSpec::default()
10524 };
10525 let err = s.validate().unwrap_err();
10526 match err {
10527 SupervisorError::NoChildren { estrategia: e } => {
10528 assert_eq!(
10529 e,
10530 s.estrategia(),
10531 "NoChildren.estrategia must byte-equal \
10532 SupervisorSpec::estrategia() — the empty-`:children` \
10533 refusal reads through the lifted accessor",
10534 );
10535 assert_eq!(
10536 e, estrategia,
10537 "NoChildren.estrategia must carry the author-declared \
10538 :supervisor :estrategia variant verbatim (got {e:?}, \
10539 expected {estrategia:?})",
10540 );
10541 }
10542 other => panic!("expected NoChildren, got {other:?} for estrategia={estrategia:?}"),
10543 }
10544 }
10545 }
10546
10547 // ── per-`:supervisor` `:max-restarts` typed-accessor coherence pins ────
10548 //
10549 // The [`SupervisorSpec::max_restarts`] accessor lift extends the peer M3
10550 // [`crate::CircuitBreaker::max_failures`] (3a74062) `Copy`-return
10551 // required-`u32` scalar accessor discipline onto the M2 supervisor-slot
10552 // per-`:supervisor` restart-budget-count `Copy`-`u32` scalar axis.
10553 // The two pins below cover (1) the accessor's byte-equal projection
10554 // against the raw field access across every representative value in
10555 // the `u32` accept-set (`1` lower boundary, `SUPERVISOR_MAX_RESTARTS_MAX`
10556 // upper boundary, `0` past-the-guard zero sentinel, `u32::MAX`
10557 // past-the-guard cap sentinel), and (2) the [`SupervisorSpec::validate`]
10558 // zero-floor / cap composition — the validate gate and the accessor
10559 // must route through the same substrate-primitive typed dispatch, so
10560 // any future silent detour that had the accessor perform a
10561 // bounds-collapsing clamp would fail here at caixa-core build time.
10562 // Peer of the sibling M3
10563 // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
10564 // (3a74062) pin on the per-`CircuitBreaker :max-failures` axis.
10565
10566 #[test]
10567 fn supervisor_spec_max_restarts_returns_max_restarts_u32_byte_equal_across_permutations() {
10568 // The canonical per-`:supervisor` restart-budget-count scalar pin:
10569 // [`SupervisorSpec::max_restarts`] must return the `:supervisor
10570 // :max-restarts` typed `u32` verbatim, `Copy`-projected from the
10571 // typed slot's own `u32` storage, byte-equal to the raw field
10572 // access across every representative value in the accept-set —
10573 // `1` (the lower boundary of the `1..=SUPERVISOR_MAX_RESTARTS_MAX`
10574 // accept-set the surrounding [`SupervisorSpec::validate`] gate
10575 // carves out on the sibling `ZeroMaxRestarts` refusal),
10576 // `SUPERVISOR_MAX_RESTARTS_MAX` (the upper boundary the same gate
10577 // carves out on the sibling `MaxRestartsExceedsCap` refusal), `0`
10578 // (a past-the-guard sentinel that pins the accessor doesn't
10579 // perform a silent bounds-collapse into `1` on the zero arm —
10580 // validate rejects zero but the accessor must ship the raw slot
10581 // verbatim so a validate-time gate regression surfaces at the
10582 // emit boundary rather than being silently absorbed), `u32::MAX`
10583 // (a past-the-guard sentinel that pins the accessor doesn't
10584 // perform a silent bounds-collapse through
10585 // `SUPERVISOR_MAX_RESTARTS_MAX` at the return path).
10586 //
10587 // Peer of the sibling M3
10588 // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
10589 // (3a74062) pin on the M3 mesh-slot `Copy`-`u32` sub-struct
10590 // required-scalar axis — same "the substrate-primitive accessor
10591 // must byte-equal the raw field access verbatim across every
10592 // value in the `u32` accept-set" discipline extended onto the M2
10593 // supervisor-slot per-`:supervisor` restart-budget-count axis.
10594 for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX, 0, u32::MAX] {
10595 let s = SupervisorSpec {
10596 max_restarts,
10597 ..SupervisorSpec::default()
10598 };
10599 assert_eq!(
10600 s.max_restarts(),
10601 max_restarts,
10602 "SupervisorSpec::max_restarts must return :supervisor \
10603 :max-restarts verbatim (got {}, expected {max_restarts})",
10604 s.max_restarts(),
10605 );
10606 assert_eq!(
10607 s.max_restarts(),
10608 s.max_restarts,
10609 "SupervisorSpec::max_restarts accessor and .max_restarts \
10610 field access must byte-equal — the accessor is the \
10611 substrate-primitive typed dispatch every downstream \
10612 restart-budget-count consumer must route through",
10613 );
10614 }
10615 }
10616
10617 #[test]
10618 fn validate_max_restarts_zero_floor_and_cap_arms_route_through_accessor() {
10619 // Composition pin: [`SupervisorSpec::validate`]'s `:max-restarts`
10620 // zero-floor + upper-cap bracket must key off
10621 // [`SupervisorSpec::max_restarts`], not the raw `.max_restarts`
10622 // field access. Structurally: a `SupervisorSpec { max_restarts:
10623 // 0, .. }` must surface the `ZeroMaxRestarts` refusal exactly, a
10624 // `SupervisorSpec { max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
10625 // .. }` must surface the `MaxRestartsExceedsCap` refusal exactly
10626 // (with the offending count carried verbatim from the accessor
10627 // return), and a `SupervisorSpec { max_restarts: 1, .. }` (the
10628 // lower boundary of the accept-set) plus a `SupervisorSpec {
10629 // max_restarts: SUPERVISOR_MAX_RESTARTS_MAX, .. }` (the upper
10630 // boundary) must pass validate. The four together jointly pin the
10631 // accessor + validate-gate composition: any future silent detour
10632 // that had the accessor return a fresh `1` on the zero arm (a
10633 // `.max_restarts().max(1)` collapse) would silently absorb the
10634 // `ZeroMaxRestarts` refusal at the accessor boundary and the
10635 // validate gate would accept a struct-literal `SupervisorSpec {
10636 // max_restarts: 0, .. }` — the composition pin catches that at
10637 // caixa-core build time.
10638 //
10639 // Peer of the sibling M3
10640 // `validate_politicas_max_failures_zero_floor_arm_routes_through_accessor`
10641 // (3a74062) pin on the sibling per-`CircuitBreaker :max-failures`
10642 // composition axis — same "the validate / shape-gate predicate
10643 // must route through the substrate-primitive typed dispatch"
10644 // discipline extended onto the peer M2 supervisor-slot
10645 // required-`u32` composition axis.
10646 let child = ChildSpec {
10647 caixa: "worker".into(),
10648 versao: "^0.1".into(),
10649 restart: RestartPolicy::Permanent,
10650 };
10651 // Zero-floor arm.
10652 let s = SupervisorSpec {
10653 max_restarts: 0,
10654 children: vec![child.clone()],
10655 ..SupervisorSpec::default()
10656 };
10657 assert_eq!(
10658 s.validate().unwrap_err(),
10659 SupervisorError::ZeroMaxRestarts,
10660 "validate must reject max_restarts == 0 with ZeroMaxRestarts \
10661 — the accessor and the validate gate must route through the \
10662 same substrate-primitive typed dispatch on the zero-floor arm",
10663 );
10664 // Cap arm — the surfaced `max_restarts:` field must byte-equal
10665 // the accessor's return so a future rebrand on the accessor
10666 // lands in the diagnostic without a coordinated rewrite.
10667 let over_cap = SUPERVISOR_MAX_RESTARTS_MAX + 1;
10668 let s = SupervisorSpec {
10669 max_restarts: over_cap,
10670 children: vec![child.clone()],
10671 ..SupervisorSpec::default()
10672 };
10673 match s.validate().unwrap_err() {
10674 SupervisorError::MaxRestartsExceedsCap { max_restarts } => {
10675 assert_eq!(
10676 max_restarts,
10677 s.max_restarts(),
10678 "MaxRestartsExceedsCap.max_restarts must byte-equal \
10679 SupervisorSpec::max_restarts() — the cap-arm refusal \
10680 reads through the lifted accessor",
10681 );
10682 assert_eq!(
10683 max_restarts, over_cap,
10684 "MaxRestartsExceedsCap.max_restarts must carry the \
10685 author-declared :supervisor :max-restarts value \
10686 verbatim (got {max_restarts}, expected {over_cap})",
10687 );
10688 }
10689 other => panic!("expected MaxRestartsExceedsCap, got {other:?}"),
10690 }
10691 // Lower + upper accept-set boundaries.
10692 for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX] {
10693 let s = SupervisorSpec {
10694 max_restarts,
10695 children: vec![child.clone()],
10696 ..SupervisorSpec::default()
10697 };
10698 assert!(
10699 s.validate().is_ok(),
10700 "validate must accept max_restarts == {max_restarts} \
10701 (an accept-set boundary of \
10702 1..=SUPERVISOR_MAX_RESTARTS_MAX)",
10703 );
10704 }
10705 }
10706
10707 // ── per-`:supervisor` `:restart-window` typed-accessor coherence pins ─
10708 //
10709 // The [`SupervisorSpec::restart_window`] accessor lift extends the peer
10710 // M2 [`crate::LimitsSpec::wall_clock`] (8cb717b) `Option<Duration>`
10711 // accessor discipline and the peer M3 [`crate::MeshPolicy::timeout`]
10712 // (7073d0f) `Option<Duration>` accessor discipline onto the M2
10713 // supervisor-slot per-`:supervisor` restart-intensity-denominator
10714 // `Option<Duration>` scalar axis — third `Copy`-return accessor on the
10715 // M2 supervisor-slot `SupervisorSpec` type, closing the last unlifted
10716 // per-`:supervisor` scalar-value axis. The three pins below cover
10717 // (1) the accessor's byte-equal projection against the raw field
10718 // access across every representative value in the `Option<Duration>`
10719 // accept-set (`None` never-reset sentinel, `Some(Duration::from_millis(1))`
10720 // lower boundary, `Some(SUPERVISOR_RESTART_WINDOW_MAX)` upper boundary,
10721 // `Some(Duration::ZERO)` past-the-guard zero sentinel, `Some(Duration::MAX)`
10722 // past-the-guard above-cap sentinel), (2) the [`SupervisorSpec::validate`]
10723 // `if let Some(w) = self.restart_window() { … }` bracket-arm
10724 // composition — the validate gate and the accessor must route through
10725 // the same substrate-primitive typed dispatch, so any future silent
10726 // detour that had the accessor perform a bounds-collapsing clamp
10727 // would fail here at caixa-core build time, and (3) the accessor's
10728 // by-copy idempotence pin — the returned `Option<Duration>` must
10729 // outlive `&self` and two successive calls must return byte-equal
10730 // values. Peer of the sibling M2
10731 // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
10732 // (8cb717b) pin on the per-`:limits :wall-clock` axis and the sibling
10733 // M3 `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
10734 // (7073d0f) pin on the per-`:politicas :timeout` axis.
10735
10736 #[test]
10737 fn supervisor_spec_restart_window_returns_option_duration_byte_equal_across_permutations() {
10738 // The canonical per-`:supervisor` restart-intensity-denominator
10739 // scalar pin: [`SupervisorSpec::restart_window`] must return the
10740 // `:supervisor :restart-window` typed [`Duration`] verbatim as an
10741 // `Option<Duration>`, `Copy`-projected from the typed slot's own
10742 // `Option<Duration>` storage, byte-equal to the raw field access
10743 // across every representative value in the accept-set — `None`
10744 // (the "never reset — every restart across the supervisor's
10745 // lifetime counts against the sibling `:max-restarts` budget"
10746 // sentinel the field's own docstring names and the peer
10747 // `validate_accepts_none_restart_window` pin locks in on the
10748 // [`SupervisorSpec::validate`] entry-side),
10749 // `Some(Duration::from_millis(1))` (the structural minimum a
10750 // validated `:restart-window` may carry, the integer-millisecond
10751 // floor [`SupervisorError::RestartWindowNotCanonical`] rejects
10752 // everything sub-ms; `Duration::ZERO` is separately rejected by
10753 // [`SupervisorError::RestartWindowZero`]),
10754 // `Some(SUPERVISOR_RESTART_WINDOW_MAX)` (the upper boundary the
10755 // surrounding [`SupervisorSpec::validate`] gate carves out on the
10756 // sibling [`SupervisorError::RestartWindowExceedsCap`] refusal),
10757 // `Some(Duration::ZERO)` (a past-the-guard sentinel that pins the
10758 // accessor doesn't perform a silent bounds-collapse into `None` on
10759 // the zero-Duration arm — validate rejects zero but the accessor
10760 // must ship the raw slot verbatim so a validate-time gate
10761 // regression surfaces at the emit boundary rather than being
10762 // silently absorbed), and `Some(Duration::MAX)` (a past-the-guard
10763 // sentinel that pins the accessor doesn't perform a silent
10764 // bounds-collapse through [`SUPERVISOR_RESTART_WINDOW_MAX`] at the
10765 // return path).
10766 //
10767 // Peer of the sibling M2
10768 // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
10769 // (8cb717b) pin on the per-`:limits :wall-clock` axis and the
10770 // sibling M3
10771 // `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
10772 // (7073d0f) pin on the per-`:politicas :timeout` axis — same "the
10773 // substrate-primitive accessor must byte-equal the raw field
10774 // access verbatim across every value in the `Option<Duration>`
10775 // accept-set" discipline extended onto the M2 supervisor-slot
10776 // per-`:supervisor` `Option<Duration>` axis. Pins against a future
10777 // silent detour that re-derived the restart-window from a peer
10778 // axis (an accidental `.max_restarts.into()` collapse that read
10779 // the restart-budget-count as a duration — the two axes serve
10780 // different halves of the `MaxIntensity / Period` restart-
10781 // intensity ratio, and confusing them silently inverts the
10782 // ratio's numerator and denominator), a `None → Some(Duration::ZERO)`
10783 // "zero means never reset" collapse (the canonical
10784 // `Option<Duration>` → `Duration` collapse footgun the
10785 // [`SupervisorError::RestartWindowZero`] validate arm guards on
10786 // the peer zero-floor axis; a zero period either trips on the
10787 // first failure or never trips depending on operator
10788 // interpretation, neither of which is the author's "never reset"
10789 // intent that `None` expresses structurally), or a per-arm
10790 // variant swap that landed on one consumer without the other.
10791 for restart_window in [
10792 None,
10793 Some(Duration::from_millis(1)),
10794 Some(SUPERVISOR_RESTART_WINDOW_MAX),
10795 Some(Duration::ZERO),
10796 Some(Duration::MAX),
10797 ] {
10798 let s = SupervisorSpec {
10799 restart_window,
10800 ..SupervisorSpec::default()
10801 };
10802 assert_eq!(
10803 s.restart_window(),
10804 restart_window,
10805 "SupervisorSpec::restart_window must return :supervisor \
10806 :restart-window verbatim (got {:?}, expected {restart_window:?})",
10807 s.restart_window(),
10808 );
10809 assert_eq!(
10810 s.restart_window(),
10811 s.restart_window,
10812 "SupervisorSpec::restart_window accessor and \
10813 .restart_window field access must byte-equal — the \
10814 accessor is the substrate-primitive typed dispatch every \
10815 downstream restart-intensity-denominator consumer must \
10816 route through",
10817 );
10818 }
10819 }
10820
10821 #[test]
10822 fn validate_restart_window_bracket_arm_routes_through_accessor() {
10823 // Composition pin: [`SupervisorSpec::validate`]'s
10824 // `:restart-window` `if let Some(w) = self.restart_window() { … }`
10825 // zero-floor + integer-millisecond canonical-form + upper-cap
10826 // bracket-arm must key off [`SupervisorSpec::restart_window`], not
10827 // the raw `.restart_window` field access. Structurally: a
10828 // `SupervisorSpec { restart_window: None, .. }` must pass the
10829 // arm gate structurally (the `if let Some(_)` shape returns
10830 // early on the `None` arm — the accessor and the validate gate
10831 // must agree on `None → skip the bracket cascade` so an authored
10832 // `:restart-window ()` structurally routes through the "never
10833 // reset" sentinel path), a `SupervisorSpec { restart_window:
10834 // Some(Duration::ZERO), .. }` must surface the `RestartWindowZero`
10835 // refusal exactly, a `SupervisorSpec { restart_window:
10836 // Some(Duration::from_micros(1500)), .. }` must surface the
10837 // `RestartWindowNotCanonical` refusal exactly (with the offending
10838 // duration carried verbatim from the accessor return), a
10839 // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX
10840 // + Duration::from_millis(1)), .. }` must surface the
10841 // `RestartWindowExceedsCap` refusal exactly (with the offending
10842 // duration carried verbatim from the accessor return), and a
10843 // `SupervisorSpec { restart_window: Some(Duration::from_millis(1)),
10844 // .. }` (the lower boundary of the accept-set) plus a
10845 // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
10846 // .. }` (the upper boundary) must pass validate. The six together
10847 // jointly pin the accessor + validate-gate composition: any future
10848 // silent detour that had the accessor return a fresh `None` on any
10849 // `Some` arm (a `.restart_window().filter(|w| !w.is_zero())`
10850 // collapse) would silently absorb the `RestartWindowZero` refusal
10851 // at the accessor boundary and the validate gate would accept a
10852 // struct-literal `SupervisorSpec { restart_window:
10853 // Some(Duration::ZERO), .. }` — the composition pin catches that
10854 // at caixa-core build time.
10855 //
10856 // Peer of the sibling M2 [`crate::LimitsSpec::wall_clock`]
10857 // (8cb717b) validate-arm-route pin on the per-`:limits :wall-clock`
10858 // axis and the peer M3 [`crate::MeshPolicy::timeout`] (7073d0f)
10859 // accessor-composition pin on the per-`:politicas :timeout` axis —
10860 // same "the validate / shape-gate predicate must route through
10861 // the substrate-primitive typed dispatch" discipline extended
10862 // onto the peer M2 supervisor-slot optional-`Duration` axis.
10863 let child = ChildSpec {
10864 caixa: "worker".into(),
10865 versao: "^0.1".into(),
10866 restart: RestartPolicy::Permanent,
10867 };
10868 // None arm — must not surface any :restart-window-shaped refusal;
10869 // the `if let Some(_)` bracket returns early on `None` structurally.
10870 let s = SupervisorSpec {
10871 restart_window: None,
10872 children: vec![child.clone()],
10873 ..SupervisorSpec::default()
10874 };
10875 assert!(
10876 s.validate().is_ok(),
10877 "validate must accept restart_window: None (the never-reset \
10878 sentinel) — the `if let Some(_)` bracket returns early on \
10879 the None arm and the accessor must agree",
10880 );
10881 // Zero-floor arm.
10882 let s = SupervisorSpec {
10883 restart_window: Some(Duration::ZERO),
10884 children: vec![child.clone()],
10885 ..SupervisorSpec::default()
10886 };
10887 assert_eq!(
10888 s.validate().unwrap_err(),
10889 SupervisorError::RestartWindowZero,
10890 "validate must reject restart_window == Some(Duration::ZERO) \
10891 with RestartWindowZero — the accessor and the validate gate \
10892 must route through the same substrate-primitive typed \
10893 dispatch on the zero-floor arm",
10894 );
10895 // Non-canonical (sub-ms) arm — the surfaced `window:` field must
10896 // byte-equal the accessor's return so a future rebrand on the
10897 // accessor lands in the diagnostic without a coordinated rewrite.
10898 let sub_ms = Duration::from_micros(1500);
10899 let s = SupervisorSpec {
10900 restart_window: Some(sub_ms),
10901 children: vec![child.clone()],
10902 ..SupervisorSpec::default()
10903 };
10904 match s.validate().unwrap_err() {
10905 SupervisorError::RestartWindowNotCanonical { window } => {
10906 assert_eq!(
10907 Some(window),
10908 s.restart_window(),
10909 "RestartWindowNotCanonical.window must byte-equal \
10910 SupervisorSpec::restart_window().unwrap() — the \
10911 non-canonical-arm refusal reads through the lifted \
10912 accessor",
10913 );
10914 assert_eq!(
10915 window, sub_ms,
10916 "RestartWindowNotCanonical.window must carry the \
10917 author-declared :supervisor :restart-window value \
10918 verbatim (got {window:?}, expected {sub_ms:?})",
10919 );
10920 }
10921 other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
10922 }
10923 // Cap arm — the surfaced `window:` field must byte-equal the
10924 // accessor's return.
10925 let over_cap = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
10926 let s = SupervisorSpec {
10927 restart_window: Some(over_cap),
10928 children: vec![child.clone()],
10929 ..SupervisorSpec::default()
10930 };
10931 match s.validate().unwrap_err() {
10932 SupervisorError::RestartWindowExceedsCap { window } => {
10933 assert_eq!(
10934 Some(window),
10935 s.restart_window(),
10936 "RestartWindowExceedsCap.window must byte-equal \
10937 SupervisorSpec::restart_window().unwrap() — the \
10938 cap-arm refusal reads through the lifted accessor",
10939 );
10940 assert_eq!(
10941 window, over_cap,
10942 "RestartWindowExceedsCap.window must carry the \
10943 author-declared :supervisor :restart-window value \
10944 verbatim (got {window:?}, expected {over_cap:?})",
10945 );
10946 }
10947 other => panic!("expected RestartWindowExceedsCap, got {other:?}"),
10948 }
10949 // Lower + upper accept-set boundaries.
10950 for restart_window in [Duration::from_millis(1), SUPERVISOR_RESTART_WINDOW_MAX] {
10951 let s = SupervisorSpec {
10952 restart_window: Some(restart_window),
10953 children: vec![child.clone()],
10954 ..SupervisorSpec::default()
10955 };
10956 assert!(
10957 s.validate().is_ok(),
10958 "validate must accept restart_window == Some({restart_window:?}) \
10959 (an accept-set boundary of \
10960 1ms..=SUPERVISOR_RESTART_WINDOW_MAX)",
10961 );
10962 }
10963 }
10964
10965 #[test]
10966 fn supervisor_spec_restart_window_projects_option_duration_by_copy() {
10967 // The by-copy pin: [`SupervisorSpec::restart_window`] returns
10968 // `Option<Duration>` by copy — `Duration` is `Copy` (so
10969 // `Option<Duration>` is `Copy`) and the accessor must return by
10970 // value, not by reference. Peer of the sibling M2
10971 // [`crate::LimitsSpec::wall_clock`] (8cb717b) by-copy pin on the
10972 // per-`:limits :wall-clock` axis and the sibling M3
10973 // [`crate::MeshPolicy::timeout`] (7073d0f) by-copy pin on the
10974 // per-`:politicas :timeout` axis, extended onto the peer M2
10975 // supervisor-slot `Option<Duration>` copy-invariant shape — the
10976 // accessor's returned `Option<Duration>` must outlive `&self`
10977 // (multiple calls must return equal values from a dropped-`&self`
10978 // copy, since the returned Option carries no borrow), and calling
10979 // the accessor twice on the same SupervisorSpec must yield the
10980 // same `Option<Duration>` verbatim (idempotent, no side effects
10981 // on `&self`).
10982 //
10983 // Pins against a future silent detour that returned
10984 // `Option<&Duration>` (which would type-check but silently break
10985 // every downstream caller — the future wasm-operator's
10986 // per-supervisor restart-intensity counter consumes `Duration` by
10987 // value and `&Duration` would fold to a detached copy at the call
10988 // site), an accidental `Option::as_ref()` projection
10989 // (`self.restart_window.as_ref()` would also type-check but
10990 // return `Option<&Duration>`), or a one-arm-only accessor that
10991 // reads `Some(*w)` in the Some arm but reads a fresh
10992 // `Default::default()` (which would collapse to `Duration::ZERO`,
10993 // not `None`) in the None arm — a footgun the
10994 // [`SupervisorError::RestartWindowZero`] validate arm explicitly
10995 // closes since Erlang/OTP's `MaxIntensity / Period` invariant
10996 // requires `Period > 0` and `None` structurally expresses "never
10997 // reset" instead.
10998 for restart_window in [
10999 None,
11000 Some(Duration::from_millis(1)),
11001 Some(Duration::from_secs(60)),
11002 Some(SUPERVISOR_RESTART_WINDOW_MAX),
11003 ] {
11004 let s = SupervisorSpec {
11005 restart_window,
11006 ..SupervisorSpec::default()
11007 };
11008 let first = s.restart_window();
11009 let second = s.restart_window();
11010 assert_eq!(
11011 first, second,
11012 "SupervisorSpec::restart_window must be idempotent — two \
11013 successive calls on the same &self must return the \
11014 same Option<Duration>",
11015 );
11016 assert_eq!(
11017 first, restart_window,
11018 "SupervisorSpec::restart_window must return :supervisor \
11019 :restart-window verbatim by copy — got {first:?}, \
11020 expected {restart_window:?}",
11021 );
11022 }
11023 }
11024
11025 // ── per-`:supervisor` `:children` typed-accessor coherence pins ─────────
11026 //
11027 // The [`SupervisorSpec::children`] accessor lift is the seed of the
11028 // slice-return (`&[T]`) accessor discipline on the substrate — the four
11029 // peer `Vec`-carry axes ([`crate::Placement::clusters`],
11030 // [`crate::AplicacaoSpec::membros`], [`crate::AplicacaoSpec::contratos`],
11031 // [`crate::UpgradeFromEntry::instructions`]) still key off the raw field
11032 // access at the time of this seed, and inherit this pin family's
11033 // discipline as future compounding runs migrate their consumers. The
11034 // three pins below cover (1) the accessor's byte-equal projection
11035 // against the raw field access across the empty / singleton / cohort
11036 // fixtures the [`SupervisorSpec::validate`] partition-dispatch fans
11037 // between, (2) the [`SupervisorSpec::validate`] `SimpleOneForOne ↔
11038 // non-SimpleOneForOne` partition dispatch's paired `.is_empty()`
11039 // consumer routing through the accessor on both arms, and (3) the
11040 // per-child validate loop's traversal reading the same slice-view the
11041 // accessor projects. Peer of the sibling M2
11042 // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
11043 // two-consumer coherence pin on the per-`:supervisor`
11044 // sibling-restart-strategy `Copy`-composite-enum scalar axis, extended
11045 // onto the per-`:supervisor` static-child-list `Vec`-carry axis.
11046
11047 #[test]
11048 fn supervisor_spec_children_returns_children_slice_byte_equal_across_permutations() {
11049 // The canonical per-`:supervisor` static-child-list scalar-shape
11050 // pin: [`SupervisorSpec::children`] must return the `:supervisor
11051 // :children` typed `Vec<ChildSpec>` verbatim as a `&[ChildSpec]`
11052 // slice-view over the same backing buffer the raw
11053 // `self.children.as_slice()` field access borrows from, byte-
11054 // equal across every representative fixture in the accept-set —
11055 // the empty slice (the `SimpleOneForOne`-arm sentinel),
11056 // the singleton slice (the minimal non-`SimpleOneForOne` shape),
11057 // and a two-child cohort (a peer non-`SimpleOneForOne` shape
11058 // with the peer three restart-policy variants in play).
11059 //
11060 // Pins against a future silent detour that returned
11061 // `&Vec<ChildSpec>` (which would type-check but leak the
11062 // storage-side `Vec`'s grow/push/reserve surface no consumer of
11063 // the typed view reaches for), a fresh-allocated
11064 // `Vec<ChildSpec>` copy (which would type-check via a coercion
11065 // but silently break every downstream caller that relied on the
11066 // slice sharing the backing buffer's identity), or an
11067 // out-of-order or length-drifted projection (which would silently
11068 // split the per-child validate loop's traversal input from the
11069 // paired partition-dispatch `.is_empty()` probe's input).
11070 //
11071 // Peer of the sibling
11072 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
11073 // (eafb619) `Copy`-composite-enum byte-equal pin on the
11074 // per-`:supervisor` sibling-restart-strategy axis, extended onto
11075 // the per-`:supervisor` static-child-list `Vec`-carry axis.
11076 let fixtures: Vec<Vec<ChildSpec>> = vec![
11077 Vec::new(),
11078 vec![child("worker", "^0.1", RestartPolicy::Permanent)],
11079 vec![
11080 child("worker", "^0.1", RestartPolicy::Permanent),
11081 child("cache-server", "^0.1", RestartPolicy::Transient),
11082 ],
11083 vec![
11084 child("worker", "^0.1", RestartPolicy::Permanent),
11085 child("cache-server", "^0.1", RestartPolicy::Transient),
11086 child("scratch-job", "^0.1", RestartPolicy::Temporary),
11087 ],
11088 ];
11089 for children in fixtures {
11090 let s = SupervisorSpec {
11091 children: children.clone(),
11092 ..SupervisorSpec::default()
11093 };
11094 assert_eq!(
11095 s.children(),
11096 children.as_slice(),
11097 "SupervisorSpec::children must return :supervisor \
11098 :children verbatim (got {:?}, expected {:?})",
11099 s.children(),
11100 children.as_slice(),
11101 );
11102 assert_eq!(
11103 s.children(),
11104 s.children.as_slice(),
11105 "SupervisorSpec::children accessor and \
11106 .children.as_slice() field access must byte-equal — \
11107 the accessor is the substrate-primitive typed \
11108 dispatch every downstream static-child-list consumer \
11109 must route through",
11110 );
11111 assert_eq!(
11112 s.children().len(),
11113 s.children.len(),
11114 "SupervisorSpec::children().len() must byte-equal \
11115 self.children.len() — a length-drift would silently \
11116 split the paired partition-dispatch `.is_empty()` \
11117 probe input from the per-child validate loop's \
11118 traversal input",
11119 );
11120 }
11121 }
11122
11123 #[test]
11124 fn validate_reads_through_lifted_children_accessor() {
11125 // Three-consumer coherence pin: the [`SupervisorSpec::validate`]
11126 // `SimpleOneForOne`-arm `!self.children().is_empty()` refusal
11127 // probe (which must trip [`SupervisorError::SimpleOneForOneWithStaticChildren`]
11128 // when the accessor projects a non-empty slice under a
11129 // `SimpleOneForOne` estrategia), the peer non-`SimpleOneForOne`-arm
11130 // `self.children().is_empty()` refusal probe (which must trip
11131 // [`SupervisorError::NoChildren`] when the accessor projects the
11132 // empty slice under any peer estrategia), and the per-child
11133 // validate loop's `for child in self.children()` traversal
11134 // (which must reach every entry in the same order the accessor
11135 // projects) must all key off the lifted accessor, so any future
11136 // rebrand on the typed slot's reader shape lands at exactly one
11137 // place. Pins the three-site coherence by exercising each
11138 // production consumer end-to-end: (1) the
11139 // `SimpleOneForOneWithStaticChildren` refusal under a non-empty
11140 // slice + `SimpleOneForOne` estrategia, (2) the `NoChildren`
11141 // refusal under the empty slice + non-`SimpleOneForOne`
11142 // estrategia across every peer variant, and (3) the per-child
11143 // duplicate-detection surface fires on the second entry of a
11144 // two-child cohort that shares a `:caixa` name (which requires
11145 // the loop to reach both entries — a first-entry-only projection
11146 // would silently pass since the dedup HashSet has room for the
11147 // first insert).
11148 //
11149 // Peer of the sibling M2
11150 // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
11151 // two-consumer coherence pin on the per-`:supervisor`
11152 // sibling-restart-strategy axis, extended onto the
11153 // per-`:supervisor` static-child-list `Vec`-carry axis.
11154
11155 // (1) `SimpleOneForOne`-arm probe: a non-empty slice under a
11156 // `SimpleOneForOne` estrategia must trip
11157 // `SimpleOneForOneWithStaticChildren`.
11158 let s = SupervisorSpec {
11159 estrategia: RestartStrategy::SimpleOneForOne,
11160 children: vec![child("worker", "^0.1", RestartPolicy::Permanent)],
11161 ..SupervisorSpec::default()
11162 };
11163 assert_eq!(
11164 s.validate().unwrap_err(),
11165 SupervisorError::SimpleOneForOneWithStaticChildren,
11166 "SimpleOneForOne + non-empty children must trip \
11167 SimpleOneForOneWithStaticChildren — the accessor projects \
11168 a non-empty slice, and the SimpleOneForOne-arm refusal \
11169 probe reads through the lifted accessor",
11170 );
11171 assert!(
11172 !s.children().is_empty(),
11173 "the SimpleOneForOne-arm refusal input must be a non-empty \
11174 slice per the accessor's projection",
11175 );
11176
11177 // (2) Peer non-`SimpleOneForOne`-arm probe: the empty slice
11178 // under any peer estrategia must trip `NoChildren`.
11179 for estrategia in [
11180 RestartStrategy::OneForOne,
11181 RestartStrategy::OneForAll,
11182 RestartStrategy::RestForOne,
11183 ] {
11184 let s = SupervisorSpec {
11185 estrategia,
11186 children: Vec::new(),
11187 ..SupervisorSpec::default()
11188 };
11189 match s.validate().unwrap_err() {
11190 SupervisorError::NoChildren { estrategia: e } => {
11191 assert_eq!(
11192 e, estrategia,
11193 "NoChildren.estrategia must carry the author-\
11194 declared :supervisor :estrategia variant \
11195 verbatim (got {e:?}, expected {estrategia:?})",
11196 );
11197 }
11198 other => panic!(
11199 "expected NoChildren, got {other:?} for \
11200 estrategia={estrategia:?}"
11201 ),
11202 }
11203 assert!(
11204 s.children().is_empty(),
11205 "the non-SimpleOneForOne-arm refusal input must be the \
11206 empty slice per the accessor's projection",
11207 );
11208 }
11209
11210 // (3) Per-child validate loop: a two-child cohort that shares a
11211 // `:caixa` name must trip `DuplicateChildCaixa` — the loop must
11212 // reach both entries through the accessor.
11213 let s = SupervisorSpec {
11214 estrategia: RestartStrategy::OneForOne,
11215 children: vec![
11216 child("worker", "^0.1", RestartPolicy::Permanent),
11217 child("worker", "^0.2", RestartPolicy::Transient),
11218 ],
11219 ..SupervisorSpec::default()
11220 };
11221 match s.validate().unwrap_err() {
11222 SupervisorError::DuplicateChildCaixa { caixa } => {
11223 assert_eq!(
11224 caixa, "worker",
11225 "DuplicateChildCaixa.caixa must carry the shared \
11226 child `:caixa` name verbatim",
11227 );
11228 }
11229 other => panic!("expected DuplicateChildCaixa, got {other:?}"),
11230 }
11231 assert_eq!(
11232 s.children().len(),
11233 2,
11234 "the per-child validate loop's traversal input must be a \
11235 two-element slice per the accessor's projection",
11236 );
11237 }
11238
11239 // Shared helper for the M2 per-`:children` per-slot-gate ≡
11240 // `validate` equivalence pins: builds an `OneForOne`-estrategia
11241 // one-cohort spec whose peer `:estrategia`↔`:children.is_empty()`
11242 // partition, `:max-restarts` zero-floor/cap, and `:restart-window`
11243 // bracket all pass cleanly so the sole failing surface is the
11244 // per-child cascade [`SupervisorSpec::validate_children`] owns, and
11245 // pins the two-altitude equivalence on the paired probe.
11246 fn assert_validate_children_matches_gate(children: Vec<ChildSpec>, expected: &SupervisorError) {
11247 let s = SupervisorSpec {
11248 estrategia: RestartStrategy::OneForOne,
11249 children,
11250 ..SupervisorSpec::default()
11251 };
11252 let via_gate = s.validate_children().unwrap_err();
11253 let via_validate = s.validate().unwrap_err();
11254 assert_eq!(&via_gate, expected, "validate_children direct dispatch",);
11255 assert_eq!(&via_validate, expected, "validate() end-to-end dispatch",);
11256 assert_eq!(
11257 via_gate, via_validate,
11258 "per-slot gate ≡ validate() must discriminate the same \
11259 refusal shape",
11260 );
11261 }
11262
11263 #[test]
11264 fn validate_children_matches_gate_on_per_axis_refusal_shapes() {
11265 // Fail-before-pass-after equivalence pin on the M2
11266 // per-`:children` per-slot gate ≡ [`SupervisorSpec::validate`]
11267 // convergence — sibling of the M3 mesh-slot
11268 // `validate_membros_*` / `validate_contratos_*` /
11269 // `validate_entrada_*` per-slot-gate ≡ `validate` pins on the
11270 // peer per-entry axes. Sweeps four of the five refusal shapes
11271 // the per-slot gate owns: (1) `EmptyChildName` on an empty-
11272 // `:caixa` child, (2) `ChildCaixaInvalid` on a structurally
11273 // invalid `:caixa` DNS-1123 label, (3) `EmptyChildVersion` on
11274 // an empty-`:versao` child, (4) `DuplicateChildCaixa` on a
11275 // duplicate-`:caixa` fan-out. Companion pin
11276 // `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
11277 // covers `ChildVersaoInvalid` (whose parser-owned reason string
11278 // needs pattern-matching, not equality) and the clean-pass
11279 // canonical fixture; together the two pins guarantee the
11280 // per-slot gate and `validate` discriminate the same set on
11281 // every per-child-covered input.
11282 assert_validate_children_matches_gate(
11283 vec![child("", "^0.1", RestartPolicy::Permanent)],
11284 &SupervisorError::EmptyChildName,
11285 );
11286 assert_validate_children_matches_gate(
11287 vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
11288 &SupervisorError::ChildCaixaInvalid {
11289 caixa: "Worker".into(),
11290 reason: "contains uppercase character 'W' (K8s DNS-1123 label names are lowercase-only; use \"worker\")".into(),
11291 },
11292 );
11293 assert_validate_children_matches_gate(
11294 vec![child("worker", "", RestartPolicy::Permanent)],
11295 &SupervisorError::EmptyChildVersion {
11296 caixa: "worker".into(),
11297 },
11298 );
11299 assert_validate_children_matches_gate(
11300 vec![
11301 child("worker", "^0.1", RestartPolicy::Permanent),
11302 child("worker", "^0.2", RestartPolicy::Transient),
11303 ],
11304 &SupervisorError::DuplicateChildCaixa {
11305 caixa: "worker".into(),
11306 },
11307 );
11308 }
11309
11310 #[test]
11311 fn validate_children_matches_gate_on_versao_invalid_and_clean_pass() {
11312 // Second half of the two-altitude equivalence pin — covers the
11313 // one refusal shape whose reason string is parser-owned
11314 // (`ChildVersaoInvalid`, whose reason comes from the shared
11315 // [`crate::version::parse_requirement`] impl and may drift) and
11316 // the clean-pass canonical fixture. Sibling pin
11317 // `validate_children_matches_gate_on_per_axis_refusal_shapes`
11318 // covers the four equality-comparable refusal shapes.
11319 let s_bad_versao = SupervisorSpec {
11320 estrategia: RestartStrategy::OneForOne,
11321 children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
11322 ..SupervisorSpec::default()
11323 };
11324 let via_gate = s_bad_versao.validate_children().unwrap_err();
11325 let via_validate = s_bad_versao.validate().unwrap_err();
11326 match (&via_gate, &via_validate) {
11327 (
11328 SupervisorError::ChildVersaoInvalid {
11329 caixa: cg,
11330 versao: vg,
11331 ..
11332 },
11333 SupervisorError::ChildVersaoInvalid {
11334 caixa: cv,
11335 versao: vv,
11336 ..
11337 },
11338 ) => {
11339 assert_eq!(cg, "worker", "per-slot gate :caixa carrier");
11340 assert_eq!(vg, "not-a-req", "per-slot gate :versao carrier");
11341 assert_eq!(cv, "worker", "validate() :caixa carrier");
11342 assert_eq!(vv, "not-a-req", "validate() :versao carrier");
11343 }
11344 other => panic!("expected ChildVersaoInvalid on both altitudes, got {other:?}"),
11345 }
11346 assert_eq!(
11347 via_gate, via_validate,
11348 "per-slot gate ≡ validate() on ChildVersaoInvalid full envelope",
11349 );
11350
11351 let s_ok = SupervisorSpec {
11352 estrategia: RestartStrategy::OneForOne,
11353 children: vec![
11354 child("worker-a", "^0.1", RestartPolicy::Permanent),
11355 child("worker-b", "~0.2.3", RestartPolicy::Transient),
11356 child("collector", "*", RestartPolicy::Temporary),
11357 ],
11358 ..SupervisorSpec::default()
11359 };
11360 s_ok.validate_children()
11361 .expect("per-slot gate must accept the clean-pass fixture");
11362 s_ok.validate()
11363 .expect("validate() must accept the clean-pass fixture");
11364 }
11365
11366 #[test]
11367 fn validate_children_is_self_contained_on_children_slot() {
11368 // Self-containment pin: [`SupervisorSpec::validate_children`]
11369 // resolves the per-child cascade against `&self` alone, without
11370 // depending on the peer `:estrategia`/`:max-restarts`/
11371 // `:restart-window` gates having run first — same posture the M3
11372 // peer per-slot gates carry (`validate_membros`,
11373 // `validate_contratos`, `validate_entrada`, `validate_placement`,
11374 // routing through their own oracles rather than borrowing state
11375 // threaded down from `validate`). A future consumer that reaches
11376 // the per-slot gate directly on a spec whose peer slots would
11377 // fail `validate` still surfaces the per-child refusal, not the
11378 // peer refusal.
11379 //
11380 // Construct a spec whose `:max-restarts` is `0` (which would
11381 // trip [`SupervisorError::ZeroMaxRestarts`] at `validate` after
11382 // the partition-dispatch) and whose `:children` carries a
11383 // `DuplicateChildCaixa` shape: the per-slot gate called directly
11384 // must surface `DuplicateChildCaixa`, proving it does not depend
11385 // on the peer `:max-restarts` gate running first.
11386 let s = SupervisorSpec {
11387 estrategia: RestartStrategy::OneForOne,
11388 max_restarts: 0,
11389 restart_window: Some(Duration::from_secs(60)),
11390 children: vec![
11391 child("worker", "^0.1", RestartPolicy::Permanent),
11392 child("worker", "^0.2", RestartPolicy::Transient),
11393 ],
11394 };
11395 assert_eq!(
11396 s.validate_children().unwrap_err(),
11397 SupervisorError::DuplicateChildCaixa {
11398 caixa: "worker".into(),
11399 },
11400 "per-slot gate must resolve per-child refusal directly against \
11401 `&self` — a dependency on the peer `:max-restarts` gate \
11402 running first would surface ZeroMaxRestarts here instead",
11403 );
11404 // The peer gate is still the surface `validate` reaches — pin
11405 // the ordering to establish that `validate_children` truly runs
11406 // last in `validate`'s dispatch, so a direct call bypasses the
11407 // peer gates on any spec whose per-child cascade would fail.
11408 assert_eq!(
11409 s.validate().unwrap_err(),
11410 SupervisorError::ZeroMaxRestarts,
11411 "validate() must surface the peer `:max-restarts` gate before \
11412 reaching the per-child cascade — this pins the dispatch \
11413 ordering the per-slot gate's self-containment complements",
11414 );
11415 }
11416
11417 #[test]
11418 fn child_spec_restart_accessor_is_const_fn() {
11419 // The [`ChildSpec::restart`] per-`:children` restart-decision-
11420 // policy `Copy`-return scalar accessor is declared
11421 // `#[must_use] pub const fn` — matching the sibling M2
11422 // per-`:supervisor` [`SupervisorSpec::estrategia`] (pinned by
11423 // [`supervisor_spec_estrategia_accessor_is_const_fn`] below,
11424 // both converted in this commit), the sibling M2
11425 // per-`:supervisor` [`SupervisorSpec::max_restarts`] (b698ec0)
11426 // `Copy`-`u32` accessor already `pub const fn`, and the peer M3
11427 // mesh-slot per-`:entrada` [`crate::Entrada::port`] (bafa004) /
11428 // per-`:placement` [`crate::Placement::estrategia`] (bafa004)
11429 // `Copy`-return `pub const fn` scalar accessors on the sibling
11430 // M3 surface. Pin the `const`-eval posture here so a future
11431 // accidental downgrade to non-`const` (an added runtime helper
11432 // reachable only from a non-`const` context, an
11433 // `Option<RestartPolicy>`-shape migration on the per-child
11434 // restart-decision axis once heterogeneous per-cluster
11435 // restart-policy overlays land that would silently drop the
11436 // `const` qualifier, a manual hand-rolled shadow) trips at
11437 // caixa-core build time rather than surfacing as a downstream
11438 // `const`-context regression far from the declaration.
11439 //
11440 // Same shape as the sibling M3
11441 // [`crate::aplicacao::tests::placement_estrategia_accessor_is_const_fn`]
11442 // and [`crate::aplicacao::tests::entrada_port_accessor_is_const_fn`]
11443 // (bafa004) pins on the peer M3 mesh-slot `Copy`-return scalar
11444 // accessor axis — the load-bearing witness lives in the
11445 // module-scope `const fn` wrapper `restart_via_const_fn` below:
11446 // a body that calls [`ChildSpec::restart`] under a `const fn`
11447 // signature is well-formed only when the callee is itself
11448 // `const fn`, so any future accidental downgrade of
11449 // [`ChildSpec::restart`] to non-`const` fails at caixa-core
11450 // build time (const-eval E0015 `cannot call non-const method`),
11451 // strictly stronger than a runtime `assert!(CONST)` and
11452 // side-stepping the destructor-in-const restriction that
11453 // blocks direct `const _: RestartPolicy = FIXTURE.restart()`
11454 // items on `ChildSpec`'s `String` carriers.
11455 //
11456 // The runtime body sweeps every closed-set [`RestartPolicy`]
11457 // arm and asserts the wrapped and direct dispatches agree.
11458 const fn restart_via_const_fn(c: &ChildSpec) -> RestartPolicy {
11459 c.restart()
11460 }
11461 for restart in [
11462 RestartPolicy::Permanent,
11463 RestartPolicy::Transient,
11464 RestartPolicy::Temporary,
11465 ] {
11466 let c = ChildSpec {
11467 caixa: "worker".into(),
11468 versao: "^0.1".into(),
11469 restart,
11470 };
11471 assert_eq!(
11472 restart_via_const_fn(&c),
11473 c.restart(),
11474 "const-fn-wrapped and direct dispatch on \
11475 ChildSpec::restart must agree for {restart:?}",
11476 );
11477 assert_eq!(
11478 c.restart(),
11479 restart,
11480 "ChildSpec::restart must return the storage-side \
11481 RestartPolicy verbatim for {restart:?} (a violation \
11482 means the accessor stopped being a raw field-return \
11483 copy)",
11484 );
11485 }
11486 }
11487
11488 #[test]
11489 fn supervisor_spec_estrategia_accessor_is_const_fn() {
11490 // The [`SupervisorSpec::estrategia`] per-`:supervisor`
11491 // sibling-restart-strategy `Copy`-return scalar accessor is
11492 // declared `#[must_use] pub const fn` — matching the sibling M2
11493 // per-`:children` [`ChildSpec::restart`] (pinned by
11494 // [`child_spec_restart_accessor_is_const_fn`] above, both
11495 // converted in this commit), the sibling M2 per-`:supervisor`
11496 // [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32`
11497 // accessor already `pub const fn`, and mirroring the peer M3
11498 // mesh-slot per-`:placement`
11499 // [`crate::Placement::estrategia`] (bafa004) `Copy`-return
11500 // `pub const fn` scalar accessor whose method-name discipline
11501 // the [`SupervisorSpec::estrategia`] method was authored to
11502 // match. Pin the `const`-eval posture here so a future
11503 // accidental downgrade to non-`const` (an added runtime helper
11504 // reachable only from a non-`const` context, an
11505 // `Option<RestartStrategy>`-shape migration once the substrate
11506 // grows per-cluster strategy overlays that would silently drop
11507 // the `const` qualifier, a manual hand-rolled shadow) trips at
11508 // caixa-core build time rather than surfacing as a downstream
11509 // `const`-context regression far from the declaration.
11510 //
11511 // Same shape as the sibling
11512 // [`child_spec_restart_accessor_is_const_fn`] pin above — the
11513 // load-bearing witness lives in the module-scope `const fn`
11514 // wrapper `estrategia_via_const_fn` below: a body that calls
11515 // [`SupervisorSpec::estrategia`] under a `const fn` signature
11516 // is well-formed only when the callee is itself `const fn`,
11517 // side-stepping the destructor-in-const restriction that would
11518 // otherwise block a direct
11519 // `const _: RestartStrategy = FIXTURE.estrategia()` item on
11520 // `SupervisorSpec`'s `Vec<ChildSpec>` / `Option<Duration>`
11521 // carriers.
11522 //
11523 // The runtime body sweeps every closed-set [`RestartStrategy`]
11524 // arm via [`RestartStrategy::ALL`] and asserts the wrapped and
11525 // direct dispatches agree.
11526 const fn estrategia_via_const_fn(s: &SupervisorSpec) -> RestartStrategy {
11527 s.estrategia()
11528 }
11529 for &estrategia in RestartStrategy::ALL {
11530 let s = SupervisorSpec {
11531 estrategia,
11532 max_restarts: 5,
11533 restart_window: Some(Duration::from_secs(60)),
11534 children: Vec::new(),
11535 };
11536 assert_eq!(
11537 estrategia_via_const_fn(&s),
11538 s.estrategia(),
11539 "const-fn-wrapped and direct dispatch on \
11540 SupervisorSpec::estrategia must agree for {estrategia:?}",
11541 );
11542 assert_eq!(
11543 s.estrategia(),
11544 estrategia,
11545 "SupervisorSpec::estrategia must return the storage-side \
11546 RestartStrategy verbatim for {estrategia:?} (a violation \
11547 means the accessor stopped being a raw field-return \
11548 copy)",
11549 );
11550 }
11551 }
11552
11553 // Per-variant equivalence pins for the [`supervisor_caixa_only_ctors!`]
11554 // macro definition (see the paired doc-block above the macro
11555 // definition) — every generated `<ctor>(caixa: &str) -> Self`
11556 // constructor folds the uniform `Self::<Variant> { caixa:
11557 // caixa.to_string() }` one-field struct-literal onto one substrate
11558 // primitive. The three per-variant equivalence pins below
11559 // (fail-before-pass-after by construction — a byte-mismatched macro
11560 // arm would trip its equivalence pin first) lock each generated
11561 // constructor to its struct-literal peer under `PartialEq`, so
11562 // every wire-up in [`SupervisorSpec::validate_children`] and
11563 // [`validate_no_self_supervision`] on that variant produces a
11564 // byte-equal `SupervisorError` to the pre-lift open-coded
11565 // struct-literal. The cross-axis pin that follows (non-default
11566 // caixa name) routes the sole constructor input axis through
11567 // `.to_string()`, so the fold does not silently collapse onto a
11568 // fixed name.
11569 //
11570 // Peer of the sibling `<slot>_ctor_matches_tuple_literal_wrap` /
11571 // `<slot>_violation_ctor_matches_struct_literal_wrap` /
11572 // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
11573 // `missing_entry_ctor_matches_struct_literal_wrap` /
11574 // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
11575 // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
11576 // `contrato_missing_target_ctor_matches_struct_literal_wrap` /
11577 // `<variant>_ctor_matches_struct_literal_wrap` equivalence pins
11578 // on the six sibling ctor families the recent trajectory closed
11579 // on the peer `LayoutError` / `AplicacaoError` envelopes.
11580
11581 #[test]
11582 fn empty_child_version_ctor_matches_struct_literal_wrap() {
11583 assert_eq!(
11584 SupervisorError::empty_child_version("worker"),
11585 SupervisorError::EmptyChildVersion {
11586 caixa: "worker".to_string(),
11587 },
11588 "generated empty_child_version ctor must produce byte-equal \
11589 SupervisorError to the open-coded struct-literal wrap on the \
11590 same &str fixture",
11591 );
11592 }
11593
11594 #[test]
11595 fn duplicate_child_caixa_ctor_matches_struct_literal_wrap() {
11596 assert_eq!(
11597 SupervisorError::duplicate_child_caixa("worker"),
11598 SupervisorError::DuplicateChildCaixa {
11599 caixa: "worker".to_string(),
11600 },
11601 "generated duplicate_child_caixa ctor must produce byte-equal \
11602 SupervisorError to the open-coded struct-literal wrap on the \
11603 same &str fixture",
11604 );
11605 }
11606
11607 #[test]
11608 fn child_supervises_self_ctor_matches_struct_literal_wrap() {
11609 assert_eq!(
11610 SupervisorError::child_supervises_self("orquestra"),
11611 SupervisorError::ChildSupervisesSelf {
11612 caixa: "orquestra".to_string(),
11613 },
11614 "generated child_supervises_self ctor must produce byte-equal \
11615 SupervisorError to the open-coded struct-literal wrap on the \
11616 same &str fixture",
11617 );
11618 }
11619
11620 // Per-variant equivalence pins for the two lifted
11621 // [`SupervisorError::child_caixa_invalid`] /
11622 // [`SupervisorError::child_versao_invalid`] inherent constructors
11623 // (fail-before-pass-after by construction — a byte-mismatched ctor body
11624 // would trip its equivalence pin first). Each pins the ctor output to
11625 // its pre-lift struct-literal peer under `PartialEq`, so every wire-up
11626 // in [`SupervisorSpec::validate_children`] on the two variants
11627 // produces a byte-equal `SupervisorError` to the pre-lift open-coded
11628 // struct-literal on the same scalar fixtures. Peers of the sibling
11629 // `membro_caixa_invalid_ctor_matches_struct_literal_wrap` /
11630 // `entrada_para_invalid_ctor_matches_struct_literal_wrap` / … pins on
11631 // the peer `AplicacaoError` envelope's
11632 // [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold.
11633
11634 #[test]
11635 fn child_caixa_invalid_ctor_matches_struct_literal_wrap() {
11636 let caixa = "Worker";
11637 let reason = "sample reason text";
11638 assert_eq!(
11639 SupervisorError::child_caixa_invalid(caixa, reason),
11640 SupervisorError::ChildCaixaInvalid {
11641 caixa: caixa.to_string(),
11642 reason: reason.to_string(),
11643 },
11644 "lifted child_caixa_invalid ctor must produce byte-equal \
11645 SupervisorError to the open-coded struct-literal wrap on the \
11646 same (&str, reason) fixture",
11647 );
11648 }
11649
11650 #[test]
11651 fn child_versao_invalid_ctor_matches_struct_literal_wrap() {
11652 let caixa = "worker";
11653 let versao = "not-a-req";
11654 let reason = "sample reason text";
11655 assert_eq!(
11656 SupervisorError::child_versao_invalid(caixa, versao, reason),
11657 SupervisorError::ChildVersaoInvalid {
11658 caixa: caixa.to_string(),
11659 versao: versao.to_string(),
11660 reason: reason.to_string(),
11661 },
11662 "lifted child_versao_invalid ctor must produce byte-equal \
11663 SupervisorError to the open-coded struct-literal wrap on the \
11664 same (&str, &str, reason) fixture",
11665 );
11666 }
11667
11668 #[test]
11669 fn supervisor_child_reason_ctors_route_reason_through_into_uniformly() {
11670 // Cross-axis pin: sweep the two lifted `{ …, reason }` ctors
11671 // against a `&str`-literal vs. `format!(…)` reason input to pin
11672 // both constructors accept the `impl Into<String>` bound
11673 // uniformly, so neither wire-up site drifts under a per-arm
11674 // wrapper transformation on the caller-side `reason` axis. Peer
11675 // of the sibling
11676 // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
11677 // sweep on the peer `AplicacaoError` envelope.
11678 let via_literal = "literal reason text";
11679 let via_format = format!("{} reason text", "literal");
11680 assert_eq!(
11681 SupervisorError::child_caixa_invalid("Worker", via_literal),
11682 SupervisorError::child_caixa_invalid("Worker", via_format.clone()),
11683 );
11684 assert_eq!(
11685 SupervisorError::child_versao_invalid("worker", "not-a-req", via_literal),
11686 SupervisorError::child_versao_invalid("worker", "not-a-req", via_format),
11687 );
11688 }
11689
11690 #[test]
11691 fn supervisor_caixa_only_ctors_route_caixa_through_to_string() {
11692 // Cross-axis pin: sweep the sole constructor input axis (`caixa:
11693 // &str`) through a non-default fixture name against every
11694 // generated arm in the [`supervisor_caixa_only_ctors!`] macro,
11695 // so any wrapper-side lowercase / trim / truncate / re-order on
11696 // the `caixa.to_string()` sole-field construction surfaces
11697 // here rather than at a downstream diagnostic-shape mismatch.
11698 // Peer of the sibling `nome_only_ctor_routes_caixa_through_
11699 // nome_accessor` / `entrada_host_invalid_ctor_routes_host_
11700 // through_to_string` / `contrato_target_ctors_route_edge_
11701 // triple_through_verbatim` / `contrato_empty_pair_ctors_
11702 // route_edge_pair_through_verbatim` cross-axis routing pins on
11703 // the peer `LayoutError` / `AplicacaoError` envelopes; extended
11704 // here onto the `SupervisorError` `{ caixa: String }` envelope
11705 // so every substrate-primitive ctor family in caixa-core
11706 // guarantees the sole-field construction routes the caller's
11707 // `&str` through `.to_string()` verbatim.
11708 let name = "cache-v2";
11709 assert_eq!(
11710 SupervisorError::empty_child_version(name),
11711 SupervisorError::EmptyChildVersion {
11712 caixa: name.to_string(),
11713 },
11714 );
11715 assert_eq!(
11716 SupervisorError::duplicate_child_caixa(name),
11717 SupervisorError::DuplicateChildCaixa {
11718 caixa: name.to_string(),
11719 },
11720 );
11721 assert_eq!(
11722 SupervisorError::child_supervises_self(name),
11723 SupervisorError::ChildSupervisesSelf {
11724 caixa: name.to_string(),
11725 },
11726 );
11727 }
11728
11729 // ── supervisor_scalar_ctors! per-variant + cross-axis pins ──────────────
11730 //
11731 // Per-variant byte-equality pins guaranteeing every generated ctor arm in
11732 // the [`supervisor_scalar_ctors!`] macro produces a `SupervisorError`
11733 // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
11734 // one-line struct-literal on the same `Copy`-`RestartStrategy | u32 |
11735 // Duration` fixture, plus one cross-axis sweep that routes each per-variant
11736 // `<field>: <ty>` scalar through the sole `$field:ident: $ty:ty` axis the
11737 // macro exposes so any wrapper-side truncation / re-order / silent `.into()`
11738 // / silent constant-substitution on any one variant surfaces here rather
11739 // than at a downstream per-`:supervisor` diagnostic-shape drift. Peer of the
11740 // sibling per-variant pins on `aplicacao_policy_scalar_ctors!` (7ef425e,
11741 // the 8-variant `AplicacaoError` `{ <field>: Duration | u32 }` fold on the
11742 // per-`:politicas` per-axis cap / canonical-form arms), plus the sibling
11743 // `supervisor_caixa_only_ctors!` (db09650), `SupervisorError::
11744 // {child_caixa_invalid,child_versao_invalid}` (d2ef2ec), and the peer
11745 // `DepError` / `AplicacaoError` / `LayoutError` / `LimitsError` /
11746 // `BehaviorError` / `UpgradeError` per-envelope ctor-macro pins.
11747 #[test]
11748 fn no_children_ctor_matches_struct_literal_wrap() {
11749 let estrategia = RestartStrategy::OneForAll;
11750 assert_eq!(
11751 SupervisorError::no_children(estrategia),
11752 SupervisorError::NoChildren { estrategia },
11753 "generated no_children ctor must produce byte-equal \
11754 `SupervisorError::NoChildren` to the pre-lift struct-literal wrap \
11755 on the same `Copy`-`RestartStrategy` fixture",
11756 );
11757 }
11758
11759 #[test]
11760 fn max_restarts_exceeds_cap_ctor_matches_struct_literal_wrap() {
11761 let max_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 1;
11762 assert_eq!(
11763 SupervisorError::max_restarts_exceeds_cap(max_restarts),
11764 SupervisorError::MaxRestartsExceedsCap { max_restarts },
11765 "generated max_restarts_exceeds_cap ctor must produce byte-equal \
11766 `SupervisorError::MaxRestartsExceedsCap` to the pre-lift \
11767 struct-literal wrap on the same `Copy`-`u32` fixture",
11768 );
11769 }
11770
11771 #[test]
11772 fn restart_window_not_canonical_ctor_matches_struct_literal_wrap() {
11773 let window = Duration::from_micros(1_500);
11774 assert_eq!(
11775 SupervisorError::restart_window_not_canonical(window),
11776 SupervisorError::RestartWindowNotCanonical { window },
11777 "generated restart_window_not_canonical ctor must produce \
11778 byte-equal `SupervisorError::RestartWindowNotCanonical` to the \
11779 pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
11780 );
11781 }
11782
11783 #[test]
11784 fn restart_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
11785 let window = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
11786 assert_eq!(
11787 SupervisorError::restart_window_exceeds_cap(window),
11788 SupervisorError::RestartWindowExceedsCap { window },
11789 "generated restart_window_exceeds_cap ctor must produce \
11790 byte-equal `SupervisorError::RestartWindowExceedsCap` to the \
11791 pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
11792 );
11793 }
11794
11795 #[test]
11796 fn supervisor_scalar_ctors_route_field_through_copy_uniformly() {
11797 // Cross-axis routing pin: sweep each generated `<field>: <ty>`
11798 // constructor input axis through a non-default `Copy` fixture against
11799 // every arm in the [`supervisor_scalar_ctors!`] macro, so any wrapper-
11800 // side silent `.into()` / silent constant-substitution / silent field
11801 // re-name away from the canonical `estrategia | max_restarts | window`
11802 // axes on any one variant, or a `RestartStrategy | u32 | Duration`
11803 // axis silently rerouted through some other `Copy` coercion, surfaces
11804 // here rather than at a downstream per-`:supervisor` diagnostic-shape
11805 // drift. Peer of the sibling
11806 // `aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly`
11807 // (7ef425e) cross-axis routing pin on the peer `AplicacaoError`
11808 // envelope's per-`:politicas` per-axis ctor family, extended here onto
11809 // the last M2 per-`:supervisor` `Copy`-scalar `SupervisorError`
11810 // variant family folded onto a substrate primitive.
11811 //
11812 // Fixtures picked out of each variant's accept-set boundary rather
11813 // than the default value so a silent constant-substitution to a per-
11814 // variant sentinel surfaces here on the structural-equality assertion.
11815 // The `RestartStrategy` fixture picks `RestForOne` (a non-default arm
11816 // that isn't the `OneForOne` [`SUPERVISOR_ESTRATEGIA_DEFAULT`] and
11817 // isn't the `SimpleOneForOne` arm the sibling
11818 // `SimpleOneForOneWithStaticChildren` unit variant intercepts). The
11819 // `max_restarts` fixture picks an above-cap magnitude the cap arm
11820 // rejects; the two `Duration` fixtures pick the sub-millisecond and
11821 // above-cap ends of the `:restart-window` canonical-form + cap
11822 // bracket respectively.
11823 let estrategia = RestartStrategy::RestForOne;
11824 let above_cap_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 137;
11825 let sub_ms = Duration::from_micros(1_500);
11826 let above_hour = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
11827 assert_eq!(
11828 SupervisorError::no_children(estrategia),
11829 SupervisorError::NoChildren { estrategia },
11830 );
11831 assert_eq!(
11832 SupervisorError::max_restarts_exceeds_cap(above_cap_restarts),
11833 SupervisorError::MaxRestartsExceedsCap {
11834 max_restarts: above_cap_restarts,
11835 },
11836 );
11837 assert_eq!(
11838 SupervisorError::restart_window_not_canonical(sub_ms),
11839 SupervisorError::RestartWindowNotCanonical { window: sub_ms },
11840 );
11841 assert_eq!(
11842 SupervisorError::restart_window_exceeds_cap(above_hour),
11843 SupervisorError::RestartWindowExceedsCap { window: above_hour },
11844 );
11845 }
11846
11847 #[test]
11848 fn supervisor_scalar_ctors_are_const_zero_runtime_work() {
11849 // Const-eval pin: the [`supervisor_scalar_ctors!`] macro spells every
11850 // generated ctor `const fn` so a caller can pin a `SupervisorError`
11851 // at compile time — the same zero-runtime-work property the pre-lift
11852 // `|<slot>| SupervisorError::<Variant> { <slot> }` closure carried on
11853 // its `Copy`-pass-through construction path (no `.to_string()` /
11854 // `.into()` allocation, no branching). If any future edit silently
11855 // drops the `const` qualifier from the macro body the per-arm `const`
11856 // bindings below fail to compile, which surfaces the regression at
11857 // the substrate-primitive definition rather than at some downstream
11858 // consumer that had come to rely on the `const`-constructibility.
11859 // Peer of the sibling
11860 // `aplicacao_policy_scalar_ctors_are_const_zero_runtime_work`
11861 // (7ef425e) const-eval pin on the peer `AplicacaoError` envelope's
11862 // per-`:politicas` per-axis ctor family.
11863 const NO_CHILDREN: SupervisorError =
11864 SupervisorError::no_children(RestartStrategy::OneForAll);
11865 const MAX_RESTARTS_CAP: SupervisorError = SupervisorError::max_restarts_exceeds_cap(1_337);
11866 const WINDOW_NC: SupervisorError =
11867 SupervisorError::restart_window_not_canonical(Duration::from_micros(1));
11868 const WINDOW_CAP: SupervisorError =
11869 SupervisorError::restart_window_exceeds_cap(Duration::from_secs(3_601));
11870 assert!(matches!(NO_CHILDREN, SupervisorError::NoChildren { .. }));
11871 assert!(matches!(
11872 MAX_RESTARTS_CAP,
11873 SupervisorError::MaxRestartsExceedsCap { .. }
11874 ));
11875 assert!(matches!(
11876 WINDOW_NC,
11877 SupervisorError::RestartWindowNotCanonical { .. }
11878 ));
11879 assert!(matches!(
11880 WINDOW_CAP,
11881 SupervisorError::RestartWindowExceedsCap { .. }
11882 ));
11883 }
11884}