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/// Trait-idiomatic *owned-input, [`std::borrow::Cow<'static, str>`]
1721/// output* forward projection on the M2 OTP-shape per-child-restart
1722/// [`RestartPolicy`] closed-set typed enum — extends the substrate-
1723/// wide [`std::borrow::Cow<'static, str>`] forward-projection family
1724/// opened on [`crate::CaixaKind`] (99c1735 owned-input, d45c409
1725/// borrowed-input) and first extended off it onto the sibling M2
1726/// OTP-shape sibling-restart [`RestartStrategy`] (7dd28b3 owned-input,
1727/// 9b3e4b3 borrowed-input) onto the second (and second-of-two-in-M2)
1728/// M2 OTP-shape closed-set fieldless typed enum peer on the caixa
1729/// surface (`:children :restart`). Routes byte-for-byte through the
1730/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
1731/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
1732/// that binds a [`RestartPolicy`] through the trait-idiomatic
1733/// [`std::borrow::Cow<'static, str>`] axis — a future
1734/// `axum::response::IntoResponse` composer whose per-policy
1735/// diagnostic-body typing rules out the sibling [`AsRef<str>`]
1736/// borrowed return, a future M4 admission-webhook rejection body
1737/// that composes the accepted-policy enumeration through the same
1738/// `RestartPolicy::ALL.iter().map(Cow::from)` shape [`crate::CaixaKind`]
1739/// and [`RestartStrategy`] already route through, a generic `<T: for<'a>
1740/// Into<std::borrow::Cow<'static, str>>>`-bound structured-log
1741/// emitter on a per-child-policy diagnostic column — reaches the same
1742/// three-arm lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`]
1743/// / [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1744/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1745/// paired [`std::fmt::Display`], [`AsRef<str>`],
1746/// [`RestartPolicy::as_str`], and the four
1747/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
1748/// forward-projection corners already return.
1749///
1750/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
1751/// [`std::borrow::Cow::Owned`] — the substrate-primitive
1752/// [`RestartPolicy::as_str`] accessor's return carries the `&'static
1753/// str` lifetime by construction (each `match` arm resolves to a
1754/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const &str`
1755/// with static lifetime), so the zero-alloc borrowed arm is the
1756/// type-correct projection with no runtime allocation.
1757///
1758/// Rust's standard library carries no blanket `impl<T: AsRef<str>>
1759/// From<T> for Cow<'static, str>` (nor an `impl<T: fmt::Display>
1760/// From<T> for Cow<'static, str>`), so the paired sibling
1761/// [`From<RestartPolicy> for &'static str`] (9fb37d0),
1762/// [`From<RestartPolicy> for String`] (7851725), [`AsRef<str>`], and
1763/// [`std::fmt::Display`] surfaces do not implicitly extend to a
1764/// [`Cow<'static, str>`]-bound call site — every such site is forced
1765/// through a `Cow::Borrowed(policy.as_str())` /
1766/// `Cow::Owned(policy.to_string())` open-code whose type bounds have
1767/// no compile-time link back to the substrate primitive until this
1768/// lift.
1769///
1770/// Second peer to extend the substrate-wide trait-idiomatic
1771/// [`std::borrow::Cow<'static, str>`] forward-projection axis off the
1772/// top-level [`crate::CaixaKind`] enum (99c1735 owned-input, d45c409
1773/// borrowed-input) onto the wider substrate — closes the M2 OTP-shape
1774/// tier of the campaign (both sibling peers, `RestartStrategy` and
1775/// `RestartPolicy`, now carry the owned-input Cow<'static, str>
1776/// forward projection) so the remaining eleven peers
1777/// (`PlacementStrategy`, `RateLimitUnit`, `DepList`, `CaixaDialeto`,
1778/// and the outside-`caixa-core` peers `WitShape`, `PathShapeViolation`,
1779/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
1780/// `FerriteRuntime`) are the future targets. Every future arm addition
1781/// (an OTP-`intrinsic` fourth restart policy the ABSORPTION-ROADMAP
1782/// might reach for once the three canonical OTP restart policies stop
1783/// covering the substrate's discovered load-shape) grows the
1784/// Cow<'static, str> axis by construction through one caixa-core edit
1785/// on [`RestartPolicy::as_str`] — rather than a coordinated rewrite
1786/// across every future Cow<'static, str>-bound consumer site.
1787///
1788/// Pinned load-bearing by
1789/// [`tests::restart_policy_from_into_static_cow_str_routes_through_as_str_accessor`]
1790/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
1791/// against [`RestartPolicy::as_str`] across the three-arm
1792/// [`RestartPolicy::ALL`]) and
1793/// [`tests::restart_policy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
1794/// (cross-axis partition pin against the paired [`From<RestartPolicy>
1795/// for &'static str`], [`From<RestartPolicy> for String`], and
1796/// [`ToString`]-through-[`std::fmt::Display`] axes, plus a
1797/// `.iter().copied().map(Cow::from)` pipe witness over
1798/// [`RestartPolicy::ALL`] that materializes the three-arm accept-set
1799/// through the [`Cow<'static, str>`] axis alone and pins the
1800/// zero-alloc discipline on every element).
1801impl From<RestartPolicy> for std::borrow::Cow<'static, str> {
1802 fn from(policy: RestartPolicy) -> std::borrow::Cow<'static, str> {
1803 std::borrow::Cow::Borrowed(policy.as_str())
1804 }
1805}
1806
1807// Fleet-wide dispatcher-catalog registrations for caixa's OTP
1808// supervisor surface — two more typed shadows over Erlang/OTP
1809// primitives the substrate now mechanically tracks (see
1810// theory/UNIFIED-COMPUTING-MODEL.md §VI for the roadmap +
1811// theory/TYPED-ABSORPTION.md for the absorption arc).
1812gen_platform::register_dispatcher!("caixa.restart-strategy", RestartStrategy);
1813gen_platform::register_dispatcher!("caixa.restart-policy", RestartPolicy);
1814
1815/// One child entry in the supervisor's `:children` list.
1816///
1817/// Every child references another caixa by `:caixa <nome>` + version
1818/// constraint. The supervisor materializes one ComputeUnit per entry.
1819#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1820#[serde(rename_all = "camelCase")]
1821pub struct ChildSpec {
1822 /// The child caixa's `:nome`. Must resolve via the same dependency
1823 /// resolution path as `:deps` (caixa-resolver).
1824 pub caixa: String,
1825
1826 /// Semver constraint (`"^0.1"`, `"~0.1.2"`, etc.) — same shape as
1827 /// [`crate::dep::Dep::versao`].
1828 pub versao: String,
1829
1830 /// Restart policy — an author-omitted slot degrades onto the
1831 /// substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`]
1832 /// (`permanent`, the Erlang/OTP worker-child default) through the
1833 /// [`Default for RestartPolicy`] impl this `#[serde(default)]` routes
1834 /// to.
1835 #[serde(default)]
1836 pub restart: RestartPolicy,
1837}
1838
1839impl ChildSpec {
1840 /// Substrate-canonical per-`:children` child-caixa `:nome` scalar
1841 /// accessor every consumer that reads the OTP-shape supervised
1842 /// child's identity keys off — returns the author-declared
1843 /// `:children :caixa` byte-string verbatim as a `&str`, borrowed
1844 /// from the typed slot's own [`String`] storage.
1845 ///
1846 /// The `:children :caixa` slot carries the DNS-1123 label — the
1847 /// child caixa's `:nome` — that every emitted cluster artifact
1848 /// derives its `metadata.name` from verbatim: the rendered
1849 /// `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name` per child, the
1850 /// [`crate::LABEL_PROGRAM`] label value on every child's pod
1851 /// identity, and the per-child K8s Service `metadata.name` the
1852 /// future wasm-operator (M3) provisions for inter-child supervision-
1853 /// tree wiring. Every downstream consumer that fans on the child's
1854 /// caixa-name keys off this scalar (the [`SupervisorSpec::validate`]
1855 /// per-child DNS-1123 gate at
1856 /// `require_valid_dns_1123_label(child.nome(), …)`, the per-child
1857 /// duplicate-detection [`crate::render::insert_first_seen`] key, the
1858 /// [`validate_no_self_supervision`] cross-slot equality check
1859 /// against the parent's `:nome`, every `SupervisorError` variant
1860 /// carrying the offending child caixa verbatim for `feira lint`
1861 /// rendering, the future wasm-operator's hierarchical reconciliation
1862 /// scheduler's per-child ComputeUnit-name projection, the future M4
1863 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1864 /// admission webhook).
1865 ///
1866 /// Prior to this lift the `.caixa` byte-string was accessed inline
1867 /// at seven sites in `supervisor.rs` — the DNS-1123 gate's
1868 /// `&child.caixa`, the four `SupervisorError::{ChildCaixaInvalid,
1869 /// EmptyChildVersion, ChildVersaoInvalid, DuplicateChildCaixa}`
1870 /// carriers' `child.caixa.clone()`, the dedup key's
1871 /// `child.caixa.as_str()`, and the [`validate_no_self_supervision`]
1872 /// `child.caixa == parent_nome` cross-slot check — seven open-coded
1873 /// field-accesses that expressed no compile-time link back to the
1874 /// typed slot. A future extension of the `:children :caixa` axis to
1875 /// a richer author surface (a per-cluster alias table the operator
1876 /// pins through a future `:placement`-scoped slot on the supervisor
1877 /// tree, a namespace-qualified rewrite the M4 CR materializer
1878 /// applies per-CR, a per-child overlay from the future `:children
1879 /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
1880 /// acknowledges) would have had to be threaded through every
1881 /// open-coded copy in lockstep or one consumer would silently
1882 /// disagree with the peers on which caixa a given child resolves to
1883 /// — a child-set lookup that treated the name as `"cart-worker"`
1884 /// while the peer duplicate-detector treated it as
1885 /// `"tenant-a/cart-worker"` would silently split the
1886 /// `DuplicateChildCaixa` membership-lookup diagnostic from the
1887 /// self-supervision detector's parent-equality check, a two-consumer
1888 /// split at the validator far from the source `caixa.lisp` with no
1889 /// field naming the identity-drift root cause. Lifting the resolution
1890 /// rule to a typed method on the substrate primitive means every
1891 /// downstream consumer of the Supervisor's per-`:children` identity
1892 /// surface reaches for exactly one typed dispatch — the resolver's
1893 /// accept-set migrates as a unit on any future axis addition.
1894 ///
1895 /// Sibling of the peer per-`:membros` [`crate::Membro::nome`]
1896 /// (4a32abf) member-caixa `:nome` scalar accessor on the M3
1897 /// mesh-slot surface — same "one typed dispatch on the substrate
1898 /// primitive, thin projections at each consumer" discipline extended
1899 /// onto the M2 supervisor-tree per-`:children` child-identity axis.
1900 /// The two typed axes (`Membro::nome` on the M3 Aplicacao side,
1901 /// `ChildSpec::nome` on the M2 Supervisor side) now share one
1902 /// accessor discipline for the shared substrate concept "another
1903 /// caixa referenced by `:nome`". Peer of the second M2 slot scalar
1904 /// accessor [`crate::UpgradeFromEntry::prior_versao`] (75d27a8) on
1905 /// the sibling per-`:upgrade-from :from` OTP-appup axis — the M2
1906 /// slot family's typed-accessor discipline now spans both the
1907 /// upgrade axis (`:upgrade-from`) and the supervision axis
1908 /// (`:children`), matching the closed M3 mesh-slot accessor family's
1909 /// shape. Named `nome()` to match the tatara-lisp author-surface
1910 /// term the field's docstring already reaches for ("The child
1911 /// caixa's `:nome`") and the peer [`crate::Membro::nome`] /
1912 /// [`crate::Caixa::nome`] / [`crate::dep::Dep::nome`] field-name
1913 /// discipline the substrate already carries — the accessor's name
1914 /// maps directly onto the canonical caixa-identity vocabulary rather
1915 /// than shadowing the field's storage-side `caixa` label.
1916 #[must_use]
1917 pub const fn nome(&self) -> &str {
1918 self.caixa.as_str()
1919 }
1920
1921 /// Substrate-canonical per-`:children` child-caixa `:versao` semver-
1922 /// requirement scalar accessor every consumer that reads the OTP-shape
1923 /// supervised child's version pin keys off — returns the author-declared
1924 /// `:children :versao` byte-string verbatim as a `&str`, borrowed from
1925 /// the typed slot's own [`String`] storage.
1926 ///
1927 /// The `:children :versao` slot carries the Cargo-shaped semver
1928 /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that pins
1929 /// which release of the supervised child caixa the OTP-shape supervisor
1930 /// tree materializes against — the same requirement grammar the peer
1931 /// `:deps :versao` / `:membros :versao` axes carry, resolved through the
1932 /// shared [`crate::render::require_valid_versao_requirement`] cascade
1933 /// and the shared [`crate::version::parse_requirement`] parser. Every
1934 /// downstream consumer that fans on the child's version pin keys off
1935 /// this scalar (the [`SupervisorSpec::validate`] per-child requirement
1936 /// gate at `require_valid_versao_requirement(child.versao_requirement(),
1937 /// …)`, the [`SupervisorError::ChildVersaoInvalid`] variant's carrier
1938 /// for `feira lint` rendering, every future per-cluster version-lock
1939 /// overlay the caixa-operator's hierarchical reconciliation scheduler
1940 /// pins through a future `:placement`-scoped supervisor-tree slot, the
1941 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1942 /// per-child version resolver, the future wasm-operator's per-child
1943 /// lacre BLAKE3-closure lookup at `ComputeUnit` materialization time).
1944 ///
1945 /// Prior to this lift the `.versao` byte-string was accessed inline at
1946 /// two `&str`-shaped sites in `caixa-core/src/supervisor.rs` — the
1947 /// [`SupervisorSpec::validate`] requirement-gate call
1948 /// `require_valid_versao_requirement(&child.versao, …)` and the
1949 /// [`SupervisorError::ChildVersaoInvalid`] carrier at
1950 /// `versao: child.versao.clone()` — two open-coded field-accesses that
1951 /// expressed no compile-time link back to the typed slot. A future
1952 /// extension of the `:children :versao` axis to a richer author surface
1953 /// (a per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
1954 /// flow, a lacre-projected concrete-version rewrite the operator
1955 /// materializes at CR-admission time, a future `:children :versao-lock`
1956 /// per-cluster override slot the wasm-operator's hierarchical
1957 /// reconciliation scheduler authors per-CR) would have had to be
1958 /// threaded through both open-coded copies in lockstep or one consumer
1959 /// would silently disagree with the peer on which release constraint a
1960 /// given child resolves to — the requirement-gate call reading
1961 /// `"^0.1"` while the error-body carrier read `"tenant-a-pin/^0.1"`
1962 /// would silently split the `ChildVersaoInvalid` diagnostic quote from
1963 /// the actual gate rejection input, a two-consumer split at the
1964 /// validator far from the source `caixa.lisp` with no field naming the
1965 /// version-pin drift root cause. Lifting the resolution rule to a typed
1966 /// method on the substrate primitive means every downstream
1967 /// requirement-facing consumer of the Supervisor's per-`:children`
1968 /// version-pin surface reaches for exactly one typed dispatch — the
1969 /// resolver's accept-set migrates as a unit on any future axis addition.
1970 ///
1971 /// Sibling of the peer per-`:membros` [`crate::Membro::versao_requirement`]
1972 /// (a40b0e3) member-caixa `:versao` scalar accessor on the M3 mesh-slot
1973 /// surface — same "one typed dispatch on the substrate primitive, thin
1974 /// projections at each consumer" discipline extended onto the M2
1975 /// supervisor-tree per-`:children` child-version-pin axis. The two typed
1976 /// axes (`Membro::versao_requirement` on the M3 Aplicacao side,
1977 /// `ChildSpec::versao_requirement` on the M2 Supervisor side) now share
1978 /// one accessor discipline for the shared substrate concept "another
1979 /// caixa referenced by a Cargo-shaped semver requirement". Peer of the
1980 /// sibling per-`:children` [`ChildSpec::nome`] (57c61d0) child-caixa
1981 /// `:nome` scalar accessor — the pair
1982 /// `(nome(), versao_requirement())` jointly projects the
1983 /// `(caixa, versao)` field pair every OTP-shape supervisor-tree consumer
1984 /// that fans on per-child identity + version pin keys off, closing the
1985 /// last unlifted per-`:children` `String`-carry axis so every downstream
1986 /// per-`:children` reader now routes through a typed dispatch on the
1987 /// substrate primitive. Named `versao_requirement()` rather than
1988 /// `versao()` because the field's storage-side `.versao` label is
1989 /// already the author-surface term (`:versao`); the accessor's name
1990 /// carries the semantic role — the semver *requirement* string the
1991 /// shared [`crate::version::parse_requirement`] entry-point consumes —
1992 /// so a raw field access and a typed dispatch read differently at every
1993 /// consumer site. Matches the peer [`crate::Membro::versao_requirement`]
1994 /// naming discipline verbatim.
1995 #[must_use]
1996 pub const fn versao_requirement(&self) -> &str {
1997 self.versao.as_str()
1998 }
1999
2000 /// Substrate-canonical per-`:children` `:restart` OTP-shaped
2001 /// per-child post-exit restart-decision policy scalar accessor every
2002 /// consumer that dispatches on the supervised child's post-exit
2003 /// reconcile posture keys off — returns the author-declared
2004 /// `:children :restart` variant verbatim as a [`RestartPolicy`],
2005 /// `Copy`-projected from the typed slot's own [`RestartPolicy`]
2006 /// storage.
2007 ///
2008 /// The `:children :restart` slot carries the closed-set OTP-shaped
2009 /// per-child restart-decision policy discriminator
2010 /// ([`RestartPolicy::Permanent`] — always restart, the OTP `permanent`
2011 /// worker-child default; [`RestartPolicy::Transient`] — restart only
2012 /// on abnormal exit, the OTP `transient` clean-completion-aware
2013 /// default; [`RestartPolicy::Temporary`] — never restart, the OTP
2014 /// `temporary` one-shot default) that every downstream consumer of
2015 /// the Supervisor's per-child post-exit reconcile branch keys off.
2016 /// Every future downstream consumer that fans on the per-child
2017 /// restart-decision keys off this scalar (the future `feira app
2018 /// graph` per-child restart column, the future wasm-operator's
2019 /// per-child post-exit restart-decision branch, the future M4
2020 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2021 /// admission webhook, the `caixa-operator`'s hierarchical
2022 /// reconciliation scheduler's per-child post-exit reconcile branch,
2023 /// the [`RestartPolicy::as_str`] `Serialize`-derive-pinning path the
2024 /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
2025 /// pin threads through).
2026 ///
2027 /// Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
2028 /// (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
2029 /// scalar accessor and the M3 mesh-slot
2030 /// [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
2031 /// [`crate::PlacementStrategy`] distribution-strategy scalar accessor
2032 /// — same "one typed dispatch on the substrate primitive,
2033 /// `Copy`-projected closed-set enum-arm discriminator that partitions
2034 /// the downstream renderer's per-arm fan-out" discipline extended
2035 /// onto the M2 supervisor-slot per-`:children` restart-decision-policy
2036 /// `Copy`-composite-enum scalar axis. Third axis on the per-`:children`
2037 /// [`ChildSpec`] type — companion to the sibling per-`:children`
2038 /// [`ChildSpec::nome`] (57c61d0) child-caixa `:nome` scalar accessor
2039 /// and the per-`:children` [`ChildSpec::versao_requirement`]
2040 /// (2c053c8) child-caixa `:versao` semver-requirement scalar accessor
2041 /// on the sibling `String`-carry axes. The triple
2042 /// `(nome(), versao_requirement(), restart())` jointly projects the
2043 /// `(caixa, versao, restart)` field trio every OTP-shape supervisor-
2044 /// tree consumer that fans on per-child identity + version pin +
2045 /// restart-decision keys off, closing the last unlifted per-`:children`
2046 /// axis so every downstream per-`:children` reader now routes through
2047 /// a typed dispatch on the substrate primitive. Named `restart()` to
2048 /// match the storage field's name and the author-surface
2049 /// `:children :restart` slot term verbatim; the accessor's identity
2050 /// name maps onto the canonical OTP-shape per-child restart-decision-
2051 /// policy vocabulary the [`RestartPolicy`] enum's docstring already
2052 /// carries.
2053 ///
2054 /// Declared `pub const fn` to close the last non-`const`
2055 /// `Copy`-return raw-field-getter posture on the M2
2056 /// per-`:children` [`ChildSpec`] substrate-primitive surface — peer
2057 /// of the sibling M2 per-`:supervisor`
2058 /// [`SupervisorSpec::estrategia`] (converted in this commit)
2059 /// `Copy`-composite-enum accessor, the sibling M2 per-`:supervisor`
2060 /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
2061 /// already lifted, and the peer M3 mesh-slot per-`:entrada`
2062 /// [`crate::Entrada::port`] (bafa004) / per-`:placement`
2063 /// [`crate::Placement::estrategia`] (bafa004) `Copy`-return
2064 /// `pub const fn` scalar accessors on the sibling M3 surface. Every
2065 /// downstream substrate-side `const`-context consumer of the
2066 /// per-`:children` restart-decision-policy scalar (a future
2067 /// module-scope `const _:() = assert!(matches!(child.restart(),
2068 /// RestartPolicy::Permanent))` invariant pin on a typed fixture, a
2069 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
2070 /// admission-webhook `const fn` per-child restart-decision floor
2071 /// over a typed [`ChildSpec`], any future `const fn` supervisor-tree
2072 /// composer over the substrate primitive that fans on the per-child
2073 /// restart-decision policy at compile time) now reaches through the
2074 /// same typed dispatch on the substrate primitive at const-eval
2075 /// time as at runtime. A future non-`Copy`-return promotion of the
2076 /// scalar (an `Option<RestartPolicy>`-shape migration on the
2077 /// per-child restart-decision axis once heterogeneous per-cluster
2078 /// restart-policy overlays land, a per-tenant restart-policy-alias
2079 /// table the M4 CR materializer resolves per-CR) that would drop
2080 /// the `const` qualifier fails the fail-before-pass-after pin
2081 /// [`tests::child_spec_restart_accessor_is_const_fn`] at caixa-core
2082 /// build time rather than surfacing as a downstream consumer
2083 /// regression.
2084 #[must_use]
2085 pub const fn restart(&self) -> RestartPolicy {
2086 self.restart
2087 }
2088}
2089
2090/// Supervisor-typed slots that live alongside the standard Caixa
2091/// fields when `:kind Supervisor`. Held flat in [`crate::Caixa`] so
2092/// the manifest stays a single typed form; this struct exists for
2093/// validation + conversion.
2094#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2095#[serde(rename_all = "camelCase")]
2096pub struct SupervisorSpec {
2097 /// Restart strategy. Defaults to [`RestartStrategy::OneForOne`].
2098 #[serde(default)]
2099 pub estrategia: RestartStrategy,
2100
2101 /// Max restarts within [`Self::restart_window`] before the
2102 /// supervisor itself terminates (and its parent supervisor decides
2103 /// what to do). Default 5.
2104 #[serde(default = "default_max_restarts")]
2105 pub max_restarts: u32,
2106
2107 /// Sliding window for `max_restarts`. Authored as a duration
2108 /// string (`"60s"`, `"5m"`); absent = "never reset". A `Some(0s)`
2109 /// is rejected by [`Self::validate`] — Erlang/OTP's
2110 /// `MaxIntensity / Period` invariant requires a positive window
2111 /// (a zero-period supervisor either trips on the first failure or
2112 /// never trips, depending on operator interpretation, neither of
2113 /// which is the author's intent). Omit the slot to express "no
2114 /// reset"; carry a positive duration to express the sliding window.
2115 #[serde(
2116 default,
2117 skip_serializing_if = "Option::is_none",
2118 with = "duration_codec"
2119 )]
2120 pub restart_window: Option<Duration>,
2121
2122 /// Static children. Empty for `SimpleOneForOne` (children added
2123 /// dynamically); required for the other three strategies.
2124 #[serde(default)]
2125 pub children: Vec<ChildSpec>,
2126}
2127
2128const fn default_max_restarts() -> u32 {
2129 // Route the private serde-`#[serde(default = "…")]` helper through
2130 // the substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] typed
2131 // `pub const` rather than the raw `5` literal — one source of truth
2132 // for the Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
2133 // default across the two production consumers that currently
2134 // dispatch on it (this helper via `#[serde(default = "…")]` on
2135 // `SupervisorSpec::max_restarts` and the [`Default for SupervisorSpec`]
2136 // impl at line 962). Pinned by
2137 // `default_max_restarts_helper_routes_through_lifted_default` +
2138 // `supervisor_spec_default_max_restarts_routes_through_lifted_default`
2139 // in the tests module; peer of the sibling caixa-core
2140 // [`crate::manifest::Caixa::supervisor_view`] `unwrap_or(…)` fold
2141 // that now routes its author-omitted `:max-restarts` arm through
2142 // the same lifted constant.
2143 SUPERVISOR_MAX_RESTARTS_DEFAULT
2144}
2145
2146/// Substrate-canonical Erlang/OTP-shaped `MaxIntensity` restart-budget-
2147/// count default for the `:supervisor :max-restarts` axis — the
2148/// canonical `{intensity, 5, 60}` `MaxIntensity` half of Learn You Some
2149/// Erlang's worker-supervisor default, extracted as a typed `pub const`
2150/// so every substrate-side consumer that resolves "what
2151/// [`SupervisorSpec::max_restarts`] value does an author-omitted
2152/// `:max-restarts` slot degrade onto?" reaches for exactly one
2153/// substrate-primitive `u32`.
2154///
2155/// The `:max-restarts` default axis has two production consumers on the
2156/// substrate side today (both prior to this lift folded onto raw `5`
2157/// literals with no compile-time link back to a shared truth): the
2158/// serde-`#[serde(default = "default_max_restarts")]` helper on
2159/// [`SupervisorSpec::max_restarts`] that every author-omitted
2160/// `:supervisor :max-restarts` slot lands in past the derive-macro's
2161/// wire-format compose, and the [`crate::manifest::Caixa::supervisor_view`]
2162/// `.max_restarts().unwrap_or(5)` fold that every downstream consumer of
2163/// the composed [`SupervisorSpec`] altitude reaches through
2164/// (`feira app graph`, the future wasm-operator's per-supervisor
2165/// restart-intensity counter, the future M4
2166/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2167/// webhook, the caixa-operator's hierarchical reconciliation scheduler).
2168/// A pair of open-coded `5`s across two files that expressed no
2169/// compile-time link back to the shared OTP-canonical default — a
2170/// future rebrand of the default (a tightening to Elixir's
2171/// `Supervisor.max_restarts: 3`, a widening to a per-cluster overlay
2172/// the operator pins through a future
2173/// `:supervisor :max-restarts-overrides` slot the MESH-COMPOSITION
2174/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
2175/// plain `u32` count to a richer `{MaxR, MaxT}` per-child-cohort
2176/// restart-budget-partition once the INSPIRATIONS §II.2 Erlang/OTP
2177/// per-child-cohort roadmap lands) would have had to be threaded
2178/// through both open-coded copies in lockstep or the wire-format
2179/// author-omitted arm and the view-construction author-omitted arm
2180/// would silently disagree on which restart-budget an omitted
2181/// `:max-restarts` resolves to (an author writing `:supervisor
2182/// (:max-restarts ())` would round-trip through serde with the new
2183/// default while `supervisor_view` silently continued to compose the
2184/// stale `5`, or vice versa), a two-consumer split at the composition
2185/// boundary far from the source `caixa.lisp` with no field naming the
2186/// default-drift root cause. Lifting the resolution rule to a typed
2187/// `pub const` on the substrate primitive means every downstream
2188/// consumer of the per-Supervisor default-restart-budget-count surface
2189/// reaches for exactly one substrate-primitive `u32` — the resolver's
2190/// accepted value migrates as a unit on any future axis change.
2191///
2192/// The `5` value pins Learn You Some Erlang's `{intensity, 5, 60}`
2193/// worker-supervisor default (the closest canonical OTP-shape
2194/// production reference the substrate carries, matching the sibling
2195/// `60s` `Period` default the [`Default for SupervisorSpec`] impl pairs
2196/// this constant with on the paired sliding-window axis). Two orders of
2197/// magnitude below the [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` ceiling
2198/// (the upper bracket on the same axis, sibling of this lower default;
2199/// both are typed `u32` const bounds on the `:supervisor :max-restarts`
2200/// axis and now share one accessor discipline on the substrate) and
2201/// above the OTP-`supervisor` callback-module `MaxR = 1` minimum-
2202/// restart floor — the "one restart, then escalate" default is
2203/// deliberately loose enough to absorb a short burst of transient
2204/// child failures without escalating past the supervisor's parent
2205/// while remaining tight enough to trip the `MaxIntensity / Period`
2206/// ratio's escalation on a genuinely-stuck child within the sibling
2207/// `60s` sliding window.
2208///
2209/// Lifted as a typed `pub const` so the bound has exactly one source
2210/// of truth — the serde-side wire-format author-omitted arm at
2211/// [`default_max_restarts`], the [`Default for SupervisorSpec`] impl's
2212/// struct-literal default field, and the caixa-core
2213/// [`crate::manifest::Caixa::supervisor_view`] fold's author-omitted
2214/// arm all read from one place. Same shape every other typed default
2215/// in this crate carries (the sibling
2216/// [`SUPERVISOR_MAX_RESTARTS_MAX`] upper cap on the same axis, the
2217/// paired [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the
2218/// sibling `:restart-window` axis, and the peer
2219/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
2220/// per-renderer defaults on the caixa-flux / caixa-helm rendering
2221/// axes).
2222pub const SUPERVISOR_MAX_RESTARTS_DEFAULT: u32 = 5;
2223
2224/// Upper-bound ceiling on the `:supervisor :max-restarts` axis — every
2225/// validated [`SupervisorSpec::max_restarts`] past
2226/// [`SupervisorSpec::validate`] lies in `1..=SUPERVISOR_MAX_RESTARTS_MAX`.
2227///
2228/// The typed field is `u32` (the zero-floor arm
2229/// [`SupervisorError::ZeroMaxRestarts`] already brackets the bottom edge),
2230/// so a programmatic struct literal
2231/// (`SupervisorSpec { max_restarts: u32::MAX, .. }`) and the equivalent
2232/// author-surface form (`:max-restarts 4294967295` or any
2233/// `:max-restarts 100000`-shape typo landing in the slot) both round-trip
2234/// cleanly through serde — a structurally unbounded `u32` ceiling. The
2235/// runtime substrate consuming the value (Erlang/OTP's
2236/// `MaxIntensity / Period` ratio, the future wasm-operator's
2237/// per-supervisor restart-intensity counter, the M4
2238/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook)
2239/// then turned a typed `:max-restarts` policy into a no-op supervisor: the
2240/// escalation threshold is structurally so high that no realistic
2241/// restarts-per-`:restart-window` traffic shape can reach it, the
2242/// supervisor never escalates to its parent, and a bad child can loop
2243/// inside the window indefinitely with the parent supervisor structurally
2244/// never receiving the "this subtree has exceeded its restart budget"
2245/// signal the typed slot is meant to express — the canonical
2246/// "supervisor intensity declared, no escalation" footgun, exactly the
2247/// peer of the [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap
2248/// on the `:politicas :circuit-breaker :max-failures` axis (both are
2249/// "trip the next-higher protection layer after N events in a rolling
2250/// window" counters with identical degenerate-at-the-high-end shape).
2251///
2252/// The `1000` ceiling matches the sibling
2253/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] (the closest
2254/// peer — same "events-per-window trip threshold" semantics, same `u32`
2255/// type, same no-op-at-the-high-end failure mode) so the M4
2256/// `mesh.pleme.io/v1alpha1/Supervisor` / `.../Aplicacao` CR materializers
2257/// and the future wasm-operator's per-supervisor restart-intensity
2258/// counter reach for either field knowing the value is in `1..=1000`
2259/// without re-validating at the reconciler layer. The cap sits two
2260/// orders of magnitude above every documented Erlang/OTP production
2261/// playbook recommendation (Learn You Some Erlang's
2262/// `{intensity, 5, 60}` worker-supervisor default, Elixir's `Supervisor`
2263/// `max_restarts: 3` default, OTP's `supervisor` callback module
2264/// `MaxR = 1` / `MaxT = 5` "minimal-restart" default, Riak Core's
2265/// typical `MaxR ∈ 5..=100`, RabbitMQ's broker-supervisor `MaxR = 5`
2266/// default) and below the clearly-pathological "effectively no
2267/// escalation" floor (`10_000`, `100_000`, `u32::MAX`): a value the
2268/// author can plausibly want at hyperscale (a long-running supervisor
2269/// over a very-flaky pool tolerating thousands of transient restarts
2270/// before escalating), but a hard wall above which the typed policy is
2271/// structurally a no-op carried verbatim on every emitted child-restart
2272/// reconciliation contract.
2273///
2274/// Lifted as a typed `pub const` so the bound has exactly one source of
2275/// truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
2276/// materializer's admission webhook and the wasm-operator-side
2277/// per-supervisor restart-intensity reconciler read from one place. Same
2278/// shape every other typed upper bound in this crate carries
2279/// ([`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
2280/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
2281/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
2282/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2283/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2284/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2285pub const SUPERVISOR_MAX_RESTARTS_MAX: u32 = 1000;
2286
2287/// Upper-bound ceiling on the `:supervisor :restart-window` axis —
2288/// every validated `Some(`[`SupervisorSpec::restart_window`]`)` past
2289/// [`SupervisorSpec::validate`] lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
2290/// (inclusive on both ends, integer-millisecond magnitudes by the
2291/// canonical-form gate immediately preceding).
2292///
2293/// The typed field is `Option<Duration>` (the zero-floor arm
2294/// [`SupervisorError::RestartWindowZero`] already rejects
2295/// `Some(Duration::ZERO)`, and the canonical-form arm
2296/// [`SupervisorError::RestartWindowNotCanonical`] already rejects
2297/// sub-millisecond residue), so a programmatic struct literal
2298/// (`SupervisorSpec { restart_window: Some(Duration::from_secs(86_400)),
2299/// .. }` — 24h) and the equivalent author-surface form
2300/// (`(:supervisor (:restart-window "24h"))` — the shared duration codec
2301/// emits `"<n>h"` for any integer-hour magnitude) both round-trip
2302/// cleanly through serde — a structurally unbounded `Duration` ceiling.
2303/// A `:restart-window` value far above the documented Erlang/OTP
2304/// `MaxIntensity / Period` production-playbook band (Learn You Some
2305/// Erlang's `{intensity, 5, 60}` worker-supervisor `Period = 60s`
2306/// default, Elixir's `Supervisor` `max_seconds: 5` default, OTP's
2307/// `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's
2308/// `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default)
2309/// degenerates the supervisor's restart-intensity counter into a
2310/// lifetime counter: the rolling failure-counting window is structurally
2311/// so long that transient restarts are never forgotten, so the
2312/// `MaxIntensity / Period` ratio degenerates from "trip the parent
2313/// supervisor when the child has exceeded its restart budget *within
2314/// the recent window*" to "trip the parent when the child has exceeded
2315/// its restart budget *over its lifetime*" — every transient restart
2316/// counts against the budget forever, the supervisor's reset semantic
2317/// never reaches the child, and the typed `:restart-window` slot
2318/// becomes a no-op rolling window carried on every emitted hierarchical
2319/// reconciliation contract. The canonical
2320/// rolling-window-degenerates-to-lifetime-counter footgun the sibling
2321/// [`crate::POLICY_BREAKER_WINDOW_MAX`] cap closes on the peer
2322/// `:politicas :circuit-breaker :window` axis with identical shape (both
2323/// are "rolling failure-counting window with a per-`Period` reset" Duration
2324/// axes whose lifetime-counter degenerate at the high end is the same
2325/// "the reset semantic never fires" CSE invariant violation).
2326///
2327/// The `1h` (3600s = `3_600_000` ms) ceiling matches the largest unit
2328/// the shared duration codec emits (`"<n>h"` for any integer-hour
2329/// magnitude) — every value in the canonical authoring form's
2330/// `<integer><unit>` grammar at or below this cap renders to a clean
2331/// canonical string — and matches the three sibling typed-`Duration`
2332/// caps already lifted to this surface
2333/// ([`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
2334/// [`crate::POLICY_BREAKER_WINDOW_MAX`]). All four typed-`Duration`
2335/// axes — per-process `:limits :wall-clock`, per-edge `:politicas
2336/// :timeout`, per-breaker `:politicas :circuit-breaker :window`, and
2337/// per-supervisor `:supervisor :restart-window` — now share a single
2338/// uniform top edge at the codec's largest emitted unit so the next
2339/// typed-slot wiring (the future wasm-operator's per-supervisor
2340/// `MaxIntensity / Period` reconciler, the M4
2341/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2342/// webhook, the `caixa-operator`'s hierarchical reconciliation
2343/// scheduler) reaches for any of the four knowing the value is in
2344/// `1ms..=1h` without re-validating at the renderer layer. The cap sits
2345/// two orders of magnitude above every documented Erlang/OTP / Elixir /
2346/// Riak Core / RabbitMQ production-playbook recommendation band
2347/// (`5s..=300s`) and below the clearly-pathological "rolling window
2348/// degenerates to lifetime counter" floor (`24h`, `7d`, `Duration::MAX`):
2349/// a value the author can plausibly want for a very-low-traffic
2350/// long-tail failure-restart window over a hyperscale-flaky child pool,
2351/// but a hard wall above which the rolling-window contract is
2352/// structurally a lifetime-counter contract.
2353///
2354/// Lifted as a typed `pub const` so the bound has exactly one source
2355/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
2356/// materializer's admission webhook, the wasm-operator-side
2357/// per-supervisor `MaxIntensity / Period` reconciler, and the
2358/// `caixa-operator`'s hierarchical reconciliation scheduler all read
2359/// from one place. Same shape every other typed upper bound in this
2360/// crate carries ([`SUPERVISOR_MAX_RESTARTS_MAX`],
2361/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
2362/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
2363/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
2364/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2365/// [`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
2366/// [`crate::POLICY_BREAKER_WINDOW_MAX`],
2367/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2368/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2369pub const SUPERVISOR_RESTART_WINDOW_MAX: Duration = Duration::from_secs(3600);
2370
2371/// Substrate-canonical Erlang/OTP-shaped `Period` sliding-window-duration
2372/// default for the `:supervisor :restart-window` axis — the canonical
2373/// `{intensity, 5, 60}` `Period` half of Learn You Some Erlang's
2374/// worker-supervisor default, extracted as a typed `pub const` so every
2375/// substrate-side consumer that resolves "what
2376/// [`SupervisorSpec::restart_window`] value does an author-omitted
2377/// `:restart-window` slot degrade onto?" reaches for exactly one
2378/// substrate-primitive [`Duration`].
2379///
2380/// The `:restart-window` default axis has one production consumer on the
2381/// substrate side today: the [`Default for SupervisorSpec`] impl's
2382/// struct-literal `restart_window` field, which prior to this lift folded
2383/// onto a raw `Duration::from_secs(60)` literal with no compile-time link
2384/// back to the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity`
2385/// half of the same `{intensity, 5, 60}` OTP-canonical default. The
2386/// [`crate::manifest::Caixa::supervisor_view`] fold deliberately does
2387/// *not* fall back to this default on the sibling `:restart-window` axis
2388/// — an author-omitted `:supervisor :restart-window` composes to
2389/// `restart_window: None` (the shared codec's soft-swallow shape),
2390/// keeping author-declared intent ("no reset — never escalate on rolling
2391/// window") distinct from the [`Default for SupervisorSpec`] "canonical
2392/// 60s Period" arm every programmatic `SupervisorSpec::default()` caller
2393/// resolves to. Prior to this lift the paired `{intensity, 5, 60}` OTP
2394/// default was split across two files with no compile-time link between
2395/// the halves: [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] pinned the
2396/// `MaxIntensity` half at the substrate primitive while the `Period`
2397/// half rode as an open-coded literal at the composition site, so a
2398/// future coherent rebrand of the paired canonical (a tightening to
2399/// Elixir's `{max_restarts: 3, max_seconds: 5}`, a widening to a
2400/// per-cluster overlay the operator pins through a future
2401/// `:supervisor :restart-window-overrides` slot the MESH-COMPOSITION
2402/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
2403/// paired constants to a per-child-cohort `{MaxR, MaxT}` restart-budget-
2404/// partition once the INSPIRATIONS §II.2 Erlang/OTP per-child-cohort
2405/// roadmap lands) would have had to migrate the `MaxIntensity` half
2406/// through the lifted constant and the `Period` half through a raw
2407/// literal in lockstep or the two halves of the same OTP-canonical
2408/// default would silently drift out of pairing. Lifting the resolution
2409/// rule to a typed `pub const` on the substrate primitive means the
2410/// paired OTP-canonical default migrates as one unit on any future
2411/// axis change.
2412///
2413/// The `60s` value pins Learn You Some Erlang's `{intensity, 5, 60}`
2414/// worker-supervisor default (the closest canonical OTP-shape
2415/// production reference the substrate carries, matching the paired
2416/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5` `MaxIntensity` half this
2417/// constant is the `Period` denominator of on the same
2418/// `MaxIntensity / Period` restart-intensity ratio). Two orders of
2419/// magnitude below the [`SUPERVISOR_RESTART_WINDOW_MAX`] `3600s`
2420/// (`1h`) ceiling (the upper bracket on the same axis, sibling of
2421/// this lower default; both are typed [`Duration`] const bounds on the
2422/// `:supervisor :restart-window` axis and now share one accessor
2423/// discipline on the substrate) and above the OTP-`supervisor`
2424/// callback-module `MaxT = 5` seconds "minimal-window" floor — the "60s
2425/// rolling window" default is deliberately loose enough to absorb a
2426/// short burst of transient child failures without escalating past the
2427/// supervisor's parent while remaining tight enough for the paired
2428/// `MaxIntensity / Period` ratio's escalation to trip on a genuinely-
2429/// stuck child within a human-scale observation window.
2430///
2431/// Lifted as a typed `pub const` so the paired OTP-canonical default has
2432/// exactly one source of truth on each half — the sibling
2433/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half and this
2434/// `Period` `60s` half now share the same substrate-primitive lift
2435/// discipline. Same shape every other typed default in this crate
2436/// carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] paired
2437/// `MaxIntensity` half on the same OTP-canonical `{intensity, 5, 60}`,
2438/// the sibling [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the same
2439/// axis, and the peer [`crate::render::DEFAULT_NAMESPACE`] /
2440/// [`crate::render::DEFAULT_LIBRARY_NAME`] per-renderer defaults on the
2441/// caixa-flux / caixa-helm rendering axes).
2442pub const SUPERVISOR_RESTART_WINDOW_DEFAULT: Duration = Duration::from_secs(60);
2443
2444/// Substrate-canonical Erlang/OTP-shaped sibling-restart-strategy default
2445/// for the `:supervisor :estrategia` axis — the canonical `one_for_one`
2446/// half of Learn You Some Erlang's `{one_for_one, intensity, 5, 60}`
2447/// worker-supervisor default, extracted as a typed `pub const` so every
2448/// substrate-side consumer that resolves "what
2449/// [`SupervisorSpec::estrategia`] variant does an author-omitted
2450/// `:estrategia` slot degrade onto?" reaches for exactly one substrate-
2451/// primitive [`RestartStrategy`].
2452///
2453/// The `:estrategia` default axis has three production consumers on the
2454/// substrate side today: the [`Default for RestartStrategy`] impl's
2455/// return arm, the [`Default for SupervisorSpec`] impl's struct-literal
2456/// `estrategia` field, and the
2457/// [`crate::manifest::Caixa::supervisor_view`] fold's
2458/// `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)` `Option<RestartStrategy>`
2459/// collapse arm — three entry points onto the same OTP-canonical
2460/// `one_for_one` value that prior to this lift folded onto a raw
2461/// `Self::OneForOne` arm at the [`Default for RestartStrategy`] impl and
2462/// implicit `RestartStrategy::default()` routes at the sibling consumers,
2463/// with no compile-time link back to the paired
2464/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` half + the paired
2465/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` half of the same
2466/// `{one_for_one, intensity, 5, 60}` OTP-canonical default. The paired
2467/// triple was split across three altitudes with no compile-time link
2468/// between the halves: the `MaxIntensity` half rode through the lifted
2469/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant (b698ec0) and the `Period`
2470/// half rode through the lifted [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2471/// constant (f7dcd0e) while the `one_for_one` half rode as an open-coded
2472/// discriminator at the [`Default for RestartStrategy`] impl, so a future
2473/// coherent rebrand of the triple (Elixir's `{:one_for_one,
2474/// max_restarts: 3, max_seconds: 5}` — same strategy, different
2475/// intensity/period; an OTP `rest_for_one` widening once the substrate
2476/// discovers startup-order-coupled child cohorts as the more common
2477/// worker-supervisor default; a per-cluster overlay the operator pins
2478/// through a future `:estrategia-overrides` slot the MESH-COMPOSITION
2479/// §III.2 supervision-canary roadmap acknowledges) would have had to
2480/// migrate the `MaxIntensity` + `Period` halves through the lifted
2481/// constants and the `one_for_one` half through an open-coded arm in
2482/// lockstep or the three halves of the same OTP-canonical default would
2483/// silently drift out of pairing. Lifting the resolution rule to a typed
2484/// `pub const` on the substrate primitive means the paired OTP-canonical
2485/// worker-supervisor default migrates as one unit on any future axis
2486/// change.
2487///
2488/// The [`RestartStrategy::OneForOne`] value pins Learn You Some Erlang's
2489/// `{one_for_one, intensity, 5, 60}` worker-supervisor default (the
2490/// closest canonical OTP-shape production reference the substrate
2491/// carries, matching the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5`
2492/// `MaxIntensity` half and the paired [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2493/// `60s` `Period` half). The `one_for_one` strategy — restart only the
2494/// failed child, leaving siblings untouched — is the default for tree-of-
2495/// independent-workers use cases the substrate's [`RestartStrategy`]
2496/// discriminator's own docstring already carries as the default arm; it
2497/// composes with the `{5, 60}` restart-intensity ratio to name the same
2498/// substrate-canonical "canonical worker-supervisor" shape the paired
2499/// halves close on their respective axes.
2500///
2501/// Lifted as a typed `pub const` so the paired OTP-canonical default has
2502/// exactly one source of truth on each of its three halves — the sibling
2503/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half, the
2504/// sibling [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` `60s` half, and
2505/// this `one_for_one` strategy half now share the same substrate-
2506/// primitive lift discipline. Same shape every other typed default in
2507/// this crate carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] +
2508/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] paired halves on the same OTP-
2509/// canonical `{one_for_one, intensity, 5, 60}`, the sibling
2510/// [`SUPERVISOR_MAX_RESTARTS_MAX`] + [`SUPERVISOR_RESTART_WINDOW_MAX`]
2511/// upper caps on the paired sibling axes, and the peer
2512/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
2513/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes).
2514pub const SUPERVISOR_ESTRATEGIA_DEFAULT: RestartStrategy = RestartStrategy::OneForOne;
2515
2516/// Substrate-canonical Erlang/OTP-shaped per-child restart-decision-policy
2517/// default for the `:children :restart` axis — the OTP `permanent`
2518/// worker-child default (`{ChildId, StartFunc, permanent, …}` in a
2519/// `supervisor`'s `init/1` child-spec tuple), extracted as a typed
2520/// `pub const` so every substrate-side consumer that resolves "what
2521/// [`ChildSpec::restart`] variant does an author-omitted `:children
2522/// :restart` slot degrade onto?" reaches for exactly one substrate-
2523/// primitive [`RestartPolicy`].
2524///
2525/// Completes the OTP-shape supervisor-tree default set at the substrate
2526/// primitive. The per-`:supervisor` axis already carries all three of its
2527/// halves as lifted typed constants — [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
2528/// (`one_for_one`, 95ffacc), [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
2529/// (`MaxIntensity` `5`, b698ec0), [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2530/// (`Period` `60s`, f7dcd0e) — while the per-`:children` axis's own
2531/// OTP-canonical default rode as an open-coded `Self::Permanent` arm in
2532/// the [`Default for RestartPolicy`] impl, the last un-lifted default on
2533/// the M2 `:supervisor` slot family. The split mattered because the two
2534/// axes resolve *together* on every author-omitted supervisor: a
2535/// `(defcaixa :kind Supervisor :children ((:caixa "worker" :versao
2536/// "^0.1")))` with no `:estrategia` and no per-child `:restart` degrades
2537/// onto `{one_for_one, 5, 60}` through three lifted constants and onto
2538/// `permanent` through an open-coded enum arm, so a future coherent
2539/// rebrand of the OTP-shape default set (an Elixir-shaped
2540/// `{:one_for_one, max_restarts: 3, max_seconds: 5}` tightening, a
2541/// per-cluster overlay the operator pins through the MESH-COMPOSITION
2542/// §III.2 supervision-canary roadmap slots, an OTP-`transient` widening
2543/// once the substrate discovers clean-completion-aware children as the
2544/// more common child shape) would have had to migrate three halves
2545/// through typed constants and the fourth through a raw enum arm in
2546/// lockstep or the supervisor-level and child-level defaults would
2547/// silently drift apart.
2548///
2549/// The `:children :restart` default axis has two production consumers on
2550/// the substrate side today: the [`Default for RestartPolicy`] impl's
2551/// return arm, and the serde-side `#[serde(default)]` on
2552/// [`ChildSpec::restart`] that resolves an author-omitted `:children
2553/// :restart` slot through that same impl. Both now key off this one
2554/// substrate primitive, so the future wasm-operator's per-child post-exit
2555/// restart-decision branch, the future M4
2556/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2557/// admission webhook, and the `caixa-operator`'s hierarchical
2558/// reconciliation scheduler's per-child fan-out all reach for one typed
2559/// identifier when they resolve an omitted per-child restart posture.
2560///
2561/// The [`RestartPolicy::Permanent`] value pins Erlang/OTP's `permanent`
2562/// worker-child restart type — always restart the child regardless of how
2563/// it died, the canonical posture for long-running services that must
2564/// always be up, matching the sibling [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
2565/// `one_for_one` tree-of-independent-workers strategy this constant pairs
2566/// with under the same `{one_for_one, intensity, 5, 60}` worker-supervisor
2567/// shape. The two alternatives the closed [`RestartPolicy::ALL`] accept-set
2568/// carries ([`RestartPolicy::Transient`] — restart only on abnormal exit;
2569/// [`RestartPolicy::Temporary`] — never restart) express deliberate
2570/// one-shot / clean-completion-aware postures an author declares
2571/// explicitly, never a posture an omitted slot should silently assume.
2572pub const SUPERVISOR_CHILD_RESTART_DEFAULT: RestartPolicy = RestartPolicy::Permanent;
2573
2574/// Route the manually-authored [`Default`] impl on [`SupervisorSpec`]
2575/// through the substrate-canonical [`SupervisorSpec::otp_canonical`]
2576/// `pub const fn` constructor rather than a struct-literal cascade over
2577/// the paired [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
2578/// [`default_max_restarts`] / [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2579/// lifted consts — one source of truth for the Erlang/OTP-canonical
2580/// `{one_for_one, 5, 60}` worker-supervisor baseline across the two
2581/// paths every downstream consumer already reaches through (the
2582/// hand-authored-until-now [`Default::default`] the
2583/// `..SupervisorSpec::default()` struct-update-syntax on every
2584/// one-axis-under-test fixture in this crate's test module rests on,
2585/// and the `pub const fn` [`SupervisorSpec::otp_canonical`] constructor
2586/// every `const`-context consumer reaches through).
2587///
2588/// Extends the [`Default`]-through-const-ctor fold discipline the
2589/// [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
2590/// (abd52c2), [`crate::aplicacao::MeshPolicy`]
2591/// [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`] (91641a4),
2592/// and [`crate::BehaviorSpec`]
2593/// [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c) folds
2594/// closed on the M2 / M3 `Option`-only "canonical unset baseline"
2595/// typed-slot spec family — extended here onto the M2 supervisor-slot
2596/// [`SupervisorSpec`] whose canonical baseline is not "everything
2597/// `None`" but the OTP-canonical `{one_for_one, 5, 60}` worker-
2598/// supervisor triple. The `empty()` peer's naming did not fit
2599/// (`SupervisorSpec` carries a discriminator-shaped `estrategia` field
2600/// and a non-zero `max_restarts`/`restart_window` pair whose canonical
2601/// shape is Erlang/OTP-descended, not the "no axis declared" bottom
2602/// the sibling `Option`-only slots fold to), so this peer is named
2603/// [`SupervisorSpec::otp_canonical`] instead — the same phrasing the
2604/// existing per-arm pin tests
2605/// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`] /
2606/// [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`] /
2607/// [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
2608/// already reach for. Pinned load-bearing by
2609/// [`tests::supervisor_spec_default_routes_through_otp_canonical_ctor`]
2610/// (byte-parity pin against [`SupervisorSpec::otp_canonical`] under
2611/// [`PartialEq`], sharpening the sibling
2612/// `supervisor_spec_default_*_routes_through_lifted_default` per-arm
2613/// pins from a per-field lift into a whole-struct one-source-of-truth
2614/// pin — the derived-until-now [`Default::default`] and the
2615/// [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
2616/// construction, not by coincidence).
2617impl Default for SupervisorSpec {
2618 #[inline]
2619 fn default() -> Self {
2620 Self::otp_canonical()
2621 }
2622}
2623
2624impl SupervisorSpec {
2625 /// `const`-context peer of the [`Default for SupervisorSpec`]
2626 /// impl (which routes through this constructor) — returns the
2627 /// Erlang/OTP-canonical `{one_for_one, 5, 60}` worker-supervisor
2628 /// baseline this crate reaches for in every fixture-builder
2629 /// `..SupervisorSpec::default()` struct-update expression and
2630 /// every downstream `SupervisorSpec::default()` seed.
2631 ///
2632 /// Each field routes through the same substrate-canonical
2633 /// [`SUPERVISOR_ESTRATEGIA_DEFAULT`] / [`default_max_restarts`] /
2634 /// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] lifted consts the
2635 /// per-arm pin tests
2636 /// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`]
2637 /// / [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`]
2638 /// / [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
2639 /// already assert, so a future coherent rebrand of the OTP-canonical
2640 /// triple (Elixir's `{max_restarts: 3, max_seconds: 5}`, a per-
2641 /// cluster overlay via a future `:restart-window-overrides` slot, a
2642 /// per-child-cohort promotion the INSPIRATIONS.md §II.2 Erlang/OTP
2643 /// absorption roadmap acknowledges) migrates through three typed
2644 /// constants in lockstep, and the paired [`Default`] impl inherits
2645 /// every future extension by construction.
2646 ///
2647 /// `pub const fn` rather than the derived-style `Default::default`
2648 /// or a `pub const SUPERVISOR_SPEC_DEFAULT: SupervisorSpec` item —
2649 /// [`Default::default`] is not `const` on stable Rust, and
2650 /// `SupervisorSpec` is non-`Copy` so a `pub const` item would force
2651 /// every consumer through a [`Clone::clone`]. The `pub const fn`
2652 /// discipline lets `const`-context callers construct the OTP-
2653 /// canonical baseline at compile time without runtime dispatch on
2654 /// the derived [`Default::default`], the same posture the sibling
2655 /// [`crate::LimitsSpec::empty`] (9739971) /
2656 /// [`crate::aplicacao::MeshPolicy::empty`] (6df969b) /
2657 /// [`crate::BehaviorSpec::empty`] (f9b18e3) `Option`-only typed-slot
2658 /// spec `pub const fn` constructors carry on the sibling
2659 /// "everything `None`" baseline axis.
2660 ///
2661 /// Fourth peer on the M2 / M3 typed-slot-spec "const-context peer
2662 /// of the derived-style [`Default`]" family — sibling of the
2663 /// [`crate::LimitsSpec::empty`] / [`crate::aplicacao::MeshPolicy::empty`]
2664 /// / [`crate::BehaviorSpec::empty`] `Option`-only "canonical unset
2665 /// baseline" trio, extended here onto the M2 supervisor-slot
2666 /// [`SupervisorSpec`] whose canonical baseline is not "everything
2667 /// `None`" but the Erlang/OTP-canonical `{one_for_one, 5, 60}`
2668 /// worker-supervisor triple. Named [`Self::otp_canonical`] rather
2669 /// than `empty()` to name the actual invariant the return value
2670 /// pins — the same phrasing already used in the per-arm pin tests
2671 /// on this file. Pinned load-bearing by
2672 /// [`tests::supervisor_spec_otp_canonical_byte_equals_default`] and
2673 /// [`tests::supervisor_spec_otp_canonical_is_usable_in_const_context`].
2674 #[must_use]
2675 pub const fn otp_canonical() -> Self {
2676 Self {
2677 estrategia: SUPERVISOR_ESTRATEGIA_DEFAULT,
2678 max_restarts: default_max_restarts(),
2679 restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
2680 children: Vec::new(),
2681 }
2682 }
2683
2684 /// Substrate-canonical per-`:supervisor` `:estrategia` OTP-shaped
2685 /// sibling-restart-strategy scalar accessor every consumer that
2686 /// dispatches on the supervisor's per-sibling restart-decision shape
2687 /// keys off — returns the author-declared `:supervisor :estrategia`
2688 /// variant verbatim as a [`RestartStrategy`], `Copy`-projected from
2689 /// the typed slot's own [`RestartStrategy`] storage.
2690 ///
2691 /// The `:supervisor :estrategia` slot carries the closed-set
2692 /// OTP-shaped sibling-restart-strategy discriminator ([`RestartStrategy::OneForOne`]
2693 /// — restart only the failed child, the Erlang/OTP `one_for_one` default;
2694 /// [`RestartStrategy::OneForAll`] — restart every child on any child
2695 /// failure, the Erlang/OTP `one_for_all` shared-state cohort default;
2696 /// [`RestartStrategy::RestForOne`] — restart the failed child and
2697 /// every child started after it, the Erlang/OTP `rest_for_one`
2698 /// startup-order default; [`RestartStrategy::SimpleOneForOne`] —
2699 /// dynamic children of the same shape, the Erlang/OTP
2700 /// `simple_one_for_one` per-session default) that every downstream
2701 /// consumer of the Supervisor's per-sibling restart-decision fan-out
2702 /// shape keys off. Validated by [`SupervisorSpec::validate`] to be
2703 /// paired coherently with the sibling `:children` axis
2704 /// (`SimpleOneForOne ↔ children.is_empty()` — the cross-slot
2705 /// partition the strategy-arm's [`SupervisorError::SimpleOneForOneWithStaticChildren`]
2706 /// / [`SupervisorError::NoChildren`] refusal cascade pins), and every
2707 /// downstream consumer that reads the strategy keys off this scalar
2708 /// (the [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
2709 /// partition-dispatch `match` arm, the non-`SimpleOneForOne`-arm
2710 /// declared-but-empty [`SupervisorError::NoChildren`] error carrier's
2711 /// `estrategia:` field, the future `feira app graph` per-Supervisor
2712 /// strategy print line, the future wasm-operator's per-supervisor
2713 /// sibling-restart-strategy branch, the future M4
2714 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-strategy
2715 /// admission-webhook resolver, the `caixa-operator`'s hierarchical
2716 /// reconciliation scheduler's per-strategy fan-out).
2717 ///
2718 /// Prior to this lift the `.estrategia` field was accessed inline at
2719 /// two production sites in `caixa-core/src/supervisor.rs` — the
2720 /// [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
2721 /// `match self.estrategia { … }` partition dispatch, and the
2722 /// non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
2723 /// carrier at `estrategia: self.estrategia` — two open-coded
2724 /// field-accesses that expressed no compile-time link back to the
2725 /// typed slot. A future extension of the `:supervisor :estrategia`
2726 /// axis to a richer author surface (a per-cluster strategy override
2727 /// the operator pins through a future `:supervisor :estrategia-overrides`
2728 /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
2729 /// acknowledges, a per-tenant strategy-alias table the M4 CR
2730 /// materializer resolves per-CR, a per-Supervisor dynamic strategy
2731 /// derivation the future adaptive-supervision engine computes from
2732 /// child-failure-history topology, a per-child-cohort strategy split
2733 /// the future `RestForCohort` extension acknowledged by the
2734 /// INSPIRATIONS.md §II.2 Erlang/OTP absorption roadmap acknowledges)
2735 /// would have had to be threaded through every open-coded copy in
2736 /// lockstep — one consumer reading the raw variant while a peer read
2737 /// the operator-resolved variant would silently split the
2738 /// [`SupervisorError::NoChildren`] diagnostic's quoted strategy from
2739 /// the actual partition-dispatch input the empty-children refusal
2740 /// arm reached under, a two-consumer split at the validator far from
2741 /// the source `caixa.lisp` with no field naming the strategy-drift
2742 /// root cause. Lifting the resolution rule to a typed method on the
2743 /// substrate primitive means every downstream consumer of the
2744 /// Supervisor's per-`:supervisor` sibling-restart-strategy surface
2745 /// reaches for exactly one typed dispatch — the resolver's accept-set
2746 /// migrates as a unit on any future axis addition.
2747 ///
2748 /// Peer of the sibling M3 mesh-slot [`crate::Placement::estrategia`]
2749 /// (921fe1b) `Copy`-return `PlacementStrategy` scalar accessor on the
2750 /// per-`:placement` distribution-strategy axis — same "one typed
2751 /// dispatch on the substrate primitive, thin projections at each
2752 /// consumer" discipline extended onto the M2 supervisor-slot
2753 /// per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
2754 /// scalar axis. The two typed axes (`Placement::estrategia` on the
2755 /// M3 Aplicacao side, `SupervisorSpec::estrategia` on the M2
2756 /// Supervisor side) now share one accessor discipline for the shared
2757 /// substrate concept "a `Copy`-projected closed-set enum-arm
2758 /// discriminator that partitions the downstream renderer's per-arm
2759 /// fan-out". First `Copy`-return accessor on the M2 supervisor-slot
2760 /// `SupervisorSpec` type — companion to the sibling per-`:children`
2761 /// [`crate::ChildSpec::nome`] (57c61d0) /
2762 /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
2763 /// scalar accessors on the sibling per-`:children` `String`-carry
2764 /// axes. Named `estrategia()` to match the storage field's name and
2765 /// the peer [`crate::Placement::estrategia`] method-name discipline
2766 /// verbatim; the accessor's identity name maps onto the canonical
2767 /// OTP-shape supervision vocabulary the [`RestartStrategy`] enum's
2768 /// docstring already carries.
2769 ///
2770 /// Declared `pub const fn` to close the M2 supervisor-slot
2771 /// `Copy`-return raw-field-getter `const`-eval-surface pass —
2772 /// sibling of the peer M2 per-`:children` [`ChildSpec::restart`]
2773 /// (converted in this commit) `Copy`-composite-enum accessor, peer
2774 /// of the sibling M2 per-`:supervisor`
2775 /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
2776 /// already lifted, and mirror of the peer M3 mesh-slot
2777 /// per-`:placement` [`crate::Placement::estrategia`] (bafa004)
2778 /// `Copy`-return `pub const fn` scalar accessor whose method-name
2779 /// discipline this accessor was authored to match. Every downstream
2780 /// substrate-side `const`-context consumer of the per-`:supervisor`
2781 /// sibling-restart-strategy scalar (a future module-scope `const
2782 /// _:() = assert!(matches!(sup.estrategia(),
2783 /// RestartStrategy::OneForOne))` invariant pin on a typed fixture,
2784 /// a future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
2785 /// admission-webhook `const fn` per-supervisor strategy-arm floor
2786 /// over a typed [`SupervisorSpec`], any future `const fn`
2787 /// supervisor-tree composer over the substrate primitive that fans
2788 /// on the sibling-restart-strategy at compile time) now reaches
2789 /// through the same typed dispatch on the substrate primitive at
2790 /// const-eval time as at runtime. A future non-`Copy`-return
2791 /// promotion of the scalar (an `Option<RestartStrategy>`-shape
2792 /// migration once the substrate grows per-cluster strategy overlays
2793 /// the [`SupervisorSpec`] docstring already anticipates, a
2794 /// per-tenant strategy-alias table the M4 CR materializer resolves
2795 /// per-CR) that would drop the `const` qualifier fails the
2796 /// fail-before-pass-after pin
2797 /// [`tests::supervisor_spec_estrategia_accessor_is_const_fn`] at
2798 /// caixa-core build time rather than surfacing as a downstream
2799 /// consumer regression.
2800 #[must_use]
2801 pub const fn estrategia(&self) -> RestartStrategy {
2802 self.estrategia
2803 }
2804
2805 /// Substrate-canonical per-`:supervisor` `:max-restarts` OTP-shaped
2806 /// `MaxIntensity` restart-budget scalar accessor every consumer that
2807 /// reads the supervisor's per-`:restart-window` restart-budget count
2808 /// keys off — returns the author-declared `:supervisor :max-restarts`
2809 /// typed `u32` verbatim, `Copy`-projected from the typed slot's own
2810 /// `u32` storage (`u32` is `Copy`, so the accessor returns by value; no
2811 /// borrow of `&self` past the call). Non-optional (the `u32` field
2812 /// carries the restart-budget count as a required axis with a
2813 /// [`default_max_restarts`]-supplied default; the zero-floor arm
2814 /// [`SupervisorError::ZeroMaxRestarts`] and the cap arm
2815 /// [`SupervisorError::MaxRestartsExceedsCap`] jointly bracket the
2816 /// accept-set to `1..=SUPERVISOR_MAX_RESTARTS_MAX`).
2817 ///
2818 /// The `:supervisor :max-restarts` slot carries the Erlang/OTP
2819 /// `MaxIntensity` restart-budget count that pairs with the sibling
2820 /// `:restart-window` `Period` to form the `MaxIntensity / Period`
2821 /// restart-intensity ratio the supervisor trips its own escalation on
2822 /// (`theory/RUNTIME-PATTERNS.md` §II.2, Learn You Some Erlang's
2823 /// `{intensity, 5, 60}` worker-supervisor default). Every downstream
2824 /// consumer of the Supervisor's per-`:supervisor` restart-budget count
2825 /// keys off this scalar (the [`SupervisorSpec::validate`] zero-floor +
2826 /// upper-cap bracket at
2827 /// `require_positive_bounded_u32(self.max_restarts(), …)`, the future
2828 /// wasm-operator's per-supervisor restart-intensity counter's
2829 /// budget-vs-count comparator, the future M4
2830 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2831 /// webhook, the `caixa-operator`'s hierarchical reconciliation
2832 /// scheduler's per-supervisor escalation-decision branch, every
2833 /// `SupervisorError::MaxRestartsExceedsCap` variant carrying the
2834 /// offending count verbatim for `feira lint` rendering).
2835 ///
2836 /// Prior to this lift the `.max_restarts` field was accessed inline at
2837 /// one production site in `caixa-core/src/supervisor.rs` — the
2838 /// [`SupervisorSpec::validate`] `require_positive_bounded_u32(self
2839 /// .max_restarts, …)` bracket-gate call — one open-coded field-access
2840 /// that expressed no compile-time link back to the typed slot. A
2841 /// future extension of the `:max-restarts` axis to a richer author
2842 /// surface (a per-cluster restart-budget override the operator pins
2843 /// through a future `:supervisor :max-restarts-overrides` slot the
2844 /// MESH-COMPOSITION §III.2 supervision-canary roadmap acknowledges,
2845 /// a per-tenant restart-budget-alias table the M4 CR materializer
2846 /// resolves per-CR, a per-supervisor dynamic restart-budget derivation
2847 /// the future adaptive-supervision engine computes from child-failure-
2848 /// history topology, a promotion of the plain `u32` count to a richer
2849 /// `{MaxR, MaxT}` tuple once Erlang/OTP's per-child-cohort restart-
2850 /// budget-partition slot comes into scope) would have had to be
2851 /// threaded through every open-coded copy in lockstep or the validate
2852 /// gate and the future M4 emit path would silently disagree on which
2853 /// restart-budget count a given supervisor resolves to — an author's
2854 /// `:max-restarts 5` would satisfy validate while the emit path
2855 /// silently read a drifted other value (a `:max-restarts 10000`
2856 /// no-op supervisor at the emit boundary would carry the author's
2857 /// declared `5` verbatim in `feira lint` output while the future
2858 /// wasm-operator's restart-intensity counter operated under the
2859 /// drifted count), a two-consumer split at the validator far from the
2860 /// source `caixa.lisp` with no field naming the restart-budget-drift
2861 /// root cause. Lifting the resolution rule to a typed method on the
2862 /// substrate primitive means every downstream consumer of the
2863 /// Supervisor's per-`:supervisor` restart-budget-count surface reaches
2864 /// for exactly one typed dispatch — the resolver's accept-set migrates
2865 /// as a unit on any future axis addition.
2866 ///
2867 /// Peer of the sibling M3 mesh-slot [`crate::CircuitBreaker::max_failures`]
2868 /// (3a74062) `Copy`-return `u32` sub-struct required-scalar accessor
2869 /// on the per-`:politicas :circuit-breaker :max-failures` Envoy-
2870 /// outlier-detection trip-threshold axis — same "one typed dispatch on
2871 /// the substrate primitive, thin projections at each consumer"
2872 /// discipline extended onto the M2 supervisor-slot per-`:supervisor`
2873 /// restart-budget-count `Copy`-`u32` scalar axis. The two typed axes
2874 /// (`CircuitBreaker::max_failures` on the M3 Aplicacao side,
2875 /// `SupervisorSpec::max_restarts` on the M2 Supervisor side) now share
2876 /// one accessor discipline for the shared substrate concept "a
2877 /// `Copy`-projected required `u32` count that trips the next-higher
2878 /// protection layer after N events in a rolling window" — both are
2879 /// counters with identical degenerate-at-the-high-end shape and share
2880 /// the paired [`crate::POLICY_BREAKER_MAX_FAILURES_MAX`] /
2881 /// [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` cap. Second `Copy`-return
2882 /// accessor on the M2 supervisor-slot `SupervisorSpec` type, sibling
2883 /// to the [`SupervisorSpec::estrategia`] (eafb619) `Copy`-composite-
2884 /// enum `RestartStrategy` accessor. Named `max_restarts()` to match
2885 /// the storage field's name verbatim and the peer
2886 /// [`crate::CircuitBreaker::max_failures`] method-name discipline; the
2887 /// accessor's identity maps onto the canonical OTP-shape supervision
2888 /// vocabulary the [`SupervisorSpec::max_restarts`] field's docstring
2889 /// already carries.
2890 #[must_use]
2891 pub const fn max_restarts(&self) -> u32 {
2892 self.max_restarts
2893 }
2894
2895 /// Substrate-canonical per-`:supervisor` `:restart-window` OTP-shaped
2896 /// `Period` sliding-window scalar accessor every consumer of the
2897 /// supervisor's `MaxIntensity / Period` restart-intensity denominator
2898 /// keys off — returns the author-declared `:supervisor :restart-window`
2899 /// typed [`Duration`] verbatim as an `Option<Duration>`, copied out of
2900 /// the typed slot's own `Option<Duration>` storage (`Duration` is
2901 /// `Copy`, so `Option<Duration>` is `Copy` and the accessor returns by
2902 /// value; no borrow of `&self` past the call). `None` when the slot is
2903 /// absent (the canonical "never reset — every restart across the
2904 /// supervisor's lifetime counts against the sibling `:max-restarts`
2905 /// budget" sentinel the field's own docstring names and the peer
2906 /// `validate_accepts_none_restart_window` pin locks in on the
2907 /// [`SupervisorSpec::validate`] entry-side).
2908 ///
2909 /// The `:supervisor :restart-window` slot carries the Erlang/OTP
2910 /// `Period` sliding-observation-interval that pairs with the sibling
2911 /// `:max-restarts` `MaxIntensity` restart-budget count to form the
2912 /// `MaxIntensity / Period` restart-intensity ratio the supervisor
2913 /// trips its own escalation on (`theory/RUNTIME-PATTERNS.md` §II.2,
2914 /// Learn You Some Erlang's `{intensity, 5, 60}` worker-supervisor
2915 /// default). The typed slot's `Option<Duration>` accept-set —
2916 /// zero-floor rejected through [`SupervisorError::RestartWindowZero`]
2917 /// (Erlang/OTP's `MaxIntensity / Period` invariant requires
2918 /// `Period > 0`; a zero period either trips on the first failure or
2919 /// never trips depending on operator interpretation, neither of which
2920 /// is the author's intent — omit the slot to express "no reset";
2921 /// carry a positive duration to express the sliding window),
2922 /// integer-millisecond canonical form enforced through
2923 /// [`SupervisorError::RestartWindowNotCanonical`] (the duration
2924 /// codec's canonical form emits `"1500ms"` not `"1.5s"` and the
2925 /// future wasm-operator's per-supervisor restart-intensity counter
2926 /// quantizes at milliseconds), upper-bounded by
2927 /// [`SUPERVISOR_RESTART_WINDOW_MAX`] (1h — the coarsest per-
2928 /// supervisor rolling window any operationally-reachable supervisor
2929 /// can honor without spanning multiple scheduler epochs the
2930 /// hierarchical-reconciliation scheduler treats as independent) —
2931 /// maps onto the future wasm-operator (M3) per-supervisor
2932 /// restart-intensity counter's rolling-observation-interval, the
2933 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2934 /// per-`spec.restartWindow` admission webhook, and the sibling
2935 /// `duration_codec`-serialized wire scalar every downstream consumer
2936 /// of the supervisor's per-`:supervisor` restart-intensity denominator
2937 /// keys off.
2938 ///
2939 /// Prior to this lift the `.restart_window` field was accessed inline
2940 /// at one production site in `caixa-core/src/supervisor.rs` — the
2941 /// [`SupervisorSpec::validate`] `if let Some(w) = self.restart_window {
2942 /// … }` zero-floor + canonical-form + upper-cap bracket arm — one
2943 /// open-coded field-access that expressed no compile-time link back to
2944 /// the typed slot. A future extension of the `:restart-window` axis to
2945 /// a richer author surface (a per-cluster restart-window override the
2946 /// operator pins through a future `:supervisor :restart-window-overrides`
2947 /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
2948 /// acknowledges, a per-tenant restart-window-alias table the M4 CR
2949 /// materializer resolves per-CR, a per-supervisor dynamic
2950 /// restart-window derivation the future adaptive-supervision engine
2951 /// computes from child-failure-history topology, a promotion of the
2952 /// plain `Option<Duration>` window to a richer `{observation, cooldown}`
2953 /// pair once Erlang/OTP's per-child-cohort observation-interval-
2954 /// partition slot comes into scope) would have had to be threaded
2955 /// through every open-coded copy in lockstep or the validate gate and
2956 /// the future M4 emit path would silently disagree on which
2957 /// restart-window a given supervisor resolves to — an author's
2958 /// `:restart-window "60s"` would satisfy validate while the emit path
2959 /// silently read a drifted other value (a `Some(Duration::from_secs(60))`
2960 /// authored slot at the emit boundary would carry the author's
2961 /// declared window verbatim in `feira lint` output while the future
2962 /// wasm-operator's restart-intensity counter operated under a
2963 /// drifted window, or vice versa: an author's `:restart-window ()`
2964 /// would carry the "never reset" sentinel through validate while the
2965 /// emit path silently substituted a default sliding window), a
2966 /// two-consumer split at the validator far from the source
2967 /// `caixa.lisp` with no field naming the restart-window-drift root
2968 /// cause. Lifting the resolution rule to a typed method on the
2969 /// substrate primitive means every downstream consumer of the
2970 /// Supervisor's per-`:supervisor` restart-intensity-denominator
2971 /// surface reaches for exactly one typed dispatch — the resolver's
2972 /// accept-set migrates as a unit on any future axis addition.
2973 ///
2974 /// Third `Copy`-return accessor on the M2 supervisor-slot
2975 /// `SupervisorSpec` type, closing the last unlifted per-`:supervisor`
2976 /// scalar-value axis (`children: Vec<ChildSpec>` carries a `Vec`
2977 /// payload rather than a `Copy`-scalar, and the per-`:children`
2978 /// [`crate::ChildSpec::nome`] (57c61d0) /
2979 /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
2980 /// scalar accessors already close the per-element `String`-carry
2981 /// axes). Sibling to the peer M2 [`crate::LimitsSpec::wall_clock`]
2982 /// (8cb717b) `Option<Duration>` accessor on the `:limits` slot's
2983 /// per-outermost-call wall-clock-deadline axis and the peer M3
2984 /// [`crate::MeshPolicy::timeout`] (7073d0f) `Option<Duration>`
2985 /// accessor on the `:politicas` slot's per-call-deadline axis — all
2986 /// three share the shared substrate concept "a `Copy`-projected
2987 /// optional `Duration` that carries a positive integer-millisecond
2988 /// canonical value with a `1ms..=<axis-specific>_MAX` accept-set and
2989 /// the paired zero-floor / non-canonical / above-cap refusal cascade"
2990 /// through the same [`crate::render::require_positive_canonical_bounded_duration`]
2991 /// bracket-helper the three axes each route through. Named
2992 /// `restart_window()` to match the storage field's name verbatim and
2993 /// the peer [`crate::LimitsSpec::wall_clock`] /
2994 /// [`crate::MeshPolicy::timeout`] method-name discipline; the
2995 /// accessor's identity maps onto the canonical OTP-shape supervision
2996 /// vocabulary the [`SupervisorSpec::restart_window`] field's docstring
2997 /// already carries.
2998 #[must_use]
2999 pub const fn restart_window(&self) -> Option<Duration> {
3000 self.restart_window
3001 }
3002
3003 /// Substrate-canonical per-`:supervisor` `:children` OTP-shaped
3004 /// static-child-list slice accessor every consumer that walks the
3005 /// supervisor's declared child set keys off — returns the author-
3006 /// declared `:supervisor :children` `Vec<ChildSpec>` verbatim as a
3007 /// `&[ChildSpec]` slice-view, borrowed from the typed slot's own
3008 /// `Vec<ChildSpec>` storage (a zero-copy slice-view over the same
3009 /// backing buffer the `Serialize`/`Deserialize` derives round-trip
3010 /// through). Non-optional: an empty slice is the load-bearing
3011 /// "author declared `:children ()`" sentinel every consumer of the
3012 /// cross-slot `SimpleOneForOne ↔ children.is_empty()` partition
3013 /// keys off (`SimpleOneForOne` requires the empty slice; the peer
3014 /// three strategies require a non-empty slice — the paired
3015 /// [`SupervisorError::SimpleOneForOneWithStaticChildren`] /
3016 /// [`SupervisorError::NoChildren`] refusal cascade pins the
3017 /// partition on both arms).
3018 ///
3019 /// The `:supervisor :children` slot carries the OTP-shaped static
3020 /// child list the supervisor materializes one ComputeUnit per
3021 /// entry from — the Erlang/OTP `supervisor:init/1`'s
3022 /// `{ok, {SupFlags, ChildSpecs}}` `ChildSpecs` list, projected
3023 /// through the tatara-lisp `:children` author surface onto a typed
3024 /// `Vec<ChildSpec>` whose per-element `(nome(),
3025 /// versao_requirement(), restart)` triple the per-child
3026 /// [`SupervisorSpec::validate`] loop already gates through the
3027 /// lifted [`ChildSpec::nome`] (57c61d0) /
3028 /// [`ChildSpec::versao_requirement`] (2c053c8) scalar accessors.
3029 /// Every downstream consumer that fans on the static child list
3030 /// keys off this slice (the [`SupervisorSpec::validate`]
3031 /// `SimpleOneForOne ↔ non-SimpleOneForOne` partition dispatch's
3032 /// `.is_empty()` probe on both arms, the [`SupervisorSpec::validate`]
3033 /// per-child DNS-1123 / semver-requirement / duplicate-detection
3034 /// fan-out loop, every future wasm-operator (M3) per-supervisor
3035 /// hierarchical-reconciliation scheduler's per-child ComputeUnit
3036 /// materialization loop, the future M4
3037 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
3038 /// admission-webhook fan-out, the future `feira app graph`
3039 /// per-supervisor tree-print traversal).
3040 ///
3041 /// Prior to this lift the `.children` `Vec<ChildSpec>` was accessed
3042 /// inline at three production sites in `caixa-core/src/supervisor.rs`
3043 /// — the [`SupervisorSpec::validate`] `SimpleOneForOne`-arm
3044 /// `!self.children.is_empty()` cross-slot refusal probe, the peer
3045 /// non-`SimpleOneForOne`-arm `self.children.is_empty()`
3046 /// [`SupervisorError::NoChildren`] refusal probe, and the per-child
3047 /// validate loop's `for child in &self.children` traversal head —
3048 /// three open-coded field-accesses that expressed no compile-time
3049 /// link back to the typed slot. A future extension of the
3050 /// `:supervisor :children` axis to a richer author surface (a
3051 /// per-cluster child-set overlay the operator pins through a future
3052 /// `:supervisor :children-overrides` slot the MESH-COMPOSITION §III.2
3053 /// supervision-canary roadmap acknowledges, a per-tenant
3054 /// child-set-alias table the M4 CR materializer resolves per-CR,
3055 /// a per-supervisor dynamic-child derivation the future adaptive-
3056 /// supervision engine computes from child-failure-history topology,
3057 /// a promotion of the plain `Vec<ChildSpec>` to a richer
3058 /// `{static, dynamic}` partition once Erlang/OTP's
3059 /// `simple_one_for_one` dynamic-child slot comes into typed scope)
3060 /// would have had to be threaded through all three open-coded copies
3061 /// in lockstep or one consumer would silently disagree with the
3062 /// peers on which child-set a given supervisor resolves to — the
3063 /// `SimpleOneForOne`-arm probe reading the raw slot while the peer
3064 /// non-`SimpleOneForOne`-arm probe read an operator-resolved slot
3065 /// would silently split the partition-dispatch's two-arm coherence
3066 /// (a supervisor that satisfies neither arm's precondition, or that
3067 /// satisfies both, at the cost of the paired
3068 /// `SimpleOneForOneWithStaticChildren`/`NoChildren` refusal cascade
3069 /// silently drifting from the per-child validate loop's actual
3070 /// traversal input), a three-consumer split at the validator far
3071 /// from the source `caixa.lisp` with no field naming the
3072 /// child-set-drift root cause. Lifting the resolution rule to a
3073 /// typed method on the substrate primitive means every downstream
3074 /// consumer of the Supervisor's per-`:supervisor` static-child-list
3075 /// surface reaches for exactly one typed dispatch — the resolver's
3076 /// accept-set migrates as a unit on any future axis addition.
3077 ///
3078 /// First slice-return (`&[T]`) accessor on any M2 or M3 typed slot
3079 /// — the seed for the same "one typed dispatch on the substrate
3080 /// primitive, thin projections at each consumer" discipline the
3081 /// closed [`crate::LimitsSpec`] / [`BehaviorSpec`] /
3082 /// [`crate::UpgradeFromEntry`] scalar-accessor families each carry
3083 /// on their `Copy` / `Option<Copy>` / `Option<&str>` axes, extended
3084 /// onto the first `Vec`-carry axis on the substrate. The four peer
3085 /// `Vec`-carry axes still unlifted at the time of this seed —
3086 /// [`crate::Placement::clusters`] (`Vec<String>` per-cluster
3087 /// distribution-target list), [`crate::AplicacaoSpec::membros`]
3088 /// (`Vec<Membro>` per-Aplicacao member list),
3089 /// [`crate::AplicacaoSpec::contratos`] (`Vec<WitContract>`
3090 /// per-Aplicacao WIT-typed edge list),
3091 /// [`crate::UpgradeFromEntry::instructions`]
3092 /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
3093 /// — inherit this accessor's discipline as future compounding runs
3094 /// migrate their consumers onto the shared slice-return shape.
3095 /// Fourth (and final) accessor on the M2 supervisor-slot
3096 /// `SupervisorSpec` type, sibling to the three `Copy`-return
3097 /// [`SupervisorSpec::estrategia`] (eafb619) /
3098 /// [`SupervisorSpec::max_restarts`] (7844f4e) /
3099 /// [`SupervisorSpec::restart_window`] (7e7b32f) accessors — closes
3100 /// the last unlifted per-`:supervisor` field axis (the
3101 /// `Vec<ChildSpec>` static-child-list carrier) so every downstream
3102 /// per-`:supervisor` reader now routes through a typed dispatch on
3103 /// the substrate primitive. Named `children()` to match the storage
3104 /// field's name verbatim and the tatara-lisp author-surface term
3105 /// (`:children`) the field's own docstring already carries; the
3106 /// accessor's identity maps onto the canonical OTP-shape
3107 /// supervision vocabulary the [`SupervisorSpec::children`] field's
3108 /// docstring already reaches for ("Static children ..."). Returns
3109 /// `&[ChildSpec]` (not `&Vec<ChildSpec>`) because every downstream
3110 /// consumer of the child list treats it as a read-only sequence —
3111 /// the slice-view is the narrowest borrow that supports every
3112 /// present + roadmapped consumer (`.is_empty()`, `.iter()`,
3113 /// index, `.len()`) without leaking the backing `Vec`'s
3114 /// grow/push/reserve surface that no consumer of the typed view
3115 /// reaches for (the storage-side `Vec` remains reachable through
3116 /// the `pub children` field for the mutation-carrying
3117 /// `Caixa::supervisor_view` fold-in path in
3118 /// `manifest.rs:supervisor_view`).
3119 #[must_use]
3120 pub const fn children(&self) -> &[ChildSpec] {
3121 self.children.as_slice()
3122 }
3123
3124 /// Validate the supervisor's typed shape — strategy ↔ children
3125 /// invariants, max_restarts > 0, restart_window > 0 when set,
3126 /// per-child non-empty + duplicate-free names.
3127 ///
3128 /// Mirrors the value-shape discipline applied to every other
3129 /// typed slot:
3130 ///
3131 /// - `Some(Duration::ZERO)` on a Duration-bearing axis is the
3132 /// same "0 means the opposite of what you think" footgun
3133 /// closed for `:politicas :timeout` (Envoy interprets a zero
3134 /// timeout as `infinite`), `:politicas :circuit-breaker
3135 /// :window`, and `:limits :wall-clock`. The
3136 /// `MaxIntensity / Period` ratio in Erlang/OTP's
3137 /// `supervisor` requires `Period > 0`; a zero period either
3138 /// trips on the first failure or never trips depending on
3139 /// operator interpretation, neither of which is the
3140 /// author's intent. Omit `:restart-window` to express "no
3141 /// reset"; carry a positive duration to express the window.
3142 /// - duplicate `:children` `:caixa` names are the same
3143 /// graph-node-set / multiset distinction closed for
3144 /// `:membros` (4bb3f3d), `:placement :clusters` (c7c7799),
3145 /// and `:entrada :paths` (eb3456d). Two children with the
3146 /// same `:caixa` materialize as two ComputeUnits with the
3147 /// same name in the cluster's HelmRelease values, one
3148 /// silently overwriting the other. Erlang/OTP's
3149 /// `child_spec.id` is required-unique per supervisor;
3150 /// pleme-io enforces the same set-not-multiset shape on
3151 /// `:caixa` (the load-bearing identity in our renderer).
3152 pub fn validate(&self) -> Result<(), SupervisorError> {
3153 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition
3154 // dispatch and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
3155 // error carrier's `estrategia:` field through the lifted
3156 // [`SupervisorSpec::estrategia`] accessor rather than the raw
3157 // `self.estrategia` field access — the two production consumers
3158 // of the per-`:supervisor` sibling-restart-strategy scalar now
3159 // key off exactly one typed dispatch on the substrate primitive,
3160 // so any future rebrand on the axis (a per-cluster strategy
3161 // override the operator pins through a future `:supervisor
3162 // :estrategia-overrides` slot, a per-tenant strategy-alias table
3163 // the M4 CR materializer resolves per-CR) migrates as a single
3164 // caixa-core edit rather than a coordinated rewrite of the two
3165 // call sites — sibling of the peer M3 [`crate::Placement::estrategia`]
3166 // (921fe1b) four-consumer migration on the per-`:placement`
3167 // distribution-strategy axis.
3168 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition-
3169 // dispatch's paired `.is_empty()` cross-slot refusal probes
3170 // (the `SimpleOneForOne`-arm
3171 // [`SupervisorError::SimpleOneForOneWithStaticChildren`] refusal
3172 // and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
3173 // refusal) through the lifted [`SupervisorSpec::children`]
3174 // slice-return accessor rather than the raw `self.children`
3175 // field access — the two paired production consumers of the
3176 // per-`:supervisor` static-child-list scalar-shape now key off
3177 // exactly one typed dispatch on the substrate primitive, so any
3178 // future rebrand on the axis (a per-cluster child-set overlay
3179 // the operator pins through a future `:supervisor
3180 // :children-overrides` slot, a per-tenant child-set-alias table
3181 // the M4 CR materializer resolves per-CR) migrates as a single
3182 // caixa-core edit rather than a coordinated rewrite of the
3183 // paired arms — first slice-return migration on any typed slot,
3184 // seed for the peer per-`:placement :clusters`,
3185 // per-`:membros`, per-`:contratos`, and per-`:upgrade-from
3186 // :instructions` `Vec`-carry axes.
3187 match self.estrategia() {
3188 RestartStrategy::SimpleOneForOne => {
3189 // SimpleOneForOne: children added at runtime. Static
3190 // list must be empty (one shape declared elsewhere).
3191 if !self.children().is_empty() {
3192 return Err(SupervisorError::SimpleOneForOneWithStaticChildren);
3193 }
3194 }
3195 _ => {
3196 if self.children().is_empty() {
3197 return Err(SupervisorError::no_children(self.estrategia()));
3198 }
3199 }
3200 }
3201 // Zero-floor + upper-cap bracket on the typed `:max-restarts`
3202 // axis. See [`crate::render::require_positive_bounded_u32`] for
3203 // the ordering discipline (zero-floor arm strictly precedes cap
3204 // arm so `0` surfaces the self-locating `ZeroMaxRestarts`
3205 // diagnostic with its counter-axis remediation directly named,
3206 // not the misleading `0 > SUPERVISOR_MAX_RESTARTS_MAX == false`
3207 // cap-arm miss). Until this bracket landed the top edge ran all
3208 // the way to `u32::MAX` and a struct-literal
3209 // `SupervisorSpec { max_restarts: 100_000, .. }` (or the
3210 // equivalent author-surface `:max-restarts 100000` /
3211 // `:max-restarts 4294967295` typo landing in the slot) silently
3212 // passed validate. The runtime substrate consuming the value
3213 // (Erlang/OTP's `MaxIntensity / Period` ratio, the future
3214 // wasm-operator's per-supervisor restart-intensity counter, the
3215 // M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
3216 // admission webhook) then turned a typed `:max-restarts`
3217 // policy into a no-op supervisor: the escalation threshold is
3218 // structurally so high that no realistic
3219 // restarts-per-`:restart-window` traffic shape can reach it,
3220 // the supervisor never escalates to its parent, and a bad
3221 // child can loop inside the window indefinitely with the
3222 // parent supervisor structurally never receiving the "this
3223 // subtree has exceeded its restart budget" signal the typed
3224 // slot is meant to express. The bracket set is
3225 // `1..=SUPERVISOR_MAX_RESTARTS_MAX`, peer with the
3226 // [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap on
3227 // the sibling `:politicas :circuit-breaker :max-failures` axis:
3228 // both are "trip the next-higher protection layer after N
3229 // events in a rolling window" counters with identical
3230 // degenerate-at-the-high-end shape and now share one canonical
3231 // bracket helper. The bracket precedes the sibling
3232 // `:restart-window` zero-floor / canonical-millisecond arms so
3233 // an over-cap `max_restarts` paired with a structurally invalid
3234 // window surfaces the bracket diagnostic first, mirroring the
3235 // `PolicyBreakerMaxFailuresExceedsCap` / window-axis cross-arm
3236 // ordering on the peer `:politicas :circuit-breaker` slot.
3237 // Route the [`SupervisorSpec::validate`] `:max-restarts` zero-floor +
3238 // upper-cap bracket-gate through the lifted [`SupervisorSpec::max_restarts`]
3239 // accessor rather than the raw `self.max_restarts` field access —
3240 // the one production consumer of the per-`:supervisor`
3241 // restart-budget-count scalar now keys off exactly one typed
3242 // dispatch on the substrate primitive, so any future rebrand on
3243 // the axis (a per-cluster restart-budget override the operator
3244 // pins through a future `:supervisor :max-restarts-overrides`
3245 // slot, a per-tenant restart-budget-alias table the M4 CR
3246 // materializer resolves per-CR) migrates as a single caixa-core
3247 // edit rather than a coordinated rewrite — sibling of the peer M3
3248 // [`crate::CircuitBreaker::max_failures`] (3a74062) migration on
3249 // the per-`:politicas :circuit-breaker :max-failures` axis.
3250 crate::render::require_positive_bounded_u32(
3251 self.max_restarts(),
3252 SUPERVISOR_MAX_RESTARTS_MAX,
3253 || SupervisorError::ZeroMaxRestarts,
3254 SupervisorError::max_restarts_exceeds_cap,
3255 )?;
3256 // Route the [`SupervisorSpec::validate`] `:restart-window`
3257 // zero-floor + integer-millisecond canonical-form + upper-cap
3258 // bracket-gate through the lifted [`SupervisorSpec::restart_window`]
3259 // accessor rather than the raw `self.restart_window` field access —
3260 // the one production consumer of the per-`:supervisor`
3261 // restart-intensity-denominator scalar now keys off exactly one
3262 // typed dispatch on the substrate primitive, so any future rebrand
3263 // on the axis (a per-cluster restart-window override the operator
3264 // pins through a future `:supervisor :restart-window-overrides`
3265 // slot, a per-tenant restart-window-alias table the M4 CR
3266 // materializer resolves per-CR) migrates as a single caixa-core
3267 // edit rather than a coordinated rewrite — sibling of the peer M2
3268 // [`crate::LimitsSpec::wall_clock`] (8cb717b) validate-arm-route
3269 // on the per-`:limits :wall-clock` axis and the peer M3
3270 // [`crate::MeshPolicy::timeout`] (7073d0f) accessor-route on the
3271 // per-`:politicas :timeout` axis.
3272 if let Some(w) = self.restart_window() {
3273 // Zero-floor + integer-millisecond canonical-form +
3274 // upper-cap bracket on the typed `:restart-window` axis.
3275 // See
3276 // [`crate::render::require_positive_canonical_bounded_duration`]
3277 // for the full three-arm ordering discipline (zero-floor
3278 // strictly precedes canonical-form so `Duration::ZERO`
3279 // surfaces the self-locating `RestartWindowZero`
3280 // diagnostic; canonical-form strictly precedes the cap arm
3281 // so a sub-millisecond above-cap value surfaces the more
3282 // fundamental round-trip-shape diagnostic first) and the
3283 // three peer typed-`Duration` sites that share this
3284 // canonical bracket ([`crate::MeshPolicy::timeout`],
3285 // [`crate::CircuitBreaker::window`],
3286 // [`crate::LimitsSpec::wall_clock`]). Every validated
3287 // value lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
3288 // (1ms..=1h), integer-millisecond granularity.
3289 crate::render::require_positive_canonical_bounded_duration(
3290 w,
3291 SUPERVISOR_RESTART_WINDOW_MAX,
3292 || SupervisorError::RestartWindowZero,
3293 SupervisorError::restart_window_not_canonical,
3294 SupervisorError::restart_window_exceeds_cap,
3295 )?;
3296 }
3297 // Route the per-child DNS-1123 / semver-requirement / duplicate-
3298 // detection fan-out loop through the lifted named per-slot gate
3299 // [`SupervisorSpec::validate_children`] rather than an inline
3300 // three-per-child cascade — every future consumer that wants to
3301 // re-check only the `:children` slot's per-entry axes (the M4
3302 // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
3303 // admission webhook re-validating one added/renamed child, the
3304 // future wasm-operator's per-child dynamic-add re-validator on
3305 // the `SimpleOneForOne` runtime-add path once dynamic-children
3306 // graduate to a typed slot, a future partial re-validator on a
3307 // per-`:children`-entry patch) reaches every per-entry axis
3308 // through one dispatch rather than re-inlining the three-arm
3309 // cascade in lockstep with `validate` or paying the peer
3310 // `:estrategia`/`:max-restarts`/`:restart-window` gates to
3311 // reach one entry check. Sibling of the peer M3 mesh-slot
3312 // per-slot gate family (`validate_membros` — the exact peer on
3313 // the M3 side, [`crate::AplicacaoSpec::validate_membros`];
3314 // `validate_contratos` — 906a5c6; `validate_entrada` — 20cd523;
3315 // `validate_placement`; `validate_politicas` routing through
3316 // `MeshPolicy::validate` — f03a154) — the M2 supervisor-slot
3317 // per-slot gate discipline now spans both the M3 mesh-slot
3318 // family and the M2 `:children` per-child-cascade axis on one
3319 // shape: one named per-slot gate per typed per-entry loop.
3320 self.validate_children()?;
3321 Ok(())
3322 }
3323
3324 /// Named per-slot gate on the M2 `:supervisor :children` per-entry
3325 /// axis — folds the per-child DNS-1123 name gate, semver-requirement
3326 /// gate, and duplicate-`:caixa` dedup arm into one call every
3327 /// consumer that wants to re-validate one `:children` entry (or the
3328 /// whole list) against the same accept-set [`SupervisorSpec::validate`]
3329 /// admits reaches through.
3330 ///
3331 /// Peer of the M3 mesh-slot [`crate::AplicacaoSpec::validate_membros`]
3332 /// per-slot gate on the analogous per-entry axis (`:membros`) — same
3333 /// three-per-entry shape (DNS-1123 name + semver-requirement +
3334 /// duplicate-`:caixa` dedup), lifted to one named substrate
3335 /// primitive per slot. The M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
3336 /// materializer's admission webhook re-checking one added or renamed
3337 /// child, the future wasm-operator's per-child dynamic-add
3338 /// re-validator on the `SimpleOneForOne` runtime-add path once
3339 /// dynamic-children graduate to a typed slot, a future partial
3340 /// re-validator on a per-`:children`-entry patch — each reaches the
3341 /// three per-entry axes through this one dispatch rather than
3342 /// re-inlining the three-arm cascade in lockstep with `validate`
3343 /// (the duplication the PRIME DIRECTIVE names as a bug) or paying
3344 /// the peer `:estrategia`/`:max-restarts`/`:restart-window` gates to
3345 /// reach one entry check.
3346 ///
3347 /// Self-contained on `&self` — resolves its own dedup `HashSet`
3348 /// through [`SupervisorSpec::children`] rather than borrowing one
3349 /// threaded down from `validate`, the same posture the peer M3
3350 /// mesh-slot per-slot gates ([`crate::AplicacaoSpec::validate_membros`],
3351 /// [`crate::AplicacaoSpec::validate_contratos`],
3352 /// [`crate::AplicacaoSpec::validate_entrada`],
3353 /// [`crate::AplicacaoSpec::validate_placement`]) each carry, so a
3354 /// consumer that reaches this gate directly (without first calling
3355 /// `validate`) still runs the full per-child cascade — pinned by
3356 /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
3357 /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
3358 /// + `validate_children_is_self_contained_on_children_slot`.
3359 ///
3360 /// The three per-entry arms run in the same canonical order the
3361 /// pre-lift inline cascade encoded (DNS-1123 → semver → dedup), so
3362 /// the diagnostic every author-declared per-`:children` entry surfaces
3363 /// through `validate` is byte-equal to the diagnostic this gate
3364 /// surfaces when called directly — the equivalence-pin pair
3365 /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
3366 /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
3367 /// asserts the two altitudes discriminate the same set on every
3368 /// per-entry-covered input.
3369 pub fn validate_children(&self) -> Result<(), SupervisorError> {
3370 let mut seen = std::collections::HashSet::new();
3371 for child in self.children() {
3372 // Every emitted cluster artifact's `metadata.name` for a
3373 // supervised child derives from this `:children :caixa` value
3374 // verbatim — the rendered `wasm.pleme.io/v1alpha1/ComputeUnit
3375 // .metadata.name` per child, the [`crate::LABEL_PROGRAM`]
3376 // label value on every child's pod identity, and the per-
3377 // child K8s [`Service`][svc] `metadata.name` the future
3378 // wasm-operator (M3) provisions for inter-child supervision
3379 // tree wiring. Each apiserver-side schema on each landing
3380 // site enforces the DNS-1123 label rule on admission; a
3381 // structurally invalid child name (`"Worker"`, `"my_worker"`,
3382 // `"team.worker"`, `"-worker"`, `"worker-"`, the >63-byte
3383 // UUID-shaped mistaken-identity slug) silently passes the
3384 // prior empty-/duplicate-only gate and the failure surfaces
3385 // at `kubectl apply` time as a `metadata.name: Invalid value`
3386 // rejection, far from the source caixa.lisp, with no field
3387 // naming the offending `:children` entry. Lifting the gate
3388 // to caixa-build time mirrors the `:membros :caixa` value-
3389 // shape trajectory (3f9d7a0) and the `:placement :clusters`
3390 // trajectory (6cbb900) onto the third DNS-1123-label-shaped
3391 // identifier axis — the supervisor tree's child names —
3392 // through the lifted
3393 // [`crate::render::require_valid_dns_1123_label`] gate the
3394 // seven peer name axes (`:membros :caixa`, `:placement
3395 // :clusters`, `:placement :affinity`, `:contratos :de`/`:para`,
3396 // `:entrada :para`, `:nome`, `:upgrade-from :module`) each
3397 // route through, so drift between the eight axes' accepted
3398 // DNS-1123-label sets is structurally impossible.
3399 //
3400 // [svc]: https://kubernetes.io/docs/concepts/services-networking/service/
3401 crate::render::require_valid_dns_1123_label(
3402 child.nome(),
3403 || SupervisorError::EmptyChildName,
3404 |reason| SupervisorError::child_caixa_invalid(child.nome(), reason),
3405 )?;
3406 // The author surface for `:children :versao` is the same
3407 // Cargo-shaped semver requirement string `:deps :versao` and
3408 // `:membros :versao` carry — and the lacre pipeline resolves
3409 // all three axes through the same
3410 // [`crate::version::parse_requirement`] entry-point. The
3411 // shared [`crate::render::require_valid_versao_requirement`]
3412 // helper brackets the empty-first + parse cascade both peer
3413 // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
3414 // [`crate::AplicacaoSpec::validate_membros`] on `:membros
3415 // :versao`) route through, so drift between the three axes'
3416 // accepted requirement sets is structurally impossible and
3417 // the parse-side no-op the empty-first arm closes (semver's
3418 // empty parse yields an implicit `*`) lives in exactly one
3419 // predicate. Every `ChildSpec::versao` past validate is
3420 // round-trippable through [`crate::parse_requirement`]
3421 // without re-checking at the resolver layer, and the three
3422 // `:versao` typed surfaces (`:deps`, `:membros`, `:children`)
3423 // are now structurally equivalent by construction.
3424 crate::render::require_valid_versao_requirement(
3425 child.versao_requirement(),
3426 || SupervisorError::empty_child_version(child.nome()),
3427 |reason| {
3428 SupervisorError::child_versao_invalid(
3429 child.nome(),
3430 child.versao_requirement(),
3431 reason,
3432 )
3433 },
3434 )?;
3435 crate::render::insert_first_seen(&mut seen, child.nome(), || {
3436 SupervisorError::duplicate_child_caixa(child.nome())
3437 })?;
3438 }
3439 Ok(())
3440 }
3441}
3442
3443/// Cross-slot coherence gate on the supervision tree: no
3444/// `:children :caixa` entry may name the supervisor's own `:nome`.
3445///
3446/// A supervisor that lists itself as a child is a degenerate self-parent
3447/// — the supervision tree is a DAG rooted at the supervisor (OTP child
3448/// specs reference *distinct* child processes; a supervisor is never its
3449/// own child), and the wasm-operator's hierarchical reconciliation would
3450/// otherwise be handed a node that is its own parent: a one-node cycle it
3451/// either rejects far from the source `caixa.lisp` or recurses on. Because
3452/// every `:nome` is a globally-unique substrate identity (DNS-1123 label +
3453/// lacre closure root), a child whose `:caixa` equals the supervisor's
3454/// `:nome` *is* the supervisor itself, not a coincidentally-named peer.
3455///
3456/// Lives outside [`SupervisorSpec::validate`] because the typed view
3457/// carries the children but not the parent `:nome`; mirrors the
3458/// cross-slot precedence gate `validate_upgrade_from_against_versao`
3459/// (which likewise reads one slot against another at the
3460/// [`crate::layout`] wire-up site) and the mesh self-edge gate
3461/// `AplicacaoSpec`'s `ContratoSelfLoop` — the same "an edge from a graph
3462/// node to itself is structurally not a tree/mesh edge" discipline, here
3463/// on the supervision-tree axis.
3464pub fn validate_no_self_supervision(
3465 children: &[ChildSpec],
3466 parent_nome: &str,
3467) -> Result<(), SupervisorError> {
3468 for child in children {
3469 if child.nome() == parent_nome {
3470 return Err(SupervisorError::child_supervises_self(parent_nome));
3471 }
3472 }
3473 Ok(())
3474}
3475
3476#[derive(Debug, Error, PartialEq, Eq)]
3477pub enum SupervisorError {
3478 #[error("supervisor :estrategia {estrategia:?} requires at least one :children entry")]
3479 NoChildren { estrategia: RestartStrategy },
3480 #[error(
3481 "SimpleOneForOne supervisors must declare zero static children (children spawn dynamically)"
3482 )]
3483 SimpleOneForOneWithStaticChildren,
3484 #[error(":max-restarts must be > 0")]
3485 ZeroMaxRestarts,
3486 #[error(
3487 ":supervisor :max-restarts ({max_restarts}) exceeds the supervisor-policy ceiling \
3488 (SUPERVISOR_MAX_RESTARTS_MAX = 1000) — a value above this cap turns the typed \
3489 restart-intensity policy into a no-op supervisor: the escalation threshold is \
3490 structurally so high that no realistic restarts-per-:restart-window traffic shape \
3491 can reach it, so the supervisor never escalates to its parent and a bad child can \
3492 loop inside the window indefinitely. Every typed-slot consumer (Erlang/OTP's \
3493 MaxIntensity/Period ratio, the future wasm-operator's per-supervisor \
3494 restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
3495 materializer's admission webhook) emits a `:max-restarts` declaration that is \
3496 structurally never reached. Pin a value in 1..=1000 (Erlang/OTP / Elixir / Riak \
3497 Core / RabbitMQ production playbooks recommend 3..=100; the OTP `supervisor` \
3498 callback module's `MaxR = 1` minimal-restart default sits at the bottom of the \
3499 band) or restructure the supervision tree (split the flaky child into its own \
3500 sub-supervisor with a tighter budget) if you need a higher restart tolerance."
3501 )]
3502 MaxRestartsExceedsCap { max_restarts: u32 },
3503 #[error(
3504 ":restart-window must be > 0 when set — Erlang/OTP's MaxIntensity/Period \
3505 requires Period > 0; a zero window either trips on the first failure or \
3506 never trips depending on operator interpretation. Omit :restart-window to \
3507 express `never reset`; carry a positive duration to express the window."
3508 )]
3509 RestartWindowZero,
3510 #[error(
3511 ":supervisor :restart-window ({window:?}) carries a sub-millisecond residue the shared `duration_codec` cannot round-trip — \
3512 the codec truncates to `as_millis()` before picking the canonical unit, so a value with `subsec_nanos() % 1_000_000 != 0` either \
3513 truncates on first serialize (e.g. `Duration::from_micros(1500)` → \"1ms\" → `Duration::from_millis(1)` ≠ original) or renders \
3514 as \"0s\" the `RestartWindowZero` arm then rejects on re-validate. Pin an integer-millisecond magnitude in the canonical authoring form \
3515 (`<integer><unit>` for unit ∈ {{ms, s, m, h}}, e.g. `\"500ms\"`, `\"30s\"`, `\"2m\"`, `\"1h\"`) or omit the field for `never reset`"
3516 )]
3517 RestartWindowNotCanonical { window: Duration },
3518 #[error(
3519 ":supervisor :restart-window ({window:?}) exceeds the supervisor-policy ceiling \
3520 (SUPERVISOR_RESTART_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
3521 per-supervisor rolling-window restart-intensity counter into a lifetime counter: the \
3522 failure-counting window is structurally so long that transient restarts are never \
3523 forgotten, the MaxIntensity/Period ratio degenerates from `trip the parent supervisor \
3524 when the child has exceeded its restart budget within the recent window` to `trip the \
3525 parent when the child has exceeded its restart budget over its lifetime`, and the \
3526 supervisor's reset semantic never reaches the child — every typed-slot consumer \
3527 (Erlang/OTP's MaxIntensity/Period reconciler, the future wasm-operator's \
3528 per-supervisor restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
3529 materializer's admission webhook, the caixa-operator's hierarchical reconciliation \
3530 scheduler) emits a `:restart-window` declaration that is structurally a no-op rolling \
3531 window. Pin a value in 1ms..=1h (Learn You Some Erlang's `{{intensity, 5, 60}}` \
3532 worker-supervisor `Period = 60s` default, Elixir's `Supervisor` `max_seconds: 5` \
3533 default, OTP's `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's \
3534 `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default — every Erlang/OTP \
3535 / Elixir production playbook sits in the 5s..=300s band; the longest documented \
3536 per-supervisor restart-window any pleme-io substrate playbook recommends maxes at \
3537 ~30m) or omit :restart-window to express `never reset` (the supervisor's restart \
3538 budget then becomes a strict lifetime counter by design, not a degenerate one — the \
3539 author surfaces the lifetime-counter semantic explicitly at the slot, rather than \
3540 hiding it behind a rolling-window declaration the cap arm rejects)"
3541 )]
3542 RestartWindowExceedsCap { window: Duration },
3543 #[error("child entry has empty :caixa name")]
3544 EmptyChildName,
3545 #[error(
3546 "child :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
3547 (the K8s apiserver enforces this rule on every `metadata.name` / Service \
3548 name / label value the child name lands in — the per-child \
3549 `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name`, the `LABEL_PROGRAM` \
3550 label value, and the future wasm-operator per-child Service `metadata.name` \
3551 — each apiserver-side schema rejects names that don't match; use a \
3552 lowercase alphanumeric + hyphen identifier like `\"worker\"` or `\"cache-v2\"`)"
3553 )]
3554 ChildCaixaInvalid { caixa: String, reason: String },
3555 #[error("child {caixa:?} has empty :versao constraint")]
3556 EmptyChildVersion { caixa: String },
3557 #[error(
3558 "child {caixa:?} :versao {versao:?} is not a valid semver requirement: \
3559 {reason} (use Cargo-shaped forms like `\"^0.1\"`, `\"~0.1.2\"`, \
3560 `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` and \
3561 `:membros :versao` carry; the lacre pipeline resolves all three \
3562 through the same parser)"
3563 )]
3564 ChildVersaoInvalid {
3565 caixa: String,
3566 versao: String,
3567 reason: String,
3568 },
3569 #[error(
3570 "child {caixa:?} appears more than once (Erlang/OTP requires unique \
3571 child_spec.id per supervisor; duplicate children materialize as duplicate \
3572 ComputeUnits in the rendered chart, one silently overwriting the other)"
3573 )]
3574 DuplicateChildCaixa { caixa: String },
3575 #[error(
3576 "supervisor {caixa:?} lists itself as a :children entry — a supervisor is \
3577 never its own child (the supervision tree is a DAG rooted at the supervisor; \
3578 OTP child specs reference distinct child processes). Since every :nome is a \
3579 globally-unique substrate identity, a child naming the supervisor's own :nome \
3580 is a one-node reconciliation cycle, not a coincidentally-named peer; drop the \
3581 self-referential :children entry or rename it to the actual child caixa."
3582 )]
3583 ChildSupervisesSelf { caixa: String },
3584}
3585
3586// Fold the three `SupervisorError::<Variant> { caixa: <&str>.to_string() }`
3587// caixa-only struct-variant wire-up sites at [`SupervisorSpec::validate_children`]
3588// and [`validate_no_self_supervision`] onto one substrate primitive per
3589// typed variant — the sibling on `SupervisorError` of the four uniform-shape
3590// `LayoutError`-envelope constructor families the peer
3591// [`crate::layout::layout_violation_ctors!`] macro closed (131ca0d, 16
3592// variants on `{ caixa, issue }`), the [`crate::layout::layout_slot_kind_ctors!`]
3593// macro closed (0419438, 4 variants on `{ caixa, kind, slots }`), the
3594// [`crate::LayoutError::missing_entry`] one-variant ctor closed (1b09f9d,
3595// on `{ kind, path }`), and the [`crate::layout::layout_nome_only_ctors!`]
3596// macro closed (3fe3dd7, 6 variants on `<Variant>(String)`), plus the
3597// [`crate::AplicacaoError::entrada_host_invalid`] one-variant ctor
3598// (17dd504, `{ host, reason }`), the [`crate::aplicacao::contrato_target_ctors!`]
3599// macro (14b81d5, 2 variants on `{ de, para, wit, expected }`), and the
3600// [`crate::aplicacao::contrato_empty_pair_ctors!`] macro (8580068, 4
3601// variants on `{ de, para }`) already at that discipline on the peer
3602// `AplicacaoError` envelopes.
3603//
3604// Each of the three wire-up sites on this shape (`EmptyChildVersion` at
3605// the per-`:children` semver-requirement empty-first arm, `DuplicateChildCaixa`
3606// at the per-`:children` dedup arm, `ChildSupervisesSelf` at the cross-slot
3607// self-supervision arm) opened the identical
3608// `SupervisorError::<Variant> { caixa: <&str>.to_string() }` struct-literal —
3609// the exact "same block re-inlined at every consumer" shape the PRIME
3610// DIRECTIVE names as a bug, on the same altitude the peer `LayoutError` /
3611// `AplicacaoError` families each closed on their sibling envelopes. The
3612// three variants share one `{ caixa: String }` shape, so the fold routes
3613// each wire-up site through one dispatch per typed variant.
3614//
3615// The macro below generates one static constructor per variant of shape
3616// `fn <slot>(caixa: &str) -> SupervisorError`, so every wire-up site
3617// collapses onto one dispatch:
3618// `SupervisorError::<slot>(<&str>)`, byte-equal to the pre-lift
3619// struct-literal on the same `&str` fixture. The uniform one-field
3620// construction (`caixa: caixa.to_string()`) is spelled once — inside the
3621// macro — rather than at every wire-up site. Every constructor is
3622// `#[must_use]` so a caller who mistakenly discards the constructed error
3623// trips a compile warning at the wire-up site.
3624//
3625// Every future consumer that wants to construct one of these three
3626// variants outside `SupervisorSpec::validate_children` /
3627// `validate_no_self_supervision` — a deferred
3628// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3629// webhook re-checking one added/renamed child, a future
3630// `feira validate --supervisor` per-caixa admission verb, a per-child
3631// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path
3632// once dynamic-children graduate to a typed slot, a per-Supervisor
3633// overlay resolver rejecting a duplicate/self-supervising child against
3634// a cluster-local snapshot — now reaches each variant through one call
3635// rather than re-inlining the three-line struct-literal in lockstep
3636// with the three in-crate wire-up sites.
3637macro_rules! supervisor_caixa_only_ctors {
3638 ($($ctor:ident => $variant:ident),* $(,)?) => {
3639 impl SupervisorError {
3640 $(
3641 #[doc = concat!(
3642 "Construct a [`SupervisorError::",
3643 stringify!($variant),
3644 "`] naming the offending `:children :caixa` (or ",
3645 "supervisor `:nome`, on the self-supervision arm). ",
3646 "Folds the uniform `Self::",
3647 stringify!($variant),
3648 " { caixa: caixa.to_string() }` one-field ",
3649 "struct-literal onto one substrate primitive so ",
3650 "every [`SupervisorSpec::validate_children`] / ",
3651 "[`validate_no_self_supervision`] wire-up on this ",
3652 "variant reads through one dispatch rather than the ",
3653 "pre-lift open-coded struct-literal block."
3654 )]
3655 #[must_use]
3656 pub fn $ctor(caixa: &str) -> Self {
3657 Self::$variant { caixa: caixa.to_string() }
3658 }
3659 )*
3660 }
3661 };
3662}
3663
3664supervisor_caixa_only_ctors! {
3665 empty_child_version => EmptyChildVersion,
3666 duplicate_child_caixa => DuplicateChildCaixa,
3667 child_supervises_self => ChildSupervisesSelf,
3668}
3669
3670// Fold the two `SupervisorError::{ChildCaixaInvalid, ChildVersaoInvalid}`
3671// struct-variant wire-up sites at [`SupervisorSpec::validate_children`] onto
3672// one substrate primitive per typed variant — the M2 supervisor-side siblings
3673// of the peer [`crate::AplicacaoError::membro_caixa_invalid`] two-slot ctor
3674// already lifted through the sibling
3675// [`crate::aplicacao::aplicacao_field_reason_ctors!`] macro (981060b) on the
3676// peer `AplicacaoError { caixa: String, reason: String }` envelope. The
3677// `ChildCaixaInvalid` variant carries the same `{ <name>: String, reason:
3678// String }` two-slot shape the peer seven-variant
3679// [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold closed on the
3680// `AplicacaoError` envelope (`MembroCaixaInvalid`, `EntradaParaInvalid`,
3681// `EntradaHostInvalid`, `EntradaPathInvalid`, `PlacementClusterInvalid`,
3682// `PlacementAffinityInvalid`, `ShardKeyInvalid`); the `ChildVersaoInvalid`
3683// variant carries the `{ caixa: String, versao: String, reason: String }`
3684// three-slot shape the sibling `AplicacaoError::MembroVersaoInvalid` axis
3685// carries on the same `:versao` value-shape.
3686//
3687// Each of the two wire-up sites opened the same closure-shaped
3688// `|reason| SupervisorError::<Variant> { caixa: child.nome().to_string(),
3689// [versao: child.versao_requirement().to_string(),] reason }` block inside
3690// the paired [`crate::render::require_valid_dns_1123_label`] and
3691// [`crate::render::require_valid_versao_requirement`] callbacks — the exact
3692// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE names
3693// as a bug, on the same altitude the peer `AplicacaoError` /
3694// `SupervisorError` / `LayoutError` / `DepError` / `LimitsError` ctor
3695// families already closed on their sibling envelopes.
3696//
3697// The two `#[must_use]` inherent constructors below fold each wire-up onto
3698// one dispatch: `SupervisorError::child_caixa_invalid(<name>, <reason>)`
3699// and `SupervisorError::child_versao_invalid(<name>, <versao>, <reason>)`,
3700// byte-equal to the pre-lift struct-literal on the same scalar fixtures.
3701// The uniform per-field `.to_string()` / `.into()` construction is spelled
3702// once — inside each ctor body — rather than at every wire-up site. The
3703// `reason: impl Into<String>` bound accepts both `&str` literals and
3704// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
3705// diagnostic shape at the lift, matching the peer
3706// [`aplicacao_field_reason_ctors!`] and
3707// [`crate::aplicacao::contrato_pair_value_reason_ctors!`] bounds on the
3708// sibling envelopes.
3709//
3710// Every future consumer that wants to construct one of these two variants
3711// outside `SupervisorSpec::validate_children` — a deferred
3712// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook
3713// re-checking one added/renamed child's `:caixa` or `:versao`, a future
3714// `feira validate --supervisor` per-caixa admission verb, a per-child
3715// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path once
3716// dynamic-children graduate to a typed slot, a per-Supervisor overlay
3717// resolver rejecting a shape-invalid child `:caixa`/`:versao` against a
3718// cluster-local snapshot — now reaches each variant through one call rather
3719// than re-inlining the per-shape struct-literal block in lockstep with the
3720// two in-crate wire-up sites.
3721impl SupervisorError {
3722 /// Construct a [`SupervisorError::ChildCaixaInvalid`] naming the
3723 /// offending `:children :caixa` value under the given `reason`. Folds
3724 /// the uniform `Self::ChildCaixaInvalid { caixa: caixa.to_string(),
3725 /// reason: reason.into() }` two-slot struct-literal onto one substrate
3726 /// primitive so every wire-up on this variant reads through one
3727 /// dispatch, matching the peer
3728 /// [`crate::AplicacaoError::membro_caixa_invalid`] ctor's shape on the
3729 /// sibling `AplicacaoError { caixa: String, reason: String }`
3730 /// envelope. `reason` accepts both `&str` literals and `format!(…)`
3731 /// outputs through the `impl Into<String>` bound.
3732 #[must_use]
3733 pub fn child_caixa_invalid(caixa: &str, reason: impl Into<String>) -> Self {
3734 Self::ChildCaixaInvalid {
3735 caixa: caixa.to_string(),
3736 reason: reason.into(),
3737 }
3738 }
3739
3740 /// Construct a [`SupervisorError::ChildVersaoInvalid`] naming the
3741 /// offending `:children :caixa` and its `:versao` requirement under
3742 /// the given `reason`. Folds the uniform `Self::ChildVersaoInvalid {
3743 /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
3744 /// reason.into() }` three-slot struct-literal onto one substrate
3745 /// primitive so every wire-up on this variant reads through one
3746 /// dispatch, matching the sibling `AplicacaoError::MembroVersaoInvalid
3747 /// { caixa, versao, reason }` three-slot axis on the peer
3748 /// `AplicacaoError` envelope. `reason` accepts both `&str` literals
3749 /// and `format!(…)` outputs through the `impl Into<String>` bound.
3750 #[must_use]
3751 pub fn child_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
3752 Self::ChildVersaoInvalid {
3753 caixa: caixa.to_string(),
3754 versao: versao.to_string(),
3755 reason: reason.into(),
3756 }
3757 }
3758}
3759
3760// Fold the four `SupervisorError::<Variant> { <field>: <Copy> }` one-field
3761// Copy-scalar struct-variant wire-up sites at [`SupervisorSpec::validate`]'s
3762// three bracket-arms — one struct-literal at the `:children`-empty
3763// non-`SimpleOneForOne` refusal cascade (`NoChildren { estrategia }`) plus
3764// three `impl FnOnce(<ty>) -> SupervisorError` bracket-closures at the
3765// [`crate::render::require_positive_bounded_u32`] `:max-restarts` cap arm
3766// (`MaxRestartsExceedsCap { max_restarts }`) and the paired
3767// [`crate::render::require_positive_canonical_bounded_duration`]
3768// `:restart-window` canonical-form + cap arms (`RestartWindowNotCanonical
3769// { window }`, `RestartWindowExceedsCap { window }`) — onto one substrate
3770// primitive per typed variant, matching the sibling
3771// [`crate::aplicacao::aplicacao_policy_scalar_ctors!`] macro (7ef425e, 8
3772// variants on the same `{ <field>: Duration | u32 }` shape) at that
3773// discipline on the peer `AplicacaoError` envelope's per-`:politicas`
3774// scalar axis. Every variant is a one-field `Copy`-pass-through struct-
3775// literal — `RestartStrategy | u32 | Duration` — so the fold routes each
3776// wire-up site through one dispatch per typed variant without a runtime-
3777// work delta.
3778//
3779// Each of the four wire-up sites opened the identical
3780// `SupervisorError::<Variant> { <field>: <val> }` struct-literal — the
3781// exact "same block re-inlined at every consumer" shape the PRIME
3782// DIRECTIVE names as a bug, on the same altitude the peer
3783// `aplicacao_policy_scalar_ctors!` fold closed on the sibling
3784// `AplicacaoError` envelope's per-`:politicas` per-axis cap / canonical-
3785// form arms. The four variants share one `{ <field>: <Copy> }` shape, so
3786// the fold routes each wire-up site through one dispatch per typed
3787// variant.
3788//
3789// The macro below generates one static constructor per variant of shape
3790// `const fn <ctor>(<field>: <ty>) -> SupervisorError`, so every wire-up
3791// site collapses onto one dispatch: `SupervisorError::<ctor>(<val>)`,
3792// byte-equal to the pre-lift struct-literal on the same `Copy`-`<ty>`
3793// fixture — as a direct call at the [`SupervisorSpec::validate`]
3794// `:children`-empty refusal, or as a bare function pointer in the
3795// `impl FnOnce(<ty>) -> SupervisorError` bracket-closure slot every
3796// [`crate::render::require_positive_bounded_u32`] /
3797// [`crate::render::require_positive_canonical_bounded_duration`] gate
3798// carries — rather than the pre-lift open-coded one-line closure over
3799// the same one-field struct-literal. `const fn` preserves the `Copy`-
3800// pass-through's zero-runtime-work property verbatim. Every constructor
3801// is `#[must_use]` so a caller who mistakenly discards the constructed
3802// error trips a compile warning at the wire-up site.
3803//
3804// Every future consumer that wants to construct one of these four
3805// variants outside `SupervisorSpec::validate` — a deferred
3806// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3807// webhook re-checking one edited `:estrategia` / `:max-restarts` /
3808// `:restart-window` slot against the cap + canonical-form cascade, a
3809// future `feira validate --supervisor` per-caixa admission verb re-
3810// running the shape gates on demand, a per-Supervisor overlay resolver
3811// rejecting an author-supplied slot against a cluster-local snapshot —
3812// now reaches each variant through one call rather than re-inlining the
3813// per-shape struct-literal block in lockstep with the four in-crate
3814// wire-up sites.
3815macro_rules! supervisor_scalar_ctors {
3816 ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
3817 impl SupervisorError {
3818 $(
3819 #[doc = concat!(
3820 "Construct a [`SupervisorError::",
3821 stringify!($variant),
3822 "`] naming the offending per-`:supervisor` `",
3823 stringify!($field),
3824 "` scalar. Folds the uniform `Self::",
3825 stringify!($variant),
3826 " { ",
3827 stringify!($field),
3828 " }` one-field `Copy`-pass-through struct-literal onto ",
3829 "one substrate primitive so every per-axis wire-up on ",
3830 "this variant reads through one dispatch — as a direct ",
3831 "call (`SupervisorError::",
3832 stringify!($ctor),
3833 "(<val>)`, byte-equal to the pre-lift struct-literal on ",
3834 "the same `Copy`-`",
3835 stringify!($ty),
3836 "` fixture) or as a bare function pointer in the ",
3837 "`impl FnOnce(",
3838 stringify!($ty),
3839 ") -> SupervisorError` bracket-closure slot every ",
3840 "`crate::render::require_positive_bounded_*` / ",
3841 "`crate::render::require_positive_canonical_bounded_*` ",
3842 "gate carries — rather than the pre-lift open-coded ",
3843 "one-line closure over the same one-field struct-",
3844 "literal. `const fn` preserves the `Copy`-pass-through's ",
3845 "zero-runtime-work property verbatim."
3846 )]
3847 #[must_use]
3848 pub const fn $ctor($field: $ty) -> Self {
3849 Self::$variant { $field }
3850 }
3851 )*
3852 }
3853 };
3854}
3855
3856supervisor_scalar_ctors! {
3857 no_children => NoChildren { estrategia: RestartStrategy },
3858 max_restarts_exceeds_cap => MaxRestartsExceedsCap { max_restarts: u32 },
3859 restart_window_not_canonical => RestartWindowNotCanonical { window: Duration },
3860 restart_window_exceeds_cap => RestartWindowExceedsCap { window: Duration },
3861}
3862
3863/// Shared duration string codec for the typed slots that take a
3864/// duration (`restart_window`, `MeshPolicy::timeout`,
3865/// `CircuitBreaker::window`, …). Public so [`crate::aplicacao`] can
3866/// reuse it without duplicating the parser.
3867pub mod duration_codec {
3868 use super::Duration;
3869 use serde::{Deserializer, Serializer};
3870
3871 pub fn serialize<S: Serializer>(v: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
3872 // Route through the canonical [`crate::render::serialize_option_via_str`]
3873 // — the substrate-side single-owner primitive for the forward
3874 // arm of the typed-magnitude codec family. See its docstring
3875 // for the full sibling roster.
3876 crate::render::serialize_option_via_str(v, s, render)
3877 }
3878
3879 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
3880 // Route through the canonical [`crate::render::deserialize_option_via_str`]
3881 // — the substrate-side single-owner primitive for the reverse
3882 // arm of the typed-magnitude codec family. See its docstring
3883 // for the full sibling roster.
3884 crate::render::deserialize_option_via_str(d, parse)
3885 }
3886
3887 pub(crate) fn parse(s: &str) -> Result<Duration, String> {
3888 // Paired whitespace-rejection arm — same canonical-form
3889 // render-determinism discipline as the peer
3890 // `limits::parse_byte_size` / `limits::parse_duration` /
3891 // `limits::parse_millicores` /
3892 // `aplicacao::rate_limit_codec::parse` sites: the ASCII
3893 // byte-scan closes the WhatWG-conformant whitespace bytes
3894 // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
3895 // `char::is_whitespace` scan closes the strictly-complementary
3896 // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
3897 // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
3898 // codepoints) that `str::trim` at parse entry silently strips.
3899 // Either drift class would round-trip through `render` to a
3900 // *different* canonical form on next emit — breaking the
3901 // THEORY.md Part V render-determinism contract on three typed-
3902 // duration slots at once (`:supervisor :restart-window`,
3903 // `:politicas :timeout`, `:politicas :circuit-breaker :window`)
3904 // via the shared codec.
3905 //
3906 // Routed through the lifted [`crate::render::reject_whitespace`]
3907 // primitive — the substrate-side single-owner paired-arm gate
3908 // every typed-magnitude codec in caixa-core shares.
3909 crate::render::reject_whitespace::<String, _, _>(
3910 s,
3911 |b| {
3912 format!(
3913 "duration: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
3914 authoring form for the typed duration slots routed through this shared codec \
3915 (`:supervisor :restart-window`, `:politicas :timeout`, \
3916 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
3917 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no whitespace bytes \
3918 anywhere. A whitespace-carrying shape (`\" 30s\"`, `\"30s \"`, `\"30 s\"`, \
3919 `\"\\t30s\"`, `\"30s\\n\"`) round-trips through `render` to a *different* \
3920 canonical form (`\"30s\"`) on first serialize — breaking the THEORY.md \
3921 Part V render-determinism contract every typed slot carries. Strip every \
3922 whitespace byte (write `\"30s\"` verbatim)"
3923 )
3924 },
3925 |ch| {
3926 format!(
3927 "duration: value {s:?} contains non-ASCII Unicode whitespace character \
3928 {ch:?} (U+{cp:04X}) — the canonical authoring form for the typed \
3929 duration slots routed through this shared codec (`:supervisor \
3930 :restart-window`, `:politicas :timeout`, `:politicas :circuit-breaker \
3931 :window`) is `<integer><unit>` (e.g. `\"30s\"`, `\"500ms\"`, `\"2m\"`, \
3932 `\"1h\"`) with no whitespace characters anywhere (ASCII or Unicode). A \
3933 non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}30s\"`, \
3934 `\"30s\\u{{2028}}\"`, `\"30\\u{{2003}}s\"`) survives the ASCII byte-scan \
3935 but `str::trim` (which uses `char::is_whitespace` — the Unicode \
3936 `White_Space` property, strictly wider than the ASCII byte set) silently \
3937 strips it at parse entry, and the value round-trips through `render` to \
3938 a *different* canonical form (`\"30s\"`) on first serialize — breaking \
3939 the THEORY.md Part V render-determinism contract every typed slot \
3940 carries. Strip every non-ASCII whitespace character (write `\"30s\"` \
3941 verbatim with only ASCII bytes)",
3942 cp = ch as u32
3943 )
3944 },
3945 )?;
3946 let s = s.trim();
3947 // Routed through the lifted
3948 // [`crate::render::split_magnitude_and_alpha_unit`] primitive —
3949 // the single-owner split every ASCII-alphabetic-unit typed-
3950 // magnitude codec in caixa-core (`limits::parse_byte_size` /
3951 // `limits::parse_duration` / this shared duration codec) shares.
3952 // See its docstring for the full sibling roster on the same
3953 // primitive altitude.
3954 let (num_part, unit) = crate::render::split_magnitude_and_alpha_unit(s);
3955 let num_trim = num_part.trim();
3956 // The canonical authoring form for every typed slot routed
3957 // through this shared codec — `:supervisor :restart-window`,
3958 // `:politicas :timeout`, `:politicas :circuit-breaker :window`
3959 // — is `<integer><unit>`. Every magnitude [`render`] emits is a
3960 // non-negative integer with no decimal point and no leading
3961 // sign, so the parser's accepted set must match for
3962 // serialize/deserialize to round-trip without canonical-form
3963 // drift. Until this gate landed the parser accepted any
3964 // `f64`-shaped magnitude (`"1.5s"` → 1500ms, `"1.0s"` → 1s,
3965 // `"0.5m"` → 30s, `"+30s"` → 30s) and serde silently round-
3966 // tripped the value to a *different* canonical string on the
3967 // next emit (`"1.5s"` → 1500ms → `"1500ms"`, `"1.0s"` → 1s →
3968 // `"1s"`, `"0.5m"` → 30s → `"30s"`, `"+30s"` → 30s → `"30s"`)
3969 // — breaking the THEORY.md Part V render-determinism contract
3970 // on three typed slots at once. Same canonical-form discipline
3971 // `crate::limits::parse_duration` (818dd38, the immediate
3972 // predecessor on the peer `:limits :wall-clock` codec) applies;
3973 // this gate lifts the discipline onto the shared codec that
3974 // backs the remaining three typed-duration slots in caixa-core.
3975 //
3976 // Strict canonical form: every byte of the magnitude is an
3977 // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
3978 // inputs the gate distinguishes "non-canonical-but-numeric"
3979 // (parses as f64 or i64 — surfaced with a self-locating
3980 // diagnostic naming the canonical authoring form, the
3981 // round-trip drift each rejected shape would produce on first
3982 // serialize, and the canonical-form remediation) from
3983 // "garbage" (parses as neither — surfaced with the existing
3984 // narrower "bad duration magnitude" wording so its diagnostic
3985 // shape remains stable for the parser-shape footgun case).
3986 // The pre-existing `num < 0.0` arm is now unreachable — the
3987 // digit-only gate strictly precedes magnitude parsing, and a
3988 // leading `-` is not an ASCII digit, so `"-30s"` lands on the
3989 // non-canonical-but-numeric branch with the `-30` named
3990 // verbatim in the diagnostic rather than the prior
3991 // value-laundered "negative duration in \"-30s\"" wording.
3992 //
3993 // Routed through the lifted
3994 // [`crate::render::is_digit_only_magnitude`] predicate — the
3995 // same source of truth the four peer typed-magnitude codec
3996 // sites share.
3997 let digit_only = crate::render::is_digit_only_magnitude(num_trim);
3998 if !digit_only {
3999 let numeric = num_trim.parse::<f64>().is_ok() || num_trim.parse::<i64>().is_ok();
4000 if numeric {
4001 return Err(format!(
4002 "duration: magnitude {num_trim:?} is not a non-negative integer — the \
4003 canonical authoring form for the typed duration slots routed through \
4004 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
4005 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
4006 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no decimal point and \
4007 no leading `+` / `-` sign. A fractional / decimal-shaped magnitude \
4008 (`\"1.5s\"`, `\"1.0s\"`, `\"0.5m\"`, `\"+30s\"`, `\"-30s\"`) round-trips \
4009 through `render` to a *different* canonical form (`\"1500ms\"`, `\"1s\"`, \
4010 `\"30s\"`, `\"30s\"`, `\"30s\"`) on first serialize — breaking the \
4011 THEORY.md Part V render-determinism contract every typed slot carries. \
4012 Pick an integer magnitude in the unit that divides cleanly (write \
4013 `\"1500ms\"` instead of `\"1.5s\"`; `\"30s\"` instead of `\"0.5m\"`)"
4014 ));
4015 }
4016 return Err(format!("bad duration magnitude in {s:?}"));
4017 }
4018 // Leading-zero arm — peer with the `rate_limit_codec` leading-
4019 // zero arm (4f46830) on the same canonical-form render-
4020 // determinism axis. The digit-only gate accepts `"030s"`,
4021 // `"00s"`, `"01h"`, `"0500ms"` as `u64::from_str` parses them
4022 // losslessly (= 30, 0, 1, 500), but `render` emits the leading-
4023 // zero-stripped form (`"30s"`, `"0s"`, `"1h"`, `"500ms"`) — a
4024 // *different* canonical string on the next emit, breaking the
4025 // THEORY.md Part V render-determinism contract the same way
4026 // `"+30s"` did before the leading-`+` arm landed. The single-
4027 // byte magnitude `"0"` (or `"0s"` / `"0ms"`) round-trips
4028 // losslessly through `render` (`render(Duration::ZERO)` emits
4029 // `"0s"`) — the downstream semantic-zero gates (e.g.
4030 // `SupervisorError::ZeroRestartWindow` on
4031 // `:supervisor :restart-window`,
4032 // `AplicacaoError::PolicyTimeoutZero` /
4033 // `PolicyCircuitBreakerWindowZero` on the typed `:politicas`
4034 // duration slots) refuse zero-magnitude authoring at the typed-
4035 // validate layer above, so the single-byte `"0"` stays in the
4036 // accepted set at this codec layer and the diagnostic
4037 // partitioning between canonical-form drift (this arm) and
4038 // semantic-zero (the downstream gates) remains stable.
4039 // Peer with the future leading-zero arms on the two remaining
4040 // typed-magnitude codecs the trajectory acknowledges:
4041 // `limits::parse_duration` backing `:limits :wall-clock`,
4042 // `limits::parse_byte_size` backing `:limits :memory` — each
4043 // carries the same canonical-form-drift class today; this
4044 // gate lands the discipline on the shared duration codec
4045 // first because the `rate_limit_codec` predecessor on the
4046 // same canonical-form-drift axis is the closest peer on the
4047 // trajectory.
4048 //
4049 // Routed through the lifted
4050 // [`crate::render::is_leading_zero_padded_magnitude`]
4051 // predicate — the same source of truth the four peer
4052 // typed-magnitude codec sites share.
4053 if crate::render::is_leading_zero_padded_magnitude(num_trim) {
4054 return Err(format!(
4055 "duration: magnitude {num_trim:?} has a non-canonical leading zero — the \
4056 canonical authoring form for the typed duration slots routed through \
4057 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
4058 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
4059 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no leading-zero padding \
4060 on the magnitude. A leading-zero magnitude (`\"030s\"`, `\"00s\"`, \
4061 `\"01h\"`, `\"0500ms\"`) round-trips through `render` to a *different* \
4062 canonical form (`\"30s\"`, `\"0s\"`, `\"1h\"`, `\"500ms\"`) on first \
4063 serialize — breaking the THEORY.md Part V render-determinism contract \
4064 every typed slot carries. Strip the leading zeros (write \
4065 `\"30s\"` instead of `\"030s\"`)"
4066 ));
4067 }
4068 // The digit-only gate guarantees every byte is `[0-9]`, and
4069 // the leading-zero arm above guarantees the magnitude is
4070 // either the single byte `"0"` or starts with `[1-9]`, so
4071 // the only way `u64::from_str` can fail here is overflow (the
4072 // magnitude exceeds `u64::MAX`). Surface that with an
4073 // overflow-shaped wording so the diagnostic names the offending
4074 // magnitude verbatim rather than collapsing onto the
4075 // non-canonical arm. The codec now operates on `u64` end-to-end
4076 // — every accepted magnitude is integer-exact; no f64 mantissa
4077 // drift between author-supplied magnitude and the consumer's
4078 // `Duration` value. Same shape `crate::limits::parse_duration`
4079 // (818dd38) carries on the peer `:limits :wall-clock` axis.
4080 let num: u64 = num_trim.parse::<u64>().map_err(|_| {
4081 format!("bad duration magnitude in {s:?} (digit-only magnitude overflows u64)")
4082 })?;
4083 // Route the `{"ms" | "s" | "" | "m" | "h"} → Duration`
4084 // unit-arm dispatch through the canonical
4085 // [`crate::render::duration_from_integer_magnitude_and_unit`]
4086 // primitive — the substrate-side single-owner unit-dispatch
4087 // table every typed-duration codec in caixa-core routes
4088 // through (peer: `crate::limits::parse_duration` backing
4089 // `:limits :wall-clock`). Every unit conversion is integer-
4090 // exact for an integer magnitude; overflow surfaces via the
4091 // typed `DurationUnitError::Overflow { multiplier }`
4092 // discriminant so this arm reconstructs the pre-lift
4093 // `"duration <num><unit> overflows u64 (magnitude × 60 …)"`
4094 // wording verbatim from `num` / `unit_trim` / the returned
4095 // `multiplier`, and the unknown-unit arm reconstructs the
4096 // pre-lift `"unknown duration unit \"<other>\""` wording from
4097 // the caller-scoped `unit_trim`. Load-bearing pinned by
4098 // `crate::render::tests::duration_from_integer_magnitude_and_unit_matches_pre_lift_unit_dispatch_table`.
4099 let unit_trim = unit.trim();
4100 let dur = crate::render::duration_from_integer_magnitude_and_unit(num, unit_trim).map_err(
4101 |e| match e {
4102 crate::render::DurationUnitError::Overflow { multiplier } => format!(
4103 "duration {num}{unit_trim} overflows u64 (magnitude × {multiplier} > 2^64-1)"
4104 ),
4105 crate::render::DurationUnitError::UnknownUnit => {
4106 format!("unknown duration unit {unit_trim:?}")
4107 }
4108 },
4109 )?;
4110 Ok(dur)
4111 }
4112
4113 /// Render a [`Duration`] in the canonical pleme-io duration string
4114 /// form (`"30s"`, `"1m"`, `"1h"`, `"500ms"`). The same form every
4115 /// caixa typed-duration slot serializes to and the same form K8s
4116 /// Gateway API HTTPRoute `timeouts` / `backendRequest` and Cilium
4117 /// EnvoyConfig per-route timeouts both expect (an integer
4118 /// followed by `s`/`m`/`h`/`ms`, no fractional values, no leading
4119 /// `+`). Lifted to `pub` so caixa-side renderers
4120 /// (`caixa-mesh::gateway_routes`'s :politicas :timeout overlay,
4121 /// the future per-:politicas `CiliumClusterwideEnvoyConfig`
4122 /// emitter, the future caixa-otel collector pipeline emitter) can
4123 /// consume the same canonical formatter without re-inlining the
4124 /// magnitude/unit decision tree (and inheriting the same drift
4125 /// footguns: a subtly different `300ms` vs `0.3s` rendering breaks
4126 /// downstream apply-time parsing in non-obvious ways).
4127 pub fn render(d: Duration) -> String {
4128 let total_ms = d.as_millis();
4129 if total_ms == 0 {
4130 return "0s".into();
4131 }
4132 if total_ms.is_multiple_of(3600 * 1000) {
4133 return format!("{}h", total_ms / (3600 * 1000));
4134 }
4135 if total_ms.is_multiple_of(60 * 1000) {
4136 return format!("{}m", total_ms / (60 * 1000));
4137 }
4138 if total_ms.is_multiple_of(1000) {
4139 return format!("{}s", total_ms / 1000);
4140 }
4141 format!("{total_ms}ms")
4142 }
4143
4144 /// True iff `d` round-trips losslessly through [`render`] + [`parse`].
4145 ///
4146 /// [`render`] truncates a `Duration` to `as_millis()` before picking the
4147 /// largest divisor unit, so any sub-millisecond residue
4148 /// (`d.subsec_nanos() % 1_000_000 != 0`) silently breaks the THEORY.md
4149 /// §V.2.7 render-determinism contract:
4150 ///
4151 /// - `Duration::from_micros(1500)` (= `1_500_000` ns) → `as_millis() == 1`
4152 /// → renders `"1ms"` → parses back to `Duration::from_millis(1)` =
4153 /// `1_000_000` ns ≠ original `1_500_000` ns;
4154 /// - `Duration::from_nanos(1)` (= 1 ns) → `as_millis() == 0` →
4155 /// renders the literal `"0s"`, which the per-axis zero-floor gate
4156 /// on every typed-`Duration` slot then rejects on re-validate.
4157 ///
4158 /// Lifted to a `pub` predicate next to the [`render`] / [`parse`] pair so
4159 /// the codec's round-trippable accepted set lives in exactly one place —
4160 /// every typed-`Duration` slot that routes through this shared codec
4161 /// (`SupervisorSpec::restart_window` via [`super::duration_codec`],
4162 /// [`crate::MeshPolicy::timeout`] / [`crate::CircuitBreaker::window`] via
4163 /// `supervisor::duration_codec` + [`super::duration_codec_required`]) and
4164 /// every typed-`Duration` slot whose own codec shares the same
4165 /// `as_millis()`-truncation shape ([`crate::LimitsSpec::wall_clock`] via
4166 /// [`crate::limits`]'s in-module `parse_duration` / `render_duration`
4167 /// pair) calls this predicate from its `validate()` to bracket the
4168 /// accepted set against the codec's accepted set, structurally. Drift
4169 /// between the codec's granularity and any typed slot's accepted set is
4170 /// then a single-source-of-truth edit at this predicate rather than a
4171 /// silent round-trip break the next consumer discovers at apply time.
4172 ///
4173 /// Peer of [`crate::aplicacao::POLICY_RETRIES_MAX`] /
4174 /// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] and the
4175 /// `is_dns_1123_label` / `is_canonical_rate_limit_window` predicate
4176 /// family — same "typed-slot's valid set matches its codec's accepted
4177 /// set, structurally" discipline carried at the codec layer.
4178 #[must_use]
4179 pub fn is_integer_millisecond_duration(d: Duration) -> bool {
4180 d.subsec_nanos().is_multiple_of(1_000_000)
4181 }
4182}
4183
4184/// Required-Duration variant for fields that aren't Option<Duration>.
4185pub mod duration_codec_required {
4186 use super::Duration;
4187 use serde::{Deserialize, Deserializer, Serializer};
4188
4189 pub fn serialize<S: Serializer>(v: &Duration, s: S) -> Result<S::Ok, S::Error> {
4190 s.serialize_str(&super::duration_codec::render(*v))
4191 }
4192
4193 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
4194 let s = String::deserialize(d)?;
4195 super::duration_codec::parse(&s).map_err(serde::de::Error::custom)
4196 }
4197}
4198
4199#[cfg(test)]
4200mod tests {
4201 use super::*;
4202
4203 fn child(name: &str, ver: &str, restart: RestartPolicy) -> ChildSpec {
4204 ChildSpec {
4205 caixa: name.into(),
4206 versao: ver.into(),
4207 restart,
4208 }
4209 }
4210
4211 #[test]
4212 fn child_spec_string_scalar_accessor_pair_is_const_fn() {
4213 // Fail-before-pass-after pin on [`ChildSpec::nome`] +
4214 // [`ChildSpec::versao_requirement`]'s `const`-eval-surface
4215 // posture. Each accessor projects the per-`:children :caixa`
4216 // / per-`:children :versao` [`String`] storage through the
4217 // `pub const fn` [`String::as_str`] (const-stable since Rust
4218 // 1.87, well within the workspace MSRV) — any future
4219 // accidental downgrade to non-`const` fails the corresponding
4220 // `<name>_via_const_fn` wrapper at caixa-core build time with
4221 // E0015 (`cannot call non-const method`), strictly stronger
4222 // than a runtime `assert!`. Sibling of the peer
4223 // per-M2/M3/universal-axis `String → &str` scalar-accessor
4224 // family pins on the sibling `const`-eval-surface passes
4225 // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
4226 // top-level manifest, [`crate::CaixaVersion::as_str`] at the
4227 // typed-newtype wrapper, [`crate::aplicacao::Membro::nome`] /
4228 // [`crate::aplicacao::Membro::versao_requirement`] at the M3
4229 // membership axis, [`crate::aplicacao::Entrada::hostname`] /
4230 // [`crate::aplicacao::Entrada::destination`] at the M3
4231 // ingress axis,
4232 // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
4233 // M2 upgrade axis, [`crate::dep::Dep::nome`] /
4234 // [`crate::dep::Dep::versao_requirement`] at the dep-graph
4235 // axis, and the per-`:contratos`
4236 // [`crate::aplicacao::WitContract::source`] /
4237 // [`crate::aplicacao::WitContract::destination`] /
4238 // [`crate::aplicacao::WitContract::world_ref`] trio the
4239 // sibling pin at 279823b already anchors).
4240 const fn nome_via_const_fn(c: &ChildSpec) -> &str {
4241 c.nome()
4242 }
4243 const fn versao_via_const_fn(c: &ChildSpec) -> &str {
4244 c.versao_requirement()
4245 }
4246 for (caixa, versao) in [
4247 ("worker-a", "^0.1"),
4248 ("worker-b", "~0.2.3"),
4249 ("collector", "*"),
4250 ] {
4251 let c = child(caixa, versao, RestartPolicy::Permanent);
4252 assert_eq!(nome_via_const_fn(&c), c.nome());
4253 assert_eq!(versao_via_const_fn(&c), c.versao_requirement());
4254 assert_eq!(c.nome(), caixa);
4255 assert_eq!(c.versao_requirement(), versao);
4256 }
4257 }
4258
4259 #[test]
4260 fn supervisor_children_slice_return_accessor_is_const_fn() {
4261 // Fail-before-pass-after pin on [`SupervisorSpec::children`]'s
4262 // `const`-eval-surface posture. The accessor destructures the
4263 // per-`:children` `Vec<ChildSpec>` storage through the
4264 // `pub const fn` [`Vec::as_slice`] (const-stable since Rust
4265 // 1.66, well within the workspace MSRV) — any future
4266 // accidental downgrade to non-`const` fails
4267 // `children_via_const_fn` at caixa-core build time with E0015
4268 // (`cannot call non-const method`), strictly stronger than a
4269 // runtime `assert!`. Sibling of the peer per-M3-mesh-slot
4270 // `Vec → &[T]` slice-return accessor family pin
4271 // [`crate::aplicacao::tests::m3_reference_return_accessor_family_is_const_fn`]
4272 // on the M3 mesh-slot per-`:clusters` / per-`:paths` /
4273 // per-`:membros` / per-`:contratos` slice-return axes, and of
4274 // the peer M2 upgrade-appup axis pin
4275 // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
4276 // on the per-`:upgrade-from :instructions` slice-return axis.
4277 const fn children_via_const_fn(s: &SupervisorSpec) -> &[ChildSpec] {
4278 s.children()
4279 }
4280 // Sweep both the empty-children (leaf-supervisor with no
4281 // static children — the `SimpleOneForOne` dynamic-child
4282 // arm's canonical shape) and the populated-children
4283 // (`OneForOne` / `OneForAll` / `RestForOne` static-child
4284 // arm's canonical shape) axes so the accessor carries a
4285 // const-dispatch pin on both arms.
4286 let s_empty = SupervisorSpec {
4287 estrategia: RestartStrategy::SimpleOneForOne,
4288 max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
4289 restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4290 children: vec![],
4291 };
4292 assert!(children_via_const_fn(&s_empty).is_empty());
4293 assert_eq!(children_via_const_fn(&s_empty), s_empty.children());
4294 let s_full = SupervisorSpec {
4295 estrategia: RestartStrategy::OneForOne,
4296 max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
4297 restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4298 children: vec![
4299 child("worker-a", "^0.1", RestartPolicy::Permanent),
4300 child("worker-b", "~0.2.3", RestartPolicy::Transient),
4301 child("collector", "*", RestartPolicy::Temporary),
4302 ],
4303 };
4304 assert_eq!(children_via_const_fn(&s_full).len(), 3);
4305 assert_eq!(children_via_const_fn(&s_full), s_full.children());
4306 }
4307
4308 #[test]
4309 fn default_has_one_for_one_and_5_restarts_in_60s() {
4310 let s = SupervisorSpec::default();
4311 assert_eq!(s.estrategia, RestartStrategy::OneForOne);
4312 assert_eq!(s.max_restarts, 5);
4313 assert_eq!(s.restart_window, Some(Duration::from_secs(60)));
4314 assert!(s.children.is_empty());
4315 }
4316
4317 #[test]
4318 fn validate_one_for_one_requires_children() {
4319 let mut s = SupervisorSpec::default();
4320 s.children = vec![];
4321 assert!(matches!(
4322 s.validate().unwrap_err(),
4323 SupervisorError::NoChildren { .. }
4324 ));
4325 s.children = vec![child("worker", "^0.1", RestartPolicy::Permanent)];
4326 s.validate().unwrap();
4327 }
4328
4329 #[test]
4330 fn validate_simple_one_for_one_forbids_static_children() {
4331 let mut s = SupervisorSpec {
4332 estrategia: RestartStrategy::SimpleOneForOne,
4333 ..SupervisorSpec::default()
4334 };
4335 s.children
4336 .push(child("w", "^0.1", RestartPolicy::Permanent));
4337 assert_eq!(
4338 s.validate().unwrap_err(),
4339 SupervisorError::SimpleOneForOneWithStaticChildren
4340 );
4341 s.children.clear();
4342 s.validate().unwrap();
4343 }
4344
4345 #[test]
4346 fn validate_rejects_zero_max_restarts() {
4347 let s = SupervisorSpec {
4348 max_restarts: 0,
4349 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4350 ..SupervisorSpec::default()
4351 };
4352 assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
4353 }
4354
4355 // ── upper-cap: SUPERVISOR_MAX_RESTARTS_MAX brackets the typed slot ─────
4356 //
4357 // The cap arm lifts the `:politicas :circuit-breaker :max-failures` /
4358 // `POLICY_BREAKER_MAX_FAILURES_MAX` (2b51ace) discipline onto the peer
4359 // `:supervisor :max-restarts` axis — both fields are "trip the
4360 // next-higher protection layer after N events in a rolling window"
4361 // counters with identical degenerate-at-the-high-end shape, so the
4362 // typed-slot's accepted set lies in `1..=1000` on the supervisor side
4363 // exactly as it lies in `1..=1000` on the breaker side.
4364
4365 #[test]
4366 fn validate_rejects_max_restarts_above_cap() {
4367 // The fail-before-pass-after pin: `SUPERVISOR_MAX_RESTARTS_MAX +
4368 // 1` is structurally one past the cap and silently passed
4369 // validate on every pre-gate codebase because the typed slot's
4370 // only check was the zero-floor arm. The no-op-supervisor vector
4371 // only surfaced at the runtime substrate (Erlang/OTP
4372 // MaxIntensity/Period ratio, the future wasm-operator's
4373 // per-supervisor restart-intensity counter) far from the source
4374 // caixa.lisp with no field naming the offending supervisor.
4375 let s = SupervisorSpec {
4376 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4377 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4378 ..SupervisorSpec::default()
4379 };
4380 assert_eq!(
4381 s.validate().unwrap_err(),
4382 SupervisorError::MaxRestartsExceedsCap {
4383 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4384 }
4385 );
4386 }
4387
4388 #[test]
4389 fn validate_rejects_max_restarts_far_above_cap() {
4390 // The `u32::MAX` worst case — the four-billion-restart
4391 // threshold a typo (`:max-restarts 4294967295`) or a
4392 // struct-literal copy-paste lands in the slot. Pin the cap
4393 // arm's coverage explicitly across the full `u32` overflow so
4394 // a future relaxation that drops the upper bound surfaces
4395 // here. Same shape every other typed-cap arm on this surface
4396 // carries (POLICY_BREAKER_MAX_FAILURES_MAX,
4397 // POLICY_RETRIES_MAX, POLICY_RATE_LIMIT_MAX).
4398 let s = SupervisorSpec {
4399 max_restarts: u32::MAX,
4400 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4401 ..SupervisorSpec::default()
4402 };
4403 assert_eq!(
4404 s.validate().unwrap_err(),
4405 SupervisorError::MaxRestartsExceedsCap {
4406 max_restarts: u32::MAX,
4407 }
4408 );
4409 }
4410
4411 #[test]
4412 fn validate_accepts_max_restarts_at_cap() {
4413 // The boundary value — exactly SUPERVISOR_MAX_RESTARTS_MAX —
4414 // must validate. The cap is inclusive on the top edge,
4415 // matching the POLICY_BREAKER_MAX_FAILURES_MAX /
4416 // POLICY_RETRIES_MAX / LIMITS_MEMORY_WASM32_MAX_BYTES
4417 // discipline on the sibling capped axes. Pin the boundary
4418 // explicitly so a future off-by-one tightening
4419 // (`>= SUPERVISOR_MAX_RESTARTS_MAX` instead of `>`) surfaces
4420 // here as a test failure rather than a silent contract
4421 // narrowing.
4422 let s = SupervisorSpec {
4423 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX,
4424 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4425 ..SupervisorSpec::default()
4426 };
4427 s.validate()
4428 .expect("max_restarts == SUPERVISOR_MAX_RESTARTS_MAX must validate");
4429 }
4430
4431 #[test]
4432 fn validate_accepts_max_restarts_typical_values() {
4433 // The documented production-playbook band positive-control
4434 // sweep — every value Erlang/OTP / Elixir / Riak Core /
4435 // RabbitMQ recommend (1..=100) must pass, plus a sweep
4436 // through the hyperscale band (200, 500, 1000) the cap
4437 // accepts. Pin the inclusive validated set explicitly so a
4438 // future tightening of the ceiling surfaces here.
4439 for n in [1u32, 3, 5, 10, 20, 50, 100, 200, 500, 1000] {
4440 let s = SupervisorSpec {
4441 max_restarts: n,
4442 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4443 ..SupervisorSpec::default()
4444 };
4445 s.validate()
4446 .unwrap_or_else(|e| panic!("max_restarts={n} must validate; got {e:?}"));
4447 }
4448 }
4449
4450 #[test]
4451 fn zero_max_restarts_takes_precedence_over_cap() {
4452 // The cross-arm ordering pin: `0` is structurally outside
4453 // both `1..` (zero-floor) and `..=SUPERVISOR_MAX_RESTARTS_MAX`
4454 // (cap), but the zero-floor diagnostic is the more
4455 // self-locating one (it directly names the counter-axis
4456 // remediation), so the validate gate must fire on zero first.
4457 // Same shape every other zero-then-shape ordering on this
4458 // surface uses (PolicyRetriesZero then
4459 // PolicyRetriesExceedsCap; PolicyBreakerZeroFailures then
4460 // PolicyBreakerMaxFailuresExceedsCap).
4461 let s = SupervisorSpec {
4462 max_restarts: 0,
4463 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4464 ..SupervisorSpec::default()
4465 };
4466 assert_eq!(
4467 s.validate().unwrap_err(),
4468 SupervisorError::ZeroMaxRestarts,
4469 "max_restarts == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
4470 );
4471 }
4472
4473 #[test]
4474 fn max_restarts_cap_takes_precedence_over_restart_window_gates() {
4475 // The cross-arm ordering pin between the cap and the sibling
4476 // `:restart-window` gates (zero-window, canonical-window). A
4477 // supervisor carrying both an over-cap `max_restarts` AND a
4478 // structurally invalid window (zero, sub-ms) must surface the
4479 // cap diagnostic first — the cap arm is wired immediately
4480 // after the zero-restart arm and strictly before the window
4481 // arms, so the offending value the diagnostic names matches
4482 // the order the author would discover the gates by reading
4483 // top-to-bottom through `SupervisorSpec::validate`. Pin the
4484 // order so a future refactor that reorders the arms surfaces
4485 // here as a test failure rather than a silent diagnostic
4486 // regression. Peer of
4487 // `circuit_breaker_max_failures_cap_takes_precedence_over_window_gates`
4488 // on the sibling `:politicas :circuit-breaker` slot.
4489 let s = SupervisorSpec {
4490 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4491 restart_window: Some(Duration::ZERO),
4492 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4493 ..SupervisorSpec::default()
4494 };
4495 assert_eq!(
4496 s.validate().unwrap_err(),
4497 SupervisorError::MaxRestartsExceedsCap {
4498 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4499 },
4500 "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
4501 );
4502 }
4503
4504 #[test]
4505 fn max_restarts_cap_diagnostic_carries_offending_value() {
4506 // The diagnostic-shape pin: the offending `u32` is carried
4507 // verbatim into the `SupervisorError::MaxRestartsExceedsCap`
4508 // variant so the surfaced error message names the value the
4509 // author wrote (`":supervisor :max-restarts (50000) exceeds the
4510 // supervisor-policy ceiling …"`), not just the cap. Same
4511 // self-locating diagnostic shape every other typed-cap arm on
4512 // this surface carries
4513 // (`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` carries
4514 // the offending failure count verbatim,
4515 // `AplicacaoError::PolicyRetriesExceedsCap` carries the offending
4516 // retries count verbatim).
4517 let s = SupervisorSpec {
4518 max_restarts: 50_000,
4519 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4520 ..SupervisorSpec::default()
4521 };
4522 let err = s.validate().unwrap_err();
4523 assert!(
4524 matches!(
4525 err,
4526 SupervisorError::MaxRestartsExceedsCap {
4527 max_restarts: 50_000
4528 }
4529 ),
4530 "got {err:?}"
4531 );
4532 let msg = err.to_string();
4533 assert!(
4534 msg.contains("50000"),
4535 ":supervisor :max-restarts cap diagnostic must carry the offending value verbatim (got: {msg})"
4536 );
4537 }
4538
4539 #[test]
4540 fn supervisor_max_restarts_default_pins_otp_canonical_value() {
4541 // Pin [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] at `5` — the
4542 // Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
4543 // half of Learn You Some Erlang's worker-supervisor default,
4544 // sibling of the `60s` `Period` half that the paired
4545 // [`Default for SupervisorSpec`] impl already pins on the
4546 // sibling `restart_window` axis. Pinning the literal here
4547 // surfaces a future rebrand (a tightening to Elixir's `3`,
4548 // a widening to a per-cluster overlay the operator pins
4549 // through a future `:max-restarts-overrides` slot) as a
4550 // deliberate test edit, not a silent contract migration.
4551 // Peer of the sibling
4552 // [`supervisor_max_restarts_cap_pins_canonical_value`]
4553 // upper-bracket pin on the same axis.
4554 assert_eq!(SUPERVISOR_MAX_RESTARTS_DEFAULT, 5);
4555 }
4556
4557 #[test]
4558 fn default_max_restarts_helper_routes_through_lifted_default() {
4559 // Composition pin: the private `default_max_restarts()`
4560 // serde-`#[serde(default = "…")]` helper on
4561 // [`SupervisorSpec::max_restarts`] must route through the
4562 // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
4563 // typed `pub const` rather than a raw `5` literal. Prior to
4564 // the lift the helper carried an inline `5` with no compile-
4565 // time link back to the shared default, so the wire-format
4566 // author-omitted arm and the caixa-core
4567 // [`crate::manifest::Caixa::supervisor_view`] fold's `unwrap_or(5)`
4568 // arm could silently split on any future default rebrand.
4569 // Byte-parity against the lifted constant closes the split.
4570 assert_eq!(default_max_restarts(), SUPERVISOR_MAX_RESTARTS_DEFAULT);
4571 }
4572
4573 #[test]
4574 fn supervisor_spec_default_max_restarts_routes_through_lifted_default() {
4575 // Composition pin: the [`Default for SupervisorSpec`] impl's
4576 // struct-literal `max_restarts` field must route through the
4577 // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
4578 // typed `pub const` (via the private helper this test's
4579 // sibling `default_max_restarts_helper_routes_through_lifted_default`
4580 // already pins onto the constant). Structurally: every
4581 // `SupervisorSpec::default()` call must yield a
4582 // `max_restarts` field byte-equal to the lifted constant
4583 // (the two paired defaults — the serde-side wire-format arm
4584 // and the struct-literal default arm — cannot silently split
4585 // on any future default rebrand). Peer of the sibling
4586 // `default_has_one_for_one_and_5_restarts_in_60s` shape pin
4587 // — this pin closes the byte-parity arm on the two paired
4588 // altitude entry points onto the shared substrate constant.
4589 assert_eq!(
4590 SupervisorSpec::default().max_restarts(),
4591 SUPERVISOR_MAX_RESTARTS_DEFAULT,
4592 );
4593 }
4594
4595 #[test]
4596 fn supervisor_restart_window_default_pins_otp_canonical_value() {
4597 // Pin [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] at `60s` — the
4598 // Erlang/OTP-canonical `{intensity, 5, 60}` `Period` half of
4599 // Learn You Some Erlang's worker-supervisor default, paired
4600 // with the sibling `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5`
4601 // `MaxIntensity` half this constant is the sliding-window
4602 // denominator of on the same `MaxIntensity / Period`
4603 // restart-intensity ratio. Pinning the literal here surfaces a
4604 // future coherent rebrand of the paired default (Elixir's
4605 // `{max_restarts: 3, max_seconds: 5}`, a per-cluster overlay
4606 // the operator pins through a future
4607 // `:restart-window-overrides` slot) as a deliberate test edit,
4608 // not a silent contract migration. Peer of the sibling
4609 // [`supervisor_max_restarts_default_pins_otp_canonical_value`]
4610 // paired-half pin on the same OTP-canonical default and the
4611 // [`supervisor_restart_window_cap_pins_canonical_value`]
4612 // upper-bracket pin on the same axis.
4613 assert_eq!(SUPERVISOR_RESTART_WINDOW_DEFAULT, Duration::from_secs(60),);
4614 }
4615
4616 #[test]
4617 fn supervisor_spec_default_restart_window_routes_through_lifted_default() {
4618 // Composition pin: the [`Default for SupervisorSpec`] impl's
4619 // struct-literal `restart_window` field must route through the
4620 // substrate-canonical [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
4621 // typed `pub const` rather than a raw
4622 // `Duration::from_secs(60)` literal. Prior to this lift the
4623 // paired `{intensity, 5, 60}` OTP-canonical default was split
4624 // across two altitudes with no compile-time link between the
4625 // halves — the `MaxIntensity` half rode through the lifted
4626 // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant while the
4627 // `Period` half rode as an open-coded literal at the
4628 // composition site, so a future coherent rebrand of the paired
4629 // canonical would have had to migrate one half through the
4630 // constant and the other through a raw literal in lockstep.
4631 // Byte-parity against the lifted constant on the `Period` half
4632 // closes the split — the paired OTP-canonical default now
4633 // migrates as one unit on any future axis change. Peer of the
4634 // sibling
4635 // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
4636 // byte-parity pin on the paired `MaxIntensity` half.
4637 assert_eq!(
4638 SupervisorSpec::default().restart_window(),
4639 Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4640 );
4641 }
4642
4643 #[test]
4644 fn supervisor_estrategia_default_pins_otp_canonical_value() {
4645 // Pin [`SUPERVISOR_ESTRATEGIA_DEFAULT`] at [`RestartStrategy::OneForOne`]
4646 // — the Erlang/OTP-canonical `one_for_one` half of Learn You Some
4647 // Erlang's `{one_for_one, intensity, 5, 60}` worker-supervisor
4648 // canonical default, paired with the sibling
4649 // `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5` `MaxIntensity` half and the
4650 // sibling `SUPERVISOR_RESTART_WINDOW_DEFAULT` `60s` `Period` half
4651 // this constant is the strategy discriminator of on the same
4652 // OTP-canonical worker-supervisor default. Pinning the arm here
4653 // surfaces a future coherent rebrand of the paired triple (Elixir's
4654 // `{:one_for_one, max_restarts: 3, max_seconds: 5}` on the sibling
4655 // intensity/period axes leaving this strategy arm untouched, an OTP
4656 // `rest_for_one` widening once the substrate discovers startup-
4657 // order-coupled child cohorts as the more common worker-supervisor
4658 // shape, a per-cluster overlay the operator pins through a future
4659 // `:estrategia-overrides` slot the MESH-COMPOSITION §III.2
4660 // supervision-canary roadmap acknowledges) as a deliberate test
4661 // edit, not a silent contract migration. Peer of the sibling
4662 // [`supervisor_max_restarts_default_pins_otp_canonical_value`] +
4663 // [`supervisor_restart_window_default_pins_otp_canonical_value`]
4664 // paired-half pins on the same OTP-canonical default.
4665 assert_eq!(SUPERVISOR_ESTRATEGIA_DEFAULT, RestartStrategy::OneForOne);
4666 }
4667
4668 #[test]
4669 fn restart_strategy_default_routes_through_lifted_default() {
4670 // Composition pin: the [`Default for RestartStrategy`] impl's
4671 // return arm must route through the substrate-canonical
4672 // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
4673 // a raw `Self::OneForOne` arm. Prior to the lift the impl carried
4674 // an inline `Self::OneForOne` with no compile-time link back to
4675 // the shared OTP-canonical `one_for_one` strategy the paired
4676 // [`Default for SupervisorSpec`] impl's struct-literal `estrategia`
4677 // field and the [`crate::manifest::Caixa::supervisor_view`] fold's
4678 // `.unwrap_or_default()` (now
4679 // `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)`) arm both key off —
4680 // so a future rebrand of the OTP-canonical strategy default (an
4681 // OTP `rest_for_one` widening once the substrate discovers
4682 // startup-order-coupled child cohorts as the more common worker-
4683 // supervisor shape, a per-cluster overlay the operator pins
4684 // through a future `:estrategia-overrides` slot) would have had to
4685 // be threaded through the `Default` impl and the two peer routes
4686 // in lockstep or the three consumers would silently split. Byte-
4687 // parity against the lifted constant closes the split. Peer of
4688 // the sibling
4689 // [`default_max_restarts_helper_routes_through_lifted_default`] +
4690 // [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
4691 // composition pins on the paired `MaxIntensity` + `Period` halves.
4692 assert_eq!(RestartStrategy::default(), SUPERVISOR_ESTRATEGIA_DEFAULT,);
4693 }
4694
4695 #[test]
4696 fn supervisor_spec_default_estrategia_routes_through_lifted_default() {
4697 // Composition pin: the [`Default for SupervisorSpec`] impl's
4698 // struct-literal `estrategia` field must route through the
4699 // substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed
4700 // `pub const` (either directly, or via the
4701 // [`RestartStrategy::default`] impl that the sibling
4702 // `restart_strategy_default_routes_through_lifted_default` pin
4703 // already routes onto the constant). Structurally: every
4704 // `SupervisorSpec::default()` call must yield an `estrategia`
4705 // field byte-equal to the lifted constant (the three paired
4706 // defaults — the [`Default for RestartStrategy`] impl arm, the
4707 // struct-literal default arm here, and the
4708 // [`crate::manifest::Caixa::supervisor_view`] fold arm — cannot
4709 // silently split on any future default rebrand). Peer of the
4710 // sibling
4711 // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
4712 // + [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
4713 // byte-parity pins on the paired `MaxIntensity` + `Period` halves
4714 // of the same `SupervisorSpec::default()` composed altitude.
4715 assert_eq!(
4716 SupervisorSpec::default().estrategia(),
4717 SUPERVISOR_ESTRATEGIA_DEFAULT,
4718 );
4719 }
4720
4721 #[test]
4722 fn supervisor_spec_default_routes_through_otp_canonical_ctor() {
4723 // Composition pin: the [`Default for SupervisorSpec`] impl must
4724 // route through the substrate-canonical
4725 // [`SupervisorSpec::otp_canonical`] `pub const fn` constructor
4726 // rather than a re-hand-authored struct-literal cascade. Sharpens
4727 // the sibling per-arm
4728 // `supervisor_spec_default_*_routes_through_lifted_default` pins
4729 // from a per-field lift into a whole-struct one-source-of-truth
4730 // pin — the derived-until-now [`Default::default`] and the
4731 // [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
4732 // construction, not by coincidence.
4733 //
4734 // A future extension of the OTP-canonical baseline (a fifth
4735 // `restart_intensity` field the Erlang/OTP `#supervisor` record
4736 // grows, a per-child-cohort split of the `restart_window` /
4737 // `max_restarts` pair, an M4 `mesh.pleme.io/v1alpha1/Supervisor`
4738 // CR materializer's admission-time overlay pass) reaches both
4739 // paths through exactly one edit on
4740 // [`SupervisorSpec::otp_canonical`] — the derived path could
4741 // silently disagree with the constructor's shape on any new
4742 // field whose [`Default::default`] resolves to a different arm
4743 // than the OTP-canonical baseline the constructor names, while
4744 // this delegated impl reaches the constructor directly and
4745 // picks up every future extension by construction.
4746 //
4747 // Fourth peer on the M2 / M3 typed-slot-spec
4748 // [`Default`]-through-const-ctor fold family — sibling of the
4749 // [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
4750 // (abd52c2), [`crate::aplicacao::MeshPolicy`]
4751 // [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`]
4752 // (91641a4), and [`crate::BehaviorSpec`]
4753 // [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c)
4754 // per-`Option`-only-typed-slot folds — extended here onto the
4755 // M2 supervisor-slot [`SupervisorSpec`] whose canonical baseline
4756 // is not "everything `None`" but the Erlang/OTP-canonical
4757 // `{one_for_one, 5, 60}` worker-supervisor triple.
4758 assert_eq!(SupervisorSpec::default(), SupervisorSpec::otp_canonical());
4759 }
4760
4761 #[test]
4762 fn supervisor_spec_otp_canonical_byte_equals_default() {
4763 // Value pin: [`SupervisorSpec::otp_canonical`] must byte-equal
4764 // the hand-authored `{one_for_one, 5, 60, []}` OTP-canonical
4765 // baseline the sibling `default_has_one_for_one_and_5_restarts_in_60s`
4766 // pin already asserts against the [`Default::default`] path.
4767 // Sharpens the pair-invariant into a per-constructor pin so a
4768 // future extension of [`SupervisorSpec`] with a fifth field
4769 // whose OTP-canonical shape is non-`Default::default`-equivalent
4770 // trips at caixa-core test time rather than at a downstream
4771 // consumer that composed [`SupervisorSpec::otp_canonical`] with
4772 // [`SupervisorSpec::validate`] as its "canonical baseline
4773 // seed".
4774 let canonical = SupervisorSpec::otp_canonical();
4775 assert_eq!(canonical.estrategia, RestartStrategy::OneForOne);
4776 assert_eq!(canonical.max_restarts, 5);
4777 assert_eq!(canonical.restart_window, Some(Duration::from_secs(60)));
4778 assert!(canonical.children.is_empty());
4779 }
4780
4781 #[test]
4782 fn supervisor_spec_otp_canonical_is_usable_in_const_context() {
4783 // Const-context pin: [`SupervisorSpec::otp_canonical`] must
4784 // remain callable from a `const`-bound position so downstream
4785 // `const`-context callers wanting a canonical OTP-baseline seed
4786 // can construct one at compile time without runtime dispatch on
4787 // the derived [`Default::default`]. Peer of the sibling
4788 // `pub const fn` [`crate::LimitsSpec::empty`] /
4789 // [`crate::aplicacao::MeshPolicy::empty`] /
4790 // [`crate::BehaviorSpec::empty`] constructors on the sibling
4791 // typed-slot-spec `pub const fn` axis. If a future edit breaks
4792 // the `const`-eligibility of [`SupervisorSpec::otp_canonical`]
4793 // (a non-`const` field-default helper, a non-`const`-stable
4794 // container type promotion), this evaluation fails at
4795 // build time on this file rather than at a downstream
4796 // `const`-context call site.
4797 const CANONICAL: SupervisorSpec = SupervisorSpec::otp_canonical();
4798 assert_eq!(CANONICAL.estrategia, SUPERVISOR_ESTRATEGIA_DEFAULT);
4799 assert_eq!(CANONICAL.max_restarts, SUPERVISOR_MAX_RESTARTS_DEFAULT);
4800 assert_eq!(
4801 CANONICAL.restart_window,
4802 Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4803 );
4804 assert!(CANONICAL.children.is_empty());
4805 }
4806
4807 #[test]
4808 fn supervisor_child_restart_default_pins_otp_canonical_value() {
4809 // Pin [`SUPERVISOR_CHILD_RESTART_DEFAULT`] at
4810 // [`RestartPolicy::Permanent`] — Erlang/OTP's `permanent`
4811 // worker-child restart type (`{ChildId, StartFunc, permanent, …}`
4812 // in a `supervisor`'s `init/1` child-spec tuple), the per-child
4813 // half of the same OTP-shape supervisor-tree default set whose
4814 // per-`:supervisor` halves the sibling
4815 // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
4816 // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] /
4817 // [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] constants pin. Pinning the
4818 // arm here surfaces a future rebrand of the per-child default (an
4819 // OTP-`transient` widening once the substrate discovers clean-
4820 // completion-aware children as the more common child shape, a
4821 // per-cluster overlay the operator pins through a future
4822 // `:restart-overrides` slot the MESH-COMPOSITION §III.2
4823 // supervision-canary roadmap acknowledges) as a deliberate test
4824 // edit, not a silent contract migration. Peer of the sibling
4825 // [`supervisor_estrategia_default_pins_otp_canonical_value`] /
4826 // [`supervisor_max_restarts_default_pins_otp_canonical_value`] /
4827 // [`supervisor_restart_window_default_pins_otp_canonical_value`]
4828 // value pins on the per-`:supervisor` halves.
4829 assert_eq!(SUPERVISOR_CHILD_RESTART_DEFAULT, RestartPolicy::Permanent);
4830 }
4831
4832 #[test]
4833 fn restart_policy_default_routes_through_lifted_default() {
4834 // Composition pin: the [`Default for RestartPolicy`] impl's return
4835 // arm must route through the substrate-canonical
4836 // [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const` rather
4837 // than a raw `Self::Permanent` arm. Prior to the lift the impl
4838 // carried an inline `Self::Permanent` with no compile-time link
4839 // back to the OTP-shape supervisor-tree default set whose three
4840 // per-`:supervisor` halves already rode through lifted constants
4841 // — so a future coherent rebrand of the set would have had to
4842 // migrate three halves through typed constants and this fourth
4843 // through a raw enum arm in lockstep or the supervisor-level and
4844 // child-level defaults would silently drift apart. Byte-parity
4845 // against the lifted constant closes the split. Peer of the
4846 // sibling
4847 // [`restart_strategy_default_routes_through_lifted_default`]
4848 // composition pin on the per-`:supervisor` `:estrategia` axis.
4849 assert_eq!(RestartPolicy::default(), SUPERVISOR_CHILD_RESTART_DEFAULT);
4850 }
4851
4852 #[test]
4853 fn child_spec_serde_default_restart_routes_through_lifted_default() {
4854 // Composition pin: the serde-side `#[serde(default)]` on
4855 // [`ChildSpec::restart`] — the wire-format author-omitted
4856 // `:children :restart` arm — must resolve onto the substrate-
4857 // canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const`
4858 // (via the [`Default for RestartPolicy`] impl the sibling
4859 // `restart_policy_default_routes_through_lifted_default` pin
4860 // already routes onto the constant). Structurally: a `ChildSpec`
4861 // deserialized from a payload that omits the `restart` key must
4862 // yield a `restart` field byte-equal to the lifted constant, so
4863 // the wire-format author-omitted arm and the
4864 // [`RestartPolicy::default`] impl arm cannot silently split on any
4865 // future default rebrand. Peer of the sibling
4866 // [`supervisor_spec_default_estrategia_routes_through_lifted_default`]
4867 // / [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
4868 // / [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
4869 // byte-parity pins on the per-`:supervisor` halves of the same
4870 // author-omitted-slot resolution surface.
4871 let omitted: ChildSpec = serde_json::from_str(r#"{"caixa":"worker","versao":"^0.1"}"#)
4872 .expect("ChildSpec must deserialize with the restart key omitted");
4873 assert_eq!(
4874 omitted.restart(),
4875 SUPERVISOR_CHILD_RESTART_DEFAULT,
4876 "an author-omitted :children :restart slot must degrade onto \
4877 the SUPERVISOR_CHILD_RESTART_DEFAULT typed pub const (got \
4878 {:?}, expected {:?})",
4879 omitted.restart(),
4880 SUPERVISOR_CHILD_RESTART_DEFAULT,
4881 );
4882 }
4883
4884 #[test]
4885 fn supervisor_max_restarts_cap_pins_canonical_value() {
4886 // The SUPERVISOR_MAX_RESTARTS_MAX constant pins the value at
4887 // 1000 — the same ceiling the peer
4888 // POLICY_BREAKER_MAX_FAILURES_MAX cap carries on the
4889 // `:politicas :circuit-breaker :max-failures` axis (both are
4890 // "trip the next-higher protection layer after N events in a
4891 // rolling window" counters with identical
4892 // degenerate-at-the-high-end shape; uniform top edge so the
4893 // M4 CR materializers and the wasm-operator reconciler reach
4894 // for either field knowing the value is in `1..=1000`). Two
4895 // orders of magnitude above every documented Erlang/OTP /
4896 // Elixir / Riak Core / RabbitMQ production-playbook
4897 // recommendation band and below the clearly-pathological
4898 // "effectively no escalation" floor (10_000, 100_000,
4899 // u32::MAX). Pinning the literal value here surfaces a future
4900 // drift (a relaxation to 10_000, a tightening to 100) as a
4901 // deliberate test edit, not a silent contract narrowing.
4902 assert_eq!(SUPERVISOR_MAX_RESTARTS_MAX, 1000);
4903 }
4904
4905 #[test]
4906 fn validate_rejects_empty_child_name() {
4907 let s = SupervisorSpec {
4908 children: vec![child("", "^0.1", RestartPolicy::Permanent)],
4909 ..SupervisorSpec::default()
4910 };
4911 assert_eq!(s.validate().unwrap_err(), SupervisorError::EmptyChildName);
4912 }
4913
4914 #[test]
4915 fn validate_rejects_empty_child_version() {
4916 let s = SupervisorSpec {
4917 children: vec![child("w", "", RestartPolicy::Permanent)],
4918 ..SupervisorSpec::default()
4919 };
4920 assert!(matches!(
4921 s.validate().unwrap_err(),
4922 SupervisorError::EmptyChildVersion { .. }
4923 ));
4924 }
4925
4926 // ── value-shape: parse-as-VersionReq on :children :versao ─────────────
4927
4928 #[test]
4929 fn validate_rejects_invalid_child_versao_requirement() {
4930 // The fail-before-pass-after pin: a non-empty but malformed
4931 // semver requirement (`"^bad-version"`) silently passed
4932 // `validate()` on every pre-gate codebase because the prior
4933 // shape only refused the empty string. The parse failure
4934 // surfaced far downstream at lacre-resolve time with a
4935 // `semver::Error` that didn't name which `:children` entry
4936 // carried the typo. The new gate moves the check to caixa-build
4937 // time at the source caixa.lisp — the third `:versao` typed
4938 // axis (`:children`) joins `:deps` and `:membros` (9888b13) at
4939 // structural parity.
4940 let s = SupervisorSpec {
4941 children: vec![
4942 child("worker", "^0.1", RestartPolicy::Permanent),
4943 child("cache", "^bad-version", RestartPolicy::Transient),
4944 ],
4945 ..SupervisorSpec::default()
4946 };
4947 let err = s.validate().unwrap_err();
4948 assert!(
4949 matches!(
4950 err,
4951 SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
4952 if caixa == "cache" && versao == "^bad-version"
4953 ),
4954 "got {err:?}"
4955 );
4956 }
4957
4958 #[test]
4959 fn validate_rejects_child_versao_with_double_caret_typo() {
4960 // `"^^0.1"` is the canonical doubled-caret typo — looks
4961 // Cargo-shaped on first glance but fails the parser because
4962 // semver doesn't accept stacked operators. Pin this
4963 // adjacent-shape footgun explicitly so a future relaxation that
4964 // accepts "looks-canonical-but-isn't" forms surfaces here.
4965 let s = SupervisorSpec {
4966 children: vec![child("worker", "^^0.1", RestartPolicy::Permanent)],
4967 ..SupervisorSpec::default()
4968 };
4969 let err = s.validate().unwrap_err();
4970 assert!(
4971 matches!(
4972 err,
4973 SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
4974 if caixa == "worker" && versao == "^^0.1"
4975 ),
4976 "got {err:?}"
4977 );
4978 }
4979
4980 #[test]
4981 fn validate_rejects_child_versao_with_v_prefixed_tag() {
4982 // `"v0.1"` is the canonical "git-tag-shape leaking into the
4983 // semver requirement slot" typo — an author copies the
4984 // publish-side git-tag string verbatim into `:versao`, but
4985 // Cargo's semver parser rejects the leading `v`. Same
4986 // adjacent-shape footgun pinned for `:membros :versao`
4987 // (9888b13).
4988 let s = SupervisorSpec {
4989 children: vec![child("worker", "v0.1", RestartPolicy::Permanent)],
4990 ..SupervisorSpec::default()
4991 };
4992 let err = s.validate().unwrap_err();
4993 assert!(
4994 matches!(
4995 err,
4996 SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
4997 if caixa == "worker" && versao == "v0.1"
4998 ),
4999 "got {err:?}"
5000 );
5001 }
5002
5003 #[test]
5004 fn validate_accepts_canonical_child_versao_forms() {
5005 // The Cargo-shaped requirement forms `:deps :versao` and
5006 // `:membros :versao` already accept via
5007 // `crate::parse_requirement` must pass the children gate
5008 // without re-validating at the resolver layer. Pin every leg so
5009 // a future tightening of the canonical set surfaces here as a
5010 // test failure.
5011 for form in [
5012 "^0.1", // caret — minor-range pin (the most common shape)
5013 "~0.1.2", // tilde — patch-range pin
5014 "0.1.0", // exact — single-version pin
5015 "*", // wildcard — any version (semver::VersionReq::STAR)
5016 ">=0.1, <2", // multi-range — comma-separated comparators
5017 ] {
5018 let s = SupervisorSpec {
5019 children: vec![child("worker", form, RestartPolicy::Permanent)],
5020 ..SupervisorSpec::default()
5021 };
5022 s.validate()
5023 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
5024 }
5025 }
5026
5027 #[test]
5028 fn child_versao_empty_takes_precedence_over_invalid() {
5029 // Order pin: the existing `EmptyChildVersion` diagnostic (which
5030 // doesn't try to parse) fires before the new
5031 // `ChildVersaoInvalid` parse-side diagnostic, so an empty
5032 // `:versao` keeps its narrower error message —
5033 // `parse_requirement` would also reject `""`, but the
5034 // empty-string arm is the more self-locating diagnostic for the
5035 // author. Same ordering discipline as
5036 // `membro_versao_empty_takes_precedence_over_invalid` in
5037 // aplicacao.rs.
5038 let s = SupervisorSpec {
5039 children: vec![child("worker", "", RestartPolicy::Permanent)],
5040 ..SupervisorSpec::default()
5041 };
5042 let err = s.validate().unwrap_err();
5043 assert!(
5044 matches!(err, SupervisorError::EmptyChildVersion { ref caixa } if caixa == "worker"),
5045 "got {err:?}"
5046 );
5047 }
5048
5049 #[test]
5050 fn child_versao_invalid_fires_before_duplicate_check() {
5051 // Order pin: a malformed requirement on a non-duplicate entry
5052 // surfaces *its own* diagnostic (which names the offending
5053 // `:versao` string), even when a later entry would otherwise
5054 // collapse onto an earlier name. The per-entry shape gate runs
5055 // inline before the duplicate-key insert — parallel to
5056 // `membro_versao_invalid_fires_before_duplicate_check` in
5057 // aplicacao.rs and the b0c8389 / c4213a4 ordering discipline.
5058 let s = SupervisorSpec {
5059 children: vec![
5060 child("worker", "^bad", RestartPolicy::Permanent),
5061 child("cache", "^0.1", RestartPolicy::Transient),
5062 child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
5063 ],
5064 ..SupervisorSpec::default()
5065 };
5066 let err = s.validate().unwrap_err();
5067 assert!(
5068 matches!(
5069 err,
5070 SupervisorError::ChildVersaoInvalid { ref caixa, .. } if caixa == "worker"
5071 ),
5072 "got {err:?}"
5073 );
5074 }
5075
5076 #[test]
5077 fn child_versao_invalid_diagnostic_carries_offending_versao() {
5078 // The diagnostic-shape pin: the error names the offending
5079 // `:versao` value verbatim so the author can grep their
5080 // caixa.lisp without re-running the build, and carries a
5081 // non-empty `reason` from `semver::VersionReq::parse` so the
5082 // parser's own wording flows through to the diagnostic.
5083 let s = SupervisorSpec {
5084 children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
5085 ..SupervisorSpec::default()
5086 };
5087 let err = s.validate().unwrap_err();
5088 let SupervisorError::ChildVersaoInvalid {
5089 caixa,
5090 versao,
5091 reason,
5092 } = err
5093 else {
5094 panic!("expected ChildVersaoInvalid, got other variant");
5095 };
5096 assert_eq!(caixa, "worker");
5097 assert_eq!(versao, "not-a-req");
5098 assert!(
5099 !reason.is_empty(),
5100 "ChildVersaoInvalid `reason` must carry the parser's wording verbatim"
5101 );
5102 }
5103
5104 // ── value-shape: DNS-1123 label rule on :children :caixa ──────────────
5105
5106 #[test]
5107 fn validate_rejects_child_caixa_with_uppercase() {
5108 // The canonical "I copied the Servico's display name verbatim"
5109 // typo — child caixa names are lowercase per K8s DNS-1123 label
5110 // rule. The diagnostic names the offending name and suggests the
5111 // lower-cased fix in one edit, mirroring the
5112 // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0).
5113 let s = SupervisorSpec {
5114 children: vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
5115 ..SupervisorSpec::default()
5116 };
5117 let err = s.validate().unwrap_err();
5118 let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
5119 panic!("expected ChildCaixaInvalid, got other variant");
5120 };
5121 assert_eq!(caixa, "Worker");
5122 assert!(
5123 reason.contains("uppercase"),
5124 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
5125 );
5126 assert!(
5127 reason.contains("\"worker\""),
5128 "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
5129 );
5130 }
5131
5132 #[test]
5133 fn validate_rejects_child_caixa_with_underscore() {
5134 // The canonical "I'm thinking of a Python module / Postgres
5135 // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
5136 // label schema. K8s rejects `metadata.name: my_worker` at
5137 // admission time with an opaque `field is invalid` (no source-
5138 // citing diagnostic). The gate moves it to caixa-build time.
5139 let s = SupervisorSpec {
5140 children: vec![child("my_worker", "^0.1", RestartPolicy::Permanent)],
5141 ..SupervisorSpec::default()
5142 };
5143 let err = s.validate().unwrap_err();
5144 assert!(
5145 matches!(
5146 err,
5147 SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
5148 if caixa == "my_worker" && reason.contains('_')
5149 ),
5150 "got {err:?}"
5151 );
5152 }
5153
5154 #[test]
5155 fn validate_rejects_child_caixa_with_dot() {
5156 // A `:children :caixa` entry is a single DNS-1123 label, not a
5157 // subdomain. The K8s Service / ComputeUnit `metadata.name` rules
5158 // forbid dots. Same shape as `rejects_membro_caixa_with_dot`
5159 // (3f9d7a0) on the peer name axis.
5160 let s = SupervisorSpec {
5161 children: vec![child("team.worker", "^0.1", RestartPolicy::Permanent)],
5162 ..SupervisorSpec::default()
5163 };
5164 let err = s.validate().unwrap_err();
5165 assert!(
5166 matches!(
5167 err,
5168 SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
5169 if caixa == "team.worker" && reason.contains('.')
5170 ),
5171 "got {err:?}"
5172 );
5173 }
5174
5175 #[test]
5176 fn validate_rejects_child_caixa_with_leading_hyphen() {
5177 // DNS-1123 / DNS-1035 boundary rule: labels must start and end
5178 // with an alphanumeric. The K8s apiserver rejects `-worker`
5179 // outright; the renderer would emit a `metadata.name: "-worker"`
5180 // that fails admission far from the source caixa.lisp.
5181 let s = SupervisorSpec {
5182 children: vec![child("-worker", "^0.1", RestartPolicy::Permanent)],
5183 ..SupervisorSpec::default()
5184 };
5185 let err = s.validate().unwrap_err();
5186 assert!(
5187 matches!(
5188 err,
5189 SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
5190 if caixa == "-worker" && reason.contains("start and end")
5191 ),
5192 "got {err:?}"
5193 );
5194 }
5195
5196 #[test]
5197 fn validate_rejects_child_caixa_with_trailing_hyphen() {
5198 // The symmetric arm of the boundary rule. Pin separately so
5199 // both ends of the label are covered against a future relaxation
5200 // that only checks one boundary.
5201 let s = SupervisorSpec {
5202 children: vec![child("worker-", "^0.1", RestartPolicy::Permanent)],
5203 ..SupervisorSpec::default()
5204 };
5205 let err = s.validate().unwrap_err();
5206 assert!(
5207 matches!(
5208 err,
5209 SupervisorError::ChildCaixaInvalid { ref caixa, .. }
5210 if caixa == "worker-"
5211 ),
5212 "got {err:?}"
5213 );
5214 }
5215
5216 #[test]
5217 fn validate_rejects_child_caixa_with_unicode() {
5218 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
5219 // (`xn--…`) by the author before it reaches K8s. The byte-by-
5220 // byte ASCII validity check rejects multi-byte UTF-8 sequences
5221 // by the first byte that fails the `[a-z0-9-]` predicate.
5222 let s = SupervisorSpec {
5223 children: vec![child("café", "^0.1", RestartPolicy::Permanent)],
5224 ..SupervisorSpec::default()
5225 };
5226 let err = s.validate().unwrap_err();
5227 assert!(
5228 matches!(
5229 err,
5230 SupervisorError::ChildCaixaInvalid { ref caixa, .. }
5231 if caixa == "café"
5232 ),
5233 "got {err:?}"
5234 );
5235 }
5236
5237 #[test]
5238 fn validate_rejects_child_caixa_with_whitespace() {
5239 // Whitespace is the canonical "I pasted from a sketch / doc"
5240 // footgun. The apiserver rejects every `metadata.name` value
5241 // carrying whitespace; pin the gate fires at the right boundary.
5242 let s = SupervisorSpec {
5243 children: vec![child("my worker", "^0.1", RestartPolicy::Permanent)],
5244 ..SupervisorSpec::default()
5245 };
5246 let err = s.validate().unwrap_err();
5247 assert!(
5248 matches!(
5249 err,
5250 SupervisorError::ChildCaixaInvalid { ref caixa, .. }
5251 if caixa == "my worker"
5252 ),
5253 "got {err:?}"
5254 );
5255 }
5256
5257 #[test]
5258 fn validate_rejects_child_caixa_too_long() {
5259 // The 64-byte boundary pin. DNS-1123 / DNS-1035 cap labels at
5260 // 63 bytes; the K8s apiserver rejects every `metadata.name`
5261 // axis over the limit at admission time. The diagnostic names
5262 // both the cap and the actual length so the author can shorten
5263 // in one edit, mirroring `rejects_membro_caixa_too_long`
5264 // (3f9d7a0) and `rejects_placement_cluster_too_long` (6cbb900).
5265 let too_long = "a".repeat(64);
5266 let s = SupervisorSpec {
5267 children: vec![child(&too_long, "^0.1", RestartPolicy::Permanent)],
5268 ..SupervisorSpec::default()
5269 };
5270 let err = s.validate().unwrap_err();
5271 let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
5272 panic!("expected ChildCaixaInvalid, got other variant");
5273 };
5274 assert_eq!(caixa, too_long);
5275 assert!(
5276 reason.contains("63"),
5277 "diagnostic must name the 63-byte cap (got: {reason:?})"
5278 );
5279 assert!(
5280 reason.contains("64"),
5281 "diagnostic must name the actual length (got: {reason:?})"
5282 );
5283 }
5284
5285 #[test]
5286 fn child_caixa_max_length_validates() {
5287 // The 63-byte boundary control pin — exactly-at-the-cap is
5288 // accepted, mirroring `membro_caixa_max_length_validates`
5289 // (3f9d7a0) and `placement_cluster_max_length_validates`
5290 // (6cbb900). Pinned separately so a future off-by-one tightening
5291 // surfaces here.
5292 let max_label = "a".repeat(63);
5293 let s = SupervisorSpec {
5294 children: vec![child(&max_label, "^0.1", RestartPolicy::Permanent)],
5295 ..SupervisorSpec::default()
5296 };
5297 s.validate().unwrap();
5298 }
5299
5300 #[test]
5301 fn validate_accepts_canonical_child_caixa_forms() {
5302 // The realistic shapes a supervised child's `:caixa` carries —
5303 // single-word `worker`, version-suffixed `cache-v2`, single-char
5304 // `a`, two-char `db`, digit-start `2-pool`, longer hyphen-joined
5305 // `payment-retry`, all-digit `0`. Pin every leg so a future
5306 // tightening (e.g. requiring a leading lowercase letter) surfaces
5307 // here as a test failure. Mirrors `accepts_canonical_membro_caixa_forms`
5308 // (3f9d7a0) and `accepts_canonical_placement_cluster_forms`
5309 // (6cbb900).
5310 for form in [
5311 "worker",
5312 "cache-v2",
5313 "a",
5314 "db",
5315 "2-pool",
5316 "payment-retry",
5317 "0",
5318 ] {
5319 let s = SupervisorSpec {
5320 children: vec![child(form, "^0.1", RestartPolicy::Permanent)],
5321 ..SupervisorSpec::default()
5322 };
5323 s.validate()
5324 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
5325 }
5326 }
5327
5328 #[test]
5329 fn child_caixa_empty_takes_precedence_over_invalid() {
5330 // Order pin: the existing `EmptyChildName` diagnostic (which
5331 // doesn't try to parse the DNS-1123 shape) fires before the new
5332 // `ChildCaixaInvalid` per-axis gate, so an empty `:caixa` keeps
5333 // its narrower error message — `is_dns_1123_label` would reject
5334 // the empty string too (boundary check on the first byte), but
5335 // the empty-string arm is the more self-locating diagnostic for
5336 // the author. Same ordering discipline as
5337 // `membro_caixa_empty_takes_precedence_over_invalid` in
5338 // aplicacao.rs.
5339 let s = SupervisorSpec {
5340 children: vec![child("", "^0.1", RestartPolicy::Permanent)],
5341 ..SupervisorSpec::default()
5342 };
5343 let err = s.validate().unwrap_err();
5344 assert_eq!(err, SupervisorError::EmptyChildName);
5345 }
5346
5347 #[test]
5348 fn child_caixa_invalid_fires_before_versao_check() {
5349 // Order pin: the per-axis shape gate runs inline before the
5350 // per-entry versao check, so a malformed `:caixa` on an entry
5351 // whose `:versao` would also fail surfaces the more self-
5352 // locating name-axis diagnostic first. Parallel to
5353 // `membro_versao_invalid_fires_before_duplicate_check` (9888b13)
5354 // and `placement_cluster_invalid_fires_before_duplicate_check`
5355 // (6cbb900).
5356 let s = SupervisorSpec {
5357 children: vec![child("My_Worker", "", RestartPolicy::Permanent)],
5358 ..SupervisorSpec::default()
5359 };
5360 let err = s.validate().unwrap_err();
5361 assert!(
5362 matches!(
5363 err,
5364 SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "My_Worker"
5365 ),
5366 "got {err:?}"
5367 );
5368 }
5369
5370 #[test]
5371 fn child_caixa_invalid_fires_before_duplicate_check() {
5372 // Order pin: a malformed name on a non-duplicate entry surfaces
5373 // its own diagnostic, even when a later entry would otherwise
5374 // collapse onto an earlier name. The per-entry shape gate runs
5375 // inline before the duplicate-key HashSet insert, mirroring
5376 // `placement_cluster_invalid_fires_before_duplicate_check`
5377 // (6cbb900).
5378 let s = SupervisorSpec {
5379 children: vec![
5380 child("Worker", "^0.1", RestartPolicy::Permanent),
5381 child("cache", "^0.1", RestartPolicy::Transient),
5382 child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
5383 ],
5384 ..SupervisorSpec::default()
5385 };
5386 let err = s.validate().unwrap_err();
5387 assert!(
5388 matches!(
5389 err,
5390 SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "Worker"
5391 ),
5392 "got {err:?}"
5393 );
5394 }
5395
5396 #[test]
5397 fn child_caixa_invalid_diagnostic_carries_offending_caixa() {
5398 // The diagnostic-shape pin: the error names the offending
5399 // `:caixa` verbatim plus a non-empty parser-shaped `reason` so
5400 // the author can grep their caixa.lisp without re-running the
5401 // build. Mirrors the diagnostic-shape sweep on every prior
5402 // value-shape gate (3f9d7a0, 6cbb900, c7d05ec).
5403 let s = SupervisorSpec {
5404 children: vec![child("My_Worker", "^0.1", RestartPolicy::Permanent)],
5405 ..SupervisorSpec::default()
5406 };
5407 let err = s.validate().unwrap_err();
5408 let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
5409 panic!("expected ChildCaixaInvalid, got other variant");
5410 };
5411 assert_eq!(caixa, "My_Worker");
5412 assert!(
5413 !reason.is_empty(),
5414 "ChildCaixaInvalid `reason` must carry the parser's wording verbatim"
5415 );
5416 }
5417
5418 // ── value-shape: zero restart_window + duplicate child names ──────────
5419
5420 #[test]
5421 fn validate_accepts_none_restart_window() {
5422 // Omitted `:restart-window` is the "never reset" sentinel —
5423 // valid by design. Mirrors :limits axes where None = unbounded.
5424 let s = SupervisorSpec {
5425 restart_window: None,
5426 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5427 ..SupervisorSpec::default()
5428 };
5429 s.validate().unwrap();
5430 }
5431
5432 #[test]
5433 fn validate_rejects_zero_restart_window() {
5434 // Same "0 means the opposite of what you think" footgun closed
5435 // for :politicas :timeout (Envoy treats 0s as infinite) and
5436 // :limits :wall-clock (wasmtime traps before the call starts).
5437 // Erlang/OTP's MaxIntensity/Period requires Period > 0.
5438 let s = SupervisorSpec {
5439 restart_window: Some(Duration::ZERO),
5440 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5441 ..SupervisorSpec::default()
5442 };
5443 assert_eq!(
5444 s.validate().unwrap_err(),
5445 SupervisorError::RestartWindowZero
5446 );
5447 }
5448
5449 // ── value-shape: integer-ms canonical-form on :restart-window ─────────
5450 //
5451 // The fourth (and last) typed-`Duration` axis in caixa-core to get
5452 // the integer-millisecond canonical-form gate — peer with
5453 // `:limits :wall-clock` (82fc3ef), `:politicas :timeout` (a4ae535),
5454 // and `:politicas :circuit-breaker :window` (a4ae535). The serde
5455 // path is already gated at the shared codec layer (see
5456 // `restart_window_serde_rejects_fractional_seconds`); this arm
5457 // closes the programmatic-struct-literal path the codec gate can't
5458 // see.
5459
5460 #[test]
5461 fn validate_rejects_sub_millisecond_restart_window() {
5462 // The fail-before-pass-after pin: a programmatic
5463 // `Duration::from_micros(1500)` (= 1_500_000 ns) silently passed
5464 // `validate` on every pre-gate codebase, then truncated to
5465 // `as_millis() == 1` on first serialize — the shared codec
5466 // emits `"1ms"`, parses it back to `Duration::from_millis(1)` =
5467 // 1_000_000 ns, the typed `restart_window` no longer matches
5468 // its rendered form.
5469 let s = SupervisorSpec {
5470 restart_window: Some(Duration::from_micros(1500)),
5471 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5472 ..SupervisorSpec::default()
5473 };
5474 match s.validate().unwrap_err() {
5475 SupervisorError::RestartWindowNotCanonical { window } => {
5476 assert_eq!(window, Duration::from_micros(1500));
5477 }
5478 other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
5479 }
5480 }
5481
5482 #[test]
5483 fn validate_rejects_one_nanosecond_restart_window() {
5484 // The far-sub-ms case: `Duration::from_nanos(1)` is non-zero
5485 // (so `RestartWindowZero` doesn't fire) but `as_millis() == 0`,
5486 // so the shared codec emits the literal `"0s"` — the next
5487 // serde round-trip would parse back to `Duration::ZERO`, which
5488 // the `RestartWindowZero` arm then rejects on re-validate. The
5489 // canonical-form gate at this layer surfaces a self-locating
5490 // diagnostic naming the offending Duration verbatim rather
5491 // than a downstream `RestartWindowZero` whose remediation
5492 // points at omitting the slot.
5493 let s = SupervisorSpec {
5494 restart_window: Some(Duration::from_nanos(1)),
5495 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5496 ..SupervisorSpec::default()
5497 };
5498 match s.validate().unwrap_err() {
5499 SupervisorError::RestartWindowNotCanonical { window } => {
5500 assert_eq!(window, Duration::from_nanos(1));
5501 }
5502 other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
5503 }
5504 }
5505
5506 #[test]
5507 fn validate_rejects_nanosecond_past_canonical_boundary_restart_window() {
5508 // The 1-ns-past-1ms boundary case: a `Duration` carrying
5509 // 1_000_001 ns is structurally past the integer-ms granularity
5510 // floor — `subsec_nanos() % 1_000_000 == 1`. The codec round-
5511 // trip would truncate to `1ms` and the consumer would observe
5512 // a 1-ns drift on every emit. Same boundary the peer
5513 // `validate_rejects_nanosecond_past_canonical_boundary` test
5514 // in limits.rs pins for the `:limits :wall-clock` axis.
5515 let w = Duration::from_nanos(1_000_001);
5516 let s = SupervisorSpec {
5517 restart_window: Some(w),
5518 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5519 ..SupervisorSpec::default()
5520 };
5521 assert_eq!(
5522 s.validate().unwrap_err(),
5523 SupervisorError::RestartWindowNotCanonical { window: w }
5524 );
5525 }
5526
5527 #[test]
5528 fn validate_accepts_integer_millisecond_restart_window_values() {
5529 // The positive-control sweep: every `Duration` the shared
5530 // codec can round-trip losslessly — the canonical
5531 // `<integer>{ms,s,m,h}` set the codec's `render` / `parse`
5532 // pair emits and accepts — passes `validate` without
5533 // surfacing the new canonical-form arm. Mirrors
5534 // `validate_accepts_integer_millisecond_wall_clock_values` on
5535 // the sibling `:limits :wall-clock` axis.
5536 for w in [
5537 Duration::from_millis(1),
5538 Duration::from_millis(500),
5539 Duration::from_millis(1500),
5540 Duration::from_secs(1),
5541 Duration::from_secs(30),
5542 Duration::from_secs(60),
5543 Duration::from_secs(120),
5544 Duration::from_secs(3600),
5545 ] {
5546 let s = SupervisorSpec {
5547 restart_window: Some(w),
5548 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5549 ..SupervisorSpec::default()
5550 };
5551 s.validate()
5552 .unwrap_or_else(|e| panic!("integer-ms {w:?} must validate, got {e:?}"));
5553 }
5554 }
5555
5556 #[test]
5557 fn validate_restart_window_zero_takes_precedence_over_canonical_gate() {
5558 // Cross-arm ordering pin: `Duration::ZERO` has
5559 // `subsec_nanos() == 0` and would otherwise pass the
5560 // canonical-form arm — the zero-floor arm must fire first so
5561 // the more self-locating `RestartWindowZero` diagnostic (with
5562 // its omit-axis remediation directly named) leads. Same
5563 // posture every peer zero-then-shape gate uses
5564 // (`WallClockZero` → `WallClockNotCanonical`,
5565 // `PolicyTimeoutZero` → `PolicyTimeoutNotCanonical`,
5566 // `PolicyBreakerZeroWindow` → `PolicyBreakerWindowNotCanonical`).
5567 let s = SupervisorSpec {
5568 restart_window: Some(Duration::ZERO),
5569 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5570 ..SupervisorSpec::default()
5571 };
5572 assert_eq!(
5573 s.validate().unwrap_err(),
5574 SupervisorError::RestartWindowZero
5575 );
5576 }
5577
5578 #[test]
5579 fn restart_window_canonical_diagnostic_carries_offending_duration() {
5580 // Diagnostic-shape pin: the canonical-form arm names the
5581 // offending `Duration` verbatim so the author's grep lands on
5582 // the field's value, not a generic "duration not canonical"
5583 // message. Same shape every other typed-canonical-form arm
5584 // on this surface carries (`WallClockNotCanonical` carries
5585 // the offending `Duration` verbatim,
5586 // `PolicyTimeoutNotCanonical` carries the offending
5587 // `Duration` verbatim).
5588 let w = Duration::from_micros(500);
5589 let s = SupervisorSpec {
5590 restart_window: Some(w),
5591 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5592 ..SupervisorSpec::default()
5593 };
5594 let err = s.validate().unwrap_err();
5595 let msg = err.to_string();
5596 assert!(
5597 msg.contains("500"),
5598 "diagnostic must carry the offending magnitude verbatim (got {msg:?})"
5599 );
5600 assert!(
5601 msg.contains("sub-millisecond"),
5602 "diagnostic must name the sub-millisecond residue class (got {msg:?})"
5603 );
5604 }
5605
5606 #[test]
5607 fn restart_window_validated_value_round_trips_through_codec() {
5608 // The structural property the canonical-ms gate enforces:
5609 // every `SupervisorSpec::restart_window` past
5610 // `SupervisorSpec::validate` round-trips losslessly through
5611 // the shared duration codec (serialize → string →
5612 // deserialize → equal value). Pin this end-to-end so a future
5613 // change to either side (the validate gate's accepted
5614 // granularity, the codec's parse/render unit set) that breaks
5615 // the alignment surfaces here. Peer of
5616 // `wall_clock_validated_value_round_trips_through_codec` on
5617 // the sibling `:limits :wall-clock` axis.
5618 for w in [
5619 Duration::from_millis(1),
5620 Duration::from_millis(1500),
5621 Duration::from_secs(30),
5622 Duration::from_secs(3600),
5623 ] {
5624 let s = SupervisorSpec {
5625 restart_window: Some(w),
5626 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5627 ..SupervisorSpec::default()
5628 };
5629 s.validate().unwrap();
5630 let json = serde_json::to_string(&s).unwrap();
5631 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5632 assert_eq!(back.restart_window, Some(w));
5633 }
5634 }
5635
5636 // ── value-shape: upper cap on :restart-window ─────────────────────────
5637 //
5638 // The fourth (and last) typed-`Duration` axis in caixa-core to get
5639 // the 1h upper cap — peer with `:limits :wall-clock` (51e0dbd),
5640 // `:politicas :timeout` (2e8ee7e), and `:politicas
5641 // :circuit-breaker :window` (379a814). Brackets the typed
5642 // `:restart-window` axis structurally: every validated value lies
5643 // in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`, integer-millisecond
5644 // granularity, closing the
5645 // rolling-window-degenerates-to-lifetime-counter footgun the prior
5646 // zero-floor-and-canonical-form-only checks left open.
5647
5648 #[test]
5649 fn validate_rejects_restart_window_above_cap() {
5650 // The fail-before-pass-after pin: 3601s = 1h + 1s is
5651 // structurally one canonical-tick past the
5652 // [`SUPERVISOR_RESTART_WINDOW_MAX`] ceiling (1h = 3600s) — an
5653 // integer-millisecond magnitude the canonical-form arm above
5654 // accepts cleanly, that the shared duration codec round-trips
5655 // losslessly as `"3601s"`, and that silently passed validate on
5656 // every pre-gate codebase because the typed slot's only checks
5657 // were the zero-floor and canonical-form arms. The runtime
5658 // substrate consuming the value (Erlang/OTP's MaxIntensity/
5659 // Period reconciler, the future wasm-operator's per-supervisor
5660 // restart-intensity counter) reaches for a `Duration` so long
5661 // no realistic restart-recovery pattern resets the counter,
5662 // far from the source caixa.lisp.
5663 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
5664 let s = SupervisorSpec {
5665 restart_window: Some(w),
5666 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5667 ..SupervisorSpec::default()
5668 };
5669 assert_eq!(
5670 s.validate().unwrap_err(),
5671 SupervisorError::RestartWindowExceedsCap { window: w }
5672 );
5673 }
5674
5675 #[test]
5676 fn validate_rejects_restart_window_one_millisecond_above_cap() {
5677 // Boundary case: exactly 1ms past the cap (the granularity the
5678 // canonical-form gate enforces). Catches a future "strictly
5679 // less than" half-measure and pins the diagnostic to name the
5680 // offending `Duration` verbatim. Peer of
5681 // `validate_rejects_wall_clock_one_millisecond_above_cap` /
5682 // `rejects_policy_timeout_one_millisecond_above_cap` /
5683 // `rejects_circuit_breaker_window_one_millisecond_above_cap`
5684 // on the sibling typed-`Duration` axes' top edges.
5685 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
5686 let s = SupervisorSpec {
5687 restart_window: Some(w),
5688 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5689 ..SupervisorSpec::default()
5690 };
5691 assert_eq!(
5692 s.validate().unwrap_err(),
5693 SupervisorError::RestartWindowExceedsCap { window: w }
5694 );
5695 }
5696
5697 #[test]
5698 fn validate_rejects_restart_window_far_above_cap() {
5699 // The "obvious authoring footgun" case: a `(:restart-window "24h")`,
5700 // `(:restart-window "7d")`, or any "I want a lifetime counter
5701 // but wrote a `<integer>h` magnitude anyway" typo — values the
5702 // canonical-form arm accepts as integer-millisecond magnitudes,
5703 // the codec round-trips losslessly through serde, but the
5704 // operator's `MaxIntensity / Period` reconciler cannot honor
5705 // as a meaningful rolling window. Until this gate landed
5706 // validate accepted them. Pin the common above-cap values (24h,
5707 // 7d, ~11.5d) so a future relaxation that drops the upper bound
5708 // surfaces here.
5709 for w in [
5710 Duration::from_secs(86_400), // 24h
5711 Duration::from_secs(604_800), // 7d
5712 Duration::from_secs(1_000_000), // ~11.5 days
5713 ] {
5714 let s = SupervisorSpec {
5715 restart_window: Some(w),
5716 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5717 ..SupervisorSpec::default()
5718 };
5719 assert_eq!(
5720 s.validate().unwrap_err(),
5721 SupervisorError::RestartWindowExceedsCap { window: w }
5722 );
5723 }
5724 }
5725
5726 #[test]
5727 fn validate_accepts_restart_window_at_cap() {
5728 // The boundary value — exactly [`SUPERVISOR_RESTART_WINDOW_MAX`]
5729 // (1h) — must validate. The cap is inclusive on the top edge,
5730 // matching the [`crate::LIMITS_WALL_CLOCK_MAX`] /
5731 // [`crate::POLICY_TIMEOUT_MAX`] /
5732 // [`crate::POLICY_BREAKER_WINDOW_MAX`] discipline on the sibling
5733 // capped axes. Pin the boundary explicitly so a future
5734 // off-by-one tightening (`>= SUPERVISOR_RESTART_WINDOW_MAX`
5735 // instead of `>`) surfaces here as a test failure rather than a
5736 // silent contract narrowing.
5737 let s = SupervisorSpec {
5738 restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
5739 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5740 ..SupervisorSpec::default()
5741 };
5742 s.validate()
5743 .expect("restart_window == SUPERVISOR_RESTART_WINDOW_MAX must validate");
5744 }
5745
5746 #[test]
5747 fn validate_accepts_restart_window_typical_values() {
5748 // The documented Erlang/OTP / Elixir / Riak Core / RabbitMQ
5749 // per-supervisor production-playbook band positive-control
5750 // sweep — every value Learn You Some Erlang's `{intensity, 5,
5751 // 60}` worker-supervisor `Period = 60s` default, Elixir's
5752 // `Supervisor` `max_seconds: 5` default, OTP's `supervisor`
5753 // callback module `MaxT = 5..=60` typical, Riak Core's `MaxT ∈
5754 // 10s..=300s`, and RabbitMQ broker-supervisor `MaxT = 5s`
5755 // default recommend (5s..=300s) must pass, plus a sweep
5756 // through the long-tail-flaky-pool band (5m, 15m, 30m, 1h) the
5757 // cap accepts. Mirrors `validate_accepts_wall_clock_typical_values`
5758 // on the sibling `:limits :wall-clock` axis.
5759 for w in [
5760 Duration::from_millis(1),
5761 Duration::from_millis(500),
5762 Duration::from_secs(1),
5763 Duration::from_secs(5), // RabbitMQ broker-supervisor default
5764 Duration::from_secs(10), // Riak Core lower
5765 Duration::from_secs(30),
5766 Duration::from_secs(60), // Learn You Some Erlang default
5767 Duration::from_secs(120), // OTP supervisor MaxT typical
5768 Duration::from_secs(300), // Riak Core upper
5769 Duration::from_secs(900), // 15m
5770 Duration::from_secs(1800),
5771 Duration::from_secs(3600), // exactly 1h, the cap
5772 ] {
5773 let s = SupervisorSpec {
5774 restart_window: Some(w),
5775 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5776 ..SupervisorSpec::default()
5777 };
5778 s.validate()
5779 .unwrap_or_else(|e| panic!("restart_window={w:?} must validate; got {e:?}"));
5780 }
5781 }
5782
5783 #[test]
5784 fn restart_window_zero_takes_precedence_over_cap() {
5785 // The cross-arm ordering pin: `Duration::ZERO` is structurally
5786 // outside both `>= 1ms` (zero-floor) and `<=
5787 // SUPERVISOR_RESTART_WINDOW_MAX` (cap), but the zero-floor
5788 // diagnostic is the more self-locating one (it directly names
5789 // the omit-axis remediation), so the validate gate must fire
5790 // on zero first. Same shape every other zero-then-cap ordering
5791 // on this surface uses (`WallClockZero` then
5792 // `WallClockExceedsCap`, `PolicyTimeoutZero` then
5793 // `PolicyTimeoutExceedsCap`, `PolicyBreakerZeroWindow` then
5794 // `PolicyBreakerWindowExceedsCap`).
5795 let s = SupervisorSpec {
5796 restart_window: Some(Duration::ZERO),
5797 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5798 ..SupervisorSpec::default()
5799 };
5800 assert_eq!(
5801 s.validate().unwrap_err(),
5802 SupervisorError::RestartWindowZero,
5803 "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
5804 );
5805 }
5806
5807 #[test]
5808 fn restart_window_canonical_takes_precedence_over_cap() {
5809 // The cross-arm ordering pin: a `Duration` that is *both*
5810 // sub-millisecond (non-canonical-form) and structurally above
5811 // the cap surfaces the canonical-form diagnostic first,
5812 // because the round-trip-shape break is the more fundamental
5813 // issue (the value can't even round-trip through the codec,
5814 // so the cap diagnostic naming `1ms..=1h` would be misleading
5815 // — there's no integer-ms form of the offending value). Pin
5816 // the order so a future refactor that reorders the arms
5817 // surfaces here as a test failure rather than a silent
5818 // diagnostic regression. Peer of
5819 // `wall_clock_canonical_takes_precedence_over_cap` /
5820 // `policy_timeout_canonical_takes_precedence_over_cap`.
5821 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_nanos(1);
5822 let s = SupervisorSpec {
5823 restart_window: Some(w),
5824 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5825 ..SupervisorSpec::default()
5826 };
5827 assert_eq!(
5828 s.validate().unwrap_err(),
5829 SupervisorError::RestartWindowNotCanonical { window: w },
5830 "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
5831 );
5832 }
5833
5834 #[test]
5835 fn max_restarts_cap_takes_precedence_over_restart_window_cap() {
5836 // The cross-arm ordering pin between the `:max-restarts` cap
5837 // and the sibling `:restart-window` cap. A supervisor carrying
5838 // both an over-cap `max_restarts` AND an over-cap window must
5839 // surface the `MaxRestartsExceedsCap` diagnostic first — the
5840 // cap arm is wired immediately after the zero-restart arm and
5841 // strictly before every window-axis arm (zero / canonical /
5842 // cap), so the offending value the diagnostic names matches
5843 // the order the author would discover the gates by reading
5844 // top-to-bottom through `SupervisorSpec::validate`. Pin the
5845 // order so a future refactor that reorders the arms surfaces
5846 // here as a test failure rather than a silent diagnostic
5847 // regression. Peer of
5848 // `max_restarts_cap_takes_precedence_over_restart_window_gates`
5849 // on the sibling zero / canonical window arms.
5850 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
5851 let s = SupervisorSpec {
5852 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5853 restart_window: Some(w),
5854 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5855 ..SupervisorSpec::default()
5856 };
5857 assert_eq!(
5858 s.validate().unwrap_err(),
5859 SupervisorError::MaxRestartsExceedsCap {
5860 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5861 },
5862 "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
5863 );
5864 }
5865
5866 #[test]
5867 fn restart_window_cap_diagnostic_carries_offending_value() {
5868 // The diagnostic-shape pin: the offending `Duration` is
5869 // carried verbatim into the
5870 // [`SupervisorError::RestartWindowExceedsCap`] variant so the
5871 // surfaced error message names the value the author wrote,
5872 // not just the cap. Same self-locating diagnostic shape every
5873 // other typed-cap arm on this surface carries
5874 // (`WallClockExceedsCap` carries the offending `Duration`
5875 // verbatim, `PolicyTimeoutExceedsCap` carries the offending
5876 // `Duration` verbatim, `PolicyBreakerWindowExceedsCap` carries
5877 // the offending `Duration` verbatim).
5878 let w = Duration::from_secs(7200); // 2h
5879 let s = SupervisorSpec {
5880 restart_window: Some(w),
5881 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5882 ..SupervisorSpec::default()
5883 };
5884 let err = s.validate().unwrap_err();
5885 assert!(
5886 matches!(err, SupervisorError::RestartWindowExceedsCap { window } if window == w),
5887 "got {err:?}"
5888 );
5889 let msg = err.to_string();
5890 assert!(
5891 msg.contains("7200"),
5892 ":supervisor :restart-window cap diagnostic must carry the offending value verbatim (got: {msg})"
5893 );
5894 }
5895
5896 #[test]
5897 fn supervisor_restart_window_cap_pins_canonical_value() {
5898 // The SUPERVISOR_RESTART_WINDOW_MAX constant pins the value at
5899 // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
5900 // shared duration codec emits as a clean canonical string
5901 // (`"<n>h"`). Pinning the literal value here surfaces a future
5902 // drift (a relaxation to 24h, a tightening to 5m) as a
5903 // deliberate test edit, not a silent contract narrowing.
5904 //
5905 // The four typed-`Duration` caps on the validation surface
5906 // (`LIMITS_WALL_CLOCK_MAX` per-process, `POLICY_TIMEOUT_MAX`
5907 // per-edge, `POLICY_BREAKER_WINDOW_MAX` per-breaker,
5908 // `SUPERVISOR_RESTART_WINDOW_MAX` per-supervisor) share a
5909 // single uniform top edge at the codec's largest emitted unit
5910 // — a structural-property invariant the equality assertions
5911 // here enshrine, so a future drift on any of the four
5912 // surfaces as a deliberate test edit. Same shape every other
5913 // typed-cap value pin uses
5914 // (`wall_clock_cap_pins_canonical_value`,
5915 // `policy_timeout_cap_pins_canonical_value`,
5916 // `circuit_breaker_window_cap_pins_canonical_value`).
5917 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, Duration::from_secs(3600));
5918 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX.as_millis(), 3_600_000);
5919 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::LIMITS_WALL_CLOCK_MAX);
5920 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::POLICY_TIMEOUT_MAX);
5921 assert_eq!(
5922 SUPERVISOR_RESTART_WINDOW_MAX,
5923 crate::POLICY_BREAKER_WINDOW_MAX
5924 );
5925 }
5926
5927 #[test]
5928 fn restart_window_cap_value_round_trips_through_codec() {
5929 // The codec round-trip property the cap arm preserves: the
5930 // [`SUPERVISOR_RESTART_WINDOW_MAX`] constant itself round-trips
5931 // through the shared duration codec — every value at the cap
5932 // serializes to the canonical `"1h"` form and parses back
5933 // identically. Pin the round-trip so a future change to the
5934 // codec's unit set or to the cap's magnitude that breaks the
5935 // round-trip property surfaces here. Peer of
5936 // `wall_clock_cap_value_round_trips_through_codec` on the
5937 // sibling `:limits :wall-clock` axis.
5938 let s = SupervisorSpec {
5939 restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
5940 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5941 ..SupervisorSpec::default()
5942 };
5943 s.validate().unwrap();
5944 let json = serde_json::to_string(&s).unwrap();
5945 assert!(
5946 json.contains("\"1h\""),
5947 "SUPERVISOR_RESTART_WINDOW_MAX must serialize to the canonical `\"1h\"` form (got {json})"
5948 );
5949 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5950 assert_eq!(back.restart_window, Some(SUPERVISOR_RESTART_WINDOW_MAX));
5951 }
5952
5953 #[test]
5954 fn validate_rejects_duplicate_child_caixa() {
5955 // Two children with the same :caixa render to two ComputeUnits
5956 // with the same name in the cluster's HelmRelease values —
5957 // one silently overwrites the other. Erlang/OTP's child_spec.id
5958 // is required-unique per supervisor; same set-not-multiset
5959 // discipline applied here as for :membros / :placement
5960 // :clusters / :entrada :paths.
5961 let s = SupervisorSpec {
5962 children: vec![
5963 child("worker", "^0.1", RestartPolicy::Permanent),
5964 child("cache", "^0.1", RestartPolicy::Transient),
5965 child("worker", "^0.2", RestartPolicy::Permanent),
5966 ],
5967 ..SupervisorSpec::default()
5968 };
5969 let err = s.validate().unwrap_err();
5970 assert!(
5971 matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "worker"),
5972 "got {err:?}"
5973 );
5974 }
5975
5976 #[test]
5977 fn validate_duplicate_child_diagnostic_names_first_collision() {
5978 // Iteration walks the :children list in declaration order —
5979 // the diagnostic names the first repeat, deterministically,
5980 // even when multiple names duplicate.
5981 let s = SupervisorSpec {
5982 children: vec![
5983 child("a", "^0.1", RestartPolicy::Permanent),
5984 child("b", "^0.1", RestartPolicy::Permanent),
5985 child("a", "^0.1", RestartPolicy::Permanent),
5986 child("b", "^0.1", RestartPolicy::Permanent),
5987 ],
5988 ..SupervisorSpec::default()
5989 };
5990 let err = s.validate().unwrap_err();
5991 assert!(
5992 matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "a"),
5993 "got {err:?}"
5994 );
5995 }
5996
5997 // ── self-supervision cross-slot gate ──────────────────────────
5998
5999 #[test]
6000 fn validate_no_self_supervision_rejects_self_referential_child() {
6001 // A supervisor whose `:children` lists its own `:nome` is a
6002 // one-node reconciliation cycle — rejected, naming the parent.
6003 let children = vec![
6004 child("worker", "^0.1", RestartPolicy::Permanent),
6005 child("orquestra", "^0.1", RestartPolicy::Permanent),
6006 ];
6007 let err = validate_no_self_supervision(&children, "orquestra").unwrap_err();
6008 assert!(
6009 matches!(err, SupervisorError::ChildSupervisesSelf { ref caixa } if caixa == "orquestra"),
6010 "got {err:?}"
6011 );
6012 }
6013
6014 #[test]
6015 fn validate_no_self_supervision_accepts_distinct_children() {
6016 // Positive control: distinct child names (including a child that
6017 // is itself a supervisor — nested trees are valid OTP) pass.
6018 let children = vec![
6019 child("worker", "^0.1", RestartPolicy::Permanent),
6020 child("sub-tree", "^0.1", RestartPolicy::Permanent),
6021 ];
6022 validate_no_self_supervision(&children, "orquestra").unwrap();
6023 }
6024
6025 #[test]
6026 fn validate_no_self_supervision_empty_children_is_ok() {
6027 // SimpleOneForOne / no-static-children supervisors have nothing
6028 // to self-reference — the gate is vacuously satisfied.
6029 validate_no_self_supervision(&[], "orquestra").unwrap();
6030 }
6031
6032 #[test]
6033 fn validate_simple_one_for_one_skips_uniqueness_check() {
6034 // SimpleOneForOne supervisors carry no static children — the
6035 // duplicate-child loop never runs. A zero-window declaration
6036 // on a SimpleOneForOne supervisor still trips the window check
6037 // (window applies to dynamic children too).
6038 let s = SupervisorSpec {
6039 estrategia: RestartStrategy::SimpleOneForOne,
6040 restart_window: None,
6041 children: vec![],
6042 ..SupervisorSpec::default()
6043 };
6044 s.validate().unwrap();
6045 let s_zero = SupervisorSpec {
6046 estrategia: RestartStrategy::SimpleOneForOne,
6047 restart_window: Some(Duration::ZERO),
6048 children: vec![],
6049 ..SupervisorSpec::default()
6050 };
6051 assert_eq!(
6052 s_zero.validate().unwrap_err(),
6053 SupervisorError::RestartWindowZero
6054 );
6055 }
6056
6057 #[test]
6058 fn validate_zero_window_runs_after_max_restarts_check() {
6059 // Pin the order: max_restarts == 0 fires before
6060 // restart_window == 0s, so an author with both wrong sees the
6061 // counter-axis diagnostic first (matches the order in the
6062 // struct and in the doc comment).
6063 let s = SupervisorSpec {
6064 max_restarts: 0,
6065 restart_window: Some(Duration::ZERO),
6066 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6067 ..SupervisorSpec::default()
6068 };
6069 assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
6070 }
6071
6072 #[test]
6073 fn round_trip_all_strategies() {
6074 for &strat in RestartStrategy::ALL {
6075 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
6076 // shape partition through the [`gen_platform::IsVariant`]
6077 // derive-generated [`RestartStrategy::is_simple_one_for_one`]
6078 // predicate rather than the raw
6079 // `matches!(strat, RestartStrategy::SimpleOneForOne)`
6080 // open-coded pattern-match — same closed-set-typed-enum
6081 // arm-discriminator dispatch discipline the sibling
6082 // [`crate::upgrade::UpgradeInstruction::is_restart`] convergence
6083 // (915a934) extended onto its two paired positive / negated
6084 // `matches!` filter sites, and the sibling
6085 // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
6086 // predicate convergence (766ec63) extended onto the M3 mesh-
6087 // slot per-`:placement` distribution-strategy `matches!`
6088 // discriminator axis. See the sibling
6089 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
6090 // fixture and the peer `manifest::tests::
6091 // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
6092 // fixture — all three sites (the last unlifted
6093 // `matches!`-based arm-discriminator axis on the OTP-shape
6094 // supervisor sibling-restart-strategy closed-set typed enum,
6095 // acknowledged in 915a934's Prior-commits footnote as the
6096 // outstanding follow-up) now consult one typed dispatch on
6097 // the substrate primitive.
6098 let s = SupervisorSpec {
6099 estrategia: strat,
6100 children: if strat.is_simple_one_for_one() {
6101 vec![]
6102 } else {
6103 vec![child("w", "^0.1", RestartPolicy::Permanent)]
6104 },
6105 ..SupervisorSpec::default()
6106 };
6107 let json = serde_json::to_string(&s).unwrap();
6108 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6109 assert_eq!(s, back);
6110 }
6111 }
6112
6113 #[test]
6114 fn round_trip_all_restart_policies() {
6115 for policy in [
6116 RestartPolicy::Permanent,
6117 RestartPolicy::Temporary,
6118 RestartPolicy::Transient,
6119 ] {
6120 let c = child("w", "^0.1", policy);
6121 let json = serde_json::to_string(&c).unwrap();
6122 let back: ChildSpec = serde_json::from_str(&json).unwrap();
6123 assert_eq!(c, back);
6124 }
6125 }
6126
6127 #[test]
6128 fn restart_strategy_is_simple_one_for_one_predicate_partitions_the_arm_set() {
6129 // The fail-before-pass-after pin on the `gen_platform::IsVariant`
6130 // derive's [`RestartStrategy::is_simple_one_for_one`] arm-
6131 // discriminator predicate: [`RestartStrategy::SimpleOneForOne`]
6132 // is the only variant that satisfies `.is_simple_one_for_one()`;
6133 // every static-children-bearing arm (`OneForOne` / `OneForAll`
6134 // / `RestForOne`) returns `false`. This pin makes the partition
6135 // invariant load-bearing at caixa-core test time so a future
6136 // derive regression (a hole that returns `false` for
6137 // `SimpleOneForOne` too, or a byte-collision that flips a second
6138 // variant to `true`) trips here rather than laundering the arm
6139 // at the three test-fixture builder sites (a hole flips the
6140 // `SimpleOneForOne` fixture to carry a non-empty children list
6141 // and the subsequent `SupervisorSpec::validate` would refuse the
6142 // fixture with [`SupervisorError::SimpleOneForOneWithStaticChildren`];
6143 // a collision flips a peer strategy's fixture to carry an empty
6144 // children list and the subsequent `validate` would refuse with
6145 // [`SupervisorError::NoChildren`] — either way, the pin fires
6146 // here, at the derive site, rather than at the fixture-refusal
6147 // site far away). Peer of the sibling
6148 // [`crate::upgrade::tests::upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
6149 // (915a934) pin on the M2 OTP-appup axis and the sibling
6150 // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
6151 // pin on the M0 `:kind` axis.
6152 let cases: &[(RestartStrategy, bool)] = &[
6153 (RestartStrategy::OneForOne, false),
6154 (RestartStrategy::OneForAll, false),
6155 (RestartStrategy::RestForOne, false),
6156 (RestartStrategy::SimpleOneForOne, true),
6157 ];
6158 for (variant, expected) in cases {
6159 assert_eq!(
6160 variant.is_simple_one_for_one(),
6161 *expected,
6162 "RestartStrategy::{variant:?}.is_simple_one_for_one() must \
6163 return {expected} (partition invariant on the \
6164 IsVariant-derived arm-discriminator predicate — every \
6165 test-fixture site that partitions the `:children` slot \
6166 shape on `SimpleOneForOne ↔ non-SimpleOneForOne` keys \
6167 off this typed dispatch, so a derive regression must \
6168 surface here rather than at the fixture-refusal site)"
6169 );
6170 }
6171 }
6172
6173 #[test]
6174 fn restart_strategy_fixture_partition_routes_through_is_simple_one_for_one_predicate() {
6175 // Byte-identity pin on the `SimpleOneForOne ↔ non-SimpleOneForOne`
6176 // fixture-shape partition against the pre-lift
6177 // `matches!(strat, RestartStrategy::SimpleOneForOne)` open-coded
6178 // pattern-match every test-fixture builder site previously
6179 // coupled to inline. Asserts the two projections agree byte-for-
6180 // byte on every arm of the enum, so a future derive regression
6181 // that flipped either predicate's arm-set would surface here at
6182 // caixa-core test time rather than at the three fixture-builder
6183 // sites (`supervisor::tests::round_trip_all_strategies`,
6184 // `supervisor::tests::supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`,
6185 // `manifest::tests::caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`)
6186 // far from the derive site. Same peer-shape byte-identity pin
6187 // every sibling `IsVariant`-derive-routed convergence carries on
6188 // the substrate's closed-set typed-enum surface (peer of
6189 // [`crate::upgrade::tests::validate_restart_exclusive_routes_through_is_restart_predicate`]
6190 // on the M2 OTP-appup axis).
6191 for &strat in RestartStrategy::ALL {
6192 let via_predicate = strat.is_simple_one_for_one();
6193 let via_matches = matches!(strat, RestartStrategy::SimpleOneForOne);
6194 assert_eq!(
6195 via_predicate, via_matches,
6196 "RestartStrategy::{strat:?}: is_simple_one_for_one() must \
6197 byte-equal matches!(_, RestartStrategy::SimpleOneForOne) — \
6198 the pre-lift open-coded pattern and the \
6199 IsVariant-derived predicate are the same axis, \
6200 one typed dispatch"
6201 );
6202 }
6203 }
6204
6205 #[test]
6206 fn duration_codec_round_trip_canonical_units() {
6207 // Note the canonical-form rule: durations serialize to the
6208 // *largest* unit that divides cleanly, so 60s ↔ "1m" and not
6209 // "60s" — but the round-trip preserves the underlying Duration.
6210 let cases = [
6211 ("30s", Duration::from_secs(30)),
6212 ("5m", Duration::from_secs(300)),
6213 ("1h", Duration::from_secs(3600)),
6214 ("500ms", Duration::from_millis(500)),
6215 ];
6216 for (lit, dur) in cases {
6217 let s = SupervisorSpec {
6218 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6219 restart_window: Some(dur),
6220 ..SupervisorSpec::default()
6221 };
6222 let json = serde_json::to_string(&s).unwrap();
6223 assert!(
6224 json.contains(&format!("\"{lit}\"")),
6225 "expected \"{lit}\" in {json}"
6226 );
6227 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6228 assert_eq!(back.restart_window, Some(dur));
6229 }
6230 }
6231
6232 #[test]
6233 fn duration_canonicalizes_to_largest_unit() {
6234 // 60 seconds → "1m" (largest cleanly-divisible unit), but the
6235 // typed Duration still equals 60s on the way back.
6236 let s = SupervisorSpec {
6237 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6238 restart_window: Some(Duration::from_secs(60)),
6239 ..SupervisorSpec::default()
6240 };
6241 let json = serde_json::to_string(&s).unwrap();
6242 assert!(json.contains("\"1m\""), "{json}");
6243 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6244 assert_eq!(back.restart_window, Some(Duration::from_secs(60)));
6245 }
6246
6247 #[test]
6248 fn three_child_one_for_one_validates() {
6249 let s = SupervisorSpec {
6250 estrategia: RestartStrategy::OneForOne,
6251 max_restarts: 5,
6252 restart_window: Some(Duration::from_secs(60)),
6253 children: vec![
6254 child("worker", "^0.1", RestartPolicy::Permanent),
6255 child("cache", "^0.1", RestartPolicy::Transient),
6256 child("scratch", "^0.1", RestartPolicy::Temporary),
6257 ],
6258 };
6259 s.validate().unwrap();
6260 }
6261
6262 #[test]
6263 fn json_uses_pascal_case_for_strategy_and_policy() {
6264 // Variant names are PascalCase by default in serde, matching
6265 // tatara-lisp's enum convention (`:estrategia OneForOne`).
6266 let c = child("w", "^0.1", RestartPolicy::Permanent);
6267 let json = serde_json::to_string(&c).unwrap();
6268 assert!(json.contains("\"Permanent\""));
6269 assert!(!json.contains("\"permanent\""));
6270
6271 let s = SupervisorSpec {
6272 estrategia: RestartStrategy::OneForOne,
6273 children: vec![c],
6274 ..SupervisorSpec::default()
6275 };
6276 let json = serde_json::to_string(&s).unwrap();
6277 assert!(json.contains("\"estrategia\":\"OneForOne\""));
6278 }
6279
6280 // ── shared duration codec: integer-magnitude canonical-form gate ──
6281 //
6282 // The gate lifts the discipline `crate::limits::parse_duration`
6283 // (818dd38) carries on the peer `:limits :wall-clock` codec onto
6284 // the shared codec backing the remaining three typed-duration
6285 // slots: `:supervisor :restart-window`, `:politicas :timeout`, and
6286 // `:politicas :circuit-breaker :window`. Every magnitude `render`
6287 // emits is a non-negative integer with no decimal point and no
6288 // leading sign, so the codec's accepted set must match for
6289 // serialize/deserialize to round-trip without canonical-form
6290 // drift.
6291
6292 #[test]
6293 fn parse_accepts_integer_canonical_units() {
6294 // Pin the happy-path: every canonical author shape `render`
6295 // ever emits parses to the same `Duration` value, so the
6296 // codec's accepted set is at least a superset of its emitted
6297 // set on the canonical-unit axis.
6298 for (lit, dur) in [
6299 ("30s", Duration::from_secs(30)),
6300 ("500ms", Duration::from_millis(500)),
6301 ("2m", Duration::from_secs(120)),
6302 ("1h", Duration::from_secs(3600)),
6303 ("0s", Duration::ZERO),
6304 ] {
6305 assert_eq!(
6306 duration_codec::parse(lit).unwrap(),
6307 dur,
6308 "parse({lit:?}) should be {dur:?}"
6309 );
6310 }
6311 }
6312
6313 #[test]
6314 fn parse_accepts_bare_integer_as_seconds() {
6315 // The `"s" | ""` arm: a bare integer with no unit is read as
6316 // seconds. Pin this so the unit-empty form keeps parsing (it
6317 // renders to `"<n>s"` on serialize — that's a unit-choice
6318 // drift the integer-magnitude gate does NOT close, matching
6319 // the `parse_byte_size` `"1024"` → `"1KiB"` scope decision in
6320 // the peer `:limits :memory` codec).
6321 assert_eq!(
6322 duration_codec::parse("30").unwrap(),
6323 Duration::from_secs(30)
6324 );
6325 }
6326
6327 #[test]
6328 fn parse_rejects_fractional_seconds_with_canonical_form_diagnostic() {
6329 // `"1.5s"` parses as f64 to 1.5 → renders back as `"1500ms"`
6330 // on first serialize — DRIFT. The integer-magnitude gate names
6331 // the offending `"1.5"` verbatim and points at the canonical
6332 // remediation `"1500ms"`.
6333 let err = duration_codec::parse("1.5s").unwrap_err();
6334 assert!(err.contains("\"1.5\""), "missing magnitude in {err:?}");
6335 assert!(
6336 err.contains("not a non-negative integer"),
6337 "missing canonical-form reason in {err:?}"
6338 );
6339 assert!(
6340 err.contains("\"1500ms\""),
6341 "missing canonical-form remediation in {err:?}"
6342 );
6343 }
6344
6345 #[test]
6346 fn parse_rejects_decimal_shaped_integer_seconds() {
6347 // `"1.0s"` is the trickiest drift class: numerically `1.0s` is
6348 // `1s` exactly, so the round-trip looks correct — but the
6349 // emitted canonical form is `"1s"`, not `"1.0s"`. Gate the
6350 // decimal-shape-with-integer-value form so author intent is
6351 // never silently rewritten.
6352 let err = duration_codec::parse("1.0s").unwrap_err();
6353 assert!(err.contains("\"1.0\""), "missing magnitude in {err:?}");
6354 assert!(
6355 err.contains("not a non-negative integer"),
6356 "missing canonical-form reason in {err:?}"
6357 );
6358 }
6359
6360 #[test]
6361 fn parse_rejects_half_unit_minute() {
6362 // `"0.5m"` is the unit-fraction footgun — author writes a
6363 // human-readable half-minute, serde silently rewrites to
6364 // `"30s"` on next emit. The gate names the offending
6365 // magnitude `"0.5"` and points at the integer-in-smaller-unit
6366 // form.
6367 let err = duration_codec::parse("0.5m").unwrap_err();
6368 assert!(err.contains("\"0.5\""), "missing magnitude in {err:?}");
6369 assert!(
6370 err.contains("\"30s\""),
6371 "missing canonical-form remediation in {err:?}"
6372 );
6373 }
6374
6375 #[test]
6376 fn parse_rejects_leading_plus_sign() {
6377 // `u64::from_str` rejects `"+30"` but `f64::from_str` accepts
6378 // it as `30.0` — the prior parser used f64 so `"+30s"` parsed
6379 // cleanly to 30s and round-tripped to `"30s"` on next emit
6380 // (DRIFT). The digit-only gate closes the leading-sign class
6381 // first; the diagnostic names `"+30"` verbatim.
6382 let err = duration_codec::parse("+30s").unwrap_err();
6383 assert!(err.contains("\"+30\""), "missing magnitude in {err:?}");
6384 assert!(
6385 err.contains("not a non-negative integer"),
6386 "missing canonical-form reason in {err:?}"
6387 );
6388 }
6389
6390 #[test]
6391 fn parse_rejects_leading_minus_sign() {
6392 // The former `num < 0.0` arm: `"-30s"` parsed as f64 to -30,
6393 // rejected with `"negative duration in \"-30s\""`. Under the
6394 // integer-magnitude gate the diagnostic is unified — `-30` is
6395 // non-digit-only, f64-numeric, and surfaces with the canonical-
6396 // form reason (no leading `+` / `-` sign) naming the offending
6397 // `"-30"` verbatim. Same diagnostic shape as every other
6398 // rejected non-integer magnitude.
6399 let err = duration_codec::parse("-30s").unwrap_err();
6400 assert!(err.contains("\"-30\""), "missing magnitude in {err:?}");
6401 assert!(
6402 err.contains("not a non-negative integer"),
6403 "missing canonical-form reason in {err:?}"
6404 );
6405 }
6406
6407 #[test]
6408 fn parse_garbage_still_falls_through_to_bad_magnitude() {
6409 // Non-digit-only AND non-numeric (`"--1s"`, `"abc"`) falls
6410 // through to the narrower "bad duration magnitude" arm — the
6411 // canonical-form diagnostic is reserved for the parser-shape
6412 // footgun case, not the "not a number at all" case. Same
6413 // shape `parse_byte_size`'s `BadByteMagnitude` arm carries on
6414 // the peer `:limits :memory` codec.
6415 let err = duration_codec::parse("--1s").unwrap_err();
6416 assert!(
6417 err.contains("bad duration magnitude"),
6418 "expected bad-magnitude wording in {err:?}"
6419 );
6420 }
6421
6422 #[test]
6423 fn parse_digit_only_magnitude_carries_zero_f64_drift() {
6424 // The accepted set is now closed under `u64`-exact integer
6425 // arithmetic: `"500ms"` → `Duration::from_millis(500)` exactly,
6426 // `"3600s"` → `Duration::from_secs(3600)` exactly, `"1h"` →
6427 // `Duration::from_secs(3600)` exactly, no f64 mantissa drift
6428 // possible. Pin the integer-exact arms across the four unit
6429 // suffixes so a future refactor that reaches back for f64
6430 // (`from_secs_f64`, `mul_f64`) surfaces here.
6431 assert_eq!(
6432 duration_codec::parse("3600s").unwrap(),
6433 Duration::from_secs(3600)
6434 );
6435 assert_eq!(
6436 duration_codec::parse("60m").unwrap(),
6437 Duration::from_secs(3600)
6438 );
6439 assert_eq!(
6440 duration_codec::parse("1h").unwrap(),
6441 Duration::from_secs(3600)
6442 );
6443 assert_eq!(
6444 duration_codec::parse("999ms").unwrap(),
6445 Duration::from_millis(999)
6446 );
6447 }
6448
6449 #[test]
6450 fn restart_window_serde_rejects_fractional_seconds() {
6451 // The shared codec backs `SupervisorSpec::restart_window`
6452 // (`with = "duration_codec"`) — so the gate applies on serde
6453 // deserialize for the typed Supervisor slot. A
6454 // `{"restartWindow":"1.5s"}` payload that previously round-
6455 // tripped to a different canonical string on next serialize
6456 // is now refused at deserialize with the integer-magnitude
6457 // diagnostic.
6458 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6459 "restartWindow":"1.5s",
6460 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6461 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6462 let msg = err.to_string();
6463 assert!(
6464 msg.contains("not a non-negative integer"),
6465 "expected integer-magnitude diagnostic in {msg:?}"
6466 );
6467 assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
6468 }
6469
6470 #[test]
6471 fn restart_window_serde_rejects_leading_plus() {
6472 // The `u64::from_str` leading-`+` permissiveness gap that
6473 // motivated the digit-only gate (the `f64`-side accepted
6474 // `"+30"`, the prior parser silently round-tripped to `"30s"`)
6475 // is now closed on the shared codec — surfaces as a structured
6476 // diagnostic at the serde layer for every typed-duration slot.
6477 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6478 "restartWindow":"+30s",
6479 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6480 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6481 let msg = err.to_string();
6482 assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
6483 assert!(
6484 msg.contains("not a non-negative integer"),
6485 "missing canonical-form reason in {msg:?}"
6486 );
6487 }
6488
6489 #[test]
6490 fn parse_rejects_leading_zero_magnitude() {
6491 // `"030s"` is digit-only, so the existing non-digit-only / sign
6492 // / fractional arm doesn't catch it — `u64::from_str("030")`
6493 // returns `Ok(30)`, so before this gate `"030s"` parsed to
6494 // `Duration::from_secs(30)` and round-tripped through `render`
6495 // to `"30s"` — a *different* canonical string on the next emit,
6496 // breaking the THEORY.md Part V render-determinism contract
6497 // exactly the way `"+30s"` did before the leading-`+` arm
6498 // landed. Peer with the `rate_limit_codec` leading-zero arm
6499 // (4f46830) on the same canonical-form-drift axis.
6500 let err = duration_codec::parse("030s").unwrap_err();
6501 assert!(
6502 err.contains("non-canonical leading zero"),
6503 "expected leading-zero diagnostic in {err:?}"
6504 );
6505 assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
6506 assert!(
6507 err.contains("\"30s\""),
6508 "missing canonical-form remediation in {err:?}"
6509 );
6510 assert!(
6511 err.contains("THEORY.md"),
6512 "missing render-determinism citation in {err:?}"
6513 );
6514 }
6515
6516 #[test]
6517 fn parse_rejects_multi_digit_zero_magnitude() {
6518 // `"00s"` and `"00ms"` are the all-zero leading-zero footgun —
6519 // digit-only, parse losslessly to `Duration::ZERO`, but render
6520 // back to `"0s"` (the single-byte canonical form) on the next
6521 // emit. The leading-zero arm refuses the drift class at the
6522 // codec layer; the semantic-zero gate downstream
6523 // (`SupervisorError::ZeroRestartWindow`, etc.) would refuse
6524 // the single-byte canonical form `"0s"` separately on the
6525 // typed-validate layer.
6526 let err = duration_codec::parse("00s").unwrap_err();
6527 assert!(
6528 err.contains("non-canonical leading zero"),
6529 "expected leading-zero diagnostic in {err:?}"
6530 );
6531 assert!(err.contains("\"00\""), "missing magnitude in {err:?}");
6532 }
6533
6534 #[test]
6535 fn parse_rejects_leading_zero_per_hour_window() {
6536 // `"01h"` is the per-hour-window footgun — multi-byte magnitude
6537 // starting with `0`, parses losslessly to `Duration::from_secs(3600)`,
6538 // renders to `"1h"` (DRIFT). The arm is unit-agnostic: every
6539 // canonical unit suffix the codec accepts (`ms` / `s` / `m` /
6540 // `h` / bare-integer-as-seconds) inherits the same gate.
6541 let err = duration_codec::parse("01h").unwrap_err();
6542 assert!(
6543 err.contains("non-canonical leading zero"),
6544 "expected leading-zero diagnostic in {err:?}"
6545 );
6546 assert!(err.contains("\"01\""), "missing magnitude in {err:?}");
6547 }
6548
6549 #[test]
6550 fn parse_rejects_leading_zero_bare_integer_as_seconds() {
6551 // The `parse_accepts_bare_integer_as_seconds` happy-path
6552 // (`"30"` → 30s) inherits the leading-zero arm: `"030"` is
6553 // multi-byte starts-with-`0`, parses losslessly to
6554 // `Duration::from_secs(30)`, renders to `"30s"` (DRIFT). The
6555 // bare-integer surface accepts permissive unit-empty
6556 // shorthand but still must reject leading-zero padding.
6557 let err = duration_codec::parse("030").unwrap_err();
6558 assert!(
6559 err.contains("non-canonical leading zero"),
6560 "expected leading-zero diagnostic in {err:?}"
6561 );
6562 assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
6563 }
6564
6565 #[test]
6566 fn parse_accepts_single_zero_magnitude_at_codec_layer() {
6567 // The codec-layer / typed-validate-layer boundary: `"0s"` /
6568 // `"0ms"` / `"0"` are the single-byte canonical-zero forms —
6569 // each round-trips losslessly through `render`
6570 // (`render(Duration::ZERO)` → `"0s"`), so the codec layer
6571 // accepts them. The downstream semantic-zero gates
6572 // (`SupervisorError::ZeroRestartWindow`,
6573 // `AplicacaoError::PolicyTimeoutZero`,
6574 // `AplicacaoError::PolicyCircuitBreakerWindowZero`) refuse
6575 // zero-magnitude authoring at the typed-validate layer above,
6576 // peer with the `rate_limit_codec` codec-layer / typed-
6577 // validate-layer partition for `"0/s"`.
6578 assert_eq!(duration_codec::parse("0s").unwrap(), Duration::ZERO);
6579 assert_eq!(duration_codec::parse("0ms").unwrap(), Duration::ZERO);
6580 assert_eq!(duration_codec::parse("0").unwrap(), Duration::ZERO);
6581 }
6582
6583 #[test]
6584 fn parse_accepts_canonical_magnitude_with_leading_one() {
6585 // The complementary boundary: a future tightening cannot
6586 // drift into rejecting valid canonical magnitudes that
6587 // happen to start with `1` (or any digit `[1-9]`). Pin
6588 // every canonical-unit suffix so the leading-zero arm
6589 // remains strictly narrower than the digit-only arm.
6590 assert_eq!(
6591 duration_codec::parse("100ms").unwrap(),
6592 Duration::from_millis(100)
6593 );
6594 assert_eq!(
6595 duration_codec::parse("100s").unwrap(),
6596 Duration::from_secs(100)
6597 );
6598 assert_eq!(
6599 duration_codec::parse("10m").unwrap(),
6600 Duration::from_secs(600)
6601 );
6602 assert_eq!(
6603 duration_codec::parse("10h").unwrap(),
6604 Duration::from_secs(36_000)
6605 );
6606 }
6607
6608 #[test]
6609 fn restart_window_serde_rejects_leading_zero() {
6610 // The shared codec backs `SupervisorSpec::restart_window`
6611 // (`with = "duration_codec"`) — so the leading-zero arm
6612 // applies on serde deserialize for the typed Supervisor slot.
6613 // A `{"restartWindow":"030s"}` payload that previously round-
6614 // tripped to a different canonical string on next serialize
6615 // is now refused at deserialize with the leading-zero
6616 // diagnostic. Peer with `restart_window_serde_rejects_leading_plus`
6617 // / `restart_window_serde_rejects_fractional_seconds` on the
6618 // same canonical-form-drift axis.
6619 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6620 "restartWindow":"030s",
6621 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6622 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6623 let msg = err.to_string();
6624 assert!(
6625 msg.contains("non-canonical leading zero"),
6626 "expected leading-zero diagnostic in {msg:?}"
6627 );
6628 assert!(msg.contains("\"030\""), "missing magnitude in {msg:?}");
6629 }
6630
6631 #[test]
6632 fn parse_rejects_leading_whitespace() {
6633 // `" 30s"` — the canonical paste-from-aligned-doc /
6634 // paste-from-YAML-quoted-plain-scalar footgun. Before this
6635 // gate the top-level `s.trim()` at parse entry silently ate
6636 // the leading space and parsed the value to
6637 // `Duration::from_secs(30)`, which then round-tripped through
6638 // `render` to `"30s"` (a *different* canonical string on the
6639 // next emit) — the exact canonical-form-drift class the
6640 // leading-`+` / leading-zero arms already close, extended
6641 // to the whitespace-byte class. Peer with the sibling
6642 // `rate_limit_codec` whitespace-rejection arm (1ad7755) on
6643 // the M3 `:politicas` axis.
6644 let err = duration_codec::parse(" 30s").unwrap_err();
6645 assert!(
6646 err.contains("contains whitespace byte"),
6647 "expected whitespace diagnostic in {err:?}"
6648 );
6649 assert!(err.contains("0x20"), "missing offending byte in {err:?}");
6650 assert!(
6651 err.contains("THEORY.md"),
6652 "missing render-determinism contract citation in {err:?}"
6653 );
6654 }
6655
6656 #[test]
6657 fn parse_rejects_trailing_whitespace() {
6658 // `"30s "` — the canonical shell-history / trailing-space
6659 // paste footgun. Before this gate the top-level `s.trim()`
6660 // silently ate the trailing space and parsed to
6661 // `Duration::from_secs(30)`, round-tripping to `"30s"` on the
6662 // next emit — same canonical-form drift as the leading-space
6663 // sibling, closed on the same whitespace-byte arm.
6664 let err = duration_codec::parse("30s ").unwrap_err();
6665 assert!(
6666 err.contains("contains whitespace byte"),
6667 "expected whitespace diagnostic in {err:?}"
6668 );
6669 assert!(err.contains("0x20"), "missing offending byte in {err:?}");
6670 }
6671
6672 #[test]
6673 fn parse_rejects_internal_whitespace_between_magnitude_and_unit() {
6674 // `"30 s"` — the canonical typographically-spaced author
6675 // shape (the same idiom every prose reference to a duration
6676 // renders as, mistakenly retained when the value is pasted
6677 // into a codec-shaped slot). Before this gate the per-part
6678 // `num_part.trim()` / `unit.trim()` calls silently ate the
6679 // whitespace between the magnitude and the unit and parsed
6680 // the value to `Duration::from_secs(30)`, round-tripping to
6681 // `"30s"` — the codec's *internal* whitespace-tolerance
6682 // vector, orthogonal to the leading / trailing surface but
6683 // the same canonical-form-drift class. Pins the arm as
6684 // strictly stronger than the pre-existing top-level
6685 // `s.trim()` behavior: it fires on whitespace anywhere in
6686 // the value, not just at the string boundary.
6687 let err = duration_codec::parse("30 s").unwrap_err();
6688 assert!(
6689 err.contains("contains whitespace byte"),
6690 "expected whitespace diagnostic in {err:?}"
6691 );
6692 assert!(err.contains("0x20"), "missing offending byte in {err:?}");
6693 }
6694
6695 #[test]
6696 fn parse_rejects_tab_byte() {
6697 // `"\t30s"` — the canonical paste-from-indented-doc /
6698 // paste-from-YAML-block-scalar footgun where a tab byte leads
6699 // the magnitude. Pins that the gate covers tab (`0x09`) as
6700 // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
6701 // members and both would be silently swallowed by `s.trim()`
6702 // pre-gate. The `is_ascii_whitespace` coverage extends beyond
6703 // space alone to the full ASCII-whitespace set (space `0x20`,
6704 // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
6705 // the tab arm as a representative of the non-space members.
6706 let err = duration_codec::parse("\t30s").unwrap_err();
6707 assert!(
6708 err.contains("contains whitespace byte"),
6709 "expected whitespace diagnostic in {err:?}"
6710 );
6711 assert!(
6712 err.contains("0x09"),
6713 "missing offending tab byte in {err:?}"
6714 );
6715 }
6716
6717 #[test]
6718 fn restart_window_serde_rejects_whitespace() {
6719 // The shared codec backs `SupervisorSpec::restart_window`
6720 // (`with = "duration_codec"`) — so the whitespace arm
6721 // applies on serde deserialize for the typed Supervisor slot.
6722 // A `{"restartWindow":" 30s"}` payload that previously round-
6723 // tripped to a different canonical string on next serialize
6724 // is now refused at deserialize with the whitespace-byte
6725 // diagnostic. Peer with `restart_window_serde_rejects_leading_zero`
6726 // / `restart_window_serde_rejects_leading_plus` /
6727 // `restart_window_serde_rejects_fractional_seconds` on the
6728 // same canonical-form-drift axis.
6729 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6730 "restartWindow":" 30s",
6731 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6732 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6733 let msg = err.to_string();
6734 assert!(
6735 msg.contains("contains whitespace byte"),
6736 "expected whitespace diagnostic in {msg:?}"
6737 );
6738 assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
6739 }
6740
6741 // ── canonical-form: non-ASCII Unicode `White_Space` duration gate ─────
6742 //
6743 // Successor to the ASCII-whitespace arm (a7ae622) on the shared
6744 // duration codec — closes the strictly-complementary class the
6745 // byte-scan cannot see, through the lifted
6746 // [`crate::render::find_non_ascii_whitespace_char`] predicate.
6747 // Applies to `:supervisor :restart-window`, `:politicas :timeout`,
6748 // and `:politicas :circuit-breaker :window` simultaneously via
6749 // this shared codec.
6750
6751 #[test]
6752 fn duration_codec_parse_rejects_leading_nbsp() {
6753 // NBSP prefix — the strictly-complementary drift class the
6754 // ASCII byte-scan cannot see. `str::trim` strips it silently
6755 // and the value drifts to `"30s"` on next serialize.
6756 let err = duration_codec::parse("\u{00A0}30s").unwrap_err();
6757 assert!(
6758 err.contains("non-ASCII Unicode whitespace character"),
6759 "expected non-ASCII whitespace diagnostic in {err:?}"
6760 );
6761 assert!(err.contains("U+00A0"), "missing codepoint in {err:?}");
6762 }
6763
6764 #[test]
6765 fn duration_codec_parse_rejects_trailing_line_separator() {
6766 // LINE SEPARATOR (`\u{2028}`) trailing — paste-from-web-doc
6767 // footgun.
6768 let err = duration_codec::parse("30s\u{2028}").unwrap_err();
6769 assert!(
6770 err.contains("non-ASCII Unicode whitespace character"),
6771 "expected non-ASCII whitespace diagnostic in {err:?}"
6772 );
6773 assert!(err.contains("U+2028"), "missing codepoint in {err:?}");
6774 }
6775
6776 #[test]
6777 fn duration_codec_parse_accepts_ascii_only_forms_after_unicode_arm() {
6778 // Positive-control pin: every ASCII-only canonical form the
6779 // renderer emits stays accepted through the new arm.
6780 assert_eq!(
6781 duration_codec::parse("30s").unwrap(),
6782 Duration::from_secs(30)
6783 );
6784 assert_eq!(
6785 duration_codec::parse("500ms").unwrap(),
6786 Duration::from_millis(500)
6787 );
6788 assert_eq!(
6789 duration_codec::parse("1h").unwrap(),
6790 Duration::from_secs(3600)
6791 );
6792 }
6793
6794 #[test]
6795 fn restart_window_serde_rejects_non_ascii_whitespace() {
6796 // The shared codec backs `SupervisorSpec::restart_window` — so
6797 // the new non-ASCII Unicode whitespace arm applies on serde
6798 // deserialize for the typed Supervisor slot. A
6799 // `{"restartWindow":" 30s"}` payload that previously
6800 // survived the ASCII byte-scan (only ASCII whitespace was
6801 // refused) is now refused at deserialize with the
6802 // non-ASCII-whitespace-and-codepoint diagnostic.
6803 let payload = "{\"estrategia\":\"OneForOne\",\"maxRestarts\":5,\
6804 \"restartWindow\":\"\u{00A0}30s\",\
6805 \"children\":[{\"caixa\":\"w\",\"versao\":\"^0.1\",\"restart\":\"Permanent\"}]}";
6806 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6807 let msg = err.to_string();
6808 assert!(
6809 msg.contains("non-ASCII Unicode whitespace character"),
6810 "expected non-ASCII whitespace diagnostic in {msg:?}"
6811 );
6812 assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
6813 }
6814
6815 // ── drift-detection: serde-derive-to-SUPERVISOR_KEY_* identity ────────
6816
6817 #[test]
6818 fn supervisor_spec_serde_keys_match_lifted_supervisor_key_consts() {
6819 // Load-bearing invariant: the four `SUPERVISOR_KEY_*` consts
6820 // (`SUPERVISOR_KEY_ESTRATEGIA` / `SUPERVISOR_KEY_MAX_RESTARTS` /
6821 // `SUPERVISOR_KEY_RESTART_WINDOW` / `SUPERVISOR_KEY_CHILDREN`)
6822 // name the exact camelCase JSON keys the
6823 // `#[serde(rename_all = "camelCase")]` attribute on
6824 // `SupervisorSpec` emits. Serialize a fully-populated spec (each
6825 // field carries `Some(_)` / non-empty) and pin that each canonical
6826 // byte-sequence appears verbatim in the JSON — a future accidental
6827 // `rename_all = "snake_case"` / `"kebab-case"` / verbatim-field-
6828 // name flip at the derive attribute (any of which would silently
6829 // break every downstream JSON consumer that reaches for one of the
6830 // four consts via `Value::get(...)`) surfaces here as a build-time
6831 // test failure at `supervisor.rs`, not as an apply-time
6832 // `.get(<stale-canonical-const>)` returning `None` far from the
6833 // derive-attr drift's commit. Peer with the sibling
6834 // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
6835 // (d8b8b4f) pin on the M2 `:limits` axis — same discipline the
6836 // M2 typed-slot family established, extended here to close the
6837 // top-level Supervisor axis.
6838 let spec = SupervisorSpec {
6839 estrategia: RestartStrategy::OneForOne,
6840 max_restarts: 5,
6841 restart_window: Some(Duration::from_secs(60)),
6842 children: vec![ChildSpec {
6843 caixa: "w".into(),
6844 versao: "^0.1".into(),
6845 restart: RestartPolicy::Permanent,
6846 }],
6847 };
6848 let json = serde_json::to_string(&spec).unwrap();
6849 for key in [
6850 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6851 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6852 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6853 crate::render::SUPERVISOR_KEY_CHILDREN,
6854 ] {
6855 let quoted = format!("\"{key}\"");
6856 assert!(
6857 json.contains("ed),
6858 "serialized SupervisorSpec must carry the lifted \
6859 SUPERVISOR_KEY_* byte-sequence {quoted} verbatim in \
6860 the JSON emission (got: {json})",
6861 );
6862 }
6863 }
6864
6865 #[test]
6866 fn supervisor_key_consts_are_pairwise_distinct() {
6867 // Cross-axis drift-detection pin: a future collapse of two
6868 // canonical top-level byte-strings onto the same value (e.g. an
6869 // accidental copy-paste flip of `SUPERVISOR_KEY_CHILDREN` to
6870 // also read `"estrategia"`) would silently reroute every
6871 // downstream probe on one axis onto the sibling axis's overlay
6872 // entry and pass every propagation-probe test that expected only
6873 // the stale axis's value. Peer of the sibling four-way distinct
6874 // pin on the `M2_LIMITS_KEY_*` tetrad (d8b8b4f).
6875 let all = [
6876 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6877 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6878 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6879 crate::render::SUPERVISOR_KEY_CHILDREN,
6880 ];
6881 for (i, a) in all.iter().enumerate() {
6882 for b in all.iter().skip(i + 1) {
6883 assert_ne!(
6884 a, b,
6885 "SUPERVISOR_KEY_* consts must be pairwise-distinct \
6886 canonical byte-sequences — got `{a}` == `{b}`",
6887 );
6888 }
6889 }
6890 }
6891
6892 #[test]
6893 fn supervisor_key_consts_are_lower_camel_case_shape() {
6894 // Shape-pin: every `SUPERVISOR_KEY_*` const must be a
6895 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
6896 // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
6897 // capital, no whitespace / dots) — the canonical shape the
6898 // `#[serde(rename_all = "camelCase")]` derive produces on
6899 // `SupervisorSpec`. A future flip to a non-camelCase attribute
6900 // at the derive surfaces both here (this test fails on the
6901 // stale-constant shape) and at
6902 // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
6903 // (that test fails on the mismatch between const and derive).
6904 // Peer with `m2_limits_key_consts_are_lower_camel_case_shape`
6905 // (d8b8b4f) on the sibling M2 `:limits` axis.
6906 for key in [
6907 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6908 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6909 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6910 crate::render::SUPERVISOR_KEY_CHILDREN,
6911 ] {
6912 assert!(
6913 !key.is_empty(),
6914 "SUPERVISOR_KEY_* must be non-empty (got {key:?})"
6915 );
6916 let first = key.chars().next().unwrap();
6917 assert!(
6918 first.is_ascii_lowercase(),
6919 "SUPERVISOR_KEY_* must lead with an ASCII-lowercase byte \
6920 (got {key:?}, leads with {first:?})",
6921 );
6922 assert!(
6923 key.chars().all(|c| c.is_ascii_alphanumeric()),
6924 "SUPERVISOR_KEY_* must be ASCII-alphanumeric only \
6925 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
6926 );
6927 }
6928 }
6929
6930 #[test]
6931 fn supervisor_key_consts_are_byte_distinct_from_supervisor_author_key_peers() {
6932 // Cross-axis drift pin: the four `SUPERVISOR_KEY_*` consts
6933 // (camelCase JSON keys, no leading colon) must never collide
6934 // byte-for-byte with the four peer `SUPERVISOR_AUTHOR_KEY_*`
6935 // consts (kebab-case author-facing labels with leading colon)
6936 // that sit next to them at `caixa_core::render`. Both families
6937 // cover the same four typed Supervisor slots on two distinct
6938 // axes (author-side kebab vs renderer-side camelCase);
6939 // collapsing either family onto the other's byte-shape would
6940 // silently reroute the render-side probe onto the author-facing
6941 // surface, or vice versa. Peer of the byte-distinctness
6942 // discipline the `M3_PLACEMENT_KEY_ESTRATEGIA` docstring names
6943 // against the peer `M3_AUTHOR_KEY_PLACEMENT`.
6944 let pairs = [
6945 (
6946 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6947 crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA,
6948 ),
6949 (
6950 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6951 crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS,
6952 ),
6953 (
6954 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6955 crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW,
6956 ),
6957 (
6958 crate::render::SUPERVISOR_KEY_CHILDREN,
6959 crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN,
6960 ),
6961 ];
6962 for (json_key, author_key) in pairs {
6963 assert_ne!(
6964 json_key, author_key,
6965 "SUPERVISOR_KEY_* (JSON side) must differ byte-for-byte \
6966 from the peer SUPERVISOR_AUTHOR_KEY_* (author side); \
6967 got JSON `{json_key}` == author `{author_key}`",
6968 );
6969 }
6970 }
6971
6972 // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_KEY_* identity ──
6973
6974 #[test]
6975 fn child_spec_serde_keys_match_lifted_supervisor_child_key_consts() {
6976 // Load-bearing invariant: the three `SUPERVISOR_CHILD_KEY_*` consts
6977 // (`SUPERVISOR_CHILD_KEY_CAIXA` / `SUPERVISOR_CHILD_KEY_VERSAO` /
6978 // `SUPERVISOR_CHILD_KEY_RESTART`) name the exact camelCase JSON
6979 // keys the `#[serde(rename_all = "camelCase")]` attribute on
6980 // `ChildSpec` emits. Serialize a fully-populated `ChildSpec` and
6981 // pin that each canonical byte-sequence appears verbatim in the
6982 // JSON — a future accidental `rename_all = "snake_case"` /
6983 // `"kebab-case"` / verbatim-field-name flip at the derive
6984 // attribute (any of which would silently break every downstream
6985 // JSON consumer that reaches for one of the three consts via
6986 // `Value::get(...)`) surfaces here as a build-time test failure at
6987 // `supervisor.rs`, not as an apply-time
6988 // `.get(<stale-canonical-const>)` returning `None` far from the
6989 // derive-attr drift's commit. Peer with the enclosing
6990 // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
6991 // (40cc4e5) pin on the M2 supervision-tree top-level axis — same
6992 // discipline the SupervisorSpec top-level lift established,
6993 // extended here to the sibling per-`:children` entry `ChildSpec`
6994 // derive so the last M2 typed-struct sub-block
6995 // `#[serde(rename_all = "camelCase")]` axis on the Supervisor
6996 // surface without a lifted serde-key peer joins the substrate's
6997 // "one canonical byte-string per typed serialized-key axis"
6998 // discipline.
6999 let c = ChildSpec {
7000 caixa: "worker".into(),
7001 versao: "^0.1".into(),
7002 restart: RestartPolicy::Permanent,
7003 };
7004 let json = serde_json::to_string(&c).unwrap();
7005 for key in [
7006 crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
7007 crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
7008 crate::render::SUPERVISOR_CHILD_KEY_RESTART,
7009 ] {
7010 let quoted = format!("\"{key}\"");
7011 assert!(
7012 json.contains("ed),
7013 "serialized ChildSpec must carry the lifted \
7014 SUPERVISOR_CHILD_KEY_* byte-sequence {quoted} verbatim \
7015 in the JSON emission (got: {json})",
7016 );
7017 }
7018 }
7019
7020 #[test]
7021 fn supervisor_child_key_consts_are_pairwise_distinct() {
7022 // Cross-axis drift-detection pin: a future collapse of two
7023 // canonical `ChildSpec` per-entry byte-strings onto the same
7024 // value (e.g. an accidental copy-paste flip of
7025 // `SUPERVISOR_CHILD_KEY_RESTART` to also read `"caixa"`) would
7026 // silently reroute every downstream probe on one axis onto the
7027 // sibling axis's overlay entry and pass every propagation-probe
7028 // test that expected only the stale axis's value. Peer of the
7029 // sibling three-way distinct pin on the `CONTRATO_KEY_*` triad
7030 // (ca463a4) and the two-way distinct pin on the `MEMBRO_KEY_*`
7031 // pair (ce80ca0).
7032 let all = [
7033 crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
7034 crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
7035 crate::render::SUPERVISOR_CHILD_KEY_RESTART,
7036 ];
7037 for (i, a) in all.iter().enumerate() {
7038 for b in all.iter().skip(i + 1) {
7039 assert_ne!(
7040 a, b,
7041 "SUPERVISOR_CHILD_KEY_* consts must be pairwise-\
7042 distinct canonical byte-sequences — got `{a}` == `{b}`",
7043 );
7044 }
7045 }
7046 }
7047
7048 #[test]
7049 fn supervisor_child_key_consts_are_lower_camel_case_shape() {
7050 // Shape-pin: every `SUPERVISOR_CHILD_KEY_*` const must be a
7051 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
7052 // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
7053 // capital, no whitespace / dots) — the canonical shape the
7054 // `#[serde(rename_all = "camelCase")]` derive produces on
7055 // `ChildSpec`. A future flip to a non-camelCase attribute at the
7056 // derive surfaces both here (this test fails on the
7057 // stale-constant shape) and at
7058 // `child_spec_serde_keys_match_lifted_supervisor_child_key_consts`
7059 // (that test fails on the mismatch between const and derive).
7060 // Peer with `supervisor_key_consts_are_lower_camel_case_shape`
7061 // (40cc4e5) on the sibling `SupervisorSpec` top-level axis.
7062 for key in [
7063 crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
7064 crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
7065 crate::render::SUPERVISOR_CHILD_KEY_RESTART,
7066 ] {
7067 assert!(
7068 !key.is_empty(),
7069 "SUPERVISOR_CHILD_KEY_* must be non-empty (got {key:?})"
7070 );
7071 let first = key.chars().next().unwrap();
7072 assert!(
7073 first.is_ascii_lowercase(),
7074 "SUPERVISOR_CHILD_KEY_* must lead with an ASCII-lowercase \
7075 byte (got {key:?}, leads with {first:?})",
7076 );
7077 assert!(
7078 key.chars().all(|c| c.is_ascii_alphanumeric()),
7079 "SUPERVISOR_CHILD_KEY_* must be ASCII-alphanumeric only \
7080 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
7081 );
7082 }
7083 }
7084
7085 // ── drift-detection: serde-derive-to-SUPERVISOR_ESTRATEGIA_* identity ────
7086
7087 #[test]
7088 fn restart_strategy_variants_serialize_to_lifted_scalar_values() {
7089 // The fail-before-pass-after pin: pre-lift there was no
7090 // single-source binding between the [`RestartStrategy`] variant
7091 // name the un-`rename`d `Serialize` derive emits under
7092 // [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the byte-string
7093 // every downstream cluster-side dispatcher (the future
7094 // wasm-operator's per-supervisor sibling-restart branch, the
7095 // future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
7096 // admission-time enum-arm bind, the `caixa-operator`'s
7097 // hierarchical reconciliation scheduler's per-strategy fan-out)
7098 // probes verbatim. A future `#[serde(rename_all = "kebab-case")]`
7099 // attribute on the enum — or a per-variant `#[serde(rename = "…")]`
7100 // override, or a variant rename in the source — would silently
7101 // rebrand the emitted scalar under one spelling while every
7102 // downstream dispatcher still probed the other, with the failure
7103 // surfacing at the operator's reconcile posture (subtrees coming
7104 // up under the `default()` `OneForOne` arm rather than the typed
7105 // slot's declared strategy — a bad child would then only take
7106 // itself down instead of the sibling set the author intended, so
7107 // shared-state children fall out of sync) far from the source
7108 // rebrand commit and with no field naming the drift. Pinning the
7109 // two paths (the `Serialize` derive's serialized string AND the
7110 // [`RestartStrategy::as_str`] helper) to the same four lifted
7111 // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
7112 // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
7113 // [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
7114 // [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
7115 // byte-strings makes any future drift on either endpoint fail
7116 // here at caixa-core build time. Peer of the M3
7117 // `placement_strategy_variants_serialize_to_lifted_scalar_values`
7118 // (3f0e21c) on the sibling `PlacementStrategy` axis — same
7119 // three-path-convergence discipline, extended to close the
7120 // OTP-shaped per-supervisor sibling-restart axis.
7121 for (variant, expected) in [
7122 (
7123 RestartStrategy::OneForOne,
7124 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7125 ),
7126 (
7127 RestartStrategy::OneForAll,
7128 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7129 ),
7130 (
7131 RestartStrategy::RestForOne,
7132 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7133 ),
7134 (
7135 RestartStrategy::SimpleOneForOne,
7136 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7137 ),
7138 ] {
7139 let json = serde_json::to_string(&variant).unwrap();
7140 assert_eq!(
7141 json,
7142 format!("\"{expected}\""),
7143 "RestartStrategy::{variant:?} must serialize to {expected:?}"
7144 );
7145 assert_eq!(
7146 variant.as_str(),
7147 expected,
7148 "RestartStrategy::{variant:?}.as_str() must return the lifted \
7149 SUPERVISOR_ESTRATEGIA_* constant"
7150 );
7151 }
7152 }
7153
7154 #[test]
7155 fn supervisor_estrategia_consts_are_pairwise_distinct() {
7156 // Cross-arm drift-detection pin: a future collapse of two
7157 // canonical variant byte-strings onto the same value (e.g. an
7158 // accidental copy-paste flip of `SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`
7159 // to also read `"OneForOne"`) would silently reroute every
7160 // downstream operator's per-strategy dispatch onto the sibling
7161 // arm's reconcile branch and pass every propagation-probe test
7162 // that expected only the stale arm's value — the mis-strategied
7163 // subtree would come up with the wrong sibling-restart posture
7164 // on every subsequent failure. Peer of the sibling four-way
7165 // distinct pin `supervisor_key_consts_are_pairwise_distinct`
7166 // (40cc4e5) on the top-level `SUPERVISOR_KEY_*` axis.
7167 let all = [
7168 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7169 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7170 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7171 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7172 ];
7173 for (i, a) in all.iter().enumerate() {
7174 for (j, b) in all.iter().enumerate() {
7175 if i != j {
7176 assert_ne!(
7177 a, b,
7178 "SUPERVISOR_ESTRATEGIA_* consts must be pairwise distinct \
7179 — got duplicate {a:?} at indices {i} and {j}",
7180 );
7181 }
7182 }
7183 }
7184 }
7185
7186 #[test]
7187 fn restart_strategy_display_routes_through_as_str_helper() {
7188 // The fail-before-pass-after pin on the first half of the
7189 // three-path convergence: pre-convergence the sibling
7190 // OTP-shape typed enum [`RestartStrategy`] carried a
7191 // [`std::fmt::Display`] surface via its
7192 // `#[discriminant(also_display)]` gen-platform derive route,
7193 // which arrived kebab-case as `"one-for-one"` /
7194 // `"one-for-all"` / `"rest-for-one"` /
7195 // `"simple-one-for-one"` while the wire format ran as
7196 // PascalCase `"OneForOne"` / `"OneForAll"` / `"RestForOne"` /
7197 // `"SimpleOneForOne"` through the un-`rename`d serde derive.
7198 // Every consumer reaching for a strategy byte-string past the
7199 // wire format had to pick between three paths
7200 // ([`RestartStrategy::as_str`], the `Serialize` derive's
7201 // serialized string, or `format!("{v}")` on the
7202 // discriminant-Display route), any two of which a future
7203 // variant rename or `#[serde(rename_all = "kebab-case")]`
7204 // attribute would silently desynchronize. Wiring
7205 // [`std::fmt::Display`] through [`RestartStrategy::as_str`]
7206 // closes the third path: every `format!("{v}")` call reaches
7207 // the same lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
7208 // const the wire format and the [`RestartStrategy::as_str`]
7209 // helper already route through, so a future variant rename
7210 // lands at exactly one place. Pin the routing here so a future
7211 // `impl std::fmt::Display for RestartStrategy`
7212 // reimplementation that hand-rolls the arms instead of
7213 // delegating to [`RestartStrategy::as_str`] fails at
7214 // caixa-core build time. Peer of the M3
7215 // `placement_strategy_display_routes_through_as_str_helper`
7216 // (cc8f749) which the M3 axis converged first.
7217 for &variant in RestartStrategy::ALL {
7218 assert_eq!(
7219 variant.to_string(),
7220 variant.as_str(),
7221 "RestartStrategy::{variant:?} Display must route through \
7222 RestartStrategy::as_str (single source of truth: the lifted \
7223 SUPERVISOR_ESTRATEGIA_* const the wire format also emits)"
7224 );
7225 }
7226 }
7227
7228 #[test]
7229 fn restart_strategy_display_matches_serialized_wire_byte_string() {
7230 // The fail-before-pass-after pin on the second half of the
7231 // three-path convergence: `Display` (user-facing text) agrees
7232 // byte-for-byte with the `Serialize` derive's wire format
7233 // (canonical camelCase-schema `SUPERVISOR_KEY_ESTRATEGIA`
7234 // scalar) on every variant. Pre-convergence the two paths
7235 // were structurally independent — a future
7236 // `#[serde(rename_all = "kebab-case")]` attribute on the
7237 // enum would silently rebrand the emitted wire scalar
7238 // (`one-for-one`, `one-for-all`, `rest-for-one`,
7239 // `simple-one-for-one`) while every consumer that
7240 // pretty-prints the strategy (the future wasm-operator's
7241 // per-supervisor sibling-restart-strategy diagnostic line,
7242 // the future `feira app graph` per-supervisor strategy line,
7243 // the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
7244 // materializer's admission-webhook rejection body) would
7245 // still emit the PascalCase form the `as_str` / `Display`
7246 // route returns, with the mismatch surfacing at consumer
7247 // parse time / operator dispatch time far from the source
7248 // rebrand commit. Pin the two paths byte-for-byte here so any
7249 // future serde-attribute or variant-rename drift is a
7250 // caixa-core-build-time test failure at this call, not a
7251 // silent per-consumer dispatch miss. Peer of the M3
7252 // `placement_strategy_display_matches_serialized_wire_byte_string`
7253 // (cc8f749) which the M3 axis converged first.
7254 for &variant in RestartStrategy::ALL {
7255 let wire = serde_json::to_string(&variant).unwrap();
7256 let unquoted = wire
7257 .strip_prefix('"')
7258 .and_then(|s| s.strip_suffix('"'))
7259 .expect("serialized RestartStrategy is a JSON string");
7260 assert_eq!(
7261 variant.to_string(),
7262 unquoted,
7263 "RestartStrategy::{variant:?} Display byte-string must match the \
7264 Serialize derive's wire byte-string (three-path convergence: \
7265 Display + as_str + Serialize all resolve to the same \
7266 SUPERVISOR_ESTRATEGIA_* const)"
7267 );
7268 }
7269 }
7270
7271 #[test]
7272 fn restart_strategy_as_ref_str_routes_through_as_str_accessor() {
7273 // Fail-before-pass-after byte-parity pin on the lifted
7274 // `impl AsRef<str> for RestartStrategy` — asserts the
7275 // standard-library trait impl and the substrate-primitive
7276 // [`RestartStrategy::as_str`] `pub const fn` accessor resolve
7277 // to the same `&str` per instance across the four-arm
7278 // closed set, so any future silent detour that routes the
7279 // impl through a divergent projection (a per-arm inline
7280 // `match self { RestartStrategy::OneForOne => "OneForOne", … }`
7281 // re-inlining that opens a compile-time link to the un-lifted
7282 // arm-literal, a swap onto the kebab-case
7283 // [`gen_platform::Discriminant`] catalog identity that would
7284 // collide the wire axis with the dispatcher-catalog axis) trips
7285 // at caixa-core test time under `PartialEq` rather than at a
7286 // downstream `impl AsRef<str>`-bound consumer's silent split.
7287 // Sweeps every one of the four arms
7288 // [`RestartStrategy::ALL`] carries so no arm's projection is
7289 // covered only by the sibling wire-format `Serialize` derive
7290 // path. Peer of the sibling
7291 // [`crate::version::tests::caixa_version_as_ref_str_routes_through_as_str_accessor`]
7292 // (16d5c7e) `AsRef<str>`-byte-parity pin on the paired
7293 // top-level `:versao` typed newtype — the two pins together
7294 // cover the substrate primitive's `AsRef<str>` projection axis
7295 // on the paired newtype + closed-set-typed-enum surface.
7296 for &variant in RestartStrategy::ALL {
7297 assert_eq!(
7298 <RestartStrategy as AsRef<str>>::as_ref(&variant),
7299 variant.as_str(),
7300 "AsRef<str> impl on RestartStrategy::{variant:?} must \
7301 byte-equal RestartStrategy::as_str on the same instance \
7302 — divergence signals a silent detour off the substrate-\
7303 primitive accessor"
7304 );
7305 }
7306 }
7307
7308 #[test]
7309 fn restart_strategy_as_ref_str_routes_through_display_via_shared_accessor() {
7310 // Fail-before-pass-after byte-parity pin on the three-path
7311 // convergence discipline the M2 sibling-restart primitive now
7312 // carries on the `&str`-projection axis:
7313 // `<RestartStrategy as AsRef<str>>::as_ref(&s)` (the newly
7314 // lifted impl), `format!("{s}")` (the pre-existing
7315 // [`fmt::Display`] impl), and `s.as_str()` (the substrate-
7316 // primitive `pub const fn` accessor both trait impls delegate
7317 // through) must resolve to the same byte-string on every
7318 // instance across the four-arm closed set. Refuses any future
7319 // divergence between the two trait impls (a stray
7320 // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
7321 // rather than delegating through the shared accessor; a
7322 // hypothetical `AsRef<str>` rewrite that inlines a per-arm
7323 // literal cascade) that would silently split the two
7324 // projection paths of the same closed-set typed enum. Mirrors
7325 // the sibling three-path-convergence discipline the peer
7326 // [`crate::CaixaVersion`] typed newtype carries on its
7327 // `AsRef<str>` / `Display` / `as_str` triple
7328 // (version.rs pin
7329 // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
7330 // 16d5c7e).
7331 for &variant in RestartStrategy::ALL {
7332 let via_as_ref: &str = <RestartStrategy as AsRef<str>>::as_ref(&variant);
7333 let via_display: String = format!("{variant}");
7334 let via_accessor: &str = variant.as_str();
7335 assert_eq!(via_as_ref, via_accessor);
7336 assert_eq!(via_display, via_accessor);
7337 assert_eq!(via_as_ref, via_display.as_str());
7338 }
7339 }
7340
7341 #[test]
7342 fn restart_strategy_all_enumerates_every_variant_exactly_once() {
7343 // Fail-before-pass-after pin on the [`RestartStrategy::ALL`]
7344 // exhaustive-iteration surface: every variant appears exactly
7345 // once, and the slice length matches the arm count of the
7346 // closed set. Every consumer that walks the accepted-strategy
7347 // set (a future `feira supervisor --estrategia …` CLI-side
7348 // arg-parse's "did you mean" hint, a future M4 admission-
7349 // webhook's rejection body naming the accepted-`:estrategia`
7350 // list, the [`RestartStrategy::from_wire`] reverse-projection
7351 // consumers that iterate the accept-set for diagnostic
7352 // rendering) reads through this slice, so a future arm addition
7353 // that grows the enum but forgets to grow [`Self::ALL`]
7354 // silently truncates every downstream consumer's accept-set at
7355 // the same pre-addition boundary — this pin fails at caixa-core
7356 // build time on the pairwise-distinct + arm-count invariants.
7357 //
7358 // Peer of the sibling [`crate::CaixaKind::ALL`] (6b1f4fb) /
7359 // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
7360 // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
7361 // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
7362 // pins on the peer closed-set typed-enum axes.
7363 let all: &[RestartStrategy] = RestartStrategy::ALL;
7364 assert_eq!(
7365 all.len(),
7366 4,
7367 "RestartStrategy::ALL must enumerate every variant of the \
7368 four-arm closed set (OneForOne, OneForAll, RestForOne, \
7369 SimpleOneForOne); got {all:?}"
7370 );
7371 for (i, a) in all.iter().enumerate() {
7372 for (j, b) in all.iter().enumerate() {
7373 if i != j {
7374 assert_ne!(
7375 a, b,
7376 "RestartStrategy::ALL must carry every variant exactly \
7377 once — got duplicate {a:?} at indices {i} and {j}"
7378 );
7379 }
7380 }
7381 }
7382 for variant in [
7383 RestartStrategy::OneForOne,
7384 RestartStrategy::OneForAll,
7385 RestartStrategy::RestForOne,
7386 RestartStrategy::SimpleOneForOne,
7387 ] {
7388 assert!(
7389 all.contains(&variant),
7390 "RestartStrategy::ALL must contain {variant:?} — a future arm \
7391 addition that grows the enum but forgets to grow the ALL slice \
7392 silently truncates every downstream consumer's accept-set at \
7393 the pre-addition boundary"
7394 );
7395 }
7396 }
7397
7398 #[test]
7399 fn restart_strategy_from_wire_accepts_every_lifted_constant() {
7400 // Fail-before-pass-after pin on the forward accept-set of the
7401 // [`RestartStrategy::from_wire`] reverse projection: every
7402 // canonical [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
7403 // constant the [`RestartStrategy::as_str`] emitter walks parses
7404 // back to its paired variant. Any future arm addition that
7405 // grows the emitter's `as_str` match but forgets to grow the
7406 // parser's `from_wire` match silently splits the two halves of
7407 // the round-trip — the wire byte-string one non-serde consumer
7408 // parses from the one the emitter wrote — with the failure
7409 // surfacing at parse time far from the rebrand commit. Pinning
7410 // the four-arm accept-set here catches the drift at caixa-core
7411 // build time.
7412 //
7413 // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
7414 // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
7415 // accept-set pins on the peer closed-set typed-enum `str → Self`
7416 // axes.
7417 for (wire, expected) in [
7418 (
7419 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7420 RestartStrategy::OneForOne,
7421 ),
7422 (
7423 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7424 RestartStrategy::OneForAll,
7425 ),
7426 (
7427 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7428 RestartStrategy::RestForOne,
7429 ),
7430 (
7431 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7432 RestartStrategy::SimpleOneForOne,
7433 ),
7434 ] {
7435 let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
7436 panic!(
7437 "RestartStrategy::from_wire({wire:?}) must accept every \
7438 SUPERVISOR_ESTRATEGIA_* constant — got None for the \
7439 lifted canonical byte-string that RestartStrategy::{expected:?} \
7440 serializes as under SUPERVISOR_KEY_ESTRATEGIA"
7441 )
7442 });
7443 assert_eq!(
7444 parsed, expected,
7445 "RestartStrategy::from_wire({wire:?}) must return \
7446 RestartStrategy::{expected:?}; got RestartStrategy::{parsed:?}"
7447 );
7448 }
7449 }
7450
7451 #[test]
7452 fn restart_strategy_from_wire_round_trips_through_as_str() {
7453 // Fail-before-pass-after pin on the closed round-trip between
7454 // the forward [`RestartStrategy::as_str`] emitter and the
7455 // reverse [`RestartStrategy::from_wire`] parser: for every
7456 // variant in [`RestartStrategy::ALL`], parsing the emitter's
7457 // output must return exactly the same variant. Any per-arm
7458 // divergence — a future arm added to `as_str` but not
7459 // `from_wire`, an accidental copy-paste flip in one but not
7460 // the other — silently splits the emit and parse halves and
7461 // the failure surfaces at consumer parse time far from the
7462 // drift site. The `ALL`-iterating shape means a future arm
7463 // addition picks up the coverage by construction.
7464 //
7465 // Peer of the sibling
7466 // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
7467 // (18c7342) round-trip pin on
7468 // [`crate::aplicacao::PlacementStrategy::from_wire`] and
7469 // [`crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`]
7470 // (6b1f4fb) round-trip pin on [`crate::CaixaKind::from_wire`].
7471 for &variant in RestartStrategy::ALL {
7472 let wire = variant.as_str();
7473 let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
7474 panic!(
7475 "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
7476 must be Some({variant:?}) — the two halves of the round-trip \
7477 dispatch on the same lifted SUPERVISOR_ESTRATEGIA_* consts; \
7478 got None on wire byte-string {wire:?}"
7479 )
7480 });
7481 assert_eq!(
7482 parsed, variant,
7483 "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
7484 must round-trip to the same variant; got {parsed:?}"
7485 );
7486 }
7487 }
7488
7489 #[test]
7490 fn restart_strategy_from_wire_rejects_unknown_byte_strings() {
7491 // Fail-before-pass-after pin on the closed-set refusal
7492 // discipline of [`RestartStrategy::from_wire`]: every
7493 // byte-string outside the four-arm accept-set returns `None`
7494 // rather than silently collapsing onto the [`Default`]
7495 // (`OneForOne`) arm or an arbitrary neighbor. The refusal set
7496 // exercised here sweeps the load-bearing drift shapes: the
7497 // empty string (a stripped serde-attribute drift), all-
7498 // whitespace strings (the canonical text-editor accidental
7499 // padding shape), the kebab-case dispatcher-catalog identities
7500 // (`"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
7501 // `"simple-one-for-one"` — the [`gen_platform::FromStrKind`]-
7502 // derived [`std::str::FromStr`] accept-set, which parses the
7503 // *other* axis of this enum's two-axis split and must not leak
7504 // into the `from_wire` PascalCase-wire accept-set), the
7505 // lowercased single-word forms (`"oneforone"`), the padded
7506 // canonical scalar (`" OneForOne "`), the trailing-newline
7507 // shapes (`"OneForOne\n"`), and neighboring-but-unknown arms
7508 // (`"AllForOne"` — the canonical typo direction).
7509 //
7510 // Peer of the sibling
7511 // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
7512 // (2aa6d23) +
7513 // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
7514 // (18c7342) refusal pins on the peer closed-set typed-enum
7515 // axes.
7516 for bad in [
7517 "",
7518 " ",
7519 "\n",
7520 "\t",
7521 "one-for-one",
7522 "one-for-all",
7523 "rest-for-one",
7524 "simple-one-for-one",
7525 "oneforone",
7526 "OneForOnes",
7527 "one_for_one",
7528 "one for one",
7529 "ONEFORONE",
7530 "OneForOne ",
7531 " OneForOne",
7532 " SimpleOneForOne ",
7533 "OneForOne\n",
7534 "restforone",
7535 "REST_FOR_ONE",
7536 "AllForOne",
7537 "Simple",
7538 "?",
7539 ] {
7540 assert!(
7541 RestartStrategy::from_wire(bad).is_none(),
7542 "RestartStrategy::from_wire({bad:?}) must return None — the \
7543 parser's accept-set is exactly the four RestartStrategy::as_str \
7544 outputs (OneForOne, OneForAll, RestForOne, SimpleOneForOne), \
7545 and this byte-string is outside that closed set"
7546 );
7547 }
7548 }
7549
7550 #[test]
7551 fn restart_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
7552 // Fail-before-pass-after pin on the fourth path of the four-path
7553 // convergence: `from_wire` (the reverse projection) inverts the
7554 // `Serialize` derive's wire byte-string on every variant.
7555 // Together with the pre-existing three-path convergence
7556 // (`Display` + `as_str` + `Serialize` all resolve to the same
7557 // lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const,
7558 // pinned by
7559 // [`restart_strategy_display_matches_serialized_wire_byte_string`])
7560 // this closes the round-trip: the wire byte-string the
7561 // `Serialize` derive emits parses back to the same variant
7562 // through `from_wire`, so any future serde-attribute or variant-
7563 // rename drift on the emit half now surfaces as a matched drift
7564 // on the parse half at caixa-core build time — the two halves
7565 // migrate as a unit through the lifted consts on any future
7566 // rename, and the round-trip cannot silently split.
7567 //
7568 // Peer of the sibling
7569 // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
7570 // (18c7342) wire-format pin on
7571 // [`crate::aplicacao::PlacementStrategy::from_wire`].
7572 for &variant in RestartStrategy::ALL {
7573 let wire = serde_json::to_string(&variant).unwrap();
7574 let unquoted = wire
7575 .strip_prefix('"')
7576 .and_then(|s| s.strip_suffix('"'))
7577 .expect("serialized RestartStrategy is a JSON string");
7578 let parsed = RestartStrategy::from_wire(unquoted).unwrap_or_else(|| {
7579 panic!(
7580 "RestartStrategy::from_wire({unquoted:?}) must accept the \
7581 Serialize derive's wire byte-string for \
7582 RestartStrategy::{variant:?} — the four-path convergence \
7583 (Display + as_str + Serialize + from_wire) resolves through \
7584 the same lifted SUPERVISOR_ESTRATEGIA_* const; got None"
7585 )
7586 });
7587 assert_eq!(
7588 parsed, variant,
7589 "RestartStrategy::from_wire of the Serialize derive's wire \
7590 byte-string for RestartStrategy::{variant:?} must round-trip \
7591 to the same variant; got {parsed:?}"
7592 );
7593 }
7594 }
7595
7596 #[test]
7597 fn restart_strategy_try_from_str_routes_through_from_wire_accessor() {
7598 // Fail-before-pass-after byte-parity pin on the newly lifted
7599 // `impl TryFrom<&str> for RestartStrategy` — asserts the standard-
7600 // library trait impl and the substrate-primitive
7601 // [`RestartStrategy::from_wire`] `Option<Self>` accessor resolve to
7602 // the same four-arm accept-set across every arm the exhaustive
7603 // [`RestartStrategy::ALL`] slice enumerates. Any future silent
7604 // detour that routes the trait impl through a divergent projection
7605 // (a per-arm inline `match s { "OneForOne" => Ok(Self::OneForOne),
7606 // … }` re-inlining that opens a compile-time link to the un-
7607 // lifted arm-literal, a hypothetical `#[serde(rename_all = "…")]`
7608 // attribute drift that silently splits the wire byte-string from
7609 // every consumer that reaches for this typed dispatch, an
7610 // accidental swap onto the kebab-case dispatcher-catalog axis the
7611 // pre-existing [`std::str::FromStr`] impl parses through and which
7612 // would collide the two-axis wire/catalog split the sibling
7613 // [`RestartStrategy::from_wire`] doc block makes load-bearing)
7614 // trips at caixa-core test time under `assert_eq!` rather than at
7615 // a downstream `impl TryFrom<&str>`-bound consumer's silent split.
7616 // Sweeps every one of the four arms [`RestartStrategy::ALL`]
7617 // carries so no arm's projection is covered only by the sibling
7618 // method-named `from_wire` path. Peer of the sibling
7619 // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
7620 // (3c83606),
7621 // [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
7622 // (bf33136), and the M3
7623 // [`crate::aplicacao::tests::placement_strategy_try_from_str_routes_through_from_wire_accessor`]
7624 // (6fd00cd) — extends the trait-idiomatic reverse-projection axis
7625 // onto the first M2-OTP-shape closed-set typed enum on the caixa
7626 // surface.
7627 for &variant in RestartStrategy::ALL {
7628 let wire = variant.as_str();
7629 assert_eq!(
7630 <RestartStrategy as TryFrom<&str>>::try_from(wire),
7631 Ok(variant),
7632 "TryFrom<&str> impl on RestartStrategy must round-trip \
7633 RestartStrategy::{variant:?}.as_str() = {wire:?} back to \
7634 Ok(RestartStrategy::{variant:?}) — divergence from \
7635 RestartStrategy::from_wire signals a silent detour off \
7636 the substrate-primitive accessor"
7637 );
7638 assert_eq!(
7639 <RestartStrategy as TryFrom<&str>>::try_from(wire).ok(),
7640 RestartStrategy::from_wire(wire),
7641 "TryFrom<&str> ok()-projection on {wire:?} must byte-equal \
7642 RestartStrategy::from_wire on the same input"
7643 );
7644 }
7645 }
7646
7647 #[test]
7648 fn restart_strategy_try_from_str_rejects_unknown_byte_strings() {
7649 // Rejection witness on the `impl TryFrom<&str> for
7650 // RestartStrategy` — sweeps a candidate set of byte-strings
7651 // outside the four-arm PascalCase wire accept-set the sibling
7652 // [`RestartStrategy::as_str`] emits and asserts every one lands on
7653 // `Err(())`, so a future accidental widening of the trait impl's
7654 // accept-set (a stray additional
7655 // `_ if s.eq_ignore_ascii_case("OneForOne") => Ok(…)` case-fold
7656 // path, a silent inclusion of the kebab-case dispatcher-catalog
7657 // byte-string the pre-existing [`std::str::FromStr`] impl the
7658 // [`gen_platform::FromStrKind`] derive installs parses onto the
7659 // wire axis — which would collide the two-axis
7660 // wire/dispatcher-catalog split the sibling
7661 // [`RestartStrategy::from_wire`] doc block makes load-bearing —
7662 // an English-rebrand or plural-arm silent alias that would
7663 // widen the wire accept-set past the OTP-canonical four) trips at
7664 // caixa-core test time. The candidate set includes the empty
7665 // string, whitespace-only padding, the kebab-case dispatcher-
7666 // catalog byte-strings on the sibling axis (a caller who confuses
7667 // the two axes trips here rather than at a downstream consumer's
7668 // silent reject), a lowercase / uppercase / mixed-case fold of
7669 // each PascalCase arm (a caller who assumes case-fold acceptance
7670 // trips here), leading/trailing whitespace padding, the trailing-
7671 // newline shape, quote-wrapped candidates, and a residual set of
7672 // plausible-but-wrong English rebrand candidates. Peer of the
7673 // sibling
7674 // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
7675 // (3c83606) and
7676 // [`crate::aplicacao::tests::placement_strategy_try_from_str_rejects_unknown_byte_strings`]
7677 // (6fd00cd) rejection witnesses.
7678 let rejected: &[&str] = &[
7679 "",
7680 " ",
7681 "\n",
7682 "\t",
7683 "one-for-one",
7684 "one-for-all",
7685 "rest-for-one",
7686 "simple-one-for-one",
7687 "oneforone",
7688 "one_for_one",
7689 "OneForOnes",
7690 "ONEFORONE",
7691 "oneforall",
7692 "restforone",
7693 "simpleoneforone",
7694 "OneForOne ",
7695 " OneForOne",
7696 " OneForAll ",
7697 "OneForOne\n",
7698 "RestForOne\t",
7699 "OneForEach",
7700 "AllForOne",
7701 "one for one",
7702 "\"OneForOne\"",
7703 "?",
7704 ];
7705 for &input in rejected {
7706 assert_eq!(
7707 <RestartStrategy as TryFrom<&str>>::try_from(input),
7708 Err(()),
7709 "TryFrom<&str> impl on RestartStrategy must reject the \
7710 non-wire byte-string {input:?} — silent acceptance signals \
7711 an accept-set widening off the paired \
7712 RestartStrategy::from_wire resolver"
7713 );
7714 }
7715 }
7716
7717 #[test]
7718 fn restart_strategy_try_from_str_and_from_wire_partition_the_accept_set() {
7719 // Cross-axis partition pin: the paired `TryFrom<&str>` and
7720 // `from_wire` reverse projections must resolve identically on
7721 // *every* input, not just the ones [`RestartStrategy::ALL`]
7722 // enumerates. Sweeps a mixed candidate set spanning accepted
7723 // (four-arm PascalCase wire byte-strings) and rejected (kebab-case
7724 // dispatcher-catalog byte-strings, empty, whitespace-padded,
7725 // quoted, English-rebrand candidates) inputs and asserts the
7726 // trait's `Result::ok()` projection byte-equals the method-named
7727 // resolver's `Option<Self>` return-shape on each, locking the two
7728 // paths together by construction so any future detour (a stray
7729 // `try_from` special-case that widens or narrows the accept-set
7730 // outside the paired `from_wire` resolver, an accidental swap
7731 // onto the kebab-case [`std::str::FromStr`] impl the
7732 // [`gen_platform::FromStrKind`] derive installs on the sibling
7733 // dispatcher-catalog axis) trips at caixa-core test time. Peer of
7734 // the sibling
7735 // [`crate::kind::tests::caixa_kind_try_from_str_and_from_wire_partition_the_accept_set`]
7736 // pin — extends the round-trip discipline onto the M2-OTP-shape
7737 // sibling-restart axis.
7738 let candidates: &[&str] = &[
7739 "OneForOne",
7740 "OneForAll",
7741 "RestForOne",
7742 "SimpleOneForOne",
7743 "",
7744 "one-for-one",
7745 "one-for-all",
7746 "rest-for-one",
7747 "simple-one-for-one",
7748 "oneforone",
7749 "unknown",
7750 "OneForOne ",
7751 " OneForOne",
7752 "\"OneForOne\"",
7753 "OneForEach",
7754 "?",
7755 ];
7756 for &input in candidates {
7757 let via_trait: Option<RestartStrategy> =
7758 <RestartStrategy as TryFrom<&str>>::try_from(input).ok();
7759 let via_method: Option<RestartStrategy> = RestartStrategy::from_wire(input);
7760 assert_eq!(
7761 via_trait, via_method,
7762 "TryFrom<&str> and from_wire must resolve identically on \
7763 input {input:?} — divergence signals the two reverse-\
7764 projection paths have drifted onto different accept-sets"
7765 );
7766 }
7767 }
7768
7769 #[test]
7770 fn restart_strategy_from_into_static_str_routes_through_as_str_accessor() {
7771 // Fail-before-pass-after byte-parity pin on the newly lifted
7772 // `impl From<RestartStrategy> for &'static str` — asserts the
7773 // standard-library trait impl and the substrate-primitive
7774 // [`RestartStrategy::as_str`] `pub const fn` accessor resolve to
7775 // the same four-arm emit-set across every arm the exhaustive
7776 // [`RestartStrategy::ALL`] slice enumerates. Any future silent
7777 // detour that routes the trait impl through a divergent
7778 // projection (a per-arm inline `match strategy { OneForOne =>
7779 // "OneForOne", … }` re-inlining that opens a compile-time link to
7780 // the un-lifted arm-literal, an accidental swap onto the sibling
7781 // kebab-case [`Self::discriminant`] dispatcher-catalog axis that
7782 // would collide the two-axis wire/catalog split the sibling
7783 // [`RestartStrategy::from_wire`] doc block makes load-bearing) trips
7784 // at caixa-core test time under `assert_eq!` rather than at a
7785 // downstream `impl Into<&'static str>`-bound consumer's silent
7786 // split. Sweeps every one of the four arms
7787 // [`RestartStrategy::ALL`] carries so no arm's projection is
7788 // covered only by the sibling method-named `as_str` /
7789 // [`std::fmt::Display`] / [`AsRef<str>`] paths. Materializes the
7790 // `<&'static str as From<RestartStrategy>>::from` output in a
7791 // `const`-shape binding to make the `'static` lifetime promise a
7792 // build-time invariant — a future accidental downgrade of any of
7793 // the four arms' [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
7794 // constants to a non-`&'static str` (a `String::leak()`-produced
7795 // return, a `Box::leak`-cast) trips at caixa-core build time
7796 // rather than at a downstream `'static`-bound consumer.
7797 const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
7798 const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
7799 const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
7800 const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
7801 for &variant in RestartStrategy::ALL {
7802 let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
7803 let via_method: &'static str = variant.as_str();
7804 assert_eq!(
7805 via_trait, via_method,
7806 "From<RestartStrategy> for &'static str impl must round-trip \
7807 RestartStrategy::{variant:?} to the same lifted \
7808 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str returns — \
7809 divergence signals a silent detour off the substrate-primitive \
7810 accessor"
7811 );
7812 let via_into: &'static str = variant.into();
7813 assert_eq!(
7814 via_into, via_method,
7815 "Into<&'static str>::into on RestartStrategy::{variant:?} must \
7816 byte-equal RestartStrategy::as_str on the same input — the \
7817 blanket-derived Into shape must resolve to the same as_str \
7818 dispatch as the explicit From impl"
7819 );
7820 }
7821 assert_eq!(
7822 [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
7823 [
7824 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7825 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7826 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7827 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7828 ],
7829 "const-context RestartStrategy::as_str must resolve to the four \
7830 lifted SUPERVISOR_ESTRATEGIA_* consts — a future accidental \
7831 downgrade of any arm to a non-const or non-static byte-string \
7832 breaks the `&'static str`-lifetime promise the paired \
7833 From<RestartStrategy> for &'static str impl carries by \
7834 construction"
7835 );
7836 }
7837
7838 #[test]
7839 fn restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set() {
7840 // Cross-axis partition pin: the paired trait-idiomatic
7841 // `From<RestartStrategy> for &'static str` forward projection and
7842 // the method-named [`RestartStrategy::as_str`] forward projection
7843 // must resolve identically on *every* arm, not just the ones
7844 // named in the primary byte-parity pin above. Sweeps every
7845 // [`RestartStrategy::ALL`] arm and asserts the trait's `From::from`
7846 // output byte-equals the method-named accessor's return-value on
7847 // each, locking the two forward-projection paths together by
7848 // construction so any future detour (a stray `From` special-case
7849 // that lands on a divergent per-arm literal outside the paired
7850 // `as_str` dispatch, a hypothetical rebrand touching one axis
7851 // without the other) trips at caixa-core test time. Peer of the
7852 // sibling reverse-projection partition pin
7853 // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
7854 // — extends the round-trip discipline onto the trait-idiomatic
7855 // *forward* axis, closing the two-way `Self ↔ &'static str`
7856 // round-trip on the trait-idiomatic pair
7857 // (`From<Self> for &'static str` + `TryFrom<&str> for Self`) as
7858 // well as the pre-existing method-named pair
7859 // (`as_str` + `from_wire`).
7860 for &variant in RestartStrategy::ALL {
7861 let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
7862 let via_method: &'static str = variant.as_str();
7863 assert_eq!(
7864 via_trait, via_method,
7865 "From<RestartStrategy> for &'static str and \
7866 RestartStrategy::as_str must resolve identically on \
7867 RestartStrategy::{variant:?} — divergence signals the \
7868 two forward-projection paths have drifted onto different \
7869 emit-sets"
7870 );
7871 }
7872 // Round-trip witness: every arm's forward `From` output re-parses
7873 // through the paired trait-idiomatic reverse `TryFrom<&str>` back
7874 // to the original variant. Closes the two-way `RestartStrategy ↔
7875 // &'static str` round-trip on the trait-idiomatic axis pair,
7876 // mirroring the pre-existing method-named `as_str` + `from_wire`
7877 // round-trip on the substrate-primitive axis pair.
7878 for &variant in RestartStrategy::ALL {
7879 let emitted: &'static str = variant.into();
7880 let re_parsed: Result<RestartStrategy, ()> =
7881 <RestartStrategy as TryFrom<&str>>::try_from(emitted);
7882 assert_eq!(
7883 re_parsed,
7884 Ok(variant),
7885 "trait-idiomatic axis pair must round-trip \
7886 RestartStrategy::{variant:?} through `.into::<&'static \
7887 str>()` and back through `TryFrom<&str>` — a break signals \
7888 the forward-emit and reverse-parse axes have drifted onto \
7889 different vocabularies"
7890 );
7891 }
7892 }
7893
7894 #[test]
7895 fn restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
7896 // Fail-before-pass-after byte-parity pin on the newly lifted
7897 // `impl From<&RestartStrategy> for &'static str` — asserts the
7898 // borrowed-input standard-library trait impl and the substrate-
7899 // primitive [`RestartStrategy::as_str`] `pub const fn` accessor
7900 // resolve to the same four-arm emit-set across every arm the
7901 // exhaustive [`RestartStrategy::ALL`] slice enumerates. Rust's
7902 // `From` trait does not auto-derive the borrowed-input sibling
7903 // from a paired owned-input impl (no `impl<T, U> From<&T> for U
7904 // where T: Copy, U: From<T>` blanket in `core`), so the
7905 // borrowed-input axis is a distinct trait-idiomatic surface
7906 // that a `.iter().map(Into::into)` shape over
7907 // [`RestartStrategy::ALL`] (whose iterator yields
7908 // `&RestartStrategy`, not `RestartStrategy`) reaches through
7909 // this impl and no other — the paired owned-input
7910 // [`From<RestartStrategy>`] impl requires an explicit
7911 // `.copied()` / dereference before the trait fires.
7912 // Materializes the `<&'static str as
7913 // From<&RestartStrategy>>::from` output in a `const`-shape
7914 // binding to make the `'static` lifetime promise a build-time
7915 // invariant.
7916 const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
7917 const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
7918 const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
7919 const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
7920 for variant in RestartStrategy::ALL {
7921 let via_trait: &'static str = <&'static str as From<&RestartStrategy>>::from(variant);
7922 let via_method: &'static str = variant.as_str();
7923 assert_eq!(
7924 via_trait, via_method,
7925 "From<&RestartStrategy> for &'static str impl must \
7926 round-trip &RestartStrategy::{variant:?} to the same \
7927 lifted SUPERVISOR_ESTRATEGIA_* const \
7928 RestartStrategy::as_str returns — divergence signals a \
7929 silent detour off the substrate-primitive accessor"
7930 );
7931 let via_into: &'static str = variant.into();
7932 assert_eq!(
7933 via_into, via_method,
7934 "Into<&'static str>::into on &RestartStrategy::{variant:?} \
7935 must byte-equal RestartStrategy::as_str on the same input — \
7936 the blanket-derived Into shape must resolve to the same \
7937 as_str dispatch as the explicit From impl"
7938 );
7939 }
7940 assert_eq!(
7941 [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
7942 [
7943 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7944 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7945 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7946 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7947 ],
7948 "const-context RestartStrategy::as_str must resolve to the \
7949 four lifted SUPERVISOR_ESTRATEGIA_* consts — the borrowed-\
7950 input From<&RestartStrategy> for &'static str impl inherits \
7951 its `'static` lifetime promise from the same accessor the \
7952 owned-input sibling routes through"
7953 );
7954 }
7955
7956 #[test]
7957 fn restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
7958 // Cross-axis partition pin: the paired trait-idiomatic
7959 // owned-input `From<RestartStrategy> for &'static str` (523157d
7960 // campaign-shape) and borrowed-input `From<&RestartStrategy> for
7961 // &'static str` (this lift) forward projections must resolve
7962 // identically on every arm, locking the two input-shape paths
7963 // together so any future detour trips at caixa-core test time.
7964 // Then a witness that a `.iter().map(Into::into)` pipe over
7965 // [`RestartStrategy::ALL`] (whose iterator yields
7966 // `&RestartStrategy`) materializes the four-arm accept-set
7967 // through the borrowed-input axis alone — the exact shape a
7968 // future wasm-operator per-supervisor sibling-restart-strategy
7969 // diagnostic line, a future substrate-wide per-arm diagnostic
7970 // column, or a
7971 // `HashMap::<&'static str, RestartStrategy>::from_iter(
7972 // RestartStrategy::ALL.iter().map(|s| (s.into(), *s)))`-style
7973 // per-strategy lookup reaches through — closing the two-way
7974 // owned/borrowed input-shape symmetry on the forward-projection
7975 // trait-idiomatic axis. Peer of the sibling
7976 // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
7977 // (64aa742) /
7978 // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
7979 // (5ab993a) /
7980 // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
7981 // (807b0b5) partition pins on the sibling closed-set typed-enum
7982 // discriminator axes — extends the borrowed-input axis
7983 // discipline onto the first M2 OTP-shape sibling-restart
7984 // closed-set typed enum on the caixa surface. Also closes the
7985 // direct two-way `&Self → &'static str → Self` round-trip via
7986 // the paired [`TryFrom<&str>`] axis — unlike the peer
7987 // [`crate::CaixaKind`] axis pair (whose forward `From` emits
7988 // lowercase Portuguese diagnostic bytes while the reverse
7989 // `TryFrom` parses `PascalCase` wire bytes, forcing the round-
7990 // trip through an intermediate wire-vocab hop), the
7991 // [`RestartStrategy::as_str`] emit and
7992 // [`RestartStrategy::from_wire`] parse share the same
7993 // `PascalCase` vocabulary by construction, so the borrowed-
7994 // input forward axis and the reverse axis compose directly.
7995 for &variant in RestartStrategy::ALL {
7996 let owned: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
7997 let borrowed: &'static str = <&'static str as From<&RestartStrategy>>::from(&variant);
7998 assert_eq!(
7999 owned, borrowed,
8000 "From<RestartStrategy> and From<&RestartStrategy> for \
8001 &'static str must resolve identically on \
8002 RestartStrategy::{variant:?} — divergence signals the \
8003 owned-input and borrowed-input forward-projection paths \
8004 have drifted onto different emit-sets"
8005 );
8006 }
8007 let via_iter: Vec<&'static str> = RestartStrategy::ALL.iter().map(Into::into).collect();
8008 let via_method: Vec<&'static str> =
8009 RestartStrategy::ALL.iter().map(|s| s.as_str()).collect();
8010 assert_eq!(
8011 via_iter, via_method,
8012 "`.iter().map(Into::into)` over RestartStrategy::ALL must \
8013 byte-equal `.iter().map(|s| s.as_str())` on every arm — the \
8014 borrowed-input `From<&RestartStrategy> for &'static str` \
8015 axis is what makes the `.iter().map(Into::into)` shape route \
8016 through the substrate-primitive `RestartStrategy::as_str` \
8017 accessor rather than through a per-call-site `.copied()` / \
8018 dereference detour"
8019 );
8020 for variant in RestartStrategy::ALL {
8021 let emitted: &'static str = variant.into();
8022 let re_parsed: Result<RestartStrategy, ()> =
8023 <RestartStrategy as TryFrom<&str>>::try_from(emitted);
8024 assert_eq!(
8025 re_parsed,
8026 Ok(*variant),
8027 "trait-idiomatic borrowed-input forward-projection + \
8028 reverse-projection axis pair must round-trip \
8029 &RestartStrategy::{variant:?} through `.into::<&'static \
8030 str>()` (via the borrowed-input axis) and back through \
8031 `TryFrom<&str>` — a break signals the borrowed-input \
8032 forward-emit and reverse-parse axes have drifted onto \
8033 different vocabularies"
8034 );
8035 }
8036 }
8037
8038 #[test]
8039 fn restart_strategy_from_into_owned_string_routes_through_as_str_accessor() {
8040 // Fail-before-pass-after byte-parity pin on the newly lifted
8041 // `impl From<RestartStrategy> for String` — asserts the
8042 // owned-`String`-returning standard-library trait impl and the
8043 // substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
8044 // accessor resolve to the same four-arm emit-set across every
8045 // arm the exhaustive [`RestartStrategy::ALL`] slice enumerates.
8046 // Rust's standard library does not carry a blanket
8047 // `impl<T: AsRef<str>> From<T> for String` (nor an
8048 // `impl<T: fmt::Display> From<T> for String`), so the
8049 // owned-`String` forward-projection axis is a distinct
8050 // trait-idiomatic surface that a
8051 // `let key: String = strategy.into();`-shaped call site
8052 // reaches through this impl and no other — the paired sibling
8053 // `From<RestartStrategy> for &'static str` impl forces every
8054 // owned-`String` call site through an explicit
8055 // `.to_owned()` / `String::from` restatement.
8056 for &variant in RestartStrategy::ALL {
8057 let via_trait: String = <String as From<RestartStrategy>>::from(variant);
8058 let via_method: &'static str = variant.as_str();
8059 assert_eq!(
8060 via_trait.as_str(),
8061 via_method,
8062 "From<RestartStrategy> for String impl must round-trip \
8063 RestartStrategy::{variant:?} to the same lifted \
8064 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
8065 returns — divergence signals a silent detour off the \
8066 substrate-primitive accessor"
8067 );
8068 let via_into: String = variant.into();
8069 assert_eq!(
8070 via_into.as_str(),
8071 via_method,
8072 "Into<String>::into on RestartStrategy::{variant:?} must \
8073 byte-equal RestartStrategy::as_str on the same input — the \
8074 blanket-derived Into shape must resolve to the same as_str \
8075 dispatch as the explicit From impl"
8076 );
8077 }
8078 }
8079
8080 #[test]
8081 fn restart_strategy_from_into_owned_string_and_static_str_agree_on_every_arm() {
8082 // Cross-axis partition pin: the paired trait-idiomatic
8083 // owned-`String` `From<RestartStrategy> for String` (this lift)
8084 // and owned-`&'static str` `From<RestartStrategy> for &'static
8085 // str` (523157d) forward projections must resolve identically
8086 // on every arm, locking the two return-type-shape paths
8087 // together so any future detour trips at caixa-core test time.
8088 // Also byte-parity witness against the sibling
8089 // [`ToString::to_string`] surface routed through
8090 // [`std::fmt::Display`] — the three owned-heap-string paths
8091 // (`.into::<String>()`, `String::from`, `.to_string()`) must
8092 // resolve identically on every arm so a future consumer that
8093 // picks any of the three lands on the same lifted
8094 // SUPERVISOR_ESTRATEGIA_* const. Then a direct round-trip
8095 // witness through the paired trait-idiomatic reverse
8096 // [`TryFrom<&str>`] axis on the owned-`String`'s
8097 // [`String::as_str`] borrow that closes the two-way
8098 // `Self → String → Self` round-trip on the trait-idiomatic
8099 // owned-`String` forward + reverse axis pair.
8100 for &variant in RestartStrategy::ALL {
8101 let owned_string: String = <String as From<RestartStrategy>>::from(variant);
8102 let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8103 assert_eq!(
8104 owned_string.as_str(),
8105 owned_static,
8106 "From<RestartStrategy> for String and From<RestartStrategy> \
8107 for &'static str must resolve identically on \
8108 RestartStrategy::{variant:?} — divergence signals the \
8109 owned-`String` and owned-`&'static str` forward-projection \
8110 return-type-shape paths have drifted onto different \
8111 emit-sets"
8112 );
8113 let via_to_string: String = variant.to_string();
8114 assert_eq!(
8115 owned_string, via_to_string,
8116 "From<RestartStrategy> for String must byte-equal \
8117 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
8118 divergence signals the trait-idiomatic owned-`String` \
8119 forward-projection axis and the ToString-through-Display \
8120 axis have drifted onto different emit-sets"
8121 );
8122 }
8123 let via_iter: Vec<String> = RestartStrategy::ALL
8124 .iter()
8125 .copied()
8126 .map(String::from)
8127 .collect();
8128 let via_method: Vec<String> = RestartStrategy::ALL
8129 .iter()
8130 .map(|s| s.as_str().to_owned())
8131 .collect();
8132 assert_eq!(
8133 via_iter, via_method,
8134 "`.iter().copied().map(String::from)` over RestartStrategy::ALL \
8135 must byte-equal `.iter().map(|s| s.as_str().to_owned())` on \
8136 every arm — the owned-`String` `From<RestartStrategy> for \
8137 String` axis is what makes the `String::from` composition \
8138 route through the substrate-primitive `RestartStrategy::as_str` \
8139 accessor rather than through a per-call-site `.to_owned()` / \
8140 `String::from(strategy.as_str())` detour"
8141 );
8142 for &variant in RestartStrategy::ALL {
8143 let emitted: String = variant.into();
8144 let re_parsed: Result<RestartStrategy, ()> =
8145 <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
8146 assert_eq!(
8147 re_parsed,
8148 Ok(variant),
8149 "trait-idiomatic owned-`String` forward-projection + \
8150 reverse-projection axis pair must round-trip \
8151 RestartStrategy::{variant:?} through `.into::<String>()` \
8152 and back through `TryFrom<&str>` on the owned-`String`'s \
8153 String::as_str borrow — a break signals the owned-`String` \
8154 forward-emit and reverse-parse axes have drifted onto \
8155 different vocabularies"
8156 );
8157 }
8158 }
8159
8160 #[test]
8161 fn restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
8162 // Fail-before-pass-after byte-parity pin on the newly lifted
8163 // `impl From<&RestartStrategy> for String` — asserts the
8164 // borrowed-input owned-`String`-returning standard-library trait
8165 // impl and the substrate-primitive [`RestartStrategy::as_str`]
8166 // `pub const fn` accessor resolve to the same four-arm emit-set
8167 // across every arm the exhaustive [`RestartStrategy::ALL`] slice
8168 // enumerates. Rust's standard library does not carry a blanket
8169 // `impl<T: AsRef<str>> From<&T> for String` (nor an
8170 // `impl<T: fmt::Display> From<&T> for String`), so the
8171 // borrowed-input owned-`String` forward-projection axis is a
8172 // distinct trait-idiomatic surface that a
8173 // `let key: String = (&strategy).into();`-shaped call site
8174 // reaches through this impl and no other — the paired sibling
8175 // `From<RestartStrategy> for String` impl forces every
8176 // borrowed-input call site through an explicit `Copy` deref
8177 // (`String::from(*strategy)`) or an `.as_str().to_owned()` /
8178 // `.to_string()` detour.
8179 for &variant in RestartStrategy::ALL {
8180 let via_trait: String = <String as From<&RestartStrategy>>::from(&variant);
8181 let via_method: &'static str = variant.as_str();
8182 assert_eq!(
8183 via_trait.as_str(),
8184 via_method,
8185 "From<&RestartStrategy> for String impl must round-trip \
8186 &RestartStrategy::{variant:?} to the same lifted \
8187 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
8188 returns — divergence signals a silent detour off the \
8189 substrate-primitive accessor"
8190 );
8191 let via_into: String = (&variant).into();
8192 assert_eq!(
8193 via_into.as_str(),
8194 via_method,
8195 "Into<String>::into on &RestartStrategy::{variant:?} must \
8196 byte-equal RestartStrategy::as_str on the same input — the \
8197 blanket-derived Into shape must resolve to the same as_str \
8198 dispatch as the explicit From impl"
8199 );
8200 }
8201 }
8202
8203 #[test]
8204 fn restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
8205 // Cross-axis partition pin: the newly lifted trait-idiomatic
8206 // borrowed-input owned-`String` `From<&RestartStrategy> for
8207 // String` (this lift), the paired owned-input owned-`String`
8208 // `From<RestartStrategy> for String` (7baa18a), the paired
8209 // borrowed-input owned-`&'static str` `From<&RestartStrategy>
8210 // for &'static str` (e941836), and the paired owned-input
8211 // owned-`&'static str` `From<RestartStrategy> for &'static str`
8212 // (523157d) — every corner of the `{Self, &Self} × {&'static
8213 // str, String}` 2×2 trait-idiomatic projection family — must
8214 // resolve identically on every arm, locking the four
8215 // return-shape × input-shape paths together so any future
8216 // detour trips at caixa-core test time. Also byte-parity
8217 // witness against the sibling [`ToString::to_string`] surface
8218 // routed through [`std::fmt::Display`] and a direct round-trip
8219 // witness through the paired trait-idiomatic reverse
8220 // [`TryFrom<&str>`] axis on the owned-`String`'s
8221 // [`String::as_str`] borrow that closes the two-way
8222 // `&Self → String → Self` round-trip on the trait-idiomatic
8223 // borrowed-input owned-`String` forward + reverse axis pair.
8224 for &variant in RestartStrategy::ALL {
8225 let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
8226 let owned_string: String = <String as From<RestartStrategy>>::from(variant);
8227 let borrowed_static: &'static str =
8228 <&'static str as From<&RestartStrategy>>::from(&variant);
8229 let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8230 assert_eq!(
8231 borrowed_string, owned_string,
8232 "From<&RestartStrategy> for String and From<RestartStrategy> \
8233 for String must resolve identically on \
8234 RestartStrategy::{variant:?} — divergence signals the \
8235 borrowed-input and owned-input owned-`String` \
8236 forward-projection input-shape paths have drifted onto \
8237 different emit-sets"
8238 );
8239 assert_eq!(
8240 borrowed_string.as_str(),
8241 borrowed_static,
8242 "From<&RestartStrategy> for String and From<&RestartStrategy> \
8243 for &'static str must resolve identically on \
8244 RestartStrategy::{variant:?} — divergence signals the \
8245 borrowed-input `&'static str` and owned-`String` \
8246 return-shape paths have drifted onto different emit-sets"
8247 );
8248 assert_eq!(
8249 borrowed_string.as_str(),
8250 owned_static,
8251 "From<&RestartStrategy> for String and From<RestartStrategy> \
8252 for &'static str must resolve identically on \
8253 RestartStrategy::{variant:?} — divergence signals a break \
8254 in the diagonal corner of the {{Self, &Self}} × \
8255 {{&'static str, String}} 2×2 trait-idiomatic \
8256 projection family"
8257 );
8258 let via_to_string: String = variant.to_string();
8259 assert_eq!(
8260 borrowed_string, via_to_string,
8261 "From<&RestartStrategy> for String must byte-equal \
8262 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
8263 divergence signals the trait-idiomatic borrowed-input \
8264 owned-`String` forward-projection axis and the \
8265 ToString-through-Display axis have drifted onto different \
8266 emit-sets"
8267 );
8268 }
8269 let via_iter: Vec<String> = RestartStrategy::ALL.iter().map(String::from).collect();
8270 let via_method: Vec<String> = RestartStrategy::ALL
8271 .iter()
8272 .map(|s| s.as_str().to_owned())
8273 .collect();
8274 assert_eq!(
8275 via_iter, via_method,
8276 "`.iter().map(String::from)` over RestartStrategy::ALL — a \
8277 call site whose iteration axis holds `&RestartStrategy` by \
8278 construction — must byte-equal `.iter().map(|s| \
8279 s.as_str().to_owned())` on every arm — the borrowed-input \
8280 owned-`String` `From<&RestartStrategy> for String` axis is \
8281 what makes the `String::from` composition route through the \
8282 substrate-primitive `RestartStrategy::as_str` accessor \
8283 without a spurious `Copy` deref (which would only be \
8284 reachable through the owned-input `From<RestartStrategy> for \
8285 String` axis by first calling `.copied()` on the iterator)"
8286 );
8287 for &variant in RestartStrategy::ALL {
8288 let emitted: String = (&variant).into();
8289 let re_parsed: Result<RestartStrategy, ()> =
8290 <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
8291 assert_eq!(
8292 re_parsed,
8293 Ok(variant),
8294 "trait-idiomatic borrowed-input owned-`String` \
8295 forward-projection + reverse-projection axis pair must \
8296 round-trip &RestartStrategy::{variant:?} through \
8297 `.into::<String>()` on the borrowed-input surface and \
8298 back through `TryFrom<&str>` on the owned-`String`'s \
8299 String::as_str borrow — a break signals the \
8300 borrowed-input owned-`String` forward-emit and \
8301 reverse-parse axes have drifted onto different \
8302 vocabularies"
8303 );
8304 }
8305 }
8306
8307 #[test]
8308 fn restart_strategy_from_into_static_cow_str_routes_through_as_str_accessor() {
8309 // Fail-before-pass-after byte-parity pin on the newly lifted
8310 // `impl From<RestartStrategy> for std::borrow::Cow<'static, str>` —
8311 // asserts the standard-library trait impl and the substrate-
8312 // primitive [`super::RestartStrategy::as_str`] `pub const fn`
8313 // accessor resolve to the same four-arm emit-set across every
8314 // arm the exhaustive [`super::RestartStrategy::ALL`] slice
8315 // enumerates. Rust's standard library does not carry a blanket
8316 // `impl<T: AsRef<str>> From<T> for Cow<'static, str>` (nor an
8317 // `impl<T: fmt::Display> From<T> for Cow<'static, str>`), so
8318 // the `Cow<'static, str>` forward-projection axis is a
8319 // distinct trait-idiomatic surface that a
8320 // `let key: Cow<'static, str> = strategy.into();`-shaped call
8321 // site reaches through this impl and no other — the paired
8322 // sibling `From<RestartStrategy> for &'static str` and
8323 // `From<RestartStrategy> for String` impls force every
8324 // `Cow<'static, str>`-parameterized call site through a
8325 // `Cow::Borrowed(strategy.as_str())` /
8326 // `Cow::Owned(strategy.to_string())` composition whose type
8327 // bounds have no compile-time link back to the substrate
8328 // primitive.
8329 //
8330 // Also asserts the projection lands on the zero-alloc
8331 // [`std::borrow::Cow::Borrowed`] arm (not the
8332 // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
8333 // [`super::RestartStrategy::as_str`] accessor's `&'static str`
8334 // return lifetime by construction makes the borrowed arm the
8335 // type-correct projection with no runtime allocation. Any
8336 // future silent detour that routes the impl through the owned
8337 // arm (an accidental `Cow::Owned(strategy.to_string())` rewrite
8338 // that would allocate on every call site where the
8339 // `&'static str` return of [`super::RestartStrategy::as_str`]
8340 // makes the zero-alloc borrowed projection type-correct) trips
8341 // at caixa-core test time under the
8342 // [`std::borrow::Cow::Borrowed`] discriminator witness rather
8343 // than at a downstream `Cow<'static, str>`-bound consumer's
8344 // silent allocation.
8345 //
8346 // First peer on the substrate-wide trait-idiomatic
8347 // [`std::borrow::Cow<'static, str>`] forward-projection family
8348 // to extend the axis off the top-level [`super::CaixaKind`]
8349 // enum (99c1735 owned-input, d45c409 borrowed-input) onto the
8350 // first M2 OTP-shape closed-set fieldless typed enum on the
8351 // caixa surface.
8352 for &variant in RestartStrategy::ALL {
8353 let via_trait: std::borrow::Cow<'static, str> =
8354 <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
8355 let via_method: &'static str = variant.as_str();
8356 assert_eq!(
8357 via_trait.as_ref(),
8358 via_method,
8359 "From<RestartStrategy> for Cow<'static, str> impl must \
8360 round-trip RestartStrategy::{variant:?} to the same \
8361 lifted SUPERVISOR_ESTRATEGIA_* const \
8362 RestartStrategy::as_str returns — divergence signals a \
8363 silent detour off the substrate-primitive accessor"
8364 );
8365 assert!(
8366 matches!(via_trait, std::borrow::Cow::Borrowed(_)),
8367 "From<RestartStrategy> for Cow<'static, str> impl must \
8368 land on the zero-alloc Cow::Borrowed arm on \
8369 RestartStrategy::{variant:?} — a Cow::Owned outcome \
8370 signals the projection has silently allocated where \
8371 the substrate-primitive RestartStrategy::as_str \
8372 `&'static str` return makes the borrowed arm the \
8373 type-correct projection"
8374 );
8375 let via_into: std::borrow::Cow<'static, str> = variant.into();
8376 assert_eq!(
8377 via_into.as_ref(),
8378 via_method,
8379 "Into<Cow<'static, str>>::into on \
8380 RestartStrategy::{variant:?} must byte-equal \
8381 RestartStrategy::as_str on the same input — the \
8382 blanket-derived Into shape must resolve to the same \
8383 as_str dispatch as the explicit From impl"
8384 );
8385 assert!(
8386 matches!(via_into, std::borrow::Cow::Borrowed(_)),
8387 "Into<Cow<'static, str>>::into on \
8388 RestartStrategy::{variant:?} must land on the \
8389 zero-alloc Cow::Borrowed arm — the blanket-derived \
8390 Into shape must resolve to the same Cow::Borrowed \
8391 dispatch as the explicit From impl"
8392 );
8393 }
8394 }
8395
8396 #[test]
8397 fn restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
8398 // Cross-axis partition pin: the newly lifted trait-idiomatic
8399 // `From<RestartStrategy> for std::borrow::Cow<'static, str>`
8400 // (this lift), the paired owned-input `From<RestartStrategy>
8401 // for &'static str` (523157d), and the paired owned-input
8402 // `From<RestartStrategy> for String` (7baa18a) forward
8403 // projections must resolve identically on every arm, locking
8404 // the three return-shape paths together by construction so any
8405 // future detour trips at caixa-core test time. Also byte-parity
8406 // witness against the sibling [`ToString::to_string`] surface
8407 // routed through [`std::fmt::Display`] — every owned-heap-
8408 // string path (the `Cow::Owned` promotion of this axis's
8409 // `.into_owned()`, `From<RestartStrategy> for String`, and
8410 // `.to_string()`) resolves to the same lifted
8411 // [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const per arm.
8412 //
8413 // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
8414 // witness over [`super::RestartStrategy::ALL`] that
8415 // materializes the four-arm accept-set through the
8416 // [`std::borrow::Cow<'static, str>`] axis alone — the exact
8417 // shape a future `axum::response::IntoResponse` per-strategy
8418 // rejection-body composer, a future M4 admission-webhook
8419 // per-strategy rejection-reason emitter whose typing rules out
8420 // the sibling [`AsRef<str>`] borrowed return, or a future
8421 // substrate-wide per-strategy diagnostic surface that binds
8422 // through a [`Cow<'static, str>`] boundary reaches through.
8423 // The pipe witness also pins the zero-alloc discipline: every
8424 // element in the collected vector satisfies the
8425 // [`std::borrow::Cow::Borrowed`] arm predicate, so a future
8426 // accidental silent-allocation regression on the pipe's
8427 // iteration axis is a caixa-core-test-time failure.
8428 for &variant in RestartStrategy::ALL {
8429 let via_cow: std::borrow::Cow<'static, str> =
8430 <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
8431 let via_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8432 let via_string: String = <String as From<RestartStrategy>>::from(variant);
8433 assert_eq!(
8434 via_cow.as_ref(),
8435 via_static,
8436 "From<RestartStrategy> for Cow<'static, str> and \
8437 From<RestartStrategy> for &'static str must resolve \
8438 identically on RestartStrategy::{variant:?} — \
8439 divergence signals the Cow<'static, str> and \
8440 &'static str return-shape paths have drifted onto \
8441 different emit-sets"
8442 );
8443 assert_eq!(
8444 via_cow.as_ref(),
8445 via_string.as_str(),
8446 "From<RestartStrategy> for Cow<'static, str> and \
8447 From<RestartStrategy> for String must resolve \
8448 identically on RestartStrategy::{variant:?} — \
8449 divergence signals the Cow<'static, str> and String \
8450 return-shape paths have drifted onto different \
8451 emit-sets"
8452 );
8453 let via_to_string: String = variant.to_string();
8454 assert_eq!(
8455 via_cow.as_ref(),
8456 via_to_string.as_str(),
8457 "From<RestartStrategy> for Cow<'static, str> must \
8458 byte-equal RestartStrategy::to_string on \
8459 RestartStrategy::{variant:?} — divergence signals the \
8460 trait-idiomatic Cow<'static, str> forward-projection \
8461 axis and the ToString-through-Display axis have \
8462 drifted onto different emit-sets"
8463 );
8464 }
8465 let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
8466 .iter()
8467 .copied()
8468 .map(std::borrow::Cow::from)
8469 .collect();
8470 let via_method: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
8471 .iter()
8472 .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
8473 .collect();
8474 assert_eq!(
8475 via_iter, via_method,
8476 "`.iter().copied().map(Cow::from)` over \
8477 RestartStrategy::ALL must byte-equal `.iter().map(|s| \
8478 Cow::Borrowed(s.as_str()))` on every arm — the \
8479 trait-idiomatic `From<RestartStrategy> for Cow<'static, \
8480 str>` axis is what makes the `Cow::from` composition \
8481 route through the substrate-primitive \
8482 `RestartStrategy::as_str` accessor with the zero-alloc \
8483 Cow::Borrowed arm by construction, rather than a \
8484 per-call-site `Cow::Owned(strategy.to_string())` \
8485 allocation"
8486 );
8487 for cow in &via_iter {
8488 assert!(
8489 matches!(cow, std::borrow::Cow::Borrowed(_)),
8490 "every element of the \
8491 .iter().copied().map(Cow::from) pipe over \
8492 RestartStrategy::ALL must land on the zero-alloc \
8493 Cow::Borrowed arm — a Cow::Owned outcome on any arm \
8494 signals the pipe's iteration axis has silently \
8495 allocated where the substrate-primitive \
8496 RestartStrategy::as_str `&'static str` return makes \
8497 the borrowed arm the type-correct projection"
8498 );
8499 }
8500 }
8501
8502 #[test]
8503 fn restart_strategy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
8504 // Fail-before-pass-after byte-parity pin on the newly lifted
8505 // `impl From<&RestartStrategy> for std::borrow::Cow<'static, str>` —
8506 // asserts the borrowed-input standard-library trait impl and
8507 // the substrate-primitive [`super::RestartStrategy::as_str`]
8508 // `pub const fn` accessor resolve to the same four-arm emit-
8509 // set across every arm the exhaustive
8510 // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
8511 // standard library does not carry a blanket
8512 // `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor a
8513 // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
8514 // the borrowed-input `Cow<'static, str>` forward-projection
8515 // axis is a distinct trait-idiomatic surface that a
8516 // `let key: Cow<'static, str> = (&strategy).into();`-shaped
8517 // call site or a
8518 // `RestartStrategy::ALL.iter().map(Cow::from)`-shaped pipe
8519 // reaches through this impl and no other — the paired owned-
8520 // input `From<RestartStrategy> for Cow<'static, str>` impl
8521 // (7dd28b3) forces every borrowed-input call site through an
8522 // explicit `Copy` deref (`Cow::from(*strategy)`) or a
8523 // `Cow::Borrowed(strategy.as_str())` open-code whose type
8524 // bounds have no compile-time link back to the substrate
8525 // primitive.
8526 //
8527 // Also asserts the projection lands on the zero-alloc
8528 // [`std::borrow::Cow::Borrowed`] arm (not the
8529 // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
8530 // [`super::RestartStrategy::as_str`] accessor's `&'static str`
8531 // return lifetime by construction makes the borrowed arm the
8532 // type-correct projection with no runtime allocation on the
8533 // borrowed-input surface just as on the paired owned-input
8534 // surface.
8535 //
8536 // Second peer on the substrate-wide trait-idiomatic
8537 // [`std::borrow::Cow<'static, str>`] forward-projection family
8538 // on this enum — closes the `{Self, &Self}` input-shape
8539 // corner of the [`Cow<'static, str>`] axis on the first M2
8540 // OTP-shape closed-set fieldless typed enum peer on the caixa
8541 // surface (`:supervisor :estrategia`), exactly as d45c409
8542 // closed it on the top-level [`super::CaixaKind`] one commit
8543 // after the owning half (99c1735) landed. Every future
8544 // closed-set fieldless typed enum peer on the substrate is a
8545 // future target of the campaign.
8546 for &variant in RestartStrategy::ALL {
8547 let via_trait: std::borrow::Cow<'static, str> =
8548 <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
8549 let via_method: &'static str = variant.as_str();
8550 assert_eq!(
8551 via_trait.as_ref(),
8552 via_method,
8553 "From<&RestartStrategy> for Cow<'static, str> impl must \
8554 round-trip &RestartStrategy::{variant:?} to the same \
8555 lifted SUPERVISOR_ESTRATEGIA_* const \
8556 RestartStrategy::as_str returns — divergence signals a \
8557 silent detour off the substrate-primitive accessor"
8558 );
8559 assert!(
8560 matches!(via_trait, std::borrow::Cow::Borrowed(_)),
8561 "From<&RestartStrategy> for Cow<'static, str> impl must \
8562 land on the zero-alloc Cow::Borrowed arm on \
8563 &RestartStrategy::{variant:?} — a Cow::Owned outcome \
8564 signals the projection has silently allocated where \
8565 the substrate-primitive RestartStrategy::as_str \
8566 `&'static str` return makes the borrowed arm the \
8567 type-correct projection"
8568 );
8569 let via_into: std::borrow::Cow<'static, str> = (&variant).into();
8570 assert_eq!(
8571 via_into.as_ref(),
8572 via_method,
8573 "Into<Cow<'static, str>>::into on \
8574 &RestartStrategy::{variant:?} must byte-equal \
8575 RestartStrategy::as_str on the same input — the \
8576 blanket-derived Into shape must resolve to the same \
8577 as_str dispatch as the explicit From impl"
8578 );
8579 assert!(
8580 matches!(via_into, std::borrow::Cow::Borrowed(_)),
8581 "Into<Cow<'static, str>>::into on \
8582 &RestartStrategy::{variant:?} must land on the \
8583 zero-alloc Cow::Borrowed arm — the blanket-derived \
8584 Into shape must resolve to the same Cow::Borrowed \
8585 dispatch as the explicit From impl"
8586 );
8587 }
8588 }
8589
8590 #[test]
8591 fn restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
8592 // Cross-axis partition pin: the newly lifted trait-idiomatic
8593 // borrowed-input `From<&RestartStrategy> for
8594 // std::borrow::Cow<'static, str>` (this lift), the paired
8595 // owned-input `From<RestartStrategy> for
8596 // std::borrow::Cow<'static, str>` (7dd28b3), the paired
8597 // borrowed-input owned-`&'static str` `From<&RestartStrategy>
8598 // for &'static str`, and the paired borrowed-input owned-
8599 // `String` `From<&RestartStrategy> for String` must resolve
8600 // identically on every arm, locking the four
8601 // return-shape × input-shape paths together by construction so
8602 // any future detour trips at caixa-core test time. Also byte-
8603 // parity witness against the sibling [`ToString::to_string`]
8604 // surface routed through [`std::fmt::Display`] — every owned-
8605 // heap-string path (this axis's `.into_owned()` promotion, the
8606 // paired [`From<&RestartStrategy> for String`], and
8607 // `.to_string()`) resolves to the same lifted
8608 // [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const per arm.
8609 //
8610 // Then a `.iter().map(std::borrow::Cow::from)` pipe witness
8611 // over [`super::RestartStrategy::ALL`] — whose iterator yields
8612 // `&RestartStrategy` by construction, so the borrowed-input
8613 // [`Cow<'static, str>`] axis is what routes the pipe through
8614 // the substrate-primitive [`super::RestartStrategy::as_str`]
8615 // accessor without a spurious [`Copy`] deref (which would only
8616 // be reachable through the owned-input
8617 // [`From<RestartStrategy> for Cow<'static, str>`] axis by
8618 // first calling `.copied()` on the iterator). The pipe witness
8619 // also pins the zero-alloc discipline: every element in the
8620 // collected vector satisfies the [`std::borrow::Cow::Borrowed`]
8621 // arm predicate, so a future accidental silent-allocation
8622 // regression on the pipe's iteration axis is a caixa-core-
8623 // test-time failure.
8624 for &strategy in RestartStrategy::ALL {
8625 let borrowed_cow: std::borrow::Cow<'static, str> =
8626 <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&strategy);
8627 let owned_cow: std::borrow::Cow<'static, str> =
8628 <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(strategy);
8629 let borrowed_static: &'static str =
8630 <&'static str as From<&RestartStrategy>>::from(&strategy);
8631 let borrowed_string: String = <String as From<&RestartStrategy>>::from(&strategy);
8632 assert_eq!(
8633 borrowed_cow, owned_cow,
8634 "From<&RestartStrategy> for Cow<'static, str> and \
8635 From<RestartStrategy> for Cow<'static, str> must \
8636 resolve identically on RestartStrategy::{strategy:?} — \
8637 divergence signals the borrowed-input and owned-input \
8638 Cow<'static, str> forward-projection input-shape \
8639 paths have drifted onto different emit-sets"
8640 );
8641 assert_eq!(
8642 borrowed_cow.as_ref(),
8643 borrowed_static,
8644 "From<&RestartStrategy> for Cow<'static, str> and \
8645 From<&RestartStrategy> for &'static str must resolve \
8646 identically on RestartStrategy::{strategy:?} — \
8647 divergence signals the borrowed-input Cow<'static, \
8648 str> and &'static str return-shape paths have drifted \
8649 onto different emit-sets"
8650 );
8651 assert_eq!(
8652 borrowed_cow.as_ref(),
8653 borrowed_string.as_str(),
8654 "From<&RestartStrategy> for Cow<'static, str> and \
8655 From<&RestartStrategy> for String must resolve \
8656 identically on RestartStrategy::{strategy:?} — \
8657 divergence signals the borrowed-input Cow<'static, \
8658 str> and owned-`String` return-shape paths have \
8659 drifted onto different emit-sets"
8660 );
8661 let via_to_string: String = strategy.to_string();
8662 assert_eq!(
8663 borrowed_cow.as_ref(),
8664 via_to_string.as_str(),
8665 "From<&RestartStrategy> for Cow<'static, str> must \
8666 byte-equal RestartStrategy::to_string on \
8667 RestartStrategy::{strategy:?} — divergence signals \
8668 the trait-idiomatic borrowed-input Cow<'static, str> \
8669 forward-projection axis and the ToString-through-\
8670 Display axis have drifted onto different emit-sets"
8671 );
8672 }
8673 let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
8674 .iter()
8675 .map(std::borrow::Cow::from)
8676 .collect();
8677 let via_method: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
8678 .iter()
8679 .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
8680 .collect();
8681 assert_eq!(
8682 via_iter, via_method,
8683 "`.iter().map(Cow::from)` over RestartStrategy::ALL — a \
8684 call site whose iteration axis holds `&RestartStrategy` \
8685 by construction — must byte-equal `.iter().map(|s| \
8686 Cow::Borrowed(s.as_str()))` on every arm — the borrowed-\
8687 input Cow<'static, str> `From<&RestartStrategy> for \
8688 Cow<'static, str>` axis is what makes the `Cow::from` \
8689 composition route through the substrate-primitive \
8690 `RestartStrategy::as_str` accessor with the zero-alloc \
8691 Cow::Borrowed arm by construction and without a spurious \
8692 `Copy` deref (which would only be reachable through the \
8693 owned-input `From<RestartStrategy> for Cow<'static, str>` \
8694 axis by first calling `.copied()` on the iterator)"
8695 );
8696 for cow in &via_iter {
8697 assert!(
8698 matches!(cow, std::borrow::Cow::Borrowed(_)),
8699 "every element of the .iter().map(Cow::from) pipe \
8700 over RestartStrategy::ALL must land on the zero-\
8701 alloc Cow::Borrowed arm — a Cow::Owned outcome on \
8702 any arm signals the pipe's iteration axis has \
8703 silently allocated where the substrate-primitive \
8704 RestartStrategy::as_str `&'static str` return makes \
8705 the borrowed arm the type-correct projection"
8706 );
8707 }
8708 }
8709
8710 #[test]
8711 fn restart_policy_try_from_str_routes_through_from_wire_accessor() {
8712 // Fail-before-pass-after byte-parity pin on the newly lifted
8713 // `impl TryFrom<&str> for RestartPolicy` — asserts the standard-
8714 // library trait impl and the substrate-primitive
8715 // [`RestartPolicy::from_wire`] `Option<Self>` accessor resolve to
8716 // the same three-arm accept-set across every arm the exhaustive
8717 // [`RestartPolicy::ALL`] slice enumerates. Any future silent
8718 // detour that routes the trait impl through a divergent
8719 // projection (a per-arm inline `match s { "Permanent" =>
8720 // Ok(Self::Permanent), … }` re-inlining that opens a compile-time
8721 // link to the un-lifted arm-literal, a hypothetical
8722 // `#[serde(rename_all = "…")]` attribute drift that silently
8723 // splits the wire byte-string from every consumer that reaches
8724 // for this typed dispatch, an accidental swap onto the kebab-case
8725 // dispatcher-catalog axis the pre-existing [`std::str::FromStr`]
8726 // impl parses through and which would collide the two-axis
8727 // wire/catalog split the sibling [`RestartPolicy::from_wire`]
8728 // doc block makes load-bearing) trips at caixa-core test time
8729 // under `assert_eq!` rather than at a downstream
8730 // `impl TryFrom<&str>`-bound consumer's silent split. Sweeps
8731 // every one of the three arms [`RestartPolicy::ALL`] carries so
8732 // no arm's projection is covered only by the sibling method-
8733 // named `from_wire` path. Peer of the sibling
8734 // [`restart_strategy_try_from_str_routes_through_from_wire_accessor`]
8735 // (5b828ed) — extends the trait-idiomatic reverse-projection
8736 // axis onto the third and final M2-OTP-shape closed-set typed
8737 // enum on the caixa surface (the paired per-child restart-
8738 // decision-policy sibling on the same M2 `:supervisor` slot).
8739 for &variant in RestartPolicy::ALL {
8740 let wire = variant.as_str();
8741 assert_eq!(
8742 <RestartPolicy as TryFrom<&str>>::try_from(wire),
8743 Ok(variant),
8744 "TryFrom<&str> impl on RestartPolicy must round-trip \
8745 RestartPolicy::{variant:?}.as_str() = {wire:?} back to \
8746 Ok(RestartPolicy::{variant:?}) — divergence from \
8747 RestartPolicy::from_wire signals a silent detour off \
8748 the substrate-primitive accessor"
8749 );
8750 assert_eq!(
8751 <RestartPolicy as TryFrom<&str>>::try_from(wire).ok(),
8752 RestartPolicy::from_wire(wire),
8753 "TryFrom<&str> ok()-projection on {wire:?} must byte-\
8754 equal RestartPolicy::from_wire on the same input"
8755 );
8756 }
8757 }
8758
8759 #[test]
8760 fn restart_policy_try_from_str_rejects_unknown_byte_strings() {
8761 // Rejection witness on the `impl TryFrom<&str> for
8762 // RestartPolicy` — sweeps a candidate set of byte-strings
8763 // outside the three-arm PascalCase wire accept-set the sibling
8764 // [`RestartPolicy::as_str`] emits and asserts every one lands on
8765 // `Err(())`, so a future accidental widening of the trait impl's
8766 // accept-set (a stray additional
8767 // `_ if s.eq_ignore_ascii_case("Permanent") => Ok(…)` case-fold
8768 // path, a silent inclusion of the kebab-case dispatcher-catalog
8769 // byte-string the pre-existing [`std::str::FromStr`] impl the
8770 // [`gen_platform::FromStrKind`] derive installs parses onto the
8771 // wire axis — which would collide the two-axis
8772 // wire/dispatcher-catalog split the sibling
8773 // [`RestartPolicy::from_wire`] doc block makes load-bearing —
8774 // an English-rebrand or plural-arm silent alias that would widen
8775 // the wire accept-set past the OTP-canonical three) trips at
8776 // caixa-core test time. The candidate set includes the empty
8777 // string, whitespace-only padding, the kebab-case dispatcher-
8778 // catalog byte-strings on the sibling axis (a caller who
8779 // confuses the two axes trips here rather than at a downstream
8780 // consumer's silent reject), a lowercase / uppercase / mixed-case
8781 // fold of each PascalCase arm (a caller who assumes case-fold
8782 // acceptance trips here), leading/trailing whitespace padding,
8783 // the trailing-newline shape, quote-wrapped candidates, and a
8784 // residual set of plausible-but-wrong English rebrand
8785 // candidates. Peer of the sibling
8786 // [`restart_strategy_try_from_str_rejects_unknown_byte_strings`]
8787 // (5b828ed) rejection witness.
8788 let rejected: &[&str] = &[
8789 "",
8790 " ",
8791 "\n",
8792 "\t",
8793 "permanent",
8794 "temporary",
8795 "transient",
8796 "PERMANENT",
8797 "TEMPORARY",
8798 "TRANSIENT",
8799 "Permanents",
8800 "Permanent ",
8801 " Permanent",
8802 " Temporary ",
8803 "Permanent\n",
8804 "Transient\t",
8805 "\"Permanent\"",
8806 "Ephemeral",
8807 "Always",
8808 "Never",
8809 "OnAbnormalExit",
8810 "intrinsic",
8811 "?",
8812 ];
8813 for &input in rejected {
8814 assert_eq!(
8815 <RestartPolicy as TryFrom<&str>>::try_from(input),
8816 Err(()),
8817 "TryFrom<&str> impl on RestartPolicy must reject the \
8818 non-wire byte-string {input:?} — silent acceptance \
8819 signals an accept-set widening off the paired \
8820 RestartPolicy::from_wire resolver"
8821 );
8822 }
8823 }
8824
8825 #[test]
8826 fn restart_policy_try_from_str_and_from_wire_partition_the_accept_set() {
8827 // Cross-axis partition pin: the paired `TryFrom<&str>` and
8828 // `from_wire` reverse projections must resolve identically on
8829 // *every* input, not just the ones [`RestartPolicy::ALL`]
8830 // enumerates. Sweeps a mixed candidate set spanning accepted
8831 // (three-arm PascalCase wire byte-strings) and rejected (kebab-
8832 // case dispatcher-catalog byte-strings, empty, whitespace-
8833 // padded, quoted, English-rebrand candidates) inputs and asserts
8834 // the trait's `Result::ok()` projection byte-equals the method-
8835 // named resolver's `Option<Self>` return-shape on each, locking
8836 // the two paths together by construction so any future detour
8837 // (a stray `try_from` special-case that widens or narrows the
8838 // accept-set outside the paired `from_wire` resolver, an
8839 // accidental swap onto the kebab-case [`std::str::FromStr`]
8840 // impl the [`gen_platform::FromStrKind`] derive installs on the
8841 // sibling dispatcher-catalog axis) trips at caixa-core test
8842 // time. Peer of the sibling
8843 // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
8844 // pin — extends the round-trip discipline onto the M2-OTP-shape
8845 // per-child restart-policy axis.
8846 let candidates: &[&str] = &[
8847 "Permanent",
8848 "Temporary",
8849 "Transient",
8850 "",
8851 "permanent",
8852 "temporary",
8853 "transient",
8854 "PERMANENT",
8855 "unknown",
8856 "Permanent ",
8857 " Permanent",
8858 "\"Permanent\"",
8859 "Ephemeral",
8860 "OnAbnormalExit",
8861 "?",
8862 ];
8863 for &input in candidates {
8864 let via_trait: Option<RestartPolicy> =
8865 <RestartPolicy as TryFrom<&str>>::try_from(input).ok();
8866 let via_method: Option<RestartPolicy> = RestartPolicy::from_wire(input);
8867 assert_eq!(
8868 via_trait, via_method,
8869 "TryFrom<&str> and from_wire must resolve identically on \
8870 input {input:?} — divergence signals the two reverse-\
8871 projection paths have drifted onto different accept-sets"
8872 );
8873 }
8874 }
8875
8876 #[test]
8877 fn restart_policy_from_into_static_str_routes_through_as_str_accessor() {
8878 // Fail-before-pass-after byte-parity pin on the newly lifted
8879 // `impl From<RestartPolicy> for &'static str` — asserts the
8880 // standard-library trait impl and the substrate-primitive
8881 // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
8882 // the same three-arm emit-set across every arm the exhaustive
8883 // [`RestartPolicy::ALL`] slice enumerates. Any future silent
8884 // detour that routes the trait impl through a divergent
8885 // projection (a per-arm inline `match policy { Permanent =>
8886 // "Permanent", … }` re-inlining that opens a compile-time link
8887 // to the un-lifted arm-literal, an accidental swap onto the
8888 // sibling kebab-case [`Self::discriminant`] dispatcher-catalog
8889 // axis that would collide the two-axis wire/catalog split the
8890 // sibling [`RestartPolicy::from_wire`] doc block makes
8891 // load-bearing) trips at caixa-core test time under
8892 // `assert_eq!` rather than at a downstream
8893 // `impl Into<&'static str>`-bound consumer's silent split.
8894 // Sweeps every one of the three arms [`RestartPolicy::ALL`]
8895 // carries so no arm's projection is covered only by the sibling
8896 // method-named `as_str` / [`std::fmt::Display`] / [`AsRef<str>`]
8897 // paths. Materializes the `<&'static str as
8898 // From<RestartPolicy>>::from` output in a `const`-shape binding
8899 // to make the `'static` lifetime promise a build-time invariant
8900 // — a future accidental downgrade of any of the three arms'
8901 // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] constants to a
8902 // non-`&'static str` (a `String::leak()`-produced return, a
8903 // `Box::leak`-cast) trips at caixa-core build time rather than
8904 // at a downstream `'static`-bound consumer. Peer of the sibling
8905 // [`restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
8906 // (523157d) — extends the trait-idiomatic forward-projection
8907 // axis onto the second (and second-of-two-in-M2) closed-set
8908 // typed enum on the caixa surface (the paired per-child
8909 // restart-decision-policy sibling on the same M2 `:supervisor`
8910 // slot).
8911 const PERMANENT: &str = RestartPolicy::Permanent.as_str();
8912 const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
8913 const TRANSIENT: &str = RestartPolicy::Transient.as_str();
8914 for &variant in RestartPolicy::ALL {
8915 let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
8916 let via_method: &'static str = variant.as_str();
8917 assert_eq!(
8918 via_trait, via_method,
8919 "From<RestartPolicy> for &'static str impl must round-trip \
8920 RestartPolicy::{variant:?} to the same lifted \
8921 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str returns — \
8922 divergence signals a silent detour off the substrate-primitive \
8923 accessor"
8924 );
8925 let via_into: &'static str = variant.into();
8926 assert_eq!(
8927 via_into, via_method,
8928 "Into<&'static str>::into on RestartPolicy::{variant:?} must \
8929 byte-equal RestartPolicy::as_str on the same input — the \
8930 blanket-derived Into shape must resolve to the same as_str \
8931 dispatch as the explicit From impl"
8932 );
8933 }
8934 assert_eq!(
8935 [PERMANENT, TEMPORARY, TRANSIENT],
8936 [
8937 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
8938 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
8939 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
8940 ],
8941 "const-context RestartPolicy::as_str must resolve to the three \
8942 lifted SUPERVISOR_CHILD_RESTART_* consts — a future accidental \
8943 downgrade of any arm to a non-const or non-static byte-string \
8944 breaks the `&'static str`-lifetime promise the paired \
8945 From<RestartPolicy> for &'static str impl carries by \
8946 construction"
8947 );
8948 }
8949
8950 #[test]
8951 fn restart_policy_from_into_static_str_and_as_str_partition_the_emit_set() {
8952 // Cross-axis partition pin: the paired trait-idiomatic
8953 // `From<RestartPolicy> for &'static str` forward projection and
8954 // the method-named [`RestartPolicy::as_str`] forward projection
8955 // must resolve identically on *every* arm, not just the ones
8956 // named in the primary byte-parity pin above. Sweeps every
8957 // [`RestartPolicy::ALL`] arm and asserts the trait's `From::from`
8958 // output byte-equals the method-named accessor's return-value on
8959 // each, locking the two forward-projection paths together by
8960 // construction so any future detour (a stray `From` special-case
8961 // that lands on a divergent per-arm literal outside the paired
8962 // `as_str` dispatch, a hypothetical rebrand touching one axis
8963 // without the other) trips at caixa-core test time. Peer of the
8964 // sibling forward-projection partition pin
8965 // [`restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
8966 // (523157d) — extends the round-trip discipline onto the
8967 // second-of-two M2-OTP-shape closed-set typed enum on the caixa
8968 // surface, closing the two-way `Self ↔ &'static str` round-trip
8969 // on the trait-idiomatic pair (`From<Self> for &'static str` +
8970 // `TryFrom<&str> for Self`) as well as the pre-existing method-
8971 // named pair (`as_str` + `from_wire`).
8972 for &variant in RestartPolicy::ALL {
8973 let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
8974 let via_method: &'static str = variant.as_str();
8975 assert_eq!(
8976 via_trait, via_method,
8977 "From<RestartPolicy> for &'static str and \
8978 RestartPolicy::as_str must resolve identically on \
8979 RestartPolicy::{variant:?} — divergence signals the \
8980 two forward-projection paths have drifted onto different \
8981 emit-sets"
8982 );
8983 }
8984 // Round-trip witness: every arm's forward `From` output re-parses
8985 // through the paired trait-idiomatic reverse `TryFrom<&str>` back
8986 // to the original variant. Closes the two-way `RestartPolicy ↔
8987 // &'static str` round-trip on the trait-idiomatic axis pair,
8988 // mirroring the pre-existing method-named `as_str` + `from_wire`
8989 // round-trip on the substrate-primitive axis pair.
8990 for &variant in RestartPolicy::ALL {
8991 let emitted: &'static str = variant.into();
8992 let re_parsed: Result<RestartPolicy, ()> =
8993 <RestartPolicy as TryFrom<&str>>::try_from(emitted);
8994 assert_eq!(
8995 re_parsed,
8996 Ok(variant),
8997 "trait-idiomatic axis pair must round-trip \
8998 RestartPolicy::{variant:?} through `.into::<&'static \
8999 str>()` and back through `TryFrom<&str>` — a break signals \
9000 the forward-emit and reverse-parse axes have drifted onto \
9001 different vocabularies"
9002 );
9003 }
9004 }
9005
9006 #[test]
9007 fn restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
9008 // Fail-before-pass-after byte-parity pin on the newly lifted
9009 // `impl From<&RestartPolicy> for &'static str` — asserts the
9010 // borrowed-input standard-library trait impl and the substrate-
9011 // primitive [`RestartPolicy::as_str`] `pub const fn` accessor
9012 // resolve to the same three-arm emit-set across every arm the
9013 // exhaustive [`RestartPolicy::ALL`] slice enumerates. Rust's
9014 // `From` trait does not auto-derive the borrowed-input sibling
9015 // from a paired owned-input impl (no `impl<T, U> From<&T> for U
9016 // where T: Copy, U: From<T>` blanket in `core`), so the
9017 // borrowed-input axis is a distinct trait-idiomatic surface
9018 // that a `.iter().map(Into::into)` shape over
9019 // [`RestartPolicy::ALL`] (whose iterator yields
9020 // `&RestartPolicy`, not `RestartPolicy`) reaches through this
9021 // impl and no other — the paired owned-input
9022 // [`From<RestartPolicy>`] impl requires an explicit `.copied()`
9023 // / dereference before the trait fires. Materializes the
9024 // `<&'static str as From<&RestartPolicy>>::from` output in a
9025 // `const`-shape binding to make the `'static` lifetime promise
9026 // a build-time invariant.
9027 const PERMANENT: &str = RestartPolicy::Permanent.as_str();
9028 const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
9029 const TRANSIENT: &str = RestartPolicy::Transient.as_str();
9030 for variant in RestartPolicy::ALL {
9031 let via_trait: &'static str = <&'static str as From<&RestartPolicy>>::from(variant);
9032 let via_method: &'static str = variant.as_str();
9033 assert_eq!(
9034 via_trait, via_method,
9035 "From<&RestartPolicy> for &'static str impl must round-trip \
9036 &RestartPolicy::{variant:?} to the same lifted \
9037 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
9038 returns — divergence signals a silent detour off the \
9039 substrate-primitive accessor"
9040 );
9041 let via_into: &'static str = variant.into();
9042 assert_eq!(
9043 via_into, via_method,
9044 "Into<&'static str>::into on &RestartPolicy::{variant:?} \
9045 must byte-equal RestartPolicy::as_str on the same input — \
9046 the blanket-derived Into shape must resolve to the same \
9047 as_str dispatch as the explicit From impl"
9048 );
9049 }
9050 assert_eq!(
9051 [PERMANENT, TEMPORARY, TRANSIENT],
9052 [
9053 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
9054 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
9055 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
9056 ],
9057 "const-context RestartPolicy::as_str must resolve to the three \
9058 lifted SUPERVISOR_CHILD_RESTART_* consts — the borrowed-input \
9059 From<&RestartPolicy> for &'static str impl inherits its \
9060 `'static` lifetime promise from the same accessor the \
9061 owned-input sibling routes through"
9062 );
9063 }
9064
9065 #[test]
9066 fn restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
9067 // Cross-axis partition pin: the paired trait-idiomatic
9068 // owned-input `From<RestartPolicy> for &'static str` (9fb37d0
9069 // campaign-shape) and borrowed-input `From<&RestartPolicy> for
9070 // &'static str` (this lift) forward projections must resolve
9071 // identically on every arm, locking the two input-shape paths
9072 // together so any future detour trips at caixa-core test time.
9073 // Then a witness that a `.iter().map(Into::into)` pipe over
9074 // [`RestartPolicy::ALL`] (whose iterator yields
9075 // `&RestartPolicy`) materializes the three-arm accept-set
9076 // through the borrowed-input axis alone — the exact shape a
9077 // future wasm-operator per-child post-exit restart-decision
9078 // diagnostic line, a future substrate-wide per-arm diagnostic
9079 // column, or a
9080 // `HashMap::<&'static str, RestartPolicy>::from_iter(
9081 // RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
9082 // per-policy lookup reaches through — closing the two-way
9083 // owned/borrowed input-shape symmetry on the forward-projection
9084 // trait-idiomatic axis. Peer of the sibling
9085 // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9086 // (64aa742) /
9087 // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9088 // (5ab993a) /
9089 // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9090 // (807b0b5) /
9091 // [`restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9092 // (e941836) partition pins on the sibling closed-set typed-enum
9093 // discriminator axes — extends the borrowed-input axis
9094 // discipline onto the second-of-two M2 OTP-shape closed-set
9095 // typed enum on the caixa surface (per-child restart-decision
9096 // policy). Also closes the direct two-way `&Self → &'static
9097 // str → Self` round-trip via the paired [`TryFrom<&str>`] axis
9098 // — unlike the peer [`crate::CaixaKind`] axis pair (whose
9099 // forward `From` emits lowercase Portuguese diagnostic bytes
9100 // while the reverse `TryFrom` parses `PascalCase` wire bytes,
9101 // forcing the round-trip through an intermediate wire-vocab
9102 // hop), the [`RestartPolicy::as_str`] emit and
9103 // [`RestartPolicy::from_wire`] parse share the same
9104 // `PascalCase` vocabulary by construction, so the borrowed-
9105 // input forward axis and the reverse axis compose directly.
9106 for &variant in RestartPolicy::ALL {
9107 let owned: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
9108 let borrowed: &'static str = <&'static str as From<&RestartPolicy>>::from(&variant);
9109 assert_eq!(
9110 owned, borrowed,
9111 "From<RestartPolicy> and From<&RestartPolicy> for \
9112 &'static str must resolve identically on \
9113 RestartPolicy::{variant:?} — divergence signals the \
9114 owned-input and borrowed-input forward-projection paths \
9115 have drifted onto different emit-sets"
9116 );
9117 }
9118 let via_iter: Vec<&'static str> = RestartPolicy::ALL.iter().map(Into::into).collect();
9119 let via_method: Vec<&'static str> = RestartPolicy::ALL.iter().map(|p| p.as_str()).collect();
9120 assert_eq!(
9121 via_iter, via_method,
9122 "`.iter().map(Into::into)` over RestartPolicy::ALL must \
9123 byte-equal `.iter().map(|p| p.as_str())` on every arm — the \
9124 borrowed-input `From<&RestartPolicy> for &'static str` axis \
9125 is what makes the `.iter().map(Into::into)` shape route \
9126 through the substrate-primitive `RestartPolicy::as_str` \
9127 accessor rather than through a per-call-site `.copied()` / \
9128 dereference detour"
9129 );
9130 for variant in RestartPolicy::ALL {
9131 let emitted: &'static str = variant.into();
9132 let re_parsed: Result<RestartPolicy, ()> =
9133 <RestartPolicy as TryFrom<&str>>::try_from(emitted);
9134 assert_eq!(
9135 re_parsed,
9136 Ok(*variant),
9137 "trait-idiomatic borrowed-input forward-projection + \
9138 reverse-projection axis pair must round-trip \
9139 &RestartPolicy::{variant:?} through `.into::<&'static \
9140 str>()` (via the borrowed-input axis) and back through \
9141 `TryFrom<&str>` — a break signals the borrowed-input \
9142 forward-emit and reverse-parse axes have drifted onto \
9143 different vocabularies"
9144 );
9145 }
9146 }
9147
9148 #[test]
9149 fn restart_policy_from_into_owned_string_routes_through_as_str_accessor() {
9150 // Fail-before-pass-after byte-parity pin on the newly lifted
9151 // `impl From<RestartPolicy> for String` — asserts the
9152 // owned-`String`-returning standard-library trait impl and the
9153 // substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
9154 // accessor resolve to the same three-arm emit-set across every
9155 // arm the exhaustive [`RestartPolicy::ALL`] slice enumerates.
9156 // Rust's standard library does not carry a blanket
9157 // `impl<T: AsRef<str>> From<T> for String` (nor an
9158 // `impl<T: fmt::Display> From<T> for String`), so the
9159 // owned-`String` forward-projection axis is a distinct
9160 // trait-idiomatic surface that a `let key: String =
9161 // policy.into();`-shaped call site reaches through this impl
9162 // and no other — the paired sibling `From<RestartPolicy> for
9163 // &'static str` impl forces every owned-`String` call site
9164 // through an explicit `.to_owned()` / `String::from`
9165 // restatement. Peer of the first-mover
9166 // [`restart_strategy_from_into_owned_string_routes_through_as_str_accessor`]
9167 // (7baa18a) — extends the trait-idiomatic owned-`String`
9168 // forward-projection axis onto the second-of-two M2 OTP-shape
9169 // closed-set typed enums on the caixa surface (per-child
9170 // restart-decision-policy sibling on the same M2 `:supervisor`
9171 // slot).
9172 for &variant in RestartPolicy::ALL {
9173 let via_trait: String = <String as From<RestartPolicy>>::from(variant);
9174 let via_method: &'static str = variant.as_str();
9175 assert_eq!(
9176 via_trait.as_str(),
9177 via_method,
9178 "From<RestartPolicy> for String impl must round-trip \
9179 RestartPolicy::{variant:?} to the same lifted \
9180 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
9181 returns — divergence signals a silent detour off the \
9182 substrate-primitive accessor"
9183 );
9184 let via_into: String = variant.into();
9185 assert_eq!(
9186 via_into.as_str(),
9187 via_method,
9188 "Into<String>::into on RestartPolicy::{variant:?} must \
9189 byte-equal RestartPolicy::as_str on the same input — the \
9190 blanket-derived Into shape must resolve to the same as_str \
9191 dispatch as the explicit From impl"
9192 );
9193 }
9194 }
9195
9196 #[test]
9197 fn restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm() {
9198 // Cross-axis partition pin: the paired trait-idiomatic
9199 // owned-`String` `From<RestartPolicy> for String` (this lift)
9200 // and owned-`&'static str` `From<RestartPolicy> for &'static
9201 // str` (9fb37d0) forward projections must resolve identically
9202 // on every arm, locking the two return-type-shape paths
9203 // together so any future detour trips at caixa-core test time.
9204 // Also byte-parity witness against the sibling
9205 // [`ToString::to_string`] surface routed through
9206 // [`std::fmt::Display`] — the three owned-heap-string paths
9207 // (`.into::<String>()`, `String::from`, `.to_string()`) must
9208 // resolve identically on every arm so a future consumer that
9209 // picks any of the three lands on the same lifted
9210 // SUPERVISOR_CHILD_RESTART_* const. Then a `.iter().copied()
9211 // .map(String::from)` pipe witness over [`RestartPolicy::ALL`]
9212 // that materializes the three-arm accept-set through the
9213 // owned-`String` axis alone — the exact shape a future
9214 // wasm-operator per-child post-exit restart-decision
9215 // diagnostic line composer or a
9216 // `HashMap::<String, RestartPolicy>::from_iter(
9217 // RestartPolicy::ALL.iter().copied().map(|p| (p.into(), p)))`-style
9218 // owned-key per-policy lookup reaches through — closing the
9219 // owned-`String` forward-projection axis's iterator-pipe
9220 // shape. Then a direct round-trip witness through the paired
9221 // trait-idiomatic reverse [`TryFrom<&str>`] axis on the
9222 // owned-`String`'s [`String::as_str`] borrow that closes the
9223 // two-way `Self → String → Self` round-trip on the trait-
9224 // idiomatic owned-`String` forward + reverse axis pair —
9225 // unlike the peer [`crate::CaixaKind`] axis pair (whose
9226 // forward `From` emits lowercase Portuguese diagnostic bytes
9227 // while the reverse `TryFrom` parses `PascalCase` wire bytes,
9228 // forcing the round-trip through an intermediate wire-vocab
9229 // hop), the [`RestartPolicy::as_str`] emit and
9230 // [`RestartPolicy::from_wire`] parse share the same
9231 // `PascalCase` vocabulary by construction, so the owned-
9232 // `String` forward axis and the reverse axis compose directly.
9233 for &variant in RestartPolicy::ALL {
9234 let owned_string: String = <String as From<RestartPolicy>>::from(variant);
9235 let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
9236 assert_eq!(
9237 owned_string.as_str(),
9238 owned_static,
9239 "From<RestartPolicy> for String and From<RestartPolicy> \
9240 for &'static str must resolve identically on \
9241 RestartPolicy::{variant:?} — divergence signals the \
9242 owned-`String` and owned-`&'static str` forward-projection \
9243 return-type-shape paths have drifted onto different \
9244 emit-sets"
9245 );
9246 let via_to_string: String = variant.to_string();
9247 assert_eq!(
9248 owned_string, via_to_string,
9249 "From<RestartPolicy> for String must byte-equal \
9250 RestartPolicy::to_string on RestartPolicy::{variant:?} — \
9251 divergence signals the trait-idiomatic owned-`String` \
9252 forward-projection axis and the ToString-through-Display \
9253 axis have drifted onto different emit-sets"
9254 );
9255 }
9256 let via_iter: Vec<String> = RestartPolicy::ALL
9257 .iter()
9258 .copied()
9259 .map(String::from)
9260 .collect();
9261 let via_method: Vec<String> = RestartPolicy::ALL
9262 .iter()
9263 .map(|p| p.as_str().to_owned())
9264 .collect();
9265 assert_eq!(
9266 via_iter, via_method,
9267 "`.iter().copied().map(String::from)` over RestartPolicy::ALL \
9268 must byte-equal `.iter().map(|p| p.as_str().to_owned())` on \
9269 every arm — the owned-`String` `From<RestartPolicy> for \
9270 String` axis is what makes the `String::from` composition \
9271 route through the substrate-primitive `RestartPolicy::as_str` \
9272 accessor rather than through a per-call-site `.to_owned()` / \
9273 `String::from(policy.as_str())` detour"
9274 );
9275 for &variant in RestartPolicy::ALL {
9276 let emitted: String = variant.into();
9277 let re_parsed: Result<RestartPolicy, ()> =
9278 <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
9279 assert_eq!(
9280 re_parsed,
9281 Ok(variant),
9282 "trait-idiomatic owned-`String` forward-projection + \
9283 reverse-projection axis pair must round-trip \
9284 RestartPolicy::{variant:?} through `.into::<String>()` \
9285 and back through `TryFrom<&str>` on the owned-`String`'s \
9286 String::as_str borrow — a break signals the owned-`String` \
9287 forward-emit and reverse-parse axes have drifted onto \
9288 different vocabularies"
9289 );
9290 }
9291 }
9292
9293 #[test]
9294 fn restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
9295 // Fail-before-pass-after byte-parity pin on the newly lifted
9296 // `impl From<&RestartPolicy> for String` — asserts the
9297 // borrowed-input owned-`String`-returning standard-library
9298 // trait impl and the substrate-primitive
9299 // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
9300 // the same three-arm emit-set across every arm the exhaustive
9301 // [`RestartPolicy::ALL`] slice enumerates. Rust's standard
9302 // library does not carry a blanket `impl<T: AsRef<str>>
9303 // From<&T> for String` (nor an `impl<T: fmt::Display> From<&T>
9304 // for String`), so the borrowed-input owned-`String` forward-
9305 // projection axis is a distinct trait-idiomatic surface that a
9306 // `let key: String = (&policy).into();`-shaped call site
9307 // reaches through this impl and no other — the paired sibling
9308 // `From<RestartPolicy> for String` impl forces every borrowed-
9309 // input call site through an explicit `Copy` deref
9310 // (`String::from(*policy)`) or an `.as_str().to_owned()` /
9311 // `.to_string()` detour. Peer of the first-mover
9312 // [`restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
9313 // (579385f) — extends the trait-idiomatic borrowed-input
9314 // owned-`String` forward-projection axis onto the second-of-
9315 // two M2 OTP-shape closed-set typed enums on the caixa surface
9316 // (per-child restart-decision-policy sibling on the same M2
9317 // `:supervisor` slot).
9318 for &variant in RestartPolicy::ALL {
9319 let via_trait: String = <String as From<&RestartPolicy>>::from(&variant);
9320 let via_method: &'static str = variant.as_str();
9321 assert_eq!(
9322 via_trait.as_str(),
9323 via_method,
9324 "From<&RestartPolicy> for String impl must round-trip \
9325 &RestartPolicy::{variant:?} to the same lifted \
9326 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
9327 returns — divergence signals a silent detour off the \
9328 substrate-primitive accessor"
9329 );
9330 let via_into: String = (&variant).into();
9331 assert_eq!(
9332 via_into.as_str(),
9333 via_method,
9334 "Into<String>::into on &RestartPolicy::{variant:?} must \
9335 byte-equal RestartPolicy::as_str on the same input — \
9336 the blanket-derived Into shape must resolve to the \
9337 same as_str dispatch as the explicit From impl"
9338 );
9339 }
9340 }
9341
9342 #[test]
9343 fn restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
9344 // Cross-axis partition pin: the newly lifted trait-idiomatic
9345 // borrowed-input owned-`String` `From<&RestartPolicy> for
9346 // String` (this lift), the paired owned-input owned-`String`
9347 // `From<RestartPolicy> for String` (7851725), the paired
9348 // borrowed-input owned-`&'static str` `From<&RestartPolicy>
9349 // for &'static str` (842c7f3), and the paired owned-input
9350 // owned-`&'static str` `From<RestartPolicy> for &'static str`
9351 // (9fb37d0) — every corner of the `{Self, &Self} × {&'static
9352 // str, String}` 2×2 trait-idiomatic projection family — must
9353 // resolve identically on every arm, locking the four
9354 // return-shape × input-shape paths together so any future
9355 // detour trips at caixa-core test time. Also byte-parity
9356 // witness against the sibling [`ToString::to_string`] surface
9357 // routed through [`std::fmt::Display`] and a direct round-trip
9358 // witness through the paired trait-idiomatic reverse
9359 // [`TryFrom<&str>`] axis on the owned-`String`'s
9360 // [`String::as_str`] borrow that closes the two-way
9361 // `&Self → String → Self` round-trip on the trait-idiomatic
9362 // borrowed-input owned-`String` forward + reverse axis pair.
9363 // Peer of the first-mover
9364 // [`restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
9365 // (579385f) — closes the whole `{Self, &Self} × {&'static str,
9366 // String}` 2×2 projection corner on both M2 OTP-shape sibling
9367 // peers.
9368 for &variant in RestartPolicy::ALL {
9369 let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
9370 let owned_string: String = <String as From<RestartPolicy>>::from(variant);
9371 let borrowed_static: &'static str =
9372 <&'static str as From<&RestartPolicy>>::from(&variant);
9373 let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
9374 assert_eq!(
9375 borrowed_string, owned_string,
9376 "From<&RestartPolicy> for String and From<RestartPolicy> \
9377 for String must resolve identically on \
9378 RestartPolicy::{variant:?} — divergence signals the \
9379 borrowed-input and owned-input owned-`String` \
9380 forward-projection input-shape paths have drifted onto \
9381 different emit-sets"
9382 );
9383 assert_eq!(
9384 borrowed_string.as_str(),
9385 borrowed_static,
9386 "From<&RestartPolicy> for String and From<&RestartPolicy> \
9387 for &'static str must resolve identically on \
9388 RestartPolicy::{variant:?} — divergence signals the \
9389 borrowed-input `&'static str` and owned-`String` \
9390 return-shape paths have drifted onto different \
9391 emit-sets"
9392 );
9393 assert_eq!(
9394 borrowed_string.as_str(),
9395 owned_static,
9396 "From<&RestartPolicy> for String and From<RestartPolicy> \
9397 for &'static str must resolve identically on \
9398 RestartPolicy::{variant:?} — divergence signals a \
9399 break in the diagonal corner of the {{Self, &Self}} × \
9400 {{&'static str, String}} 2×2 trait-idiomatic \
9401 projection family"
9402 );
9403 let via_to_string: String = variant.to_string();
9404 assert_eq!(
9405 borrowed_string, via_to_string,
9406 "From<&RestartPolicy> for String must byte-equal \
9407 RestartPolicy::to_string on RestartPolicy::{variant:?} \
9408 — divergence signals the trait-idiomatic borrowed-input \
9409 owned-`String` forward-projection axis and the \
9410 ToString-through-Display axis have drifted onto \
9411 different emit-sets"
9412 );
9413 }
9414 let via_iter: Vec<String> = RestartPolicy::ALL.iter().map(String::from).collect();
9415 let via_method: Vec<String> = RestartPolicy::ALL
9416 .iter()
9417 .map(|p| p.as_str().to_owned())
9418 .collect();
9419 assert_eq!(
9420 via_iter, via_method,
9421 "`.iter().map(String::from)` over RestartPolicy::ALL — a \
9422 call site whose iteration axis holds `&RestartPolicy` by \
9423 construction — must byte-equal `.iter().map(|p| \
9424 p.as_str().to_owned())` on every arm — the borrowed-input \
9425 owned-`String` `From<&RestartPolicy> for String` axis is \
9426 what makes the `String::from` composition route through \
9427 the substrate-primitive `RestartPolicy::as_str` accessor \
9428 without a spurious `Copy` deref (which would only be \
9429 reachable through the owned-input `From<RestartPolicy> \
9430 for String` axis by first calling `.copied()` on the \
9431 iterator)"
9432 );
9433 for &variant in RestartPolicy::ALL {
9434 let emitted: String = (&variant).into();
9435 let re_parsed: Result<RestartPolicy, ()> =
9436 <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
9437 assert_eq!(
9438 re_parsed,
9439 Ok(variant),
9440 "trait-idiomatic borrowed-input owned-`String` \
9441 forward-projection + reverse-projection axis pair must \
9442 round-trip &RestartPolicy::{variant:?} through \
9443 `.into::<String>()` on the borrowed-input surface and \
9444 back through `TryFrom<&str>` on the owned-`String`'s \
9445 String::as_str borrow — a break signals the \
9446 borrowed-input owned-`String` forward-emit and \
9447 reverse-parse axes have drifted onto different \
9448 vocabularies"
9449 );
9450 }
9451 }
9452
9453 #[test]
9454 fn restart_policy_from_into_static_cow_str_routes_through_as_str_accessor() {
9455 // Fail-before-pass-after byte-parity pin on the newly lifted
9456 // `impl From<RestartPolicy> for std::borrow::Cow<'static, str>` —
9457 // asserts the standard-library trait impl and the substrate-
9458 // primitive [`super::RestartPolicy::as_str`] `pub const fn`
9459 // accessor resolve to the same three-arm emit-set across every
9460 // arm the exhaustive [`super::RestartPolicy::ALL`] slice
9461 // enumerates. Rust's standard library does not carry a blanket
9462 // `impl<T: AsRef<str>> From<T> for Cow<'static, str>` (nor an
9463 // `impl<T: fmt::Display> From<T> for Cow<'static, str>`), so
9464 // the `Cow<'static, str>` forward-projection axis is a
9465 // distinct trait-idiomatic surface that a
9466 // `let key: Cow<'static, str> = policy.into();`-shaped call
9467 // site reaches through this impl and no other — the paired
9468 // sibling `From<RestartPolicy> for &'static str` and
9469 // `From<RestartPolicy> for String` impls force every
9470 // `Cow<'static, str>`-parameterized call site through a
9471 // `Cow::Borrowed(policy.as_str())` /
9472 // `Cow::Owned(policy.to_string())` composition whose type
9473 // bounds have no compile-time link back to the substrate
9474 // primitive.
9475 //
9476 // Also asserts the projection lands on the zero-alloc
9477 // [`std::borrow::Cow::Borrowed`] arm (not the
9478 // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
9479 // [`super::RestartPolicy::as_str`] accessor's `&'static str`
9480 // return lifetime by construction makes the borrowed arm the
9481 // type-correct projection with no runtime allocation. Any
9482 // future silent detour that routes the impl through the owned
9483 // arm (an accidental `Cow::Owned(policy.to_string())` rewrite
9484 // that would allocate on every call site where the
9485 // `&'static str` return of [`super::RestartPolicy::as_str`]
9486 // makes the zero-alloc borrowed projection type-correct) trips
9487 // at caixa-core test time under the
9488 // [`std::borrow::Cow::Borrowed`] discriminator witness rather
9489 // than at a downstream `Cow<'static, str>`-bound consumer's
9490 // silent allocation.
9491 //
9492 // Second peer on the substrate-wide trait-idiomatic
9493 // [`std::borrow::Cow<'static, str>`] forward-projection family
9494 // to extend the axis off the top-level [`super::CaixaKind`]
9495 // enum (99c1735 owned-input, d45c409 borrowed-input) onto the
9496 // second (and second-of-two-in-M2) M2 OTP-shape closed-set
9497 // fieldless typed enum peer on the caixa surface — closes the
9498 // M2 OTP-shape tier of the campaign on the owned-input axis
9499 // (both sibling peers, `RestartStrategy` and `RestartPolicy`,
9500 // now carry the owned-input Cow<'static, str> forward
9501 // projection).
9502 for &variant in RestartPolicy::ALL {
9503 let via_trait: std::borrow::Cow<'static, str> =
9504 <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
9505 let via_method: &'static str = variant.as_str();
9506 assert_eq!(
9507 via_trait.as_ref(),
9508 via_method,
9509 "From<RestartPolicy> for Cow<'static, str> impl must \
9510 round-trip RestartPolicy::{variant:?} to the same \
9511 lifted SUPERVISOR_CHILD_RESTART_* const \
9512 RestartPolicy::as_str returns — divergence signals a \
9513 silent detour off the substrate-primitive accessor"
9514 );
9515 assert!(
9516 matches!(via_trait, std::borrow::Cow::Borrowed(_)),
9517 "From<RestartPolicy> for Cow<'static, str> impl must \
9518 land on the zero-alloc Cow::Borrowed arm on \
9519 RestartPolicy::{variant:?} — a Cow::Owned outcome \
9520 signals the projection has silently allocated where \
9521 the substrate-primitive RestartPolicy::as_str \
9522 `&'static str` return makes the borrowed arm the \
9523 type-correct projection"
9524 );
9525 let via_into: std::borrow::Cow<'static, str> = variant.into();
9526 assert_eq!(
9527 via_into.as_ref(),
9528 via_method,
9529 "Into<Cow<'static, str>>::into on \
9530 RestartPolicy::{variant:?} must byte-equal \
9531 RestartPolicy::as_str on the same input — the \
9532 blanket-derived Into shape must resolve to the same \
9533 as_str dispatch as the explicit From impl"
9534 );
9535 assert!(
9536 matches!(via_into, std::borrow::Cow::Borrowed(_)),
9537 "Into<Cow<'static, str>>::into on \
9538 RestartPolicy::{variant:?} must land on the \
9539 zero-alloc Cow::Borrowed arm — the blanket-derived \
9540 Into shape must resolve to the same Cow::Borrowed \
9541 dispatch as the explicit From impl"
9542 );
9543 }
9544 }
9545
9546 #[test]
9547 fn restart_policy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
9548 // Cross-axis partition pin: the newly lifted trait-idiomatic
9549 // `From<RestartPolicy> for std::borrow::Cow<'static, str>`
9550 // (this lift), the paired owned-input `From<RestartPolicy>
9551 // for &'static str` (9fb37d0), and the paired owned-input
9552 // `From<RestartPolicy> for String` (7851725) forward
9553 // projections must resolve identically on every arm, locking
9554 // the three return-shape paths together by construction so any
9555 // future detour trips at caixa-core test time. Also byte-parity
9556 // witness against the sibling [`ToString::to_string`] surface
9557 // routed through [`std::fmt::Display`] — every owned-heap-
9558 // string path (the `Cow::Owned` promotion of this axis's
9559 // `.into_owned()`, `From<RestartPolicy> for String`, and
9560 // `.to_string()`) resolves to the same lifted
9561 // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const per arm.
9562 //
9563 // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
9564 // witness over [`super::RestartPolicy::ALL`] that
9565 // materializes the three-arm accept-set through the
9566 // [`std::borrow::Cow<'static, str>`] axis alone — the exact
9567 // shape a future `axum::response::IntoResponse` per-policy
9568 // rejection-body composer, a future M4 admission-webhook
9569 // per-policy rejection-reason emitter whose typing rules out
9570 // the sibling [`AsRef<str>`] borrowed return, or a future
9571 // substrate-wide per-policy diagnostic surface that binds
9572 // through a [`Cow<'static, str>`] boundary reaches through.
9573 // The pipe witness also pins the zero-alloc discipline: every
9574 // element in the collected vector satisfies the
9575 // [`std::borrow::Cow::Borrowed`] arm predicate, so a future
9576 // accidental silent-allocation regression on the pipe's
9577 // iteration axis is a caixa-core-test-time failure. Peer of
9578 // the first-mover
9579 // [`restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
9580 // (7dd28b3) on the sibling M2 OTP-shape sibling-restart axis
9581 // — closes the whole owned-input `Cow<'static, str>` +
9582 // paired `{&'static str, String}` cross-axis-parity corner on
9583 // both M2 OTP-shape sibling peers.
9584 for &variant in RestartPolicy::ALL {
9585 let via_cow: std::borrow::Cow<'static, str> =
9586 <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
9587 let via_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
9588 let via_string: String = <String as From<RestartPolicy>>::from(variant);
9589 assert_eq!(
9590 via_cow.as_ref(),
9591 via_static,
9592 "From<RestartPolicy> for Cow<'static, str> and \
9593 From<RestartPolicy> for &'static str must resolve \
9594 identically on RestartPolicy::{variant:?} — \
9595 divergence signals the Cow<'static, str> and \
9596 &'static str return-shape paths have drifted onto \
9597 different emit-sets"
9598 );
9599 assert_eq!(
9600 via_cow.as_ref(),
9601 via_string.as_str(),
9602 "From<RestartPolicy> for Cow<'static, str> and \
9603 From<RestartPolicy> for String must resolve \
9604 identically on RestartPolicy::{variant:?} — \
9605 divergence signals the Cow<'static, str> and String \
9606 return-shape paths have drifted onto different \
9607 emit-sets"
9608 );
9609 let via_to_string: String = variant.to_string();
9610 assert_eq!(
9611 via_cow.as_ref(),
9612 via_to_string.as_str(),
9613 "From<RestartPolicy> for Cow<'static, str> must \
9614 byte-equal RestartPolicy::to_string on \
9615 RestartPolicy::{variant:?} — divergence signals the \
9616 trait-idiomatic Cow<'static, str> forward-projection \
9617 axis and the ToString-through-Display axis have \
9618 drifted onto different emit-sets"
9619 );
9620 }
9621 let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
9622 .iter()
9623 .copied()
9624 .map(std::borrow::Cow::from)
9625 .collect();
9626 let via_method: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
9627 .iter()
9628 .map(|p| std::borrow::Cow::Borrowed(p.as_str()))
9629 .collect();
9630 assert_eq!(
9631 via_iter, via_method,
9632 "`.iter().copied().map(Cow::from)` over \
9633 RestartPolicy::ALL must byte-equal `.iter().map(|p| \
9634 Cow::Borrowed(p.as_str()))` on every arm — the \
9635 trait-idiomatic `From<RestartPolicy> for Cow<'static, \
9636 str>` axis is what makes the `Cow::from` composition \
9637 route through the substrate-primitive \
9638 `RestartPolicy::as_str` accessor with the zero-alloc \
9639 Cow::Borrowed arm by construction, rather than a \
9640 per-call-site `Cow::Owned(policy.to_string())` \
9641 allocation"
9642 );
9643 for cow in &via_iter {
9644 assert!(
9645 matches!(cow, std::borrow::Cow::Borrowed(_)),
9646 "every element of the \
9647 .iter().copied().map(Cow::from) pipe over \
9648 RestartPolicy::ALL must land on the zero-alloc \
9649 Cow::Borrowed arm — a Cow::Owned outcome on any arm \
9650 signals the pipe's iteration axis has silently \
9651 allocated where the substrate-primitive \
9652 RestartPolicy::as_str `&'static str` return makes \
9653 the borrowed arm the type-correct projection"
9654 );
9655 }
9656 }
9657
9658 // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_RESTART_* identity ─
9659
9660 #[test]
9661 fn restart_policy_variants_serialize_to_lifted_scalar_values() {
9662 // The fail-before-pass-after pin: pre-lift there was no
9663 // single-source binding between the [`RestartPolicy`] variant
9664 // name the un-`rename`d `Serialize` derive emits under
9665 // [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
9666 // byte-string every downstream cluster-side dispatcher (the
9667 // future wasm-operator's per-child post-exit restart-decision
9668 // branch, the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
9669 // materializer's admission-time enum-arm bind, the
9670 // `caixa-operator`'s hierarchical reconciliation scheduler's
9671 // per-child-policy fan-out) probes verbatim. A future
9672 // `#[serde(rename_all = "kebab-case")]` attribute on the enum —
9673 // or a per-variant `#[serde(rename = "…")]` override, or a
9674 // variant rename in the source — would silently rebrand the
9675 // emitted scalar under one spelling while every downstream
9676 // dispatcher still probed the other, with the failure surfacing
9677 // at the operator's reconcile posture (children coming up under
9678 // the `default()` `Permanent` arm rather than the typed slot's
9679 // declared policy — a `:temporary` `oneShot` child would be
9680 // restarted on clean exit, treating the successful-completion
9681 // signal as failure and re-running the completion-terminal
9682 // one-shot indefinitely; a `:transient` child that clean-exited
9683 // would be restarted, masking the clean-completion contract)
9684 // far from the source rebrand commit and with no field naming
9685 // the drift. Pinning the two paths (the `Serialize` derive's
9686 // serialized string AND the [`RestartPolicy::as_str`] helper)
9687 // to the same three lifted
9688 // [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
9689 // [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
9690 // [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
9691 // byte-strings makes any future drift on either endpoint fail
9692 // here at caixa-core build time. Peer of the sibling
9693 // [`restart_strategy_variants_serialize_to_lifted_scalar_values`]
9694 // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
9695 // and the M3
9696 // `placement_strategy_variants_serialize_to_lifted_scalar_values`
9697 // (3f0e21c) on the per-Aplicacao distribution-strategy axis —
9698 // same three-path-convergence discipline, extended to close the
9699 // third OTP-shaped closed-enum discriminator axis on the caixa
9700 // typed surface (per-child restart-decision policy).
9701 for (variant, expected) in [
9702 (
9703 RestartPolicy::Permanent,
9704 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
9705 ),
9706 (
9707 RestartPolicy::Temporary,
9708 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
9709 ),
9710 (
9711 RestartPolicy::Transient,
9712 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
9713 ),
9714 ] {
9715 let json = serde_json::to_string(&variant).unwrap();
9716 assert_eq!(
9717 json,
9718 format!("\"{expected}\""),
9719 "RestartPolicy::{variant:?} must serialize to {expected:?}"
9720 );
9721 assert_eq!(
9722 variant.as_str(),
9723 expected,
9724 "RestartPolicy::{variant:?}.as_str() must return the lifted \
9725 SUPERVISOR_CHILD_RESTART_* constant"
9726 );
9727 }
9728 }
9729
9730 #[test]
9731 fn supervisor_child_restart_consts_are_pairwise_distinct() {
9732 // Cross-arm drift-detection pin: a future collapse of two
9733 // canonical variant byte-strings onto the same value (e.g. an
9734 // accidental copy-paste flip of `SUPERVISOR_CHILD_RESTART_TRANSIENT`
9735 // to also read `"Permanent"`) would silently reroute every
9736 // downstream operator's per-child-policy dispatch onto the
9737 // sibling arm's reconcile branch and pass every propagation-probe
9738 // test that expected only the stale arm's value — a `:transient`
9739 // child would come up under the `:permanent` restart-decision
9740 // posture on every subsequent clean exit, so a completion-terminal
9741 // child would be restarted indefinitely against its declared
9742 // policy. Peer of the sibling
9743 // [`supervisor_estrategia_consts_are_pairwise_distinct`]
9744 // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
9745 // and the four-way distinct pin
9746 // `supervisor_key_consts_are_pairwise_distinct` (40cc4e5) on the
9747 // top-level `SUPERVISOR_KEY_*` axis.
9748 let all = [
9749 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
9750 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
9751 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
9752 ];
9753 for (i, a) in all.iter().enumerate() {
9754 for (j, b) in all.iter().enumerate() {
9755 if i != j {
9756 assert_ne!(
9757 a, b,
9758 "SUPERVISOR_CHILD_RESTART_* consts must be pairwise distinct \
9759 — got duplicate {a:?} at indices {i} and {j}",
9760 );
9761 }
9762 }
9763 }
9764 }
9765
9766 #[test]
9767 fn restart_policy_display_routes_through_as_str_helper() {
9768 // The fail-before-pass-after pin on the first half of the
9769 // three-path convergence: pre-convergence [`RestartPolicy`]
9770 // carried a [`std::fmt::Display`] surface via its
9771 // `#[discriminant(also_display)]` gen-platform derive route,
9772 // which arrived kebab-case as `"permanent"` / `"temporary"`
9773 // / `"transient"` on this three-arm enum (whose variant
9774 // names each collapse to their own lowercase form under the
9775 // kebab-case transform) while the wire format ran as
9776 // PascalCase `"Permanent"` / `"Temporary"` / `"Transient"`
9777 // through the un-`rename`d serde derive. Every consumer
9778 // reaching for a policy byte-string past the wire format had
9779 // to pick between three paths ([`RestartPolicy::as_str`],
9780 // the `Serialize` derive's serialized string, or
9781 // `format!("{v}")` on the discriminant-Display route), any
9782 // two of which a future variant rename or
9783 // `#[serde(rename_all = "kebab-case")]` attribute would
9784 // silently desynchronize. Wiring [`std::fmt::Display`]
9785 // through [`RestartPolicy::as_str`] closes the third path:
9786 // every `format!("{v}")` call reaches the same lifted
9787 // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the
9788 // wire format and the [`RestartPolicy::as_str`] helper
9789 // already route through, so a future variant rename lands at
9790 // exactly one place. Pin the routing here so a future
9791 // `impl std::fmt::Display for RestartPolicy`
9792 // reimplementation that hand-rolls the arms instead of
9793 // delegating to [`RestartPolicy::as_str`] fails at
9794 // caixa-core build time. Peer of the sibling
9795 // [`restart_strategy_display_routes_through_as_str_helper`]
9796 // on the per-supervisor sibling-restart-strategy axis and
9797 // the M3
9798 // `placement_strategy_display_routes_through_as_str_helper`
9799 // (cc8f749) — the third of three OTP-shape closed-enum
9800 // discriminator axes on the caixa typed surface now
9801 // converged onto the same three-path
9802 // (Display → as_str → lifted const) discipline.
9803 for variant in [
9804 RestartPolicy::Permanent,
9805 RestartPolicy::Temporary,
9806 RestartPolicy::Transient,
9807 ] {
9808 assert_eq!(
9809 variant.to_string(),
9810 variant.as_str(),
9811 "RestartPolicy::{variant:?} Display must route through \
9812 RestartPolicy::as_str (single source of truth: the lifted \
9813 SUPERVISOR_CHILD_RESTART_* const the wire format also emits)"
9814 );
9815 }
9816 }
9817
9818 #[test]
9819 fn restart_policy_display_matches_serialized_wire_byte_string() {
9820 // The fail-before-pass-after pin on the second half of the
9821 // three-path convergence: `Display` (user-facing text) agrees
9822 // byte-for-byte with the `Serialize` derive's wire format
9823 // (canonical camelCase-schema `SUPERVISOR_CHILD_KEY_RESTART`
9824 // scalar) on every variant. Pre-convergence the two paths
9825 // were structurally independent — a future
9826 // `#[serde(rename_all = "kebab-case")]` attribute on the
9827 // enum would silently rebrand the emitted wire scalar
9828 // (`permanent`, `temporary`, `transient`) while every
9829 // consumer that pretty-prints the policy (the future
9830 // wasm-operator's per-child post-exit restart-decision
9831 // diagnostic line, the future `feira app graph` per-child
9832 // restart column, the future M4
9833 // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
9834 // per-child admission-webhook rejection body) would still
9835 // emit the PascalCase form the `as_str` / `Display` route
9836 // returns, with the mismatch surfacing at consumer parse
9837 // time / operator dispatch time far from the source rebrand
9838 // commit. Pin the two paths byte-for-byte here so any future
9839 // serde-attribute or variant-rename drift is a
9840 // caixa-core-build-time test failure at this call, not a
9841 // silent per-consumer dispatch miss. Peer of the sibling
9842 // [`restart_strategy_display_matches_serialized_wire_byte_string`]
9843 // on the per-supervisor sibling-restart-strategy axis and
9844 // the M3
9845 // `placement_strategy_display_matches_serialized_wire_byte_string`
9846 // (cc8f749).
9847 for variant in [
9848 RestartPolicy::Permanent,
9849 RestartPolicy::Temporary,
9850 RestartPolicy::Transient,
9851 ] {
9852 let wire = serde_json::to_string(&variant).unwrap();
9853 let unquoted = wire
9854 .strip_prefix('"')
9855 .and_then(|s| s.strip_suffix('"'))
9856 .expect("serialized RestartPolicy is a JSON string");
9857 assert_eq!(
9858 variant.to_string(),
9859 unquoted,
9860 "RestartPolicy::{variant:?} Display byte-string must match the \
9861 Serialize derive's wire byte-string (three-path convergence: \
9862 Display + as_str + Serialize all resolve to the same \
9863 SUPERVISOR_CHILD_RESTART_* const)"
9864 );
9865 }
9866 }
9867
9868 #[test]
9869 fn restart_policy_as_ref_str_routes_through_as_str_accessor() {
9870 // Fail-before-pass-after byte-parity pin on the lifted
9871 // `impl AsRef<str> for RestartPolicy` — asserts the
9872 // standard-library trait impl and the substrate-primitive
9873 // [`RestartPolicy::as_str`] `pub const fn` accessor resolve
9874 // to the same `&str` per instance across the three-arm
9875 // closed set, so any future silent detour that routes the
9876 // impl through a divergent projection (a per-arm inline
9877 // `match self { RestartPolicy::Permanent => "Permanent", … }`
9878 // re-inlining that opens a compile-time link to the un-lifted
9879 // arm-literal, a swap onto the kebab-case
9880 // [`gen_platform::Discriminant`] catalog identity that would
9881 // collide the wire axis with the dispatcher-catalog axis) trips
9882 // at caixa-core test time under `PartialEq` rather than at a
9883 // downstream `impl AsRef<str>`-bound consumer's silent split.
9884 // Sweeps every one of the three arms
9885 // [`RestartPolicy::ALL`] carries so no arm's projection is
9886 // covered only by the sibling wire-format `Serialize` derive
9887 // path. Peer of the sibling
9888 // [`restart_strategy_as_ref_str_routes_through_as_str_accessor`]
9889 // (63eb1a4) on the paired per-supervisor sibling-restart-
9890 // strategy axis and the [`crate::CaixaVersion`]
9891 // `AsRef<str>`-byte-parity pin (16d5c7e) on the paired
9892 // top-level `:versao` typed newtype — the three pins together
9893 // cover the substrate primitive's `AsRef<str>` projection axis
9894 // on the paired newtype + M2 closed-set-typed-enum surface.
9895 for &variant in RestartPolicy::ALL {
9896 assert_eq!(
9897 <RestartPolicy as AsRef<str>>::as_ref(&variant),
9898 variant.as_str(),
9899 "AsRef<str> impl on RestartPolicy::{variant:?} must \
9900 byte-equal RestartPolicy::as_str on the same instance \
9901 — divergence signals a silent detour off the substrate-\
9902 primitive accessor"
9903 );
9904 }
9905 }
9906
9907 #[test]
9908 fn restart_policy_as_ref_str_routes_through_display_via_shared_accessor() {
9909 // Fail-before-pass-after byte-parity pin on the three-path
9910 // convergence discipline the M2 per-child-restart-policy
9911 // primitive now carries on the `&str`-projection axis:
9912 // `<RestartPolicy as AsRef<str>>::as_ref(&v)` (the newly
9913 // lifted impl), `format!("{v}")` (the pre-existing
9914 // [`fmt::Display`] impl), and `v.as_str()` (the substrate-
9915 // primitive `pub const fn` accessor both trait impls delegate
9916 // through) must resolve to the same byte-string on every
9917 // instance across the three-arm closed set. Refuses any future
9918 // divergence between the two trait impls (a stray
9919 // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
9920 // rather than delegating through the shared accessor; a
9921 // hypothetical `AsRef<str>` rewrite that inlines a per-arm
9922 // literal cascade) that would silently split the two
9923 // projection paths of the same closed-set typed enum. Mirrors
9924 // the sibling three-path-convergence discipline the peer
9925 // [`RestartStrategy`] typed enum carries on its
9926 // `AsRef<str>` / `Display` / `as_str` triple
9927 // (supervisor.rs pin
9928 // `restart_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
9929 // 63eb1a4) and the [`crate::CaixaVersion`] typed newtype
9930 // carries on the same triple (version.rs pin
9931 // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
9932 // 16d5c7e).
9933 for &variant in RestartPolicy::ALL {
9934 let via_as_ref: &str = <RestartPolicy as AsRef<str>>::as_ref(&variant);
9935 let via_display: String = format!("{variant}");
9936 let via_accessor: &str = variant.as_str();
9937 assert_eq!(via_as_ref, via_accessor);
9938 assert_eq!(via_display, via_accessor);
9939 assert_eq!(via_as_ref, via_display.as_str());
9940 }
9941 }
9942
9943 #[test]
9944 fn restart_policy_all_enumerates_every_variant_exactly_once() {
9945 // Fail-before-pass-after pin on the [`RestartPolicy::ALL`]
9946 // exhaustive-iteration surface: every variant appears exactly
9947 // once, and the slice length matches the arm count of the
9948 // closed set. Every consumer that walks the accepted-policy
9949 // set (a future `feira supervisor --restart …` CLI-side
9950 // arg-parse's "did you mean" hint, a future M4 admission-
9951 // webhook's per-child rejection body naming the accepted-
9952 // `:restart` list, the [`RestartPolicy::from_wire`] reverse-
9953 // projection consumers that iterate the accept-set for
9954 // diagnostic rendering) reads through this slice, so a future
9955 // arm addition that grows the enum but forgets to grow
9956 // [`Self::ALL`] silently truncates every downstream consumer's
9957 // accept-set at the same pre-addition boundary — this pin
9958 // fails at caixa-core build time on the pairwise-distinct +
9959 // arm-count invariants.
9960 //
9961 // Peer of the sibling [`RestartStrategy::ALL`] (4eec29c) /
9962 // [`crate::CaixaKind::ALL`] (6b1f4fb) /
9963 // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
9964 // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
9965 // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
9966 // pins on the peer closed-set typed-enum axes.
9967 let all: &[RestartPolicy] = RestartPolicy::ALL;
9968 assert_eq!(
9969 all.len(),
9970 3,
9971 "RestartPolicy::ALL must enumerate every variant of the \
9972 three-arm closed set (Permanent, Temporary, Transient); \
9973 got {all:?}"
9974 );
9975 for (i, a) in all.iter().enumerate() {
9976 for (j, b) in all.iter().enumerate() {
9977 if i != j {
9978 assert_ne!(
9979 a, b,
9980 "RestartPolicy::ALL must carry every variant exactly \
9981 once — got duplicate {a:?} at indices {i} and {j}"
9982 );
9983 }
9984 }
9985 }
9986 for variant in [
9987 RestartPolicy::Permanent,
9988 RestartPolicy::Temporary,
9989 RestartPolicy::Transient,
9990 ] {
9991 assert!(
9992 all.contains(&variant),
9993 "RestartPolicy::ALL must contain {variant:?} — a future arm \
9994 addition that grows the enum but forgets to grow the ALL slice \
9995 silently truncates every downstream consumer's accept-set at \
9996 the pre-addition boundary"
9997 );
9998 }
9999 }
10000
10001 #[test]
10002 fn restart_policy_from_wire_accepts_every_lifted_constant() {
10003 // Fail-before-pass-after pin on the forward accept-set of the
10004 // [`RestartPolicy::from_wire`] reverse projection: every
10005 // canonical [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
10006 // constant the [`RestartPolicy::as_str`] emitter walks parses
10007 // back to its paired variant. Any future arm addition that
10008 // grows the emitter's `as_str` match but forgets to grow the
10009 // parser's `from_wire` match silently splits the two halves of
10010 // the round-trip — the wire byte-string one non-serde consumer
10011 // parses from the one the emitter wrote — with the failure
10012 // surfacing at the operator's reconcile posture (a `:temporary`
10013 // `oneShot` child restarted on clean exit, a `:transient` child
10014 // restarted after clean completion) far from the rebrand
10015 // commit. Pinning the three-arm accept-set here catches the
10016 // drift at caixa-core build time.
10017 //
10018 // Peer of the sibling [`RestartStrategy::from_wire`] (4eec29c)
10019 // + [`crate::CaixaKind::from_wire`] (2aa6d23)
10020 // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
10021 // accept-set pins on the peer closed-set typed-enum `str → Self`
10022 // axes.
10023 for (wire, expected) in [
10024 (
10025 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
10026 RestartPolicy::Permanent,
10027 ),
10028 (
10029 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
10030 RestartPolicy::Temporary,
10031 ),
10032 (
10033 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
10034 RestartPolicy::Transient,
10035 ),
10036 ] {
10037 let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
10038 panic!(
10039 "RestartPolicy::from_wire({wire:?}) must accept every \
10040 SUPERVISOR_CHILD_RESTART_* constant — got None for the \
10041 lifted canonical byte-string that RestartPolicy::{expected:?} \
10042 serializes as under SUPERVISOR_CHILD_KEY_RESTART"
10043 )
10044 });
10045 assert_eq!(
10046 parsed, expected,
10047 "RestartPolicy::from_wire({wire:?}) must return \
10048 RestartPolicy::{expected:?}; got RestartPolicy::{parsed:?}"
10049 );
10050 }
10051 }
10052
10053 #[test]
10054 fn restart_policy_from_wire_round_trips_through_as_str() {
10055 // Fail-before-pass-after pin on the closed round-trip between
10056 // the forward [`RestartPolicy::as_str`] emitter and the
10057 // reverse [`RestartPolicy::from_wire`] parser: for every
10058 // variant in [`RestartPolicy::ALL`], parsing the emitter's
10059 // output must return exactly the same variant. Any per-arm
10060 // divergence — a future arm added to `as_str` but not
10061 // `from_wire`, an accidental copy-paste flip in one but not
10062 // the other — silently splits the emit and parse halves and
10063 // the failure surfaces at consumer parse time far from the
10064 // drift site. The `ALL`-iterating shape means a future arm
10065 // addition picks up the coverage by construction.
10066 //
10067 // Peer of the sibling
10068 // [`restart_strategy_from_wire_round_trips_through_as_str`]
10069 // (4eec29c) round-trip pin on
10070 // [`RestartStrategy::from_wire`] and the M3
10071 // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
10072 // (18c7342) round-trip pin on
10073 // [`crate::aplicacao::PlacementStrategy::from_wire`].
10074 for &variant in RestartPolicy::ALL {
10075 let wire = variant.as_str();
10076 let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
10077 panic!(
10078 "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
10079 must be Some({variant:?}) — the two halves of the round-trip \
10080 dispatch on the same lifted SUPERVISOR_CHILD_RESTART_* consts; \
10081 got None on wire byte-string {wire:?}"
10082 )
10083 });
10084 assert_eq!(
10085 parsed, variant,
10086 "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
10087 must round-trip to the same variant; got {parsed:?}"
10088 );
10089 }
10090 }
10091
10092 #[test]
10093 fn restart_policy_from_wire_rejects_unknown_byte_strings() {
10094 // Fail-before-pass-after pin on the closed-set refusal
10095 // discipline of [`RestartPolicy::from_wire`]: every
10096 // byte-string outside the three-arm accept-set returns `None`
10097 // rather than silently collapsing onto the [`Default`]
10098 // (`Permanent`) arm or an arbitrary neighbor. The refusal set
10099 // exercised here sweeps the load-bearing drift shapes: the
10100 // empty string (a stripped serde-attribute drift), all-
10101 // whitespace strings (the canonical text-editor accidental
10102 // padding shape), the kebab-case dispatcher-catalog identities
10103 // (`"permanent"` / `"temporary"` / `"transient"` — the
10104 // [`gen_platform::FromStrKind`]-derived [`std::str::FromStr`]
10105 // accept-set, which parses the *other* axis of this enum's
10106 // two-axis split and must not leak into the `from_wire`
10107 // PascalCase-wire accept-set — a lowercase leak here would
10108 // silently accept the operator's kebab-case
10109 // dispatcher-catalog probe under the wire-axis parser and mis-
10110 // route a `:permanent` intent), the padded canonical scalar
10111 // (`" Permanent "`), the trailing-newline shapes
10112 // (`"Permanent\n"`), the uppercase-single-word forms
10113 // (`"PERMANENT"`), and neighboring-but-unknown arms
10114 // (`"Restart"` — the canonical typo direction toward the
10115 // sibling [`RestartStrategy`] enum's own wire-arm namespace).
10116 //
10117 // Peer of the sibling
10118 // [`restart_strategy_from_wire_rejects_unknown_byte_strings`]
10119 // (4eec29c) +
10120 // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
10121 // (2aa6d23) +
10122 // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
10123 // (18c7342) refusal pins on the peer closed-set typed-enum
10124 // axes.
10125 for bad in [
10126 "",
10127 " ",
10128 "\n",
10129 "\t",
10130 "permanent",
10131 "temporary",
10132 "transient",
10133 "PERMANENT",
10134 "TEMPORARY",
10135 "TRANSIENT",
10136 "Permanents",
10137 "Permanent ",
10138 " Permanent",
10139 " Transient ",
10140 "Permanent\n",
10141 "perma",
10142 "Trans",
10143 "OneForOne",
10144 "Restart",
10145 "?",
10146 ] {
10147 assert!(
10148 RestartPolicy::from_wire(bad).is_none(),
10149 "RestartPolicy::from_wire({bad:?}) must return None — the \
10150 parser's accept-set is exactly the three RestartPolicy::as_str \
10151 outputs (Permanent, Temporary, Transient), and this \
10152 byte-string is outside that closed set"
10153 );
10154 }
10155 }
10156
10157 #[test]
10158 fn restart_policy_from_wire_matches_serialize_derive_wire_byte_string() {
10159 // Fail-before-pass-after pin on the fourth path of the four-path
10160 // convergence: `from_wire` (the reverse projection) inverts the
10161 // `Serialize` derive's wire byte-string on every variant.
10162 // Together with the pre-existing three-path convergence
10163 // (`Display` + `as_str` + `Serialize` all resolve to the same
10164 // lifted [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const,
10165 // pinned by
10166 // [`restart_policy_display_matches_serialized_wire_byte_string`])
10167 // this closes the round-trip: the wire byte-string the
10168 // `Serialize` derive emits parses back to the same variant
10169 // through `from_wire`, so any future serde-attribute or variant-
10170 // rename drift on the emit half now surfaces as a matched drift
10171 // on the parse half at caixa-core build time — the two halves
10172 // migrate as a unit through the lifted consts on any future
10173 // rename, and the round-trip cannot silently split.
10174 //
10175 // Peer of the sibling
10176 // [`restart_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
10177 // (4eec29c) wire-format pin on
10178 // [`RestartStrategy::from_wire`] and the M3
10179 // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
10180 // (18c7342) wire-format pin on
10181 // [`crate::aplicacao::PlacementStrategy::from_wire`].
10182 for &variant in RestartPolicy::ALL {
10183 let wire = serde_json::to_string(&variant).unwrap();
10184 let unquoted = wire
10185 .strip_prefix('"')
10186 .and_then(|s| s.strip_suffix('"'))
10187 .expect("serialized RestartPolicy is a JSON string");
10188 let parsed = RestartPolicy::from_wire(unquoted).unwrap_or_else(|| {
10189 panic!(
10190 "RestartPolicy::from_wire({unquoted:?}) must accept the \
10191 Serialize derive's wire byte-string for \
10192 RestartPolicy::{variant:?} — the four-path convergence \
10193 (Display + as_str + Serialize + from_wire) resolves through \
10194 the same lifted SUPERVISOR_CHILD_RESTART_* const; got None"
10195 )
10196 });
10197 assert_eq!(
10198 parsed, variant,
10199 "RestartPolicy::from_wire of the Serialize derive's wire \
10200 byte-string for RestartPolicy::{variant:?} must round-trip \
10201 to the same variant; got {parsed:?}"
10202 );
10203 }
10204 }
10205
10206 // ── drift-detection: ChildSpec::nome accessor pins ────────────────────
10207 //
10208 // The M2 supervisor-tree sibling of the M3 `Membro::nome` (4a32abf) pin
10209 // pair (`membro_nome_returns_caixa_byte_equal_across_permutations` +
10210 // `membro_nome_borrows_from_caixa_storage`) — extended here to the M2
10211 // per-`:children` child-caixa `:nome` axis, sibling to the first M2
10212 // slot scalar accessor `UpgradeFromEntry::prior_versao` (75d27a8) on
10213 // the peer per-`:upgrade-from :from` axis. The three pins jointly
10214 // brace the accessor against every future silent detour that would
10215 // desynchronize it from the raw `.caixa` field access every consumer
10216 // previously open-coded.
10217
10218 #[test]
10219 fn child_spec_nome_returns_caixa_byte_equal_across_permutations() {
10220 // The canonical per-`:children` child-caixa `:nome`-scalar pin:
10221 // [`ChildSpec::nome`] must return the `:children :caixa` field
10222 // byte-for-byte across every DNS-1123-label value the upstream
10223 // [`crate::render::require_valid_dns_1123_label`] gate at
10224 // `SupervisorSpec::validate` admits. Peer of the sibling
10225 // `membro_nome_returns_caixa_byte_equal_across_permutations`
10226 // (4a32abf) pin on the M3 per-`:membros` axis — same "the
10227 // substrate-primitive accessor must byte-equal the raw field
10228 // access verbatim across every author-declared value" discipline
10229 // extended to the M2 supervisor-tree per-`:children` arm. Pins
10230 // against a future silent detour that re-normalized the child
10231 // identity (an accidental `.to_lowercase()` — every `:children
10232 // :caixa` is validated as a DNS-1123 label upstream, so any
10233 // re-normalization is redundant + a drift surface between the
10234 // validator and the accessor), a namespace-prefix rewrite (an
10235 // accidental `format!("{namespace}/{caixa}")` per-CR
10236 // fully-qualified rewrite that didn't land on the peer axes), or
10237 // a per-cluster alias stamp the future wasm-operator's
10238 // hierarchical reconciliation scheduler authors on one consumer
10239 // without the others. Five values sweep the accept-set the
10240 // DNS-1123 gate upstream admits (short single-word / dashed /
10241 // v-suffixed / mixed-digit child names).
10242 for name in [
10243 "worker",
10244 "cache-server",
10245 "scratch-job",
10246 "orders-v2",
10247 "session-8080",
10248 ] {
10249 let c = ChildSpec {
10250 caixa: name.into(),
10251 versao: "^0.1".into(),
10252 restart: RestartPolicy::Permanent,
10253 };
10254 assert_eq!(
10255 c.nome(),
10256 name,
10257 "ChildSpec::nome must return :children :caixa verbatim \
10258 (got {:?}, expected {name:?})",
10259 c.nome(),
10260 );
10261 assert_eq!(
10262 c.nome(),
10263 c.caixa.as_str(),
10264 "ChildSpec::nome must byte-equal the .caixa field access",
10265 );
10266 }
10267 }
10268
10269 #[test]
10270 fn child_spec_nome_borrows_from_caixa_storage() {
10271 // The borrow-not-copy pin: [`ChildSpec::nome`] must return a
10272 // `&str` slice that borrows from the typed slot's own [`String`]
10273 // storage — same-address invariant with `c.caixa.as_str()`. Pins
10274 // against a future silent detour that allocated a fresh `String`
10275 // (`self.caixa.clone()` in the body would type-check but silently
10276 // drop the borrow, and every downstream consumer that assumed
10277 // the returned slice outlives `&self` would break on a stale-
10278 // reference use-after-free — the [`crate::render::insert_first_seen`]
10279 // dedup key at [`SupervisorSpec::validate`], the
10280 // [`validate_no_self_supervision`] equality check against the
10281 // parent's `:nome` string slice, the DNS-1123 gate's `&str`
10282 // borrow — each would silently misbehave if this accessor
10283 // produced a detached copy). Peer of the sibling
10284 // `membro_nome_borrows_from_caixa_storage` (4a32abf) pin on the
10285 // M3 per-`:membros` axis and the
10286 // `prior_versao_borrows_from_from_storage` (75d27a8) pin on the
10287 // first M2 slot scalar accessor.
10288 let c = ChildSpec {
10289 caixa: "worker".into(),
10290 versao: "^0.1".into(),
10291 restart: RestartPolicy::Permanent,
10292 };
10293 let name = c.nome();
10294 let caixa_slice = c.caixa.as_str();
10295 assert_eq!(
10296 name.as_ptr(),
10297 caixa_slice.as_ptr(),
10298 "ChildSpec::nome must borrow from the .caixa String's backing \
10299 storage — a fresh allocation here means the accessor no \
10300 longer names the substrate-primitive typed dispatch and \
10301 every downstream consumer would silently carry a detached \
10302 copy",
10303 );
10304 assert_eq!(
10305 name.len(),
10306 caixa_slice.len(),
10307 "ChildSpec::nome and .caixa.as_str() must byte-equal in length \
10308 as well as in address",
10309 );
10310 }
10311
10312 #[test]
10313 fn validate_gates_child_nome_through_lifted_accessor() {
10314 // Bilateral coherence pin: every `:children :caixa` that
10315 // [`SupervisorSpec::validate`] accepts is one
10316 // [`crate::render::require_valid_dns_1123_label`] accepts on the
10317 // accessor-projected value, and vice versa on the reject side.
10318 // This closes the "the validator reads through the accessor"
10319 // contract structurally — a future silent detour that made the
10320 // accessor return a different byte-string than the validator
10321 // gates against would surface here as a coverage mismatch, not
10322 // as an apply-time DNS-1123 rejection at
10323 // `metadata.name: Invalid value` far from the caixa.lisp source.
10324 // Peer of the M2 sibling
10325 // `validate_parses_prior_versao_through_lifted_accessor`
10326 // (75d27a8) on the per-`:upgrade-from :from` axis and the M3
10327 // `validate_membros` peer discipline.
10328 //
10329 // Accept-set sweep: five DNS-1123-label values the upstream gate
10330 // admits.
10331 for ok_name in ["a", "worker", "cache-server", "orders-v2", "svc-8080"] {
10332 let s = SupervisorSpec {
10333 children: vec![ChildSpec {
10334 caixa: ok_name.into(),
10335 versao: "^0.1".into(),
10336 restart: RestartPolicy::Permanent,
10337 }],
10338 ..SupervisorSpec::default()
10339 };
10340 s.validate().unwrap_or_else(|e| {
10341 panic!(
10342 "SupervisorSpec::validate must accept :children :caixa {ok_name:?} \
10343 (upstream DNS-1123 gate accepts it): got {e:?}",
10344 );
10345 });
10346 let c = ChildSpec {
10347 caixa: ok_name.into(),
10348 versao: "^0.1".into(),
10349 restart: RestartPolicy::Permanent,
10350 };
10351 crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| ())
10352 .unwrap_or_else(|()| {
10353 panic!(
10354 "require_valid_dns_1123_label must accept the accessor-projected \
10355 :children :caixa {ok_name:?}",
10356 );
10357 });
10358 }
10359 // Reject-set sweep: five DNS-1123-label-violating shapes the
10360 // upstream gate refuses (empty / uppercase / underscore / dot /
10361 // leading-hyphen). Every rejection at the validator must
10362 // correspond to a rejection when the accessor's projected value
10363 // is fed back through the shared gate.
10364 for bad_name in ["", "Worker", "my_worker", "team.worker", "-worker"] {
10365 let s = SupervisorSpec {
10366 children: vec![ChildSpec {
10367 caixa: bad_name.into(),
10368 versao: "^0.1".into(),
10369 restart: RestartPolicy::Permanent,
10370 }],
10371 ..SupervisorSpec::default()
10372 };
10373 let err = s.validate().unwrap_err();
10374 assert!(
10375 matches!(
10376 err,
10377 SupervisorError::EmptyChildName | SupervisorError::ChildCaixaInvalid { .. }
10378 ),
10379 "SupervisorSpec::validate must reject :children :caixa {bad_name:?} \
10380 via the DNS-1123 gate: got {err:?}",
10381 );
10382 let c = ChildSpec {
10383 caixa: bad_name.into(),
10384 versao: "^0.1".into(),
10385 restart: RestartPolicy::Permanent,
10386 };
10387 assert!(
10388 crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| (),)
10389 .is_err(),
10390 "require_valid_dns_1123_label must reject the accessor-projected \
10391 :children :caixa {bad_name:?}",
10392 );
10393 }
10394 }
10395
10396 // ── drift-detection: ChildSpec::versao_requirement accessor pins ──────
10397 //
10398 // Sibling of the peer per-`:membros` `membro_versao_requirement_*`
10399 // (a40b0e3) pin pair on the M3 mesh-slot surface — extended here to the
10400 // M2 supervisor-tree per-`:children` child-`:versao` axis, sibling to
10401 // the just-landed [`ChildSpec::nome`] (57c61d0) child-`:nome` pin
10402 // trio on the peer per-`:children` `String`-carry axis. The three pins
10403 // jointly brace the accessor against every future silent detour that
10404 // would desynchronize it from the raw `.versao` field access the
10405 // requirement gate + error carrier previously open-coded.
10406 //
10407 // Closes the last unlifted per-`:children` `String`-carry axis: the
10408 // pair (`nome`, `versao_requirement`) now jointly projects the
10409 // (`.caixa`, `.versao`) field pair every OTP-shape supervisor-tree
10410 // consumer that fans on per-child identity + version pin reads,
10411 // matching the peer M3 (`Membro::nome`, `Membro::versao_requirement`)
10412 // pair discipline verbatim.
10413 #[test]
10414 fn child_spec_versao_requirement_returns_versao_byte_equal_across_permutations() {
10415 // The canonical per-`:children` child-`:versao`-scalar pin:
10416 // [`ChildSpec::versao_requirement`] must return the `:children
10417 // :versao` field byte-for-byte across every Cargo-shaped semver
10418 // requirement value the upstream
10419 // [`crate::render::require_valid_versao_requirement`] gate admits.
10420 // Peer of the sibling
10421 // `membro_versao_requirement_returns_versao_byte_equal_across_permutations`
10422 // (a40b0e3) pin on the M3 per-`:membros` axis — same "the
10423 // substrate-primitive accessor must byte-equal the raw field
10424 // access verbatim across every author-declared value" discipline
10425 // extended to the M2 supervisor-tree per-`:children` arm. Pins
10426 // against a future silent detour that re-canonicalized the
10427 // requirement (an accidental `.to_string()` via
10428 // [`crate::version::parse_requirement`] → [`std::fmt::Display`]
10429 // round-trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and
10430 // silently drifted the error carrier's quoted requirement away
10431 // from the source `caixa.lisp`, an accidental whitespace trim on
10432 // `"^ 0.1"` that no consumer ever produced from the field-access
10433 // side, an accidental per-cluster lacre-projected concrete-version
10434 // rewrite that didn't land on the peer requirement-gate call).
10435 // Five values sweep the accept-set the shared
10436 // [`crate::render::require_valid_versao_requirement`] gate admits
10437 // (caret / tilde / exact / wildcard / bare-major).
10438 for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
10439 let c = ChildSpec {
10440 caixa: "worker".into(),
10441 versao: req.into(),
10442 restart: RestartPolicy::Permanent,
10443 };
10444 assert_eq!(
10445 c.versao_requirement(),
10446 req,
10447 "ChildSpec::versao_requirement must return :children :versao \
10448 verbatim (got {:?}, expected {req:?})",
10449 c.versao_requirement(),
10450 );
10451 assert_eq!(
10452 c.versao_requirement(),
10453 c.versao.as_str(),
10454 "ChildSpec::versao_requirement must byte-equal the .versao \
10455 field access",
10456 );
10457 }
10458 }
10459
10460 #[test]
10461 fn child_spec_versao_requirement_borrows_from_versao_storage() {
10462 // The borrow-not-copy pin: [`ChildSpec::versao_requirement`] must
10463 // return a `&str` slice that borrows from the typed slot's own
10464 // [`String`] storage — same-address invariant with
10465 // `c.versao.as_str()`. Pins against a future silent detour that
10466 // allocated a fresh `String` (`self.versao.clone()` in the body
10467 // would type-check but silently drop the borrow, and every
10468 // downstream consumer that assumed the returned slice outlives
10469 // `&self` — the [`crate::render::require_valid_versao_requirement`]
10470 // gate's `&str` borrow, the [`SupervisorError::ChildVersaoInvalid`]
10471 // `.to_string()` carrier's byte-length assumption — would silently
10472 // misbehave if this accessor produced a detached copy). Peer of
10473 // the sibling `child_spec_nome_borrows_from_caixa_storage`
10474 // (57c61d0) pin on the per-`:children` `:nome` axis and the M3
10475 // `membro_versao_requirement_borrows_from_versao_storage` (a40b0e3)
10476 // pin on the peer per-`:membros` `:versao` axis.
10477 let c = ChildSpec {
10478 caixa: "worker".into(),
10479 versao: "^0.1".into(),
10480 restart: RestartPolicy::Permanent,
10481 };
10482 let req = c.versao_requirement();
10483 let versao_slice = c.versao.as_str();
10484 assert_eq!(
10485 req.as_ptr(),
10486 versao_slice.as_ptr(),
10487 "ChildSpec::versao_requirement must borrow from the .versao \
10488 String's backing storage — a fresh allocation here means the \
10489 accessor no longer names the substrate-primitive typed \
10490 dispatch and every downstream consumer would silently carry \
10491 a detached copy",
10492 );
10493 assert_eq!(
10494 req.len(),
10495 versao_slice.len(),
10496 "ChildSpec::versao_requirement and .versao.as_str() must \
10497 byte-equal in length as well as in address",
10498 );
10499 }
10500
10501 #[test]
10502 fn validate_gates_child_versao_through_lifted_accessor() {
10503 // Bilateral coherence pin: every `:children :versao` that
10504 // [`SupervisorSpec::validate`] accepts is one
10505 // [`crate::render::require_valid_versao_requirement`] accepts on
10506 // the accessor-projected value, and vice versa on the reject side.
10507 // This closes the "the validator reads through the accessor"
10508 // contract structurally — a future silent detour that made the
10509 // accessor return a different byte-string than the validator gates
10510 // against would surface here as a coverage mismatch, not as a
10511 // resolver-time semver-parse rejection at lacre-closure time far
10512 // from the caixa.lisp source. Peer of the sibling
10513 // `validate_gates_child_nome_through_lifted_accessor` (57c61d0) on
10514 // the per-`:children :caixa` axis and the M2
10515 // `validate_parses_prior_versao_through_lifted_accessor` (75d27a8)
10516 // on the peer per-`:upgrade-from :from` axis.
10517 //
10518 // Accept-set sweep: five Cargo-shaped semver requirement values
10519 // the upstream gate admits (caret / tilde / exact / wildcard /
10520 // bare-major).
10521 for ok_req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
10522 let s = SupervisorSpec {
10523 children: vec![ChildSpec {
10524 caixa: "worker".into(),
10525 versao: ok_req.into(),
10526 restart: RestartPolicy::Permanent,
10527 }],
10528 ..SupervisorSpec::default()
10529 };
10530 s.validate().unwrap_or_else(|e| {
10531 panic!(
10532 "SupervisorSpec::validate must accept :children :versao {ok_req:?} \
10533 (upstream versao-requirement gate accepts it): got {e:?}",
10534 );
10535 });
10536 let c = ChildSpec {
10537 caixa: "worker".into(),
10538 versao: ok_req.into(),
10539 restart: RestartPolicy::Permanent,
10540 };
10541 crate::render::require_valid_versao_requirement(
10542 c.versao_requirement(),
10543 || (),
10544 |_reason| (),
10545 )
10546 .unwrap_or_else(|()| {
10547 panic!(
10548 "require_valid_versao_requirement must accept the accessor-projected \
10549 :children :versao {ok_req:?}",
10550 );
10551 });
10552 }
10553 // Reject-set sweep: five requirement-violating shapes the upstream
10554 // gate refuses. The empty string closes the empty-first arm of the
10555 // shared [`crate::render::require_valid_versao_requirement`]
10556 // cascade; the four non-empty arms exercise distinct semver-parse
10557 // failure modes the M3 peer per-`:membros` reject-set already pins
10558 // (`rejects_invalid_membro_versao_requirement` on `^bad-version`,
10559 // `rejects_membro_versao_with_double_caret_typo` on `^^0.1`,
10560 // `rejects_membro_versao_with_v_prefixed_tag` on `v0.1`) — the
10561 // shared parser routing means the same reject-set must fail
10562 // identically at the M2 supervisor-tree per-`:children` accessor
10563 // arm here. Every rejection at the validator must correspond to a
10564 // rejection when the accessor's projected value is fed back
10565 // through the shared gate.
10566 //
10567 // (Bare partial magnitudes like `"0.1"` and bare identifiers like
10568 // `"not-a-semver"` are intentionally *not* in the reject-set: the
10569 // semver crate accepts `"0.1"` as an implicit `^0.1` requirement,
10570 // and the identifier-tail arm's grammar admits some non-canonical
10571 // shapes — matching what the M3 peer test suite already documents
10572 // as the shared parser's accept-set edges.)
10573 for bad_req in ["", "v0.1.0", "^bad-version", "^^0.1", "v0.1"] {
10574 let s = SupervisorSpec {
10575 children: vec![ChildSpec {
10576 caixa: "worker".into(),
10577 versao: bad_req.into(),
10578 restart: RestartPolicy::Permanent,
10579 }],
10580 ..SupervisorSpec::default()
10581 };
10582 let err = s.validate().unwrap_err();
10583 assert!(
10584 matches!(
10585 err,
10586 SupervisorError::EmptyChildVersion { .. }
10587 | SupervisorError::ChildVersaoInvalid { .. }
10588 ),
10589 "SupervisorSpec::validate must reject :children :versao {bad_req:?} \
10590 via the versao-requirement gate: got {err:?}",
10591 );
10592 let c = ChildSpec {
10593 caixa: "worker".into(),
10594 versao: bad_req.into(),
10595 restart: RestartPolicy::Permanent,
10596 };
10597 assert!(
10598 crate::render::require_valid_versao_requirement(
10599 c.versao_requirement(),
10600 || (),
10601 |_reason| (),
10602 )
10603 .is_err(),
10604 "require_valid_versao_requirement must reject the accessor-projected \
10605 :children :versao {bad_req:?}",
10606 );
10607 }
10608 }
10609
10610 // ── per-`:children` `:restart` typed-accessor coherence pins ──────────
10611 //
10612 // The [`ChildSpec::restart`] accessor lift closes the last unlifted
10613 // per-`:children` axis (the pair `nome()` + `versao_requirement()`
10614 // already project the `String`-carry `(caixa, versao)` fields; the
10615 // `Copy`-composite-enum `restart` field is the third and final axis).
10616 // Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
10617 // (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
10618 // scalar accessor and the M3 mesh-slot [`crate::Placement::estrategia`]
10619 // (921fe1b) `Copy`-return [`crate::PlacementStrategy`] distribution-
10620 // strategy scalar accessor — same "one typed dispatch on the substrate
10621 // primitive, `Copy`-projected closed-set enum-arm discriminator" shape
10622 // extended onto the M2 supervisor-slot per-`:children` restart-decision
10623 // axis. The pin below covers the accessor's byte-equal projection
10624 // against the raw field access across every variant in the closed
10625 // accept-set (`Permanent`, `Transient`, `Temporary`).
10626
10627 #[test]
10628 fn child_spec_restart_returns_restart_verbatim_across_permutations() {
10629 // The canonical per-`:children` restart-decision-policy-scalar
10630 // pin: [`ChildSpec::restart`] must return the `:children :restart`
10631 // field verbatim as a [`RestartPolicy`], `Copy`-projected from the
10632 // typed slot's own [`RestartPolicy`] storage across every variant
10633 // in the closed accept-set (`Permanent`, `Transient`, `Temporary`).
10634 // Pins against a future silent detour that re-derived the policy
10635 // from a peer axis (an accidental fallback to
10636 // `if is_supervisor_child { Permanent } else { Temporary }` that
10637 // collapsed the child's kind axis into the restart discriminator),
10638 // a variant remap the operator authors on one consumer without the
10639 // other, or a stale-derive detour that substituted
10640 // [`RestartPolicy::default`] when the field held any explicit
10641 // variant (which would silently collapse the distinction between
10642 // "author explicitly declared `:restart Permanent`" and "author
10643 // omitted the slot and inherited the default" the future
10644 // per-cluster restart-decision override slot depends on).
10645 //
10646 // Peer of the sibling per-`:supervisor`
10647 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
10648 // (eafb619) pin on the M2 supervisor-slot sibling-restart-strategy
10649 // axis and the M3
10650 // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
10651 // (921fe1b) pin on the per-`:placement` distribution-strategy axis
10652 // — same "the substrate-primitive accessor must byte-equal the raw
10653 // field access verbatim across every author-declared value"
10654 // discipline extended onto the M2 supervisor-slot per-`:children`
10655 // restart-decision-policy axis, closing the last unlifted axis on
10656 // the per-`:children` [`ChildSpec`] type.
10657 for restart in [
10658 RestartPolicy::Permanent,
10659 RestartPolicy::Transient,
10660 RestartPolicy::Temporary,
10661 ] {
10662 let c = ChildSpec {
10663 caixa: "worker".into(),
10664 versao: "^0.1".into(),
10665 restart,
10666 };
10667 assert_eq!(
10668 c.restart(),
10669 restart,
10670 "ChildSpec::restart must return :children :restart \
10671 verbatim (got {:?}, expected {restart:?})",
10672 c.restart(),
10673 );
10674 assert_eq!(
10675 c.restart(),
10676 c.restart,
10677 "ChildSpec::restart accessor and .restart field access \
10678 must byte-equal — the accessor is the substrate-primitive \
10679 typed dispatch every downstream per-child restart-\
10680 decision consumer must route through",
10681 );
10682 }
10683 }
10684
10685 // ── per-`:supervisor` `:estrategia` typed-accessor coherence pins ─────
10686 //
10687 // The [`SupervisorSpec::estrategia`] accessor lift extends the peer M3
10688 // [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
10689 // distribution-strategy accessor discipline onto the M2 supervisor-slot
10690 // per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
10691 // scalar axis. The two pins below cover (1) the accessor's byte-equal
10692 // projection against the raw field access across every variant in the
10693 // closed accept-set, and (2) the two-consumer coherence between the
10694 // [`SupervisorSpec::validate`] partition-dispatch `match` arm and the
10695 // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
10696 // carrier's `estrategia:` field — peer of the sibling M3
10697 // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
10698 // / `validate_placement_reads_through_lifted_estrategia_accessor` pin
10699 // pair on the per-`:placement` distribution-strategy axis.
10700
10701 #[test]
10702 fn supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations() {
10703 // The canonical per-`:supervisor` sibling-restart-strategy-scalar
10704 // pin: [`SupervisorSpec::estrategia`] must return the
10705 // `:supervisor :estrategia` field verbatim as a
10706 // [`RestartStrategy`], `Copy`-projected from the typed slot's own
10707 // [`RestartStrategy`] storage across every variant in the closed
10708 // accept-set (`OneForOne`, `OneForAll`, `RestForOne`,
10709 // `SimpleOneForOne`). Pins against a future silent detour that
10710 // re-derived the strategy from a peer axis (an accidental
10711 // fallback to `if children.is_empty() { SimpleOneForOne } else {
10712 // OneForOne }` collapse that read the children-count axis into
10713 // the strategy discriminator), a variant remap the operator
10714 // authors on one consumer without the other, or a stale-derive
10715 // detour that substituted [`RestartStrategy::default`] when the
10716 // field held any explicit variant (which would silently collapse
10717 // the distinction between "author explicitly declared
10718 // `:estrategia OneForOne`" and "author omitted the slot and
10719 // inherited the default" the future per-cluster strategy override
10720 // slot depends on). Peer of the sibling M3
10721 // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
10722 // (921fe1b) pin on the M3 mesh-slot `Copy`-composite-enum scalar
10723 // axis — same "the substrate-primitive accessor must byte-equal
10724 // the raw field access verbatim across every author-declared
10725 // value" discipline extended onto the M2 supervisor-slot
10726 // per-`:supervisor` sibling-restart-strategy axis.
10727 for &estrategia in RestartStrategy::ALL {
10728 // `SimpleOneForOne` requires `children.is_empty()`; the peer
10729 // three strategies require a non-empty static children list.
10730 // Build each shape coherently so the pin's fixture would
10731 // itself pass [`SupervisorSpec::validate`] once fed through
10732 // the sibling coherence pin below — the byte-equal projection
10733 // asserted here is a strictly weaker property (a `Copy` field
10734 // read) that does not depend on `validate` running, but
10735 // keeping the fixture validate-clean means a future extension
10736 // of the pin to exercise `validate` end-to-end does not have
10737 // to re-author the children shape.
10738 //
10739 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
10740 // shape partition through the [`gen_platform::IsVariant`]
10741 // derive-generated
10742 // [`RestartStrategy::is_simple_one_for_one`] predicate rather
10743 // than the raw `matches!(estrategia, RestartStrategy::
10744 // SimpleOneForOne)` open-coded pattern-match — same closed-
10745 // set-typed-enum arm-discriminator dispatch discipline the
10746 // sibling [`crate::upgrade::UpgradeInstruction::is_restart`]
10747 // convergence (915a934) extended onto its two paired positive
10748 // / negated `matches!` sites and the peer
10749 // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
10750 // predicate convergence (766ec63) extended onto the M3 mesh-
10751 // slot per-`:placement` distribution-strategy discriminator
10752 // axis. See the sibling `round_trip_all_strategies` and the
10753 // peer `manifest::tests::
10754 // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
10755 // fixture for the two peer sites the same lift closes on.
10756 let children = if estrategia.is_simple_one_for_one() {
10757 Vec::new()
10758 } else {
10759 vec![ChildSpec {
10760 caixa: "worker".into(),
10761 versao: "^0.1".into(),
10762 restart: RestartPolicy::Permanent,
10763 }]
10764 };
10765 let s = SupervisorSpec {
10766 estrategia,
10767 children,
10768 ..SupervisorSpec::default()
10769 };
10770 assert_eq!(
10771 s.estrategia(),
10772 estrategia,
10773 "SupervisorSpec::estrategia must return :supervisor :estrategia \
10774 verbatim (got {:?}, expected {estrategia:?})",
10775 s.estrategia(),
10776 );
10777 assert_eq!(
10778 s.estrategia(),
10779 s.estrategia,
10780 "SupervisorSpec::estrategia accessor and .estrategia field \
10781 access must byte-equal — the accessor is the substrate-\
10782 primitive typed dispatch every downstream sibling-restart-\
10783 strategy consumer must route through",
10784 );
10785 }
10786 }
10787
10788 #[test]
10789 fn validate_reads_through_lifted_estrategia_accessor() {
10790 // Two-consumer coherence pin: the [`SupervisorSpec::validate`]
10791 // `SimpleOneForOne ↔ non-SimpleOneForOne` `match` partition
10792 // dispatch (which reads through [`SupervisorSpec::estrategia`]
10793 // to fan across the strategy-arm shape-gate cascades) and the
10794 // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
10795 // error carrier's `estrategia:` field (which reads through
10796 // [`SupervisorSpec::estrategia`] to name the strategy the empty
10797 // `:children` list was declared against) must both key off the
10798 // lifted accessor, so any future rebrand on the typed slot's
10799 // reader shape lands at exactly one place. Pins the two-site
10800 // coherence by exercising the `NoChildren` error surface end-to-
10801 // end across every non-`SimpleOneForOne` variant and asserting
10802 // the surfaced `estrategia:` field byte-equals the accessor's
10803 // return. Peer of the sibling M3
10804 // `validate_placement_reads_through_lifted_estrategia_accessor`
10805 // (921fe1b) three-consumer coherence pin on the per-`:placement`
10806 // distribution-strategy axis.
10807 for estrategia in [
10808 RestartStrategy::OneForOne,
10809 RestartStrategy::OneForAll,
10810 RestartStrategy::RestForOne,
10811 ] {
10812 let s = SupervisorSpec {
10813 estrategia,
10814 children: Vec::new(),
10815 ..SupervisorSpec::default()
10816 };
10817 let err = s.validate().unwrap_err();
10818 match err {
10819 SupervisorError::NoChildren { estrategia: e } => {
10820 assert_eq!(
10821 e,
10822 s.estrategia(),
10823 "NoChildren.estrategia must byte-equal \
10824 SupervisorSpec::estrategia() — the empty-`:children` \
10825 refusal reads through the lifted accessor",
10826 );
10827 assert_eq!(
10828 e, estrategia,
10829 "NoChildren.estrategia must carry the author-declared \
10830 :supervisor :estrategia variant verbatim (got {e:?}, \
10831 expected {estrategia:?})",
10832 );
10833 }
10834 other => panic!("expected NoChildren, got {other:?} for estrategia={estrategia:?}"),
10835 }
10836 }
10837 }
10838
10839 // ── per-`:supervisor` `:max-restarts` typed-accessor coherence pins ────
10840 //
10841 // The [`SupervisorSpec::max_restarts`] accessor lift extends the peer M3
10842 // [`crate::CircuitBreaker::max_failures`] (3a74062) `Copy`-return
10843 // required-`u32` scalar accessor discipline onto the M2 supervisor-slot
10844 // per-`:supervisor` restart-budget-count `Copy`-`u32` scalar axis.
10845 // The two pins below cover (1) the accessor's byte-equal projection
10846 // against the raw field access across every representative value in
10847 // the `u32` accept-set (`1` lower boundary, `SUPERVISOR_MAX_RESTARTS_MAX`
10848 // upper boundary, `0` past-the-guard zero sentinel, `u32::MAX`
10849 // past-the-guard cap sentinel), and (2) the [`SupervisorSpec::validate`]
10850 // zero-floor / cap composition — the validate gate and the accessor
10851 // must route through the same substrate-primitive typed dispatch, so
10852 // any future silent detour that had the accessor perform a
10853 // bounds-collapsing clamp would fail here at caixa-core build time.
10854 // Peer of the sibling M3
10855 // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
10856 // (3a74062) pin on the per-`CircuitBreaker :max-failures` axis.
10857
10858 #[test]
10859 fn supervisor_spec_max_restarts_returns_max_restarts_u32_byte_equal_across_permutations() {
10860 // The canonical per-`:supervisor` restart-budget-count scalar pin:
10861 // [`SupervisorSpec::max_restarts`] must return the `:supervisor
10862 // :max-restarts` typed `u32` verbatim, `Copy`-projected from the
10863 // typed slot's own `u32` storage, byte-equal to the raw field
10864 // access across every representative value in the accept-set —
10865 // `1` (the lower boundary of the `1..=SUPERVISOR_MAX_RESTARTS_MAX`
10866 // accept-set the surrounding [`SupervisorSpec::validate`] gate
10867 // carves out on the sibling `ZeroMaxRestarts` refusal),
10868 // `SUPERVISOR_MAX_RESTARTS_MAX` (the upper boundary the same gate
10869 // carves out on the sibling `MaxRestartsExceedsCap` refusal), `0`
10870 // (a past-the-guard sentinel that pins the accessor doesn't
10871 // perform a silent bounds-collapse into `1` on the zero arm —
10872 // validate rejects zero but the accessor must ship the raw slot
10873 // verbatim so a validate-time gate regression surfaces at the
10874 // emit boundary rather than being silently absorbed), `u32::MAX`
10875 // (a past-the-guard sentinel that pins the accessor doesn't
10876 // perform a silent bounds-collapse through
10877 // `SUPERVISOR_MAX_RESTARTS_MAX` at the return path).
10878 //
10879 // Peer of the sibling M3
10880 // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
10881 // (3a74062) pin on the M3 mesh-slot `Copy`-`u32` sub-struct
10882 // required-scalar axis — same "the substrate-primitive accessor
10883 // must byte-equal the raw field access verbatim across every
10884 // value in the `u32` accept-set" discipline extended onto the M2
10885 // supervisor-slot per-`:supervisor` restart-budget-count axis.
10886 for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX, 0, u32::MAX] {
10887 let s = SupervisorSpec {
10888 max_restarts,
10889 ..SupervisorSpec::default()
10890 };
10891 assert_eq!(
10892 s.max_restarts(),
10893 max_restarts,
10894 "SupervisorSpec::max_restarts must return :supervisor \
10895 :max-restarts verbatim (got {}, expected {max_restarts})",
10896 s.max_restarts(),
10897 );
10898 assert_eq!(
10899 s.max_restarts(),
10900 s.max_restarts,
10901 "SupervisorSpec::max_restarts accessor and .max_restarts \
10902 field access must byte-equal — the accessor is the \
10903 substrate-primitive typed dispatch every downstream \
10904 restart-budget-count consumer must route through",
10905 );
10906 }
10907 }
10908
10909 #[test]
10910 fn validate_max_restarts_zero_floor_and_cap_arms_route_through_accessor() {
10911 // Composition pin: [`SupervisorSpec::validate`]'s `:max-restarts`
10912 // zero-floor + upper-cap bracket must key off
10913 // [`SupervisorSpec::max_restarts`], not the raw `.max_restarts`
10914 // field access. Structurally: a `SupervisorSpec { max_restarts:
10915 // 0, .. }` must surface the `ZeroMaxRestarts` refusal exactly, a
10916 // `SupervisorSpec { max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
10917 // .. }` must surface the `MaxRestartsExceedsCap` refusal exactly
10918 // (with the offending count carried verbatim from the accessor
10919 // return), and a `SupervisorSpec { max_restarts: 1, .. }` (the
10920 // lower boundary of the accept-set) plus a `SupervisorSpec {
10921 // max_restarts: SUPERVISOR_MAX_RESTARTS_MAX, .. }` (the upper
10922 // boundary) must pass validate. The four together jointly pin the
10923 // accessor + validate-gate composition: any future silent detour
10924 // that had the accessor return a fresh `1` on the zero arm (a
10925 // `.max_restarts().max(1)` collapse) would silently absorb the
10926 // `ZeroMaxRestarts` refusal at the accessor boundary and the
10927 // validate gate would accept a struct-literal `SupervisorSpec {
10928 // max_restarts: 0, .. }` — the composition pin catches that at
10929 // caixa-core build time.
10930 //
10931 // Peer of the sibling M3
10932 // `validate_politicas_max_failures_zero_floor_arm_routes_through_accessor`
10933 // (3a74062) pin on the sibling per-`CircuitBreaker :max-failures`
10934 // composition axis — same "the validate / shape-gate predicate
10935 // must route through the substrate-primitive typed dispatch"
10936 // discipline extended onto the peer M2 supervisor-slot
10937 // required-`u32` composition axis.
10938 let child = ChildSpec {
10939 caixa: "worker".into(),
10940 versao: "^0.1".into(),
10941 restart: RestartPolicy::Permanent,
10942 };
10943 // Zero-floor arm.
10944 let s = SupervisorSpec {
10945 max_restarts: 0,
10946 children: vec![child.clone()],
10947 ..SupervisorSpec::default()
10948 };
10949 assert_eq!(
10950 s.validate().unwrap_err(),
10951 SupervisorError::ZeroMaxRestarts,
10952 "validate must reject max_restarts == 0 with ZeroMaxRestarts \
10953 — the accessor and the validate gate must route through the \
10954 same substrate-primitive typed dispatch on the zero-floor arm",
10955 );
10956 // Cap arm — the surfaced `max_restarts:` field must byte-equal
10957 // the accessor's return so a future rebrand on the accessor
10958 // lands in the diagnostic without a coordinated rewrite.
10959 let over_cap = SUPERVISOR_MAX_RESTARTS_MAX + 1;
10960 let s = SupervisorSpec {
10961 max_restarts: over_cap,
10962 children: vec![child.clone()],
10963 ..SupervisorSpec::default()
10964 };
10965 match s.validate().unwrap_err() {
10966 SupervisorError::MaxRestartsExceedsCap { max_restarts } => {
10967 assert_eq!(
10968 max_restarts,
10969 s.max_restarts(),
10970 "MaxRestartsExceedsCap.max_restarts must byte-equal \
10971 SupervisorSpec::max_restarts() — the cap-arm refusal \
10972 reads through the lifted accessor",
10973 );
10974 assert_eq!(
10975 max_restarts, over_cap,
10976 "MaxRestartsExceedsCap.max_restarts must carry the \
10977 author-declared :supervisor :max-restarts value \
10978 verbatim (got {max_restarts}, expected {over_cap})",
10979 );
10980 }
10981 other => panic!("expected MaxRestartsExceedsCap, got {other:?}"),
10982 }
10983 // Lower + upper accept-set boundaries.
10984 for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX] {
10985 let s = SupervisorSpec {
10986 max_restarts,
10987 children: vec![child.clone()],
10988 ..SupervisorSpec::default()
10989 };
10990 assert!(
10991 s.validate().is_ok(),
10992 "validate must accept max_restarts == {max_restarts} \
10993 (an accept-set boundary of \
10994 1..=SUPERVISOR_MAX_RESTARTS_MAX)",
10995 );
10996 }
10997 }
10998
10999 // ── per-`:supervisor` `:restart-window` typed-accessor coherence pins ─
11000 //
11001 // The [`SupervisorSpec::restart_window`] accessor lift extends the peer
11002 // M2 [`crate::LimitsSpec::wall_clock`] (8cb717b) `Option<Duration>`
11003 // accessor discipline and the peer M3 [`crate::MeshPolicy::timeout`]
11004 // (7073d0f) `Option<Duration>` accessor discipline onto the M2
11005 // supervisor-slot per-`:supervisor` restart-intensity-denominator
11006 // `Option<Duration>` scalar axis — third `Copy`-return accessor on the
11007 // M2 supervisor-slot `SupervisorSpec` type, closing the last unlifted
11008 // per-`:supervisor` scalar-value axis. The three pins below cover
11009 // (1) the accessor's byte-equal projection against the raw field
11010 // access across every representative value in the `Option<Duration>`
11011 // accept-set (`None` never-reset sentinel, `Some(Duration::from_millis(1))`
11012 // lower boundary, `Some(SUPERVISOR_RESTART_WINDOW_MAX)` upper boundary,
11013 // `Some(Duration::ZERO)` past-the-guard zero sentinel, `Some(Duration::MAX)`
11014 // past-the-guard above-cap sentinel), (2) the [`SupervisorSpec::validate`]
11015 // `if let Some(w) = self.restart_window() { … }` bracket-arm
11016 // composition — the validate gate and the accessor must route through
11017 // the same substrate-primitive typed dispatch, so any future silent
11018 // detour that had the accessor perform a bounds-collapsing clamp
11019 // would fail here at caixa-core build time, and (3) the accessor's
11020 // by-copy idempotence pin — the returned `Option<Duration>` must
11021 // outlive `&self` and two successive calls must return byte-equal
11022 // values. Peer of the sibling M2
11023 // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
11024 // (8cb717b) pin on the per-`:limits :wall-clock` axis and the sibling
11025 // M3 `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
11026 // (7073d0f) pin on the per-`:politicas :timeout` axis.
11027
11028 #[test]
11029 fn supervisor_spec_restart_window_returns_option_duration_byte_equal_across_permutations() {
11030 // The canonical per-`:supervisor` restart-intensity-denominator
11031 // scalar pin: [`SupervisorSpec::restart_window`] must return the
11032 // `:supervisor :restart-window` typed [`Duration`] verbatim as an
11033 // `Option<Duration>`, `Copy`-projected from the typed slot's own
11034 // `Option<Duration>` storage, byte-equal to the raw field access
11035 // across every representative value in the accept-set — `None`
11036 // (the "never reset — every restart across the supervisor's
11037 // lifetime counts against the sibling `:max-restarts` budget"
11038 // sentinel the field's own docstring names and the peer
11039 // `validate_accepts_none_restart_window` pin locks in on the
11040 // [`SupervisorSpec::validate`] entry-side),
11041 // `Some(Duration::from_millis(1))` (the structural minimum a
11042 // validated `:restart-window` may carry, the integer-millisecond
11043 // floor [`SupervisorError::RestartWindowNotCanonical`] rejects
11044 // everything sub-ms; `Duration::ZERO` is separately rejected by
11045 // [`SupervisorError::RestartWindowZero`]),
11046 // `Some(SUPERVISOR_RESTART_WINDOW_MAX)` (the upper boundary the
11047 // surrounding [`SupervisorSpec::validate`] gate carves out on the
11048 // sibling [`SupervisorError::RestartWindowExceedsCap`] refusal),
11049 // `Some(Duration::ZERO)` (a past-the-guard sentinel that pins the
11050 // accessor doesn't perform a silent bounds-collapse into `None` on
11051 // the zero-Duration arm — validate rejects zero but the accessor
11052 // must ship the raw slot verbatim so a validate-time gate
11053 // regression surfaces at the emit boundary rather than being
11054 // silently absorbed), and `Some(Duration::MAX)` (a past-the-guard
11055 // sentinel that pins the accessor doesn't perform a silent
11056 // bounds-collapse through [`SUPERVISOR_RESTART_WINDOW_MAX`] at the
11057 // return path).
11058 //
11059 // Peer of the sibling M2
11060 // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
11061 // (8cb717b) pin on the per-`:limits :wall-clock` axis and the
11062 // sibling M3
11063 // `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
11064 // (7073d0f) pin on the per-`:politicas :timeout` axis — same "the
11065 // substrate-primitive accessor must byte-equal the raw field
11066 // access verbatim across every value in the `Option<Duration>`
11067 // accept-set" discipline extended onto the M2 supervisor-slot
11068 // per-`:supervisor` `Option<Duration>` axis. Pins against a future
11069 // silent detour that re-derived the restart-window from a peer
11070 // axis (an accidental `.max_restarts.into()` collapse that read
11071 // the restart-budget-count as a duration — the two axes serve
11072 // different halves of the `MaxIntensity / Period` restart-
11073 // intensity ratio, and confusing them silently inverts the
11074 // ratio's numerator and denominator), a `None → Some(Duration::ZERO)`
11075 // "zero means never reset" collapse (the canonical
11076 // `Option<Duration>` → `Duration` collapse footgun the
11077 // [`SupervisorError::RestartWindowZero`] validate arm guards on
11078 // the peer zero-floor axis; a zero period either trips on the
11079 // first failure or never trips depending on operator
11080 // interpretation, neither of which is the author's "never reset"
11081 // intent that `None` expresses structurally), or a per-arm
11082 // variant swap that landed on one consumer without the other.
11083 for restart_window in [
11084 None,
11085 Some(Duration::from_millis(1)),
11086 Some(SUPERVISOR_RESTART_WINDOW_MAX),
11087 Some(Duration::ZERO),
11088 Some(Duration::MAX),
11089 ] {
11090 let s = SupervisorSpec {
11091 restart_window,
11092 ..SupervisorSpec::default()
11093 };
11094 assert_eq!(
11095 s.restart_window(),
11096 restart_window,
11097 "SupervisorSpec::restart_window must return :supervisor \
11098 :restart-window verbatim (got {:?}, expected {restart_window:?})",
11099 s.restart_window(),
11100 );
11101 assert_eq!(
11102 s.restart_window(),
11103 s.restart_window,
11104 "SupervisorSpec::restart_window accessor and \
11105 .restart_window field access must byte-equal — the \
11106 accessor is the substrate-primitive typed dispatch every \
11107 downstream restart-intensity-denominator consumer must \
11108 route through",
11109 );
11110 }
11111 }
11112
11113 #[test]
11114 fn validate_restart_window_bracket_arm_routes_through_accessor() {
11115 // Composition pin: [`SupervisorSpec::validate`]'s
11116 // `:restart-window` `if let Some(w) = self.restart_window() { … }`
11117 // zero-floor + integer-millisecond canonical-form + upper-cap
11118 // bracket-arm must key off [`SupervisorSpec::restart_window`], not
11119 // the raw `.restart_window` field access. Structurally: a
11120 // `SupervisorSpec { restart_window: None, .. }` must pass the
11121 // arm gate structurally (the `if let Some(_)` shape returns
11122 // early on the `None` arm — the accessor and the validate gate
11123 // must agree on `None → skip the bracket cascade` so an authored
11124 // `:restart-window ()` structurally routes through the "never
11125 // reset" sentinel path), a `SupervisorSpec { restart_window:
11126 // Some(Duration::ZERO), .. }` must surface the `RestartWindowZero`
11127 // refusal exactly, a `SupervisorSpec { restart_window:
11128 // Some(Duration::from_micros(1500)), .. }` must surface the
11129 // `RestartWindowNotCanonical` refusal exactly (with the offending
11130 // duration carried verbatim from the accessor return), a
11131 // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX
11132 // + Duration::from_millis(1)), .. }` must surface the
11133 // `RestartWindowExceedsCap` refusal exactly (with the offending
11134 // duration carried verbatim from the accessor return), and a
11135 // `SupervisorSpec { restart_window: Some(Duration::from_millis(1)),
11136 // .. }` (the lower boundary of the accept-set) plus a
11137 // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
11138 // .. }` (the upper boundary) must pass validate. The six together
11139 // jointly pin the accessor + validate-gate composition: any future
11140 // silent detour that had the accessor return a fresh `None` on any
11141 // `Some` arm (a `.restart_window().filter(|w| !w.is_zero())`
11142 // collapse) would silently absorb the `RestartWindowZero` refusal
11143 // at the accessor boundary and the validate gate would accept a
11144 // struct-literal `SupervisorSpec { restart_window:
11145 // Some(Duration::ZERO), .. }` — the composition pin catches that
11146 // at caixa-core build time.
11147 //
11148 // Peer of the sibling M2 [`crate::LimitsSpec::wall_clock`]
11149 // (8cb717b) validate-arm-route pin on the per-`:limits :wall-clock`
11150 // axis and the peer M3 [`crate::MeshPolicy::timeout`] (7073d0f)
11151 // accessor-composition pin on the per-`:politicas :timeout` axis —
11152 // same "the validate / shape-gate predicate must route through
11153 // the substrate-primitive typed dispatch" discipline extended
11154 // onto the peer M2 supervisor-slot optional-`Duration` axis.
11155 let child = ChildSpec {
11156 caixa: "worker".into(),
11157 versao: "^0.1".into(),
11158 restart: RestartPolicy::Permanent,
11159 };
11160 // None arm — must not surface any :restart-window-shaped refusal;
11161 // the `if let Some(_)` bracket returns early on `None` structurally.
11162 let s = SupervisorSpec {
11163 restart_window: None,
11164 children: vec![child.clone()],
11165 ..SupervisorSpec::default()
11166 };
11167 assert!(
11168 s.validate().is_ok(),
11169 "validate must accept restart_window: None (the never-reset \
11170 sentinel) — the `if let Some(_)` bracket returns early on \
11171 the None arm and the accessor must agree",
11172 );
11173 // Zero-floor arm.
11174 let s = SupervisorSpec {
11175 restart_window: Some(Duration::ZERO),
11176 children: vec![child.clone()],
11177 ..SupervisorSpec::default()
11178 };
11179 assert_eq!(
11180 s.validate().unwrap_err(),
11181 SupervisorError::RestartWindowZero,
11182 "validate must reject restart_window == Some(Duration::ZERO) \
11183 with RestartWindowZero — the accessor and the validate gate \
11184 must route through the same substrate-primitive typed \
11185 dispatch on the zero-floor arm",
11186 );
11187 // Non-canonical (sub-ms) arm — the surfaced `window:` field must
11188 // byte-equal the accessor's return so a future rebrand on the
11189 // accessor lands in the diagnostic without a coordinated rewrite.
11190 let sub_ms = Duration::from_micros(1500);
11191 let s = SupervisorSpec {
11192 restart_window: Some(sub_ms),
11193 children: vec![child.clone()],
11194 ..SupervisorSpec::default()
11195 };
11196 match s.validate().unwrap_err() {
11197 SupervisorError::RestartWindowNotCanonical { window } => {
11198 assert_eq!(
11199 Some(window),
11200 s.restart_window(),
11201 "RestartWindowNotCanonical.window must byte-equal \
11202 SupervisorSpec::restart_window().unwrap() — the \
11203 non-canonical-arm refusal reads through the lifted \
11204 accessor",
11205 );
11206 assert_eq!(
11207 window, sub_ms,
11208 "RestartWindowNotCanonical.window must carry the \
11209 author-declared :supervisor :restart-window value \
11210 verbatim (got {window:?}, expected {sub_ms:?})",
11211 );
11212 }
11213 other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
11214 }
11215 // Cap arm — the surfaced `window:` field must byte-equal the
11216 // accessor's return.
11217 let over_cap = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
11218 let s = SupervisorSpec {
11219 restart_window: Some(over_cap),
11220 children: vec![child.clone()],
11221 ..SupervisorSpec::default()
11222 };
11223 match s.validate().unwrap_err() {
11224 SupervisorError::RestartWindowExceedsCap { window } => {
11225 assert_eq!(
11226 Some(window),
11227 s.restart_window(),
11228 "RestartWindowExceedsCap.window must byte-equal \
11229 SupervisorSpec::restart_window().unwrap() — the \
11230 cap-arm refusal reads through the lifted accessor",
11231 );
11232 assert_eq!(
11233 window, over_cap,
11234 "RestartWindowExceedsCap.window must carry the \
11235 author-declared :supervisor :restart-window value \
11236 verbatim (got {window:?}, expected {over_cap:?})",
11237 );
11238 }
11239 other => panic!("expected RestartWindowExceedsCap, got {other:?}"),
11240 }
11241 // Lower + upper accept-set boundaries.
11242 for restart_window in [Duration::from_millis(1), SUPERVISOR_RESTART_WINDOW_MAX] {
11243 let s = SupervisorSpec {
11244 restart_window: Some(restart_window),
11245 children: vec![child.clone()],
11246 ..SupervisorSpec::default()
11247 };
11248 assert!(
11249 s.validate().is_ok(),
11250 "validate must accept restart_window == Some({restart_window:?}) \
11251 (an accept-set boundary of \
11252 1ms..=SUPERVISOR_RESTART_WINDOW_MAX)",
11253 );
11254 }
11255 }
11256
11257 #[test]
11258 fn supervisor_spec_restart_window_projects_option_duration_by_copy() {
11259 // The by-copy pin: [`SupervisorSpec::restart_window`] returns
11260 // `Option<Duration>` by copy — `Duration` is `Copy` (so
11261 // `Option<Duration>` is `Copy`) and the accessor must return by
11262 // value, not by reference. Peer of the sibling M2
11263 // [`crate::LimitsSpec::wall_clock`] (8cb717b) by-copy pin on the
11264 // per-`:limits :wall-clock` axis and the sibling M3
11265 // [`crate::MeshPolicy::timeout`] (7073d0f) by-copy pin on the
11266 // per-`:politicas :timeout` axis, extended onto the peer M2
11267 // supervisor-slot `Option<Duration>` copy-invariant shape — the
11268 // accessor's returned `Option<Duration>` must outlive `&self`
11269 // (multiple calls must return equal values from a dropped-`&self`
11270 // copy, since the returned Option carries no borrow), and calling
11271 // the accessor twice on the same SupervisorSpec must yield the
11272 // same `Option<Duration>` verbatim (idempotent, no side effects
11273 // on `&self`).
11274 //
11275 // Pins against a future silent detour that returned
11276 // `Option<&Duration>` (which would type-check but silently break
11277 // every downstream caller — the future wasm-operator's
11278 // per-supervisor restart-intensity counter consumes `Duration` by
11279 // value and `&Duration` would fold to a detached copy at the call
11280 // site), an accidental `Option::as_ref()` projection
11281 // (`self.restart_window.as_ref()` would also type-check but
11282 // return `Option<&Duration>`), or a one-arm-only accessor that
11283 // reads `Some(*w)` in the Some arm but reads a fresh
11284 // `Default::default()` (which would collapse to `Duration::ZERO`,
11285 // not `None`) in the None arm — a footgun the
11286 // [`SupervisorError::RestartWindowZero`] validate arm explicitly
11287 // closes since Erlang/OTP's `MaxIntensity / Period` invariant
11288 // requires `Period > 0` and `None` structurally expresses "never
11289 // reset" instead.
11290 for restart_window in [
11291 None,
11292 Some(Duration::from_millis(1)),
11293 Some(Duration::from_secs(60)),
11294 Some(SUPERVISOR_RESTART_WINDOW_MAX),
11295 ] {
11296 let s = SupervisorSpec {
11297 restart_window,
11298 ..SupervisorSpec::default()
11299 };
11300 let first = s.restart_window();
11301 let second = s.restart_window();
11302 assert_eq!(
11303 first, second,
11304 "SupervisorSpec::restart_window must be idempotent — two \
11305 successive calls on the same &self must return the \
11306 same Option<Duration>",
11307 );
11308 assert_eq!(
11309 first, restart_window,
11310 "SupervisorSpec::restart_window must return :supervisor \
11311 :restart-window verbatim by copy — got {first:?}, \
11312 expected {restart_window:?}",
11313 );
11314 }
11315 }
11316
11317 // ── per-`:supervisor` `:children` typed-accessor coherence pins ─────────
11318 //
11319 // The [`SupervisorSpec::children`] accessor lift is the seed of the
11320 // slice-return (`&[T]`) accessor discipline on the substrate — the four
11321 // peer `Vec`-carry axes ([`crate::Placement::clusters`],
11322 // [`crate::AplicacaoSpec::membros`], [`crate::AplicacaoSpec::contratos`],
11323 // [`crate::UpgradeFromEntry::instructions`]) still key off the raw field
11324 // access at the time of this seed, and inherit this pin family's
11325 // discipline as future compounding runs migrate their consumers. The
11326 // three pins below cover (1) the accessor's byte-equal projection
11327 // against the raw field access across the empty / singleton / cohort
11328 // fixtures the [`SupervisorSpec::validate`] partition-dispatch fans
11329 // between, (2) the [`SupervisorSpec::validate`] `SimpleOneForOne ↔
11330 // non-SimpleOneForOne` partition dispatch's paired `.is_empty()`
11331 // consumer routing through the accessor on both arms, and (3) the
11332 // per-child validate loop's traversal reading the same slice-view the
11333 // accessor projects. Peer of the sibling M2
11334 // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
11335 // two-consumer coherence pin on the per-`:supervisor`
11336 // sibling-restart-strategy `Copy`-composite-enum scalar axis, extended
11337 // onto the per-`:supervisor` static-child-list `Vec`-carry axis.
11338
11339 #[test]
11340 fn supervisor_spec_children_returns_children_slice_byte_equal_across_permutations() {
11341 // The canonical per-`:supervisor` static-child-list scalar-shape
11342 // pin: [`SupervisorSpec::children`] must return the `:supervisor
11343 // :children` typed `Vec<ChildSpec>` verbatim as a `&[ChildSpec]`
11344 // slice-view over the same backing buffer the raw
11345 // `self.children.as_slice()` field access borrows from, byte-
11346 // equal across every representative fixture in the accept-set —
11347 // the empty slice (the `SimpleOneForOne`-arm sentinel),
11348 // the singleton slice (the minimal non-`SimpleOneForOne` shape),
11349 // and a two-child cohort (a peer non-`SimpleOneForOne` shape
11350 // with the peer three restart-policy variants in play).
11351 //
11352 // Pins against a future silent detour that returned
11353 // `&Vec<ChildSpec>` (which would type-check but leak the
11354 // storage-side `Vec`'s grow/push/reserve surface no consumer of
11355 // the typed view reaches for), a fresh-allocated
11356 // `Vec<ChildSpec>` copy (which would type-check via a coercion
11357 // but silently break every downstream caller that relied on the
11358 // slice sharing the backing buffer's identity), or an
11359 // out-of-order or length-drifted projection (which would silently
11360 // split the per-child validate loop's traversal input from the
11361 // paired partition-dispatch `.is_empty()` probe's input).
11362 //
11363 // Peer of the sibling
11364 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
11365 // (eafb619) `Copy`-composite-enum byte-equal pin on the
11366 // per-`:supervisor` sibling-restart-strategy axis, extended onto
11367 // the per-`:supervisor` static-child-list `Vec`-carry axis.
11368 let fixtures: Vec<Vec<ChildSpec>> = vec![
11369 Vec::new(),
11370 vec![child("worker", "^0.1", RestartPolicy::Permanent)],
11371 vec![
11372 child("worker", "^0.1", RestartPolicy::Permanent),
11373 child("cache-server", "^0.1", RestartPolicy::Transient),
11374 ],
11375 vec![
11376 child("worker", "^0.1", RestartPolicy::Permanent),
11377 child("cache-server", "^0.1", RestartPolicy::Transient),
11378 child("scratch-job", "^0.1", RestartPolicy::Temporary),
11379 ],
11380 ];
11381 for children in fixtures {
11382 let s = SupervisorSpec {
11383 children: children.clone(),
11384 ..SupervisorSpec::default()
11385 };
11386 assert_eq!(
11387 s.children(),
11388 children.as_slice(),
11389 "SupervisorSpec::children must return :supervisor \
11390 :children verbatim (got {:?}, expected {:?})",
11391 s.children(),
11392 children.as_slice(),
11393 );
11394 assert_eq!(
11395 s.children(),
11396 s.children.as_slice(),
11397 "SupervisorSpec::children accessor and \
11398 .children.as_slice() field access must byte-equal — \
11399 the accessor is the substrate-primitive typed \
11400 dispatch every downstream static-child-list consumer \
11401 must route through",
11402 );
11403 assert_eq!(
11404 s.children().len(),
11405 s.children.len(),
11406 "SupervisorSpec::children().len() must byte-equal \
11407 self.children.len() — a length-drift would silently \
11408 split the paired partition-dispatch `.is_empty()` \
11409 probe input from the per-child validate loop's \
11410 traversal input",
11411 );
11412 }
11413 }
11414
11415 #[test]
11416 fn validate_reads_through_lifted_children_accessor() {
11417 // Three-consumer coherence pin: the [`SupervisorSpec::validate`]
11418 // `SimpleOneForOne`-arm `!self.children().is_empty()` refusal
11419 // probe (which must trip [`SupervisorError::SimpleOneForOneWithStaticChildren`]
11420 // when the accessor projects a non-empty slice under a
11421 // `SimpleOneForOne` estrategia), the peer non-`SimpleOneForOne`-arm
11422 // `self.children().is_empty()` refusal probe (which must trip
11423 // [`SupervisorError::NoChildren`] when the accessor projects the
11424 // empty slice under any peer estrategia), and the per-child
11425 // validate loop's `for child in self.children()` traversal
11426 // (which must reach every entry in the same order the accessor
11427 // projects) must all key off the lifted accessor, so any future
11428 // rebrand on the typed slot's reader shape lands at exactly one
11429 // place. Pins the three-site coherence by exercising each
11430 // production consumer end-to-end: (1) the
11431 // `SimpleOneForOneWithStaticChildren` refusal under a non-empty
11432 // slice + `SimpleOneForOne` estrategia, (2) the `NoChildren`
11433 // refusal under the empty slice + non-`SimpleOneForOne`
11434 // estrategia across every peer variant, and (3) the per-child
11435 // duplicate-detection surface fires on the second entry of a
11436 // two-child cohort that shares a `:caixa` name (which requires
11437 // the loop to reach both entries — a first-entry-only projection
11438 // would silently pass since the dedup HashSet has room for the
11439 // first insert).
11440 //
11441 // Peer of the sibling M2
11442 // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
11443 // two-consumer coherence pin on the per-`:supervisor`
11444 // sibling-restart-strategy axis, extended onto the
11445 // per-`:supervisor` static-child-list `Vec`-carry axis.
11446
11447 // (1) `SimpleOneForOne`-arm probe: a non-empty slice under a
11448 // `SimpleOneForOne` estrategia must trip
11449 // `SimpleOneForOneWithStaticChildren`.
11450 let s = SupervisorSpec {
11451 estrategia: RestartStrategy::SimpleOneForOne,
11452 children: vec![child("worker", "^0.1", RestartPolicy::Permanent)],
11453 ..SupervisorSpec::default()
11454 };
11455 assert_eq!(
11456 s.validate().unwrap_err(),
11457 SupervisorError::SimpleOneForOneWithStaticChildren,
11458 "SimpleOneForOne + non-empty children must trip \
11459 SimpleOneForOneWithStaticChildren — the accessor projects \
11460 a non-empty slice, and the SimpleOneForOne-arm refusal \
11461 probe reads through the lifted accessor",
11462 );
11463 assert!(
11464 !s.children().is_empty(),
11465 "the SimpleOneForOne-arm refusal input must be a non-empty \
11466 slice per the accessor's projection",
11467 );
11468
11469 // (2) Peer non-`SimpleOneForOne`-arm probe: the empty slice
11470 // under any peer estrategia must trip `NoChildren`.
11471 for estrategia in [
11472 RestartStrategy::OneForOne,
11473 RestartStrategy::OneForAll,
11474 RestartStrategy::RestForOne,
11475 ] {
11476 let s = SupervisorSpec {
11477 estrategia,
11478 children: Vec::new(),
11479 ..SupervisorSpec::default()
11480 };
11481 match s.validate().unwrap_err() {
11482 SupervisorError::NoChildren { estrategia: e } => {
11483 assert_eq!(
11484 e, estrategia,
11485 "NoChildren.estrategia must carry the author-\
11486 declared :supervisor :estrategia variant \
11487 verbatim (got {e:?}, expected {estrategia:?})",
11488 );
11489 }
11490 other => panic!(
11491 "expected NoChildren, got {other:?} for \
11492 estrategia={estrategia:?}"
11493 ),
11494 }
11495 assert!(
11496 s.children().is_empty(),
11497 "the non-SimpleOneForOne-arm refusal input must be the \
11498 empty slice per the accessor's projection",
11499 );
11500 }
11501
11502 // (3) Per-child validate loop: a two-child cohort that shares a
11503 // `:caixa` name must trip `DuplicateChildCaixa` — the loop must
11504 // reach both entries through the accessor.
11505 let s = SupervisorSpec {
11506 estrategia: RestartStrategy::OneForOne,
11507 children: vec![
11508 child("worker", "^0.1", RestartPolicy::Permanent),
11509 child("worker", "^0.2", RestartPolicy::Transient),
11510 ],
11511 ..SupervisorSpec::default()
11512 };
11513 match s.validate().unwrap_err() {
11514 SupervisorError::DuplicateChildCaixa { caixa } => {
11515 assert_eq!(
11516 caixa, "worker",
11517 "DuplicateChildCaixa.caixa must carry the shared \
11518 child `:caixa` name verbatim",
11519 );
11520 }
11521 other => panic!("expected DuplicateChildCaixa, got {other:?}"),
11522 }
11523 assert_eq!(
11524 s.children().len(),
11525 2,
11526 "the per-child validate loop's traversal input must be a \
11527 two-element slice per the accessor's projection",
11528 );
11529 }
11530
11531 // Shared helper for the M2 per-`:children` per-slot-gate ≡
11532 // `validate` equivalence pins: builds an `OneForOne`-estrategia
11533 // one-cohort spec whose peer `:estrategia`↔`:children.is_empty()`
11534 // partition, `:max-restarts` zero-floor/cap, and `:restart-window`
11535 // bracket all pass cleanly so the sole failing surface is the
11536 // per-child cascade [`SupervisorSpec::validate_children`] owns, and
11537 // pins the two-altitude equivalence on the paired probe.
11538 fn assert_validate_children_matches_gate(children: Vec<ChildSpec>, expected: &SupervisorError) {
11539 let s = SupervisorSpec {
11540 estrategia: RestartStrategy::OneForOne,
11541 children,
11542 ..SupervisorSpec::default()
11543 };
11544 let via_gate = s.validate_children().unwrap_err();
11545 let via_validate = s.validate().unwrap_err();
11546 assert_eq!(&via_gate, expected, "validate_children direct dispatch",);
11547 assert_eq!(&via_validate, expected, "validate() end-to-end dispatch",);
11548 assert_eq!(
11549 via_gate, via_validate,
11550 "per-slot gate ≡ validate() must discriminate the same \
11551 refusal shape",
11552 );
11553 }
11554
11555 #[test]
11556 fn validate_children_matches_gate_on_per_axis_refusal_shapes() {
11557 // Fail-before-pass-after equivalence pin on the M2
11558 // per-`:children` per-slot gate ≡ [`SupervisorSpec::validate`]
11559 // convergence — sibling of the M3 mesh-slot
11560 // `validate_membros_*` / `validate_contratos_*` /
11561 // `validate_entrada_*` per-slot-gate ≡ `validate` pins on the
11562 // peer per-entry axes. Sweeps four of the five refusal shapes
11563 // the per-slot gate owns: (1) `EmptyChildName` on an empty-
11564 // `:caixa` child, (2) `ChildCaixaInvalid` on a structurally
11565 // invalid `:caixa` DNS-1123 label, (3) `EmptyChildVersion` on
11566 // an empty-`:versao` child, (4) `DuplicateChildCaixa` on a
11567 // duplicate-`:caixa` fan-out. Companion pin
11568 // `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
11569 // covers `ChildVersaoInvalid` (whose parser-owned reason string
11570 // needs pattern-matching, not equality) and the clean-pass
11571 // canonical fixture; together the two pins guarantee the
11572 // per-slot gate and `validate` discriminate the same set on
11573 // every per-child-covered input.
11574 assert_validate_children_matches_gate(
11575 vec![child("", "^0.1", RestartPolicy::Permanent)],
11576 &SupervisorError::EmptyChildName,
11577 );
11578 assert_validate_children_matches_gate(
11579 vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
11580 &SupervisorError::ChildCaixaInvalid {
11581 caixa: "Worker".into(),
11582 reason: "contains uppercase character 'W' (K8s DNS-1123 label names are lowercase-only; use \"worker\")".into(),
11583 },
11584 );
11585 assert_validate_children_matches_gate(
11586 vec![child("worker", "", RestartPolicy::Permanent)],
11587 &SupervisorError::EmptyChildVersion {
11588 caixa: "worker".into(),
11589 },
11590 );
11591 assert_validate_children_matches_gate(
11592 vec![
11593 child("worker", "^0.1", RestartPolicy::Permanent),
11594 child("worker", "^0.2", RestartPolicy::Transient),
11595 ],
11596 &SupervisorError::DuplicateChildCaixa {
11597 caixa: "worker".into(),
11598 },
11599 );
11600 }
11601
11602 #[test]
11603 fn validate_children_matches_gate_on_versao_invalid_and_clean_pass() {
11604 // Second half of the two-altitude equivalence pin — covers the
11605 // one refusal shape whose reason string is parser-owned
11606 // (`ChildVersaoInvalid`, whose reason comes from the shared
11607 // [`crate::version::parse_requirement`] impl and may drift) and
11608 // the clean-pass canonical fixture. Sibling pin
11609 // `validate_children_matches_gate_on_per_axis_refusal_shapes`
11610 // covers the four equality-comparable refusal shapes.
11611 let s_bad_versao = SupervisorSpec {
11612 estrategia: RestartStrategy::OneForOne,
11613 children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
11614 ..SupervisorSpec::default()
11615 };
11616 let via_gate = s_bad_versao.validate_children().unwrap_err();
11617 let via_validate = s_bad_versao.validate().unwrap_err();
11618 match (&via_gate, &via_validate) {
11619 (
11620 SupervisorError::ChildVersaoInvalid {
11621 caixa: cg,
11622 versao: vg,
11623 ..
11624 },
11625 SupervisorError::ChildVersaoInvalid {
11626 caixa: cv,
11627 versao: vv,
11628 ..
11629 },
11630 ) => {
11631 assert_eq!(cg, "worker", "per-slot gate :caixa carrier");
11632 assert_eq!(vg, "not-a-req", "per-slot gate :versao carrier");
11633 assert_eq!(cv, "worker", "validate() :caixa carrier");
11634 assert_eq!(vv, "not-a-req", "validate() :versao carrier");
11635 }
11636 other => panic!("expected ChildVersaoInvalid on both altitudes, got {other:?}"),
11637 }
11638 assert_eq!(
11639 via_gate, via_validate,
11640 "per-slot gate ≡ validate() on ChildVersaoInvalid full envelope",
11641 );
11642
11643 let s_ok = SupervisorSpec {
11644 estrategia: RestartStrategy::OneForOne,
11645 children: vec![
11646 child("worker-a", "^0.1", RestartPolicy::Permanent),
11647 child("worker-b", "~0.2.3", RestartPolicy::Transient),
11648 child("collector", "*", RestartPolicy::Temporary),
11649 ],
11650 ..SupervisorSpec::default()
11651 };
11652 s_ok.validate_children()
11653 .expect("per-slot gate must accept the clean-pass fixture");
11654 s_ok.validate()
11655 .expect("validate() must accept the clean-pass fixture");
11656 }
11657
11658 #[test]
11659 fn validate_children_is_self_contained_on_children_slot() {
11660 // Self-containment pin: [`SupervisorSpec::validate_children`]
11661 // resolves the per-child cascade against `&self` alone, without
11662 // depending on the peer `:estrategia`/`:max-restarts`/
11663 // `:restart-window` gates having run first — same posture the M3
11664 // peer per-slot gates carry (`validate_membros`,
11665 // `validate_contratos`, `validate_entrada`, `validate_placement`,
11666 // routing through their own oracles rather than borrowing state
11667 // threaded down from `validate`). A future consumer that reaches
11668 // the per-slot gate directly on a spec whose peer slots would
11669 // fail `validate` still surfaces the per-child refusal, not the
11670 // peer refusal.
11671 //
11672 // Construct a spec whose `:max-restarts` is `0` (which would
11673 // trip [`SupervisorError::ZeroMaxRestarts`] at `validate` after
11674 // the partition-dispatch) and whose `:children` carries a
11675 // `DuplicateChildCaixa` shape: the per-slot gate called directly
11676 // must surface `DuplicateChildCaixa`, proving it does not depend
11677 // on the peer `:max-restarts` gate running first.
11678 let s = SupervisorSpec {
11679 estrategia: RestartStrategy::OneForOne,
11680 max_restarts: 0,
11681 restart_window: Some(Duration::from_secs(60)),
11682 children: vec![
11683 child("worker", "^0.1", RestartPolicy::Permanent),
11684 child("worker", "^0.2", RestartPolicy::Transient),
11685 ],
11686 };
11687 assert_eq!(
11688 s.validate_children().unwrap_err(),
11689 SupervisorError::DuplicateChildCaixa {
11690 caixa: "worker".into(),
11691 },
11692 "per-slot gate must resolve per-child refusal directly against \
11693 `&self` — a dependency on the peer `:max-restarts` gate \
11694 running first would surface ZeroMaxRestarts here instead",
11695 );
11696 // The peer gate is still the surface `validate` reaches — pin
11697 // the ordering to establish that `validate_children` truly runs
11698 // last in `validate`'s dispatch, so a direct call bypasses the
11699 // peer gates on any spec whose per-child cascade would fail.
11700 assert_eq!(
11701 s.validate().unwrap_err(),
11702 SupervisorError::ZeroMaxRestarts,
11703 "validate() must surface the peer `:max-restarts` gate before \
11704 reaching the per-child cascade — this pins the dispatch \
11705 ordering the per-slot gate's self-containment complements",
11706 );
11707 }
11708
11709 #[test]
11710 fn child_spec_restart_accessor_is_const_fn() {
11711 // The [`ChildSpec::restart`] per-`:children` restart-decision-
11712 // policy `Copy`-return scalar accessor is declared
11713 // `#[must_use] pub const fn` — matching the sibling M2
11714 // per-`:supervisor` [`SupervisorSpec::estrategia`] (pinned by
11715 // [`supervisor_spec_estrategia_accessor_is_const_fn`] below,
11716 // both converted in this commit), the sibling M2
11717 // per-`:supervisor` [`SupervisorSpec::max_restarts`] (b698ec0)
11718 // `Copy`-`u32` accessor already `pub const fn`, and the peer M3
11719 // mesh-slot per-`:entrada` [`crate::Entrada::port`] (bafa004) /
11720 // per-`:placement` [`crate::Placement::estrategia`] (bafa004)
11721 // `Copy`-return `pub const fn` scalar accessors on the sibling
11722 // M3 surface. Pin the `const`-eval posture here so a future
11723 // accidental downgrade to non-`const` (an added runtime helper
11724 // reachable only from a non-`const` context, an
11725 // `Option<RestartPolicy>`-shape migration on the per-child
11726 // restart-decision axis once heterogeneous per-cluster
11727 // restart-policy overlays land that would silently drop the
11728 // `const` qualifier, a manual hand-rolled shadow) trips at
11729 // caixa-core build time rather than surfacing as a downstream
11730 // `const`-context regression far from the declaration.
11731 //
11732 // Same shape as the sibling M3
11733 // [`crate::aplicacao::tests::placement_estrategia_accessor_is_const_fn`]
11734 // and [`crate::aplicacao::tests::entrada_port_accessor_is_const_fn`]
11735 // (bafa004) pins on the peer M3 mesh-slot `Copy`-return scalar
11736 // accessor axis — the load-bearing witness lives in the
11737 // module-scope `const fn` wrapper `restart_via_const_fn` below:
11738 // a body that calls [`ChildSpec::restart`] under a `const fn`
11739 // signature is well-formed only when the callee is itself
11740 // `const fn`, so any future accidental downgrade of
11741 // [`ChildSpec::restart`] to non-`const` fails at caixa-core
11742 // build time (const-eval E0015 `cannot call non-const method`),
11743 // strictly stronger than a runtime `assert!(CONST)` and
11744 // side-stepping the destructor-in-const restriction that
11745 // blocks direct `const _: RestartPolicy = FIXTURE.restart()`
11746 // items on `ChildSpec`'s `String` carriers.
11747 //
11748 // The runtime body sweeps every closed-set [`RestartPolicy`]
11749 // arm and asserts the wrapped and direct dispatches agree.
11750 const fn restart_via_const_fn(c: &ChildSpec) -> RestartPolicy {
11751 c.restart()
11752 }
11753 for restart in [
11754 RestartPolicy::Permanent,
11755 RestartPolicy::Transient,
11756 RestartPolicy::Temporary,
11757 ] {
11758 let c = ChildSpec {
11759 caixa: "worker".into(),
11760 versao: "^0.1".into(),
11761 restart,
11762 };
11763 assert_eq!(
11764 restart_via_const_fn(&c),
11765 c.restart(),
11766 "const-fn-wrapped and direct dispatch on \
11767 ChildSpec::restart must agree for {restart:?}",
11768 );
11769 assert_eq!(
11770 c.restart(),
11771 restart,
11772 "ChildSpec::restart must return the storage-side \
11773 RestartPolicy verbatim for {restart:?} (a violation \
11774 means the accessor stopped being a raw field-return \
11775 copy)",
11776 );
11777 }
11778 }
11779
11780 #[test]
11781 fn supervisor_spec_estrategia_accessor_is_const_fn() {
11782 // The [`SupervisorSpec::estrategia`] per-`:supervisor`
11783 // sibling-restart-strategy `Copy`-return scalar accessor is
11784 // declared `#[must_use] pub const fn` — matching the sibling M2
11785 // per-`:children` [`ChildSpec::restart`] (pinned by
11786 // [`child_spec_restart_accessor_is_const_fn`] above, both
11787 // converted in this commit), the sibling M2 per-`:supervisor`
11788 // [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32`
11789 // accessor already `pub const fn`, and mirroring the peer M3
11790 // mesh-slot per-`:placement`
11791 // [`crate::Placement::estrategia`] (bafa004) `Copy`-return
11792 // `pub const fn` scalar accessor whose method-name discipline
11793 // the [`SupervisorSpec::estrategia`] method was authored to
11794 // match. Pin the `const`-eval posture here so a future
11795 // accidental downgrade to non-`const` (an added runtime helper
11796 // reachable only from a non-`const` context, an
11797 // `Option<RestartStrategy>`-shape migration once the substrate
11798 // grows per-cluster strategy overlays that would silently drop
11799 // the `const` qualifier, a manual hand-rolled shadow) trips at
11800 // caixa-core build time rather than surfacing as a downstream
11801 // `const`-context regression far from the declaration.
11802 //
11803 // Same shape as the sibling
11804 // [`child_spec_restart_accessor_is_const_fn`] pin above — the
11805 // load-bearing witness lives in the module-scope `const fn`
11806 // wrapper `estrategia_via_const_fn` below: a body that calls
11807 // [`SupervisorSpec::estrategia`] under a `const fn` signature
11808 // is well-formed only when the callee is itself `const fn`,
11809 // side-stepping the destructor-in-const restriction that would
11810 // otherwise block a direct
11811 // `const _: RestartStrategy = FIXTURE.estrategia()` item on
11812 // `SupervisorSpec`'s `Vec<ChildSpec>` / `Option<Duration>`
11813 // carriers.
11814 //
11815 // The runtime body sweeps every closed-set [`RestartStrategy`]
11816 // arm via [`RestartStrategy::ALL`] and asserts the wrapped and
11817 // direct dispatches agree.
11818 const fn estrategia_via_const_fn(s: &SupervisorSpec) -> RestartStrategy {
11819 s.estrategia()
11820 }
11821 for &estrategia in RestartStrategy::ALL {
11822 let s = SupervisorSpec {
11823 estrategia,
11824 max_restarts: 5,
11825 restart_window: Some(Duration::from_secs(60)),
11826 children: Vec::new(),
11827 };
11828 assert_eq!(
11829 estrategia_via_const_fn(&s),
11830 s.estrategia(),
11831 "const-fn-wrapped and direct dispatch on \
11832 SupervisorSpec::estrategia must agree for {estrategia:?}",
11833 );
11834 assert_eq!(
11835 s.estrategia(),
11836 estrategia,
11837 "SupervisorSpec::estrategia must return the storage-side \
11838 RestartStrategy verbatim for {estrategia:?} (a violation \
11839 means the accessor stopped being a raw field-return \
11840 copy)",
11841 );
11842 }
11843 }
11844
11845 // Per-variant equivalence pins for the [`supervisor_caixa_only_ctors!`]
11846 // macro definition (see the paired doc-block above the macro
11847 // definition) — every generated `<ctor>(caixa: &str) -> Self`
11848 // constructor folds the uniform `Self::<Variant> { caixa:
11849 // caixa.to_string() }` one-field struct-literal onto one substrate
11850 // primitive. The three per-variant equivalence pins below
11851 // (fail-before-pass-after by construction — a byte-mismatched macro
11852 // arm would trip its equivalence pin first) lock each generated
11853 // constructor to its struct-literal peer under `PartialEq`, so
11854 // every wire-up in [`SupervisorSpec::validate_children`] and
11855 // [`validate_no_self_supervision`] on that variant produces a
11856 // byte-equal `SupervisorError` to the pre-lift open-coded
11857 // struct-literal. The cross-axis pin that follows (non-default
11858 // caixa name) routes the sole constructor input axis through
11859 // `.to_string()`, so the fold does not silently collapse onto a
11860 // fixed name.
11861 //
11862 // Peer of the sibling `<slot>_ctor_matches_tuple_literal_wrap` /
11863 // `<slot>_violation_ctor_matches_struct_literal_wrap` /
11864 // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
11865 // `missing_entry_ctor_matches_struct_literal_wrap` /
11866 // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
11867 // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
11868 // `contrato_missing_target_ctor_matches_struct_literal_wrap` /
11869 // `<variant>_ctor_matches_struct_literal_wrap` equivalence pins
11870 // on the six sibling ctor families the recent trajectory closed
11871 // on the peer `LayoutError` / `AplicacaoError` envelopes.
11872
11873 #[test]
11874 fn empty_child_version_ctor_matches_struct_literal_wrap() {
11875 assert_eq!(
11876 SupervisorError::empty_child_version("worker"),
11877 SupervisorError::EmptyChildVersion {
11878 caixa: "worker".to_string(),
11879 },
11880 "generated empty_child_version ctor must produce byte-equal \
11881 SupervisorError to the open-coded struct-literal wrap on the \
11882 same &str fixture",
11883 );
11884 }
11885
11886 #[test]
11887 fn duplicate_child_caixa_ctor_matches_struct_literal_wrap() {
11888 assert_eq!(
11889 SupervisorError::duplicate_child_caixa("worker"),
11890 SupervisorError::DuplicateChildCaixa {
11891 caixa: "worker".to_string(),
11892 },
11893 "generated duplicate_child_caixa ctor must produce byte-equal \
11894 SupervisorError to the open-coded struct-literal wrap on the \
11895 same &str fixture",
11896 );
11897 }
11898
11899 #[test]
11900 fn child_supervises_self_ctor_matches_struct_literal_wrap() {
11901 assert_eq!(
11902 SupervisorError::child_supervises_self("orquestra"),
11903 SupervisorError::ChildSupervisesSelf {
11904 caixa: "orquestra".to_string(),
11905 },
11906 "generated child_supervises_self ctor must produce byte-equal \
11907 SupervisorError to the open-coded struct-literal wrap on the \
11908 same &str fixture",
11909 );
11910 }
11911
11912 // Per-variant equivalence pins for the two lifted
11913 // [`SupervisorError::child_caixa_invalid`] /
11914 // [`SupervisorError::child_versao_invalid`] inherent constructors
11915 // (fail-before-pass-after by construction — a byte-mismatched ctor body
11916 // would trip its equivalence pin first). Each pins the ctor output to
11917 // its pre-lift struct-literal peer under `PartialEq`, so every wire-up
11918 // in [`SupervisorSpec::validate_children`] on the two variants
11919 // produces a byte-equal `SupervisorError` to the pre-lift open-coded
11920 // struct-literal on the same scalar fixtures. Peers of the sibling
11921 // `membro_caixa_invalid_ctor_matches_struct_literal_wrap` /
11922 // `entrada_para_invalid_ctor_matches_struct_literal_wrap` / … pins on
11923 // the peer `AplicacaoError` envelope's
11924 // [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold.
11925
11926 #[test]
11927 fn child_caixa_invalid_ctor_matches_struct_literal_wrap() {
11928 let caixa = "Worker";
11929 let reason = "sample reason text";
11930 assert_eq!(
11931 SupervisorError::child_caixa_invalid(caixa, reason),
11932 SupervisorError::ChildCaixaInvalid {
11933 caixa: caixa.to_string(),
11934 reason: reason.to_string(),
11935 },
11936 "lifted child_caixa_invalid ctor must produce byte-equal \
11937 SupervisorError to the open-coded struct-literal wrap on the \
11938 same (&str, reason) fixture",
11939 );
11940 }
11941
11942 #[test]
11943 fn child_versao_invalid_ctor_matches_struct_literal_wrap() {
11944 let caixa = "worker";
11945 let versao = "not-a-req";
11946 let reason = "sample reason text";
11947 assert_eq!(
11948 SupervisorError::child_versao_invalid(caixa, versao, reason),
11949 SupervisorError::ChildVersaoInvalid {
11950 caixa: caixa.to_string(),
11951 versao: versao.to_string(),
11952 reason: reason.to_string(),
11953 },
11954 "lifted child_versao_invalid ctor must produce byte-equal \
11955 SupervisorError to the open-coded struct-literal wrap on the \
11956 same (&str, &str, reason) fixture",
11957 );
11958 }
11959
11960 #[test]
11961 fn supervisor_child_reason_ctors_route_reason_through_into_uniformly() {
11962 // Cross-axis pin: sweep the two lifted `{ …, reason }` ctors
11963 // against a `&str`-literal vs. `format!(…)` reason input to pin
11964 // both constructors accept the `impl Into<String>` bound
11965 // uniformly, so neither wire-up site drifts under a per-arm
11966 // wrapper transformation on the caller-side `reason` axis. Peer
11967 // of the sibling
11968 // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
11969 // sweep on the peer `AplicacaoError` envelope.
11970 let via_literal = "literal reason text";
11971 let via_format = format!("{} reason text", "literal");
11972 assert_eq!(
11973 SupervisorError::child_caixa_invalid("Worker", via_literal),
11974 SupervisorError::child_caixa_invalid("Worker", via_format.clone()),
11975 );
11976 assert_eq!(
11977 SupervisorError::child_versao_invalid("worker", "not-a-req", via_literal),
11978 SupervisorError::child_versao_invalid("worker", "not-a-req", via_format),
11979 );
11980 }
11981
11982 #[test]
11983 fn supervisor_caixa_only_ctors_route_caixa_through_to_string() {
11984 // Cross-axis pin: sweep the sole constructor input axis (`caixa:
11985 // &str`) through a non-default fixture name against every
11986 // generated arm in the [`supervisor_caixa_only_ctors!`] macro,
11987 // so any wrapper-side lowercase / trim / truncate / re-order on
11988 // the `caixa.to_string()` sole-field construction surfaces
11989 // here rather than at a downstream diagnostic-shape mismatch.
11990 // Peer of the sibling `nome_only_ctor_routes_caixa_through_
11991 // nome_accessor` / `entrada_host_invalid_ctor_routes_host_
11992 // through_to_string` / `contrato_target_ctors_route_edge_
11993 // triple_through_verbatim` / `contrato_empty_pair_ctors_
11994 // route_edge_pair_through_verbatim` cross-axis routing pins on
11995 // the peer `LayoutError` / `AplicacaoError` envelopes; extended
11996 // here onto the `SupervisorError` `{ caixa: String }` envelope
11997 // so every substrate-primitive ctor family in caixa-core
11998 // guarantees the sole-field construction routes the caller's
11999 // `&str` through `.to_string()` verbatim.
12000 let name = "cache-v2";
12001 assert_eq!(
12002 SupervisorError::empty_child_version(name),
12003 SupervisorError::EmptyChildVersion {
12004 caixa: name.to_string(),
12005 },
12006 );
12007 assert_eq!(
12008 SupervisorError::duplicate_child_caixa(name),
12009 SupervisorError::DuplicateChildCaixa {
12010 caixa: name.to_string(),
12011 },
12012 );
12013 assert_eq!(
12014 SupervisorError::child_supervises_self(name),
12015 SupervisorError::ChildSupervisesSelf {
12016 caixa: name.to_string(),
12017 },
12018 );
12019 }
12020
12021 // ── supervisor_scalar_ctors! per-variant + cross-axis pins ──────────────
12022 //
12023 // Per-variant byte-equality pins guaranteeing every generated ctor arm in
12024 // the [`supervisor_scalar_ctors!`] macro produces a `SupervisorError`
12025 // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
12026 // one-line struct-literal on the same `Copy`-`RestartStrategy | u32 |
12027 // Duration` fixture, plus one cross-axis sweep that routes each per-variant
12028 // `<field>: <ty>` scalar through the sole `$field:ident: $ty:ty` axis the
12029 // macro exposes so any wrapper-side truncation / re-order / silent `.into()`
12030 // / silent constant-substitution on any one variant surfaces here rather
12031 // than at a downstream per-`:supervisor` diagnostic-shape drift. Peer of the
12032 // sibling per-variant pins on `aplicacao_policy_scalar_ctors!` (7ef425e,
12033 // the 8-variant `AplicacaoError` `{ <field>: Duration | u32 }` fold on the
12034 // per-`:politicas` per-axis cap / canonical-form arms), plus the sibling
12035 // `supervisor_caixa_only_ctors!` (db09650), `SupervisorError::
12036 // {child_caixa_invalid,child_versao_invalid}` (d2ef2ec), and the peer
12037 // `DepError` / `AplicacaoError` / `LayoutError` / `LimitsError` /
12038 // `BehaviorError` / `UpgradeError` per-envelope ctor-macro pins.
12039 #[test]
12040 fn no_children_ctor_matches_struct_literal_wrap() {
12041 let estrategia = RestartStrategy::OneForAll;
12042 assert_eq!(
12043 SupervisorError::no_children(estrategia),
12044 SupervisorError::NoChildren { estrategia },
12045 "generated no_children ctor must produce byte-equal \
12046 `SupervisorError::NoChildren` to the pre-lift struct-literal wrap \
12047 on the same `Copy`-`RestartStrategy` fixture",
12048 );
12049 }
12050
12051 #[test]
12052 fn max_restarts_exceeds_cap_ctor_matches_struct_literal_wrap() {
12053 let max_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 1;
12054 assert_eq!(
12055 SupervisorError::max_restarts_exceeds_cap(max_restarts),
12056 SupervisorError::MaxRestartsExceedsCap { max_restarts },
12057 "generated max_restarts_exceeds_cap ctor must produce byte-equal \
12058 `SupervisorError::MaxRestartsExceedsCap` to the pre-lift \
12059 struct-literal wrap on the same `Copy`-`u32` fixture",
12060 );
12061 }
12062
12063 #[test]
12064 fn restart_window_not_canonical_ctor_matches_struct_literal_wrap() {
12065 let window = Duration::from_micros(1_500);
12066 assert_eq!(
12067 SupervisorError::restart_window_not_canonical(window),
12068 SupervisorError::RestartWindowNotCanonical { window },
12069 "generated restart_window_not_canonical ctor must produce \
12070 byte-equal `SupervisorError::RestartWindowNotCanonical` to the \
12071 pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
12072 );
12073 }
12074
12075 #[test]
12076 fn restart_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
12077 let window = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
12078 assert_eq!(
12079 SupervisorError::restart_window_exceeds_cap(window),
12080 SupervisorError::RestartWindowExceedsCap { window },
12081 "generated restart_window_exceeds_cap ctor must produce \
12082 byte-equal `SupervisorError::RestartWindowExceedsCap` to the \
12083 pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
12084 );
12085 }
12086
12087 #[test]
12088 fn supervisor_scalar_ctors_route_field_through_copy_uniformly() {
12089 // Cross-axis routing pin: sweep each generated `<field>: <ty>`
12090 // constructor input axis through a non-default `Copy` fixture against
12091 // every arm in the [`supervisor_scalar_ctors!`] macro, so any wrapper-
12092 // side silent `.into()` / silent constant-substitution / silent field
12093 // re-name away from the canonical `estrategia | max_restarts | window`
12094 // axes on any one variant, or a `RestartStrategy | u32 | Duration`
12095 // axis silently rerouted through some other `Copy` coercion, surfaces
12096 // here rather than at a downstream per-`:supervisor` diagnostic-shape
12097 // drift. Peer of the sibling
12098 // `aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly`
12099 // (7ef425e) cross-axis routing pin on the peer `AplicacaoError`
12100 // envelope's per-`:politicas` per-axis ctor family, extended here onto
12101 // the last M2 per-`:supervisor` `Copy`-scalar `SupervisorError`
12102 // variant family folded onto a substrate primitive.
12103 //
12104 // Fixtures picked out of each variant's accept-set boundary rather
12105 // than the default value so a silent constant-substitution to a per-
12106 // variant sentinel surfaces here on the structural-equality assertion.
12107 // The `RestartStrategy` fixture picks `RestForOne` (a non-default arm
12108 // that isn't the `OneForOne` [`SUPERVISOR_ESTRATEGIA_DEFAULT`] and
12109 // isn't the `SimpleOneForOne` arm the sibling
12110 // `SimpleOneForOneWithStaticChildren` unit variant intercepts). The
12111 // `max_restarts` fixture picks an above-cap magnitude the cap arm
12112 // rejects; the two `Duration` fixtures pick the sub-millisecond and
12113 // above-cap ends of the `:restart-window` canonical-form + cap
12114 // bracket respectively.
12115 let estrategia = RestartStrategy::RestForOne;
12116 let above_cap_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 137;
12117 let sub_ms = Duration::from_micros(1_500);
12118 let above_hour = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
12119 assert_eq!(
12120 SupervisorError::no_children(estrategia),
12121 SupervisorError::NoChildren { estrategia },
12122 );
12123 assert_eq!(
12124 SupervisorError::max_restarts_exceeds_cap(above_cap_restarts),
12125 SupervisorError::MaxRestartsExceedsCap {
12126 max_restarts: above_cap_restarts,
12127 },
12128 );
12129 assert_eq!(
12130 SupervisorError::restart_window_not_canonical(sub_ms),
12131 SupervisorError::RestartWindowNotCanonical { window: sub_ms },
12132 );
12133 assert_eq!(
12134 SupervisorError::restart_window_exceeds_cap(above_hour),
12135 SupervisorError::RestartWindowExceedsCap { window: above_hour },
12136 );
12137 }
12138
12139 #[test]
12140 fn supervisor_scalar_ctors_are_const_zero_runtime_work() {
12141 // Const-eval pin: the [`supervisor_scalar_ctors!`] macro spells every
12142 // generated ctor `const fn` so a caller can pin a `SupervisorError`
12143 // at compile time — the same zero-runtime-work property the pre-lift
12144 // `|<slot>| SupervisorError::<Variant> { <slot> }` closure carried on
12145 // its `Copy`-pass-through construction path (no `.to_string()` /
12146 // `.into()` allocation, no branching). If any future edit silently
12147 // drops the `const` qualifier from the macro body the per-arm `const`
12148 // bindings below fail to compile, which surfaces the regression at
12149 // the substrate-primitive definition rather than at some downstream
12150 // consumer that had come to rely on the `const`-constructibility.
12151 // Peer of the sibling
12152 // `aplicacao_policy_scalar_ctors_are_const_zero_runtime_work`
12153 // (7ef425e) const-eval pin on the peer `AplicacaoError` envelope's
12154 // per-`:politicas` per-axis ctor family.
12155 const NO_CHILDREN: SupervisorError =
12156 SupervisorError::no_children(RestartStrategy::OneForAll);
12157 const MAX_RESTARTS_CAP: SupervisorError = SupervisorError::max_restarts_exceeds_cap(1_337);
12158 const WINDOW_NC: SupervisorError =
12159 SupervisorError::restart_window_not_canonical(Duration::from_micros(1));
12160 const WINDOW_CAP: SupervisorError =
12161 SupervisorError::restart_window_exceeds_cap(Duration::from_secs(3_601));
12162 assert!(matches!(NO_CHILDREN, SupervisorError::NoChildren { .. }));
12163 assert!(matches!(
12164 MAX_RESTARTS_CAP,
12165 SupervisorError::MaxRestartsExceedsCap { .. }
12166 ));
12167 assert!(matches!(
12168 WINDOW_NC,
12169 SupervisorError::RestartWindowNotCanonical { .. }
12170 ));
12171 assert!(matches!(
12172 WINDOW_CAP,
12173 SupervisorError::RestartWindowExceedsCap { .. }
12174 ));
12175 }
12176}