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/// Trait-idiomatic *owned-input, [`Box<str>`] output* forward
956/// projection on the M2 OTP-shape sibling-restart [`RestartStrategy`]
957/// closed-set fieldless typed enum — opens a fresh
958/// substrate-wide `Box<str>` forward-projection campaign tier on the
959/// first M2 OTP-shape closed-set fieldless typed enum peer on the
960/// caixa surface, immediately after the paired `Cow<'static, str>`
961/// axis (7dd28b3 / ee577fd) closed the
962/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}` 2×3
963/// corner on this enum. Routes byte-for-byte through the
964/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
965/// accessor via [`Box::<str>::from`] on the returned `&'static str`,
966/// so every consumer that binds a
967/// `let key: Box<str> = strategy.into();`-shaped call site — a
968/// per-supervisor metric-key materializer that stashes the strategy
969/// discriminator in a `Box<str>`-typed heap-owned scalar for cheap
970/// clone (a shared-nothing per-strategy accept-set the
971/// `caixa-operator` reconciliation scheduler carries), a future
972/// admission-webhook rejection body whose per-arm `Box<str>` field
973/// composes from an owned `RestartStrategy` handle — reaches the
974/// same four-arm lifted
975/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
976/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
977/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
978/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
979/// the sibling
980/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
981/// forward-projection corner already returns. Rust's standard
982/// library carries `impl From<&str> for Box<str>` and
983/// `impl From<String> for Box<str>` but no blanket
984/// `impl<T: AsRef<str>> From<T> for Box<str>`, so this axis is a
985/// distinct trait-idiomatic surface that a downstream
986/// `RestartStrategy → Box<str>` `.into()` reaches through this impl
987/// and no other — without a
988/// `Box::from(strategy.as_str())` open-code whose type bounds have
989/// no compile-time link back to the substrate primitive.
990///
991/// Pinned load-bearing by
992/// [`tests::restart_strategy_from_into_box_str_routes_through_as_str_accessor`]
993/// (byte-parity pin against [`RestartStrategy::as_str`] across the
994/// four-arm [`RestartStrategy::ALL`] emit-set on the owned-input
995/// surface, plus a blanket-derived [`Into`] shape witness).
996impl From<RestartStrategy> for Box<str> {
997 fn from(strategy: RestartStrategy) -> Box<str> {
998 Box::<str>::from(strategy.as_str())
999 }
1000}
1001
1002/// Trait-idiomatic *borrowed-input, [`Box<str>`] output* forward
1003/// projection on the M2 OTP-shape sibling-restart [`RestartStrategy`]
1004/// closed-set fieldless typed enum — closes the `{Self, &Self}`
1005/// input-shape corner of the substrate-wide `Box<str>`
1006/// forward-projection axis opened one commit prior (69ef45c) on the
1007/// paired owned-input [`From<RestartStrategy> for Box<str>`] impl.
1008/// Routes byte-for-byte through the same substrate-primitive
1009/// [`RestartStrategy::as_str`] `pub const fn` accessor via
1010/// [`Box::<str>::from`] on the returned `&'static str`, so every
1011/// consumer that holds a `&RestartStrategy` and needs a
1012/// [`Box<str>`] — a
1013/// `RestartStrategy::ALL.iter().map(Box::<str>::from).collect::<Vec<_>>()`
1014/// per-arm accept-set materializer (whose iterator over
1015/// `&'static [RestartStrategy]` yields `&RestartStrategy`, not
1016/// `RestartStrategy`, so the paired owned-input
1017/// [`From<RestartStrategy> for Box<str>`] axis alone forces every
1018/// call site through an explicit `.copied()` / dereference /
1019/// [`Copy`]-bound restatement rather than the direct trait-idiomatic
1020/// projection), a per-supervisor metric-key materializer holding
1021/// `&RestartStrategy` through a `caixa-operator` reconciliation
1022/// scheduler's borrow lifetime, a future admission-webhook rejection
1023/// body whose per-arm `Box<str>` field composes from a borrowed
1024/// `&RestartStrategy` handle without a spurious [`Copy`] deref —
1025/// reaches the same four-arm lifted
1026/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
1027/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
1028/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
1029/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
1030/// the paired owned-input [`From<RestartStrategy> for Box<str>`] and
1031/// the sibling
1032/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
1033/// forward-projection corner already return.
1034///
1035/// Second peer on the substrate-wide trait-idiomatic
1036/// [`Box<str>`] forward-projection family opened one commit prior
1037/// (69ef45c) on the paired owned-input
1038/// [`From<RestartStrategy> for Box<str>`] impl — closes the
1039/// `{Self, &Self}` input-shape corner of the [`Box<str>`] axis on
1040/// the first M2 OTP-shape closed-set fieldless typed enum peer on
1041/// the caixa surface (`:supervisor :estrategia`), exactly as
1042/// ee577fd closed the paired [`Cow<'static, str>`] axis one commit
1043/// after its owning half (7dd28b3) landed. Rust's standard library
1044/// carries `impl From<&str> for Box<str>` and
1045/// `impl From<String> for Box<str>` but no blanket
1046/// `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
1047/// `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
1048/// every closed-set fieldless typed enum peer on the substrate that
1049/// carries the paired owned-input `Box<str>` axis but not the
1050/// borrowed-input axis forces every borrowed-input
1051/// `Box<str>`-parameterized call site through a spurious [`Copy`]
1052/// deref (`Box::<str>::from((*strategy).as_str())`) or a
1053/// `Box::<str>::from(strategy.as_str())` open-code whose type bounds
1054/// have no compile-time link back to the substrate primitive.
1055///
1056/// Pinned load-bearing by
1057/// [`tests::restart_strategy_from_borrowed_into_box_str_routes_through_as_str_accessor`]
1058/// (byte-parity pin against [`RestartStrategy::as_str`] across the
1059/// four-arm [`RestartStrategy::ALL`] emit-set on the borrowed-input
1060/// surface, plus a blanket-derived [`Into`] shape witness and a
1061/// cross-axis pin against the paired owned-input
1062/// [`From<RestartStrategy> for Box<str>`] and the sibling
1063/// borrowed-input `{&'static str, String, Cow<'static, str>}`
1064/// return-shape axes).
1065impl From<&RestartStrategy> for Box<str> {
1066 fn from(strategy: &RestartStrategy) -> Box<str> {
1067 Box::<str>::from(strategy.as_str())
1068 }
1069}
1070
1071/// Per-child restart policy.
1072///
1073/// Permanent / Temporary / Transient match Erlang/OTP semantics 1:1.
1074#[derive(
1075 Serialize,
1076 Deserialize,
1077 Debug,
1078 Clone,
1079 Copy,
1080 PartialEq,
1081 Eq,
1082 Hash,
1083 gen_platform::TypedDispatcher,
1084 gen_platform::Discriminant,
1085 gen_platform::IsVariant,
1086 gen_platform::FromStrKind,
1087)]
1088pub enum RestartPolicy {
1089 /// Always restart the child, regardless of how it died. Used for
1090 /// long-running services that must always be up.
1091 Permanent,
1092 /// Never restart. Used for one-shot work whose completion is
1093 /// itself the success signal (`oneShot` triggers map here).
1094 Temporary,
1095 /// Restart only when the child died *abnormally* (non-zero exit
1096 /// or unhandled exception). A clean exit completes the child.
1097 Transient,
1098}
1099
1100impl Default for RestartPolicy {
1101 fn default() -> Self {
1102 // Route the [`Default for RestartPolicy`] impl's return arm through
1103 // the substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed
1104 // `pub const` rather than a raw `Self::Permanent` arm — one source
1105 // of truth for the Erlang/OTP-canonical `permanent` worker-child
1106 // default across the two production consumers that currently
1107 // dispatch on it (this impl at the [`RestartPolicy::default`] call
1108 // and the serde-side `#[serde(default)]` on
1109 // [`ChildSpec::restart`] that resolves an author-omitted
1110 // `:children :restart` slot through `RestartPolicy::default()`).
1111 // Peer of the sibling per-`:supervisor` axis
1112 // [`Default for RestartStrategy`] → [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
1113 // route (95ffacc) — the two impls now share one substrate-primitive
1114 // lift discipline, so any future coherent rebrand of the OTP-shape
1115 // supervisor+child default set migrates through typed constants in
1116 // lockstep instead of splitting a lifted supervisor half against
1117 // an open-coded child half. Pinned by
1118 // `restart_policy_default_routes_through_lifted_default` +
1119 // `child_spec_serde_default_restart_routes_through_lifted_default`
1120 // in the tests module.
1121 SUPERVISOR_CHILD_RESTART_DEFAULT
1122 }
1123}
1124
1125impl RestartPolicy {
1126 /// Exhaustive iteration surface for every consumer that walks the
1127 /// closed three-arm [`RestartPolicy`] discriminator set (the future
1128 /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1129 /// per-child admission-webhook rejection body naming the accepted-
1130 /// `:restart` list, a future `feira supervisor --restart …` CLI
1131 /// arg-parse's "did you mean" hint via a [`Self::from_wire`]-scan
1132 /// over the slice, the future `feira app graph` per-child restart
1133 /// column, any future round-trip fuzz harness that sweeps every
1134 /// arm). A future arm addition (an OTP-`intrinsic` fourth arm the
1135 /// theory
1136 /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1137 /// might reach for once the three canonical OTP restart policies
1138 /// stop covering the substrate's discovered load-shape) extends
1139 /// this slice as one edit and every consumer picks up the new entry
1140 /// by construction; the compiler-checked exhaustiveness on the
1141 /// sibling method `match` arms ([`Self::as_str`] / [`Self::from_wire`])
1142 /// is the build-time guarantee that no arm forgets to grow.
1143 ///
1144 /// Peer of the sibling closed-set typed enums'
1145 /// [`RestartStrategy::ALL`] (4eec29c) /
1146 /// [`crate::CaixaKind::ALL`] (6b1f4fb) /
1147 /// [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
1148 /// [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
1149 /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
1150 /// surfaces — the sixth (and the third and final M2 OTP-shape)
1151 /// closed-set typed enum on the caixa surface to converge onto the
1152 /// same one-canonical-arm-list-per-enum discipline. Sibling axis to
1153 /// the peer [`RestartStrategy::ALL`] on the per-supervisor
1154 /// sibling-restart-strategy axis; this closes the per-child
1155 /// restart-decision-policy axis on the same M2 `:supervisor` slot.
1156 pub const ALL: &'static [Self] = &[Self::Permanent, Self::Temporary, Self::Transient];
1157
1158 /// Canonical PascalCase discriminator scalar this variant serializes
1159 /// as under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`]. The three
1160 /// arms return the paired
1161 /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1162 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1163 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] lifted
1164 /// constants so every substrate consumer that dispatches on the
1165 /// per-child restart-decision policy (the future wasm-operator's
1166 /// per-child post-exit restart-decision branch, the future M4
1167 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1168 /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
1169 /// reconciliation scheduler's per-child-policy fan-out) reads the
1170 /// same byte-string the `Serialize` derive emits — the pin test in
1171 /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
1172 /// asserts the two paths agree, peer of the M2
1173 /// [`RestartStrategy::as_str`] (09ffb2d) on the sibling per-supervisor
1174 /// sibling-restart-strategy axis and the M3
1175 /// [`crate::aplicacao::PlacementStrategy::as_str`] (cc8f749) on the
1176 /// per-Aplicacao distribution-strategy axis — the third of three
1177 /// OTP-shaped closed-enum discriminator axes on the caixa typed
1178 /// surface to converge onto the same three-path-convergence
1179 /// (`Serialize` derive → `as_str` helper → lifted constant)
1180 /// drift-detection posture.
1181 #[must_use]
1182 pub const fn as_str(self) -> &'static str {
1183 match self {
1184 Self::Permanent => crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
1185 Self::Temporary => crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
1186 Self::Transient => crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
1187 }
1188 }
1189
1190 /// Substrate-canonical reverse projection on the `:children :restart`
1191 /// closed-set axis — parses the `PascalCase` discriminator scalar
1192 /// back to the typed variant, or `None` when `s` is outside the
1193 /// closed-set arm-string set [`Self::as_str`] emits. Dispatches on
1194 /// the same lifted
1195 /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1196 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1197 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] constants
1198 /// the [`Self::as_str`] emitter walks, so the parse and emit halves
1199 /// of the round-trip migrate through one caixa-core edit on any
1200 /// future arm addition.
1201 ///
1202 /// Prior to this lift the substrate carried only the forward
1203 /// `Self → &str` projection on the OTP per-child restart-policy
1204 /// axis (the [`Self::as_str`] emitter, the [`std::fmt::Display`]
1205 /// impl routed through it, the `Serialize` derive that emits the
1206 /// same byte-string under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`])
1207 /// plus the kebab-case dispatcher-catalog identity via
1208 /// [`Self::discriminant`] — every non-serde consumer that wanted to
1209 /// parse a wire-form `PascalCase` policy scalar had to re-inline a
1210 /// three-arm `match s { "Permanent" => …, "Temporary" => …,
1211 /// "Transient" => …, _ => … }` cascade that expressed no
1212 /// compile-time link back to the typed variant's canonical lifted
1213 /// constant. A future variant rename or per-arm serde-attribute
1214 /// drift would silently split the wire byte-string one non-serde
1215 /// consumer parsed from the one the emitter wrote, with the failure
1216 /// surfacing at the operator's reconcile posture (a `:temporary`
1217 /// `oneShot` child being restarted on clean exit, treating the
1218 /// successful-completion signal as failure and re-running the
1219 /// completion-terminal one-shot indefinitely; a `:transient` child
1220 /// that clean-exited being restarted, masking the clean-completion
1221 /// contract) far from the rebrand commit and with no field naming
1222 /// the drift.
1223 ///
1224 /// Distinct axis from the [`std::str::FromStr`] impl the
1225 /// [`gen_platform::FromStrKind`] derive already installs on this
1226 /// enum by design, not by drift: `FromStr` parses the *kebab-case*
1227 /// dispatcher-catalog identity (`"permanent"` / `"temporary"` /
1228 /// `"transient"` — the inverse of [`Self::discriminant`]), while
1229 /// this method inverts the `PascalCase` wire byte-string
1230 /// [`Self::as_str`] emits. The two-axis split lets the dispatcher-
1231 /// catalog identity live in kebab-case (where every peer catalog
1232 /// identifier already lives) without forcing a wire-format rename
1233 /// on the tatara-lisp author surface (`:restart Permanent`,
1234 /// `PascalCase`) — the same two-axis distinction the sibling
1235 /// [`RestartStrategy::from_wire`] (4eec29c) /
1236 /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
1237 /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
1238 /// carry on their peer closed-set typed-enum wire round-trips.
1239 ///
1240 /// Same closed-set-reverse-projection discipline the sibling
1241 /// [`RestartStrategy::from_wire`] (4eec29c) /
1242 /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
1243 /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
1244 /// [`crate::aplicacao::RateLimitUnit::from_suffix`] typed enums
1245 /// carry on the peer wire-side `str → Self` axes — extended onto
1246 /// the M2 OTP-shape per-child restart-policy closed-set axis, the
1247 /// sixth substrate-side closed-set typed enum (and the third and
1248 /// final OTP-shape closed-enum discriminator axis) to converge on
1249 /// the two-way `str ↔ Self` round-trip. Method-named `from_wire`
1250 /// (not `from_str`) to match the peer [`RestartStrategy::from_wire`]
1251 /// shape verbatim and side-step the [`std::str::FromStr`] impl the
1252 /// derive already installs on the sibling kebab-case axis. Returns
1253 /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
1254 /// shapes: the caller picks the diagnostic form appropriate for
1255 /// its use site.
1256 #[must_use]
1257 pub fn from_wire(s: &str) -> Option<Self> {
1258 match s {
1259 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT => Some(Self::Permanent),
1260 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY => Some(Self::Temporary),
1261 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT => Some(Self::Transient),
1262 _ => None,
1263 }
1264 }
1265}
1266
1267/// [`std::fmt::Display`] routed through [`RestartPolicy::as_str`], so the
1268/// pretty-printed byte-string every consumer that formats the policy as
1269/// user-facing text lands on (the future wasm-operator's per-child
1270/// post-exit restart-decision diagnostic line, the future `feira app
1271/// graph` per-child restart column, the future M4
1272/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1273/// admission-webhook rejection body) reaches for the same lifted
1274/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1275/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1276/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1277/// wire-format `Serialize` derive already emits under
1278/// [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
1279/// [`RestartPolicy::as_str`] helper already returns.
1280///
1281/// Pre-convergence the two paths structurally disagreed — the
1282/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
1283/// route (now retired here) sent [`std::fmt::Display`] through the
1284/// gen-platform discriminant catalog string, which arrives kebab-case as
1285/// `"permanent"` / `"temporary"` / `"transient"` on this three-arm enum
1286/// (whose variant names each collapse to their own lowercase form under
1287/// the kebab-case transform), while the wire format ran as `PascalCase`
1288/// `"Permanent"` / `"Temporary"` / `"Transient"` through the un-`rename`d
1289/// serde derive. Every consumer that formatted the policy for a
1290/// diagnostic line, a graph column, or a rejection body under
1291/// `format!("{v}")` therefore landed under a different byte-string than
1292/// the wire format the operator's per-child-policy dispatch keyed off —
1293/// a silent split whose apply-time symptom (a `format!("{v}")`-carrying
1294/// diagnostic quoting `"permanent"` while the wire scalar the operator
1295/// probed was `"Permanent"`) surfaced as a confused correlate at
1296/// operator-log time far from the two-declaration site.
1297///
1298/// Routing `Display` through [`RestartPolicy::as_str`] closes the third
1299/// path: every `format!("{v}")` call reaches the same lifted
1300/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the wire format
1301/// and the [`RestartPolicy::as_str`] helper route through — `Debug` (the
1302/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
1303/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
1304/// byte-string per variant. A future variant rename or
1305/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
1306/// exactly one place, structurally.
1307///
1308/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
1309/// (from `#[derive(gen_platform::Discriminant)]`) still returns
1310/// `"permanent"` / `"temporary"` / `"transient"`, and the fleet-wide
1311/// [`gen_platform::register_dispatcher!("caixa.restart-policy", …)`]
1312/// registration keys the catalog off the same kebab identity. The two
1313/// naming worlds now live on separate typed methods (`Display` /
1314/// `as_str` for the wire byte-string, `discriminant` for the catalog
1315/// identity) rather than sharing one `Display` route that structurally
1316/// disagrees with the wire format.
1317///
1318/// Pin tests
1319/// [`tests::restart_policy_display_routes_through_as_str_helper`]
1320/// and
1321/// [`tests::restart_policy_display_matches_serialized_wire_byte_string`]
1322/// assert the three paths agree byte-for-byte on every variant, so a
1323/// future variant rename or per-arm serde attribute drift is a build
1324/// error visible at caixa-core test time, not a silent per-consumer
1325/// dispatch miss at apply / reconcile time.
1326///
1327/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
1328/// (aplicacao.rs:2306) on the per-Aplicacao distribution-strategy axis
1329/// and the sibling [`RestartStrategy`] `Display` impl on the
1330/// per-supervisor sibling-restart-strategy axis — same three-path-
1331/// convergence discipline, extended to close the third and final of
1332/// three OTP-shaped closed-enum discriminator axes on the caixa typed
1333/// surface.
1334impl std::fmt::Display for RestartPolicy {
1335 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1336 f.write_str(self.as_str())
1337 }
1338}
1339
1340/// Substrate-canonical [`AsRef<str>`] projection on the M2
1341/// per-child-restart-policy [`RestartPolicy`] closed-set typed enum —
1342/// routes through the same [`RestartPolicy::as_str`] `pub const fn`
1343/// scalar accessor the paired [`std::fmt::Display`] impl and the
1344/// un-`rename`d [`serde::Serialize`] derive already key off, so any
1345/// future consumer that binds a [`RestartPolicy`] through the
1346/// standard-library `impl AsRef<str>` bound (a future
1347/// [`caixa-feira`] `feira supervisor --restart <arm>` verb that
1348/// composes the emitted `PascalCase` wire scalar into a
1349/// [`std::process::Command::arg`] shell-out of the future
1350/// wasm-operator's per-child admission gate, a per-child structured-
1351/// log recorder on the future `caixa-operator`'s hierarchical
1352/// reconciliation surface that accepts `impl AsRef<str>` at the
1353/// `tracing::field::Value` `Str`-arm, a [`std::collections::HashMap`]
1354/// lookup keyed on the restart-policy wire byte through
1355/// `map.get::<str>(policy.as_ref())` on a future per-policy
1356/// dispatch table) reaches the paired
1357/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1358/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1359/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
1360/// lifted-const through one substrate-primitive dispatch rather
1361/// than an open-coded `.as_str()` projection at every wire-up.
1362///
1363/// Peer of the sibling [`std::fmt::Display`] impl on the same
1364/// primitive — both delegate to the shared [`RestartPolicy::as_str`]
1365/// `pub const fn` accessor, so [`format!("{v}")`], `v.as_str()`, and
1366/// `<RestartPolicy as AsRef<str>>::as_ref(&v)` resolve to the same
1367/// byte-string per instance by construction. A future variant rename
1368/// or `#[serde(rename_all = "kebab-case")]` attribute-drift on the
1369/// enum reaches every one of the three paths (plus the wire-format
1370/// `Serialize` derive that already routes through the same lifted
1371/// const) through exactly one caixa-core edit.
1372///
1373/// Same "route the trait impl through the substrate-primitive
1374/// accessor" discipline the sibling [`crate::CaixaVersion`]
1375/// [`AsRef<str>`] impl (16d5c7e) and the paired M2
1376/// [`RestartStrategy`] [`AsRef<str>`] impl (63eb1a4) carry — extends
1377/// the axis onto the paired per-child-restart-decision-policy
1378/// sibling on the same M2 `:supervisor` slot (the second M2
1379/// OTP-shape closed-set typed enum to converge onto the standard-
1380/// library [`AsRef<str>`] projection). Rust-side newtype/typed-enum
1381/// convention pairs [`AsRef<str>`] and [`fmt::Display`] on the same
1382/// primitive so a caller who has one has both; before this lift,
1383/// [`RestartPolicy`] carried [`fmt::Display`] but not the paired
1384/// [`AsRef<str>`] impl the convention names.
1385///
1386/// Pinned load-bearing by
1387/// [`tests::restart_policy_as_ref_str_routes_through_as_str_accessor`]
1388/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1389/// three-arm closed set) and
1390/// [`tests::restart_policy_as_ref_str_routes_through_display_via_shared_accessor`]
1391/// (three-path convergence: `AsRef<str>` + `Display` + `as_str` all
1392/// resolve to the same lifted `SUPERVISOR_CHILD_RESTART_*` const per
1393/// arm) — any future silent detour that routes the impl through a
1394/// divergent projection (a per-arm inline `match self { … }`
1395/// re-inlining that opens a compile-time link to the un-lifted
1396/// arm-literal, a swap onto the kebab-case
1397/// [`gen_platform::Discriminant`] catalog identity that would
1398/// collide the wire axis with the dispatcher-catalog axis) trips at
1399/// caixa-core test time under `assert_eq!` rather than at a
1400/// downstream `impl AsRef<str>`-bound consumer's silent split.
1401impl AsRef<str> for RestartPolicy {
1402 fn as_ref(&self) -> &str {
1403 self.as_str()
1404 }
1405}
1406
1407/// Trait-idiomatic reverse projection on the M2-OTP-shape per-child
1408/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
1409/// byte-for-byte through the paired substrate-primitive
1410/// [`RestartPolicy::from_wire`] `Option<Self>` accessor so every future
1411/// consumer that binds a `PascalCase` `:children :restart` wire
1412/// byte-string through the standard-library `.try_into()` / [`TryFrom`]
1413/// axis (a future [`caixa-feira`] `feira supervisor --restart
1414/// <Permanent|Temporary|Transient>` CLI arg-parse that composes into
1415/// `let restart: RestartPolicy = s.try_into()?`, a future
1416/// `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook that folds a
1417/// `spec.children[*].restart: String` field through
1418/// `RestartPolicy::try_from(&s)?`, a generic
1419/// `<T: TryFrom<&str>>`-bound loader over any of the substrate's closed-
1420/// set typed enums) reaches the same three-arm accept-set the sibling
1421/// [`RestartPolicy::from_wire`] resolver parses through and the sibling
1422/// [`RestartPolicy::as_str`] emits, rather than an open-coded per-arm
1423/// `match s { "Permanent" => …, "Temporary" => …, "Transient" => …, _ =>
1424/// … }` cascade whose arm-set has no compile-time link back to the
1425/// substrate primitive.
1426///
1427/// Complements the pre-existing forward-projection triple
1428/// ([`std::fmt::Display`], [`AsRef<str>`], [`RestartPolicy::as_str`])
1429/// with the paired trait-idiomatic reverse-projection axis: Rust-side
1430/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
1431/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so a
1432/// caller who can project *out to* a `&str` can also project *in from*
1433/// one. The [`TryFrom<&str>`] axis is deliberately chosen over
1434/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
1435/// lint the sibling method-named [`RestartPolicy::from_wire`] would
1436/// trigger under a `FromStr` impl and to avoid colliding with the
1437/// [`std::str::FromStr`] impl the [`gen_platform::FromStrKind`] derive
1438/// already installs on the paired *kebab-case dispatcher-catalog* axis
1439/// (which parses `"permanent"` / `"temporary"` / `"transient"`, the
1440/// inverse of [`Self::discriminant`]) — this impl closes the trait-
1441/// idiomatic reverse axis on the *`PascalCase` wire* half without
1442/// disturbing either the method-named `from_wire` shape every sibling
1443/// closed-set typed enum on the substrate already carries or the
1444/// pre-existing `FromStr` on the dispatcher-catalog half, keeping the
1445/// two-axis split the sibling [`Self::from_wire`] doc block motivates.
1446///
1447/// `type Error = ()` matches the sibling [`RestartPolicy::from_wire`]'s
1448/// `Option<Self>` return-shape's deliberate deferral of error typing: the
1449/// caller picks the diagnostic form appropriate for its use site (a
1450/// future `feira supervisor --restart` arg-parse composes its own
1451/// per-verb "unknown restart: <arg> — accepted: {…}" message enumerating
1452/// [`RestartPolicy::ALL`], a future M4 admission-webhook rejection body
1453/// wraps the `Err(())` outcome with the accepted-set enumeration for
1454/// operator diagnostics, a `Result::map_err` at the call site lifts the
1455/// unit-error to a per-verb error type). Same shape the peer
1456/// [`RestartStrategy`] (5b828ed) on the sibling per-supervisor axis,
1457/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136), and
1458/// [`crate::aplicacao::PlacementStrategy`] (6fd00cd) blocks motivate on
1459/// their peer closed-set typed enums' reverse projections.
1460///
1461/// The paired [`TryFrom<&str>`] impl reaches the same three-arm accept-
1462/// set the [`RestartPolicy::from_wire`] resolver dispatches through, so
1463/// any future arm addition (an OTP-`intrinsic` fourth arm the theory
1464/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1465/// might reach for once the three canonical OTP restart policies stop
1466/// covering the substrate's discovered load-shape) grows the trait-
1467/// idiomatic axis by construction — one caixa-core edit on
1468/// [`RestartPolicy::from_wire`] extends both the method-named reverse
1469/// projection every existing consumer keys off and the trait-idiomatic
1470/// reverse projection this impl exposes, without a coordinated rewrite
1471/// across every future `TryFrom<&str>`-bound consumer's arm-set.
1472///
1473/// Extends the substrate-wide closed-set-enum reverse-projection family
1474/// ([`crate::CaixaKind`] via 3c83606, [`crate::CaixaDialeto`] via
1475/// bf33136, [`crate::aplicacao::PlacementStrategy`] via 6fd00cd, and
1476/// [`RestartStrategy`] via 5b828ed) onto the third and final OTP-shape
1477/// closed-enum discriminator axis on the caixa surface — the paired
1478/// per-child `:children :restart` closed set the future wasm-operator's
1479/// hierarchical reconciliation scheduler's per-child post-exit
1480/// restart-decision branch keys off end-to-end.
1481///
1482/// Pinned load-bearing by
1483/// [`tests::restart_policy_try_from_str_routes_through_from_wire_accessor`]
1484/// (byte-parity pin against [`RestartPolicy::from_wire`] across the
1485/// three-arm accept-set),
1486/// [`tests::restart_policy_try_from_str_rejects_unknown_byte_strings`]
1487/// (rejection witness against silent accept-set widening), and
1488/// [`tests::restart_policy_try_from_str_and_from_wire_partition_the_accept_set`]
1489/// (cross-axis partition pin locking the trait and method-named
1490/// projections onto one accept-set).
1491impl TryFrom<&str> for RestartPolicy {
1492 type Error = ();
1493
1494 fn try_from(s: &str) -> Result<Self, Self::Error> {
1495 Self::from_wire(s).ok_or(())
1496 }
1497}
1498
1499/// Trait-idiomatic forward projection on the M2-OTP-shape per-child
1500/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
1501/// byte-for-byte through the paired substrate-primitive
1502/// [`RestartPolicy::as_str`] `pub const fn` accessor. Return type is
1503/// `&'static str` by construction — every [`RestartPolicy::as_str`] arm
1504/// resolves to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const
1505/// &str` with `'static` lifetime, so the trait's return-type promise is
1506/// upheld structurally without a [`String::leak`] cast or a per-arm inline
1507/// literal.
1508///
1509/// Every future consumer that specifically needs `&'static str` lifetime
1510/// bytes on the per-child restart-decision axis (a
1511/// [`tracing::field::valuable::Value::Str`] recording where the `Str`
1512/// arm's typing demands `&'static str`, a
1513/// [`std::borrow::Cow::Borrowed`]`::<'static, str>(policy.into())` composer
1514/// on the future M4 admission-webhook rejection body where the
1515/// `Cow<'static, str>` typing rules out the sibling [`AsRef<str>`]
1516/// borrowed return, a generic `<T: Into<&'static str>>`-bound serializer
1517/// or error formatter that requires the `'static` bound) reaches the same
1518/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1519/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1520/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] substrate-
1521/// primitive dispatch rather than an open-coded per-arm literal cascade
1522/// whose arm-set has no compile-time link back to the substrate primitive.
1523///
1524/// Peer of the sibling M2-OTP-shape [`RestartStrategy`] forward-projection
1525/// impl (523157d) on the per-supervisor sibling-restart-strategy axis —
1526/// the second (and second-of-two-in-M2) closed-set typed enum on the
1527/// caixa surface to converge onto the paired trait-idiomatic forward-
1528/// projection axis. With this lift the paired per-child
1529/// `:children :restart` closed-set typed enum carries the full sibling
1530/// quintet ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
1531/// [`TryFrom<&str>`] via 6fdd0d9, `From<Self> for &'static str` via this
1532/// lift) plus the round-trip witness through both the trait-idiomatic
1533/// (`From<Self> for &'static str` + `TryFrom<&str>`) and the method-named
1534/// (`as_str` + `from_wire`) axis pairs — mirrors the sibling
1535/// [`RestartStrategy`] surface arm-for-arm, so every future arm addition
1536/// (an OTP-`intrinsic` fourth arm the theory
1537/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1538/// might reach for once the three canonical OTP restart policies stop
1539/// covering the substrate's discovered load-shape) grows the trait-
1540/// idiomatic forward axis by construction: one caixa-core edit on
1541/// [`RestartPolicy::as_str`] extends every one of the five sibling
1542/// forward-projection paths ([`std::fmt::Display`], [`AsRef<str>`],
1543/// [`Self::as_str`] itself, this `From<Self> for &'static str`, and the
1544/// un-`rename`d [`serde::Serialize`] derive that also emits `as_str`'s
1545/// bytes) without a coordinated rewrite across every future
1546/// `Into<&'static str>`-bound consumer's arm-set.
1547///
1548/// Pinned load-bearing by
1549/// [`tests::restart_policy_from_into_static_str_routes_through_as_str_accessor`]
1550/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1551/// three-arm emit-set, plus a `const`-context materialization witness for
1552/// the `&'static str` lifetime promise) and
1553/// [`tests::restart_policy_from_into_static_str_and_as_str_partition_the_emit_set`]
1554/// (partition pin asserting `<&'static str as From<RestartPolicy>>::from`
1555/// and [`RestartPolicy::as_str`] agree on every arm, plus a two-way
1556/// round-trip witness through the paired trait-idiomatic reverse-
1557/// projection axis [`TryFrom<&str>`] (6fdd0d9): every
1558/// `policy.into::<&'static str>()` output re-parses back through
1559/// [`RestartPolicy::try_from`] to the original variant, closing the two-
1560/// way `Self ↔ &'static str` round-trip on the trait-idiomatic axis pair).
1561impl From<RestartPolicy> for &'static str {
1562 fn from(policy: RestartPolicy) -> &'static str {
1563 policy.as_str()
1564 }
1565}
1566
1567/// Trait-idiomatic *forward* projection on [`RestartPolicy`] from a
1568/// *borrowed* input onto the `&'static str` axis — the borrowed-input
1569/// companion to the paired owned-input [`From<RestartPolicy> for
1570/// &'static str`] impl immediately above. Routes byte-for-byte through
1571/// the same substrate-primitive [`RestartPolicy::as_str`] `pub const
1572/// fn` accessor so every consumer that binds a `&RestartPolicy`
1573/// through the standard-library `.into()` / [`From<&Self> for &'static
1574/// str`] axis (a `RestartPolicy::ALL.iter().map(<&'static
1575/// str>::from).collect::<Vec<_>>()` per-arm accept-set materializer —
1576/// whose iterator over `&'static [RestartPolicy]` yields
1577/// `&RestartPolicy`, not `RestartPolicy`, so the owned-input
1578/// [`From<RestartPolicy>`] axis alone forces every call site through
1579/// an explicit `.copied()` / dereference / [`Copy`]-bound restatement
1580/// rather than the direct trait-idiomatic projection; a future generic
1581/// `<T: Copy + for<'a> Into<&'static str>>`-bound diagnostic column
1582/// that walks the `iter().map(Into::into)` shape verbatim across every
1583/// substrate-wide closed-set typed enum; the future wasm-operator's
1584/// per-child post-exit restart-decision diagnostic line that composes
1585/// the accepted-set enumeration from an iterated
1586/// `RestartPolicy::ALL.iter().map(|p| p.into())` pipe rather than a
1587/// per-arm `match p { … }` cascade; a future
1588/// `HashMap::<&'static str, RestartPolicy>::from_iter(
1589/// RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
1590/// per-policy reverse-lookup table the sibling [`TryFrom<&str>`] impl
1591/// cannot compose without this borrowed-input axis in place) reaches
1592/// the same three-arm lifted
1593/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1594/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1595/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1596/// paired owned-input [`From<RestartPolicy> for &'static str`], the
1597/// sibling [`std::fmt::Display`], [`AsRef<str>`], and
1598/// [`RestartPolicy::as_str`] surfaces already return.
1599///
1600/// Fifth peer on the substrate-wide trait-idiomatic *borrowed-input*
1601/// forward-projection family opened on [`crate::dep::DepList`]
1602/// (64aa742) and extended onto [`crate::CaixaKind`] (5ab993a),
1603/// [`crate::CaixaDialeto`] (807b0b5), and the paired
1604/// per-supervisor sibling-restart-strategy [`RestartStrategy`]
1605/// (e941836). Rust's `From` trait does not auto-derive the
1606/// `From<&Self>` sibling from a `From<Self>` impl (the blanket
1607/// `impl<T, U> From<&T> for U where T: Copy, U: From<T>` does not
1608/// exist in `core`), so every closed-set typed enum that carries the
1609/// owned-input axis but not the borrowed-input axis forces every
1610/// borrowed-input call site through a `.copied()` /
1611/// `<&'static str>::from(*policy)` / `policy.as_str()` detour whose
1612/// type bounds have no compile-time link to the substrate primitive.
1613/// [`RestartPolicy`] is the second (and second-of-two-in-M2)
1614/// OTP-shape peer to converge onto this campaign — sibling of the
1615/// paired per-supervisor [`RestartStrategy`] borrowed-input axis, so
1616/// with this lift both closed-set typed enums on the M2 `:supervisor`
1617/// slot now carry the full sibling quintet ([`std::fmt::Display`],
1618/// [`AsRef<str>`], [`Self::as_str`], `From<Self> for &'static str`,
1619/// `From<&Self> for &'static str`) plus the paired trait-idiomatic
1620/// reverse projection [`TryFrom<&str>`], closing the borrowed-input
1621/// forward-projection axis on the M2 OTP-shape slot as a unit.
1622///
1623/// Same three-path convergence discipline as the paired owned-input
1624/// impl (this borrowed-input axis, the paired owned-input
1625/// [`From<RestartPolicy> for &'static str`], and
1626/// [`RestartPolicy::as_str`] all route through the same lifted
1627/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const), so a future
1628/// variant rename or per-arm serde-attribute drift reaches every one
1629/// of the six sibling forward-projection paths
1630/// ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
1631/// [`From<Self> for &'static str`], this [`From<&Self> for &'static
1632/// str`], and the un-`rename`d [`serde::Serialize`] derive that also
1633/// emits [`Self::as_str`]'s bytes) through exactly one caixa-core
1634/// edit.
1635///
1636/// The [`RestartPolicy::as_str`] emit and [`RestartPolicy::from_wire`]
1637/// parse share the same `PascalCase` vocabulary by construction, so
1638/// the borrowed-input forward axis and the reverse axis compose
1639/// directly — the round-trip witness pin below locks this direct
1640/// composition without the intermediate wire-vocab hop the peer
1641/// [`crate::CaixaKind`] axis pair requires.
1642///
1643/// Pinned load-bearing by
1644/// [`tests::restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
1645/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1646/// three-arm emit-set via a borrowed input, plus a `const`-context
1647/// materialization witness for the `&'static str` lifetime promise,
1648/// plus a blanket `.into()` shape) and
1649/// [`tests::restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
1650/// (cross-axis partition pin against the paired owned-input
1651/// [`From<RestartPolicy> for &'static str`] impl, plus a
1652/// `.iter().map(Into::into)` pipe witness over
1653/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
1654/// [`TryFrom<&str>`] that closes the two-way `&Self → &'static str →
1655/// Self` round-trip without the wire-vocab intermediate the peer
1656/// [`crate::CaixaKind`] axis pair requires).
1657impl From<&RestartPolicy> for &'static str {
1658 fn from(policy: &RestartPolicy) -> &'static str {
1659 policy.as_str()
1660 }
1661}
1662
1663/// Trait-idiomatic *owned-`String`* forward projection on the second
1664/// M2 OTP-shape closed-set typed enum ([`RestartPolicy`]) — the
1665/// owned-heap-string companion to the paired `&'static str`-returning
1666/// [`From<RestartPolicy> for &'static str`] / [`From<&RestartPolicy>
1667/// for &'static str`] impls immediately above. Routes byte-for-byte
1668/// through the substrate-primitive [`RestartPolicy::as_str`] `pub
1669/// const fn` accessor (via [`str::to_owned`]) so every consumer that
1670/// binds a [`RestartPolicy`] through the standard-library `.into()` /
1671/// [`From<Self> for String`] (equivalently [`Into<String>`]) axis — a
1672/// future `serde_json::Value::String(policy.into())` structured-payload
1673/// composer where the `Value::String` arm typing demands an owned
1674/// [`String`] and the sibling [`&'static str`]-returning axis forces
1675/// an explicit `.to_owned()` / `String::from` restatement at every
1676/// call site, a future `HashMap::<String, RestartPolicy>::from_iter(
1677/// RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))` per-policy
1678/// lookup where the map's key type is owned [`String`] rather than
1679/// [`&'static str`], a future `Cow::<'static, str>::Owned(policy.into())`
1680/// composer on the future M4 admission-webhook rejection body's
1681/// owned-arm, the future wasm-operator's per-child post-exit
1682/// diagnostic emit `serde_json::json!({ "restart": policy })` where the
1683/// JSON serializer's `Serialize` impl on [`String`] owns the emit-path
1684/// — reaches the same three-arm lifted
1685/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1686/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1687/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1688/// paired [`std::fmt::Display`], [`AsRef<str>`],
1689/// [`RestartPolicy::as_str`], and the two `&'static str`-returning
1690/// forward-projection impls already return.
1691///
1692/// Extends the trait-idiomatic *owned-`String`* forward-projection
1693/// axis onto the second-of-two M2 OTP-shape closed-set typed enums on
1694/// the caixa surface — mirror of the first-mover
1695/// [`From<RestartStrategy> for String`] (7baa18a) that opened this
1696/// axis on the sibling supervisor-level strategy enum. Rust's standard
1697/// library does not carry a blanket `impl<T: AsRef<str>> From<T> for
1698/// String` (nor an `impl<T: fmt::Display> From<T> for String`), so
1699/// every closed-set typed enum that carries the paired `AsRef<str>` /
1700/// `Display` / `From<Self> for &'static str` triple but not the
1701/// owned-[`String`] axis forces every owned-string call site through a
1702/// `.to_string()` / `.as_str().to_owned()` / `String::from(policy.as_str())`
1703/// detour whose type bounds have no compile-time link to the
1704/// substrate primitive.
1705///
1706/// Deliberately routes through the human-readable
1707/// [`RestartPolicy::as_str`] axis — for this enum the wire format
1708/// (`PascalCase`, tatara-lisp author surface `:restart Permanent`) and
1709/// the diagnostic byte-string share the same vocabulary by
1710/// construction (unlike the sibling [`crate::CaixaKind`] enum whose
1711/// two axes diverge), so the owned-[`String`] projection lands
1712/// byte-identically on both the wire vocabulary the paired
1713/// [`serde::Serialize`] derive emits and the diagnostic vocabulary the
1714/// [`RestartPolicy::as_str`] helper returns, and — because the paired
1715/// [`TryFrom<&str>`] / [`RestartPolicy::from_wire`] reverse-projection
1716/// axis parses the same `PascalCase` vocabulary — the direct two-way
1717/// `Self → String → Self` round-trip composes without the wire-vocab
1718/// intermediate hop the peer [`crate::CaixaKind`] owned-[`String`]
1719/// axis pair requires.
1720///
1721/// Pinned load-bearing by
1722/// [`tests::restart_policy_from_into_owned_string_routes_through_as_str_accessor`]
1723/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1724/// three-arm emit-set, plus a blanket `.into::<String>()` shape
1725/// witness) and
1726/// [`tests::restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm`]
1727/// (cross-axis partition pin against the paired owned-input
1728/// [`From<RestartPolicy> for &'static str`] impl and the sibling
1729/// [`ToString::to_string`] surface routed through [`std::fmt::Display`],
1730/// plus a `.iter().copied().map(String::from)` pipe witness over
1731/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
1732/// [`TryFrom<&str>`] on the owned-[`String`]'s [`String::as_str`]
1733/// borrow that closes the two-way `Self → String → Self` round-trip
1734/// on the trait-idiomatic owned-[`String`] forward + reverse axis
1735/// pair).
1736impl From<RestartPolicy> for String {
1737 fn from(policy: RestartPolicy) -> String {
1738 policy.as_str().to_owned()
1739 }
1740}
1741
1742/// Trait-idiomatic *borrowed-input, owned-`String` output* forward
1743/// projection on the second-of-two M2 OTP-shape closed-set typed enum
1744/// ([`RestartPolicy`]) — the fourth (and closing) corner of the
1745/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
1746/// projection family on this enum, mirror of the first-mover
1747/// [`From<&RestartStrategy> for String`] (579385f) that opened the
1748/// 2×2-completion corner on the sibling supervisor-level strategy
1749/// enum. Routes byte-for-byte through the substrate-primitive
1750/// [`RestartPolicy::as_str`] `pub const fn` accessor (via
1751/// [`str::to_owned`]) so every consumer that holds a borrowed
1752/// [`&RestartPolicy`] and needs an owned [`String`] — a future
1753/// `serde_json::Value::String(String::from(&policy))` structured-payload
1754/// composer over a borrowed field, a future `Iterator::map` over
1755/// `&[RestartPolicy]` that projects to owned keys through
1756/// `.iter().map(String::from)`, a future `HashMap::<String,
1757/// RestartPolicy>::from_iter` that keys off a borrowed-iteration axis
1758/// where dereferencing the policy would force an unnecessary `Copy` at
1759/// every step, the future wasm-operator's per-supervisor
1760/// `child_policies.iter().map(String::from).collect()` per-child post-
1761/// exit restart-decision diagnostic emit whose iteration axis is
1762/// borrowed by construction — reaches the same three-arm lifted
1763/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1764/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1765/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1766/// paired [`std::fmt::Display`], [`AsRef<str>`],
1767/// [`RestartPolicy::as_str`], and the three other trait-idiomatic
1768/// forward-projection impls
1769/// ([`From<RestartPolicy> for &'static str`],
1770/// [`From<&RestartPolicy> for &'static str`],
1771/// [`From<RestartPolicy> for String`]) already return.
1772///
1773/// Second peer on the substrate-wide trait-idiomatic *borrowed-input,
1774/// owned-`String` output* forward-projection family opened on
1775/// [`crate::supervisor::RestartStrategy`] (579385f) — closes the
1776/// `{Self, &Self} × {&'static str, String}` 2×2 projection corner on
1777/// both M2 OTP-shape sibling peers (the paired supervisor-level
1778/// sibling-restart-strategy axis and the per-child restart-decision-
1779/// policy axis), so the whole M2 OTP-shape axis pair now carries the
1780/// full four-corner family by construction. Rust's standard library
1781/// does not carry a blanket `impl<T: AsRef<str>> From<&T> for String`
1782/// (nor an `impl<T: fmt::Display> From<&T> for String`), so every
1783/// closed-set typed enum that carries the paired `AsRef<str>` /
1784/// `Display` / `From<Self> for &'static str` / `From<&Self> for
1785/// &'static str` / `From<Self> for String` quintuple but not the
1786/// borrowed-input owned-[`String`] axis forces every borrowed-input
1787/// owned-string call site through a `policy.as_str().to_owned()` /
1788/// `String::from(*policy)` (with a spurious `Copy`) /
1789/// `policy.to_string()` (through `Display`) detour whose type bounds
1790/// have no compile-time link to the substrate primitive.
1791///
1792/// Deliberately routes through the human-readable
1793/// [`RestartPolicy::as_str`] axis — for this enum the wire format
1794/// (`PascalCase`, tatara-lisp author surface `:restart Permanent`) and
1795/// the diagnostic byte-string share the same vocabulary by
1796/// construction (unlike the sibling [`crate::CaixaKind`] enum whose
1797/// two axes diverge), so the borrowed-input owned-[`String`]
1798/// projection lands byte-identically on both the wire vocabulary the
1799/// paired [`serde::Serialize`] derive emits and the diagnostic
1800/// vocabulary the [`RestartPolicy::as_str`] helper returns, and —
1801/// because the paired [`TryFrom<&str>`] / [`RestartPolicy::from_wire`]
1802/// reverse-projection axis parses the same `PascalCase` vocabulary —
1803/// the direct two-way `&Self → String → Self` round-trip composes
1804/// without the wire-vocab intermediate hop the peer
1805/// [`crate::CaixaKind`] axis pair requires.
1806///
1807/// The remaining thirteen closed-set typed enums on the caixa
1808/// substrate surface (`CaixaKind`, `CaixaDialeto`, `DepList`,
1809/// `PlacementStrategy`, `WitShape`, `RateLimitUnit`,
1810/// `PathShapeViolation`, `InvariantKind`, `ArchVerdict`, `Severity`,
1811/// `FixSafety`, `Semantic`, `FerriteRuntime`) are the future targets
1812/// of this 2×2-completion campaign — each carries the same paired
1813/// quintuple that this borrowed-input owned-[`String`] axis extends
1814/// onto.
1815///
1816/// Pinned load-bearing by
1817/// [`tests::restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
1818/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1819/// three-arm emit-set through the borrowed-input surface) and
1820/// [`tests::restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
1821/// (cross-axis partition pin against the paired owned-input owned-
1822/// [`String`] [`From<RestartPolicy> for String`] impl, the paired
1823/// borrowed-input owned-[`&'static str`] [`From<&RestartPolicy> for
1824/// &'static str`] impl, and the sibling [`ToString::to_string`]
1825/// surface routed through [`std::fmt::Display`], plus a direct round-
1826/// trip witness through [`TryFrom<&str>`] on the owned-[`String`]'s
1827/// [`String::as_str`] borrow that closes the two-way
1828/// `&Self → String → Self` round-trip on the trait-idiomatic
1829/// borrowed-input owned-[`String`] forward + reverse axis pair).
1830impl From<&RestartPolicy> for String {
1831 fn from(policy: &RestartPolicy) -> String {
1832 policy.as_str().to_owned()
1833 }
1834}
1835
1836/// Trait-idiomatic *owned-input, [`std::borrow::Cow<'static, str>`]
1837/// output* forward projection on the M2 OTP-shape per-child-restart
1838/// [`RestartPolicy`] closed-set typed enum — extends the substrate-
1839/// wide [`std::borrow::Cow<'static, str>`] forward-projection family
1840/// opened on [`crate::CaixaKind`] (99c1735 owned-input, d45c409
1841/// borrowed-input) and first extended off it onto the sibling M2
1842/// OTP-shape sibling-restart [`RestartStrategy`] (7dd28b3 owned-input,
1843/// 9b3e4b3 borrowed-input) onto the second (and second-of-two-in-M2)
1844/// M2 OTP-shape closed-set fieldless typed enum peer on the caixa
1845/// surface (`:children :restart`). Routes byte-for-byte through the
1846/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
1847/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
1848/// that binds a [`RestartPolicy`] through the trait-idiomatic
1849/// [`std::borrow::Cow<'static, str>`] axis — a future
1850/// `axum::response::IntoResponse` composer whose per-policy
1851/// diagnostic-body typing rules out the sibling [`AsRef<str>`]
1852/// borrowed return, a future M4 admission-webhook rejection body
1853/// that composes the accepted-policy enumeration through the same
1854/// `RestartPolicy::ALL.iter().map(Cow::from)` shape [`crate::CaixaKind`]
1855/// and [`RestartStrategy`] already route through, a generic `<T: for<'a>
1856/// Into<std::borrow::Cow<'static, str>>>`-bound structured-log
1857/// emitter on a per-child-policy diagnostic column — reaches the same
1858/// three-arm lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`]
1859/// / [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1860/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1861/// paired [`std::fmt::Display`], [`AsRef<str>`],
1862/// [`RestartPolicy::as_str`], and the four
1863/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
1864/// forward-projection corners already return.
1865///
1866/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
1867/// [`std::borrow::Cow::Owned`] — the substrate-primitive
1868/// [`RestartPolicy::as_str`] accessor's return carries the `&'static
1869/// str` lifetime by construction (each `match` arm resolves to a
1870/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const &str`
1871/// with static lifetime), so the zero-alloc borrowed arm is the
1872/// type-correct projection with no runtime allocation.
1873///
1874/// Rust's standard library carries no blanket `impl<T: AsRef<str>>
1875/// From<T> for Cow<'static, str>` (nor an `impl<T: fmt::Display>
1876/// From<T> for Cow<'static, str>`), so the paired sibling
1877/// [`From<RestartPolicy> for &'static str`] (9fb37d0),
1878/// [`From<RestartPolicy> for String`] (7851725), [`AsRef<str>`], and
1879/// [`std::fmt::Display`] surfaces do not implicitly extend to a
1880/// [`Cow<'static, str>`]-bound call site — every such site is forced
1881/// through a `Cow::Borrowed(policy.as_str())` /
1882/// `Cow::Owned(policy.to_string())` open-code whose type bounds have
1883/// no compile-time link back to the substrate primitive until this
1884/// lift.
1885///
1886/// Second peer to extend the substrate-wide trait-idiomatic
1887/// [`std::borrow::Cow<'static, str>`] forward-projection axis off the
1888/// top-level [`crate::CaixaKind`] enum (99c1735 owned-input, d45c409
1889/// borrowed-input) onto the wider substrate — closes the M2 OTP-shape
1890/// tier of the campaign (both sibling peers, `RestartStrategy` and
1891/// `RestartPolicy`, now carry the owned-input Cow<'static, str>
1892/// forward projection) so the remaining eleven peers
1893/// (`PlacementStrategy`, `RateLimitUnit`, `DepList`, `CaixaDialeto`,
1894/// and the outside-`caixa-core` peers `WitShape`, `PathShapeViolation`,
1895/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
1896/// `FerriteRuntime`) are the future targets. Every future arm addition
1897/// (an OTP-`intrinsic` fourth restart policy the ABSORPTION-ROADMAP
1898/// might reach for once the three canonical OTP restart policies stop
1899/// covering the substrate's discovered load-shape) grows the
1900/// Cow<'static, str> axis by construction through one caixa-core edit
1901/// on [`RestartPolicy::as_str`] — rather than a coordinated rewrite
1902/// across every future Cow<'static, str>-bound consumer site.
1903///
1904/// Pinned load-bearing by
1905/// [`tests::restart_policy_from_into_static_cow_str_routes_through_as_str_accessor`]
1906/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
1907/// against [`RestartPolicy::as_str`] across the three-arm
1908/// [`RestartPolicy::ALL`]) and
1909/// [`tests::restart_policy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
1910/// (cross-axis partition pin against the paired [`From<RestartPolicy>
1911/// for &'static str`], [`From<RestartPolicy> for String`], and
1912/// [`ToString`]-through-[`std::fmt::Display`] axes, plus a
1913/// `.iter().copied().map(Cow::from)` pipe witness over
1914/// [`RestartPolicy::ALL`] that materializes the three-arm accept-set
1915/// through the [`Cow<'static, str>`] axis alone and pins the
1916/// zero-alloc discipline on every element).
1917impl From<RestartPolicy> for std::borrow::Cow<'static, str> {
1918 fn from(policy: RestartPolicy) -> std::borrow::Cow<'static, str> {
1919 std::borrow::Cow::Borrowed(policy.as_str())
1920 }
1921}
1922
1923/// Trait-idiomatic *borrowed-input, [`std::borrow::Cow<'static, str>`]
1924/// output* forward projection on the M2 OTP-shape per-child-restart
1925/// [`RestartPolicy`] closed-set typed enum — the borrowed-input
1926/// companion to the paired owned-input
1927/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl
1928/// immediately above (0612398). Routes byte-for-byte through the same
1929/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
1930/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
1931/// that holds a `&RestartPolicy` and needs a
1932/// [`std::borrow::Cow<'static, str>`] — a
1933/// `RestartPolicy::ALL.iter().map(std::borrow::Cow::from).collect::<Vec<_>>()`
1934/// per-arm accept-set materializer (whose iterator over
1935/// `&'static [RestartPolicy]` yields `&RestartPolicy`, not
1936/// `RestartPolicy`, so the paired owned-input
1937/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] axis
1938/// alone forces every call site through an explicit `.copied()` /
1939/// dereference / [`Copy`]-bound restatement rather than the direct
1940/// trait-idiomatic projection), a future generic
1941/// `<T: for<'a> Into<std::borrow::Cow<'static, str>>>`-bound emitter
1942/// on a per-child-policy diagnostic column that walks the
1943/// `iter().map(Into::into)` shape verbatim, the future M4 admission-
1944/// webhook rejection body that composes the accepted-policy
1945/// enumeration from an iterated
1946/// `RestartPolicy::ALL.iter().map(|p| p.into())` pipe rather than a
1947/// per-arm `match p { … }` cascade — reaches the same three-arm
1948/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1949/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1950/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1951/// paired [`std::fmt::Display`], [`AsRef<str>`],
1952/// [`RestartPolicy::as_str`], the four
1953/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
1954/// forward-projection corners, and the paired owned-input
1955/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl
1956/// already return.
1957///
1958/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
1959/// [`std::borrow::Cow::Owned`] — the substrate-primitive
1960/// [`RestartPolicy::as_str`] accessor's return carries the
1961/// `&'static str` lifetime by construction (each `match` arm resolves
1962/// to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const &str`
1963/// with static lifetime), so the zero-alloc borrowed arm is the
1964/// type-correct projection with no runtime allocation.
1965///
1966/// Closes the `{Self, &Self}` input-shape corner on the M2 OTP-shape
1967/// per-child-restart [`std::borrow::Cow<'static, str>`] axis opened
1968/// one commit prior (0612398) on the paired owned-input
1969/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl —
1970/// second-of-two-in-M2 closed-set fieldless typed enum peer on the
1971/// caixa surface (paired with the sibling-restart [`RestartStrategy`]
1972/// which carries both {Self, &Self} × Cow<'static, str> corners since
1973/// 7dd28b3 owned-input, 9b3e4b3 borrowed-input), exactly as d45c409
1974/// closed it on the top-level [`crate::CaixaKind`] one commit after
1975/// the owning half (99c1735) landed. This lift closes the whole M2
1976/// OTP-shape tier of the substrate-wide [`Cow<'static, str>`]
1977/// forward-projection campaign on both input-shape corners
1978/// ({Self, &Self}) of both M2 OTP-shape sibling peers
1979/// ([`RestartStrategy`] and [`RestartPolicy`]), so the remaining
1980/// eleven substrate-wide peers (`PlacementStrategy`, `RateLimitUnit`,
1981/// `DepList`, `CaixaDialeto`, `WitShape`, `PathShapeViolation`,
1982/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
1983/// `FerriteRuntime`) become the future targets of the campaign. Rust's
1984/// standard library does not carry a blanket
1985/// `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor an
1986/// `impl<T: fmt::Display> From<&T> for Cow<'static, str>`), so every
1987/// closed-set fieldless typed enum peer on the substrate that carries
1988/// the paired owned-input [`Cow<'static, str>`] axis but not the
1989/// borrowed-input axis forces every borrowed-input
1990/// [`Cow<'static, str>`]-parameterized call site through a spurious
1991/// [`Copy`] deref (`std::borrow::Cow::from(*policy)`) or a
1992/// `std::borrow::Cow::Borrowed(policy.as_str())` open-code whose type
1993/// bounds have no compile-time link to the substrate primitive.
1994///
1995/// Pinned load-bearing by
1996/// [`tests::restart_policy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor`]
1997/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
1998/// against [`RestartPolicy::as_str`] across the three-arm
1999/// [`RestartPolicy::ALL`] through the borrowed-input surface) and
2000/// [`tests::restart_policy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
2001/// (cross-axis partition pin against the paired owned-input
2002/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`], the
2003/// paired borrowed-input owned-`&'static str`
2004/// [`From<&RestartPolicy> for &'static str`], and the paired
2005/// borrowed-input owned-`String` [`From<&RestartPolicy> for String`]
2006/// impls, plus a `.iter().map(std::borrow::Cow::from)` pipe witness
2007/// over [`RestartPolicy::ALL`] — whose iterator yields
2008/// `&RestartPolicy` by construction, so the borrowed-input
2009/// [`Cow<'static, str>`] axis is what routes the pipe through the
2010/// substrate-primitive [`RestartPolicy::as_str`] accessor with the
2011/// zero-alloc [`Cow::Borrowed`] arm by construction and without a
2012/// spurious [`Copy`] deref).
2013impl From<&RestartPolicy> for std::borrow::Cow<'static, str> {
2014 fn from(policy: &RestartPolicy) -> std::borrow::Cow<'static, str> {
2015 std::borrow::Cow::Borrowed(policy.as_str())
2016 }
2017}
2018
2019/// Trait-idiomatic *owned-input, [`Box<str>`] output* forward
2020/// projection on the M2 OTP-shape per-child-restart [`RestartPolicy`]
2021/// closed-set fieldless typed enum — extends the substrate-wide
2022/// `Box<str>` forward-projection campaign tier opened one commit prior
2023/// (69ef45c) on the paired sibling-restart [`RestartStrategy`] onto
2024/// the second (and third-and-final) M2 OTP-shape closed-set fieldless
2025/// typed enum peer on the caixa surface (`:children :restart`),
2026/// immediately after the paired `Cow<'static, str>` axis (0612398 /
2027/// b4dc55c) closed the
2028/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}` 2×3
2029/// corner on this enum. Routes byte-for-byte through the
2030/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2031/// accessor via [`Box::<str>::from`] on the returned `&'static str`,
2032/// so every consumer that binds a
2033/// `let key: Box<str> = policy.into();`-shaped call site — a
2034/// per-child metric-key materializer that stashes the policy
2035/// discriminator in a `Box<str>`-typed heap-owned scalar for cheap
2036/// clone (a shared-nothing per-policy accept-set the `caixa-operator`
2037/// hierarchical reconciliation scheduler's per-child restart-decision
2038/// fan-out carries), a future admission-webhook rejection body whose
2039/// per-arm `Box<str>` field composes from an owned `RestartPolicy`
2040/// handle — reaches the same three-arm lifted
2041/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2042/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2043/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2044/// sibling
2045/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
2046/// forward-projection corner already returns. Rust's standard library
2047/// carries `impl From<&str> for Box<str>` and
2048/// `impl From<String> for Box<str>` but no blanket
2049/// `impl<T: AsRef<str>> From<T> for Box<str>` (nor any
2050/// `impl<T: Copy, U: From<T>> From<T> for U` route from the enum), so
2051/// this axis is a distinct trait-idiomatic surface that a downstream
2052/// `RestartPolicy → Box<str>` `.into()` reaches through this impl and
2053/// no other — without a `Box::from(policy.as_str())` open-code whose
2054/// type bounds have no compile-time link back to the substrate
2055/// primitive.
2056///
2057/// Second peer on the substrate-wide trait-idiomatic [`Box<str>`]
2058/// forward-projection family opened on the sibling-restart
2059/// [`RestartStrategy`] (69ef45c / 59ae5dc) — closes the whole M2
2060/// OTP-shape tier of the substrate-wide [`Box<str>`] forward-
2061/// projection campaign's owned-input corner on both M2 OTP-shape
2062/// sibling peers ([`RestartStrategy`] and [`RestartPolicy`]), the
2063/// paired borrowed-input `From<&RestartPolicy> for Box<str>` closer
2064/// and the remaining fieldless-enum peers on the M3 mesh-shape /
2065/// outside-M3 caixa-core / render-side / outside-caixa-core tiers
2066/// are the future targets of the campaign.
2067///
2068/// Pinned load-bearing by
2069/// [`tests::restart_policy_from_into_box_str_routes_through_as_str_accessor`]
2070/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2071/// three-arm [`RestartPolicy::ALL`] emit-set on the owned-input
2072/// surface, plus a blanket-derived [`Into`] shape witness).
2073impl From<RestartPolicy> for Box<str> {
2074 fn from(policy: RestartPolicy) -> Box<str> {
2075 Box::<str>::from(policy.as_str())
2076 }
2077}
2078
2079/// Trait-idiomatic *borrowed-input, [`Box<str>`] output* forward
2080/// projection on the M2 OTP-shape per-child-restart [`RestartPolicy`]
2081/// closed-set fieldless typed enum — the borrowed-input companion to
2082/// the paired owned-input [`From<RestartPolicy> for Box<str>`] impl
2083/// (0a1b313, one commit prior) that closes the `{Self, &Self}`
2084/// input-shape corner of the substrate-wide [`Box<str>`] forward-
2085/// projection axis on the second (and third-and-final) M2 OTP-shape
2086/// closed-set fieldless typed enum peer on the caixa surface
2087/// (`:children :restart`), routing byte-for-byte through the
2088/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2089/// accessor via [`Box::<str>::from`] on the returned `&'static str`.
2090/// Every consumer that holds a `&RestartPolicy` and needs a
2091/// [`Box<str>`] — a
2092/// `RestartPolicy::ALL.iter().map(Box::<str>::from).collect::<Vec<_>>()`
2093/// per-arm accept-set materializer (whose iterator over
2094/// `&'static [RestartPolicy]` yields `&RestartPolicy`, not
2095/// `RestartPolicy`, so the paired owned-input
2096/// [`From<RestartPolicy> for Box<str>`] axis alone forces every
2097/// call site through an explicit [`Copy`] deref or a
2098/// `.copied()` restatement rather than the direct trait-idiomatic
2099/// projection), a per-child metric-key materializer holding
2100/// `&RestartPolicy` through a `caixa-operator` hierarchical
2101/// reconciliation scheduler's borrow lifetime, a future admission-
2102/// webhook rejection body whose per-arm `Box<str>` field composes
2103/// from a borrowed `&RestartPolicy` handle — reaches the
2104/// substrate-primitive [`RestartPolicy::as_str`] accessor through
2105/// this impl and no other, without a
2106/// `Box::<str>::from(policy.as_str())` open-code whose type bounds
2107/// have no compile-time link back to the substrate primitive.
2108///
2109/// Rust's standard library carries `impl From<&str> for Box<str>`
2110/// and `impl From<String> for Box<str>` but no blanket
2111/// `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
2112/// `Copy`-based `impl<T: Copy, U: From<&T> for U`), so every closed-
2113/// set fieldless typed enum peer on the substrate that carries the
2114/// paired owned-input `Box<str>` axis but not the borrowed-input
2115/// axis forces every borrowed-input `Box<str>`-parameterized call
2116/// site through a spurious [`Copy`] deref
2117/// (`Box::<str>::from((*policy).as_str())`) or a
2118/// `Box::<str>::from(policy.as_str())` open-code whose type bounds
2119/// have no compile-time link back to the substrate primitive.
2120///
2121/// Fourth (and closing) peer on the substrate-wide trait-idiomatic
2122/// [`Box<str>`] forward-projection family on the M2 OTP-shape tier
2123/// — closes the whole `{Self, &Self}` input-shape corner of the
2124/// [`Box<str>`] axis on both M2 OTP-shape sibling peers
2125/// ([`RestartStrategy`] and [`RestartPolicy`]), exactly as b4dc55c
2126/// closed the paired [`Cow<'static, str>`] axis one commit after
2127/// its owning half (0612398) landed on this enum. The remaining
2128/// fieldless-enum peers on the M3 mesh-shape / outside-M3 caixa-
2129/// core / render-side / outside-caixa-core tiers are the future
2130/// targets of the [`Box<str>`] campaign.
2131///
2132/// Pinned load-bearing by
2133/// [`tests::restart_policy_from_borrowed_into_box_str_routes_through_as_str_accessor`]
2134/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2135/// three-arm [`RestartPolicy::ALL`] emit-set on the borrowed-input
2136/// surface, plus a blanket-derived [`Into`] shape witness, a
2137/// cross-axis partition pin against the paired owned-input
2138/// [`From<RestartPolicy> for Box<str>`] and the sibling borrowed-
2139/// input `{&'static str, String, Cow<'static, str>}` return-shape
2140/// axes, and a `.iter().map(Box::<str>::from)` pipe witness over
2141/// [`RestartPolicy::ALL`] — whose iterator yields `&RestartPolicy`
2142/// by construction, so the borrowed-input [`Box<str>`] axis is
2143/// what routes the pipe through the substrate-primitive
2144/// [`RestartPolicy::as_str`] accessor without a spurious [`Copy`]
2145/// deref).
2146impl From<&RestartPolicy> for Box<str> {
2147 fn from(policy: &RestartPolicy) -> Box<str> {
2148 Box::<str>::from(policy.as_str())
2149 }
2150}
2151
2152// Fleet-wide dispatcher-catalog registrations for caixa's OTP
2153// supervisor surface — two more typed shadows over Erlang/OTP
2154// primitives the substrate now mechanically tracks (see
2155// theory/UNIFIED-COMPUTING-MODEL.md §VI for the roadmap +
2156// theory/TYPED-ABSORPTION.md for the absorption arc).
2157gen_platform::register_dispatcher!("caixa.restart-strategy", RestartStrategy);
2158gen_platform::register_dispatcher!("caixa.restart-policy", RestartPolicy);
2159
2160/// One child entry in the supervisor's `:children` list.
2161///
2162/// Every child references another caixa by `:caixa <nome>` + version
2163/// constraint. The supervisor materializes one ComputeUnit per entry.
2164#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2165#[serde(rename_all = "camelCase")]
2166pub struct ChildSpec {
2167 /// The child caixa's `:nome`. Must resolve via the same dependency
2168 /// resolution path as `:deps` (caixa-resolver).
2169 pub caixa: String,
2170
2171 /// Semver constraint (`"^0.1"`, `"~0.1.2"`, etc.) — same shape as
2172 /// [`crate::dep::Dep::versao`].
2173 pub versao: String,
2174
2175 /// Restart policy — an author-omitted slot degrades onto the
2176 /// substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`]
2177 /// (`permanent`, the Erlang/OTP worker-child default) through the
2178 /// [`Default for RestartPolicy`] impl this `#[serde(default)]` routes
2179 /// to.
2180 #[serde(default)]
2181 pub restart: RestartPolicy,
2182}
2183
2184impl ChildSpec {
2185 /// Substrate-canonical per-`:children` child-caixa `:nome` scalar
2186 /// accessor every consumer that reads the OTP-shape supervised
2187 /// child's identity keys off — returns the author-declared
2188 /// `:children :caixa` byte-string verbatim as a `&str`, borrowed
2189 /// from the typed slot's own [`String`] storage.
2190 ///
2191 /// The `:children :caixa` slot carries the DNS-1123 label — the
2192 /// child caixa's `:nome` — that every emitted cluster artifact
2193 /// derives its `metadata.name` from verbatim: the rendered
2194 /// `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name` per child, the
2195 /// [`crate::LABEL_PROGRAM`] label value on every child's pod
2196 /// identity, and the per-child K8s Service `metadata.name` the
2197 /// future wasm-operator (M3) provisions for inter-child supervision-
2198 /// tree wiring. Every downstream consumer that fans on the child's
2199 /// caixa-name keys off this scalar (the [`SupervisorSpec::validate`]
2200 /// per-child DNS-1123 gate at
2201 /// `require_valid_dns_1123_label(child.nome(), …)`, the per-child
2202 /// duplicate-detection [`crate::render::insert_first_seen`] key, the
2203 /// [`validate_no_self_supervision`] cross-slot equality check
2204 /// against the parent's `:nome`, every `SupervisorError` variant
2205 /// carrying the offending child caixa verbatim for `feira lint`
2206 /// rendering, the future wasm-operator's hierarchical reconciliation
2207 /// scheduler's per-child ComputeUnit-name projection, the future M4
2208 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2209 /// admission webhook).
2210 ///
2211 /// Prior to this lift the `.caixa` byte-string was accessed inline
2212 /// at seven sites in `supervisor.rs` — the DNS-1123 gate's
2213 /// `&child.caixa`, the four `SupervisorError::{ChildCaixaInvalid,
2214 /// EmptyChildVersion, ChildVersaoInvalid, DuplicateChildCaixa}`
2215 /// carriers' `child.caixa.clone()`, the dedup key's
2216 /// `child.caixa.as_str()`, and the [`validate_no_self_supervision`]
2217 /// `child.caixa == parent_nome` cross-slot check — seven open-coded
2218 /// field-accesses that expressed no compile-time link back to the
2219 /// typed slot. A future extension of the `:children :caixa` axis to
2220 /// a richer author surface (a per-cluster alias table the operator
2221 /// pins through a future `:placement`-scoped slot on the supervisor
2222 /// tree, a namespace-qualified rewrite the M4 CR materializer
2223 /// applies per-CR, a per-child overlay from the future `:children
2224 /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
2225 /// acknowledges) would have had to be threaded through every
2226 /// open-coded copy in lockstep or one consumer would silently
2227 /// disagree with the peers on which caixa a given child resolves to
2228 /// — a child-set lookup that treated the name as `"cart-worker"`
2229 /// while the peer duplicate-detector treated it as
2230 /// `"tenant-a/cart-worker"` would silently split the
2231 /// `DuplicateChildCaixa` membership-lookup diagnostic from the
2232 /// self-supervision detector's parent-equality check, a two-consumer
2233 /// split at the validator far from the source `caixa.lisp` with no
2234 /// field naming the identity-drift root cause. Lifting the resolution
2235 /// rule to a typed method on the substrate primitive means every
2236 /// downstream consumer of the Supervisor's per-`:children` identity
2237 /// surface reaches for exactly one typed dispatch — the resolver's
2238 /// accept-set migrates as a unit on any future axis addition.
2239 ///
2240 /// Sibling of the peer per-`:membros` [`crate::Membro::nome`]
2241 /// (4a32abf) member-caixa `:nome` scalar accessor on the M3
2242 /// mesh-slot surface — same "one typed dispatch on the substrate
2243 /// primitive, thin projections at each consumer" discipline extended
2244 /// onto the M2 supervisor-tree per-`:children` child-identity axis.
2245 /// The two typed axes (`Membro::nome` on the M3 Aplicacao side,
2246 /// `ChildSpec::nome` on the M2 Supervisor side) now share one
2247 /// accessor discipline for the shared substrate concept "another
2248 /// caixa referenced by `:nome`". Peer of the second M2 slot scalar
2249 /// accessor [`crate::UpgradeFromEntry::prior_versao`] (75d27a8) on
2250 /// the sibling per-`:upgrade-from :from` OTP-appup axis — the M2
2251 /// slot family's typed-accessor discipline now spans both the
2252 /// upgrade axis (`:upgrade-from`) and the supervision axis
2253 /// (`:children`), matching the closed M3 mesh-slot accessor family's
2254 /// shape. Named `nome()` to match the tatara-lisp author-surface
2255 /// term the field's docstring already reaches for ("The child
2256 /// caixa's `:nome`") and the peer [`crate::Membro::nome`] /
2257 /// [`crate::Caixa::nome`] / [`crate::dep::Dep::nome`] field-name
2258 /// discipline the substrate already carries — the accessor's name
2259 /// maps directly onto the canonical caixa-identity vocabulary rather
2260 /// than shadowing the field's storage-side `caixa` label.
2261 #[must_use]
2262 pub const fn nome(&self) -> &str {
2263 self.caixa.as_str()
2264 }
2265
2266 /// Substrate-canonical per-`:children` child-caixa `:versao` semver-
2267 /// requirement scalar accessor every consumer that reads the OTP-shape
2268 /// supervised child's version pin keys off — returns the author-declared
2269 /// `:children :versao` byte-string verbatim as a `&str`, borrowed from
2270 /// the typed slot's own [`String`] storage.
2271 ///
2272 /// The `:children :versao` slot carries the Cargo-shaped semver
2273 /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that pins
2274 /// which release of the supervised child caixa the OTP-shape supervisor
2275 /// tree materializes against — the same requirement grammar the peer
2276 /// `:deps :versao` / `:membros :versao` axes carry, resolved through the
2277 /// shared [`crate::render::require_valid_versao_requirement`] cascade
2278 /// and the shared [`crate::version::parse_requirement`] parser. Every
2279 /// downstream consumer that fans on the child's version pin keys off
2280 /// this scalar (the [`SupervisorSpec::validate`] per-child requirement
2281 /// gate at `require_valid_versao_requirement(child.versao_requirement(),
2282 /// …)`, the [`SupervisorError::ChildVersaoInvalid`] variant's carrier
2283 /// for `feira lint` rendering, every future per-cluster version-lock
2284 /// overlay the caixa-operator's hierarchical reconciliation scheduler
2285 /// pins through a future `:placement`-scoped supervisor-tree slot, the
2286 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2287 /// per-child version resolver, the future wasm-operator's per-child
2288 /// lacre BLAKE3-closure lookup at `ComputeUnit` materialization time).
2289 ///
2290 /// Prior to this lift the `.versao` byte-string was accessed inline at
2291 /// two `&str`-shaped sites in `caixa-core/src/supervisor.rs` — the
2292 /// [`SupervisorSpec::validate`] requirement-gate call
2293 /// `require_valid_versao_requirement(&child.versao, …)` and the
2294 /// [`SupervisorError::ChildVersaoInvalid`] carrier at
2295 /// `versao: child.versao.clone()` — two open-coded field-accesses that
2296 /// expressed no compile-time link back to the typed slot. A future
2297 /// extension of the `:children :versao` axis to a richer author surface
2298 /// (a per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
2299 /// flow, a lacre-projected concrete-version rewrite the operator
2300 /// materializes at CR-admission time, a future `:children :versao-lock`
2301 /// per-cluster override slot the wasm-operator's hierarchical
2302 /// reconciliation scheduler authors per-CR) would have had to be
2303 /// threaded through both open-coded copies in lockstep or one consumer
2304 /// would silently disagree with the peer on which release constraint a
2305 /// given child resolves to — the requirement-gate call reading
2306 /// `"^0.1"` while the error-body carrier read `"tenant-a-pin/^0.1"`
2307 /// would silently split the `ChildVersaoInvalid` diagnostic quote from
2308 /// the actual gate rejection input, a two-consumer split at the
2309 /// validator far from the source `caixa.lisp` with no field naming the
2310 /// version-pin drift root cause. Lifting the resolution rule to a typed
2311 /// method on the substrate primitive means every downstream
2312 /// requirement-facing consumer of the Supervisor's per-`:children`
2313 /// version-pin surface reaches for exactly one typed dispatch — the
2314 /// resolver's accept-set migrates as a unit on any future axis addition.
2315 ///
2316 /// Sibling of the peer per-`:membros` [`crate::Membro::versao_requirement`]
2317 /// (a40b0e3) member-caixa `:versao` scalar accessor on the M3 mesh-slot
2318 /// surface — same "one typed dispatch on the substrate primitive, thin
2319 /// projections at each consumer" discipline extended onto the M2
2320 /// supervisor-tree per-`:children` child-version-pin axis. The two typed
2321 /// axes (`Membro::versao_requirement` on the M3 Aplicacao side,
2322 /// `ChildSpec::versao_requirement` on the M2 Supervisor side) now share
2323 /// one accessor discipline for the shared substrate concept "another
2324 /// caixa referenced by a Cargo-shaped semver requirement". Peer of the
2325 /// sibling per-`:children` [`ChildSpec::nome`] (57c61d0) child-caixa
2326 /// `:nome` scalar accessor — the pair
2327 /// `(nome(), versao_requirement())` jointly projects the
2328 /// `(caixa, versao)` field pair every OTP-shape supervisor-tree consumer
2329 /// that fans on per-child identity + version pin keys off, closing the
2330 /// last unlifted per-`:children` `String`-carry axis so every downstream
2331 /// per-`:children` reader now routes through a typed dispatch on the
2332 /// substrate primitive. Named `versao_requirement()` rather than
2333 /// `versao()` because the field's storage-side `.versao` label is
2334 /// already the author-surface term (`:versao`); the accessor's name
2335 /// carries the semantic role — the semver *requirement* string the
2336 /// shared [`crate::version::parse_requirement`] entry-point consumes —
2337 /// so a raw field access and a typed dispatch read differently at every
2338 /// consumer site. Matches the peer [`crate::Membro::versao_requirement`]
2339 /// naming discipline verbatim.
2340 #[must_use]
2341 pub const fn versao_requirement(&self) -> &str {
2342 self.versao.as_str()
2343 }
2344
2345 /// Substrate-canonical per-`:children` `:restart` OTP-shaped
2346 /// per-child post-exit restart-decision policy scalar accessor every
2347 /// consumer that dispatches on the supervised child's post-exit
2348 /// reconcile posture keys off — returns the author-declared
2349 /// `:children :restart` variant verbatim as a [`RestartPolicy`],
2350 /// `Copy`-projected from the typed slot's own [`RestartPolicy`]
2351 /// storage.
2352 ///
2353 /// The `:children :restart` slot carries the closed-set OTP-shaped
2354 /// per-child restart-decision policy discriminator
2355 /// ([`RestartPolicy::Permanent`] — always restart, the OTP `permanent`
2356 /// worker-child default; [`RestartPolicy::Transient`] — restart only
2357 /// on abnormal exit, the OTP `transient` clean-completion-aware
2358 /// default; [`RestartPolicy::Temporary`] — never restart, the OTP
2359 /// `temporary` one-shot default) that every downstream consumer of
2360 /// the Supervisor's per-child post-exit reconcile branch keys off.
2361 /// Every future downstream consumer that fans on the per-child
2362 /// restart-decision keys off this scalar (the future `feira app
2363 /// graph` per-child restart column, the future wasm-operator's
2364 /// per-child post-exit restart-decision branch, the future M4
2365 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2366 /// admission webhook, the `caixa-operator`'s hierarchical
2367 /// reconciliation scheduler's per-child post-exit reconcile branch,
2368 /// the [`RestartPolicy::as_str`] `Serialize`-derive-pinning path the
2369 /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
2370 /// pin threads through).
2371 ///
2372 /// Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
2373 /// (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
2374 /// scalar accessor and the M3 mesh-slot
2375 /// [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
2376 /// [`crate::PlacementStrategy`] distribution-strategy scalar accessor
2377 /// — same "one typed dispatch on the substrate primitive,
2378 /// `Copy`-projected closed-set enum-arm discriminator that partitions
2379 /// the downstream renderer's per-arm fan-out" discipline extended
2380 /// onto the M2 supervisor-slot per-`:children` restart-decision-policy
2381 /// `Copy`-composite-enum scalar axis. Third axis on the per-`:children`
2382 /// [`ChildSpec`] type — companion to the sibling per-`:children`
2383 /// [`ChildSpec::nome`] (57c61d0) child-caixa `:nome` scalar accessor
2384 /// and the per-`:children` [`ChildSpec::versao_requirement`]
2385 /// (2c053c8) child-caixa `:versao` semver-requirement scalar accessor
2386 /// on the sibling `String`-carry axes. The triple
2387 /// `(nome(), versao_requirement(), restart())` jointly projects the
2388 /// `(caixa, versao, restart)` field trio every OTP-shape supervisor-
2389 /// tree consumer that fans on per-child identity + version pin +
2390 /// restart-decision keys off, closing the last unlifted per-`:children`
2391 /// axis so every downstream per-`:children` reader now routes through
2392 /// a typed dispatch on the substrate primitive. Named `restart()` to
2393 /// match the storage field's name and the author-surface
2394 /// `:children :restart` slot term verbatim; the accessor's identity
2395 /// name maps onto the canonical OTP-shape per-child restart-decision-
2396 /// policy vocabulary the [`RestartPolicy`] enum's docstring already
2397 /// carries.
2398 ///
2399 /// Declared `pub const fn` to close the last non-`const`
2400 /// `Copy`-return raw-field-getter posture on the M2
2401 /// per-`:children` [`ChildSpec`] substrate-primitive surface — peer
2402 /// of the sibling M2 per-`:supervisor`
2403 /// [`SupervisorSpec::estrategia`] (converted in this commit)
2404 /// `Copy`-composite-enum accessor, the sibling M2 per-`:supervisor`
2405 /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
2406 /// already lifted, and the peer M3 mesh-slot per-`:entrada`
2407 /// [`crate::Entrada::port`] (bafa004) / per-`:placement`
2408 /// [`crate::Placement::estrategia`] (bafa004) `Copy`-return
2409 /// `pub const fn` scalar accessors on the sibling M3 surface. Every
2410 /// downstream substrate-side `const`-context consumer of the
2411 /// per-`:children` restart-decision-policy scalar (a future
2412 /// module-scope `const _:() = assert!(matches!(child.restart(),
2413 /// RestartPolicy::Permanent))` invariant pin on a typed fixture, a
2414 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
2415 /// admission-webhook `const fn` per-child restart-decision floor
2416 /// over a typed [`ChildSpec`], any future `const fn` supervisor-tree
2417 /// composer over the substrate primitive that fans on the per-child
2418 /// restart-decision policy at compile time) now reaches through the
2419 /// same typed dispatch on the substrate primitive at const-eval
2420 /// time as at runtime. A future non-`Copy`-return promotion of the
2421 /// scalar (an `Option<RestartPolicy>`-shape migration on the
2422 /// per-child restart-decision axis once heterogeneous per-cluster
2423 /// restart-policy overlays land, a per-tenant restart-policy-alias
2424 /// table the M4 CR materializer resolves per-CR) that would drop
2425 /// the `const` qualifier fails the fail-before-pass-after pin
2426 /// [`tests::child_spec_restart_accessor_is_const_fn`] at caixa-core
2427 /// build time rather than surfacing as a downstream consumer
2428 /// regression.
2429 #[must_use]
2430 pub const fn restart(&self) -> RestartPolicy {
2431 self.restart
2432 }
2433}
2434
2435/// Supervisor-typed slots that live alongside the standard Caixa
2436/// fields when `:kind Supervisor`. Held flat in [`crate::Caixa`] so
2437/// the manifest stays a single typed form; this struct exists for
2438/// validation + conversion.
2439#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2440#[serde(rename_all = "camelCase")]
2441pub struct SupervisorSpec {
2442 /// Restart strategy. Defaults to [`RestartStrategy::OneForOne`].
2443 #[serde(default)]
2444 pub estrategia: RestartStrategy,
2445
2446 /// Max restarts within [`Self::restart_window`] before the
2447 /// supervisor itself terminates (and its parent supervisor decides
2448 /// what to do). Default 5.
2449 #[serde(default = "default_max_restarts")]
2450 pub max_restarts: u32,
2451
2452 /// Sliding window for `max_restarts`. Authored as a duration
2453 /// string (`"60s"`, `"5m"`); absent = "never reset". A `Some(0s)`
2454 /// is rejected by [`Self::validate`] — Erlang/OTP's
2455 /// `MaxIntensity / Period` invariant requires a positive window
2456 /// (a zero-period supervisor either trips on the first failure or
2457 /// never trips, depending on operator interpretation, neither of
2458 /// which is the author's intent). Omit the slot to express "no
2459 /// reset"; carry a positive duration to express the sliding window.
2460 #[serde(
2461 default,
2462 skip_serializing_if = "Option::is_none",
2463 with = "duration_codec"
2464 )]
2465 pub restart_window: Option<Duration>,
2466
2467 /// Static children. Empty for `SimpleOneForOne` (children added
2468 /// dynamically); required for the other three strategies.
2469 #[serde(default)]
2470 pub children: Vec<ChildSpec>,
2471}
2472
2473const fn default_max_restarts() -> u32 {
2474 // Route the private serde-`#[serde(default = "…")]` helper through
2475 // the substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] typed
2476 // `pub const` rather than the raw `5` literal — one source of truth
2477 // for the Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
2478 // default across the two production consumers that currently
2479 // dispatch on it (this helper via `#[serde(default = "…")]` on
2480 // `SupervisorSpec::max_restarts` and the [`Default for SupervisorSpec`]
2481 // impl at line 962). Pinned by
2482 // `default_max_restarts_helper_routes_through_lifted_default` +
2483 // `supervisor_spec_default_max_restarts_routes_through_lifted_default`
2484 // in the tests module; peer of the sibling caixa-core
2485 // [`crate::manifest::Caixa::supervisor_view`] `unwrap_or(…)` fold
2486 // that now routes its author-omitted `:max-restarts` arm through
2487 // the same lifted constant.
2488 SUPERVISOR_MAX_RESTARTS_DEFAULT
2489}
2490
2491/// Substrate-canonical Erlang/OTP-shaped `MaxIntensity` restart-budget-
2492/// count default for the `:supervisor :max-restarts` axis — the
2493/// canonical `{intensity, 5, 60}` `MaxIntensity` half of Learn You Some
2494/// Erlang's worker-supervisor default, extracted as a typed `pub const`
2495/// so every substrate-side consumer that resolves "what
2496/// [`SupervisorSpec::max_restarts`] value does an author-omitted
2497/// `:max-restarts` slot degrade onto?" reaches for exactly one
2498/// substrate-primitive `u32`.
2499///
2500/// The `:max-restarts` default axis has two production consumers on the
2501/// substrate side today (both prior to this lift folded onto raw `5`
2502/// literals with no compile-time link back to a shared truth): the
2503/// serde-`#[serde(default = "default_max_restarts")]` helper on
2504/// [`SupervisorSpec::max_restarts`] that every author-omitted
2505/// `:supervisor :max-restarts` slot lands in past the derive-macro's
2506/// wire-format compose, and the [`crate::manifest::Caixa::supervisor_view`]
2507/// `.max_restarts().unwrap_or(5)` fold that every downstream consumer of
2508/// the composed [`SupervisorSpec`] altitude reaches through
2509/// (`feira app graph`, the future wasm-operator's per-supervisor
2510/// restart-intensity counter, the future M4
2511/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2512/// webhook, the caixa-operator's hierarchical reconciliation scheduler).
2513/// A pair of open-coded `5`s across two files that expressed no
2514/// compile-time link back to the shared OTP-canonical default — a
2515/// future rebrand of the default (a tightening to Elixir's
2516/// `Supervisor.max_restarts: 3`, a widening to a per-cluster overlay
2517/// the operator pins through a future
2518/// `:supervisor :max-restarts-overrides` slot the MESH-COMPOSITION
2519/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
2520/// plain `u32` count to a richer `{MaxR, MaxT}` per-child-cohort
2521/// restart-budget-partition once the INSPIRATIONS §II.2 Erlang/OTP
2522/// per-child-cohort roadmap lands) would have had to be threaded
2523/// through both open-coded copies in lockstep or the wire-format
2524/// author-omitted arm and the view-construction author-omitted arm
2525/// would silently disagree on which restart-budget an omitted
2526/// `:max-restarts` resolves to (an author writing `:supervisor
2527/// (:max-restarts ())` would round-trip through serde with the new
2528/// default while `supervisor_view` silently continued to compose the
2529/// stale `5`, or vice versa), a two-consumer split at the composition
2530/// boundary far from the source `caixa.lisp` with no field naming the
2531/// default-drift root cause. Lifting the resolution rule to a typed
2532/// `pub const` on the substrate primitive means every downstream
2533/// consumer of the per-Supervisor default-restart-budget-count surface
2534/// reaches for exactly one substrate-primitive `u32` — the resolver's
2535/// accepted value migrates as a unit on any future axis change.
2536///
2537/// The `5` value pins Learn You Some Erlang's `{intensity, 5, 60}`
2538/// worker-supervisor default (the closest canonical OTP-shape
2539/// production reference the substrate carries, matching the sibling
2540/// `60s` `Period` default the [`Default for SupervisorSpec`] impl pairs
2541/// this constant with on the paired sliding-window axis). Two orders of
2542/// magnitude below the [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` ceiling
2543/// (the upper bracket on the same axis, sibling of this lower default;
2544/// both are typed `u32` const bounds on the `:supervisor :max-restarts`
2545/// axis and now share one accessor discipline on the substrate) and
2546/// above the OTP-`supervisor` callback-module `MaxR = 1` minimum-
2547/// restart floor — the "one restart, then escalate" default is
2548/// deliberately loose enough to absorb a short burst of transient
2549/// child failures without escalating past the supervisor's parent
2550/// while remaining tight enough to trip the `MaxIntensity / Period`
2551/// ratio's escalation on a genuinely-stuck child within the sibling
2552/// `60s` sliding window.
2553///
2554/// Lifted as a typed `pub const` so the bound has exactly one source
2555/// of truth — the serde-side wire-format author-omitted arm at
2556/// [`default_max_restarts`], the [`Default for SupervisorSpec`] impl's
2557/// struct-literal default field, and the caixa-core
2558/// [`crate::manifest::Caixa::supervisor_view`] fold's author-omitted
2559/// arm all read from one place. Same shape every other typed default
2560/// in this crate carries (the sibling
2561/// [`SUPERVISOR_MAX_RESTARTS_MAX`] upper cap on the same axis, the
2562/// paired [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the
2563/// sibling `:restart-window` axis, and the peer
2564/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
2565/// per-renderer defaults on the caixa-flux / caixa-helm rendering
2566/// axes).
2567pub const SUPERVISOR_MAX_RESTARTS_DEFAULT: u32 = 5;
2568
2569/// Upper-bound ceiling on the `:supervisor :max-restarts` axis — every
2570/// validated [`SupervisorSpec::max_restarts`] past
2571/// [`SupervisorSpec::validate`] lies in `1..=SUPERVISOR_MAX_RESTARTS_MAX`.
2572///
2573/// The typed field is `u32` (the zero-floor arm
2574/// [`SupervisorError::ZeroMaxRestarts`] already brackets the bottom edge),
2575/// so a programmatic struct literal
2576/// (`SupervisorSpec { max_restarts: u32::MAX, .. }`) and the equivalent
2577/// author-surface form (`:max-restarts 4294967295` or any
2578/// `:max-restarts 100000`-shape typo landing in the slot) both round-trip
2579/// cleanly through serde — a structurally unbounded `u32` ceiling. The
2580/// runtime substrate consuming the value (Erlang/OTP's
2581/// `MaxIntensity / Period` ratio, the future wasm-operator's
2582/// per-supervisor restart-intensity counter, the M4
2583/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook)
2584/// then turned a typed `:max-restarts` policy into a no-op supervisor: the
2585/// escalation threshold is structurally so high that no realistic
2586/// restarts-per-`:restart-window` traffic shape can reach it, the
2587/// supervisor never escalates to its parent, and a bad child can loop
2588/// inside the window indefinitely with the parent supervisor structurally
2589/// never receiving the "this subtree has exceeded its restart budget"
2590/// signal the typed slot is meant to express — the canonical
2591/// "supervisor intensity declared, no escalation" footgun, exactly the
2592/// peer of the [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap
2593/// on the `:politicas :circuit-breaker :max-failures` axis (both are
2594/// "trip the next-higher protection layer after N events in a rolling
2595/// window" counters with identical degenerate-at-the-high-end shape).
2596///
2597/// The `1000` ceiling matches the sibling
2598/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] (the closest
2599/// peer — same "events-per-window trip threshold" semantics, same `u32`
2600/// type, same no-op-at-the-high-end failure mode) so the M4
2601/// `mesh.pleme.io/v1alpha1/Supervisor` / `.../Aplicacao` CR materializers
2602/// and the future wasm-operator's per-supervisor restart-intensity
2603/// counter reach for either field knowing the value is in `1..=1000`
2604/// without re-validating at the reconciler layer. The cap sits two
2605/// orders of magnitude above every documented Erlang/OTP production
2606/// playbook recommendation (Learn You Some Erlang's
2607/// `{intensity, 5, 60}` worker-supervisor default, Elixir's `Supervisor`
2608/// `max_restarts: 3` default, OTP's `supervisor` callback module
2609/// `MaxR = 1` / `MaxT = 5` "minimal-restart" default, Riak Core's
2610/// typical `MaxR ∈ 5..=100`, RabbitMQ's broker-supervisor `MaxR = 5`
2611/// default) and below the clearly-pathological "effectively no
2612/// escalation" floor (`10_000`, `100_000`, `u32::MAX`): a value the
2613/// author can plausibly want at hyperscale (a long-running supervisor
2614/// over a very-flaky pool tolerating thousands of transient restarts
2615/// before escalating), but a hard wall above which the typed policy is
2616/// structurally a no-op carried verbatim on every emitted child-restart
2617/// reconciliation contract.
2618///
2619/// Lifted as a typed `pub const` so the bound has exactly one source of
2620/// truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
2621/// materializer's admission webhook and the wasm-operator-side
2622/// per-supervisor restart-intensity reconciler read from one place. Same
2623/// shape every other typed upper bound in this crate carries
2624/// ([`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
2625/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
2626/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
2627/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2628/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2629/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2630pub const SUPERVISOR_MAX_RESTARTS_MAX: u32 = 1000;
2631
2632/// Upper-bound ceiling on the `:supervisor :restart-window` axis —
2633/// every validated `Some(`[`SupervisorSpec::restart_window`]`)` past
2634/// [`SupervisorSpec::validate`] lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
2635/// (inclusive on both ends, integer-millisecond magnitudes by the
2636/// canonical-form gate immediately preceding).
2637///
2638/// The typed field is `Option<Duration>` (the zero-floor arm
2639/// [`SupervisorError::RestartWindowZero`] already rejects
2640/// `Some(Duration::ZERO)`, and the canonical-form arm
2641/// [`SupervisorError::RestartWindowNotCanonical`] already rejects
2642/// sub-millisecond residue), so a programmatic struct literal
2643/// (`SupervisorSpec { restart_window: Some(Duration::from_secs(86_400)),
2644/// .. }` — 24h) and the equivalent author-surface form
2645/// (`(:supervisor (:restart-window "24h"))` — the shared duration codec
2646/// emits `"<n>h"` for any integer-hour magnitude) both round-trip
2647/// cleanly through serde — a structurally unbounded `Duration` ceiling.
2648/// A `:restart-window` value far above the documented Erlang/OTP
2649/// `MaxIntensity / Period` production-playbook band (Learn You Some
2650/// Erlang's `{intensity, 5, 60}` worker-supervisor `Period = 60s`
2651/// default, Elixir's `Supervisor` `max_seconds: 5` default, OTP's
2652/// `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's
2653/// `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default)
2654/// degenerates the supervisor's restart-intensity counter into a
2655/// lifetime counter: the rolling failure-counting window is structurally
2656/// so long that transient restarts are never forgotten, so the
2657/// `MaxIntensity / Period` ratio degenerates from "trip the parent
2658/// supervisor when the child has exceeded its restart budget *within
2659/// the recent window*" to "trip the parent when the child has exceeded
2660/// its restart budget *over its lifetime*" — every transient restart
2661/// counts against the budget forever, the supervisor's reset semantic
2662/// never reaches the child, and the typed `:restart-window` slot
2663/// becomes a no-op rolling window carried on every emitted hierarchical
2664/// reconciliation contract. The canonical
2665/// rolling-window-degenerates-to-lifetime-counter footgun the sibling
2666/// [`crate::POLICY_BREAKER_WINDOW_MAX`] cap closes on the peer
2667/// `:politicas :circuit-breaker :window` axis with identical shape (both
2668/// are "rolling failure-counting window with a per-`Period` reset" Duration
2669/// axes whose lifetime-counter degenerate at the high end is the same
2670/// "the reset semantic never fires" CSE invariant violation).
2671///
2672/// The `1h` (3600s = `3_600_000` ms) ceiling matches the largest unit
2673/// the shared duration codec emits (`"<n>h"` for any integer-hour
2674/// magnitude) — every value in the canonical authoring form's
2675/// `<integer><unit>` grammar at or below this cap renders to a clean
2676/// canonical string — and matches the three sibling typed-`Duration`
2677/// caps already lifted to this surface
2678/// ([`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
2679/// [`crate::POLICY_BREAKER_WINDOW_MAX`]). All four typed-`Duration`
2680/// axes — per-process `:limits :wall-clock`, per-edge `:politicas
2681/// :timeout`, per-breaker `:politicas :circuit-breaker :window`, and
2682/// per-supervisor `:supervisor :restart-window` — now share a single
2683/// uniform top edge at the codec's largest emitted unit so the next
2684/// typed-slot wiring (the future wasm-operator's per-supervisor
2685/// `MaxIntensity / Period` reconciler, the M4
2686/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2687/// webhook, the `caixa-operator`'s hierarchical reconciliation
2688/// scheduler) reaches for any of the four knowing the value is in
2689/// `1ms..=1h` without re-validating at the renderer layer. The cap sits
2690/// two orders of magnitude above every documented Erlang/OTP / Elixir /
2691/// Riak Core / RabbitMQ production-playbook recommendation band
2692/// (`5s..=300s`) and below the clearly-pathological "rolling window
2693/// degenerates to lifetime counter" floor (`24h`, `7d`, `Duration::MAX`):
2694/// a value the author can plausibly want for a very-low-traffic
2695/// long-tail failure-restart window over a hyperscale-flaky child pool,
2696/// but a hard wall above which the rolling-window contract is
2697/// structurally a lifetime-counter contract.
2698///
2699/// Lifted as a typed `pub const` so the bound has exactly one source
2700/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
2701/// materializer's admission webhook, the wasm-operator-side
2702/// per-supervisor `MaxIntensity / Period` reconciler, and the
2703/// `caixa-operator`'s hierarchical reconciliation scheduler all read
2704/// from one place. Same shape every other typed upper bound in this
2705/// crate carries ([`SUPERVISOR_MAX_RESTARTS_MAX`],
2706/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
2707/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
2708/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
2709/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2710/// [`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
2711/// [`crate::POLICY_BREAKER_WINDOW_MAX`],
2712/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2713/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2714pub const SUPERVISOR_RESTART_WINDOW_MAX: Duration = Duration::from_secs(3600);
2715
2716/// Substrate-canonical Erlang/OTP-shaped `Period` sliding-window-duration
2717/// default for the `:supervisor :restart-window` axis — the canonical
2718/// `{intensity, 5, 60}` `Period` half of Learn You Some Erlang's
2719/// worker-supervisor default, extracted as a typed `pub const` so every
2720/// substrate-side consumer that resolves "what
2721/// [`SupervisorSpec::restart_window`] value does an author-omitted
2722/// `:restart-window` slot degrade onto?" reaches for exactly one
2723/// substrate-primitive [`Duration`].
2724///
2725/// The `:restart-window` default axis has one production consumer on the
2726/// substrate side today: the [`Default for SupervisorSpec`] impl's
2727/// struct-literal `restart_window` field, which prior to this lift folded
2728/// onto a raw `Duration::from_secs(60)` literal with no compile-time link
2729/// back to the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity`
2730/// half of the same `{intensity, 5, 60}` OTP-canonical default. The
2731/// [`crate::manifest::Caixa::supervisor_view`] fold deliberately does
2732/// *not* fall back to this default on the sibling `:restart-window` axis
2733/// — an author-omitted `:supervisor :restart-window` composes to
2734/// `restart_window: None` (the shared codec's soft-swallow shape),
2735/// keeping author-declared intent ("no reset — never escalate on rolling
2736/// window") distinct from the [`Default for SupervisorSpec`] "canonical
2737/// 60s Period" arm every programmatic `SupervisorSpec::default()` caller
2738/// resolves to. Prior to this lift the paired `{intensity, 5, 60}` OTP
2739/// default was split across two files with no compile-time link between
2740/// the halves: [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] pinned the
2741/// `MaxIntensity` half at the substrate primitive while the `Period`
2742/// half rode as an open-coded literal at the composition site, so a
2743/// future coherent rebrand of the paired canonical (a tightening to
2744/// Elixir's `{max_restarts: 3, max_seconds: 5}`, a widening to a
2745/// per-cluster overlay the operator pins through a future
2746/// `:supervisor :restart-window-overrides` slot the MESH-COMPOSITION
2747/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
2748/// paired constants to a per-child-cohort `{MaxR, MaxT}` restart-budget-
2749/// partition once the INSPIRATIONS §II.2 Erlang/OTP per-child-cohort
2750/// roadmap lands) would have had to migrate the `MaxIntensity` half
2751/// through the lifted constant and the `Period` half through a raw
2752/// literal in lockstep or the two halves of the same OTP-canonical
2753/// default would silently drift out of pairing. Lifting the resolution
2754/// rule to a typed `pub const` on the substrate primitive means the
2755/// paired OTP-canonical default migrates as one unit on any future
2756/// axis change.
2757///
2758/// The `60s` value pins Learn You Some Erlang's `{intensity, 5, 60}`
2759/// worker-supervisor default (the closest canonical OTP-shape
2760/// production reference the substrate carries, matching the paired
2761/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5` `MaxIntensity` half this
2762/// constant is the `Period` denominator of on the same
2763/// `MaxIntensity / Period` restart-intensity ratio). Two orders of
2764/// magnitude below the [`SUPERVISOR_RESTART_WINDOW_MAX`] `3600s`
2765/// (`1h`) ceiling (the upper bracket on the same axis, sibling of
2766/// this lower default; both are typed [`Duration`] const bounds on the
2767/// `:supervisor :restart-window` axis and now share one accessor
2768/// discipline on the substrate) and above the OTP-`supervisor`
2769/// callback-module `MaxT = 5` seconds "minimal-window" floor — the "60s
2770/// rolling window" default is deliberately loose enough to absorb a
2771/// short burst of transient child failures without escalating past the
2772/// supervisor's parent while remaining tight enough for the paired
2773/// `MaxIntensity / Period` ratio's escalation to trip on a genuinely-
2774/// stuck child within a human-scale observation window.
2775///
2776/// Lifted as a typed `pub const` so the paired OTP-canonical default has
2777/// exactly one source of truth on each half — the sibling
2778/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half and this
2779/// `Period` `60s` half now share the same substrate-primitive lift
2780/// discipline. Same shape every other typed default in this crate
2781/// carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] paired
2782/// `MaxIntensity` half on the same OTP-canonical `{intensity, 5, 60}`,
2783/// the sibling [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the same
2784/// axis, and the peer [`crate::render::DEFAULT_NAMESPACE`] /
2785/// [`crate::render::DEFAULT_LIBRARY_NAME`] per-renderer defaults on the
2786/// caixa-flux / caixa-helm rendering axes).
2787pub const SUPERVISOR_RESTART_WINDOW_DEFAULT: Duration = Duration::from_secs(60);
2788
2789/// Substrate-canonical Erlang/OTP-shaped sibling-restart-strategy default
2790/// for the `:supervisor :estrategia` axis — the canonical `one_for_one`
2791/// half of Learn You Some Erlang's `{one_for_one, intensity, 5, 60}`
2792/// worker-supervisor default, extracted as a typed `pub const` so every
2793/// substrate-side consumer that resolves "what
2794/// [`SupervisorSpec::estrategia`] variant does an author-omitted
2795/// `:estrategia` slot degrade onto?" reaches for exactly one substrate-
2796/// primitive [`RestartStrategy`].
2797///
2798/// The `:estrategia` default axis has three production consumers on the
2799/// substrate side today: the [`Default for RestartStrategy`] impl's
2800/// return arm, the [`Default for SupervisorSpec`] impl's struct-literal
2801/// `estrategia` field, and the
2802/// [`crate::manifest::Caixa::supervisor_view`] fold's
2803/// `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)` `Option<RestartStrategy>`
2804/// collapse arm — three entry points onto the same OTP-canonical
2805/// `one_for_one` value that prior to this lift folded onto a raw
2806/// `Self::OneForOne` arm at the [`Default for RestartStrategy`] impl and
2807/// implicit `RestartStrategy::default()` routes at the sibling consumers,
2808/// with no compile-time link back to the paired
2809/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` half + the paired
2810/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` half of the same
2811/// `{one_for_one, intensity, 5, 60}` OTP-canonical default. The paired
2812/// triple was split across three altitudes with no compile-time link
2813/// between the halves: the `MaxIntensity` half rode through the lifted
2814/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant (b698ec0) and the `Period`
2815/// half rode through the lifted [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2816/// constant (f7dcd0e) while the `one_for_one` half rode as an open-coded
2817/// discriminator at the [`Default for RestartStrategy`] impl, so a future
2818/// coherent rebrand of the triple (Elixir's `{:one_for_one,
2819/// max_restarts: 3, max_seconds: 5}` — same strategy, different
2820/// intensity/period; an OTP `rest_for_one` widening once the substrate
2821/// discovers startup-order-coupled child cohorts as the more common
2822/// worker-supervisor default; a per-cluster overlay the operator pins
2823/// through a future `:estrategia-overrides` slot the MESH-COMPOSITION
2824/// §III.2 supervision-canary roadmap acknowledges) would have had to
2825/// migrate the `MaxIntensity` + `Period` halves through the lifted
2826/// constants and the `one_for_one` half through an open-coded arm in
2827/// lockstep or the three halves of the same OTP-canonical default would
2828/// silently drift out of pairing. Lifting the resolution rule to a typed
2829/// `pub const` on the substrate primitive means the paired OTP-canonical
2830/// worker-supervisor default migrates as one unit on any future axis
2831/// change.
2832///
2833/// The [`RestartStrategy::OneForOne`] value pins Learn You Some Erlang's
2834/// `{one_for_one, intensity, 5, 60}` worker-supervisor default (the
2835/// closest canonical OTP-shape production reference the substrate
2836/// carries, matching the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5`
2837/// `MaxIntensity` half and the paired [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2838/// `60s` `Period` half). The `one_for_one` strategy — restart only the
2839/// failed child, leaving siblings untouched — is the default for tree-of-
2840/// independent-workers use cases the substrate's [`RestartStrategy`]
2841/// discriminator's own docstring already carries as the default arm; it
2842/// composes with the `{5, 60}` restart-intensity ratio to name the same
2843/// substrate-canonical "canonical worker-supervisor" shape the paired
2844/// halves close on their respective axes.
2845///
2846/// Lifted as a typed `pub const` so the paired OTP-canonical default has
2847/// exactly one source of truth on each of its three halves — the sibling
2848/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half, the
2849/// sibling [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` `60s` half, and
2850/// this `one_for_one` strategy half now share the same substrate-
2851/// primitive lift discipline. Same shape every other typed default in
2852/// this crate carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] +
2853/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] paired halves on the same OTP-
2854/// canonical `{one_for_one, intensity, 5, 60}`, the sibling
2855/// [`SUPERVISOR_MAX_RESTARTS_MAX`] + [`SUPERVISOR_RESTART_WINDOW_MAX`]
2856/// upper caps on the paired sibling axes, and the peer
2857/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
2858/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes).
2859pub const SUPERVISOR_ESTRATEGIA_DEFAULT: RestartStrategy = RestartStrategy::OneForOne;
2860
2861/// Substrate-canonical Erlang/OTP-shaped per-child restart-decision-policy
2862/// default for the `:children :restart` axis — the OTP `permanent`
2863/// worker-child default (`{ChildId, StartFunc, permanent, …}` in a
2864/// `supervisor`'s `init/1` child-spec tuple), extracted as a typed
2865/// `pub const` so every substrate-side consumer that resolves "what
2866/// [`ChildSpec::restart`] variant does an author-omitted `:children
2867/// :restart` slot degrade onto?" reaches for exactly one substrate-
2868/// primitive [`RestartPolicy`].
2869///
2870/// Completes the OTP-shape supervisor-tree default set at the substrate
2871/// primitive. The per-`:supervisor` axis already carries all three of its
2872/// halves as lifted typed constants — [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
2873/// (`one_for_one`, 95ffacc), [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
2874/// (`MaxIntensity` `5`, b698ec0), [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2875/// (`Period` `60s`, f7dcd0e) — while the per-`:children` axis's own
2876/// OTP-canonical default rode as an open-coded `Self::Permanent` arm in
2877/// the [`Default for RestartPolicy`] impl, the last un-lifted default on
2878/// the M2 `:supervisor` slot family. The split mattered because the two
2879/// axes resolve *together* on every author-omitted supervisor: a
2880/// `(defcaixa :kind Supervisor :children ((:caixa "worker" :versao
2881/// "^0.1")))` with no `:estrategia` and no per-child `:restart` degrades
2882/// onto `{one_for_one, 5, 60}` through three lifted constants and onto
2883/// `permanent` through an open-coded enum arm, so a future coherent
2884/// rebrand of the OTP-shape default set (an Elixir-shaped
2885/// `{:one_for_one, max_restarts: 3, max_seconds: 5}` tightening, a
2886/// per-cluster overlay the operator pins through the MESH-COMPOSITION
2887/// §III.2 supervision-canary roadmap slots, an OTP-`transient` widening
2888/// once the substrate discovers clean-completion-aware children as the
2889/// more common child shape) would have had to migrate three halves
2890/// through typed constants and the fourth through a raw enum arm in
2891/// lockstep or the supervisor-level and child-level defaults would
2892/// silently drift apart.
2893///
2894/// The `:children :restart` default axis has two production consumers on
2895/// the substrate side today: the [`Default for RestartPolicy`] impl's
2896/// return arm, and the serde-side `#[serde(default)]` on
2897/// [`ChildSpec::restart`] that resolves an author-omitted `:children
2898/// :restart` slot through that same impl. Both now key off this one
2899/// substrate primitive, so the future wasm-operator's per-child post-exit
2900/// restart-decision branch, the future M4
2901/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2902/// admission webhook, and the `caixa-operator`'s hierarchical
2903/// reconciliation scheduler's per-child fan-out all reach for one typed
2904/// identifier when they resolve an omitted per-child restart posture.
2905///
2906/// The [`RestartPolicy::Permanent`] value pins Erlang/OTP's `permanent`
2907/// worker-child restart type — always restart the child regardless of how
2908/// it died, the canonical posture for long-running services that must
2909/// always be up, matching the sibling [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
2910/// `one_for_one` tree-of-independent-workers strategy this constant pairs
2911/// with under the same `{one_for_one, intensity, 5, 60}` worker-supervisor
2912/// shape. The two alternatives the closed [`RestartPolicy::ALL`] accept-set
2913/// carries ([`RestartPolicy::Transient`] — restart only on abnormal exit;
2914/// [`RestartPolicy::Temporary`] — never restart) express deliberate
2915/// one-shot / clean-completion-aware postures an author declares
2916/// explicitly, never a posture an omitted slot should silently assume.
2917pub const SUPERVISOR_CHILD_RESTART_DEFAULT: RestartPolicy = RestartPolicy::Permanent;
2918
2919/// Route the manually-authored [`Default`] impl on [`SupervisorSpec`]
2920/// through the substrate-canonical [`SupervisorSpec::otp_canonical`]
2921/// `pub const fn` constructor rather than a struct-literal cascade over
2922/// the paired [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
2923/// [`default_max_restarts`] / [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2924/// lifted consts — one source of truth for the Erlang/OTP-canonical
2925/// `{one_for_one, 5, 60}` worker-supervisor baseline across the two
2926/// paths every downstream consumer already reaches through (the
2927/// hand-authored-until-now [`Default::default`] the
2928/// `..SupervisorSpec::default()` struct-update-syntax on every
2929/// one-axis-under-test fixture in this crate's test module rests on,
2930/// and the `pub const fn` [`SupervisorSpec::otp_canonical`] constructor
2931/// every `const`-context consumer reaches through).
2932///
2933/// Extends the [`Default`]-through-const-ctor fold discipline the
2934/// [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
2935/// (abd52c2), [`crate::aplicacao::MeshPolicy`]
2936/// [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`] (91641a4),
2937/// and [`crate::BehaviorSpec`]
2938/// [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c) folds
2939/// closed on the M2 / M3 `Option`-only "canonical unset baseline"
2940/// typed-slot spec family — extended here onto the M2 supervisor-slot
2941/// [`SupervisorSpec`] whose canonical baseline is not "everything
2942/// `None`" but the OTP-canonical `{one_for_one, 5, 60}` worker-
2943/// supervisor triple. The `empty()` peer's naming did not fit
2944/// (`SupervisorSpec` carries a discriminator-shaped `estrategia` field
2945/// and a non-zero `max_restarts`/`restart_window` pair whose canonical
2946/// shape is Erlang/OTP-descended, not the "no axis declared" bottom
2947/// the sibling `Option`-only slots fold to), so this peer is named
2948/// [`SupervisorSpec::otp_canonical`] instead — the same phrasing the
2949/// existing per-arm pin tests
2950/// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`] /
2951/// [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`] /
2952/// [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
2953/// already reach for. Pinned load-bearing by
2954/// [`tests::supervisor_spec_default_routes_through_otp_canonical_ctor`]
2955/// (byte-parity pin against [`SupervisorSpec::otp_canonical`] under
2956/// [`PartialEq`], sharpening the sibling
2957/// `supervisor_spec_default_*_routes_through_lifted_default` per-arm
2958/// pins from a per-field lift into a whole-struct one-source-of-truth
2959/// pin — the derived-until-now [`Default::default`] and the
2960/// [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
2961/// construction, not by coincidence).
2962impl Default for SupervisorSpec {
2963 #[inline]
2964 fn default() -> Self {
2965 Self::otp_canonical()
2966 }
2967}
2968
2969impl SupervisorSpec {
2970 /// `const`-context peer of the [`Default for SupervisorSpec`]
2971 /// impl (which routes through this constructor) — returns the
2972 /// Erlang/OTP-canonical `{one_for_one, 5, 60}` worker-supervisor
2973 /// baseline this crate reaches for in every fixture-builder
2974 /// `..SupervisorSpec::default()` struct-update expression and
2975 /// every downstream `SupervisorSpec::default()` seed.
2976 ///
2977 /// Each field routes through the same substrate-canonical
2978 /// [`SUPERVISOR_ESTRATEGIA_DEFAULT`] / [`default_max_restarts`] /
2979 /// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] lifted consts the
2980 /// per-arm pin tests
2981 /// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`]
2982 /// / [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`]
2983 /// / [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
2984 /// already assert, so a future coherent rebrand of the OTP-canonical
2985 /// triple (Elixir's `{max_restarts: 3, max_seconds: 5}`, a per-
2986 /// cluster overlay via a future `:restart-window-overrides` slot, a
2987 /// per-child-cohort promotion the INSPIRATIONS.md §II.2 Erlang/OTP
2988 /// absorption roadmap acknowledges) migrates through three typed
2989 /// constants in lockstep, and the paired [`Default`] impl inherits
2990 /// every future extension by construction.
2991 ///
2992 /// `pub const fn` rather than the derived-style `Default::default`
2993 /// or a `pub const SUPERVISOR_SPEC_DEFAULT: SupervisorSpec` item —
2994 /// [`Default::default`] is not `const` on stable Rust, and
2995 /// `SupervisorSpec` is non-`Copy` so a `pub const` item would force
2996 /// every consumer through a [`Clone::clone`]. The `pub const fn`
2997 /// discipline lets `const`-context callers construct the OTP-
2998 /// canonical baseline at compile time without runtime dispatch on
2999 /// the derived [`Default::default`], the same posture the sibling
3000 /// [`crate::LimitsSpec::empty`] (9739971) /
3001 /// [`crate::aplicacao::MeshPolicy::empty`] (6df969b) /
3002 /// [`crate::BehaviorSpec::empty`] (f9b18e3) `Option`-only typed-slot
3003 /// spec `pub const fn` constructors carry on the sibling
3004 /// "everything `None`" baseline axis.
3005 ///
3006 /// Fourth peer on the M2 / M3 typed-slot-spec "const-context peer
3007 /// of the derived-style [`Default`]" family — sibling of the
3008 /// [`crate::LimitsSpec::empty`] / [`crate::aplicacao::MeshPolicy::empty`]
3009 /// / [`crate::BehaviorSpec::empty`] `Option`-only "canonical unset
3010 /// baseline" trio, extended here onto the M2 supervisor-slot
3011 /// [`SupervisorSpec`] whose canonical baseline is not "everything
3012 /// `None`" but the Erlang/OTP-canonical `{one_for_one, 5, 60}`
3013 /// worker-supervisor triple. Named [`Self::otp_canonical`] rather
3014 /// than `empty()` to name the actual invariant the return value
3015 /// pins — the same phrasing already used in the per-arm pin tests
3016 /// on this file. Pinned load-bearing by
3017 /// [`tests::supervisor_spec_otp_canonical_byte_equals_default`] and
3018 /// [`tests::supervisor_spec_otp_canonical_is_usable_in_const_context`].
3019 #[must_use]
3020 pub const fn otp_canonical() -> Self {
3021 Self {
3022 estrategia: SUPERVISOR_ESTRATEGIA_DEFAULT,
3023 max_restarts: default_max_restarts(),
3024 restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3025 children: Vec::new(),
3026 }
3027 }
3028
3029 /// Substrate-canonical per-`:supervisor` `:estrategia` OTP-shaped
3030 /// sibling-restart-strategy scalar accessor every consumer that
3031 /// dispatches on the supervisor's per-sibling restart-decision shape
3032 /// keys off — returns the author-declared `:supervisor :estrategia`
3033 /// variant verbatim as a [`RestartStrategy`], `Copy`-projected from
3034 /// the typed slot's own [`RestartStrategy`] storage.
3035 ///
3036 /// The `:supervisor :estrategia` slot carries the closed-set
3037 /// OTP-shaped sibling-restart-strategy discriminator ([`RestartStrategy::OneForOne`]
3038 /// — restart only the failed child, the Erlang/OTP `one_for_one` default;
3039 /// [`RestartStrategy::OneForAll`] — restart every child on any child
3040 /// failure, the Erlang/OTP `one_for_all` shared-state cohort default;
3041 /// [`RestartStrategy::RestForOne`] — restart the failed child and
3042 /// every child started after it, the Erlang/OTP `rest_for_one`
3043 /// startup-order default; [`RestartStrategy::SimpleOneForOne`] —
3044 /// dynamic children of the same shape, the Erlang/OTP
3045 /// `simple_one_for_one` per-session default) that every downstream
3046 /// consumer of the Supervisor's per-sibling restart-decision fan-out
3047 /// shape keys off. Validated by [`SupervisorSpec::validate`] to be
3048 /// paired coherently with the sibling `:children` axis
3049 /// (`SimpleOneForOne ↔ children.is_empty()` — the cross-slot
3050 /// partition the strategy-arm's [`SupervisorError::SimpleOneForOneWithStaticChildren`]
3051 /// / [`SupervisorError::NoChildren`] refusal cascade pins), and every
3052 /// downstream consumer that reads the strategy keys off this scalar
3053 /// (the [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
3054 /// partition-dispatch `match` arm, the non-`SimpleOneForOne`-arm
3055 /// declared-but-empty [`SupervisorError::NoChildren`] error carrier's
3056 /// `estrategia:` field, the future `feira app graph` per-Supervisor
3057 /// strategy print line, the future wasm-operator's per-supervisor
3058 /// sibling-restart-strategy branch, the future M4
3059 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-strategy
3060 /// admission-webhook resolver, the `caixa-operator`'s hierarchical
3061 /// reconciliation scheduler's per-strategy fan-out).
3062 ///
3063 /// Prior to this lift the `.estrategia` field was accessed inline at
3064 /// two production sites in `caixa-core/src/supervisor.rs` — the
3065 /// [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
3066 /// `match self.estrategia { … }` partition dispatch, and the
3067 /// non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
3068 /// carrier at `estrategia: self.estrategia` — two open-coded
3069 /// field-accesses that expressed no compile-time link back to the
3070 /// typed slot. A future extension of the `:supervisor :estrategia`
3071 /// axis to a richer author surface (a per-cluster strategy override
3072 /// the operator pins through a future `:supervisor :estrategia-overrides`
3073 /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
3074 /// acknowledges, a per-tenant strategy-alias table the M4 CR
3075 /// materializer resolves per-CR, a per-Supervisor dynamic strategy
3076 /// derivation the future adaptive-supervision engine computes from
3077 /// child-failure-history topology, a per-child-cohort strategy split
3078 /// the future `RestForCohort` extension acknowledged by the
3079 /// INSPIRATIONS.md §II.2 Erlang/OTP absorption roadmap acknowledges)
3080 /// would have had to be threaded through every open-coded copy in
3081 /// lockstep — one consumer reading the raw variant while a peer read
3082 /// the operator-resolved variant would silently split the
3083 /// [`SupervisorError::NoChildren`] diagnostic's quoted strategy from
3084 /// the actual partition-dispatch input the empty-children refusal
3085 /// arm reached under, a two-consumer split at the validator far from
3086 /// the source `caixa.lisp` with no field naming the strategy-drift
3087 /// root cause. Lifting the resolution rule to a typed method on the
3088 /// substrate primitive means every downstream consumer of the
3089 /// Supervisor's per-`:supervisor` sibling-restart-strategy surface
3090 /// reaches for exactly one typed dispatch — the resolver's accept-set
3091 /// migrates as a unit on any future axis addition.
3092 ///
3093 /// Peer of the sibling M3 mesh-slot [`crate::Placement::estrategia`]
3094 /// (921fe1b) `Copy`-return `PlacementStrategy` scalar accessor on the
3095 /// per-`:placement` distribution-strategy axis — same "one typed
3096 /// dispatch on the substrate primitive, thin projections at each
3097 /// consumer" discipline extended onto the M2 supervisor-slot
3098 /// per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
3099 /// scalar axis. The two typed axes (`Placement::estrategia` on the
3100 /// M3 Aplicacao side, `SupervisorSpec::estrategia` on the M2
3101 /// Supervisor side) now share one accessor discipline for the shared
3102 /// substrate concept "a `Copy`-projected closed-set enum-arm
3103 /// discriminator that partitions the downstream renderer's per-arm
3104 /// fan-out". First `Copy`-return accessor on the M2 supervisor-slot
3105 /// `SupervisorSpec` type — companion to the sibling per-`:children`
3106 /// [`crate::ChildSpec::nome`] (57c61d0) /
3107 /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
3108 /// scalar accessors on the sibling per-`:children` `String`-carry
3109 /// axes. Named `estrategia()` to match the storage field's name and
3110 /// the peer [`crate::Placement::estrategia`] method-name discipline
3111 /// verbatim; the accessor's identity name maps onto the canonical
3112 /// OTP-shape supervision vocabulary the [`RestartStrategy`] enum's
3113 /// docstring already carries.
3114 ///
3115 /// Declared `pub const fn` to close the M2 supervisor-slot
3116 /// `Copy`-return raw-field-getter `const`-eval-surface pass —
3117 /// sibling of the peer M2 per-`:children` [`ChildSpec::restart`]
3118 /// (converted in this commit) `Copy`-composite-enum accessor, peer
3119 /// of the sibling M2 per-`:supervisor`
3120 /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
3121 /// already lifted, and mirror of the peer M3 mesh-slot
3122 /// per-`:placement` [`crate::Placement::estrategia`] (bafa004)
3123 /// `Copy`-return `pub const fn` scalar accessor whose method-name
3124 /// discipline this accessor was authored to match. Every downstream
3125 /// substrate-side `const`-context consumer of the per-`:supervisor`
3126 /// sibling-restart-strategy scalar (a future module-scope `const
3127 /// _:() = assert!(matches!(sup.estrategia(),
3128 /// RestartStrategy::OneForOne))` invariant pin on a typed fixture,
3129 /// a future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
3130 /// admission-webhook `const fn` per-supervisor strategy-arm floor
3131 /// over a typed [`SupervisorSpec`], any future `const fn`
3132 /// supervisor-tree composer over the substrate primitive that fans
3133 /// on the sibling-restart-strategy at compile time) now reaches
3134 /// through the same typed dispatch on the substrate primitive at
3135 /// const-eval time as at runtime. A future non-`Copy`-return
3136 /// promotion of the scalar (an `Option<RestartStrategy>`-shape
3137 /// migration once the substrate grows per-cluster strategy overlays
3138 /// the [`SupervisorSpec`] docstring already anticipates, a
3139 /// per-tenant strategy-alias table the M4 CR materializer resolves
3140 /// per-CR) that would drop the `const` qualifier fails the
3141 /// fail-before-pass-after pin
3142 /// [`tests::supervisor_spec_estrategia_accessor_is_const_fn`] at
3143 /// caixa-core build time rather than surfacing as a downstream
3144 /// consumer regression.
3145 #[must_use]
3146 pub const fn estrategia(&self) -> RestartStrategy {
3147 self.estrategia
3148 }
3149
3150 /// Substrate-canonical per-`:supervisor` `:max-restarts` OTP-shaped
3151 /// `MaxIntensity` restart-budget scalar accessor every consumer that
3152 /// reads the supervisor's per-`:restart-window` restart-budget count
3153 /// keys off — returns the author-declared `:supervisor :max-restarts`
3154 /// typed `u32` verbatim, `Copy`-projected from the typed slot's own
3155 /// `u32` storage (`u32` is `Copy`, so the accessor returns by value; no
3156 /// borrow of `&self` past the call). Non-optional (the `u32` field
3157 /// carries the restart-budget count as a required axis with a
3158 /// [`default_max_restarts`]-supplied default; the zero-floor arm
3159 /// [`SupervisorError::ZeroMaxRestarts`] and the cap arm
3160 /// [`SupervisorError::MaxRestartsExceedsCap`] jointly bracket the
3161 /// accept-set to `1..=SUPERVISOR_MAX_RESTARTS_MAX`).
3162 ///
3163 /// The `:supervisor :max-restarts` slot carries the Erlang/OTP
3164 /// `MaxIntensity` restart-budget count that pairs with the sibling
3165 /// `:restart-window` `Period` to form the `MaxIntensity / Period`
3166 /// restart-intensity ratio the supervisor trips its own escalation on
3167 /// (`theory/RUNTIME-PATTERNS.md` §II.2, Learn You Some Erlang's
3168 /// `{intensity, 5, 60}` worker-supervisor default). Every downstream
3169 /// consumer of the Supervisor's per-`:supervisor` restart-budget count
3170 /// keys off this scalar (the [`SupervisorSpec::validate`] zero-floor +
3171 /// upper-cap bracket at
3172 /// `require_positive_bounded_u32(self.max_restarts(), …)`, the future
3173 /// wasm-operator's per-supervisor restart-intensity counter's
3174 /// budget-vs-count comparator, the future M4
3175 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3176 /// webhook, the `caixa-operator`'s hierarchical reconciliation
3177 /// scheduler's per-supervisor escalation-decision branch, every
3178 /// `SupervisorError::MaxRestartsExceedsCap` variant carrying the
3179 /// offending count verbatim for `feira lint` rendering).
3180 ///
3181 /// Prior to this lift the `.max_restarts` field was accessed inline at
3182 /// one production site in `caixa-core/src/supervisor.rs` — the
3183 /// [`SupervisorSpec::validate`] `require_positive_bounded_u32(self
3184 /// .max_restarts, …)` bracket-gate call — one open-coded field-access
3185 /// that expressed no compile-time link back to the typed slot. A
3186 /// future extension of the `:max-restarts` axis to a richer author
3187 /// surface (a per-cluster restart-budget override the operator pins
3188 /// through a future `:supervisor :max-restarts-overrides` slot the
3189 /// MESH-COMPOSITION §III.2 supervision-canary roadmap acknowledges,
3190 /// a per-tenant restart-budget-alias table the M4 CR materializer
3191 /// resolves per-CR, a per-supervisor dynamic restart-budget derivation
3192 /// the future adaptive-supervision engine computes from child-failure-
3193 /// history topology, a promotion of the plain `u32` count to a richer
3194 /// `{MaxR, MaxT}` tuple once Erlang/OTP's per-child-cohort restart-
3195 /// budget-partition slot comes into scope) would have had to be
3196 /// threaded through every open-coded copy in lockstep or the validate
3197 /// gate and the future M4 emit path would silently disagree on which
3198 /// restart-budget count a given supervisor resolves to — an author's
3199 /// `:max-restarts 5` would satisfy validate while the emit path
3200 /// silently read a drifted other value (a `:max-restarts 10000`
3201 /// no-op supervisor at the emit boundary would carry the author's
3202 /// declared `5` verbatim in `feira lint` output while the future
3203 /// wasm-operator's restart-intensity counter operated under the
3204 /// drifted count), a two-consumer split at the validator far from the
3205 /// source `caixa.lisp` with no field naming the restart-budget-drift
3206 /// root cause. Lifting the resolution rule to a typed method on the
3207 /// substrate primitive means every downstream consumer of the
3208 /// Supervisor's per-`:supervisor` restart-budget-count surface reaches
3209 /// for exactly one typed dispatch — the resolver's accept-set migrates
3210 /// as a unit on any future axis addition.
3211 ///
3212 /// Peer of the sibling M3 mesh-slot [`crate::CircuitBreaker::max_failures`]
3213 /// (3a74062) `Copy`-return `u32` sub-struct required-scalar accessor
3214 /// on the per-`:politicas :circuit-breaker :max-failures` Envoy-
3215 /// outlier-detection trip-threshold axis — same "one typed dispatch on
3216 /// the substrate primitive, thin projections at each consumer"
3217 /// discipline extended onto the M2 supervisor-slot per-`:supervisor`
3218 /// restart-budget-count `Copy`-`u32` scalar axis. The two typed axes
3219 /// (`CircuitBreaker::max_failures` on the M3 Aplicacao side,
3220 /// `SupervisorSpec::max_restarts` on the M2 Supervisor side) now share
3221 /// one accessor discipline for the shared substrate concept "a
3222 /// `Copy`-projected required `u32` count that trips the next-higher
3223 /// protection layer after N events in a rolling window" — both are
3224 /// counters with identical degenerate-at-the-high-end shape and share
3225 /// the paired [`crate::POLICY_BREAKER_MAX_FAILURES_MAX`] /
3226 /// [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` cap. Second `Copy`-return
3227 /// accessor on the M2 supervisor-slot `SupervisorSpec` type, sibling
3228 /// to the [`SupervisorSpec::estrategia`] (eafb619) `Copy`-composite-
3229 /// enum `RestartStrategy` accessor. Named `max_restarts()` to match
3230 /// the storage field's name verbatim and the peer
3231 /// [`crate::CircuitBreaker::max_failures`] method-name discipline; the
3232 /// accessor's identity maps onto the canonical OTP-shape supervision
3233 /// vocabulary the [`SupervisorSpec::max_restarts`] field's docstring
3234 /// already carries.
3235 #[must_use]
3236 pub const fn max_restarts(&self) -> u32 {
3237 self.max_restarts
3238 }
3239
3240 /// Substrate-canonical per-`:supervisor` `:restart-window` OTP-shaped
3241 /// `Period` sliding-window scalar accessor every consumer of the
3242 /// supervisor's `MaxIntensity / Period` restart-intensity denominator
3243 /// keys off — returns the author-declared `:supervisor :restart-window`
3244 /// typed [`Duration`] verbatim as an `Option<Duration>`, copied out of
3245 /// the typed slot's own `Option<Duration>` storage (`Duration` is
3246 /// `Copy`, so `Option<Duration>` is `Copy` and the accessor returns by
3247 /// value; no borrow of `&self` past the call). `None` when the slot is
3248 /// absent (the canonical "never reset — every restart across the
3249 /// supervisor's lifetime counts against the sibling `:max-restarts`
3250 /// budget" sentinel the field's own docstring names and the peer
3251 /// `validate_accepts_none_restart_window` pin locks in on the
3252 /// [`SupervisorSpec::validate`] entry-side).
3253 ///
3254 /// The `:supervisor :restart-window` slot carries the Erlang/OTP
3255 /// `Period` sliding-observation-interval that pairs with the sibling
3256 /// `:max-restarts` `MaxIntensity` restart-budget count to form the
3257 /// `MaxIntensity / Period` restart-intensity ratio the supervisor
3258 /// trips its own escalation on (`theory/RUNTIME-PATTERNS.md` §II.2,
3259 /// Learn You Some Erlang's `{intensity, 5, 60}` worker-supervisor
3260 /// default). The typed slot's `Option<Duration>` accept-set —
3261 /// zero-floor rejected through [`SupervisorError::RestartWindowZero`]
3262 /// (Erlang/OTP's `MaxIntensity / Period` invariant requires
3263 /// `Period > 0`; a zero period either trips on the first failure or
3264 /// never trips depending on operator interpretation, neither of which
3265 /// is the author's intent — omit the slot to express "no reset";
3266 /// carry a positive duration to express the sliding window),
3267 /// integer-millisecond canonical form enforced through
3268 /// [`SupervisorError::RestartWindowNotCanonical`] (the duration
3269 /// codec's canonical form emits `"1500ms"` not `"1.5s"` and the
3270 /// future wasm-operator's per-supervisor restart-intensity counter
3271 /// quantizes at milliseconds), upper-bounded by
3272 /// [`SUPERVISOR_RESTART_WINDOW_MAX`] (1h — the coarsest per-
3273 /// supervisor rolling window any operationally-reachable supervisor
3274 /// can honor without spanning multiple scheduler epochs the
3275 /// hierarchical-reconciliation scheduler treats as independent) —
3276 /// maps onto the future wasm-operator (M3) per-supervisor
3277 /// restart-intensity counter's rolling-observation-interval, the
3278 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
3279 /// per-`spec.restartWindow` admission webhook, and the sibling
3280 /// `duration_codec`-serialized wire scalar every downstream consumer
3281 /// of the supervisor's per-`:supervisor` restart-intensity denominator
3282 /// keys off.
3283 ///
3284 /// Prior to this lift the `.restart_window` field was accessed inline
3285 /// at one production site in `caixa-core/src/supervisor.rs` — the
3286 /// [`SupervisorSpec::validate`] `if let Some(w) = self.restart_window {
3287 /// … }` zero-floor + canonical-form + upper-cap bracket arm — one
3288 /// open-coded field-access that expressed no compile-time link back to
3289 /// the typed slot. A future extension of the `:restart-window` axis to
3290 /// a richer author surface (a per-cluster restart-window override the
3291 /// operator pins through a future `:supervisor :restart-window-overrides`
3292 /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
3293 /// acknowledges, a per-tenant restart-window-alias table the M4 CR
3294 /// materializer resolves per-CR, a per-supervisor dynamic
3295 /// restart-window derivation the future adaptive-supervision engine
3296 /// computes from child-failure-history topology, a promotion of the
3297 /// plain `Option<Duration>` window to a richer `{observation, cooldown}`
3298 /// pair once Erlang/OTP's per-child-cohort observation-interval-
3299 /// partition slot comes into scope) would have had to be threaded
3300 /// through every open-coded copy in lockstep or the validate gate and
3301 /// the future M4 emit path would silently disagree on which
3302 /// restart-window a given supervisor resolves to — an author's
3303 /// `:restart-window "60s"` would satisfy validate while the emit path
3304 /// silently read a drifted other value (a `Some(Duration::from_secs(60))`
3305 /// authored slot at the emit boundary would carry the author's
3306 /// declared window verbatim in `feira lint` output while the future
3307 /// wasm-operator's restart-intensity counter operated under a
3308 /// drifted window, or vice versa: an author's `:restart-window ()`
3309 /// would carry the "never reset" sentinel through validate while the
3310 /// emit path silently substituted a default sliding window), a
3311 /// two-consumer split at the validator far from the source
3312 /// `caixa.lisp` with no field naming the restart-window-drift root
3313 /// cause. Lifting the resolution rule to a typed method on the
3314 /// substrate primitive means every downstream consumer of the
3315 /// Supervisor's per-`:supervisor` restart-intensity-denominator
3316 /// surface reaches for exactly one typed dispatch — the resolver's
3317 /// accept-set migrates as a unit on any future axis addition.
3318 ///
3319 /// Third `Copy`-return accessor on the M2 supervisor-slot
3320 /// `SupervisorSpec` type, closing the last unlifted per-`:supervisor`
3321 /// scalar-value axis (`children: Vec<ChildSpec>` carries a `Vec`
3322 /// payload rather than a `Copy`-scalar, and the per-`:children`
3323 /// [`crate::ChildSpec::nome`] (57c61d0) /
3324 /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
3325 /// scalar accessors already close the per-element `String`-carry
3326 /// axes). Sibling to the peer M2 [`crate::LimitsSpec::wall_clock`]
3327 /// (8cb717b) `Option<Duration>` accessor on the `:limits` slot's
3328 /// per-outermost-call wall-clock-deadline axis and the peer M3
3329 /// [`crate::MeshPolicy::timeout`] (7073d0f) `Option<Duration>`
3330 /// accessor on the `:politicas` slot's per-call-deadline axis — all
3331 /// three share the shared substrate concept "a `Copy`-projected
3332 /// optional `Duration` that carries a positive integer-millisecond
3333 /// canonical value with a `1ms..=<axis-specific>_MAX` accept-set and
3334 /// the paired zero-floor / non-canonical / above-cap refusal cascade"
3335 /// through the same [`crate::render::require_positive_canonical_bounded_duration`]
3336 /// bracket-helper the three axes each route through. Named
3337 /// `restart_window()` to match the storage field's name verbatim and
3338 /// the peer [`crate::LimitsSpec::wall_clock`] /
3339 /// [`crate::MeshPolicy::timeout`] method-name discipline; the
3340 /// accessor's identity maps onto the canonical OTP-shape supervision
3341 /// vocabulary the [`SupervisorSpec::restart_window`] field's docstring
3342 /// already carries.
3343 #[must_use]
3344 pub const fn restart_window(&self) -> Option<Duration> {
3345 self.restart_window
3346 }
3347
3348 /// Substrate-canonical per-`:supervisor` `:children` OTP-shaped
3349 /// static-child-list slice accessor every consumer that walks the
3350 /// supervisor's declared child set keys off — returns the author-
3351 /// declared `:supervisor :children` `Vec<ChildSpec>` verbatim as a
3352 /// `&[ChildSpec]` slice-view, borrowed from the typed slot's own
3353 /// `Vec<ChildSpec>` storage (a zero-copy slice-view over the same
3354 /// backing buffer the `Serialize`/`Deserialize` derives round-trip
3355 /// through). Non-optional: an empty slice is the load-bearing
3356 /// "author declared `:children ()`" sentinel every consumer of the
3357 /// cross-slot `SimpleOneForOne ↔ children.is_empty()` partition
3358 /// keys off (`SimpleOneForOne` requires the empty slice; the peer
3359 /// three strategies require a non-empty slice — the paired
3360 /// [`SupervisorError::SimpleOneForOneWithStaticChildren`] /
3361 /// [`SupervisorError::NoChildren`] refusal cascade pins the
3362 /// partition on both arms).
3363 ///
3364 /// The `:supervisor :children` slot carries the OTP-shaped static
3365 /// child list the supervisor materializes one ComputeUnit per
3366 /// entry from — the Erlang/OTP `supervisor:init/1`'s
3367 /// `{ok, {SupFlags, ChildSpecs}}` `ChildSpecs` list, projected
3368 /// through the tatara-lisp `:children` author surface onto a typed
3369 /// `Vec<ChildSpec>` whose per-element `(nome(),
3370 /// versao_requirement(), restart)` triple the per-child
3371 /// [`SupervisorSpec::validate`] loop already gates through the
3372 /// lifted [`ChildSpec::nome`] (57c61d0) /
3373 /// [`ChildSpec::versao_requirement`] (2c053c8) scalar accessors.
3374 /// Every downstream consumer that fans on the static child list
3375 /// keys off this slice (the [`SupervisorSpec::validate`]
3376 /// `SimpleOneForOne ↔ non-SimpleOneForOne` partition dispatch's
3377 /// `.is_empty()` probe on both arms, the [`SupervisorSpec::validate`]
3378 /// per-child DNS-1123 / semver-requirement / duplicate-detection
3379 /// fan-out loop, every future wasm-operator (M3) per-supervisor
3380 /// hierarchical-reconciliation scheduler's per-child ComputeUnit
3381 /// materialization loop, the future M4
3382 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
3383 /// admission-webhook fan-out, the future `feira app graph`
3384 /// per-supervisor tree-print traversal).
3385 ///
3386 /// Prior to this lift the `.children` `Vec<ChildSpec>` was accessed
3387 /// inline at three production sites in `caixa-core/src/supervisor.rs`
3388 /// — the [`SupervisorSpec::validate`] `SimpleOneForOne`-arm
3389 /// `!self.children.is_empty()` cross-slot refusal probe, the peer
3390 /// non-`SimpleOneForOne`-arm `self.children.is_empty()`
3391 /// [`SupervisorError::NoChildren`] refusal probe, and the per-child
3392 /// validate loop's `for child in &self.children` traversal head —
3393 /// three open-coded field-accesses that expressed no compile-time
3394 /// link back to the typed slot. A future extension of the
3395 /// `:supervisor :children` axis to a richer author surface (a
3396 /// per-cluster child-set overlay the operator pins through a future
3397 /// `:supervisor :children-overrides` slot the MESH-COMPOSITION §III.2
3398 /// supervision-canary roadmap acknowledges, a per-tenant
3399 /// child-set-alias table the M4 CR materializer resolves per-CR,
3400 /// a per-supervisor dynamic-child derivation the future adaptive-
3401 /// supervision engine computes from child-failure-history topology,
3402 /// a promotion of the plain `Vec<ChildSpec>` to a richer
3403 /// `{static, dynamic}` partition once Erlang/OTP's
3404 /// `simple_one_for_one` dynamic-child slot comes into typed scope)
3405 /// would have had to be threaded through all three open-coded copies
3406 /// in lockstep or one consumer would silently disagree with the
3407 /// peers on which child-set a given supervisor resolves to — the
3408 /// `SimpleOneForOne`-arm probe reading the raw slot while the peer
3409 /// non-`SimpleOneForOne`-arm probe read an operator-resolved slot
3410 /// would silently split the partition-dispatch's two-arm coherence
3411 /// (a supervisor that satisfies neither arm's precondition, or that
3412 /// satisfies both, at the cost of the paired
3413 /// `SimpleOneForOneWithStaticChildren`/`NoChildren` refusal cascade
3414 /// silently drifting from the per-child validate loop's actual
3415 /// traversal input), a three-consumer split at the validator far
3416 /// from the source `caixa.lisp` with no field naming the
3417 /// child-set-drift root cause. Lifting the resolution rule to a
3418 /// typed method on the substrate primitive means every downstream
3419 /// consumer of the Supervisor's per-`:supervisor` static-child-list
3420 /// surface reaches for exactly one typed dispatch — the resolver's
3421 /// accept-set migrates as a unit on any future axis addition.
3422 ///
3423 /// First slice-return (`&[T]`) accessor on any M2 or M3 typed slot
3424 /// — the seed for the same "one typed dispatch on the substrate
3425 /// primitive, thin projections at each consumer" discipline the
3426 /// closed [`crate::LimitsSpec`] / [`BehaviorSpec`] /
3427 /// [`crate::UpgradeFromEntry`] scalar-accessor families each carry
3428 /// on their `Copy` / `Option<Copy>` / `Option<&str>` axes, extended
3429 /// onto the first `Vec`-carry axis on the substrate. The four peer
3430 /// `Vec`-carry axes still unlifted at the time of this seed —
3431 /// [`crate::Placement::clusters`] (`Vec<String>` per-cluster
3432 /// distribution-target list), [`crate::AplicacaoSpec::membros`]
3433 /// (`Vec<Membro>` per-Aplicacao member list),
3434 /// [`crate::AplicacaoSpec::contratos`] (`Vec<WitContract>`
3435 /// per-Aplicacao WIT-typed edge list),
3436 /// [`crate::UpgradeFromEntry::instructions`]
3437 /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
3438 /// — inherit this accessor's discipline as future compounding runs
3439 /// migrate their consumers onto the shared slice-return shape.
3440 /// Fourth (and final) accessor on the M2 supervisor-slot
3441 /// `SupervisorSpec` type, sibling to the three `Copy`-return
3442 /// [`SupervisorSpec::estrategia`] (eafb619) /
3443 /// [`SupervisorSpec::max_restarts`] (7844f4e) /
3444 /// [`SupervisorSpec::restart_window`] (7e7b32f) accessors — closes
3445 /// the last unlifted per-`:supervisor` field axis (the
3446 /// `Vec<ChildSpec>` static-child-list carrier) so every downstream
3447 /// per-`:supervisor` reader now routes through a typed dispatch on
3448 /// the substrate primitive. Named `children()` to match the storage
3449 /// field's name verbatim and the tatara-lisp author-surface term
3450 /// (`:children`) the field's own docstring already carries; the
3451 /// accessor's identity maps onto the canonical OTP-shape
3452 /// supervision vocabulary the [`SupervisorSpec::children`] field's
3453 /// docstring already reaches for ("Static children ..."). Returns
3454 /// `&[ChildSpec]` (not `&Vec<ChildSpec>`) because every downstream
3455 /// consumer of the child list treats it as a read-only sequence —
3456 /// the slice-view is the narrowest borrow that supports every
3457 /// present + roadmapped consumer (`.is_empty()`, `.iter()`,
3458 /// index, `.len()`) without leaking the backing `Vec`'s
3459 /// grow/push/reserve surface that no consumer of the typed view
3460 /// reaches for (the storage-side `Vec` remains reachable through
3461 /// the `pub children` field for the mutation-carrying
3462 /// `Caixa::supervisor_view` fold-in path in
3463 /// `manifest.rs:supervisor_view`).
3464 #[must_use]
3465 pub const fn children(&self) -> &[ChildSpec] {
3466 self.children.as_slice()
3467 }
3468
3469 /// Validate the supervisor's typed shape — strategy ↔ children
3470 /// invariants, max_restarts > 0, restart_window > 0 when set,
3471 /// per-child non-empty + duplicate-free names.
3472 ///
3473 /// Mirrors the value-shape discipline applied to every other
3474 /// typed slot:
3475 ///
3476 /// - `Some(Duration::ZERO)` on a Duration-bearing axis is the
3477 /// same "0 means the opposite of what you think" footgun
3478 /// closed for `:politicas :timeout` (Envoy interprets a zero
3479 /// timeout as `infinite`), `:politicas :circuit-breaker
3480 /// :window`, and `:limits :wall-clock`. The
3481 /// `MaxIntensity / Period` ratio in Erlang/OTP's
3482 /// `supervisor` requires `Period > 0`; a zero period either
3483 /// trips on the first failure or never trips depending on
3484 /// operator interpretation, neither of which is the
3485 /// author's intent. Omit `:restart-window` to express "no
3486 /// reset"; carry a positive duration to express the window.
3487 /// - duplicate `:children` `:caixa` names are the same
3488 /// graph-node-set / multiset distinction closed for
3489 /// `:membros` (4bb3f3d), `:placement :clusters` (c7c7799),
3490 /// and `:entrada :paths` (eb3456d). Two children with the
3491 /// same `:caixa` materialize as two ComputeUnits with the
3492 /// same name in the cluster's HelmRelease values, one
3493 /// silently overwriting the other. Erlang/OTP's
3494 /// `child_spec.id` is required-unique per supervisor;
3495 /// pleme-io enforces the same set-not-multiset shape on
3496 /// `:caixa` (the load-bearing identity in our renderer).
3497 pub fn validate(&self) -> Result<(), SupervisorError> {
3498 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition
3499 // dispatch and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
3500 // error carrier's `estrategia:` field through the lifted
3501 // [`SupervisorSpec::estrategia`] accessor rather than the raw
3502 // `self.estrategia` field access — the two production consumers
3503 // of the per-`:supervisor` sibling-restart-strategy scalar now
3504 // key off exactly one typed dispatch on the substrate primitive,
3505 // so any future rebrand on the axis (a per-cluster strategy
3506 // override the operator pins through a future `:supervisor
3507 // :estrategia-overrides` slot, a per-tenant strategy-alias table
3508 // the M4 CR materializer resolves per-CR) migrates as a single
3509 // caixa-core edit rather than a coordinated rewrite of the two
3510 // call sites — sibling of the peer M3 [`crate::Placement::estrategia`]
3511 // (921fe1b) four-consumer migration on the per-`:placement`
3512 // distribution-strategy axis.
3513 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition-
3514 // dispatch's paired `.is_empty()` cross-slot refusal probes
3515 // (the `SimpleOneForOne`-arm
3516 // [`SupervisorError::SimpleOneForOneWithStaticChildren`] refusal
3517 // and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
3518 // refusal) through the lifted [`SupervisorSpec::children`]
3519 // slice-return accessor rather than the raw `self.children`
3520 // field access — the two paired production consumers of the
3521 // per-`:supervisor` static-child-list scalar-shape now key off
3522 // exactly one typed dispatch on the substrate primitive, so any
3523 // future rebrand on the axis (a per-cluster child-set overlay
3524 // the operator pins through a future `:supervisor
3525 // :children-overrides` slot, a per-tenant child-set-alias table
3526 // the M4 CR materializer resolves per-CR) migrates as a single
3527 // caixa-core edit rather than a coordinated rewrite of the
3528 // paired arms — first slice-return migration on any typed slot,
3529 // seed for the peer per-`:placement :clusters`,
3530 // per-`:membros`, per-`:contratos`, and per-`:upgrade-from
3531 // :instructions` `Vec`-carry axes.
3532 match self.estrategia() {
3533 RestartStrategy::SimpleOneForOne => {
3534 // SimpleOneForOne: children added at runtime. Static
3535 // list must be empty (one shape declared elsewhere).
3536 if !self.children().is_empty() {
3537 return Err(SupervisorError::SimpleOneForOneWithStaticChildren);
3538 }
3539 }
3540 _ => {
3541 if self.children().is_empty() {
3542 return Err(SupervisorError::no_children(self.estrategia()));
3543 }
3544 }
3545 }
3546 // Zero-floor + upper-cap bracket on the typed `:max-restarts`
3547 // axis. See [`crate::render::require_positive_bounded_u32`] for
3548 // the ordering discipline (zero-floor arm strictly precedes cap
3549 // arm so `0` surfaces the self-locating `ZeroMaxRestarts`
3550 // diagnostic with its counter-axis remediation directly named,
3551 // not the misleading `0 > SUPERVISOR_MAX_RESTARTS_MAX == false`
3552 // cap-arm miss). Until this bracket landed the top edge ran all
3553 // the way to `u32::MAX` and a struct-literal
3554 // `SupervisorSpec { max_restarts: 100_000, .. }` (or the
3555 // equivalent author-surface `:max-restarts 100000` /
3556 // `:max-restarts 4294967295` typo landing in the slot) silently
3557 // passed validate. The runtime substrate consuming the value
3558 // (Erlang/OTP's `MaxIntensity / Period` ratio, the future
3559 // wasm-operator's per-supervisor restart-intensity counter, the
3560 // M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
3561 // admission webhook) then turned a typed `:max-restarts`
3562 // policy into a no-op supervisor: the escalation threshold is
3563 // structurally so high that no realistic
3564 // restarts-per-`:restart-window` traffic shape can reach it,
3565 // the supervisor never escalates to its parent, and a bad
3566 // child can loop inside the window indefinitely with the
3567 // parent supervisor structurally never receiving the "this
3568 // subtree has exceeded its restart budget" signal the typed
3569 // slot is meant to express. The bracket set is
3570 // `1..=SUPERVISOR_MAX_RESTARTS_MAX`, peer with the
3571 // [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap on
3572 // the sibling `:politicas :circuit-breaker :max-failures` axis:
3573 // both are "trip the next-higher protection layer after N
3574 // events in a rolling window" counters with identical
3575 // degenerate-at-the-high-end shape and now share one canonical
3576 // bracket helper. The bracket precedes the sibling
3577 // `:restart-window` zero-floor / canonical-millisecond arms so
3578 // an over-cap `max_restarts` paired with a structurally invalid
3579 // window surfaces the bracket diagnostic first, mirroring the
3580 // `PolicyBreakerMaxFailuresExceedsCap` / window-axis cross-arm
3581 // ordering on the peer `:politicas :circuit-breaker` slot.
3582 // Route the [`SupervisorSpec::validate`] `:max-restarts` zero-floor +
3583 // upper-cap bracket-gate through the lifted [`SupervisorSpec::max_restarts`]
3584 // accessor rather than the raw `self.max_restarts` field access —
3585 // the one production consumer of the per-`:supervisor`
3586 // restart-budget-count scalar now keys off exactly one typed
3587 // dispatch on the substrate primitive, so any future rebrand on
3588 // the axis (a per-cluster restart-budget override the operator
3589 // pins through a future `:supervisor :max-restarts-overrides`
3590 // slot, a per-tenant restart-budget-alias table the M4 CR
3591 // materializer resolves per-CR) migrates as a single caixa-core
3592 // edit rather than a coordinated rewrite — sibling of the peer M3
3593 // [`crate::CircuitBreaker::max_failures`] (3a74062) migration on
3594 // the per-`:politicas :circuit-breaker :max-failures` axis.
3595 crate::render::require_positive_bounded_u32(
3596 self.max_restarts(),
3597 SUPERVISOR_MAX_RESTARTS_MAX,
3598 || SupervisorError::ZeroMaxRestarts,
3599 SupervisorError::max_restarts_exceeds_cap,
3600 )?;
3601 // Route the [`SupervisorSpec::validate`] `:restart-window`
3602 // zero-floor + integer-millisecond canonical-form + upper-cap
3603 // bracket-gate through the lifted [`SupervisorSpec::restart_window`]
3604 // accessor rather than the raw `self.restart_window` field access —
3605 // the one production consumer of the per-`:supervisor`
3606 // restart-intensity-denominator scalar now keys off exactly one
3607 // typed dispatch on the substrate primitive, so any future rebrand
3608 // on the axis (a per-cluster restart-window override the operator
3609 // pins through a future `:supervisor :restart-window-overrides`
3610 // slot, a per-tenant restart-window-alias table the M4 CR
3611 // materializer resolves per-CR) migrates as a single caixa-core
3612 // edit rather than a coordinated rewrite — sibling of the peer M2
3613 // [`crate::LimitsSpec::wall_clock`] (8cb717b) validate-arm-route
3614 // on the per-`:limits :wall-clock` axis and the peer M3
3615 // [`crate::MeshPolicy::timeout`] (7073d0f) accessor-route on the
3616 // per-`:politicas :timeout` axis.
3617 if let Some(w) = self.restart_window() {
3618 // Zero-floor + integer-millisecond canonical-form +
3619 // upper-cap bracket on the typed `:restart-window` axis.
3620 // See
3621 // [`crate::render::require_positive_canonical_bounded_duration`]
3622 // for the full three-arm ordering discipline (zero-floor
3623 // strictly precedes canonical-form so `Duration::ZERO`
3624 // surfaces the self-locating `RestartWindowZero`
3625 // diagnostic; canonical-form strictly precedes the cap arm
3626 // so a sub-millisecond above-cap value surfaces the more
3627 // fundamental round-trip-shape diagnostic first) and the
3628 // three peer typed-`Duration` sites that share this
3629 // canonical bracket ([`crate::MeshPolicy::timeout`],
3630 // [`crate::CircuitBreaker::window`],
3631 // [`crate::LimitsSpec::wall_clock`]). Every validated
3632 // value lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
3633 // (1ms..=1h), integer-millisecond granularity.
3634 crate::render::require_positive_canonical_bounded_duration(
3635 w,
3636 SUPERVISOR_RESTART_WINDOW_MAX,
3637 || SupervisorError::RestartWindowZero,
3638 SupervisorError::restart_window_not_canonical,
3639 SupervisorError::restart_window_exceeds_cap,
3640 )?;
3641 }
3642 // Route the per-child DNS-1123 / semver-requirement / duplicate-
3643 // detection fan-out loop through the lifted named per-slot gate
3644 // [`SupervisorSpec::validate_children`] rather than an inline
3645 // three-per-child cascade — every future consumer that wants to
3646 // re-check only the `:children` slot's per-entry axes (the M4
3647 // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
3648 // admission webhook re-validating one added/renamed child, the
3649 // future wasm-operator's per-child dynamic-add re-validator on
3650 // the `SimpleOneForOne` runtime-add path once dynamic-children
3651 // graduate to a typed slot, a future partial re-validator on a
3652 // per-`:children`-entry patch) reaches every per-entry axis
3653 // through one dispatch rather than re-inlining the three-arm
3654 // cascade in lockstep with `validate` or paying the peer
3655 // `:estrategia`/`:max-restarts`/`:restart-window` gates to
3656 // reach one entry check. Sibling of the peer M3 mesh-slot
3657 // per-slot gate family (`validate_membros` — the exact peer on
3658 // the M3 side, [`crate::AplicacaoSpec::validate_membros`];
3659 // `validate_contratos` — 906a5c6; `validate_entrada` — 20cd523;
3660 // `validate_placement`; `validate_politicas` routing through
3661 // `MeshPolicy::validate` — f03a154) — the M2 supervisor-slot
3662 // per-slot gate discipline now spans both the M3 mesh-slot
3663 // family and the M2 `:children` per-child-cascade axis on one
3664 // shape: one named per-slot gate per typed per-entry loop.
3665 self.validate_children()?;
3666 Ok(())
3667 }
3668
3669 /// Named per-slot gate on the M2 `:supervisor :children` per-entry
3670 /// axis — folds the per-child DNS-1123 name gate, semver-requirement
3671 /// gate, and duplicate-`:caixa` dedup arm into one call every
3672 /// consumer that wants to re-validate one `:children` entry (or the
3673 /// whole list) against the same accept-set [`SupervisorSpec::validate`]
3674 /// admits reaches through.
3675 ///
3676 /// Peer of the M3 mesh-slot [`crate::AplicacaoSpec::validate_membros`]
3677 /// per-slot gate on the analogous per-entry axis (`:membros`) — same
3678 /// three-per-entry shape (DNS-1123 name + semver-requirement +
3679 /// duplicate-`:caixa` dedup), lifted to one named substrate
3680 /// primitive per slot. The M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
3681 /// materializer's admission webhook re-checking one added or renamed
3682 /// child, the future wasm-operator's per-child dynamic-add
3683 /// re-validator on the `SimpleOneForOne` runtime-add path once
3684 /// dynamic-children graduate to a typed slot, a future partial
3685 /// re-validator on a per-`:children`-entry patch — each reaches the
3686 /// three per-entry axes through this one dispatch rather than
3687 /// re-inlining the three-arm cascade in lockstep with `validate`
3688 /// (the duplication the PRIME DIRECTIVE names as a bug) or paying
3689 /// the peer `:estrategia`/`:max-restarts`/`:restart-window` gates to
3690 /// reach one entry check.
3691 ///
3692 /// Self-contained on `&self` — resolves its own dedup `HashSet`
3693 /// through [`SupervisorSpec::children`] rather than borrowing one
3694 /// threaded down from `validate`, the same posture the peer M3
3695 /// mesh-slot per-slot gates ([`crate::AplicacaoSpec::validate_membros`],
3696 /// [`crate::AplicacaoSpec::validate_contratos`],
3697 /// [`crate::AplicacaoSpec::validate_entrada`],
3698 /// [`crate::AplicacaoSpec::validate_placement`]) each carry, so a
3699 /// consumer that reaches this gate directly (without first calling
3700 /// `validate`) still runs the full per-child cascade — pinned by
3701 /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
3702 /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
3703 /// + `validate_children_is_self_contained_on_children_slot`.
3704 ///
3705 /// The three per-entry arms run in the same canonical order the
3706 /// pre-lift inline cascade encoded (DNS-1123 → semver → dedup), so
3707 /// the diagnostic every author-declared per-`:children` entry surfaces
3708 /// through `validate` is byte-equal to the diagnostic this gate
3709 /// surfaces when called directly — the equivalence-pin pair
3710 /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
3711 /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
3712 /// asserts the two altitudes discriminate the same set on every
3713 /// per-entry-covered input.
3714 pub fn validate_children(&self) -> Result<(), SupervisorError> {
3715 let mut seen = std::collections::HashSet::new();
3716 for child in self.children() {
3717 // Every emitted cluster artifact's `metadata.name` for a
3718 // supervised child derives from this `:children :caixa` value
3719 // verbatim — the rendered `wasm.pleme.io/v1alpha1/ComputeUnit
3720 // .metadata.name` per child, the [`crate::LABEL_PROGRAM`]
3721 // label value on every child's pod identity, and the per-
3722 // child K8s [`Service`][svc] `metadata.name` the future
3723 // wasm-operator (M3) provisions for inter-child supervision
3724 // tree wiring. Each apiserver-side schema on each landing
3725 // site enforces the DNS-1123 label rule on admission; a
3726 // structurally invalid child name (`"Worker"`, `"my_worker"`,
3727 // `"team.worker"`, `"-worker"`, `"worker-"`, the >63-byte
3728 // UUID-shaped mistaken-identity slug) silently passes the
3729 // prior empty-/duplicate-only gate and the failure surfaces
3730 // at `kubectl apply` time as a `metadata.name: Invalid value`
3731 // rejection, far from the source caixa.lisp, with no field
3732 // naming the offending `:children` entry. Lifting the gate
3733 // to caixa-build time mirrors the `:membros :caixa` value-
3734 // shape trajectory (3f9d7a0) and the `:placement :clusters`
3735 // trajectory (6cbb900) onto the third DNS-1123-label-shaped
3736 // identifier axis — the supervisor tree's child names —
3737 // through the lifted
3738 // [`crate::render::require_valid_dns_1123_label`] gate the
3739 // seven peer name axes (`:membros :caixa`, `:placement
3740 // :clusters`, `:placement :affinity`, `:contratos :de`/`:para`,
3741 // `:entrada :para`, `:nome`, `:upgrade-from :module`) each
3742 // route through, so drift between the eight axes' accepted
3743 // DNS-1123-label sets is structurally impossible.
3744 //
3745 // [svc]: https://kubernetes.io/docs/concepts/services-networking/service/
3746 crate::render::require_valid_dns_1123_label(
3747 child.nome(),
3748 || SupervisorError::EmptyChildName,
3749 |reason| SupervisorError::child_caixa_invalid(child.nome(), reason),
3750 )?;
3751 // The author surface for `:children :versao` is the same
3752 // Cargo-shaped semver requirement string `:deps :versao` and
3753 // `:membros :versao` carry — and the lacre pipeline resolves
3754 // all three axes through the same
3755 // [`crate::version::parse_requirement`] entry-point. The
3756 // shared [`crate::render::require_valid_versao_requirement`]
3757 // helper brackets the empty-first + parse cascade both peer
3758 // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
3759 // [`crate::AplicacaoSpec::validate_membros`] on `:membros
3760 // :versao`) route through, so drift between the three axes'
3761 // accepted requirement sets is structurally impossible and
3762 // the parse-side no-op the empty-first arm closes (semver's
3763 // empty parse yields an implicit `*`) lives in exactly one
3764 // predicate. Every `ChildSpec::versao` past validate is
3765 // round-trippable through [`crate::parse_requirement`]
3766 // without re-checking at the resolver layer, and the three
3767 // `:versao` typed surfaces (`:deps`, `:membros`, `:children`)
3768 // are now structurally equivalent by construction.
3769 crate::render::require_valid_versao_requirement(
3770 child.versao_requirement(),
3771 || SupervisorError::empty_child_version(child.nome()),
3772 |reason| {
3773 SupervisorError::child_versao_invalid(
3774 child.nome(),
3775 child.versao_requirement(),
3776 reason,
3777 )
3778 },
3779 )?;
3780 crate::render::insert_first_seen(&mut seen, child.nome(), || {
3781 SupervisorError::duplicate_child_caixa(child.nome())
3782 })?;
3783 }
3784 Ok(())
3785 }
3786}
3787
3788/// Cross-slot coherence gate on the supervision tree: no
3789/// `:children :caixa` entry may name the supervisor's own `:nome`.
3790///
3791/// A supervisor that lists itself as a child is a degenerate self-parent
3792/// — the supervision tree is a DAG rooted at the supervisor (OTP child
3793/// specs reference *distinct* child processes; a supervisor is never its
3794/// own child), and the wasm-operator's hierarchical reconciliation would
3795/// otherwise be handed a node that is its own parent: a one-node cycle it
3796/// either rejects far from the source `caixa.lisp` or recurses on. Because
3797/// every `:nome` is a globally-unique substrate identity (DNS-1123 label +
3798/// lacre closure root), a child whose `:caixa` equals the supervisor's
3799/// `:nome` *is* the supervisor itself, not a coincidentally-named peer.
3800///
3801/// Lives outside [`SupervisorSpec::validate`] because the typed view
3802/// carries the children but not the parent `:nome`; mirrors the
3803/// cross-slot precedence gate `validate_upgrade_from_against_versao`
3804/// (which likewise reads one slot against another at the
3805/// [`crate::layout`] wire-up site) and the mesh self-edge gate
3806/// `AplicacaoSpec`'s `ContratoSelfLoop` — the same "an edge from a graph
3807/// node to itself is structurally not a tree/mesh edge" discipline, here
3808/// on the supervision-tree axis.
3809pub fn validate_no_self_supervision(
3810 children: &[ChildSpec],
3811 parent_nome: &str,
3812) -> Result<(), SupervisorError> {
3813 for child in children {
3814 if child.nome() == parent_nome {
3815 return Err(SupervisorError::child_supervises_self(parent_nome));
3816 }
3817 }
3818 Ok(())
3819}
3820
3821#[derive(Debug, Error, PartialEq, Eq)]
3822pub enum SupervisorError {
3823 #[error("supervisor :estrategia {estrategia:?} requires at least one :children entry")]
3824 NoChildren { estrategia: RestartStrategy },
3825 #[error(
3826 "SimpleOneForOne supervisors must declare zero static children (children spawn dynamically)"
3827 )]
3828 SimpleOneForOneWithStaticChildren,
3829 #[error(":max-restarts must be > 0")]
3830 ZeroMaxRestarts,
3831 #[error(
3832 ":supervisor :max-restarts ({max_restarts}) exceeds the supervisor-policy ceiling \
3833 (SUPERVISOR_MAX_RESTARTS_MAX = 1000) — a value above this cap turns the typed \
3834 restart-intensity policy into a no-op supervisor: the escalation threshold is \
3835 structurally so high that no realistic restarts-per-:restart-window traffic shape \
3836 can reach it, so the supervisor never escalates to its parent and a bad child can \
3837 loop inside the window indefinitely. Every typed-slot consumer (Erlang/OTP's \
3838 MaxIntensity/Period ratio, the future wasm-operator's per-supervisor \
3839 restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
3840 materializer's admission webhook) emits a `:max-restarts` declaration that is \
3841 structurally never reached. Pin a value in 1..=1000 (Erlang/OTP / Elixir / Riak \
3842 Core / RabbitMQ production playbooks recommend 3..=100; the OTP `supervisor` \
3843 callback module's `MaxR = 1` minimal-restart default sits at the bottom of the \
3844 band) or restructure the supervision tree (split the flaky child into its own \
3845 sub-supervisor with a tighter budget) if you need a higher restart tolerance."
3846 )]
3847 MaxRestartsExceedsCap { max_restarts: u32 },
3848 #[error(
3849 ":restart-window must be > 0 when set — Erlang/OTP's MaxIntensity/Period \
3850 requires Period > 0; a zero window either trips on the first failure or \
3851 never trips depending on operator interpretation. Omit :restart-window to \
3852 express `never reset`; carry a positive duration to express the window."
3853 )]
3854 RestartWindowZero,
3855 #[error(
3856 ":supervisor :restart-window ({window:?}) carries a sub-millisecond residue the shared `duration_codec` cannot round-trip — \
3857 the codec truncates to `as_millis()` before picking the canonical unit, so a value with `subsec_nanos() % 1_000_000 != 0` either \
3858 truncates on first serialize (e.g. `Duration::from_micros(1500)` → \"1ms\" → `Duration::from_millis(1)` ≠ original) or renders \
3859 as \"0s\" the `RestartWindowZero` arm then rejects on re-validate. Pin an integer-millisecond magnitude in the canonical authoring form \
3860 (`<integer><unit>` for unit ∈ {{ms, s, m, h}}, e.g. `\"500ms\"`, `\"30s\"`, `\"2m\"`, `\"1h\"`) or omit the field for `never reset`"
3861 )]
3862 RestartWindowNotCanonical { window: Duration },
3863 #[error(
3864 ":supervisor :restart-window ({window:?}) exceeds the supervisor-policy ceiling \
3865 (SUPERVISOR_RESTART_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
3866 per-supervisor rolling-window restart-intensity counter into a lifetime counter: the \
3867 failure-counting window is structurally so long that transient restarts are never \
3868 forgotten, the MaxIntensity/Period ratio degenerates from `trip the parent supervisor \
3869 when the child has exceeded its restart budget within the recent window` to `trip the \
3870 parent when the child has exceeded its restart budget over its lifetime`, and the \
3871 supervisor's reset semantic never reaches the child — every typed-slot consumer \
3872 (Erlang/OTP's MaxIntensity/Period reconciler, the future wasm-operator's \
3873 per-supervisor restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
3874 materializer's admission webhook, the caixa-operator's hierarchical reconciliation \
3875 scheduler) emits a `:restart-window` declaration that is structurally a no-op rolling \
3876 window. Pin a value in 1ms..=1h (Learn You Some Erlang's `{{intensity, 5, 60}}` \
3877 worker-supervisor `Period = 60s` default, Elixir's `Supervisor` `max_seconds: 5` \
3878 default, OTP's `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's \
3879 `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default — every Erlang/OTP \
3880 / Elixir production playbook sits in the 5s..=300s band; the longest documented \
3881 per-supervisor restart-window any pleme-io substrate playbook recommends maxes at \
3882 ~30m) or omit :restart-window to express `never reset` (the supervisor's restart \
3883 budget then becomes a strict lifetime counter by design, not a degenerate one — the \
3884 author surfaces the lifetime-counter semantic explicitly at the slot, rather than \
3885 hiding it behind a rolling-window declaration the cap arm rejects)"
3886 )]
3887 RestartWindowExceedsCap { window: Duration },
3888 #[error("child entry has empty :caixa name")]
3889 EmptyChildName,
3890 #[error(
3891 "child :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
3892 (the K8s apiserver enforces this rule on every `metadata.name` / Service \
3893 name / label value the child name lands in — the per-child \
3894 `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name`, the `LABEL_PROGRAM` \
3895 label value, and the future wasm-operator per-child Service `metadata.name` \
3896 — each apiserver-side schema rejects names that don't match; use a \
3897 lowercase alphanumeric + hyphen identifier like `\"worker\"` or `\"cache-v2\"`)"
3898 )]
3899 ChildCaixaInvalid { caixa: String, reason: String },
3900 #[error("child {caixa:?} has empty :versao constraint")]
3901 EmptyChildVersion { caixa: String },
3902 #[error(
3903 "child {caixa:?} :versao {versao:?} is not a valid semver requirement: \
3904 {reason} (use Cargo-shaped forms like `\"^0.1\"`, `\"~0.1.2\"`, \
3905 `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` and \
3906 `:membros :versao` carry; the lacre pipeline resolves all three \
3907 through the same parser)"
3908 )]
3909 ChildVersaoInvalid {
3910 caixa: String,
3911 versao: String,
3912 reason: String,
3913 },
3914 #[error(
3915 "child {caixa:?} appears more than once (Erlang/OTP requires unique \
3916 child_spec.id per supervisor; duplicate children materialize as duplicate \
3917 ComputeUnits in the rendered chart, one silently overwriting the other)"
3918 )]
3919 DuplicateChildCaixa { caixa: String },
3920 #[error(
3921 "supervisor {caixa:?} lists itself as a :children entry — a supervisor is \
3922 never its own child (the supervision tree is a DAG rooted at the supervisor; \
3923 OTP child specs reference distinct child processes). Since every :nome is a \
3924 globally-unique substrate identity, a child naming the supervisor's own :nome \
3925 is a one-node reconciliation cycle, not a coincidentally-named peer; drop the \
3926 self-referential :children entry or rename it to the actual child caixa."
3927 )]
3928 ChildSupervisesSelf { caixa: String },
3929}
3930
3931// Fold the three `SupervisorError::<Variant> { caixa: <&str>.to_string() }`
3932// caixa-only struct-variant wire-up sites at [`SupervisorSpec::validate_children`]
3933// and [`validate_no_self_supervision`] onto one substrate primitive per
3934// typed variant — the sibling on `SupervisorError` of the four uniform-shape
3935// `LayoutError`-envelope constructor families the peer
3936// [`crate::layout::layout_violation_ctors!`] macro closed (131ca0d, 16
3937// variants on `{ caixa, issue }`), the [`crate::layout::layout_slot_kind_ctors!`]
3938// macro closed (0419438, 4 variants on `{ caixa, kind, slots }`), the
3939// [`crate::LayoutError::missing_entry`] one-variant ctor closed (1b09f9d,
3940// on `{ kind, path }`), and the [`crate::layout::layout_nome_only_ctors!`]
3941// macro closed (3fe3dd7, 6 variants on `<Variant>(String)`), plus the
3942// [`crate::AplicacaoError::entrada_host_invalid`] one-variant ctor
3943// (17dd504, `{ host, reason }`), the [`crate::aplicacao::contrato_target_ctors!`]
3944// macro (14b81d5, 2 variants on `{ de, para, wit, expected }`), and the
3945// [`crate::aplicacao::contrato_empty_pair_ctors!`] macro (8580068, 4
3946// variants on `{ de, para }`) already at that discipline on the peer
3947// `AplicacaoError` envelopes.
3948//
3949// Each of the three wire-up sites on this shape (`EmptyChildVersion` at
3950// the per-`:children` semver-requirement empty-first arm, `DuplicateChildCaixa`
3951// at the per-`:children` dedup arm, `ChildSupervisesSelf` at the cross-slot
3952// self-supervision arm) opened the identical
3953// `SupervisorError::<Variant> { caixa: <&str>.to_string() }` struct-literal —
3954// the exact "same block re-inlined at every consumer" shape the PRIME
3955// DIRECTIVE names as a bug, on the same altitude the peer `LayoutError` /
3956// `AplicacaoError` families each closed on their sibling envelopes. The
3957// three variants share one `{ caixa: String }` shape, so the fold routes
3958// each wire-up site through one dispatch per typed variant.
3959//
3960// The macro below generates one static constructor per variant of shape
3961// `fn <slot>(caixa: &str) -> SupervisorError`, so every wire-up site
3962// collapses onto one dispatch:
3963// `SupervisorError::<slot>(<&str>)`, byte-equal to the pre-lift
3964// struct-literal on the same `&str` fixture. The uniform one-field
3965// construction (`caixa: caixa.to_string()`) is spelled once — inside the
3966// macro — rather than at every wire-up site. Every constructor is
3967// `#[must_use]` so a caller who mistakenly discards the constructed error
3968// trips a compile warning at the wire-up site.
3969//
3970// Every future consumer that wants to construct one of these three
3971// variants outside `SupervisorSpec::validate_children` /
3972// `validate_no_self_supervision` — a deferred
3973// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3974// webhook re-checking one added/renamed child, a future
3975// `feira validate --supervisor` per-caixa admission verb, a per-child
3976// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path
3977// once dynamic-children graduate to a typed slot, a per-Supervisor
3978// overlay resolver rejecting a duplicate/self-supervising child against
3979// a cluster-local snapshot — now reaches each variant through one call
3980// rather than re-inlining the three-line struct-literal in lockstep
3981// with the three in-crate wire-up sites.
3982macro_rules! supervisor_caixa_only_ctors {
3983 ($($ctor:ident => $variant:ident),* $(,)?) => {
3984 impl SupervisorError {
3985 $(
3986 #[doc = concat!(
3987 "Construct a [`SupervisorError::",
3988 stringify!($variant),
3989 "`] naming the offending `:children :caixa` (or ",
3990 "supervisor `:nome`, on the self-supervision arm). ",
3991 "Folds the uniform `Self::",
3992 stringify!($variant),
3993 " { caixa: caixa.to_string() }` one-field ",
3994 "struct-literal onto one substrate primitive so ",
3995 "every [`SupervisorSpec::validate_children`] / ",
3996 "[`validate_no_self_supervision`] wire-up on this ",
3997 "variant reads through one dispatch rather than the ",
3998 "pre-lift open-coded struct-literal block."
3999 )]
4000 #[must_use]
4001 pub fn $ctor(caixa: &str) -> Self {
4002 Self::$variant { caixa: caixa.to_string() }
4003 }
4004 )*
4005 }
4006 };
4007}
4008
4009supervisor_caixa_only_ctors! {
4010 empty_child_version => EmptyChildVersion,
4011 duplicate_child_caixa => DuplicateChildCaixa,
4012 child_supervises_self => ChildSupervisesSelf,
4013}
4014
4015// Fold the two `SupervisorError::{ChildCaixaInvalid, ChildVersaoInvalid}`
4016// struct-variant wire-up sites at [`SupervisorSpec::validate_children`] onto
4017// one substrate primitive per typed variant — the M2 supervisor-side siblings
4018// of the peer [`crate::AplicacaoError::membro_caixa_invalid`] two-slot ctor
4019// already lifted through the sibling
4020// [`crate::aplicacao::aplicacao_field_reason_ctors!`] macro (981060b) on the
4021// peer `AplicacaoError { caixa: String, reason: String }` envelope. The
4022// `ChildCaixaInvalid` variant carries the same `{ <name>: String, reason:
4023// String }` two-slot shape the peer seven-variant
4024// [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold closed on the
4025// `AplicacaoError` envelope (`MembroCaixaInvalid`, `EntradaParaInvalid`,
4026// `EntradaHostInvalid`, `EntradaPathInvalid`, `PlacementClusterInvalid`,
4027// `PlacementAffinityInvalid`, `ShardKeyInvalid`); the `ChildVersaoInvalid`
4028// variant carries the `{ caixa: String, versao: String, reason: String }`
4029// three-slot shape the sibling `AplicacaoError::MembroVersaoInvalid` axis
4030// carries on the same `:versao` value-shape.
4031//
4032// Each of the two wire-up sites opened the same closure-shaped
4033// `|reason| SupervisorError::<Variant> { caixa: child.nome().to_string(),
4034// [versao: child.versao_requirement().to_string(),] reason }` block inside
4035// the paired [`crate::render::require_valid_dns_1123_label`] and
4036// [`crate::render::require_valid_versao_requirement`] callbacks — the exact
4037// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE names
4038// as a bug, on the same altitude the peer `AplicacaoError` /
4039// `SupervisorError` / `LayoutError` / `DepError` / `LimitsError` ctor
4040// families already closed on their sibling envelopes.
4041//
4042// The two `#[must_use]` inherent constructors below fold each wire-up onto
4043// one dispatch: `SupervisorError::child_caixa_invalid(<name>, <reason>)`
4044// and `SupervisorError::child_versao_invalid(<name>, <versao>, <reason>)`,
4045// byte-equal to the pre-lift struct-literal on the same scalar fixtures.
4046// The uniform per-field `.to_string()` / `.into()` construction is spelled
4047// once — inside each ctor body — rather than at every wire-up site. The
4048// `reason: impl Into<String>` bound accepts both `&str` literals and
4049// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
4050// diagnostic shape at the lift, matching the peer
4051// [`aplicacao_field_reason_ctors!`] and
4052// [`crate::aplicacao::contrato_pair_value_reason_ctors!`] bounds on the
4053// sibling envelopes.
4054//
4055// Every future consumer that wants to construct one of these two variants
4056// outside `SupervisorSpec::validate_children` — a deferred
4057// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook
4058// re-checking one added/renamed child's `:caixa` or `:versao`, a future
4059// `feira validate --supervisor` per-caixa admission verb, a per-child
4060// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path once
4061// dynamic-children graduate to a typed slot, a per-Supervisor overlay
4062// resolver rejecting a shape-invalid child `:caixa`/`:versao` against a
4063// cluster-local snapshot — now reaches each variant through one call rather
4064// than re-inlining the per-shape struct-literal block in lockstep with the
4065// two in-crate wire-up sites.
4066impl SupervisorError {
4067 /// Construct a [`SupervisorError::ChildCaixaInvalid`] naming the
4068 /// offending `:children :caixa` value under the given `reason`. Folds
4069 /// the uniform `Self::ChildCaixaInvalid { caixa: caixa.to_string(),
4070 /// reason: reason.into() }` two-slot struct-literal onto one substrate
4071 /// primitive so every wire-up on this variant reads through one
4072 /// dispatch, matching the peer
4073 /// [`crate::AplicacaoError::membro_caixa_invalid`] ctor's shape on the
4074 /// sibling `AplicacaoError { caixa: String, reason: String }`
4075 /// envelope. `reason` accepts both `&str` literals and `format!(…)`
4076 /// outputs through the `impl Into<String>` bound.
4077 #[must_use]
4078 pub fn child_caixa_invalid(caixa: &str, reason: impl Into<String>) -> Self {
4079 Self::ChildCaixaInvalid {
4080 caixa: caixa.to_string(),
4081 reason: reason.into(),
4082 }
4083 }
4084
4085 /// Construct a [`SupervisorError::ChildVersaoInvalid`] naming the
4086 /// offending `:children :caixa` and its `:versao` requirement under
4087 /// the given `reason`. Folds the uniform `Self::ChildVersaoInvalid {
4088 /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
4089 /// reason.into() }` three-slot struct-literal onto one substrate
4090 /// primitive so every wire-up on this variant reads through one
4091 /// dispatch, matching the sibling `AplicacaoError::MembroVersaoInvalid
4092 /// { caixa, versao, reason }` three-slot axis on the peer
4093 /// `AplicacaoError` envelope. `reason` accepts both `&str` literals
4094 /// and `format!(…)` outputs through the `impl Into<String>` bound.
4095 #[must_use]
4096 pub fn child_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
4097 Self::ChildVersaoInvalid {
4098 caixa: caixa.to_string(),
4099 versao: versao.to_string(),
4100 reason: reason.into(),
4101 }
4102 }
4103}
4104
4105// Fold the four `SupervisorError::<Variant> { <field>: <Copy> }` one-field
4106// Copy-scalar struct-variant wire-up sites at [`SupervisorSpec::validate`]'s
4107// three bracket-arms — one struct-literal at the `:children`-empty
4108// non-`SimpleOneForOne` refusal cascade (`NoChildren { estrategia }`) plus
4109// three `impl FnOnce(<ty>) -> SupervisorError` bracket-closures at the
4110// [`crate::render::require_positive_bounded_u32`] `:max-restarts` cap arm
4111// (`MaxRestartsExceedsCap { max_restarts }`) and the paired
4112// [`crate::render::require_positive_canonical_bounded_duration`]
4113// `:restart-window` canonical-form + cap arms (`RestartWindowNotCanonical
4114// { window }`, `RestartWindowExceedsCap { window }`) — onto one substrate
4115// primitive per typed variant, matching the sibling
4116// [`crate::aplicacao::aplicacao_policy_scalar_ctors!`] macro (7ef425e, 8
4117// variants on the same `{ <field>: Duration | u32 }` shape) at that
4118// discipline on the peer `AplicacaoError` envelope's per-`:politicas`
4119// scalar axis. Every variant is a one-field `Copy`-pass-through struct-
4120// literal — `RestartStrategy | u32 | Duration` — so the fold routes each
4121// wire-up site through one dispatch per typed variant without a runtime-
4122// work delta.
4123//
4124// Each of the four wire-up sites opened the identical
4125// `SupervisorError::<Variant> { <field>: <val> }` struct-literal — the
4126// exact "same block re-inlined at every consumer" shape the PRIME
4127// DIRECTIVE names as a bug, on the same altitude the peer
4128// `aplicacao_policy_scalar_ctors!` fold closed on the sibling
4129// `AplicacaoError` envelope's per-`:politicas` per-axis cap / canonical-
4130// form arms. The four variants share one `{ <field>: <Copy> }` shape, so
4131// the fold routes each wire-up site through one dispatch per typed
4132// variant.
4133//
4134// The macro below generates one static constructor per variant of shape
4135// `const fn <ctor>(<field>: <ty>) -> SupervisorError`, so every wire-up
4136// site collapses onto one dispatch: `SupervisorError::<ctor>(<val>)`,
4137// byte-equal to the pre-lift struct-literal on the same `Copy`-`<ty>`
4138// fixture — as a direct call at the [`SupervisorSpec::validate`]
4139// `:children`-empty refusal, or as a bare function pointer in the
4140// `impl FnOnce(<ty>) -> SupervisorError` bracket-closure slot every
4141// [`crate::render::require_positive_bounded_u32`] /
4142// [`crate::render::require_positive_canonical_bounded_duration`] gate
4143// carries — rather than the pre-lift open-coded one-line closure over
4144// the same one-field struct-literal. `const fn` preserves the `Copy`-
4145// pass-through's zero-runtime-work property verbatim. Every constructor
4146// is `#[must_use]` so a caller who mistakenly discards the constructed
4147// error trips a compile warning at the wire-up site.
4148//
4149// Every future consumer that wants to construct one of these four
4150// variants outside `SupervisorSpec::validate` — a deferred
4151// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
4152// webhook re-checking one edited `:estrategia` / `:max-restarts` /
4153// `:restart-window` slot against the cap + canonical-form cascade, a
4154// future `feira validate --supervisor` per-caixa admission verb re-
4155// running the shape gates on demand, a per-Supervisor overlay resolver
4156// rejecting an author-supplied slot against a cluster-local snapshot —
4157// now reaches each variant through one call rather than re-inlining the
4158// per-shape struct-literal block in lockstep with the four in-crate
4159// wire-up sites.
4160macro_rules! supervisor_scalar_ctors {
4161 ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
4162 impl SupervisorError {
4163 $(
4164 #[doc = concat!(
4165 "Construct a [`SupervisorError::",
4166 stringify!($variant),
4167 "`] naming the offending per-`:supervisor` `",
4168 stringify!($field),
4169 "` scalar. Folds the uniform `Self::",
4170 stringify!($variant),
4171 " { ",
4172 stringify!($field),
4173 " }` one-field `Copy`-pass-through struct-literal onto ",
4174 "one substrate primitive so every per-axis wire-up on ",
4175 "this variant reads through one dispatch — as a direct ",
4176 "call (`SupervisorError::",
4177 stringify!($ctor),
4178 "(<val>)`, byte-equal to the pre-lift struct-literal on ",
4179 "the same `Copy`-`",
4180 stringify!($ty),
4181 "` fixture) or as a bare function pointer in the ",
4182 "`impl FnOnce(",
4183 stringify!($ty),
4184 ") -> SupervisorError` bracket-closure slot every ",
4185 "`crate::render::require_positive_bounded_*` / ",
4186 "`crate::render::require_positive_canonical_bounded_*` ",
4187 "gate carries — rather than the pre-lift open-coded ",
4188 "one-line closure over the same one-field struct-",
4189 "literal. `const fn` preserves the `Copy`-pass-through's ",
4190 "zero-runtime-work property verbatim."
4191 )]
4192 #[must_use]
4193 pub const fn $ctor($field: $ty) -> Self {
4194 Self::$variant { $field }
4195 }
4196 )*
4197 }
4198 };
4199}
4200
4201supervisor_scalar_ctors! {
4202 no_children => NoChildren { estrategia: RestartStrategy },
4203 max_restarts_exceeds_cap => MaxRestartsExceedsCap { max_restarts: u32 },
4204 restart_window_not_canonical => RestartWindowNotCanonical { window: Duration },
4205 restart_window_exceeds_cap => RestartWindowExceedsCap { window: Duration },
4206}
4207
4208/// Shared duration string codec for the typed slots that take a
4209/// duration (`restart_window`, `MeshPolicy::timeout`,
4210/// `CircuitBreaker::window`, …). Public so [`crate::aplicacao`] can
4211/// reuse it without duplicating the parser.
4212pub mod duration_codec {
4213 use super::Duration;
4214 use serde::{Deserializer, Serializer};
4215
4216 pub fn serialize<S: Serializer>(v: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
4217 // Route through the canonical [`crate::render::serialize_option_via_str`]
4218 // — the substrate-side single-owner primitive for the forward
4219 // arm of the typed-magnitude codec family. See its docstring
4220 // for the full sibling roster.
4221 crate::render::serialize_option_via_str(v, s, render)
4222 }
4223
4224 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
4225 // Route through the canonical [`crate::render::deserialize_option_via_str`]
4226 // — the substrate-side single-owner primitive for the reverse
4227 // arm of the typed-magnitude codec family. See its docstring
4228 // for the full sibling roster.
4229 crate::render::deserialize_option_via_str(d, parse)
4230 }
4231
4232 pub(crate) fn parse(s: &str) -> Result<Duration, String> {
4233 // Paired whitespace-rejection arm — same canonical-form
4234 // render-determinism discipline as the peer
4235 // `limits::parse_byte_size` / `limits::parse_duration` /
4236 // `limits::parse_millicores` /
4237 // `aplicacao::rate_limit_codec::parse` sites: the ASCII
4238 // byte-scan closes the WhatWG-conformant whitespace bytes
4239 // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
4240 // `char::is_whitespace` scan closes the strictly-complementary
4241 // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
4242 // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
4243 // codepoints) that `str::trim` at parse entry silently strips.
4244 // Either drift class would round-trip through `render` to a
4245 // *different* canonical form on next emit — breaking the
4246 // THEORY.md Part V render-determinism contract on three typed-
4247 // duration slots at once (`:supervisor :restart-window`,
4248 // `:politicas :timeout`, `:politicas :circuit-breaker :window`)
4249 // via the shared codec.
4250 //
4251 // Routed through the lifted [`crate::render::reject_whitespace`]
4252 // primitive — the substrate-side single-owner paired-arm gate
4253 // every typed-magnitude codec in caixa-core shares.
4254 crate::render::reject_whitespace::<String, _, _>(
4255 s,
4256 |b| {
4257 format!(
4258 "duration: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
4259 authoring form for the typed duration slots routed through this shared codec \
4260 (`:supervisor :restart-window`, `:politicas :timeout`, \
4261 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
4262 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no whitespace bytes \
4263 anywhere. A whitespace-carrying shape (`\" 30s\"`, `\"30s \"`, `\"30 s\"`, \
4264 `\"\\t30s\"`, `\"30s\\n\"`) round-trips through `render` to a *different* \
4265 canonical form (`\"30s\"`) on first serialize — breaking the THEORY.md \
4266 Part V render-determinism contract every typed slot carries. Strip every \
4267 whitespace byte (write `\"30s\"` verbatim)"
4268 )
4269 },
4270 |ch| {
4271 format!(
4272 "duration: value {s:?} contains non-ASCII Unicode whitespace character \
4273 {ch:?} (U+{cp:04X}) — the canonical authoring form for the typed \
4274 duration slots routed through this shared codec (`:supervisor \
4275 :restart-window`, `:politicas :timeout`, `:politicas :circuit-breaker \
4276 :window`) is `<integer><unit>` (e.g. `\"30s\"`, `\"500ms\"`, `\"2m\"`, \
4277 `\"1h\"`) with no whitespace characters anywhere (ASCII or Unicode). A \
4278 non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}30s\"`, \
4279 `\"30s\\u{{2028}}\"`, `\"30\\u{{2003}}s\"`) survives the ASCII byte-scan \
4280 but `str::trim` (which uses `char::is_whitespace` — the Unicode \
4281 `White_Space` property, strictly wider than the ASCII byte set) silently \
4282 strips it at parse entry, and the value round-trips through `render` to \
4283 a *different* canonical form (`\"30s\"`) on first serialize — breaking \
4284 the THEORY.md Part V render-determinism contract every typed slot \
4285 carries. Strip every non-ASCII whitespace character (write `\"30s\"` \
4286 verbatim with only ASCII bytes)",
4287 cp = ch as u32
4288 )
4289 },
4290 )?;
4291 let s = s.trim();
4292 // Routed through the lifted
4293 // [`crate::render::split_magnitude_and_alpha_unit`] primitive —
4294 // the single-owner split every ASCII-alphabetic-unit typed-
4295 // magnitude codec in caixa-core (`limits::parse_byte_size` /
4296 // `limits::parse_duration` / this shared duration codec) shares.
4297 // See its docstring for the full sibling roster on the same
4298 // primitive altitude.
4299 let (num_part, unit) = crate::render::split_magnitude_and_alpha_unit(s);
4300 let num_trim = num_part.trim();
4301 // The canonical authoring form for every typed slot routed
4302 // through this shared codec — `:supervisor :restart-window`,
4303 // `:politicas :timeout`, `:politicas :circuit-breaker :window`
4304 // — is `<integer><unit>`. Every magnitude [`render`] emits is a
4305 // non-negative integer with no decimal point and no leading
4306 // sign, so the parser's accepted set must match for
4307 // serialize/deserialize to round-trip without canonical-form
4308 // drift. Until this gate landed the parser accepted any
4309 // `f64`-shaped magnitude (`"1.5s"` → 1500ms, `"1.0s"` → 1s,
4310 // `"0.5m"` → 30s, `"+30s"` → 30s) and serde silently round-
4311 // tripped the value to a *different* canonical string on the
4312 // next emit (`"1.5s"` → 1500ms → `"1500ms"`, `"1.0s"` → 1s →
4313 // `"1s"`, `"0.5m"` → 30s → `"30s"`, `"+30s"` → 30s → `"30s"`)
4314 // — breaking the THEORY.md Part V render-determinism contract
4315 // on three typed slots at once. Same canonical-form discipline
4316 // `crate::limits::parse_duration` (818dd38, the immediate
4317 // predecessor on the peer `:limits :wall-clock` codec) applies;
4318 // this gate lifts the discipline onto the shared codec that
4319 // backs the remaining three typed-duration slots in caixa-core.
4320 //
4321 // Strict canonical form: every byte of the magnitude is an
4322 // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
4323 // inputs the gate distinguishes "non-canonical-but-numeric"
4324 // (parses as f64 or i64 — surfaced with a self-locating
4325 // diagnostic naming the canonical authoring form, the
4326 // round-trip drift each rejected shape would produce on first
4327 // serialize, and the canonical-form remediation) from
4328 // "garbage" (parses as neither — surfaced with the existing
4329 // narrower "bad duration magnitude" wording so its diagnostic
4330 // shape remains stable for the parser-shape footgun case).
4331 // The pre-existing `num < 0.0` arm is now unreachable — the
4332 // digit-only gate strictly precedes magnitude parsing, and a
4333 // leading `-` is not an ASCII digit, so `"-30s"` lands on the
4334 // non-canonical-but-numeric branch with the `-30` named
4335 // verbatim in the diagnostic rather than the prior
4336 // value-laundered "negative duration in \"-30s\"" wording.
4337 //
4338 // Routed through the lifted
4339 // [`crate::render::is_digit_only_magnitude`] predicate — the
4340 // same source of truth the four peer typed-magnitude codec
4341 // sites share.
4342 let digit_only = crate::render::is_digit_only_magnitude(num_trim);
4343 if !digit_only {
4344 let numeric = num_trim.parse::<f64>().is_ok() || num_trim.parse::<i64>().is_ok();
4345 if numeric {
4346 return Err(format!(
4347 "duration: magnitude {num_trim:?} is not a non-negative integer — the \
4348 canonical authoring form for the typed duration slots routed through \
4349 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
4350 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
4351 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no decimal point and \
4352 no leading `+` / `-` sign. A fractional / decimal-shaped magnitude \
4353 (`\"1.5s\"`, `\"1.0s\"`, `\"0.5m\"`, `\"+30s\"`, `\"-30s\"`) round-trips \
4354 through `render` to a *different* canonical form (`\"1500ms\"`, `\"1s\"`, \
4355 `\"30s\"`, `\"30s\"`, `\"30s\"`) on first serialize — breaking the \
4356 THEORY.md Part V render-determinism contract every typed slot carries. \
4357 Pick an integer magnitude in the unit that divides cleanly (write \
4358 `\"1500ms\"` instead of `\"1.5s\"`; `\"30s\"` instead of `\"0.5m\"`)"
4359 ));
4360 }
4361 return Err(format!("bad duration magnitude in {s:?}"));
4362 }
4363 // Leading-zero arm — peer with the `rate_limit_codec` leading-
4364 // zero arm (4f46830) on the same canonical-form render-
4365 // determinism axis. The digit-only gate accepts `"030s"`,
4366 // `"00s"`, `"01h"`, `"0500ms"` as `u64::from_str` parses them
4367 // losslessly (= 30, 0, 1, 500), but `render` emits the leading-
4368 // zero-stripped form (`"30s"`, `"0s"`, `"1h"`, `"500ms"`) — a
4369 // *different* canonical string on the next emit, breaking the
4370 // THEORY.md Part V render-determinism contract the same way
4371 // `"+30s"` did before the leading-`+` arm landed. The single-
4372 // byte magnitude `"0"` (or `"0s"` / `"0ms"`) round-trips
4373 // losslessly through `render` (`render(Duration::ZERO)` emits
4374 // `"0s"`) — the downstream semantic-zero gates (e.g.
4375 // `SupervisorError::ZeroRestartWindow` on
4376 // `:supervisor :restart-window`,
4377 // `AplicacaoError::PolicyTimeoutZero` /
4378 // `PolicyCircuitBreakerWindowZero` on the typed `:politicas`
4379 // duration slots) refuse zero-magnitude authoring at the typed-
4380 // validate layer above, so the single-byte `"0"` stays in the
4381 // accepted set at this codec layer and the diagnostic
4382 // partitioning between canonical-form drift (this arm) and
4383 // semantic-zero (the downstream gates) remains stable.
4384 // Peer with the future leading-zero arms on the two remaining
4385 // typed-magnitude codecs the trajectory acknowledges:
4386 // `limits::parse_duration` backing `:limits :wall-clock`,
4387 // `limits::parse_byte_size` backing `:limits :memory` — each
4388 // carries the same canonical-form-drift class today; this
4389 // gate lands the discipline on the shared duration codec
4390 // first because the `rate_limit_codec` predecessor on the
4391 // same canonical-form-drift axis is the closest peer on the
4392 // trajectory.
4393 //
4394 // Routed through the lifted
4395 // [`crate::render::is_leading_zero_padded_magnitude`]
4396 // predicate — the same source of truth the four peer
4397 // typed-magnitude codec sites share.
4398 if crate::render::is_leading_zero_padded_magnitude(num_trim) {
4399 return Err(format!(
4400 "duration: magnitude {num_trim:?} has a non-canonical leading zero — the \
4401 canonical authoring form for the typed duration slots routed through \
4402 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
4403 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
4404 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no leading-zero padding \
4405 on the magnitude. A leading-zero magnitude (`\"030s\"`, `\"00s\"`, \
4406 `\"01h\"`, `\"0500ms\"`) round-trips through `render` to a *different* \
4407 canonical form (`\"30s\"`, `\"0s\"`, `\"1h\"`, `\"500ms\"`) on first \
4408 serialize — breaking the THEORY.md Part V render-determinism contract \
4409 every typed slot carries. Strip the leading zeros (write \
4410 `\"30s\"` instead of `\"030s\"`)"
4411 ));
4412 }
4413 // The digit-only gate guarantees every byte is `[0-9]`, and
4414 // the leading-zero arm above guarantees the magnitude is
4415 // either the single byte `"0"` or starts with `[1-9]`, so
4416 // the only way `u64::from_str` can fail here is overflow (the
4417 // magnitude exceeds `u64::MAX`). Surface that with an
4418 // overflow-shaped wording so the diagnostic names the offending
4419 // magnitude verbatim rather than collapsing onto the
4420 // non-canonical arm. The codec now operates on `u64` end-to-end
4421 // — every accepted magnitude is integer-exact; no f64 mantissa
4422 // drift between author-supplied magnitude and the consumer's
4423 // `Duration` value. Same shape `crate::limits::parse_duration`
4424 // (818dd38) carries on the peer `:limits :wall-clock` axis.
4425 let num: u64 = num_trim.parse::<u64>().map_err(|_| {
4426 format!("bad duration magnitude in {s:?} (digit-only magnitude overflows u64)")
4427 })?;
4428 // Route the `{"ms" | "s" | "" | "m" | "h"} → Duration`
4429 // unit-arm dispatch through the canonical
4430 // [`crate::render::duration_from_integer_magnitude_and_unit`]
4431 // primitive — the substrate-side single-owner unit-dispatch
4432 // table every typed-duration codec in caixa-core routes
4433 // through (peer: `crate::limits::parse_duration` backing
4434 // `:limits :wall-clock`). Every unit conversion is integer-
4435 // exact for an integer magnitude; overflow surfaces via the
4436 // typed `DurationUnitError::Overflow { multiplier }`
4437 // discriminant so this arm reconstructs the pre-lift
4438 // `"duration <num><unit> overflows u64 (magnitude × 60 …)"`
4439 // wording verbatim from `num` / `unit_trim` / the returned
4440 // `multiplier`, and the unknown-unit arm reconstructs the
4441 // pre-lift `"unknown duration unit \"<other>\""` wording from
4442 // the caller-scoped `unit_trim`. Load-bearing pinned by
4443 // `crate::render::tests::duration_from_integer_magnitude_and_unit_matches_pre_lift_unit_dispatch_table`.
4444 let unit_trim = unit.trim();
4445 let dur = crate::render::duration_from_integer_magnitude_and_unit(num, unit_trim).map_err(
4446 |e| match e {
4447 crate::render::DurationUnitError::Overflow { multiplier } => format!(
4448 "duration {num}{unit_trim} overflows u64 (magnitude × {multiplier} > 2^64-1)"
4449 ),
4450 crate::render::DurationUnitError::UnknownUnit => {
4451 format!("unknown duration unit {unit_trim:?}")
4452 }
4453 },
4454 )?;
4455 Ok(dur)
4456 }
4457
4458 /// Render a [`Duration`] in the canonical pleme-io duration string
4459 /// form (`"30s"`, `"1m"`, `"1h"`, `"500ms"`). The same form every
4460 /// caixa typed-duration slot serializes to and the same form K8s
4461 /// Gateway API HTTPRoute `timeouts` / `backendRequest` and Cilium
4462 /// EnvoyConfig per-route timeouts both expect (an integer
4463 /// followed by `s`/`m`/`h`/`ms`, no fractional values, no leading
4464 /// `+`). Lifted to `pub` so caixa-side renderers
4465 /// (`caixa-mesh::gateway_routes`'s :politicas :timeout overlay,
4466 /// the future per-:politicas `CiliumClusterwideEnvoyConfig`
4467 /// emitter, the future caixa-otel collector pipeline emitter) can
4468 /// consume the same canonical formatter without re-inlining the
4469 /// magnitude/unit decision tree (and inheriting the same drift
4470 /// footguns: a subtly different `300ms` vs `0.3s` rendering breaks
4471 /// downstream apply-time parsing in non-obvious ways).
4472 pub fn render(d: Duration) -> String {
4473 let total_ms = d.as_millis();
4474 if total_ms == 0 {
4475 return "0s".into();
4476 }
4477 if total_ms.is_multiple_of(3600 * 1000) {
4478 return format!("{}h", total_ms / (3600 * 1000));
4479 }
4480 if total_ms.is_multiple_of(60 * 1000) {
4481 return format!("{}m", total_ms / (60 * 1000));
4482 }
4483 if total_ms.is_multiple_of(1000) {
4484 return format!("{}s", total_ms / 1000);
4485 }
4486 format!("{total_ms}ms")
4487 }
4488
4489 /// True iff `d` round-trips losslessly through [`render`] + [`parse`].
4490 ///
4491 /// [`render`] truncates a `Duration` to `as_millis()` before picking the
4492 /// largest divisor unit, so any sub-millisecond residue
4493 /// (`d.subsec_nanos() % 1_000_000 != 0`) silently breaks the THEORY.md
4494 /// §V.2.7 render-determinism contract:
4495 ///
4496 /// - `Duration::from_micros(1500)` (= `1_500_000` ns) → `as_millis() == 1`
4497 /// → renders `"1ms"` → parses back to `Duration::from_millis(1)` =
4498 /// `1_000_000` ns ≠ original `1_500_000` ns;
4499 /// - `Duration::from_nanos(1)` (= 1 ns) → `as_millis() == 0` →
4500 /// renders the literal `"0s"`, which the per-axis zero-floor gate
4501 /// on every typed-`Duration` slot then rejects on re-validate.
4502 ///
4503 /// Lifted to a `pub` predicate next to the [`render`] / [`parse`] pair so
4504 /// the codec's round-trippable accepted set lives in exactly one place —
4505 /// every typed-`Duration` slot that routes through this shared codec
4506 /// (`SupervisorSpec::restart_window` via [`super::duration_codec`],
4507 /// [`crate::MeshPolicy::timeout`] / [`crate::CircuitBreaker::window`] via
4508 /// `supervisor::duration_codec` + [`super::duration_codec_required`]) and
4509 /// every typed-`Duration` slot whose own codec shares the same
4510 /// `as_millis()`-truncation shape ([`crate::LimitsSpec::wall_clock`] via
4511 /// [`crate::limits`]'s in-module `parse_duration` / `render_duration`
4512 /// pair) calls this predicate from its `validate()` to bracket the
4513 /// accepted set against the codec's accepted set, structurally. Drift
4514 /// between the codec's granularity and any typed slot's accepted set is
4515 /// then a single-source-of-truth edit at this predicate rather than a
4516 /// silent round-trip break the next consumer discovers at apply time.
4517 ///
4518 /// Peer of [`crate::aplicacao::POLICY_RETRIES_MAX`] /
4519 /// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] and the
4520 /// `is_dns_1123_label` / `is_canonical_rate_limit_window` predicate
4521 /// family — same "typed-slot's valid set matches its codec's accepted
4522 /// set, structurally" discipline carried at the codec layer.
4523 #[must_use]
4524 pub fn is_integer_millisecond_duration(d: Duration) -> bool {
4525 d.subsec_nanos().is_multiple_of(1_000_000)
4526 }
4527}
4528
4529/// Required-Duration variant for fields that aren't Option<Duration>.
4530pub mod duration_codec_required {
4531 use super::Duration;
4532 use serde::{Deserialize, Deserializer, Serializer};
4533
4534 pub fn serialize<S: Serializer>(v: &Duration, s: S) -> Result<S::Ok, S::Error> {
4535 s.serialize_str(&super::duration_codec::render(*v))
4536 }
4537
4538 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
4539 let s = String::deserialize(d)?;
4540 super::duration_codec::parse(&s).map_err(serde::de::Error::custom)
4541 }
4542}
4543
4544#[cfg(test)]
4545mod tests {
4546 use super::*;
4547
4548 fn child(name: &str, ver: &str, restart: RestartPolicy) -> ChildSpec {
4549 ChildSpec {
4550 caixa: name.into(),
4551 versao: ver.into(),
4552 restart,
4553 }
4554 }
4555
4556 #[test]
4557 fn child_spec_string_scalar_accessor_pair_is_const_fn() {
4558 // Fail-before-pass-after pin on [`ChildSpec::nome`] +
4559 // [`ChildSpec::versao_requirement`]'s `const`-eval-surface
4560 // posture. Each accessor projects the per-`:children :caixa`
4561 // / per-`:children :versao` [`String`] storage through the
4562 // `pub const fn` [`String::as_str`] (const-stable since Rust
4563 // 1.87, well within the workspace MSRV) — any future
4564 // accidental downgrade to non-`const` fails the corresponding
4565 // `<name>_via_const_fn` wrapper at caixa-core build time with
4566 // E0015 (`cannot call non-const method`), strictly stronger
4567 // than a runtime `assert!`. Sibling of the peer
4568 // per-M2/M3/universal-axis `String → &str` scalar-accessor
4569 // family pins on the sibling `const`-eval-surface passes
4570 // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
4571 // top-level manifest, [`crate::CaixaVersion::as_str`] at the
4572 // typed-newtype wrapper, [`crate::aplicacao::Membro::nome`] /
4573 // [`crate::aplicacao::Membro::versao_requirement`] at the M3
4574 // membership axis, [`crate::aplicacao::Entrada::hostname`] /
4575 // [`crate::aplicacao::Entrada::destination`] at the M3
4576 // ingress axis,
4577 // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
4578 // M2 upgrade axis, [`crate::dep::Dep::nome`] /
4579 // [`crate::dep::Dep::versao_requirement`] at the dep-graph
4580 // axis, and the per-`:contratos`
4581 // [`crate::aplicacao::WitContract::source`] /
4582 // [`crate::aplicacao::WitContract::destination`] /
4583 // [`crate::aplicacao::WitContract::world_ref`] trio the
4584 // sibling pin at 279823b already anchors).
4585 const fn nome_via_const_fn(c: &ChildSpec) -> &str {
4586 c.nome()
4587 }
4588 const fn versao_via_const_fn(c: &ChildSpec) -> &str {
4589 c.versao_requirement()
4590 }
4591 for (caixa, versao) in [
4592 ("worker-a", "^0.1"),
4593 ("worker-b", "~0.2.3"),
4594 ("collector", "*"),
4595 ] {
4596 let c = child(caixa, versao, RestartPolicy::Permanent);
4597 assert_eq!(nome_via_const_fn(&c), c.nome());
4598 assert_eq!(versao_via_const_fn(&c), c.versao_requirement());
4599 assert_eq!(c.nome(), caixa);
4600 assert_eq!(c.versao_requirement(), versao);
4601 }
4602 }
4603
4604 #[test]
4605 fn supervisor_children_slice_return_accessor_is_const_fn() {
4606 // Fail-before-pass-after pin on [`SupervisorSpec::children`]'s
4607 // `const`-eval-surface posture. The accessor destructures the
4608 // per-`:children` `Vec<ChildSpec>` storage through the
4609 // `pub const fn` [`Vec::as_slice`] (const-stable since Rust
4610 // 1.66, well within the workspace MSRV) — any future
4611 // accidental downgrade to non-`const` fails
4612 // `children_via_const_fn` at caixa-core build time with E0015
4613 // (`cannot call non-const method`), strictly stronger than a
4614 // runtime `assert!`. Sibling of the peer per-M3-mesh-slot
4615 // `Vec → &[T]` slice-return accessor family pin
4616 // [`crate::aplicacao::tests::m3_reference_return_accessor_family_is_const_fn`]
4617 // on the M3 mesh-slot per-`:clusters` / per-`:paths` /
4618 // per-`:membros` / per-`:contratos` slice-return axes, and of
4619 // the peer M2 upgrade-appup axis pin
4620 // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
4621 // on the per-`:upgrade-from :instructions` slice-return axis.
4622 const fn children_via_const_fn(s: &SupervisorSpec) -> &[ChildSpec] {
4623 s.children()
4624 }
4625 // Sweep both the empty-children (leaf-supervisor with no
4626 // static children — the `SimpleOneForOne` dynamic-child
4627 // arm's canonical shape) and the populated-children
4628 // (`OneForOne` / `OneForAll` / `RestForOne` static-child
4629 // arm's canonical shape) axes so the accessor carries a
4630 // const-dispatch pin on both arms.
4631 let s_empty = SupervisorSpec {
4632 estrategia: RestartStrategy::SimpleOneForOne,
4633 max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
4634 restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4635 children: vec![],
4636 };
4637 assert!(children_via_const_fn(&s_empty).is_empty());
4638 assert_eq!(children_via_const_fn(&s_empty), s_empty.children());
4639 let s_full = SupervisorSpec {
4640 estrategia: RestartStrategy::OneForOne,
4641 max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
4642 restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4643 children: vec![
4644 child("worker-a", "^0.1", RestartPolicy::Permanent),
4645 child("worker-b", "~0.2.3", RestartPolicy::Transient),
4646 child("collector", "*", RestartPolicy::Temporary),
4647 ],
4648 };
4649 assert_eq!(children_via_const_fn(&s_full).len(), 3);
4650 assert_eq!(children_via_const_fn(&s_full), s_full.children());
4651 }
4652
4653 #[test]
4654 fn default_has_one_for_one_and_5_restarts_in_60s() {
4655 let s = SupervisorSpec::default();
4656 assert_eq!(s.estrategia, RestartStrategy::OneForOne);
4657 assert_eq!(s.max_restarts, 5);
4658 assert_eq!(s.restart_window, Some(Duration::from_secs(60)));
4659 assert!(s.children.is_empty());
4660 }
4661
4662 #[test]
4663 fn validate_one_for_one_requires_children() {
4664 let mut s = SupervisorSpec::default();
4665 s.children = vec![];
4666 assert!(matches!(
4667 s.validate().unwrap_err(),
4668 SupervisorError::NoChildren { .. }
4669 ));
4670 s.children = vec![child("worker", "^0.1", RestartPolicy::Permanent)];
4671 s.validate().unwrap();
4672 }
4673
4674 #[test]
4675 fn validate_simple_one_for_one_forbids_static_children() {
4676 let mut s = SupervisorSpec {
4677 estrategia: RestartStrategy::SimpleOneForOne,
4678 ..SupervisorSpec::default()
4679 };
4680 s.children
4681 .push(child("w", "^0.1", RestartPolicy::Permanent));
4682 assert_eq!(
4683 s.validate().unwrap_err(),
4684 SupervisorError::SimpleOneForOneWithStaticChildren
4685 );
4686 s.children.clear();
4687 s.validate().unwrap();
4688 }
4689
4690 #[test]
4691 fn validate_rejects_zero_max_restarts() {
4692 let s = SupervisorSpec {
4693 max_restarts: 0,
4694 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4695 ..SupervisorSpec::default()
4696 };
4697 assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
4698 }
4699
4700 // ── upper-cap: SUPERVISOR_MAX_RESTARTS_MAX brackets the typed slot ─────
4701 //
4702 // The cap arm lifts the `:politicas :circuit-breaker :max-failures` /
4703 // `POLICY_BREAKER_MAX_FAILURES_MAX` (2b51ace) discipline onto the peer
4704 // `:supervisor :max-restarts` axis — both fields are "trip the
4705 // next-higher protection layer after N events in a rolling window"
4706 // counters with identical degenerate-at-the-high-end shape, so the
4707 // typed-slot's accepted set lies in `1..=1000` on the supervisor side
4708 // exactly as it lies in `1..=1000` on the breaker side.
4709
4710 #[test]
4711 fn validate_rejects_max_restarts_above_cap() {
4712 // The fail-before-pass-after pin: `SUPERVISOR_MAX_RESTARTS_MAX +
4713 // 1` is structurally one past the cap and silently passed
4714 // validate on every pre-gate codebase because the typed slot's
4715 // only check was the zero-floor arm. The no-op-supervisor vector
4716 // only surfaced at the runtime substrate (Erlang/OTP
4717 // MaxIntensity/Period ratio, the future wasm-operator's
4718 // per-supervisor restart-intensity counter) far from the source
4719 // caixa.lisp with no field naming the offending supervisor.
4720 let s = SupervisorSpec {
4721 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4722 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4723 ..SupervisorSpec::default()
4724 };
4725 assert_eq!(
4726 s.validate().unwrap_err(),
4727 SupervisorError::MaxRestartsExceedsCap {
4728 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4729 }
4730 );
4731 }
4732
4733 #[test]
4734 fn validate_rejects_max_restarts_far_above_cap() {
4735 // The `u32::MAX` worst case — the four-billion-restart
4736 // threshold a typo (`:max-restarts 4294967295`) or a
4737 // struct-literal copy-paste lands in the slot. Pin the cap
4738 // arm's coverage explicitly across the full `u32` overflow so
4739 // a future relaxation that drops the upper bound surfaces
4740 // here. Same shape every other typed-cap arm on this surface
4741 // carries (POLICY_BREAKER_MAX_FAILURES_MAX,
4742 // POLICY_RETRIES_MAX, POLICY_RATE_LIMIT_MAX).
4743 let s = SupervisorSpec {
4744 max_restarts: u32::MAX,
4745 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4746 ..SupervisorSpec::default()
4747 };
4748 assert_eq!(
4749 s.validate().unwrap_err(),
4750 SupervisorError::MaxRestartsExceedsCap {
4751 max_restarts: u32::MAX,
4752 }
4753 );
4754 }
4755
4756 #[test]
4757 fn validate_accepts_max_restarts_at_cap() {
4758 // The boundary value — exactly SUPERVISOR_MAX_RESTARTS_MAX —
4759 // must validate. The cap is inclusive on the top edge,
4760 // matching the POLICY_BREAKER_MAX_FAILURES_MAX /
4761 // POLICY_RETRIES_MAX / LIMITS_MEMORY_WASM32_MAX_BYTES
4762 // discipline on the sibling capped axes. Pin the boundary
4763 // explicitly so a future off-by-one tightening
4764 // (`>= SUPERVISOR_MAX_RESTARTS_MAX` instead of `>`) surfaces
4765 // here as a test failure rather than a silent contract
4766 // narrowing.
4767 let s = SupervisorSpec {
4768 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX,
4769 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4770 ..SupervisorSpec::default()
4771 };
4772 s.validate()
4773 .expect("max_restarts == SUPERVISOR_MAX_RESTARTS_MAX must validate");
4774 }
4775
4776 #[test]
4777 fn validate_accepts_max_restarts_typical_values() {
4778 // The documented production-playbook band positive-control
4779 // sweep — every value Erlang/OTP / Elixir / Riak Core /
4780 // RabbitMQ recommend (1..=100) must pass, plus a sweep
4781 // through the hyperscale band (200, 500, 1000) the cap
4782 // accepts. Pin the inclusive validated set explicitly so a
4783 // future tightening of the ceiling surfaces here.
4784 for n in [1u32, 3, 5, 10, 20, 50, 100, 200, 500, 1000] {
4785 let s = SupervisorSpec {
4786 max_restarts: n,
4787 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4788 ..SupervisorSpec::default()
4789 };
4790 s.validate()
4791 .unwrap_or_else(|e| panic!("max_restarts={n} must validate; got {e:?}"));
4792 }
4793 }
4794
4795 #[test]
4796 fn zero_max_restarts_takes_precedence_over_cap() {
4797 // The cross-arm ordering pin: `0` is structurally outside
4798 // both `1..` (zero-floor) and `..=SUPERVISOR_MAX_RESTARTS_MAX`
4799 // (cap), but the zero-floor diagnostic is the more
4800 // self-locating one (it directly names the counter-axis
4801 // remediation), so the validate gate must fire on zero first.
4802 // Same shape every other zero-then-shape ordering on this
4803 // surface uses (PolicyRetriesZero then
4804 // PolicyRetriesExceedsCap; PolicyBreakerZeroFailures then
4805 // PolicyBreakerMaxFailuresExceedsCap).
4806 let s = SupervisorSpec {
4807 max_restarts: 0,
4808 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4809 ..SupervisorSpec::default()
4810 };
4811 assert_eq!(
4812 s.validate().unwrap_err(),
4813 SupervisorError::ZeroMaxRestarts,
4814 "max_restarts == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
4815 );
4816 }
4817
4818 #[test]
4819 fn max_restarts_cap_takes_precedence_over_restart_window_gates() {
4820 // The cross-arm ordering pin between the cap and the sibling
4821 // `:restart-window` gates (zero-window, canonical-window). A
4822 // supervisor carrying both an over-cap `max_restarts` AND a
4823 // structurally invalid window (zero, sub-ms) must surface the
4824 // cap diagnostic first — the cap arm is wired immediately
4825 // after the zero-restart arm and strictly before the window
4826 // arms, so the offending value the diagnostic names matches
4827 // the order the author would discover the gates by reading
4828 // top-to-bottom through `SupervisorSpec::validate`. Pin the
4829 // order so a future refactor that reorders the arms surfaces
4830 // here as a test failure rather than a silent diagnostic
4831 // regression. Peer of
4832 // `circuit_breaker_max_failures_cap_takes_precedence_over_window_gates`
4833 // on the sibling `:politicas :circuit-breaker` slot.
4834 let s = SupervisorSpec {
4835 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4836 restart_window: Some(Duration::ZERO),
4837 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4838 ..SupervisorSpec::default()
4839 };
4840 assert_eq!(
4841 s.validate().unwrap_err(),
4842 SupervisorError::MaxRestartsExceedsCap {
4843 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4844 },
4845 "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
4846 );
4847 }
4848
4849 #[test]
4850 fn max_restarts_cap_diagnostic_carries_offending_value() {
4851 // The diagnostic-shape pin: the offending `u32` is carried
4852 // verbatim into the `SupervisorError::MaxRestartsExceedsCap`
4853 // variant so the surfaced error message names the value the
4854 // author wrote (`":supervisor :max-restarts (50000) exceeds the
4855 // supervisor-policy ceiling …"`), not just the cap. Same
4856 // self-locating diagnostic shape every other typed-cap arm on
4857 // this surface carries
4858 // (`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` carries
4859 // the offending failure count verbatim,
4860 // `AplicacaoError::PolicyRetriesExceedsCap` carries the offending
4861 // retries count verbatim).
4862 let s = SupervisorSpec {
4863 max_restarts: 50_000,
4864 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4865 ..SupervisorSpec::default()
4866 };
4867 let err = s.validate().unwrap_err();
4868 assert!(
4869 matches!(
4870 err,
4871 SupervisorError::MaxRestartsExceedsCap {
4872 max_restarts: 50_000
4873 }
4874 ),
4875 "got {err:?}"
4876 );
4877 let msg = err.to_string();
4878 assert!(
4879 msg.contains("50000"),
4880 ":supervisor :max-restarts cap diagnostic must carry the offending value verbatim (got: {msg})"
4881 );
4882 }
4883
4884 #[test]
4885 fn supervisor_max_restarts_default_pins_otp_canonical_value() {
4886 // Pin [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] at `5` — the
4887 // Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
4888 // half of Learn You Some Erlang's worker-supervisor default,
4889 // sibling of the `60s` `Period` half that the paired
4890 // [`Default for SupervisorSpec`] impl already pins on the
4891 // sibling `restart_window` axis. Pinning the literal here
4892 // surfaces a future rebrand (a tightening to Elixir's `3`,
4893 // a widening to a per-cluster overlay the operator pins
4894 // through a future `:max-restarts-overrides` slot) as a
4895 // deliberate test edit, not a silent contract migration.
4896 // Peer of the sibling
4897 // [`supervisor_max_restarts_cap_pins_canonical_value`]
4898 // upper-bracket pin on the same axis.
4899 assert_eq!(SUPERVISOR_MAX_RESTARTS_DEFAULT, 5);
4900 }
4901
4902 #[test]
4903 fn default_max_restarts_helper_routes_through_lifted_default() {
4904 // Composition pin: the private `default_max_restarts()`
4905 // serde-`#[serde(default = "…")]` helper on
4906 // [`SupervisorSpec::max_restarts`] must route through the
4907 // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
4908 // typed `pub const` rather than a raw `5` literal. Prior to
4909 // the lift the helper carried an inline `5` with no compile-
4910 // time link back to the shared default, so the wire-format
4911 // author-omitted arm and the caixa-core
4912 // [`crate::manifest::Caixa::supervisor_view`] fold's `unwrap_or(5)`
4913 // arm could silently split on any future default rebrand.
4914 // Byte-parity against the lifted constant closes the split.
4915 assert_eq!(default_max_restarts(), SUPERVISOR_MAX_RESTARTS_DEFAULT);
4916 }
4917
4918 #[test]
4919 fn supervisor_spec_default_max_restarts_routes_through_lifted_default() {
4920 // Composition pin: the [`Default for SupervisorSpec`] impl's
4921 // struct-literal `max_restarts` field must route through the
4922 // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
4923 // typed `pub const` (via the private helper this test's
4924 // sibling `default_max_restarts_helper_routes_through_lifted_default`
4925 // already pins onto the constant). Structurally: every
4926 // `SupervisorSpec::default()` call must yield a
4927 // `max_restarts` field byte-equal to the lifted constant
4928 // (the two paired defaults — the serde-side wire-format arm
4929 // and the struct-literal default arm — cannot silently split
4930 // on any future default rebrand). Peer of the sibling
4931 // `default_has_one_for_one_and_5_restarts_in_60s` shape pin
4932 // — this pin closes the byte-parity arm on the two paired
4933 // altitude entry points onto the shared substrate constant.
4934 assert_eq!(
4935 SupervisorSpec::default().max_restarts(),
4936 SUPERVISOR_MAX_RESTARTS_DEFAULT,
4937 );
4938 }
4939
4940 #[test]
4941 fn supervisor_restart_window_default_pins_otp_canonical_value() {
4942 // Pin [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] at `60s` — the
4943 // Erlang/OTP-canonical `{intensity, 5, 60}` `Period` half of
4944 // Learn You Some Erlang's worker-supervisor default, paired
4945 // with the sibling `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5`
4946 // `MaxIntensity` half this constant is the sliding-window
4947 // denominator of on the same `MaxIntensity / Period`
4948 // restart-intensity ratio. Pinning the literal here surfaces a
4949 // future coherent rebrand of the paired default (Elixir's
4950 // `{max_restarts: 3, max_seconds: 5}`, a per-cluster overlay
4951 // the operator pins through a future
4952 // `:restart-window-overrides` slot) as a deliberate test edit,
4953 // not a silent contract migration. Peer of the sibling
4954 // [`supervisor_max_restarts_default_pins_otp_canonical_value`]
4955 // paired-half pin on the same OTP-canonical default and the
4956 // [`supervisor_restart_window_cap_pins_canonical_value`]
4957 // upper-bracket pin on the same axis.
4958 assert_eq!(SUPERVISOR_RESTART_WINDOW_DEFAULT, Duration::from_secs(60),);
4959 }
4960
4961 #[test]
4962 fn supervisor_spec_default_restart_window_routes_through_lifted_default() {
4963 // Composition pin: the [`Default for SupervisorSpec`] impl's
4964 // struct-literal `restart_window` field must route through the
4965 // substrate-canonical [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
4966 // typed `pub const` rather than a raw
4967 // `Duration::from_secs(60)` literal. Prior to this lift the
4968 // paired `{intensity, 5, 60}` OTP-canonical default was split
4969 // across two altitudes with no compile-time link between the
4970 // halves — the `MaxIntensity` half rode through the lifted
4971 // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant while the
4972 // `Period` half rode as an open-coded literal at the
4973 // composition site, so a future coherent rebrand of the paired
4974 // canonical would have had to migrate one half through the
4975 // constant and the other through a raw literal in lockstep.
4976 // Byte-parity against the lifted constant on the `Period` half
4977 // closes the split — the paired OTP-canonical default now
4978 // migrates as one unit on any future axis change. Peer of the
4979 // sibling
4980 // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
4981 // byte-parity pin on the paired `MaxIntensity` half.
4982 assert_eq!(
4983 SupervisorSpec::default().restart_window(),
4984 Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4985 );
4986 }
4987
4988 #[test]
4989 fn supervisor_estrategia_default_pins_otp_canonical_value() {
4990 // Pin [`SUPERVISOR_ESTRATEGIA_DEFAULT`] at [`RestartStrategy::OneForOne`]
4991 // — the Erlang/OTP-canonical `one_for_one` half of Learn You Some
4992 // Erlang's `{one_for_one, intensity, 5, 60}` worker-supervisor
4993 // canonical default, paired with the sibling
4994 // `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5` `MaxIntensity` half and the
4995 // sibling `SUPERVISOR_RESTART_WINDOW_DEFAULT` `60s` `Period` half
4996 // this constant is the strategy discriminator of on the same
4997 // OTP-canonical worker-supervisor default. Pinning the arm here
4998 // surfaces a future coherent rebrand of the paired triple (Elixir's
4999 // `{:one_for_one, max_restarts: 3, max_seconds: 5}` on the sibling
5000 // intensity/period axes leaving this strategy arm untouched, an OTP
5001 // `rest_for_one` widening once the substrate discovers startup-
5002 // order-coupled child cohorts as the more common worker-supervisor
5003 // shape, a per-cluster overlay the operator pins through a future
5004 // `:estrategia-overrides` slot the MESH-COMPOSITION §III.2
5005 // supervision-canary roadmap acknowledges) as a deliberate test
5006 // edit, not a silent contract migration. Peer of the sibling
5007 // [`supervisor_max_restarts_default_pins_otp_canonical_value`] +
5008 // [`supervisor_restart_window_default_pins_otp_canonical_value`]
5009 // paired-half pins on the same OTP-canonical default.
5010 assert_eq!(SUPERVISOR_ESTRATEGIA_DEFAULT, RestartStrategy::OneForOne);
5011 }
5012
5013 #[test]
5014 fn restart_strategy_default_routes_through_lifted_default() {
5015 // Composition pin: the [`Default for RestartStrategy`] impl's
5016 // return arm must route through the substrate-canonical
5017 // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
5018 // a raw `Self::OneForOne` arm. Prior to the lift the impl carried
5019 // an inline `Self::OneForOne` with no compile-time link back to
5020 // the shared OTP-canonical `one_for_one` strategy the paired
5021 // [`Default for SupervisorSpec`] impl's struct-literal `estrategia`
5022 // field and the [`crate::manifest::Caixa::supervisor_view`] fold's
5023 // `.unwrap_or_default()` (now
5024 // `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)`) arm both key off —
5025 // so a future rebrand of the OTP-canonical strategy default (an
5026 // OTP `rest_for_one` widening once the substrate discovers
5027 // startup-order-coupled child cohorts as the more common worker-
5028 // supervisor shape, a per-cluster overlay the operator pins
5029 // through a future `:estrategia-overrides` slot) would have had to
5030 // be threaded through the `Default` impl and the two peer routes
5031 // in lockstep or the three consumers would silently split. Byte-
5032 // parity against the lifted constant closes the split. Peer of
5033 // the sibling
5034 // [`default_max_restarts_helper_routes_through_lifted_default`] +
5035 // [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
5036 // composition pins on the paired `MaxIntensity` + `Period` halves.
5037 assert_eq!(RestartStrategy::default(), SUPERVISOR_ESTRATEGIA_DEFAULT,);
5038 }
5039
5040 #[test]
5041 fn supervisor_spec_default_estrategia_routes_through_lifted_default() {
5042 // Composition pin: the [`Default for SupervisorSpec`] impl's
5043 // struct-literal `estrategia` field must route through the
5044 // substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed
5045 // `pub const` (either directly, or via the
5046 // [`RestartStrategy::default`] impl that the sibling
5047 // `restart_strategy_default_routes_through_lifted_default` pin
5048 // already routes onto the constant). Structurally: every
5049 // `SupervisorSpec::default()` call must yield an `estrategia`
5050 // field byte-equal to the lifted constant (the three paired
5051 // defaults — the [`Default for RestartStrategy`] impl arm, the
5052 // struct-literal default arm here, and the
5053 // [`crate::manifest::Caixa::supervisor_view`] fold arm — cannot
5054 // silently split on any future default rebrand). Peer of the
5055 // sibling
5056 // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
5057 // + [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
5058 // byte-parity pins on the paired `MaxIntensity` + `Period` halves
5059 // of the same `SupervisorSpec::default()` composed altitude.
5060 assert_eq!(
5061 SupervisorSpec::default().estrategia(),
5062 SUPERVISOR_ESTRATEGIA_DEFAULT,
5063 );
5064 }
5065
5066 #[test]
5067 fn supervisor_spec_default_routes_through_otp_canonical_ctor() {
5068 // Composition pin: the [`Default for SupervisorSpec`] impl must
5069 // route through the substrate-canonical
5070 // [`SupervisorSpec::otp_canonical`] `pub const fn` constructor
5071 // rather than a re-hand-authored struct-literal cascade. Sharpens
5072 // the sibling per-arm
5073 // `supervisor_spec_default_*_routes_through_lifted_default` pins
5074 // from a per-field lift into a whole-struct one-source-of-truth
5075 // pin — the derived-until-now [`Default::default`] and the
5076 // [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
5077 // construction, not by coincidence.
5078 //
5079 // A future extension of the OTP-canonical baseline (a fifth
5080 // `restart_intensity` field the Erlang/OTP `#supervisor` record
5081 // grows, a per-child-cohort split of the `restart_window` /
5082 // `max_restarts` pair, an M4 `mesh.pleme.io/v1alpha1/Supervisor`
5083 // CR materializer's admission-time overlay pass) reaches both
5084 // paths through exactly one edit on
5085 // [`SupervisorSpec::otp_canonical`] — the derived path could
5086 // silently disagree with the constructor's shape on any new
5087 // field whose [`Default::default`] resolves to a different arm
5088 // than the OTP-canonical baseline the constructor names, while
5089 // this delegated impl reaches the constructor directly and
5090 // picks up every future extension by construction.
5091 //
5092 // Fourth peer on the M2 / M3 typed-slot-spec
5093 // [`Default`]-through-const-ctor fold family — sibling of the
5094 // [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
5095 // (abd52c2), [`crate::aplicacao::MeshPolicy`]
5096 // [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`]
5097 // (91641a4), and [`crate::BehaviorSpec`]
5098 // [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c)
5099 // per-`Option`-only-typed-slot folds — extended here onto the
5100 // M2 supervisor-slot [`SupervisorSpec`] whose canonical baseline
5101 // is not "everything `None`" but the Erlang/OTP-canonical
5102 // `{one_for_one, 5, 60}` worker-supervisor triple.
5103 assert_eq!(SupervisorSpec::default(), SupervisorSpec::otp_canonical());
5104 }
5105
5106 #[test]
5107 fn supervisor_spec_otp_canonical_byte_equals_default() {
5108 // Value pin: [`SupervisorSpec::otp_canonical`] must byte-equal
5109 // the hand-authored `{one_for_one, 5, 60, []}` OTP-canonical
5110 // baseline the sibling `default_has_one_for_one_and_5_restarts_in_60s`
5111 // pin already asserts against the [`Default::default`] path.
5112 // Sharpens the pair-invariant into a per-constructor pin so a
5113 // future extension of [`SupervisorSpec`] with a fifth field
5114 // whose OTP-canonical shape is non-`Default::default`-equivalent
5115 // trips at caixa-core test time rather than at a downstream
5116 // consumer that composed [`SupervisorSpec::otp_canonical`] with
5117 // [`SupervisorSpec::validate`] as its "canonical baseline
5118 // seed".
5119 let canonical = SupervisorSpec::otp_canonical();
5120 assert_eq!(canonical.estrategia, RestartStrategy::OneForOne);
5121 assert_eq!(canonical.max_restarts, 5);
5122 assert_eq!(canonical.restart_window, Some(Duration::from_secs(60)));
5123 assert!(canonical.children.is_empty());
5124 }
5125
5126 #[test]
5127 fn supervisor_spec_otp_canonical_is_usable_in_const_context() {
5128 // Const-context pin: [`SupervisorSpec::otp_canonical`] must
5129 // remain callable from a `const`-bound position so downstream
5130 // `const`-context callers wanting a canonical OTP-baseline seed
5131 // can construct one at compile time without runtime dispatch on
5132 // the derived [`Default::default`]. Peer of the sibling
5133 // `pub const fn` [`crate::LimitsSpec::empty`] /
5134 // [`crate::aplicacao::MeshPolicy::empty`] /
5135 // [`crate::BehaviorSpec::empty`] constructors on the sibling
5136 // typed-slot-spec `pub const fn` axis. If a future edit breaks
5137 // the `const`-eligibility of [`SupervisorSpec::otp_canonical`]
5138 // (a non-`const` field-default helper, a non-`const`-stable
5139 // container type promotion), this evaluation fails at
5140 // build time on this file rather than at a downstream
5141 // `const`-context call site.
5142 const CANONICAL: SupervisorSpec = SupervisorSpec::otp_canonical();
5143 assert_eq!(CANONICAL.estrategia, SUPERVISOR_ESTRATEGIA_DEFAULT);
5144 assert_eq!(CANONICAL.max_restarts, SUPERVISOR_MAX_RESTARTS_DEFAULT);
5145 assert_eq!(
5146 CANONICAL.restart_window,
5147 Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
5148 );
5149 assert!(CANONICAL.children.is_empty());
5150 }
5151
5152 #[test]
5153 fn supervisor_child_restart_default_pins_otp_canonical_value() {
5154 // Pin [`SUPERVISOR_CHILD_RESTART_DEFAULT`] at
5155 // [`RestartPolicy::Permanent`] — Erlang/OTP's `permanent`
5156 // worker-child restart type (`{ChildId, StartFunc, permanent, …}`
5157 // in a `supervisor`'s `init/1` child-spec tuple), the per-child
5158 // half of the same OTP-shape supervisor-tree default set whose
5159 // per-`:supervisor` halves the sibling
5160 // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
5161 // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] /
5162 // [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] constants pin. Pinning the
5163 // arm here surfaces a future rebrand of the per-child default (an
5164 // OTP-`transient` widening once the substrate discovers clean-
5165 // completion-aware children as the more common child shape, a
5166 // per-cluster overlay the operator pins through a future
5167 // `:restart-overrides` slot the MESH-COMPOSITION §III.2
5168 // supervision-canary roadmap acknowledges) as a deliberate test
5169 // edit, not a silent contract migration. Peer of the sibling
5170 // [`supervisor_estrategia_default_pins_otp_canonical_value`] /
5171 // [`supervisor_max_restarts_default_pins_otp_canonical_value`] /
5172 // [`supervisor_restart_window_default_pins_otp_canonical_value`]
5173 // value pins on the per-`:supervisor` halves.
5174 assert_eq!(SUPERVISOR_CHILD_RESTART_DEFAULT, RestartPolicy::Permanent);
5175 }
5176
5177 #[test]
5178 fn restart_policy_default_routes_through_lifted_default() {
5179 // Composition pin: the [`Default for RestartPolicy`] impl's return
5180 // arm must route through the substrate-canonical
5181 // [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const` rather
5182 // than a raw `Self::Permanent` arm. Prior to the lift the impl
5183 // carried an inline `Self::Permanent` with no compile-time link
5184 // back to the OTP-shape supervisor-tree default set whose three
5185 // per-`:supervisor` halves already rode through lifted constants
5186 // — so a future coherent rebrand of the set would have had to
5187 // migrate three halves through typed constants and this fourth
5188 // through a raw enum arm in lockstep or the supervisor-level and
5189 // child-level defaults would silently drift apart. Byte-parity
5190 // against the lifted constant closes the split. Peer of the
5191 // sibling
5192 // [`restart_strategy_default_routes_through_lifted_default`]
5193 // composition pin on the per-`:supervisor` `:estrategia` axis.
5194 assert_eq!(RestartPolicy::default(), SUPERVISOR_CHILD_RESTART_DEFAULT);
5195 }
5196
5197 #[test]
5198 fn child_spec_serde_default_restart_routes_through_lifted_default() {
5199 // Composition pin: the serde-side `#[serde(default)]` on
5200 // [`ChildSpec::restart`] — the wire-format author-omitted
5201 // `:children :restart` arm — must resolve onto the substrate-
5202 // canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const`
5203 // (via the [`Default for RestartPolicy`] impl the sibling
5204 // `restart_policy_default_routes_through_lifted_default` pin
5205 // already routes onto the constant). Structurally: a `ChildSpec`
5206 // deserialized from a payload that omits the `restart` key must
5207 // yield a `restart` field byte-equal to the lifted constant, so
5208 // the wire-format author-omitted arm and the
5209 // [`RestartPolicy::default`] impl arm cannot silently split on any
5210 // future default rebrand. Peer of the sibling
5211 // [`supervisor_spec_default_estrategia_routes_through_lifted_default`]
5212 // / [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
5213 // / [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
5214 // byte-parity pins on the per-`:supervisor` halves of the same
5215 // author-omitted-slot resolution surface.
5216 let omitted: ChildSpec = serde_json::from_str(r#"{"caixa":"worker","versao":"^0.1"}"#)
5217 .expect("ChildSpec must deserialize with the restart key omitted");
5218 assert_eq!(
5219 omitted.restart(),
5220 SUPERVISOR_CHILD_RESTART_DEFAULT,
5221 "an author-omitted :children :restart slot must degrade onto \
5222 the SUPERVISOR_CHILD_RESTART_DEFAULT typed pub const (got \
5223 {:?}, expected {:?})",
5224 omitted.restart(),
5225 SUPERVISOR_CHILD_RESTART_DEFAULT,
5226 );
5227 }
5228
5229 #[test]
5230 fn supervisor_max_restarts_cap_pins_canonical_value() {
5231 // The SUPERVISOR_MAX_RESTARTS_MAX constant pins the value at
5232 // 1000 — the same ceiling the peer
5233 // POLICY_BREAKER_MAX_FAILURES_MAX cap carries on the
5234 // `:politicas :circuit-breaker :max-failures` axis (both are
5235 // "trip the next-higher protection layer after N events in a
5236 // rolling window" counters with identical
5237 // degenerate-at-the-high-end shape; uniform top edge so the
5238 // M4 CR materializers and the wasm-operator reconciler reach
5239 // for either field knowing the value is in `1..=1000`). Two
5240 // orders of magnitude above every documented Erlang/OTP /
5241 // Elixir / Riak Core / RabbitMQ production-playbook
5242 // recommendation band and below the clearly-pathological
5243 // "effectively no escalation" floor (10_000, 100_000,
5244 // u32::MAX). Pinning the literal value here surfaces a future
5245 // drift (a relaxation to 10_000, a tightening to 100) as a
5246 // deliberate test edit, not a silent contract narrowing.
5247 assert_eq!(SUPERVISOR_MAX_RESTARTS_MAX, 1000);
5248 }
5249
5250 #[test]
5251 fn validate_rejects_empty_child_name() {
5252 let s = SupervisorSpec {
5253 children: vec![child("", "^0.1", RestartPolicy::Permanent)],
5254 ..SupervisorSpec::default()
5255 };
5256 assert_eq!(s.validate().unwrap_err(), SupervisorError::EmptyChildName);
5257 }
5258
5259 #[test]
5260 fn validate_rejects_empty_child_version() {
5261 let s = SupervisorSpec {
5262 children: vec![child("w", "", RestartPolicy::Permanent)],
5263 ..SupervisorSpec::default()
5264 };
5265 assert!(matches!(
5266 s.validate().unwrap_err(),
5267 SupervisorError::EmptyChildVersion { .. }
5268 ));
5269 }
5270
5271 // ── value-shape: parse-as-VersionReq on :children :versao ─────────────
5272
5273 #[test]
5274 fn validate_rejects_invalid_child_versao_requirement() {
5275 // The fail-before-pass-after pin: a non-empty but malformed
5276 // semver requirement (`"^bad-version"`) silently passed
5277 // `validate()` on every pre-gate codebase because the prior
5278 // shape only refused the empty string. The parse failure
5279 // surfaced far downstream at lacre-resolve time with a
5280 // `semver::Error` that didn't name which `:children` entry
5281 // carried the typo. The new gate moves the check to caixa-build
5282 // time at the source caixa.lisp — the third `:versao` typed
5283 // axis (`:children`) joins `:deps` and `:membros` (9888b13) at
5284 // structural parity.
5285 let s = SupervisorSpec {
5286 children: vec![
5287 child("worker", "^0.1", RestartPolicy::Permanent),
5288 child("cache", "^bad-version", RestartPolicy::Transient),
5289 ],
5290 ..SupervisorSpec::default()
5291 };
5292 let err = s.validate().unwrap_err();
5293 assert!(
5294 matches!(
5295 err,
5296 SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
5297 if caixa == "cache" && versao == "^bad-version"
5298 ),
5299 "got {err:?}"
5300 );
5301 }
5302
5303 #[test]
5304 fn validate_rejects_child_versao_with_double_caret_typo() {
5305 // `"^^0.1"` is the canonical doubled-caret typo — looks
5306 // Cargo-shaped on first glance but fails the parser because
5307 // semver doesn't accept stacked operators. Pin this
5308 // adjacent-shape footgun explicitly so a future relaxation that
5309 // accepts "looks-canonical-but-isn't" forms surfaces here.
5310 let s = SupervisorSpec {
5311 children: vec![child("worker", "^^0.1", RestartPolicy::Permanent)],
5312 ..SupervisorSpec::default()
5313 };
5314 let err = s.validate().unwrap_err();
5315 assert!(
5316 matches!(
5317 err,
5318 SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
5319 if caixa == "worker" && versao == "^^0.1"
5320 ),
5321 "got {err:?}"
5322 );
5323 }
5324
5325 #[test]
5326 fn validate_rejects_child_versao_with_v_prefixed_tag() {
5327 // `"v0.1"` is the canonical "git-tag-shape leaking into the
5328 // semver requirement slot" typo — an author copies the
5329 // publish-side git-tag string verbatim into `:versao`, but
5330 // Cargo's semver parser rejects the leading `v`. Same
5331 // adjacent-shape footgun pinned for `:membros :versao`
5332 // (9888b13).
5333 let s = SupervisorSpec {
5334 children: vec![child("worker", "v0.1", RestartPolicy::Permanent)],
5335 ..SupervisorSpec::default()
5336 };
5337 let err = s.validate().unwrap_err();
5338 assert!(
5339 matches!(
5340 err,
5341 SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
5342 if caixa == "worker" && versao == "v0.1"
5343 ),
5344 "got {err:?}"
5345 );
5346 }
5347
5348 #[test]
5349 fn validate_accepts_canonical_child_versao_forms() {
5350 // The Cargo-shaped requirement forms `:deps :versao` and
5351 // `:membros :versao` already accept via
5352 // `crate::parse_requirement` must pass the children gate
5353 // without re-validating at the resolver layer. Pin every leg so
5354 // a future tightening of the canonical set surfaces here as a
5355 // test failure.
5356 for form in [
5357 "^0.1", // caret — minor-range pin (the most common shape)
5358 "~0.1.2", // tilde — patch-range pin
5359 "0.1.0", // exact — single-version pin
5360 "*", // wildcard — any version (semver::VersionReq::STAR)
5361 ">=0.1, <2", // multi-range — comma-separated comparators
5362 ] {
5363 let s = SupervisorSpec {
5364 children: vec![child("worker", form, RestartPolicy::Permanent)],
5365 ..SupervisorSpec::default()
5366 };
5367 s.validate()
5368 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
5369 }
5370 }
5371
5372 #[test]
5373 fn child_versao_empty_takes_precedence_over_invalid() {
5374 // Order pin: the existing `EmptyChildVersion` diagnostic (which
5375 // doesn't try to parse) fires before the new
5376 // `ChildVersaoInvalid` parse-side diagnostic, so an empty
5377 // `:versao` keeps its narrower error message —
5378 // `parse_requirement` would also reject `""`, but the
5379 // empty-string arm is the more self-locating diagnostic for the
5380 // author. Same ordering discipline as
5381 // `membro_versao_empty_takes_precedence_over_invalid` in
5382 // aplicacao.rs.
5383 let s = SupervisorSpec {
5384 children: vec![child("worker", "", RestartPolicy::Permanent)],
5385 ..SupervisorSpec::default()
5386 };
5387 let err = s.validate().unwrap_err();
5388 assert!(
5389 matches!(err, SupervisorError::EmptyChildVersion { ref caixa } if caixa == "worker"),
5390 "got {err:?}"
5391 );
5392 }
5393
5394 #[test]
5395 fn child_versao_invalid_fires_before_duplicate_check() {
5396 // Order pin: a malformed requirement on a non-duplicate entry
5397 // surfaces *its own* diagnostic (which names the offending
5398 // `:versao` string), even when a later entry would otherwise
5399 // collapse onto an earlier name. The per-entry shape gate runs
5400 // inline before the duplicate-key insert — parallel to
5401 // `membro_versao_invalid_fires_before_duplicate_check` in
5402 // aplicacao.rs and the b0c8389 / c4213a4 ordering discipline.
5403 let s = SupervisorSpec {
5404 children: vec![
5405 child("worker", "^bad", RestartPolicy::Permanent),
5406 child("cache", "^0.1", RestartPolicy::Transient),
5407 child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
5408 ],
5409 ..SupervisorSpec::default()
5410 };
5411 let err = s.validate().unwrap_err();
5412 assert!(
5413 matches!(
5414 err,
5415 SupervisorError::ChildVersaoInvalid { ref caixa, .. } if caixa == "worker"
5416 ),
5417 "got {err:?}"
5418 );
5419 }
5420
5421 #[test]
5422 fn child_versao_invalid_diagnostic_carries_offending_versao() {
5423 // The diagnostic-shape pin: the error names the offending
5424 // `:versao` value verbatim so the author can grep their
5425 // caixa.lisp without re-running the build, and carries a
5426 // non-empty `reason` from `semver::VersionReq::parse` so the
5427 // parser's own wording flows through to the diagnostic.
5428 let s = SupervisorSpec {
5429 children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
5430 ..SupervisorSpec::default()
5431 };
5432 let err = s.validate().unwrap_err();
5433 let SupervisorError::ChildVersaoInvalid {
5434 caixa,
5435 versao,
5436 reason,
5437 } = err
5438 else {
5439 panic!("expected ChildVersaoInvalid, got other variant");
5440 };
5441 assert_eq!(caixa, "worker");
5442 assert_eq!(versao, "not-a-req");
5443 assert!(
5444 !reason.is_empty(),
5445 "ChildVersaoInvalid `reason` must carry the parser's wording verbatim"
5446 );
5447 }
5448
5449 // ── value-shape: DNS-1123 label rule on :children :caixa ──────────────
5450
5451 #[test]
5452 fn validate_rejects_child_caixa_with_uppercase() {
5453 // The canonical "I copied the Servico's display name verbatim"
5454 // typo — child caixa names are lowercase per K8s DNS-1123 label
5455 // rule. The diagnostic names the offending name and suggests the
5456 // lower-cased fix in one edit, mirroring the
5457 // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0).
5458 let s = SupervisorSpec {
5459 children: vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
5460 ..SupervisorSpec::default()
5461 };
5462 let err = s.validate().unwrap_err();
5463 let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
5464 panic!("expected ChildCaixaInvalid, got other variant");
5465 };
5466 assert_eq!(caixa, "Worker");
5467 assert!(
5468 reason.contains("uppercase"),
5469 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
5470 );
5471 assert!(
5472 reason.contains("\"worker\""),
5473 "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
5474 );
5475 }
5476
5477 #[test]
5478 fn validate_rejects_child_caixa_with_underscore() {
5479 // The canonical "I'm thinking of a Python module / Postgres
5480 // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
5481 // label schema. K8s rejects `metadata.name: my_worker` at
5482 // admission time with an opaque `field is invalid` (no source-
5483 // citing diagnostic). The gate moves it to caixa-build time.
5484 let s = SupervisorSpec {
5485 children: vec![child("my_worker", "^0.1", RestartPolicy::Permanent)],
5486 ..SupervisorSpec::default()
5487 };
5488 let err = s.validate().unwrap_err();
5489 assert!(
5490 matches!(
5491 err,
5492 SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
5493 if caixa == "my_worker" && reason.contains('_')
5494 ),
5495 "got {err:?}"
5496 );
5497 }
5498
5499 #[test]
5500 fn validate_rejects_child_caixa_with_dot() {
5501 // A `:children :caixa` entry is a single DNS-1123 label, not a
5502 // subdomain. The K8s Service / ComputeUnit `metadata.name` rules
5503 // forbid dots. Same shape as `rejects_membro_caixa_with_dot`
5504 // (3f9d7a0) on the peer name axis.
5505 let s = SupervisorSpec {
5506 children: vec![child("team.worker", "^0.1", RestartPolicy::Permanent)],
5507 ..SupervisorSpec::default()
5508 };
5509 let err = s.validate().unwrap_err();
5510 assert!(
5511 matches!(
5512 err,
5513 SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
5514 if caixa == "team.worker" && reason.contains('.')
5515 ),
5516 "got {err:?}"
5517 );
5518 }
5519
5520 #[test]
5521 fn validate_rejects_child_caixa_with_leading_hyphen() {
5522 // DNS-1123 / DNS-1035 boundary rule: labels must start and end
5523 // with an alphanumeric. The K8s apiserver rejects `-worker`
5524 // outright; the renderer would emit a `metadata.name: "-worker"`
5525 // that fails admission far from the source caixa.lisp.
5526 let s = SupervisorSpec {
5527 children: vec![child("-worker", "^0.1", RestartPolicy::Permanent)],
5528 ..SupervisorSpec::default()
5529 };
5530 let err = s.validate().unwrap_err();
5531 assert!(
5532 matches!(
5533 err,
5534 SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
5535 if caixa == "-worker" && reason.contains("start and end")
5536 ),
5537 "got {err:?}"
5538 );
5539 }
5540
5541 #[test]
5542 fn validate_rejects_child_caixa_with_trailing_hyphen() {
5543 // The symmetric arm of the boundary rule. Pin separately so
5544 // both ends of the label are covered against a future relaxation
5545 // that only checks one boundary.
5546 let s = SupervisorSpec {
5547 children: vec![child("worker-", "^0.1", RestartPolicy::Permanent)],
5548 ..SupervisorSpec::default()
5549 };
5550 let err = s.validate().unwrap_err();
5551 assert!(
5552 matches!(
5553 err,
5554 SupervisorError::ChildCaixaInvalid { ref caixa, .. }
5555 if caixa == "worker-"
5556 ),
5557 "got {err:?}"
5558 );
5559 }
5560
5561 #[test]
5562 fn validate_rejects_child_caixa_with_unicode() {
5563 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
5564 // (`xn--…`) by the author before it reaches K8s. The byte-by-
5565 // byte ASCII validity check rejects multi-byte UTF-8 sequences
5566 // by the first byte that fails the `[a-z0-9-]` predicate.
5567 let s = SupervisorSpec {
5568 children: vec![child("café", "^0.1", RestartPolicy::Permanent)],
5569 ..SupervisorSpec::default()
5570 };
5571 let err = s.validate().unwrap_err();
5572 assert!(
5573 matches!(
5574 err,
5575 SupervisorError::ChildCaixaInvalid { ref caixa, .. }
5576 if caixa == "café"
5577 ),
5578 "got {err:?}"
5579 );
5580 }
5581
5582 #[test]
5583 fn validate_rejects_child_caixa_with_whitespace() {
5584 // Whitespace is the canonical "I pasted from a sketch / doc"
5585 // footgun. The apiserver rejects every `metadata.name` value
5586 // carrying whitespace; pin the gate fires at the right boundary.
5587 let s = SupervisorSpec {
5588 children: vec![child("my worker", "^0.1", RestartPolicy::Permanent)],
5589 ..SupervisorSpec::default()
5590 };
5591 let err = s.validate().unwrap_err();
5592 assert!(
5593 matches!(
5594 err,
5595 SupervisorError::ChildCaixaInvalid { ref caixa, .. }
5596 if caixa == "my worker"
5597 ),
5598 "got {err:?}"
5599 );
5600 }
5601
5602 #[test]
5603 fn validate_rejects_child_caixa_too_long() {
5604 // The 64-byte boundary pin. DNS-1123 / DNS-1035 cap labels at
5605 // 63 bytes; the K8s apiserver rejects every `metadata.name`
5606 // axis over the limit at admission time. The diagnostic names
5607 // both the cap and the actual length so the author can shorten
5608 // in one edit, mirroring `rejects_membro_caixa_too_long`
5609 // (3f9d7a0) and `rejects_placement_cluster_too_long` (6cbb900).
5610 let too_long = "a".repeat(64);
5611 let s = SupervisorSpec {
5612 children: vec![child(&too_long, "^0.1", RestartPolicy::Permanent)],
5613 ..SupervisorSpec::default()
5614 };
5615 let err = s.validate().unwrap_err();
5616 let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
5617 panic!("expected ChildCaixaInvalid, got other variant");
5618 };
5619 assert_eq!(caixa, too_long);
5620 assert!(
5621 reason.contains("63"),
5622 "diagnostic must name the 63-byte cap (got: {reason:?})"
5623 );
5624 assert!(
5625 reason.contains("64"),
5626 "diagnostic must name the actual length (got: {reason:?})"
5627 );
5628 }
5629
5630 #[test]
5631 fn child_caixa_max_length_validates() {
5632 // The 63-byte boundary control pin — exactly-at-the-cap is
5633 // accepted, mirroring `membro_caixa_max_length_validates`
5634 // (3f9d7a0) and `placement_cluster_max_length_validates`
5635 // (6cbb900). Pinned separately so a future off-by-one tightening
5636 // surfaces here.
5637 let max_label = "a".repeat(63);
5638 let s = SupervisorSpec {
5639 children: vec![child(&max_label, "^0.1", RestartPolicy::Permanent)],
5640 ..SupervisorSpec::default()
5641 };
5642 s.validate().unwrap();
5643 }
5644
5645 #[test]
5646 fn validate_accepts_canonical_child_caixa_forms() {
5647 // The realistic shapes a supervised child's `:caixa` carries —
5648 // single-word `worker`, version-suffixed `cache-v2`, single-char
5649 // `a`, two-char `db`, digit-start `2-pool`, longer hyphen-joined
5650 // `payment-retry`, all-digit `0`. Pin every leg so a future
5651 // tightening (e.g. requiring a leading lowercase letter) surfaces
5652 // here as a test failure. Mirrors `accepts_canonical_membro_caixa_forms`
5653 // (3f9d7a0) and `accepts_canonical_placement_cluster_forms`
5654 // (6cbb900).
5655 for form in [
5656 "worker",
5657 "cache-v2",
5658 "a",
5659 "db",
5660 "2-pool",
5661 "payment-retry",
5662 "0",
5663 ] {
5664 let s = SupervisorSpec {
5665 children: vec![child(form, "^0.1", RestartPolicy::Permanent)],
5666 ..SupervisorSpec::default()
5667 };
5668 s.validate()
5669 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
5670 }
5671 }
5672
5673 #[test]
5674 fn child_caixa_empty_takes_precedence_over_invalid() {
5675 // Order pin: the existing `EmptyChildName` diagnostic (which
5676 // doesn't try to parse the DNS-1123 shape) fires before the new
5677 // `ChildCaixaInvalid` per-axis gate, so an empty `:caixa` keeps
5678 // its narrower error message — `is_dns_1123_label` would reject
5679 // the empty string too (boundary check on the first byte), but
5680 // the empty-string arm is the more self-locating diagnostic for
5681 // the author. Same ordering discipline as
5682 // `membro_caixa_empty_takes_precedence_over_invalid` in
5683 // aplicacao.rs.
5684 let s = SupervisorSpec {
5685 children: vec![child("", "^0.1", RestartPolicy::Permanent)],
5686 ..SupervisorSpec::default()
5687 };
5688 let err = s.validate().unwrap_err();
5689 assert_eq!(err, SupervisorError::EmptyChildName);
5690 }
5691
5692 #[test]
5693 fn child_caixa_invalid_fires_before_versao_check() {
5694 // Order pin: the per-axis shape gate runs inline before the
5695 // per-entry versao check, so a malformed `:caixa` on an entry
5696 // whose `:versao` would also fail surfaces the more self-
5697 // locating name-axis diagnostic first. Parallel to
5698 // `membro_versao_invalid_fires_before_duplicate_check` (9888b13)
5699 // and `placement_cluster_invalid_fires_before_duplicate_check`
5700 // (6cbb900).
5701 let s = SupervisorSpec {
5702 children: vec![child("My_Worker", "", RestartPolicy::Permanent)],
5703 ..SupervisorSpec::default()
5704 };
5705 let err = s.validate().unwrap_err();
5706 assert!(
5707 matches!(
5708 err,
5709 SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "My_Worker"
5710 ),
5711 "got {err:?}"
5712 );
5713 }
5714
5715 #[test]
5716 fn child_caixa_invalid_fires_before_duplicate_check() {
5717 // Order pin: a malformed name on a non-duplicate entry surfaces
5718 // its own diagnostic, even when a later entry would otherwise
5719 // collapse onto an earlier name. The per-entry shape gate runs
5720 // inline before the duplicate-key HashSet insert, mirroring
5721 // `placement_cluster_invalid_fires_before_duplicate_check`
5722 // (6cbb900).
5723 let s = SupervisorSpec {
5724 children: vec![
5725 child("Worker", "^0.1", RestartPolicy::Permanent),
5726 child("cache", "^0.1", RestartPolicy::Transient),
5727 child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
5728 ],
5729 ..SupervisorSpec::default()
5730 };
5731 let err = s.validate().unwrap_err();
5732 assert!(
5733 matches!(
5734 err,
5735 SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "Worker"
5736 ),
5737 "got {err:?}"
5738 );
5739 }
5740
5741 #[test]
5742 fn child_caixa_invalid_diagnostic_carries_offending_caixa() {
5743 // The diagnostic-shape pin: the error names the offending
5744 // `:caixa` verbatim plus a non-empty parser-shaped `reason` so
5745 // the author can grep their caixa.lisp without re-running the
5746 // build. Mirrors the diagnostic-shape sweep on every prior
5747 // value-shape gate (3f9d7a0, 6cbb900, c7d05ec).
5748 let s = SupervisorSpec {
5749 children: vec![child("My_Worker", "^0.1", RestartPolicy::Permanent)],
5750 ..SupervisorSpec::default()
5751 };
5752 let err = s.validate().unwrap_err();
5753 let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
5754 panic!("expected ChildCaixaInvalid, got other variant");
5755 };
5756 assert_eq!(caixa, "My_Worker");
5757 assert!(
5758 !reason.is_empty(),
5759 "ChildCaixaInvalid `reason` must carry the parser's wording verbatim"
5760 );
5761 }
5762
5763 // ── value-shape: zero restart_window + duplicate child names ──────────
5764
5765 #[test]
5766 fn validate_accepts_none_restart_window() {
5767 // Omitted `:restart-window` is the "never reset" sentinel —
5768 // valid by design. Mirrors :limits axes where None = unbounded.
5769 let s = SupervisorSpec {
5770 restart_window: None,
5771 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5772 ..SupervisorSpec::default()
5773 };
5774 s.validate().unwrap();
5775 }
5776
5777 #[test]
5778 fn validate_rejects_zero_restart_window() {
5779 // Same "0 means the opposite of what you think" footgun closed
5780 // for :politicas :timeout (Envoy treats 0s as infinite) and
5781 // :limits :wall-clock (wasmtime traps before the call starts).
5782 // Erlang/OTP's MaxIntensity/Period requires Period > 0.
5783 let s = SupervisorSpec {
5784 restart_window: Some(Duration::ZERO),
5785 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5786 ..SupervisorSpec::default()
5787 };
5788 assert_eq!(
5789 s.validate().unwrap_err(),
5790 SupervisorError::RestartWindowZero
5791 );
5792 }
5793
5794 // ── value-shape: integer-ms canonical-form on :restart-window ─────────
5795 //
5796 // The fourth (and last) typed-`Duration` axis in caixa-core to get
5797 // the integer-millisecond canonical-form gate — peer with
5798 // `:limits :wall-clock` (82fc3ef), `:politicas :timeout` (a4ae535),
5799 // and `:politicas :circuit-breaker :window` (a4ae535). The serde
5800 // path is already gated at the shared codec layer (see
5801 // `restart_window_serde_rejects_fractional_seconds`); this arm
5802 // closes the programmatic-struct-literal path the codec gate can't
5803 // see.
5804
5805 #[test]
5806 fn validate_rejects_sub_millisecond_restart_window() {
5807 // The fail-before-pass-after pin: a programmatic
5808 // `Duration::from_micros(1500)` (= 1_500_000 ns) silently passed
5809 // `validate` on every pre-gate codebase, then truncated to
5810 // `as_millis() == 1` on first serialize — the shared codec
5811 // emits `"1ms"`, parses it back to `Duration::from_millis(1)` =
5812 // 1_000_000 ns, the typed `restart_window` no longer matches
5813 // its rendered form.
5814 let s = SupervisorSpec {
5815 restart_window: Some(Duration::from_micros(1500)),
5816 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5817 ..SupervisorSpec::default()
5818 };
5819 match s.validate().unwrap_err() {
5820 SupervisorError::RestartWindowNotCanonical { window } => {
5821 assert_eq!(window, Duration::from_micros(1500));
5822 }
5823 other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
5824 }
5825 }
5826
5827 #[test]
5828 fn validate_rejects_one_nanosecond_restart_window() {
5829 // The far-sub-ms case: `Duration::from_nanos(1)` is non-zero
5830 // (so `RestartWindowZero` doesn't fire) but `as_millis() == 0`,
5831 // so the shared codec emits the literal `"0s"` — the next
5832 // serde round-trip would parse back to `Duration::ZERO`, which
5833 // the `RestartWindowZero` arm then rejects on re-validate. The
5834 // canonical-form gate at this layer surfaces a self-locating
5835 // diagnostic naming the offending Duration verbatim rather
5836 // than a downstream `RestartWindowZero` whose remediation
5837 // points at omitting the slot.
5838 let s = SupervisorSpec {
5839 restart_window: Some(Duration::from_nanos(1)),
5840 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5841 ..SupervisorSpec::default()
5842 };
5843 match s.validate().unwrap_err() {
5844 SupervisorError::RestartWindowNotCanonical { window } => {
5845 assert_eq!(window, Duration::from_nanos(1));
5846 }
5847 other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
5848 }
5849 }
5850
5851 #[test]
5852 fn validate_rejects_nanosecond_past_canonical_boundary_restart_window() {
5853 // The 1-ns-past-1ms boundary case: a `Duration` carrying
5854 // 1_000_001 ns is structurally past the integer-ms granularity
5855 // floor — `subsec_nanos() % 1_000_000 == 1`. The codec round-
5856 // trip would truncate to `1ms` and the consumer would observe
5857 // a 1-ns drift on every emit. Same boundary the peer
5858 // `validate_rejects_nanosecond_past_canonical_boundary` test
5859 // in limits.rs pins for the `:limits :wall-clock` axis.
5860 let w = Duration::from_nanos(1_000_001);
5861 let s = SupervisorSpec {
5862 restart_window: Some(w),
5863 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5864 ..SupervisorSpec::default()
5865 };
5866 assert_eq!(
5867 s.validate().unwrap_err(),
5868 SupervisorError::RestartWindowNotCanonical { window: w }
5869 );
5870 }
5871
5872 #[test]
5873 fn validate_accepts_integer_millisecond_restart_window_values() {
5874 // The positive-control sweep: every `Duration` the shared
5875 // codec can round-trip losslessly — the canonical
5876 // `<integer>{ms,s,m,h}` set the codec's `render` / `parse`
5877 // pair emits and accepts — passes `validate` without
5878 // surfacing the new canonical-form arm. Mirrors
5879 // `validate_accepts_integer_millisecond_wall_clock_values` on
5880 // the sibling `:limits :wall-clock` axis.
5881 for w in [
5882 Duration::from_millis(1),
5883 Duration::from_millis(500),
5884 Duration::from_millis(1500),
5885 Duration::from_secs(1),
5886 Duration::from_secs(30),
5887 Duration::from_secs(60),
5888 Duration::from_secs(120),
5889 Duration::from_secs(3600),
5890 ] {
5891 let s = SupervisorSpec {
5892 restart_window: Some(w),
5893 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5894 ..SupervisorSpec::default()
5895 };
5896 s.validate()
5897 .unwrap_or_else(|e| panic!("integer-ms {w:?} must validate, got {e:?}"));
5898 }
5899 }
5900
5901 #[test]
5902 fn validate_restart_window_zero_takes_precedence_over_canonical_gate() {
5903 // Cross-arm ordering pin: `Duration::ZERO` has
5904 // `subsec_nanos() == 0` and would otherwise pass the
5905 // canonical-form arm — the zero-floor arm must fire first so
5906 // the more self-locating `RestartWindowZero` diagnostic (with
5907 // its omit-axis remediation directly named) leads. Same
5908 // posture every peer zero-then-shape gate uses
5909 // (`WallClockZero` → `WallClockNotCanonical`,
5910 // `PolicyTimeoutZero` → `PolicyTimeoutNotCanonical`,
5911 // `PolicyBreakerZeroWindow` → `PolicyBreakerWindowNotCanonical`).
5912 let s = SupervisorSpec {
5913 restart_window: Some(Duration::ZERO),
5914 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5915 ..SupervisorSpec::default()
5916 };
5917 assert_eq!(
5918 s.validate().unwrap_err(),
5919 SupervisorError::RestartWindowZero
5920 );
5921 }
5922
5923 #[test]
5924 fn restart_window_canonical_diagnostic_carries_offending_duration() {
5925 // Diagnostic-shape pin: the canonical-form arm names the
5926 // offending `Duration` verbatim so the author's grep lands on
5927 // the field's value, not a generic "duration not canonical"
5928 // message. Same shape every other typed-canonical-form arm
5929 // on this surface carries (`WallClockNotCanonical` carries
5930 // the offending `Duration` verbatim,
5931 // `PolicyTimeoutNotCanonical` carries the offending
5932 // `Duration` verbatim).
5933 let w = Duration::from_micros(500);
5934 let s = SupervisorSpec {
5935 restart_window: Some(w),
5936 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5937 ..SupervisorSpec::default()
5938 };
5939 let err = s.validate().unwrap_err();
5940 let msg = err.to_string();
5941 assert!(
5942 msg.contains("500"),
5943 "diagnostic must carry the offending magnitude verbatim (got {msg:?})"
5944 );
5945 assert!(
5946 msg.contains("sub-millisecond"),
5947 "diagnostic must name the sub-millisecond residue class (got {msg:?})"
5948 );
5949 }
5950
5951 #[test]
5952 fn restart_window_validated_value_round_trips_through_codec() {
5953 // The structural property the canonical-ms gate enforces:
5954 // every `SupervisorSpec::restart_window` past
5955 // `SupervisorSpec::validate` round-trips losslessly through
5956 // the shared duration codec (serialize → string →
5957 // deserialize → equal value). Pin this end-to-end so a future
5958 // change to either side (the validate gate's accepted
5959 // granularity, the codec's parse/render unit set) that breaks
5960 // the alignment surfaces here. Peer of
5961 // `wall_clock_validated_value_round_trips_through_codec` on
5962 // the sibling `:limits :wall-clock` axis.
5963 for w in [
5964 Duration::from_millis(1),
5965 Duration::from_millis(1500),
5966 Duration::from_secs(30),
5967 Duration::from_secs(3600),
5968 ] {
5969 let s = SupervisorSpec {
5970 restart_window: Some(w),
5971 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5972 ..SupervisorSpec::default()
5973 };
5974 s.validate().unwrap();
5975 let json = serde_json::to_string(&s).unwrap();
5976 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5977 assert_eq!(back.restart_window, Some(w));
5978 }
5979 }
5980
5981 // ── value-shape: upper cap on :restart-window ─────────────────────────
5982 //
5983 // The fourth (and last) typed-`Duration` axis in caixa-core to get
5984 // the 1h upper cap — peer with `:limits :wall-clock` (51e0dbd),
5985 // `:politicas :timeout` (2e8ee7e), and `:politicas
5986 // :circuit-breaker :window` (379a814). Brackets the typed
5987 // `:restart-window` axis structurally: every validated value lies
5988 // in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`, integer-millisecond
5989 // granularity, closing the
5990 // rolling-window-degenerates-to-lifetime-counter footgun the prior
5991 // zero-floor-and-canonical-form-only checks left open.
5992
5993 #[test]
5994 fn validate_rejects_restart_window_above_cap() {
5995 // The fail-before-pass-after pin: 3601s = 1h + 1s is
5996 // structurally one canonical-tick past the
5997 // [`SUPERVISOR_RESTART_WINDOW_MAX`] ceiling (1h = 3600s) — an
5998 // integer-millisecond magnitude the canonical-form arm above
5999 // accepts cleanly, that the shared duration codec round-trips
6000 // losslessly as `"3601s"`, and that silently passed validate on
6001 // every pre-gate codebase because the typed slot's only checks
6002 // were the zero-floor and canonical-form arms. The runtime
6003 // substrate consuming the value (Erlang/OTP's MaxIntensity/
6004 // Period reconciler, the future wasm-operator's per-supervisor
6005 // restart-intensity counter) reaches for a `Duration` so long
6006 // no realistic restart-recovery pattern resets the counter,
6007 // far from the source caixa.lisp.
6008 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
6009 let s = SupervisorSpec {
6010 restart_window: Some(w),
6011 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6012 ..SupervisorSpec::default()
6013 };
6014 assert_eq!(
6015 s.validate().unwrap_err(),
6016 SupervisorError::RestartWindowExceedsCap { window: w }
6017 );
6018 }
6019
6020 #[test]
6021 fn validate_rejects_restart_window_one_millisecond_above_cap() {
6022 // Boundary case: exactly 1ms past the cap (the granularity the
6023 // canonical-form gate enforces). Catches a future "strictly
6024 // less than" half-measure and pins the diagnostic to name the
6025 // offending `Duration` verbatim. Peer of
6026 // `validate_rejects_wall_clock_one_millisecond_above_cap` /
6027 // `rejects_policy_timeout_one_millisecond_above_cap` /
6028 // `rejects_circuit_breaker_window_one_millisecond_above_cap`
6029 // on the sibling typed-`Duration` axes' top edges.
6030 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
6031 let s = SupervisorSpec {
6032 restart_window: Some(w),
6033 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6034 ..SupervisorSpec::default()
6035 };
6036 assert_eq!(
6037 s.validate().unwrap_err(),
6038 SupervisorError::RestartWindowExceedsCap { window: w }
6039 );
6040 }
6041
6042 #[test]
6043 fn validate_rejects_restart_window_far_above_cap() {
6044 // The "obvious authoring footgun" case: a `(:restart-window "24h")`,
6045 // `(:restart-window "7d")`, or any "I want a lifetime counter
6046 // but wrote a `<integer>h` magnitude anyway" typo — values the
6047 // canonical-form arm accepts as integer-millisecond magnitudes,
6048 // the codec round-trips losslessly through serde, but the
6049 // operator's `MaxIntensity / Period` reconciler cannot honor
6050 // as a meaningful rolling window. Until this gate landed
6051 // validate accepted them. Pin the common above-cap values (24h,
6052 // 7d, ~11.5d) so a future relaxation that drops the upper bound
6053 // surfaces here.
6054 for w in [
6055 Duration::from_secs(86_400), // 24h
6056 Duration::from_secs(604_800), // 7d
6057 Duration::from_secs(1_000_000), // ~11.5 days
6058 ] {
6059 let s = SupervisorSpec {
6060 restart_window: Some(w),
6061 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6062 ..SupervisorSpec::default()
6063 };
6064 assert_eq!(
6065 s.validate().unwrap_err(),
6066 SupervisorError::RestartWindowExceedsCap { window: w }
6067 );
6068 }
6069 }
6070
6071 #[test]
6072 fn validate_accepts_restart_window_at_cap() {
6073 // The boundary value — exactly [`SUPERVISOR_RESTART_WINDOW_MAX`]
6074 // (1h) — must validate. The cap is inclusive on the top edge,
6075 // matching the [`crate::LIMITS_WALL_CLOCK_MAX`] /
6076 // [`crate::POLICY_TIMEOUT_MAX`] /
6077 // [`crate::POLICY_BREAKER_WINDOW_MAX`] discipline on the sibling
6078 // capped axes. Pin the boundary explicitly so a future
6079 // off-by-one tightening (`>= SUPERVISOR_RESTART_WINDOW_MAX`
6080 // instead of `>`) surfaces here as a test failure rather than a
6081 // silent contract narrowing.
6082 let s = SupervisorSpec {
6083 restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
6084 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6085 ..SupervisorSpec::default()
6086 };
6087 s.validate()
6088 .expect("restart_window == SUPERVISOR_RESTART_WINDOW_MAX must validate");
6089 }
6090
6091 #[test]
6092 fn validate_accepts_restart_window_typical_values() {
6093 // The documented Erlang/OTP / Elixir / Riak Core / RabbitMQ
6094 // per-supervisor production-playbook band positive-control
6095 // sweep — every value Learn You Some Erlang's `{intensity, 5,
6096 // 60}` worker-supervisor `Period = 60s` default, Elixir's
6097 // `Supervisor` `max_seconds: 5` default, OTP's `supervisor`
6098 // callback module `MaxT = 5..=60` typical, Riak Core's `MaxT ∈
6099 // 10s..=300s`, and RabbitMQ broker-supervisor `MaxT = 5s`
6100 // default recommend (5s..=300s) must pass, plus a sweep
6101 // through the long-tail-flaky-pool band (5m, 15m, 30m, 1h) the
6102 // cap accepts. Mirrors `validate_accepts_wall_clock_typical_values`
6103 // on the sibling `:limits :wall-clock` axis.
6104 for w in [
6105 Duration::from_millis(1),
6106 Duration::from_millis(500),
6107 Duration::from_secs(1),
6108 Duration::from_secs(5), // RabbitMQ broker-supervisor default
6109 Duration::from_secs(10), // Riak Core lower
6110 Duration::from_secs(30),
6111 Duration::from_secs(60), // Learn You Some Erlang default
6112 Duration::from_secs(120), // OTP supervisor MaxT typical
6113 Duration::from_secs(300), // Riak Core upper
6114 Duration::from_secs(900), // 15m
6115 Duration::from_secs(1800),
6116 Duration::from_secs(3600), // exactly 1h, the cap
6117 ] {
6118 let s = SupervisorSpec {
6119 restart_window: Some(w),
6120 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6121 ..SupervisorSpec::default()
6122 };
6123 s.validate()
6124 .unwrap_or_else(|e| panic!("restart_window={w:?} must validate; got {e:?}"));
6125 }
6126 }
6127
6128 #[test]
6129 fn restart_window_zero_takes_precedence_over_cap() {
6130 // The cross-arm ordering pin: `Duration::ZERO` is structurally
6131 // outside both `>= 1ms` (zero-floor) and `<=
6132 // SUPERVISOR_RESTART_WINDOW_MAX` (cap), but the zero-floor
6133 // diagnostic is the more self-locating one (it directly names
6134 // the omit-axis remediation), so the validate gate must fire
6135 // on zero first. Same shape every other zero-then-cap ordering
6136 // on this surface uses (`WallClockZero` then
6137 // `WallClockExceedsCap`, `PolicyTimeoutZero` then
6138 // `PolicyTimeoutExceedsCap`, `PolicyBreakerZeroWindow` then
6139 // `PolicyBreakerWindowExceedsCap`).
6140 let s = SupervisorSpec {
6141 restart_window: Some(Duration::ZERO),
6142 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6143 ..SupervisorSpec::default()
6144 };
6145 assert_eq!(
6146 s.validate().unwrap_err(),
6147 SupervisorError::RestartWindowZero,
6148 "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
6149 );
6150 }
6151
6152 #[test]
6153 fn restart_window_canonical_takes_precedence_over_cap() {
6154 // The cross-arm ordering pin: a `Duration` that is *both*
6155 // sub-millisecond (non-canonical-form) and structurally above
6156 // the cap surfaces the canonical-form diagnostic first,
6157 // because the round-trip-shape break is the more fundamental
6158 // issue (the value can't even round-trip through the codec,
6159 // so the cap diagnostic naming `1ms..=1h` would be misleading
6160 // — there's no integer-ms form of the offending value). Pin
6161 // the order so a future refactor that reorders the arms
6162 // surfaces here as a test failure rather than a silent
6163 // diagnostic regression. Peer of
6164 // `wall_clock_canonical_takes_precedence_over_cap` /
6165 // `policy_timeout_canonical_takes_precedence_over_cap`.
6166 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_nanos(1);
6167 let s = SupervisorSpec {
6168 restart_window: Some(w),
6169 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6170 ..SupervisorSpec::default()
6171 };
6172 assert_eq!(
6173 s.validate().unwrap_err(),
6174 SupervisorError::RestartWindowNotCanonical { window: w },
6175 "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
6176 );
6177 }
6178
6179 #[test]
6180 fn max_restarts_cap_takes_precedence_over_restart_window_cap() {
6181 // The cross-arm ordering pin between the `:max-restarts` cap
6182 // and the sibling `:restart-window` cap. A supervisor carrying
6183 // both an over-cap `max_restarts` AND an over-cap window must
6184 // surface the `MaxRestartsExceedsCap` diagnostic first — the
6185 // cap arm is wired immediately after the zero-restart arm and
6186 // strictly before every window-axis arm (zero / canonical /
6187 // cap), so the offending value the diagnostic names matches
6188 // the order the author would discover the gates by reading
6189 // top-to-bottom through `SupervisorSpec::validate`. Pin the
6190 // order so a future refactor that reorders the arms surfaces
6191 // here as a test failure rather than a silent diagnostic
6192 // regression. Peer of
6193 // `max_restarts_cap_takes_precedence_over_restart_window_gates`
6194 // on the sibling zero / canonical window arms.
6195 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
6196 let s = SupervisorSpec {
6197 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
6198 restart_window: Some(w),
6199 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6200 ..SupervisorSpec::default()
6201 };
6202 assert_eq!(
6203 s.validate().unwrap_err(),
6204 SupervisorError::MaxRestartsExceedsCap {
6205 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
6206 },
6207 "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
6208 );
6209 }
6210
6211 #[test]
6212 fn restart_window_cap_diagnostic_carries_offending_value() {
6213 // The diagnostic-shape pin: the offending `Duration` is
6214 // carried verbatim into the
6215 // [`SupervisorError::RestartWindowExceedsCap`] variant so the
6216 // surfaced error message names the value the author wrote,
6217 // not just the cap. Same self-locating diagnostic shape every
6218 // other typed-cap arm on this surface carries
6219 // (`WallClockExceedsCap` carries the offending `Duration`
6220 // verbatim, `PolicyTimeoutExceedsCap` carries the offending
6221 // `Duration` verbatim, `PolicyBreakerWindowExceedsCap` carries
6222 // the offending `Duration` verbatim).
6223 let w = Duration::from_secs(7200); // 2h
6224 let s = SupervisorSpec {
6225 restart_window: Some(w),
6226 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6227 ..SupervisorSpec::default()
6228 };
6229 let err = s.validate().unwrap_err();
6230 assert!(
6231 matches!(err, SupervisorError::RestartWindowExceedsCap { window } if window == w),
6232 "got {err:?}"
6233 );
6234 let msg = err.to_string();
6235 assert!(
6236 msg.contains("7200"),
6237 ":supervisor :restart-window cap diagnostic must carry the offending value verbatim (got: {msg})"
6238 );
6239 }
6240
6241 #[test]
6242 fn supervisor_restart_window_cap_pins_canonical_value() {
6243 // The SUPERVISOR_RESTART_WINDOW_MAX constant pins the value at
6244 // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
6245 // shared duration codec emits as a clean canonical string
6246 // (`"<n>h"`). Pinning the literal value here surfaces a future
6247 // drift (a relaxation to 24h, a tightening to 5m) as a
6248 // deliberate test edit, not a silent contract narrowing.
6249 //
6250 // The four typed-`Duration` caps on the validation surface
6251 // (`LIMITS_WALL_CLOCK_MAX` per-process, `POLICY_TIMEOUT_MAX`
6252 // per-edge, `POLICY_BREAKER_WINDOW_MAX` per-breaker,
6253 // `SUPERVISOR_RESTART_WINDOW_MAX` per-supervisor) share a
6254 // single uniform top edge at the codec's largest emitted unit
6255 // — a structural-property invariant the equality assertions
6256 // here enshrine, so a future drift on any of the four
6257 // surfaces as a deliberate test edit. Same shape every other
6258 // typed-cap value pin uses
6259 // (`wall_clock_cap_pins_canonical_value`,
6260 // `policy_timeout_cap_pins_canonical_value`,
6261 // `circuit_breaker_window_cap_pins_canonical_value`).
6262 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, Duration::from_secs(3600));
6263 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX.as_millis(), 3_600_000);
6264 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::LIMITS_WALL_CLOCK_MAX);
6265 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::POLICY_TIMEOUT_MAX);
6266 assert_eq!(
6267 SUPERVISOR_RESTART_WINDOW_MAX,
6268 crate::POLICY_BREAKER_WINDOW_MAX
6269 );
6270 }
6271
6272 #[test]
6273 fn restart_window_cap_value_round_trips_through_codec() {
6274 // The codec round-trip property the cap arm preserves: the
6275 // [`SUPERVISOR_RESTART_WINDOW_MAX`] constant itself round-trips
6276 // through the shared duration codec — every value at the cap
6277 // serializes to the canonical `"1h"` form and parses back
6278 // identically. Pin the round-trip so a future change to the
6279 // codec's unit set or to the cap's magnitude that breaks the
6280 // round-trip property surfaces here. Peer of
6281 // `wall_clock_cap_value_round_trips_through_codec` on the
6282 // sibling `:limits :wall-clock` axis.
6283 let s = SupervisorSpec {
6284 restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
6285 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6286 ..SupervisorSpec::default()
6287 };
6288 s.validate().unwrap();
6289 let json = serde_json::to_string(&s).unwrap();
6290 assert!(
6291 json.contains("\"1h\""),
6292 "SUPERVISOR_RESTART_WINDOW_MAX must serialize to the canonical `\"1h\"` form (got {json})"
6293 );
6294 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6295 assert_eq!(back.restart_window, Some(SUPERVISOR_RESTART_WINDOW_MAX));
6296 }
6297
6298 #[test]
6299 fn validate_rejects_duplicate_child_caixa() {
6300 // Two children with the same :caixa render to two ComputeUnits
6301 // with the same name in the cluster's HelmRelease values —
6302 // one silently overwrites the other. Erlang/OTP's child_spec.id
6303 // is required-unique per supervisor; same set-not-multiset
6304 // discipline applied here as for :membros / :placement
6305 // :clusters / :entrada :paths.
6306 let s = SupervisorSpec {
6307 children: vec![
6308 child("worker", "^0.1", RestartPolicy::Permanent),
6309 child("cache", "^0.1", RestartPolicy::Transient),
6310 child("worker", "^0.2", RestartPolicy::Permanent),
6311 ],
6312 ..SupervisorSpec::default()
6313 };
6314 let err = s.validate().unwrap_err();
6315 assert!(
6316 matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "worker"),
6317 "got {err:?}"
6318 );
6319 }
6320
6321 #[test]
6322 fn validate_duplicate_child_diagnostic_names_first_collision() {
6323 // Iteration walks the :children list in declaration order —
6324 // the diagnostic names the first repeat, deterministically,
6325 // even when multiple names duplicate.
6326 let s = SupervisorSpec {
6327 children: vec![
6328 child("a", "^0.1", RestartPolicy::Permanent),
6329 child("b", "^0.1", RestartPolicy::Permanent),
6330 child("a", "^0.1", RestartPolicy::Permanent),
6331 child("b", "^0.1", RestartPolicy::Permanent),
6332 ],
6333 ..SupervisorSpec::default()
6334 };
6335 let err = s.validate().unwrap_err();
6336 assert!(
6337 matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "a"),
6338 "got {err:?}"
6339 );
6340 }
6341
6342 // ── self-supervision cross-slot gate ──────────────────────────
6343
6344 #[test]
6345 fn validate_no_self_supervision_rejects_self_referential_child() {
6346 // A supervisor whose `:children` lists its own `:nome` is a
6347 // one-node reconciliation cycle — rejected, naming the parent.
6348 let children = vec![
6349 child("worker", "^0.1", RestartPolicy::Permanent),
6350 child("orquestra", "^0.1", RestartPolicy::Permanent),
6351 ];
6352 let err = validate_no_self_supervision(&children, "orquestra").unwrap_err();
6353 assert!(
6354 matches!(err, SupervisorError::ChildSupervisesSelf { ref caixa } if caixa == "orquestra"),
6355 "got {err:?}"
6356 );
6357 }
6358
6359 #[test]
6360 fn validate_no_self_supervision_accepts_distinct_children() {
6361 // Positive control: distinct child names (including a child that
6362 // is itself a supervisor — nested trees are valid OTP) pass.
6363 let children = vec![
6364 child("worker", "^0.1", RestartPolicy::Permanent),
6365 child("sub-tree", "^0.1", RestartPolicy::Permanent),
6366 ];
6367 validate_no_self_supervision(&children, "orquestra").unwrap();
6368 }
6369
6370 #[test]
6371 fn validate_no_self_supervision_empty_children_is_ok() {
6372 // SimpleOneForOne / no-static-children supervisors have nothing
6373 // to self-reference — the gate is vacuously satisfied.
6374 validate_no_self_supervision(&[], "orquestra").unwrap();
6375 }
6376
6377 #[test]
6378 fn validate_simple_one_for_one_skips_uniqueness_check() {
6379 // SimpleOneForOne supervisors carry no static children — the
6380 // duplicate-child loop never runs. A zero-window declaration
6381 // on a SimpleOneForOne supervisor still trips the window check
6382 // (window applies to dynamic children too).
6383 let s = SupervisorSpec {
6384 estrategia: RestartStrategy::SimpleOneForOne,
6385 restart_window: None,
6386 children: vec![],
6387 ..SupervisorSpec::default()
6388 };
6389 s.validate().unwrap();
6390 let s_zero = SupervisorSpec {
6391 estrategia: RestartStrategy::SimpleOneForOne,
6392 restart_window: Some(Duration::ZERO),
6393 children: vec![],
6394 ..SupervisorSpec::default()
6395 };
6396 assert_eq!(
6397 s_zero.validate().unwrap_err(),
6398 SupervisorError::RestartWindowZero
6399 );
6400 }
6401
6402 #[test]
6403 fn validate_zero_window_runs_after_max_restarts_check() {
6404 // Pin the order: max_restarts == 0 fires before
6405 // restart_window == 0s, so an author with both wrong sees the
6406 // counter-axis diagnostic first (matches the order in the
6407 // struct and in the doc comment).
6408 let s = SupervisorSpec {
6409 max_restarts: 0,
6410 restart_window: Some(Duration::ZERO),
6411 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6412 ..SupervisorSpec::default()
6413 };
6414 assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
6415 }
6416
6417 #[test]
6418 fn round_trip_all_strategies() {
6419 for &strat in RestartStrategy::ALL {
6420 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
6421 // shape partition through the [`gen_platform::IsVariant`]
6422 // derive-generated [`RestartStrategy::is_simple_one_for_one`]
6423 // predicate rather than the raw
6424 // `matches!(strat, RestartStrategy::SimpleOneForOne)`
6425 // open-coded pattern-match — same closed-set-typed-enum
6426 // arm-discriminator dispatch discipline the sibling
6427 // [`crate::upgrade::UpgradeInstruction::is_restart`] convergence
6428 // (915a934) extended onto its two paired positive / negated
6429 // `matches!` filter sites, and the sibling
6430 // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
6431 // predicate convergence (766ec63) extended onto the M3 mesh-
6432 // slot per-`:placement` distribution-strategy `matches!`
6433 // discriminator axis. See the sibling
6434 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
6435 // fixture and the peer `manifest::tests::
6436 // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
6437 // fixture — all three sites (the last unlifted
6438 // `matches!`-based arm-discriminator axis on the OTP-shape
6439 // supervisor sibling-restart-strategy closed-set typed enum,
6440 // acknowledged in 915a934's Prior-commits footnote as the
6441 // outstanding follow-up) now consult one typed dispatch on
6442 // the substrate primitive.
6443 let s = SupervisorSpec {
6444 estrategia: strat,
6445 children: if strat.is_simple_one_for_one() {
6446 vec![]
6447 } else {
6448 vec![child("w", "^0.1", RestartPolicy::Permanent)]
6449 },
6450 ..SupervisorSpec::default()
6451 };
6452 let json = serde_json::to_string(&s).unwrap();
6453 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6454 assert_eq!(s, back);
6455 }
6456 }
6457
6458 #[test]
6459 fn round_trip_all_restart_policies() {
6460 for policy in [
6461 RestartPolicy::Permanent,
6462 RestartPolicy::Temporary,
6463 RestartPolicy::Transient,
6464 ] {
6465 let c = child("w", "^0.1", policy);
6466 let json = serde_json::to_string(&c).unwrap();
6467 let back: ChildSpec = serde_json::from_str(&json).unwrap();
6468 assert_eq!(c, back);
6469 }
6470 }
6471
6472 #[test]
6473 fn restart_strategy_is_simple_one_for_one_predicate_partitions_the_arm_set() {
6474 // The fail-before-pass-after pin on the `gen_platform::IsVariant`
6475 // derive's [`RestartStrategy::is_simple_one_for_one`] arm-
6476 // discriminator predicate: [`RestartStrategy::SimpleOneForOne`]
6477 // is the only variant that satisfies `.is_simple_one_for_one()`;
6478 // every static-children-bearing arm (`OneForOne` / `OneForAll`
6479 // / `RestForOne`) returns `false`. This pin makes the partition
6480 // invariant load-bearing at caixa-core test time so a future
6481 // derive regression (a hole that returns `false` for
6482 // `SimpleOneForOne` too, or a byte-collision that flips a second
6483 // variant to `true`) trips here rather than laundering the arm
6484 // at the three test-fixture builder sites (a hole flips the
6485 // `SimpleOneForOne` fixture to carry a non-empty children list
6486 // and the subsequent `SupervisorSpec::validate` would refuse the
6487 // fixture with [`SupervisorError::SimpleOneForOneWithStaticChildren`];
6488 // a collision flips a peer strategy's fixture to carry an empty
6489 // children list and the subsequent `validate` would refuse with
6490 // [`SupervisorError::NoChildren`] — either way, the pin fires
6491 // here, at the derive site, rather than at the fixture-refusal
6492 // site far away). Peer of the sibling
6493 // [`crate::upgrade::tests::upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
6494 // (915a934) pin on the M2 OTP-appup axis and the sibling
6495 // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
6496 // pin on the M0 `:kind` axis.
6497 let cases: &[(RestartStrategy, bool)] = &[
6498 (RestartStrategy::OneForOne, false),
6499 (RestartStrategy::OneForAll, false),
6500 (RestartStrategy::RestForOne, false),
6501 (RestartStrategy::SimpleOneForOne, true),
6502 ];
6503 for (variant, expected) in cases {
6504 assert_eq!(
6505 variant.is_simple_one_for_one(),
6506 *expected,
6507 "RestartStrategy::{variant:?}.is_simple_one_for_one() must \
6508 return {expected} (partition invariant on the \
6509 IsVariant-derived arm-discriminator predicate — every \
6510 test-fixture site that partitions the `:children` slot \
6511 shape on `SimpleOneForOne ↔ non-SimpleOneForOne` keys \
6512 off this typed dispatch, so a derive regression must \
6513 surface here rather than at the fixture-refusal site)"
6514 );
6515 }
6516 }
6517
6518 #[test]
6519 fn restart_strategy_fixture_partition_routes_through_is_simple_one_for_one_predicate() {
6520 // Byte-identity pin on the `SimpleOneForOne ↔ non-SimpleOneForOne`
6521 // fixture-shape partition against the pre-lift
6522 // `matches!(strat, RestartStrategy::SimpleOneForOne)` open-coded
6523 // pattern-match every test-fixture builder site previously
6524 // coupled to inline. Asserts the two projections agree byte-for-
6525 // byte on every arm of the enum, so a future derive regression
6526 // that flipped either predicate's arm-set would surface here at
6527 // caixa-core test time rather than at the three fixture-builder
6528 // sites (`supervisor::tests::round_trip_all_strategies`,
6529 // `supervisor::tests::supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`,
6530 // `manifest::tests::caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`)
6531 // far from the derive site. Same peer-shape byte-identity pin
6532 // every sibling `IsVariant`-derive-routed convergence carries on
6533 // the substrate's closed-set typed-enum surface (peer of
6534 // [`crate::upgrade::tests::validate_restart_exclusive_routes_through_is_restart_predicate`]
6535 // on the M2 OTP-appup axis).
6536 for &strat in RestartStrategy::ALL {
6537 let via_predicate = strat.is_simple_one_for_one();
6538 let via_matches = matches!(strat, RestartStrategy::SimpleOneForOne);
6539 assert_eq!(
6540 via_predicate, via_matches,
6541 "RestartStrategy::{strat:?}: is_simple_one_for_one() must \
6542 byte-equal matches!(_, RestartStrategy::SimpleOneForOne) — \
6543 the pre-lift open-coded pattern and the \
6544 IsVariant-derived predicate are the same axis, \
6545 one typed dispatch"
6546 );
6547 }
6548 }
6549
6550 #[test]
6551 fn duration_codec_round_trip_canonical_units() {
6552 // Note the canonical-form rule: durations serialize to the
6553 // *largest* unit that divides cleanly, so 60s ↔ "1m" and not
6554 // "60s" — but the round-trip preserves the underlying Duration.
6555 let cases = [
6556 ("30s", Duration::from_secs(30)),
6557 ("5m", Duration::from_secs(300)),
6558 ("1h", Duration::from_secs(3600)),
6559 ("500ms", Duration::from_millis(500)),
6560 ];
6561 for (lit, dur) in cases {
6562 let s = SupervisorSpec {
6563 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6564 restart_window: Some(dur),
6565 ..SupervisorSpec::default()
6566 };
6567 let json = serde_json::to_string(&s).unwrap();
6568 assert!(
6569 json.contains(&format!("\"{lit}\"")),
6570 "expected \"{lit}\" in {json}"
6571 );
6572 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6573 assert_eq!(back.restart_window, Some(dur));
6574 }
6575 }
6576
6577 #[test]
6578 fn duration_canonicalizes_to_largest_unit() {
6579 // 60 seconds → "1m" (largest cleanly-divisible unit), but the
6580 // typed Duration still equals 60s on the way back.
6581 let s = SupervisorSpec {
6582 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6583 restart_window: Some(Duration::from_secs(60)),
6584 ..SupervisorSpec::default()
6585 };
6586 let json = serde_json::to_string(&s).unwrap();
6587 assert!(json.contains("\"1m\""), "{json}");
6588 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6589 assert_eq!(back.restart_window, Some(Duration::from_secs(60)));
6590 }
6591
6592 #[test]
6593 fn three_child_one_for_one_validates() {
6594 let s = SupervisorSpec {
6595 estrategia: RestartStrategy::OneForOne,
6596 max_restarts: 5,
6597 restart_window: Some(Duration::from_secs(60)),
6598 children: vec![
6599 child("worker", "^0.1", RestartPolicy::Permanent),
6600 child("cache", "^0.1", RestartPolicy::Transient),
6601 child("scratch", "^0.1", RestartPolicy::Temporary),
6602 ],
6603 };
6604 s.validate().unwrap();
6605 }
6606
6607 #[test]
6608 fn json_uses_pascal_case_for_strategy_and_policy() {
6609 // Variant names are PascalCase by default in serde, matching
6610 // tatara-lisp's enum convention (`:estrategia OneForOne`).
6611 let c = child("w", "^0.1", RestartPolicy::Permanent);
6612 let json = serde_json::to_string(&c).unwrap();
6613 assert!(json.contains("\"Permanent\""));
6614 assert!(!json.contains("\"permanent\""));
6615
6616 let s = SupervisorSpec {
6617 estrategia: RestartStrategy::OneForOne,
6618 children: vec![c],
6619 ..SupervisorSpec::default()
6620 };
6621 let json = serde_json::to_string(&s).unwrap();
6622 assert!(json.contains("\"estrategia\":\"OneForOne\""));
6623 }
6624
6625 // ── shared duration codec: integer-magnitude canonical-form gate ──
6626 //
6627 // The gate lifts the discipline `crate::limits::parse_duration`
6628 // (818dd38) carries on the peer `:limits :wall-clock` codec onto
6629 // the shared codec backing the remaining three typed-duration
6630 // slots: `:supervisor :restart-window`, `:politicas :timeout`, and
6631 // `:politicas :circuit-breaker :window`. Every magnitude `render`
6632 // emits is a non-negative integer with no decimal point and no
6633 // leading sign, so the codec's accepted set must match for
6634 // serialize/deserialize to round-trip without canonical-form
6635 // drift.
6636
6637 #[test]
6638 fn parse_accepts_integer_canonical_units() {
6639 // Pin the happy-path: every canonical author shape `render`
6640 // ever emits parses to the same `Duration` value, so the
6641 // codec's accepted set is at least a superset of its emitted
6642 // set on the canonical-unit axis.
6643 for (lit, dur) in [
6644 ("30s", Duration::from_secs(30)),
6645 ("500ms", Duration::from_millis(500)),
6646 ("2m", Duration::from_secs(120)),
6647 ("1h", Duration::from_secs(3600)),
6648 ("0s", Duration::ZERO),
6649 ] {
6650 assert_eq!(
6651 duration_codec::parse(lit).unwrap(),
6652 dur,
6653 "parse({lit:?}) should be {dur:?}"
6654 );
6655 }
6656 }
6657
6658 #[test]
6659 fn parse_accepts_bare_integer_as_seconds() {
6660 // The `"s" | ""` arm: a bare integer with no unit is read as
6661 // seconds. Pin this so the unit-empty form keeps parsing (it
6662 // renders to `"<n>s"` on serialize — that's a unit-choice
6663 // drift the integer-magnitude gate does NOT close, matching
6664 // the `parse_byte_size` `"1024"` → `"1KiB"` scope decision in
6665 // the peer `:limits :memory` codec).
6666 assert_eq!(
6667 duration_codec::parse("30").unwrap(),
6668 Duration::from_secs(30)
6669 );
6670 }
6671
6672 #[test]
6673 fn parse_rejects_fractional_seconds_with_canonical_form_diagnostic() {
6674 // `"1.5s"` parses as f64 to 1.5 → renders back as `"1500ms"`
6675 // on first serialize — DRIFT. The integer-magnitude gate names
6676 // the offending `"1.5"` verbatim and points at the canonical
6677 // remediation `"1500ms"`.
6678 let err = duration_codec::parse("1.5s").unwrap_err();
6679 assert!(err.contains("\"1.5\""), "missing magnitude in {err:?}");
6680 assert!(
6681 err.contains("not a non-negative integer"),
6682 "missing canonical-form reason in {err:?}"
6683 );
6684 assert!(
6685 err.contains("\"1500ms\""),
6686 "missing canonical-form remediation in {err:?}"
6687 );
6688 }
6689
6690 #[test]
6691 fn parse_rejects_decimal_shaped_integer_seconds() {
6692 // `"1.0s"` is the trickiest drift class: numerically `1.0s` is
6693 // `1s` exactly, so the round-trip looks correct — but the
6694 // emitted canonical form is `"1s"`, not `"1.0s"`. Gate the
6695 // decimal-shape-with-integer-value form so author intent is
6696 // never silently rewritten.
6697 let err = duration_codec::parse("1.0s").unwrap_err();
6698 assert!(err.contains("\"1.0\""), "missing magnitude in {err:?}");
6699 assert!(
6700 err.contains("not a non-negative integer"),
6701 "missing canonical-form reason in {err:?}"
6702 );
6703 }
6704
6705 #[test]
6706 fn parse_rejects_half_unit_minute() {
6707 // `"0.5m"` is the unit-fraction footgun — author writes a
6708 // human-readable half-minute, serde silently rewrites to
6709 // `"30s"` on next emit. The gate names the offending
6710 // magnitude `"0.5"` and points at the integer-in-smaller-unit
6711 // form.
6712 let err = duration_codec::parse("0.5m").unwrap_err();
6713 assert!(err.contains("\"0.5\""), "missing magnitude in {err:?}");
6714 assert!(
6715 err.contains("\"30s\""),
6716 "missing canonical-form remediation in {err:?}"
6717 );
6718 }
6719
6720 #[test]
6721 fn parse_rejects_leading_plus_sign() {
6722 // `u64::from_str` rejects `"+30"` but `f64::from_str` accepts
6723 // it as `30.0` — the prior parser used f64 so `"+30s"` parsed
6724 // cleanly to 30s and round-tripped to `"30s"` on next emit
6725 // (DRIFT). The digit-only gate closes the leading-sign class
6726 // first; the diagnostic names `"+30"` verbatim.
6727 let err = duration_codec::parse("+30s").unwrap_err();
6728 assert!(err.contains("\"+30\""), "missing magnitude in {err:?}");
6729 assert!(
6730 err.contains("not a non-negative integer"),
6731 "missing canonical-form reason in {err:?}"
6732 );
6733 }
6734
6735 #[test]
6736 fn parse_rejects_leading_minus_sign() {
6737 // The former `num < 0.0` arm: `"-30s"` parsed as f64 to -30,
6738 // rejected with `"negative duration in \"-30s\""`. Under the
6739 // integer-magnitude gate the diagnostic is unified — `-30` is
6740 // non-digit-only, f64-numeric, and surfaces with the canonical-
6741 // form reason (no leading `+` / `-` sign) naming the offending
6742 // `"-30"` verbatim. Same diagnostic shape as every other
6743 // rejected non-integer magnitude.
6744 let err = duration_codec::parse("-30s").unwrap_err();
6745 assert!(err.contains("\"-30\""), "missing magnitude in {err:?}");
6746 assert!(
6747 err.contains("not a non-negative integer"),
6748 "missing canonical-form reason in {err:?}"
6749 );
6750 }
6751
6752 #[test]
6753 fn parse_garbage_still_falls_through_to_bad_magnitude() {
6754 // Non-digit-only AND non-numeric (`"--1s"`, `"abc"`) falls
6755 // through to the narrower "bad duration magnitude" arm — the
6756 // canonical-form diagnostic is reserved for the parser-shape
6757 // footgun case, not the "not a number at all" case. Same
6758 // shape `parse_byte_size`'s `BadByteMagnitude` arm carries on
6759 // the peer `:limits :memory` codec.
6760 let err = duration_codec::parse("--1s").unwrap_err();
6761 assert!(
6762 err.contains("bad duration magnitude"),
6763 "expected bad-magnitude wording in {err:?}"
6764 );
6765 }
6766
6767 #[test]
6768 fn parse_digit_only_magnitude_carries_zero_f64_drift() {
6769 // The accepted set is now closed under `u64`-exact integer
6770 // arithmetic: `"500ms"` → `Duration::from_millis(500)` exactly,
6771 // `"3600s"` → `Duration::from_secs(3600)` exactly, `"1h"` →
6772 // `Duration::from_secs(3600)` exactly, no f64 mantissa drift
6773 // possible. Pin the integer-exact arms across the four unit
6774 // suffixes so a future refactor that reaches back for f64
6775 // (`from_secs_f64`, `mul_f64`) surfaces here.
6776 assert_eq!(
6777 duration_codec::parse("3600s").unwrap(),
6778 Duration::from_secs(3600)
6779 );
6780 assert_eq!(
6781 duration_codec::parse("60m").unwrap(),
6782 Duration::from_secs(3600)
6783 );
6784 assert_eq!(
6785 duration_codec::parse("1h").unwrap(),
6786 Duration::from_secs(3600)
6787 );
6788 assert_eq!(
6789 duration_codec::parse("999ms").unwrap(),
6790 Duration::from_millis(999)
6791 );
6792 }
6793
6794 #[test]
6795 fn restart_window_serde_rejects_fractional_seconds() {
6796 // The shared codec backs `SupervisorSpec::restart_window`
6797 // (`with = "duration_codec"`) — so the gate applies on serde
6798 // deserialize for the typed Supervisor slot. A
6799 // `{"restartWindow":"1.5s"}` payload that previously round-
6800 // tripped to a different canonical string on next serialize
6801 // is now refused at deserialize with the integer-magnitude
6802 // diagnostic.
6803 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6804 "restartWindow":"1.5s",
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("not a non-negative integer"),
6810 "expected integer-magnitude diagnostic in {msg:?}"
6811 );
6812 assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
6813 }
6814
6815 #[test]
6816 fn restart_window_serde_rejects_leading_plus() {
6817 // The `u64::from_str` leading-`+` permissiveness gap that
6818 // motivated the digit-only gate (the `f64`-side accepted
6819 // `"+30"`, the prior parser silently round-tripped to `"30s"`)
6820 // is now closed on the shared codec — surfaces as a structured
6821 // diagnostic at the serde layer for every typed-duration slot.
6822 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6823 "restartWindow":"+30s",
6824 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6825 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6826 let msg = err.to_string();
6827 assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
6828 assert!(
6829 msg.contains("not a non-negative integer"),
6830 "missing canonical-form reason in {msg:?}"
6831 );
6832 }
6833
6834 #[test]
6835 fn parse_rejects_leading_zero_magnitude() {
6836 // `"030s"` is digit-only, so the existing non-digit-only / sign
6837 // / fractional arm doesn't catch it — `u64::from_str("030")`
6838 // returns `Ok(30)`, so before this gate `"030s"` parsed to
6839 // `Duration::from_secs(30)` and round-tripped through `render`
6840 // to `"30s"` — a *different* canonical string on the next emit,
6841 // breaking the THEORY.md Part V render-determinism contract
6842 // exactly the way `"+30s"` did before the leading-`+` arm
6843 // landed. Peer with the `rate_limit_codec` leading-zero arm
6844 // (4f46830) on the same canonical-form-drift axis.
6845 let err = duration_codec::parse("030s").unwrap_err();
6846 assert!(
6847 err.contains("non-canonical leading zero"),
6848 "expected leading-zero diagnostic in {err:?}"
6849 );
6850 assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
6851 assert!(
6852 err.contains("\"30s\""),
6853 "missing canonical-form remediation in {err:?}"
6854 );
6855 assert!(
6856 err.contains("THEORY.md"),
6857 "missing render-determinism citation in {err:?}"
6858 );
6859 }
6860
6861 #[test]
6862 fn parse_rejects_multi_digit_zero_magnitude() {
6863 // `"00s"` and `"00ms"` are the all-zero leading-zero footgun —
6864 // digit-only, parse losslessly to `Duration::ZERO`, but render
6865 // back to `"0s"` (the single-byte canonical form) on the next
6866 // emit. The leading-zero arm refuses the drift class at the
6867 // codec layer; the semantic-zero gate downstream
6868 // (`SupervisorError::ZeroRestartWindow`, etc.) would refuse
6869 // the single-byte canonical form `"0s"` separately on the
6870 // typed-validate layer.
6871 let err = duration_codec::parse("00s").unwrap_err();
6872 assert!(
6873 err.contains("non-canonical leading zero"),
6874 "expected leading-zero diagnostic in {err:?}"
6875 );
6876 assert!(err.contains("\"00\""), "missing magnitude in {err:?}");
6877 }
6878
6879 #[test]
6880 fn parse_rejects_leading_zero_per_hour_window() {
6881 // `"01h"` is the per-hour-window footgun — multi-byte magnitude
6882 // starting with `0`, parses losslessly to `Duration::from_secs(3600)`,
6883 // renders to `"1h"` (DRIFT). The arm is unit-agnostic: every
6884 // canonical unit suffix the codec accepts (`ms` / `s` / `m` /
6885 // `h` / bare-integer-as-seconds) inherits the same gate.
6886 let err = duration_codec::parse("01h").unwrap_err();
6887 assert!(
6888 err.contains("non-canonical leading zero"),
6889 "expected leading-zero diagnostic in {err:?}"
6890 );
6891 assert!(err.contains("\"01\""), "missing magnitude in {err:?}");
6892 }
6893
6894 #[test]
6895 fn parse_rejects_leading_zero_bare_integer_as_seconds() {
6896 // The `parse_accepts_bare_integer_as_seconds` happy-path
6897 // (`"30"` → 30s) inherits the leading-zero arm: `"030"` is
6898 // multi-byte starts-with-`0`, parses losslessly to
6899 // `Duration::from_secs(30)`, renders to `"30s"` (DRIFT). The
6900 // bare-integer surface accepts permissive unit-empty
6901 // shorthand but still must reject leading-zero padding.
6902 let err = duration_codec::parse("030").unwrap_err();
6903 assert!(
6904 err.contains("non-canonical leading zero"),
6905 "expected leading-zero diagnostic in {err:?}"
6906 );
6907 assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
6908 }
6909
6910 #[test]
6911 fn parse_accepts_single_zero_magnitude_at_codec_layer() {
6912 // The codec-layer / typed-validate-layer boundary: `"0s"` /
6913 // `"0ms"` / `"0"` are the single-byte canonical-zero forms —
6914 // each round-trips losslessly through `render`
6915 // (`render(Duration::ZERO)` → `"0s"`), so the codec layer
6916 // accepts them. The downstream semantic-zero gates
6917 // (`SupervisorError::ZeroRestartWindow`,
6918 // `AplicacaoError::PolicyTimeoutZero`,
6919 // `AplicacaoError::PolicyCircuitBreakerWindowZero`) refuse
6920 // zero-magnitude authoring at the typed-validate layer above,
6921 // peer with the `rate_limit_codec` codec-layer / typed-
6922 // validate-layer partition for `"0/s"`.
6923 assert_eq!(duration_codec::parse("0s").unwrap(), Duration::ZERO);
6924 assert_eq!(duration_codec::parse("0ms").unwrap(), Duration::ZERO);
6925 assert_eq!(duration_codec::parse("0").unwrap(), Duration::ZERO);
6926 }
6927
6928 #[test]
6929 fn parse_accepts_canonical_magnitude_with_leading_one() {
6930 // The complementary boundary: a future tightening cannot
6931 // drift into rejecting valid canonical magnitudes that
6932 // happen to start with `1` (or any digit `[1-9]`). Pin
6933 // every canonical-unit suffix so the leading-zero arm
6934 // remains strictly narrower than the digit-only arm.
6935 assert_eq!(
6936 duration_codec::parse("100ms").unwrap(),
6937 Duration::from_millis(100)
6938 );
6939 assert_eq!(
6940 duration_codec::parse("100s").unwrap(),
6941 Duration::from_secs(100)
6942 );
6943 assert_eq!(
6944 duration_codec::parse("10m").unwrap(),
6945 Duration::from_secs(600)
6946 );
6947 assert_eq!(
6948 duration_codec::parse("10h").unwrap(),
6949 Duration::from_secs(36_000)
6950 );
6951 }
6952
6953 #[test]
6954 fn restart_window_serde_rejects_leading_zero() {
6955 // The shared codec backs `SupervisorSpec::restart_window`
6956 // (`with = "duration_codec"`) — so the leading-zero arm
6957 // applies on serde deserialize for the typed Supervisor slot.
6958 // A `{"restartWindow":"030s"}` payload that previously round-
6959 // tripped to a different canonical string on next serialize
6960 // is now refused at deserialize with the leading-zero
6961 // diagnostic. Peer with `restart_window_serde_rejects_leading_plus`
6962 // / `restart_window_serde_rejects_fractional_seconds` on the
6963 // same canonical-form-drift axis.
6964 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6965 "restartWindow":"030s",
6966 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6967 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6968 let msg = err.to_string();
6969 assert!(
6970 msg.contains("non-canonical leading zero"),
6971 "expected leading-zero diagnostic in {msg:?}"
6972 );
6973 assert!(msg.contains("\"030\""), "missing magnitude in {msg:?}");
6974 }
6975
6976 #[test]
6977 fn parse_rejects_leading_whitespace() {
6978 // `" 30s"` — the canonical paste-from-aligned-doc /
6979 // paste-from-YAML-quoted-plain-scalar footgun. Before this
6980 // gate the top-level `s.trim()` at parse entry silently ate
6981 // the leading space and parsed the value to
6982 // `Duration::from_secs(30)`, which then round-tripped through
6983 // `render` to `"30s"` (a *different* canonical string on the
6984 // next emit) — the exact canonical-form-drift class the
6985 // leading-`+` / leading-zero arms already close, extended
6986 // to the whitespace-byte class. Peer with the sibling
6987 // `rate_limit_codec` whitespace-rejection arm (1ad7755) on
6988 // the M3 `:politicas` axis.
6989 let err = duration_codec::parse(" 30s").unwrap_err();
6990 assert!(
6991 err.contains("contains whitespace byte"),
6992 "expected whitespace diagnostic in {err:?}"
6993 );
6994 assert!(err.contains("0x20"), "missing offending byte in {err:?}");
6995 assert!(
6996 err.contains("THEORY.md"),
6997 "missing render-determinism contract citation in {err:?}"
6998 );
6999 }
7000
7001 #[test]
7002 fn parse_rejects_trailing_whitespace() {
7003 // `"30s "` — the canonical shell-history / trailing-space
7004 // paste footgun. Before this gate the top-level `s.trim()`
7005 // silently ate the trailing space and parsed to
7006 // `Duration::from_secs(30)`, round-tripping to `"30s"` on the
7007 // next emit — same canonical-form drift as the leading-space
7008 // sibling, closed on the same whitespace-byte arm.
7009 let err = duration_codec::parse("30s ").unwrap_err();
7010 assert!(
7011 err.contains("contains whitespace byte"),
7012 "expected whitespace diagnostic in {err:?}"
7013 );
7014 assert!(err.contains("0x20"), "missing offending byte in {err:?}");
7015 }
7016
7017 #[test]
7018 fn parse_rejects_internal_whitespace_between_magnitude_and_unit() {
7019 // `"30 s"` — the canonical typographically-spaced author
7020 // shape (the same idiom every prose reference to a duration
7021 // renders as, mistakenly retained when the value is pasted
7022 // into a codec-shaped slot). Before this gate the per-part
7023 // `num_part.trim()` / `unit.trim()` calls silently ate the
7024 // whitespace between the magnitude and the unit and parsed
7025 // the value to `Duration::from_secs(30)`, round-tripping to
7026 // `"30s"` — the codec's *internal* whitespace-tolerance
7027 // vector, orthogonal to the leading / trailing surface but
7028 // the same canonical-form-drift class. Pins the arm as
7029 // strictly stronger than the pre-existing top-level
7030 // `s.trim()` behavior: it fires on whitespace anywhere in
7031 // the value, not just at the string boundary.
7032 let err = duration_codec::parse("30 s").unwrap_err();
7033 assert!(
7034 err.contains("contains whitespace byte"),
7035 "expected whitespace diagnostic in {err:?}"
7036 );
7037 assert!(err.contains("0x20"), "missing offending byte in {err:?}");
7038 }
7039
7040 #[test]
7041 fn parse_rejects_tab_byte() {
7042 // `"\t30s"` — the canonical paste-from-indented-doc /
7043 // paste-from-YAML-block-scalar footgun where a tab byte leads
7044 // the magnitude. Pins that the gate covers tab (`0x09`) as
7045 // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
7046 // members and both would be silently swallowed by `s.trim()`
7047 // pre-gate. The `is_ascii_whitespace` coverage extends beyond
7048 // space alone to the full ASCII-whitespace set (space `0x20`,
7049 // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
7050 // the tab arm as a representative of the non-space members.
7051 let err = duration_codec::parse("\t30s").unwrap_err();
7052 assert!(
7053 err.contains("contains whitespace byte"),
7054 "expected whitespace diagnostic in {err:?}"
7055 );
7056 assert!(
7057 err.contains("0x09"),
7058 "missing offending tab byte in {err:?}"
7059 );
7060 }
7061
7062 #[test]
7063 fn restart_window_serde_rejects_whitespace() {
7064 // The shared codec backs `SupervisorSpec::restart_window`
7065 // (`with = "duration_codec"`) — so the whitespace arm
7066 // applies on serde deserialize for the typed Supervisor slot.
7067 // A `{"restartWindow":" 30s"}` payload that previously round-
7068 // tripped to a different canonical string on next serialize
7069 // is now refused at deserialize with the whitespace-byte
7070 // diagnostic. Peer with `restart_window_serde_rejects_leading_zero`
7071 // / `restart_window_serde_rejects_leading_plus` /
7072 // `restart_window_serde_rejects_fractional_seconds` on the
7073 // same canonical-form-drift axis.
7074 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
7075 "restartWindow":" 30s",
7076 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
7077 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7078 let msg = err.to_string();
7079 assert!(
7080 msg.contains("contains whitespace byte"),
7081 "expected whitespace diagnostic in {msg:?}"
7082 );
7083 assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
7084 }
7085
7086 // ── canonical-form: non-ASCII Unicode `White_Space` duration gate ─────
7087 //
7088 // Successor to the ASCII-whitespace arm (a7ae622) on the shared
7089 // duration codec — closes the strictly-complementary class the
7090 // byte-scan cannot see, through the lifted
7091 // [`crate::render::find_non_ascii_whitespace_char`] predicate.
7092 // Applies to `:supervisor :restart-window`, `:politicas :timeout`,
7093 // and `:politicas :circuit-breaker :window` simultaneously via
7094 // this shared codec.
7095
7096 #[test]
7097 fn duration_codec_parse_rejects_leading_nbsp() {
7098 // NBSP prefix — the strictly-complementary drift class the
7099 // ASCII byte-scan cannot see. `str::trim` strips it silently
7100 // and the value drifts to `"30s"` on next serialize.
7101 let err = duration_codec::parse("\u{00A0}30s").unwrap_err();
7102 assert!(
7103 err.contains("non-ASCII Unicode whitespace character"),
7104 "expected non-ASCII whitespace diagnostic in {err:?}"
7105 );
7106 assert!(err.contains("U+00A0"), "missing codepoint in {err:?}");
7107 }
7108
7109 #[test]
7110 fn duration_codec_parse_rejects_trailing_line_separator() {
7111 // LINE SEPARATOR (`\u{2028}`) trailing — paste-from-web-doc
7112 // footgun.
7113 let err = duration_codec::parse("30s\u{2028}").unwrap_err();
7114 assert!(
7115 err.contains("non-ASCII Unicode whitespace character"),
7116 "expected non-ASCII whitespace diagnostic in {err:?}"
7117 );
7118 assert!(err.contains("U+2028"), "missing codepoint in {err:?}");
7119 }
7120
7121 #[test]
7122 fn duration_codec_parse_accepts_ascii_only_forms_after_unicode_arm() {
7123 // Positive-control pin: every ASCII-only canonical form the
7124 // renderer emits stays accepted through the new arm.
7125 assert_eq!(
7126 duration_codec::parse("30s").unwrap(),
7127 Duration::from_secs(30)
7128 );
7129 assert_eq!(
7130 duration_codec::parse("500ms").unwrap(),
7131 Duration::from_millis(500)
7132 );
7133 assert_eq!(
7134 duration_codec::parse("1h").unwrap(),
7135 Duration::from_secs(3600)
7136 );
7137 }
7138
7139 #[test]
7140 fn restart_window_serde_rejects_non_ascii_whitespace() {
7141 // The shared codec backs `SupervisorSpec::restart_window` — so
7142 // the new non-ASCII Unicode whitespace arm applies on serde
7143 // deserialize for the typed Supervisor slot. A
7144 // `{"restartWindow":" 30s"}` payload that previously
7145 // survived the ASCII byte-scan (only ASCII whitespace was
7146 // refused) is now refused at deserialize with the
7147 // non-ASCII-whitespace-and-codepoint diagnostic.
7148 let payload = "{\"estrategia\":\"OneForOne\",\"maxRestarts\":5,\
7149 \"restartWindow\":\"\u{00A0}30s\",\
7150 \"children\":[{\"caixa\":\"w\",\"versao\":\"^0.1\",\"restart\":\"Permanent\"}]}";
7151 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7152 let msg = err.to_string();
7153 assert!(
7154 msg.contains("non-ASCII Unicode whitespace character"),
7155 "expected non-ASCII whitespace diagnostic in {msg:?}"
7156 );
7157 assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
7158 }
7159
7160 // ── drift-detection: serde-derive-to-SUPERVISOR_KEY_* identity ────────
7161
7162 #[test]
7163 fn supervisor_spec_serde_keys_match_lifted_supervisor_key_consts() {
7164 // Load-bearing invariant: the four `SUPERVISOR_KEY_*` consts
7165 // (`SUPERVISOR_KEY_ESTRATEGIA` / `SUPERVISOR_KEY_MAX_RESTARTS` /
7166 // `SUPERVISOR_KEY_RESTART_WINDOW` / `SUPERVISOR_KEY_CHILDREN`)
7167 // name the exact camelCase JSON keys the
7168 // `#[serde(rename_all = "camelCase")]` attribute on
7169 // `SupervisorSpec` emits. Serialize a fully-populated spec (each
7170 // field carries `Some(_)` / non-empty) and pin that each canonical
7171 // byte-sequence appears verbatim in the JSON — a future accidental
7172 // `rename_all = "snake_case"` / `"kebab-case"` / verbatim-field-
7173 // name flip at the derive attribute (any of which would silently
7174 // break every downstream JSON consumer that reaches for one of the
7175 // four consts via `Value::get(...)`) surfaces here as a build-time
7176 // test failure at `supervisor.rs`, not as an apply-time
7177 // `.get(<stale-canonical-const>)` returning `None` far from the
7178 // derive-attr drift's commit. Peer with the sibling
7179 // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
7180 // (d8b8b4f) pin on the M2 `:limits` axis — same discipline the
7181 // M2 typed-slot family established, extended here to close the
7182 // top-level Supervisor axis.
7183 let spec = SupervisorSpec {
7184 estrategia: RestartStrategy::OneForOne,
7185 max_restarts: 5,
7186 restart_window: Some(Duration::from_secs(60)),
7187 children: vec![ChildSpec {
7188 caixa: "w".into(),
7189 versao: "^0.1".into(),
7190 restart: RestartPolicy::Permanent,
7191 }],
7192 };
7193 let json = serde_json::to_string(&spec).unwrap();
7194 for key in [
7195 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7196 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7197 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7198 crate::render::SUPERVISOR_KEY_CHILDREN,
7199 ] {
7200 let quoted = format!("\"{key}\"");
7201 assert!(
7202 json.contains("ed),
7203 "serialized SupervisorSpec must carry the lifted \
7204 SUPERVISOR_KEY_* byte-sequence {quoted} verbatim in \
7205 the JSON emission (got: {json})",
7206 );
7207 }
7208 }
7209
7210 #[test]
7211 fn supervisor_key_consts_are_pairwise_distinct() {
7212 // Cross-axis drift-detection pin: a future collapse of two
7213 // canonical top-level byte-strings onto the same value (e.g. an
7214 // accidental copy-paste flip of `SUPERVISOR_KEY_CHILDREN` to
7215 // also read `"estrategia"`) would silently reroute every
7216 // downstream probe on one axis onto the sibling axis's overlay
7217 // entry and pass every propagation-probe test that expected only
7218 // the stale axis's value. Peer of the sibling four-way distinct
7219 // pin on the `M2_LIMITS_KEY_*` tetrad (d8b8b4f).
7220 let all = [
7221 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7222 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7223 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7224 crate::render::SUPERVISOR_KEY_CHILDREN,
7225 ];
7226 for (i, a) in all.iter().enumerate() {
7227 for b in all.iter().skip(i + 1) {
7228 assert_ne!(
7229 a, b,
7230 "SUPERVISOR_KEY_* consts must be pairwise-distinct \
7231 canonical byte-sequences — got `{a}` == `{b}`",
7232 );
7233 }
7234 }
7235 }
7236
7237 #[test]
7238 fn supervisor_key_consts_are_lower_camel_case_shape() {
7239 // Shape-pin: every `SUPERVISOR_KEY_*` const must be a
7240 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
7241 // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
7242 // capital, no whitespace / dots) — the canonical shape the
7243 // `#[serde(rename_all = "camelCase")]` derive produces on
7244 // `SupervisorSpec`. A future flip to a non-camelCase attribute
7245 // at the derive surfaces both here (this test fails on the
7246 // stale-constant shape) and at
7247 // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
7248 // (that test fails on the mismatch between const and derive).
7249 // Peer with `m2_limits_key_consts_are_lower_camel_case_shape`
7250 // (d8b8b4f) on the sibling M2 `:limits` axis.
7251 for key in [
7252 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7253 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7254 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7255 crate::render::SUPERVISOR_KEY_CHILDREN,
7256 ] {
7257 assert!(
7258 !key.is_empty(),
7259 "SUPERVISOR_KEY_* must be non-empty (got {key:?})"
7260 );
7261 let first = key.chars().next().unwrap();
7262 assert!(
7263 first.is_ascii_lowercase(),
7264 "SUPERVISOR_KEY_* must lead with an ASCII-lowercase byte \
7265 (got {key:?}, leads with {first:?})",
7266 );
7267 assert!(
7268 key.chars().all(|c| c.is_ascii_alphanumeric()),
7269 "SUPERVISOR_KEY_* must be ASCII-alphanumeric only \
7270 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
7271 );
7272 }
7273 }
7274
7275 #[test]
7276 fn supervisor_key_consts_are_byte_distinct_from_supervisor_author_key_peers() {
7277 // Cross-axis drift pin: the four `SUPERVISOR_KEY_*` consts
7278 // (camelCase JSON keys, no leading colon) must never collide
7279 // byte-for-byte with the four peer `SUPERVISOR_AUTHOR_KEY_*`
7280 // consts (kebab-case author-facing labels with leading colon)
7281 // that sit next to them at `caixa_core::render`. Both families
7282 // cover the same four typed Supervisor slots on two distinct
7283 // axes (author-side kebab vs renderer-side camelCase);
7284 // collapsing either family onto the other's byte-shape would
7285 // silently reroute the render-side probe onto the author-facing
7286 // surface, or vice versa. Peer of the byte-distinctness
7287 // discipline the `M3_PLACEMENT_KEY_ESTRATEGIA` docstring names
7288 // against the peer `M3_AUTHOR_KEY_PLACEMENT`.
7289 let pairs = [
7290 (
7291 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7292 crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA,
7293 ),
7294 (
7295 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7296 crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS,
7297 ),
7298 (
7299 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7300 crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW,
7301 ),
7302 (
7303 crate::render::SUPERVISOR_KEY_CHILDREN,
7304 crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN,
7305 ),
7306 ];
7307 for (json_key, author_key) in pairs {
7308 assert_ne!(
7309 json_key, author_key,
7310 "SUPERVISOR_KEY_* (JSON side) must differ byte-for-byte \
7311 from the peer SUPERVISOR_AUTHOR_KEY_* (author side); \
7312 got JSON `{json_key}` == author `{author_key}`",
7313 );
7314 }
7315 }
7316
7317 // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_KEY_* identity ──
7318
7319 #[test]
7320 fn child_spec_serde_keys_match_lifted_supervisor_child_key_consts() {
7321 // Load-bearing invariant: the three `SUPERVISOR_CHILD_KEY_*` consts
7322 // (`SUPERVISOR_CHILD_KEY_CAIXA` / `SUPERVISOR_CHILD_KEY_VERSAO` /
7323 // `SUPERVISOR_CHILD_KEY_RESTART`) name the exact camelCase JSON
7324 // keys the `#[serde(rename_all = "camelCase")]` attribute on
7325 // `ChildSpec` emits. Serialize a fully-populated `ChildSpec` and
7326 // pin that each canonical byte-sequence appears verbatim in the
7327 // JSON — a future accidental `rename_all = "snake_case"` /
7328 // `"kebab-case"` / verbatim-field-name flip at the derive
7329 // attribute (any of which would silently break every downstream
7330 // JSON consumer that reaches for one of the three consts via
7331 // `Value::get(...)`) surfaces here as a build-time test failure at
7332 // `supervisor.rs`, not as an apply-time
7333 // `.get(<stale-canonical-const>)` returning `None` far from the
7334 // derive-attr drift's commit. Peer with the enclosing
7335 // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
7336 // (40cc4e5) pin on the M2 supervision-tree top-level axis — same
7337 // discipline the SupervisorSpec top-level lift established,
7338 // extended here to the sibling per-`:children` entry `ChildSpec`
7339 // derive so the last M2 typed-struct sub-block
7340 // `#[serde(rename_all = "camelCase")]` axis on the Supervisor
7341 // surface without a lifted serde-key peer joins the substrate's
7342 // "one canonical byte-string per typed serialized-key axis"
7343 // discipline.
7344 let c = ChildSpec {
7345 caixa: "worker".into(),
7346 versao: "^0.1".into(),
7347 restart: RestartPolicy::Permanent,
7348 };
7349 let json = serde_json::to_string(&c).unwrap();
7350 for key in [
7351 crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
7352 crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
7353 crate::render::SUPERVISOR_CHILD_KEY_RESTART,
7354 ] {
7355 let quoted = format!("\"{key}\"");
7356 assert!(
7357 json.contains("ed),
7358 "serialized ChildSpec must carry the lifted \
7359 SUPERVISOR_CHILD_KEY_* byte-sequence {quoted} verbatim \
7360 in the JSON emission (got: {json})",
7361 );
7362 }
7363 }
7364
7365 #[test]
7366 fn supervisor_child_key_consts_are_pairwise_distinct() {
7367 // Cross-axis drift-detection pin: a future collapse of two
7368 // canonical `ChildSpec` per-entry byte-strings onto the same
7369 // value (e.g. an accidental copy-paste flip of
7370 // `SUPERVISOR_CHILD_KEY_RESTART` to also read `"caixa"`) would
7371 // silently reroute every downstream probe on one axis onto the
7372 // sibling axis's overlay entry and pass every propagation-probe
7373 // test that expected only the stale axis's value. Peer of the
7374 // sibling three-way distinct pin on the `CONTRATO_KEY_*` triad
7375 // (ca463a4) and the two-way distinct pin on the `MEMBRO_KEY_*`
7376 // pair (ce80ca0).
7377 let all = [
7378 crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
7379 crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
7380 crate::render::SUPERVISOR_CHILD_KEY_RESTART,
7381 ];
7382 for (i, a) in all.iter().enumerate() {
7383 for b in all.iter().skip(i + 1) {
7384 assert_ne!(
7385 a, b,
7386 "SUPERVISOR_CHILD_KEY_* consts must be pairwise-\
7387 distinct canonical byte-sequences — got `{a}` == `{b}`",
7388 );
7389 }
7390 }
7391 }
7392
7393 #[test]
7394 fn supervisor_child_key_consts_are_lower_camel_case_shape() {
7395 // Shape-pin: every `SUPERVISOR_CHILD_KEY_*` const must be a
7396 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
7397 // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
7398 // capital, no whitespace / dots) — the canonical shape the
7399 // `#[serde(rename_all = "camelCase")]` derive produces on
7400 // `ChildSpec`. A future flip to a non-camelCase attribute at the
7401 // derive surfaces both here (this test fails on the
7402 // stale-constant shape) and at
7403 // `child_spec_serde_keys_match_lifted_supervisor_child_key_consts`
7404 // (that test fails on the mismatch between const and derive).
7405 // Peer with `supervisor_key_consts_are_lower_camel_case_shape`
7406 // (40cc4e5) on the sibling `SupervisorSpec` top-level axis.
7407 for key in [
7408 crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
7409 crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
7410 crate::render::SUPERVISOR_CHILD_KEY_RESTART,
7411 ] {
7412 assert!(
7413 !key.is_empty(),
7414 "SUPERVISOR_CHILD_KEY_* must be non-empty (got {key:?})"
7415 );
7416 let first = key.chars().next().unwrap();
7417 assert!(
7418 first.is_ascii_lowercase(),
7419 "SUPERVISOR_CHILD_KEY_* must lead with an ASCII-lowercase \
7420 byte (got {key:?}, leads with {first:?})",
7421 );
7422 assert!(
7423 key.chars().all(|c| c.is_ascii_alphanumeric()),
7424 "SUPERVISOR_CHILD_KEY_* must be ASCII-alphanumeric only \
7425 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
7426 );
7427 }
7428 }
7429
7430 // ── drift-detection: serde-derive-to-SUPERVISOR_ESTRATEGIA_* identity ────
7431
7432 #[test]
7433 fn restart_strategy_variants_serialize_to_lifted_scalar_values() {
7434 // The fail-before-pass-after pin: pre-lift there was no
7435 // single-source binding between the [`RestartStrategy`] variant
7436 // name the un-`rename`d `Serialize` derive emits under
7437 // [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the byte-string
7438 // every downstream cluster-side dispatcher (the future
7439 // wasm-operator's per-supervisor sibling-restart branch, the
7440 // future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
7441 // admission-time enum-arm bind, the `caixa-operator`'s
7442 // hierarchical reconciliation scheduler's per-strategy fan-out)
7443 // probes verbatim. A future `#[serde(rename_all = "kebab-case")]`
7444 // attribute on the enum — or a per-variant `#[serde(rename = "…")]`
7445 // override, or a variant rename in the source — would silently
7446 // rebrand the emitted scalar under one spelling while every
7447 // downstream dispatcher still probed the other, with the failure
7448 // surfacing at the operator's reconcile posture (subtrees coming
7449 // up under the `default()` `OneForOne` arm rather than the typed
7450 // slot's declared strategy — a bad child would then only take
7451 // itself down instead of the sibling set the author intended, so
7452 // shared-state children fall out of sync) far from the source
7453 // rebrand commit and with no field naming the drift. Pinning the
7454 // two paths (the `Serialize` derive's serialized string AND the
7455 // [`RestartStrategy::as_str`] helper) to the same four lifted
7456 // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
7457 // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
7458 // [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
7459 // [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
7460 // byte-strings makes any future drift on either endpoint fail
7461 // here at caixa-core build time. Peer of the M3
7462 // `placement_strategy_variants_serialize_to_lifted_scalar_values`
7463 // (3f0e21c) on the sibling `PlacementStrategy` axis — same
7464 // three-path-convergence discipline, extended to close the
7465 // OTP-shaped per-supervisor sibling-restart axis.
7466 for (variant, expected) in [
7467 (
7468 RestartStrategy::OneForOne,
7469 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7470 ),
7471 (
7472 RestartStrategy::OneForAll,
7473 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7474 ),
7475 (
7476 RestartStrategy::RestForOne,
7477 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7478 ),
7479 (
7480 RestartStrategy::SimpleOneForOne,
7481 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7482 ),
7483 ] {
7484 let json = serde_json::to_string(&variant).unwrap();
7485 assert_eq!(
7486 json,
7487 format!("\"{expected}\""),
7488 "RestartStrategy::{variant:?} must serialize to {expected:?}"
7489 );
7490 assert_eq!(
7491 variant.as_str(),
7492 expected,
7493 "RestartStrategy::{variant:?}.as_str() must return the lifted \
7494 SUPERVISOR_ESTRATEGIA_* constant"
7495 );
7496 }
7497 }
7498
7499 #[test]
7500 fn supervisor_estrategia_consts_are_pairwise_distinct() {
7501 // Cross-arm drift-detection pin: a future collapse of two
7502 // canonical variant byte-strings onto the same value (e.g. an
7503 // accidental copy-paste flip of `SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`
7504 // to also read `"OneForOne"`) would silently reroute every
7505 // downstream operator's per-strategy dispatch onto the sibling
7506 // arm's reconcile branch and pass every propagation-probe test
7507 // that expected only the stale arm's value — the mis-strategied
7508 // subtree would come up with the wrong sibling-restart posture
7509 // on every subsequent failure. Peer of the sibling four-way
7510 // distinct pin `supervisor_key_consts_are_pairwise_distinct`
7511 // (40cc4e5) on the top-level `SUPERVISOR_KEY_*` axis.
7512 let all = [
7513 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7514 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7515 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7516 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7517 ];
7518 for (i, a) in all.iter().enumerate() {
7519 for (j, b) in all.iter().enumerate() {
7520 if i != j {
7521 assert_ne!(
7522 a, b,
7523 "SUPERVISOR_ESTRATEGIA_* consts must be pairwise distinct \
7524 — got duplicate {a:?} at indices {i} and {j}",
7525 );
7526 }
7527 }
7528 }
7529 }
7530
7531 #[test]
7532 fn restart_strategy_display_routes_through_as_str_helper() {
7533 // The fail-before-pass-after pin on the first half of the
7534 // three-path convergence: pre-convergence the sibling
7535 // OTP-shape typed enum [`RestartStrategy`] carried a
7536 // [`std::fmt::Display`] surface via its
7537 // `#[discriminant(also_display)]` gen-platform derive route,
7538 // which arrived kebab-case as `"one-for-one"` /
7539 // `"one-for-all"` / `"rest-for-one"` /
7540 // `"simple-one-for-one"` while the wire format ran as
7541 // PascalCase `"OneForOne"` / `"OneForAll"` / `"RestForOne"` /
7542 // `"SimpleOneForOne"` through the un-`rename`d serde derive.
7543 // Every consumer reaching for a strategy byte-string past the
7544 // wire format had to pick between three paths
7545 // ([`RestartStrategy::as_str`], the `Serialize` derive's
7546 // serialized string, or `format!("{v}")` on the
7547 // discriminant-Display route), any two of which a future
7548 // variant rename or `#[serde(rename_all = "kebab-case")]`
7549 // attribute would silently desynchronize. Wiring
7550 // [`std::fmt::Display`] through [`RestartStrategy::as_str`]
7551 // closes the third path: every `format!("{v}")` call reaches
7552 // the same lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
7553 // const the wire format and the [`RestartStrategy::as_str`]
7554 // helper already route through, so a future variant rename
7555 // lands at exactly one place. Pin the routing here so a future
7556 // `impl std::fmt::Display for RestartStrategy`
7557 // reimplementation that hand-rolls the arms instead of
7558 // delegating to [`RestartStrategy::as_str`] fails at
7559 // caixa-core build time. Peer of the M3
7560 // `placement_strategy_display_routes_through_as_str_helper`
7561 // (cc8f749) which the M3 axis converged first.
7562 for &variant in RestartStrategy::ALL {
7563 assert_eq!(
7564 variant.to_string(),
7565 variant.as_str(),
7566 "RestartStrategy::{variant:?} Display must route through \
7567 RestartStrategy::as_str (single source of truth: the lifted \
7568 SUPERVISOR_ESTRATEGIA_* const the wire format also emits)"
7569 );
7570 }
7571 }
7572
7573 #[test]
7574 fn restart_strategy_display_matches_serialized_wire_byte_string() {
7575 // The fail-before-pass-after pin on the second half of the
7576 // three-path convergence: `Display` (user-facing text) agrees
7577 // byte-for-byte with the `Serialize` derive's wire format
7578 // (canonical camelCase-schema `SUPERVISOR_KEY_ESTRATEGIA`
7579 // scalar) on every variant. Pre-convergence the two paths
7580 // were structurally independent — a future
7581 // `#[serde(rename_all = "kebab-case")]` attribute on the
7582 // enum would silently rebrand the emitted wire scalar
7583 // (`one-for-one`, `one-for-all`, `rest-for-one`,
7584 // `simple-one-for-one`) while every consumer that
7585 // pretty-prints the strategy (the future wasm-operator's
7586 // per-supervisor sibling-restart-strategy diagnostic line,
7587 // the future `feira app graph` per-supervisor strategy line,
7588 // the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
7589 // materializer's admission-webhook rejection body) would
7590 // still emit the PascalCase form the `as_str` / `Display`
7591 // route returns, with the mismatch surfacing at consumer
7592 // parse time / operator dispatch time far from the source
7593 // rebrand commit. Pin the two paths byte-for-byte here so any
7594 // future serde-attribute or variant-rename drift is a
7595 // caixa-core-build-time test failure at this call, not a
7596 // silent per-consumer dispatch miss. Peer of the M3
7597 // `placement_strategy_display_matches_serialized_wire_byte_string`
7598 // (cc8f749) which the M3 axis converged first.
7599 for &variant in RestartStrategy::ALL {
7600 let wire = serde_json::to_string(&variant).unwrap();
7601 let unquoted = wire
7602 .strip_prefix('"')
7603 .and_then(|s| s.strip_suffix('"'))
7604 .expect("serialized RestartStrategy is a JSON string");
7605 assert_eq!(
7606 variant.to_string(),
7607 unquoted,
7608 "RestartStrategy::{variant:?} Display byte-string must match the \
7609 Serialize derive's wire byte-string (three-path convergence: \
7610 Display + as_str + Serialize all resolve to the same \
7611 SUPERVISOR_ESTRATEGIA_* const)"
7612 );
7613 }
7614 }
7615
7616 #[test]
7617 fn restart_strategy_as_ref_str_routes_through_as_str_accessor() {
7618 // Fail-before-pass-after byte-parity pin on the lifted
7619 // `impl AsRef<str> for RestartStrategy` — asserts the
7620 // standard-library trait impl and the substrate-primitive
7621 // [`RestartStrategy::as_str`] `pub const fn` accessor resolve
7622 // to the same `&str` per instance across the four-arm
7623 // closed set, so any future silent detour that routes the
7624 // impl through a divergent projection (a per-arm inline
7625 // `match self { RestartStrategy::OneForOne => "OneForOne", … }`
7626 // re-inlining that opens a compile-time link to the un-lifted
7627 // arm-literal, a swap onto the kebab-case
7628 // [`gen_platform::Discriminant`] catalog identity that would
7629 // collide the wire axis with the dispatcher-catalog axis) trips
7630 // at caixa-core test time under `PartialEq` rather than at a
7631 // downstream `impl AsRef<str>`-bound consumer's silent split.
7632 // Sweeps every one of the four arms
7633 // [`RestartStrategy::ALL`] carries so no arm's projection is
7634 // covered only by the sibling wire-format `Serialize` derive
7635 // path. Peer of the sibling
7636 // [`crate::version::tests::caixa_version_as_ref_str_routes_through_as_str_accessor`]
7637 // (16d5c7e) `AsRef<str>`-byte-parity pin on the paired
7638 // top-level `:versao` typed newtype — the two pins together
7639 // cover the substrate primitive's `AsRef<str>` projection axis
7640 // on the paired newtype + closed-set-typed-enum surface.
7641 for &variant in RestartStrategy::ALL {
7642 assert_eq!(
7643 <RestartStrategy as AsRef<str>>::as_ref(&variant),
7644 variant.as_str(),
7645 "AsRef<str> impl on RestartStrategy::{variant:?} must \
7646 byte-equal RestartStrategy::as_str on the same instance \
7647 — divergence signals a silent detour off the substrate-\
7648 primitive accessor"
7649 );
7650 }
7651 }
7652
7653 #[test]
7654 fn restart_strategy_as_ref_str_routes_through_display_via_shared_accessor() {
7655 // Fail-before-pass-after byte-parity pin on the three-path
7656 // convergence discipline the M2 sibling-restart primitive now
7657 // carries on the `&str`-projection axis:
7658 // `<RestartStrategy as AsRef<str>>::as_ref(&s)` (the newly
7659 // lifted impl), `format!("{s}")` (the pre-existing
7660 // [`fmt::Display`] impl), and `s.as_str()` (the substrate-
7661 // primitive `pub const fn` accessor both trait impls delegate
7662 // through) must resolve to the same byte-string on every
7663 // instance across the four-arm closed set. Refuses any future
7664 // divergence between the two trait impls (a stray
7665 // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
7666 // rather than delegating through the shared accessor; a
7667 // hypothetical `AsRef<str>` rewrite that inlines a per-arm
7668 // literal cascade) that would silently split the two
7669 // projection paths of the same closed-set typed enum. Mirrors
7670 // the sibling three-path-convergence discipline the peer
7671 // [`crate::CaixaVersion`] typed newtype carries on its
7672 // `AsRef<str>` / `Display` / `as_str` triple
7673 // (version.rs pin
7674 // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
7675 // 16d5c7e).
7676 for &variant in RestartStrategy::ALL {
7677 let via_as_ref: &str = <RestartStrategy as AsRef<str>>::as_ref(&variant);
7678 let via_display: String = format!("{variant}");
7679 let via_accessor: &str = variant.as_str();
7680 assert_eq!(via_as_ref, via_accessor);
7681 assert_eq!(via_display, via_accessor);
7682 assert_eq!(via_as_ref, via_display.as_str());
7683 }
7684 }
7685
7686 #[test]
7687 fn restart_strategy_all_enumerates_every_variant_exactly_once() {
7688 // Fail-before-pass-after pin on the [`RestartStrategy::ALL`]
7689 // exhaustive-iteration surface: every variant appears exactly
7690 // once, and the slice length matches the arm count of the
7691 // closed set. Every consumer that walks the accepted-strategy
7692 // set (a future `feira supervisor --estrategia …` CLI-side
7693 // arg-parse's "did you mean" hint, a future M4 admission-
7694 // webhook's rejection body naming the accepted-`:estrategia`
7695 // list, the [`RestartStrategy::from_wire`] reverse-projection
7696 // consumers that iterate the accept-set for diagnostic
7697 // rendering) reads through this slice, so a future arm addition
7698 // that grows the enum but forgets to grow [`Self::ALL`]
7699 // silently truncates every downstream consumer's accept-set at
7700 // the same pre-addition boundary — this pin fails at caixa-core
7701 // build time on the pairwise-distinct + arm-count invariants.
7702 //
7703 // Peer of the sibling [`crate::CaixaKind::ALL`] (6b1f4fb) /
7704 // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
7705 // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
7706 // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
7707 // pins on the peer closed-set typed-enum axes.
7708 let all: &[RestartStrategy] = RestartStrategy::ALL;
7709 assert_eq!(
7710 all.len(),
7711 4,
7712 "RestartStrategy::ALL must enumerate every variant of the \
7713 four-arm closed set (OneForOne, OneForAll, RestForOne, \
7714 SimpleOneForOne); got {all:?}"
7715 );
7716 for (i, a) in all.iter().enumerate() {
7717 for (j, b) in all.iter().enumerate() {
7718 if i != j {
7719 assert_ne!(
7720 a, b,
7721 "RestartStrategy::ALL must carry every variant exactly \
7722 once — got duplicate {a:?} at indices {i} and {j}"
7723 );
7724 }
7725 }
7726 }
7727 for variant in [
7728 RestartStrategy::OneForOne,
7729 RestartStrategy::OneForAll,
7730 RestartStrategy::RestForOne,
7731 RestartStrategy::SimpleOneForOne,
7732 ] {
7733 assert!(
7734 all.contains(&variant),
7735 "RestartStrategy::ALL must contain {variant:?} — a future arm \
7736 addition that grows the enum but forgets to grow the ALL slice \
7737 silently truncates every downstream consumer's accept-set at \
7738 the pre-addition boundary"
7739 );
7740 }
7741 }
7742
7743 #[test]
7744 fn restart_strategy_from_wire_accepts_every_lifted_constant() {
7745 // Fail-before-pass-after pin on the forward accept-set of the
7746 // [`RestartStrategy::from_wire`] reverse projection: every
7747 // canonical [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
7748 // constant the [`RestartStrategy::as_str`] emitter walks parses
7749 // back to its paired variant. Any future arm addition that
7750 // grows the emitter's `as_str` match but forgets to grow the
7751 // parser's `from_wire` match silently splits the two halves of
7752 // the round-trip — the wire byte-string one non-serde consumer
7753 // parses from the one the emitter wrote — with the failure
7754 // surfacing at parse time far from the rebrand commit. Pinning
7755 // the four-arm accept-set here catches the drift at caixa-core
7756 // build time.
7757 //
7758 // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
7759 // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
7760 // accept-set pins on the peer closed-set typed-enum `str → Self`
7761 // axes.
7762 for (wire, expected) in [
7763 (
7764 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7765 RestartStrategy::OneForOne,
7766 ),
7767 (
7768 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7769 RestartStrategy::OneForAll,
7770 ),
7771 (
7772 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7773 RestartStrategy::RestForOne,
7774 ),
7775 (
7776 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7777 RestartStrategy::SimpleOneForOne,
7778 ),
7779 ] {
7780 let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
7781 panic!(
7782 "RestartStrategy::from_wire({wire:?}) must accept every \
7783 SUPERVISOR_ESTRATEGIA_* constant — got None for the \
7784 lifted canonical byte-string that RestartStrategy::{expected:?} \
7785 serializes as under SUPERVISOR_KEY_ESTRATEGIA"
7786 )
7787 });
7788 assert_eq!(
7789 parsed, expected,
7790 "RestartStrategy::from_wire({wire:?}) must return \
7791 RestartStrategy::{expected:?}; got RestartStrategy::{parsed:?}"
7792 );
7793 }
7794 }
7795
7796 #[test]
7797 fn restart_strategy_from_wire_round_trips_through_as_str() {
7798 // Fail-before-pass-after pin on the closed round-trip between
7799 // the forward [`RestartStrategy::as_str`] emitter and the
7800 // reverse [`RestartStrategy::from_wire`] parser: for every
7801 // variant in [`RestartStrategy::ALL`], parsing the emitter's
7802 // output must return exactly the same variant. Any per-arm
7803 // divergence — a future arm added to `as_str` but not
7804 // `from_wire`, an accidental copy-paste flip in one but not
7805 // the other — silently splits the emit and parse halves and
7806 // the failure surfaces at consumer parse time far from the
7807 // drift site. The `ALL`-iterating shape means a future arm
7808 // addition picks up the coverage by construction.
7809 //
7810 // Peer of the sibling
7811 // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
7812 // (18c7342) round-trip pin on
7813 // [`crate::aplicacao::PlacementStrategy::from_wire`] and
7814 // [`crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`]
7815 // (6b1f4fb) round-trip pin on [`crate::CaixaKind::from_wire`].
7816 for &variant in RestartStrategy::ALL {
7817 let wire = variant.as_str();
7818 let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
7819 panic!(
7820 "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
7821 must be Some({variant:?}) — the two halves of the round-trip \
7822 dispatch on the same lifted SUPERVISOR_ESTRATEGIA_* consts; \
7823 got None on wire byte-string {wire:?}"
7824 )
7825 });
7826 assert_eq!(
7827 parsed, variant,
7828 "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
7829 must round-trip to the same variant; got {parsed:?}"
7830 );
7831 }
7832 }
7833
7834 #[test]
7835 fn restart_strategy_from_wire_rejects_unknown_byte_strings() {
7836 // Fail-before-pass-after pin on the closed-set refusal
7837 // discipline of [`RestartStrategy::from_wire`]: every
7838 // byte-string outside the four-arm accept-set returns `None`
7839 // rather than silently collapsing onto the [`Default`]
7840 // (`OneForOne`) arm or an arbitrary neighbor. The refusal set
7841 // exercised here sweeps the load-bearing drift shapes: the
7842 // empty string (a stripped serde-attribute drift), all-
7843 // whitespace strings (the canonical text-editor accidental
7844 // padding shape), the kebab-case dispatcher-catalog identities
7845 // (`"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
7846 // `"simple-one-for-one"` — the [`gen_platform::FromStrKind`]-
7847 // derived [`std::str::FromStr`] accept-set, which parses the
7848 // *other* axis of this enum's two-axis split and must not leak
7849 // into the `from_wire` PascalCase-wire accept-set), the
7850 // lowercased single-word forms (`"oneforone"`), the padded
7851 // canonical scalar (`" OneForOne "`), the trailing-newline
7852 // shapes (`"OneForOne\n"`), and neighboring-but-unknown arms
7853 // (`"AllForOne"` — the canonical typo direction).
7854 //
7855 // Peer of the sibling
7856 // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
7857 // (2aa6d23) +
7858 // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
7859 // (18c7342) refusal pins on the peer closed-set typed-enum
7860 // axes.
7861 for bad in [
7862 "",
7863 " ",
7864 "\n",
7865 "\t",
7866 "one-for-one",
7867 "one-for-all",
7868 "rest-for-one",
7869 "simple-one-for-one",
7870 "oneforone",
7871 "OneForOnes",
7872 "one_for_one",
7873 "one for one",
7874 "ONEFORONE",
7875 "OneForOne ",
7876 " OneForOne",
7877 " SimpleOneForOne ",
7878 "OneForOne\n",
7879 "restforone",
7880 "REST_FOR_ONE",
7881 "AllForOne",
7882 "Simple",
7883 "?",
7884 ] {
7885 assert!(
7886 RestartStrategy::from_wire(bad).is_none(),
7887 "RestartStrategy::from_wire({bad:?}) must return None — the \
7888 parser's accept-set is exactly the four RestartStrategy::as_str \
7889 outputs (OneForOne, OneForAll, RestForOne, SimpleOneForOne), \
7890 and this byte-string is outside that closed set"
7891 );
7892 }
7893 }
7894
7895 #[test]
7896 fn restart_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
7897 // Fail-before-pass-after pin on the fourth path of the four-path
7898 // convergence: `from_wire` (the reverse projection) inverts the
7899 // `Serialize` derive's wire byte-string on every variant.
7900 // Together with the pre-existing three-path convergence
7901 // (`Display` + `as_str` + `Serialize` all resolve to the same
7902 // lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const,
7903 // pinned by
7904 // [`restart_strategy_display_matches_serialized_wire_byte_string`])
7905 // this closes the round-trip: the wire byte-string the
7906 // `Serialize` derive emits parses back to the same variant
7907 // through `from_wire`, so any future serde-attribute or variant-
7908 // rename drift on the emit half now surfaces as a matched drift
7909 // on the parse half at caixa-core build time — the two halves
7910 // migrate as a unit through the lifted consts on any future
7911 // rename, and the round-trip cannot silently split.
7912 //
7913 // Peer of the sibling
7914 // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
7915 // (18c7342) wire-format pin on
7916 // [`crate::aplicacao::PlacementStrategy::from_wire`].
7917 for &variant in RestartStrategy::ALL {
7918 let wire = serde_json::to_string(&variant).unwrap();
7919 let unquoted = wire
7920 .strip_prefix('"')
7921 .and_then(|s| s.strip_suffix('"'))
7922 .expect("serialized RestartStrategy is a JSON string");
7923 let parsed = RestartStrategy::from_wire(unquoted).unwrap_or_else(|| {
7924 panic!(
7925 "RestartStrategy::from_wire({unquoted:?}) must accept the \
7926 Serialize derive's wire byte-string for \
7927 RestartStrategy::{variant:?} — the four-path convergence \
7928 (Display + as_str + Serialize + from_wire) resolves through \
7929 the same lifted SUPERVISOR_ESTRATEGIA_* const; got None"
7930 )
7931 });
7932 assert_eq!(
7933 parsed, variant,
7934 "RestartStrategy::from_wire of the Serialize derive's wire \
7935 byte-string for RestartStrategy::{variant:?} must round-trip \
7936 to the same variant; got {parsed:?}"
7937 );
7938 }
7939 }
7940
7941 #[test]
7942 fn restart_strategy_try_from_str_routes_through_from_wire_accessor() {
7943 // Fail-before-pass-after byte-parity pin on the newly lifted
7944 // `impl TryFrom<&str> for RestartStrategy` — asserts the standard-
7945 // library trait impl and the substrate-primitive
7946 // [`RestartStrategy::from_wire`] `Option<Self>` accessor resolve to
7947 // the same four-arm accept-set across every arm the exhaustive
7948 // [`RestartStrategy::ALL`] slice enumerates. Any future silent
7949 // detour that routes the trait impl through a divergent projection
7950 // (a per-arm inline `match s { "OneForOne" => Ok(Self::OneForOne),
7951 // … }` re-inlining that opens a compile-time link to the un-
7952 // lifted arm-literal, a hypothetical `#[serde(rename_all = "…")]`
7953 // attribute drift that silently splits the wire byte-string from
7954 // every consumer that reaches for this typed dispatch, an
7955 // accidental swap onto the kebab-case dispatcher-catalog axis the
7956 // pre-existing [`std::str::FromStr`] impl parses through and which
7957 // would collide the two-axis wire/catalog split the sibling
7958 // [`RestartStrategy::from_wire`] doc block makes load-bearing)
7959 // trips at caixa-core test time under `assert_eq!` rather than at
7960 // a downstream `impl TryFrom<&str>`-bound consumer's silent split.
7961 // Sweeps every one of the four arms [`RestartStrategy::ALL`]
7962 // carries so no arm's projection is covered only by the sibling
7963 // method-named `from_wire` path. Peer of the sibling
7964 // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
7965 // (3c83606),
7966 // [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
7967 // (bf33136), and the M3
7968 // [`crate::aplicacao::tests::placement_strategy_try_from_str_routes_through_from_wire_accessor`]
7969 // (6fd00cd) — extends the trait-idiomatic reverse-projection axis
7970 // onto the first M2-OTP-shape closed-set typed enum on the caixa
7971 // surface.
7972 for &variant in RestartStrategy::ALL {
7973 let wire = variant.as_str();
7974 assert_eq!(
7975 <RestartStrategy as TryFrom<&str>>::try_from(wire),
7976 Ok(variant),
7977 "TryFrom<&str> impl on RestartStrategy must round-trip \
7978 RestartStrategy::{variant:?}.as_str() = {wire:?} back to \
7979 Ok(RestartStrategy::{variant:?}) — divergence from \
7980 RestartStrategy::from_wire signals a silent detour off \
7981 the substrate-primitive accessor"
7982 );
7983 assert_eq!(
7984 <RestartStrategy as TryFrom<&str>>::try_from(wire).ok(),
7985 RestartStrategy::from_wire(wire),
7986 "TryFrom<&str> ok()-projection on {wire:?} must byte-equal \
7987 RestartStrategy::from_wire on the same input"
7988 );
7989 }
7990 }
7991
7992 #[test]
7993 fn restart_strategy_try_from_str_rejects_unknown_byte_strings() {
7994 // Rejection witness on the `impl TryFrom<&str> for
7995 // RestartStrategy` — sweeps a candidate set of byte-strings
7996 // outside the four-arm PascalCase wire accept-set the sibling
7997 // [`RestartStrategy::as_str`] emits and asserts every one lands on
7998 // `Err(())`, so a future accidental widening of the trait impl's
7999 // accept-set (a stray additional
8000 // `_ if s.eq_ignore_ascii_case("OneForOne") => Ok(…)` case-fold
8001 // path, a silent inclusion of the kebab-case dispatcher-catalog
8002 // byte-string the pre-existing [`std::str::FromStr`] impl the
8003 // [`gen_platform::FromStrKind`] derive installs parses onto the
8004 // wire axis — which would collide the two-axis
8005 // wire/dispatcher-catalog split the sibling
8006 // [`RestartStrategy::from_wire`] doc block makes load-bearing —
8007 // an English-rebrand or plural-arm silent alias that would
8008 // widen the wire accept-set past the OTP-canonical four) trips at
8009 // caixa-core test time. The candidate set includes the empty
8010 // string, whitespace-only padding, the kebab-case dispatcher-
8011 // catalog byte-strings on the sibling axis (a caller who confuses
8012 // the two axes trips here rather than at a downstream consumer's
8013 // silent reject), a lowercase / uppercase / mixed-case fold of
8014 // each PascalCase arm (a caller who assumes case-fold acceptance
8015 // trips here), leading/trailing whitespace padding, the trailing-
8016 // newline shape, quote-wrapped candidates, and a residual set of
8017 // plausible-but-wrong English rebrand candidates. Peer of the
8018 // sibling
8019 // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
8020 // (3c83606) and
8021 // [`crate::aplicacao::tests::placement_strategy_try_from_str_rejects_unknown_byte_strings`]
8022 // (6fd00cd) rejection witnesses.
8023 let rejected: &[&str] = &[
8024 "",
8025 " ",
8026 "\n",
8027 "\t",
8028 "one-for-one",
8029 "one-for-all",
8030 "rest-for-one",
8031 "simple-one-for-one",
8032 "oneforone",
8033 "one_for_one",
8034 "OneForOnes",
8035 "ONEFORONE",
8036 "oneforall",
8037 "restforone",
8038 "simpleoneforone",
8039 "OneForOne ",
8040 " OneForOne",
8041 " OneForAll ",
8042 "OneForOne\n",
8043 "RestForOne\t",
8044 "OneForEach",
8045 "AllForOne",
8046 "one for one",
8047 "\"OneForOne\"",
8048 "?",
8049 ];
8050 for &input in rejected {
8051 assert_eq!(
8052 <RestartStrategy as TryFrom<&str>>::try_from(input),
8053 Err(()),
8054 "TryFrom<&str> impl on RestartStrategy must reject the \
8055 non-wire byte-string {input:?} — silent acceptance signals \
8056 an accept-set widening off the paired \
8057 RestartStrategy::from_wire resolver"
8058 );
8059 }
8060 }
8061
8062 #[test]
8063 fn restart_strategy_try_from_str_and_from_wire_partition_the_accept_set() {
8064 // Cross-axis partition pin: the paired `TryFrom<&str>` and
8065 // `from_wire` reverse projections must resolve identically on
8066 // *every* input, not just the ones [`RestartStrategy::ALL`]
8067 // enumerates. Sweeps a mixed candidate set spanning accepted
8068 // (four-arm PascalCase wire byte-strings) and rejected (kebab-case
8069 // dispatcher-catalog byte-strings, empty, whitespace-padded,
8070 // quoted, English-rebrand candidates) inputs and asserts the
8071 // trait's `Result::ok()` projection byte-equals the method-named
8072 // resolver's `Option<Self>` return-shape on each, locking the two
8073 // paths together by construction so any future detour (a stray
8074 // `try_from` special-case that widens or narrows the accept-set
8075 // outside the paired `from_wire` resolver, an accidental swap
8076 // onto the kebab-case [`std::str::FromStr`] impl the
8077 // [`gen_platform::FromStrKind`] derive installs on the sibling
8078 // dispatcher-catalog axis) trips at caixa-core test time. Peer of
8079 // the sibling
8080 // [`crate::kind::tests::caixa_kind_try_from_str_and_from_wire_partition_the_accept_set`]
8081 // pin — extends the round-trip discipline onto the M2-OTP-shape
8082 // sibling-restart axis.
8083 let candidates: &[&str] = &[
8084 "OneForOne",
8085 "OneForAll",
8086 "RestForOne",
8087 "SimpleOneForOne",
8088 "",
8089 "one-for-one",
8090 "one-for-all",
8091 "rest-for-one",
8092 "simple-one-for-one",
8093 "oneforone",
8094 "unknown",
8095 "OneForOne ",
8096 " OneForOne",
8097 "\"OneForOne\"",
8098 "OneForEach",
8099 "?",
8100 ];
8101 for &input in candidates {
8102 let via_trait: Option<RestartStrategy> =
8103 <RestartStrategy as TryFrom<&str>>::try_from(input).ok();
8104 let via_method: Option<RestartStrategy> = RestartStrategy::from_wire(input);
8105 assert_eq!(
8106 via_trait, via_method,
8107 "TryFrom<&str> and from_wire must resolve identically on \
8108 input {input:?} — divergence signals the two reverse-\
8109 projection paths have drifted onto different accept-sets"
8110 );
8111 }
8112 }
8113
8114 #[test]
8115 fn restart_strategy_from_into_static_str_routes_through_as_str_accessor() {
8116 // Fail-before-pass-after byte-parity pin on the newly lifted
8117 // `impl From<RestartStrategy> for &'static str` — asserts the
8118 // standard-library trait impl and the substrate-primitive
8119 // [`RestartStrategy::as_str`] `pub const fn` accessor resolve to
8120 // the same four-arm emit-set across every arm the exhaustive
8121 // [`RestartStrategy::ALL`] slice enumerates. Any future silent
8122 // detour that routes the trait impl through a divergent
8123 // projection (a per-arm inline `match strategy { OneForOne =>
8124 // "OneForOne", … }` re-inlining that opens a compile-time link to
8125 // the un-lifted arm-literal, an accidental swap onto the sibling
8126 // kebab-case [`Self::discriminant`] dispatcher-catalog axis that
8127 // would collide the two-axis wire/catalog split the sibling
8128 // [`RestartStrategy::from_wire`] doc block makes load-bearing) trips
8129 // at caixa-core test time under `assert_eq!` rather than at a
8130 // downstream `impl Into<&'static str>`-bound consumer's silent
8131 // split. Sweeps every one of the four arms
8132 // [`RestartStrategy::ALL`] carries so no arm's projection is
8133 // covered only by the sibling method-named `as_str` /
8134 // [`std::fmt::Display`] / [`AsRef<str>`] paths. Materializes the
8135 // `<&'static str as From<RestartStrategy>>::from` output in a
8136 // `const`-shape binding to make the `'static` lifetime promise a
8137 // build-time invariant — a future accidental downgrade of any of
8138 // the four arms' [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
8139 // constants to a non-`&'static str` (a `String::leak()`-produced
8140 // return, a `Box::leak`-cast) trips at caixa-core build time
8141 // rather than at a downstream `'static`-bound consumer.
8142 const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
8143 const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
8144 const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
8145 const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
8146 for &variant in RestartStrategy::ALL {
8147 let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8148 let via_method: &'static str = variant.as_str();
8149 assert_eq!(
8150 via_trait, via_method,
8151 "From<RestartStrategy> for &'static str impl must round-trip \
8152 RestartStrategy::{variant:?} to the same lifted \
8153 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str returns — \
8154 divergence signals a silent detour off the substrate-primitive \
8155 accessor"
8156 );
8157 let via_into: &'static str = variant.into();
8158 assert_eq!(
8159 via_into, via_method,
8160 "Into<&'static str>::into on RestartStrategy::{variant:?} must \
8161 byte-equal RestartStrategy::as_str on the same input — the \
8162 blanket-derived Into shape must resolve to the same as_str \
8163 dispatch as the explicit From impl"
8164 );
8165 }
8166 assert_eq!(
8167 [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
8168 [
8169 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8170 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8171 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8172 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8173 ],
8174 "const-context RestartStrategy::as_str must resolve to the four \
8175 lifted SUPERVISOR_ESTRATEGIA_* consts — a future accidental \
8176 downgrade of any arm to a non-const or non-static byte-string \
8177 breaks the `&'static str`-lifetime promise the paired \
8178 From<RestartStrategy> for &'static str impl carries by \
8179 construction"
8180 );
8181 }
8182
8183 #[test]
8184 fn restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set() {
8185 // Cross-axis partition pin: the paired trait-idiomatic
8186 // `From<RestartStrategy> for &'static str` forward projection and
8187 // the method-named [`RestartStrategy::as_str`] forward projection
8188 // must resolve identically on *every* arm, not just the ones
8189 // named in the primary byte-parity pin above. Sweeps every
8190 // [`RestartStrategy::ALL`] arm and asserts the trait's `From::from`
8191 // output byte-equals the method-named accessor's return-value on
8192 // each, locking the two forward-projection paths together by
8193 // construction so any future detour (a stray `From` special-case
8194 // that lands on a divergent per-arm literal outside the paired
8195 // `as_str` dispatch, a hypothetical rebrand touching one axis
8196 // without the other) trips at caixa-core test time. Peer of the
8197 // sibling reverse-projection partition pin
8198 // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
8199 // — extends the round-trip discipline onto the trait-idiomatic
8200 // *forward* axis, closing the two-way `Self ↔ &'static str`
8201 // round-trip on the trait-idiomatic pair
8202 // (`From<Self> for &'static str` + `TryFrom<&str> for Self`) as
8203 // well as the pre-existing method-named pair
8204 // (`as_str` + `from_wire`).
8205 for &variant in RestartStrategy::ALL {
8206 let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8207 let via_method: &'static str = variant.as_str();
8208 assert_eq!(
8209 via_trait, via_method,
8210 "From<RestartStrategy> for &'static str and \
8211 RestartStrategy::as_str must resolve identically on \
8212 RestartStrategy::{variant:?} — divergence signals the \
8213 two forward-projection paths have drifted onto different \
8214 emit-sets"
8215 );
8216 }
8217 // Round-trip witness: every arm's forward `From` output re-parses
8218 // through the paired trait-idiomatic reverse `TryFrom<&str>` back
8219 // to the original variant. Closes the two-way `RestartStrategy ↔
8220 // &'static str` round-trip on the trait-idiomatic axis pair,
8221 // mirroring the pre-existing method-named `as_str` + `from_wire`
8222 // round-trip on the substrate-primitive axis pair.
8223 for &variant in RestartStrategy::ALL {
8224 let emitted: &'static str = variant.into();
8225 let re_parsed: Result<RestartStrategy, ()> =
8226 <RestartStrategy as TryFrom<&str>>::try_from(emitted);
8227 assert_eq!(
8228 re_parsed,
8229 Ok(variant),
8230 "trait-idiomatic axis pair must round-trip \
8231 RestartStrategy::{variant:?} through `.into::<&'static \
8232 str>()` and back through `TryFrom<&str>` — a break signals \
8233 the forward-emit and reverse-parse axes have drifted onto \
8234 different vocabularies"
8235 );
8236 }
8237 }
8238
8239 #[test]
8240 fn restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
8241 // Fail-before-pass-after byte-parity pin on the newly lifted
8242 // `impl From<&RestartStrategy> for &'static str` — asserts the
8243 // borrowed-input standard-library trait impl and the substrate-
8244 // primitive [`RestartStrategy::as_str`] `pub const fn` accessor
8245 // resolve to the same four-arm emit-set across every arm the
8246 // exhaustive [`RestartStrategy::ALL`] slice enumerates. Rust's
8247 // `From` trait does not auto-derive the borrowed-input sibling
8248 // from a paired owned-input impl (no `impl<T, U> From<&T> for U
8249 // where T: Copy, U: From<T>` blanket in `core`), so the
8250 // borrowed-input axis is a distinct trait-idiomatic surface
8251 // that a `.iter().map(Into::into)` shape over
8252 // [`RestartStrategy::ALL`] (whose iterator yields
8253 // `&RestartStrategy`, not `RestartStrategy`) reaches through
8254 // this impl and no other — the paired owned-input
8255 // [`From<RestartStrategy>`] impl requires an explicit
8256 // `.copied()` / dereference before the trait fires.
8257 // Materializes the `<&'static str as
8258 // From<&RestartStrategy>>::from` output in a `const`-shape
8259 // binding to make the `'static` lifetime promise a build-time
8260 // invariant.
8261 const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
8262 const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
8263 const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
8264 const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
8265 for variant in RestartStrategy::ALL {
8266 let via_trait: &'static str = <&'static str as From<&RestartStrategy>>::from(variant);
8267 let via_method: &'static str = variant.as_str();
8268 assert_eq!(
8269 via_trait, via_method,
8270 "From<&RestartStrategy> for &'static str impl must \
8271 round-trip &RestartStrategy::{variant:?} to the same \
8272 lifted SUPERVISOR_ESTRATEGIA_* const \
8273 RestartStrategy::as_str returns — divergence signals a \
8274 silent detour off the substrate-primitive accessor"
8275 );
8276 let via_into: &'static str = variant.into();
8277 assert_eq!(
8278 via_into, via_method,
8279 "Into<&'static str>::into on &RestartStrategy::{variant:?} \
8280 must byte-equal RestartStrategy::as_str on the same input — \
8281 the blanket-derived Into shape must resolve to the same \
8282 as_str dispatch as the explicit From impl"
8283 );
8284 }
8285 assert_eq!(
8286 [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
8287 [
8288 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8289 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8290 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8291 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8292 ],
8293 "const-context RestartStrategy::as_str must resolve to the \
8294 four lifted SUPERVISOR_ESTRATEGIA_* consts — the borrowed-\
8295 input From<&RestartStrategy> for &'static str impl inherits \
8296 its `'static` lifetime promise from the same accessor the \
8297 owned-input sibling routes through"
8298 );
8299 }
8300
8301 #[test]
8302 fn restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
8303 // Cross-axis partition pin: the paired trait-idiomatic
8304 // owned-input `From<RestartStrategy> for &'static str` (523157d
8305 // campaign-shape) and borrowed-input `From<&RestartStrategy> for
8306 // &'static str` (this lift) forward projections must resolve
8307 // identically on every arm, locking the two input-shape paths
8308 // together so any future detour trips at caixa-core test time.
8309 // Then a witness that a `.iter().map(Into::into)` pipe over
8310 // [`RestartStrategy::ALL`] (whose iterator yields
8311 // `&RestartStrategy`) materializes the four-arm accept-set
8312 // through the borrowed-input axis alone — the exact shape a
8313 // future wasm-operator per-supervisor sibling-restart-strategy
8314 // diagnostic line, a future substrate-wide per-arm diagnostic
8315 // column, or a
8316 // `HashMap::<&'static str, RestartStrategy>::from_iter(
8317 // RestartStrategy::ALL.iter().map(|s| (s.into(), *s)))`-style
8318 // per-strategy lookup reaches through — closing the two-way
8319 // owned/borrowed input-shape symmetry on the forward-projection
8320 // trait-idiomatic axis. Peer of the sibling
8321 // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8322 // (64aa742) /
8323 // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8324 // (5ab993a) /
8325 // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8326 // (807b0b5) partition pins on the sibling closed-set typed-enum
8327 // discriminator axes — extends the borrowed-input axis
8328 // discipline onto the first M2 OTP-shape sibling-restart
8329 // closed-set typed enum on the caixa surface. Also closes the
8330 // direct two-way `&Self → &'static str → Self` round-trip via
8331 // the paired [`TryFrom<&str>`] axis — unlike the peer
8332 // [`crate::CaixaKind`] axis pair (whose forward `From` emits
8333 // lowercase Portuguese diagnostic bytes while the reverse
8334 // `TryFrom` parses `PascalCase` wire bytes, forcing the round-
8335 // trip through an intermediate wire-vocab hop), the
8336 // [`RestartStrategy::as_str`] emit and
8337 // [`RestartStrategy::from_wire`] parse share the same
8338 // `PascalCase` vocabulary by construction, so the borrowed-
8339 // input forward axis and the reverse axis compose directly.
8340 for &variant in RestartStrategy::ALL {
8341 let owned: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8342 let borrowed: &'static str = <&'static str as From<&RestartStrategy>>::from(&variant);
8343 assert_eq!(
8344 owned, borrowed,
8345 "From<RestartStrategy> and From<&RestartStrategy> for \
8346 &'static str must resolve identically on \
8347 RestartStrategy::{variant:?} — divergence signals the \
8348 owned-input and borrowed-input forward-projection paths \
8349 have drifted onto different emit-sets"
8350 );
8351 }
8352 let via_iter: Vec<&'static str> = RestartStrategy::ALL.iter().map(Into::into).collect();
8353 let via_method: Vec<&'static str> =
8354 RestartStrategy::ALL.iter().map(|s| s.as_str()).collect();
8355 assert_eq!(
8356 via_iter, via_method,
8357 "`.iter().map(Into::into)` over RestartStrategy::ALL must \
8358 byte-equal `.iter().map(|s| s.as_str())` on every arm — the \
8359 borrowed-input `From<&RestartStrategy> for &'static str` \
8360 axis is what makes the `.iter().map(Into::into)` shape route \
8361 through the substrate-primitive `RestartStrategy::as_str` \
8362 accessor rather than through a per-call-site `.copied()` / \
8363 dereference detour"
8364 );
8365 for variant in RestartStrategy::ALL {
8366 let emitted: &'static str = variant.into();
8367 let re_parsed: Result<RestartStrategy, ()> =
8368 <RestartStrategy as TryFrom<&str>>::try_from(emitted);
8369 assert_eq!(
8370 re_parsed,
8371 Ok(*variant),
8372 "trait-idiomatic borrowed-input forward-projection + \
8373 reverse-projection axis pair must round-trip \
8374 &RestartStrategy::{variant:?} through `.into::<&'static \
8375 str>()` (via the borrowed-input axis) and back through \
8376 `TryFrom<&str>` — a break signals the borrowed-input \
8377 forward-emit and reverse-parse axes have drifted onto \
8378 different vocabularies"
8379 );
8380 }
8381 }
8382
8383 #[test]
8384 fn restart_strategy_from_into_owned_string_routes_through_as_str_accessor() {
8385 // Fail-before-pass-after byte-parity pin on the newly lifted
8386 // `impl From<RestartStrategy> for String` — asserts the
8387 // owned-`String`-returning standard-library trait impl and the
8388 // substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
8389 // accessor resolve to the same four-arm emit-set across every
8390 // arm the exhaustive [`RestartStrategy::ALL`] slice enumerates.
8391 // Rust's standard library does not carry a blanket
8392 // `impl<T: AsRef<str>> From<T> for String` (nor an
8393 // `impl<T: fmt::Display> From<T> for String`), so the
8394 // owned-`String` forward-projection axis is a distinct
8395 // trait-idiomatic surface that a
8396 // `let key: String = strategy.into();`-shaped call site
8397 // reaches through this impl and no other — the paired sibling
8398 // `From<RestartStrategy> for &'static str` impl forces every
8399 // owned-`String` call site through an explicit
8400 // `.to_owned()` / `String::from` restatement.
8401 for &variant in RestartStrategy::ALL {
8402 let via_trait: String = <String as From<RestartStrategy>>::from(variant);
8403 let via_method: &'static str = variant.as_str();
8404 assert_eq!(
8405 via_trait.as_str(),
8406 via_method,
8407 "From<RestartStrategy> for String impl must round-trip \
8408 RestartStrategy::{variant:?} to the same lifted \
8409 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
8410 returns — divergence signals a silent detour off the \
8411 substrate-primitive accessor"
8412 );
8413 let via_into: String = variant.into();
8414 assert_eq!(
8415 via_into.as_str(),
8416 via_method,
8417 "Into<String>::into on RestartStrategy::{variant:?} must \
8418 byte-equal RestartStrategy::as_str on the same input — the \
8419 blanket-derived Into shape must resolve to the same as_str \
8420 dispatch as the explicit From impl"
8421 );
8422 }
8423 }
8424
8425 #[test]
8426 fn restart_strategy_from_into_owned_string_and_static_str_agree_on_every_arm() {
8427 // Cross-axis partition pin: the paired trait-idiomatic
8428 // owned-`String` `From<RestartStrategy> for String` (this lift)
8429 // and owned-`&'static str` `From<RestartStrategy> for &'static
8430 // str` (523157d) forward projections must resolve identically
8431 // on every arm, locking the two return-type-shape paths
8432 // together so any future detour trips at caixa-core test time.
8433 // Also byte-parity witness against the sibling
8434 // [`ToString::to_string`] surface routed through
8435 // [`std::fmt::Display`] — the three owned-heap-string paths
8436 // (`.into::<String>()`, `String::from`, `.to_string()`) must
8437 // resolve identically on every arm so a future consumer that
8438 // picks any of the three lands on the same lifted
8439 // SUPERVISOR_ESTRATEGIA_* const. Then a direct round-trip
8440 // witness through the paired trait-idiomatic reverse
8441 // [`TryFrom<&str>`] axis on the owned-`String`'s
8442 // [`String::as_str`] borrow that closes the two-way
8443 // `Self → String → Self` round-trip on the trait-idiomatic
8444 // owned-`String` forward + reverse axis pair.
8445 for &variant in RestartStrategy::ALL {
8446 let owned_string: String = <String as From<RestartStrategy>>::from(variant);
8447 let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8448 assert_eq!(
8449 owned_string.as_str(),
8450 owned_static,
8451 "From<RestartStrategy> for String and From<RestartStrategy> \
8452 for &'static str must resolve identically on \
8453 RestartStrategy::{variant:?} — divergence signals the \
8454 owned-`String` and owned-`&'static str` forward-projection \
8455 return-type-shape paths have drifted onto different \
8456 emit-sets"
8457 );
8458 let via_to_string: String = variant.to_string();
8459 assert_eq!(
8460 owned_string, via_to_string,
8461 "From<RestartStrategy> for String must byte-equal \
8462 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
8463 divergence signals the trait-idiomatic owned-`String` \
8464 forward-projection axis and the ToString-through-Display \
8465 axis have drifted onto different emit-sets"
8466 );
8467 }
8468 let via_iter: Vec<String> = RestartStrategy::ALL
8469 .iter()
8470 .copied()
8471 .map(String::from)
8472 .collect();
8473 let via_method: Vec<String> = RestartStrategy::ALL
8474 .iter()
8475 .map(|s| s.as_str().to_owned())
8476 .collect();
8477 assert_eq!(
8478 via_iter, via_method,
8479 "`.iter().copied().map(String::from)` over RestartStrategy::ALL \
8480 must byte-equal `.iter().map(|s| s.as_str().to_owned())` on \
8481 every arm — the owned-`String` `From<RestartStrategy> for \
8482 String` axis is what makes the `String::from` composition \
8483 route through the substrate-primitive `RestartStrategy::as_str` \
8484 accessor rather than through a per-call-site `.to_owned()` / \
8485 `String::from(strategy.as_str())` detour"
8486 );
8487 for &variant in RestartStrategy::ALL {
8488 let emitted: String = variant.into();
8489 let re_parsed: Result<RestartStrategy, ()> =
8490 <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
8491 assert_eq!(
8492 re_parsed,
8493 Ok(variant),
8494 "trait-idiomatic owned-`String` forward-projection + \
8495 reverse-projection axis pair must round-trip \
8496 RestartStrategy::{variant:?} through `.into::<String>()` \
8497 and back through `TryFrom<&str>` on the owned-`String`'s \
8498 String::as_str borrow — a break signals the owned-`String` \
8499 forward-emit and reverse-parse axes have drifted onto \
8500 different vocabularies"
8501 );
8502 }
8503 }
8504
8505 #[test]
8506 fn restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
8507 // Fail-before-pass-after byte-parity pin on the newly lifted
8508 // `impl From<&RestartStrategy> for String` — asserts the
8509 // borrowed-input owned-`String`-returning standard-library trait
8510 // impl and the substrate-primitive [`RestartStrategy::as_str`]
8511 // `pub const fn` accessor resolve to the same four-arm emit-set
8512 // across every arm the exhaustive [`RestartStrategy::ALL`] slice
8513 // enumerates. Rust's standard library does not carry a blanket
8514 // `impl<T: AsRef<str>> From<&T> for String` (nor an
8515 // `impl<T: fmt::Display> From<&T> for String`), so the
8516 // borrowed-input owned-`String` forward-projection axis is a
8517 // distinct trait-idiomatic surface that a
8518 // `let key: String = (&strategy).into();`-shaped call site
8519 // reaches through this impl and no other — the paired sibling
8520 // `From<RestartStrategy> for String` impl forces every
8521 // borrowed-input call site through an explicit `Copy` deref
8522 // (`String::from(*strategy)`) or an `.as_str().to_owned()` /
8523 // `.to_string()` detour.
8524 for &variant in RestartStrategy::ALL {
8525 let via_trait: String = <String as From<&RestartStrategy>>::from(&variant);
8526 let via_method: &'static str = variant.as_str();
8527 assert_eq!(
8528 via_trait.as_str(),
8529 via_method,
8530 "From<&RestartStrategy> for String impl must round-trip \
8531 &RestartStrategy::{variant:?} to the same lifted \
8532 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
8533 returns — divergence signals a silent detour off the \
8534 substrate-primitive accessor"
8535 );
8536 let via_into: String = (&variant).into();
8537 assert_eq!(
8538 via_into.as_str(),
8539 via_method,
8540 "Into<String>::into on &RestartStrategy::{variant:?} must \
8541 byte-equal RestartStrategy::as_str on the same input — the \
8542 blanket-derived Into shape must resolve to the same as_str \
8543 dispatch as the explicit From impl"
8544 );
8545 }
8546 }
8547
8548 #[test]
8549 fn restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
8550 // Cross-axis partition pin: the newly lifted trait-idiomatic
8551 // borrowed-input owned-`String` `From<&RestartStrategy> for
8552 // String` (this lift), the paired owned-input owned-`String`
8553 // `From<RestartStrategy> for String` (7baa18a), the paired
8554 // borrowed-input owned-`&'static str` `From<&RestartStrategy>
8555 // for &'static str` (e941836), and the paired owned-input
8556 // owned-`&'static str` `From<RestartStrategy> for &'static str`
8557 // (523157d) — every corner of the `{Self, &Self} × {&'static
8558 // str, String}` 2×2 trait-idiomatic projection family — must
8559 // resolve identically on every arm, locking the four
8560 // return-shape × input-shape paths together so any future
8561 // detour trips at caixa-core test time. Also byte-parity
8562 // witness against the sibling [`ToString::to_string`] surface
8563 // routed through [`std::fmt::Display`] and a direct round-trip
8564 // witness through the paired trait-idiomatic reverse
8565 // [`TryFrom<&str>`] axis on the owned-`String`'s
8566 // [`String::as_str`] borrow that closes the two-way
8567 // `&Self → String → Self` round-trip on the trait-idiomatic
8568 // borrowed-input owned-`String` forward + reverse axis pair.
8569 for &variant in RestartStrategy::ALL {
8570 let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
8571 let owned_string: String = <String as From<RestartStrategy>>::from(variant);
8572 let borrowed_static: &'static str =
8573 <&'static str as From<&RestartStrategy>>::from(&variant);
8574 let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8575 assert_eq!(
8576 borrowed_string, owned_string,
8577 "From<&RestartStrategy> for String and From<RestartStrategy> \
8578 for String must resolve identically on \
8579 RestartStrategy::{variant:?} — divergence signals the \
8580 borrowed-input and owned-input owned-`String` \
8581 forward-projection input-shape paths have drifted onto \
8582 different emit-sets"
8583 );
8584 assert_eq!(
8585 borrowed_string.as_str(),
8586 borrowed_static,
8587 "From<&RestartStrategy> for String and From<&RestartStrategy> \
8588 for &'static str must resolve identically on \
8589 RestartStrategy::{variant:?} — divergence signals the \
8590 borrowed-input `&'static str` and owned-`String` \
8591 return-shape paths have drifted onto different emit-sets"
8592 );
8593 assert_eq!(
8594 borrowed_string.as_str(),
8595 owned_static,
8596 "From<&RestartStrategy> for String and From<RestartStrategy> \
8597 for &'static str must resolve identically on \
8598 RestartStrategy::{variant:?} — divergence signals a break \
8599 in the diagonal corner of the {{Self, &Self}} × \
8600 {{&'static str, String}} 2×2 trait-idiomatic \
8601 projection family"
8602 );
8603 let via_to_string: String = variant.to_string();
8604 assert_eq!(
8605 borrowed_string, via_to_string,
8606 "From<&RestartStrategy> for String must byte-equal \
8607 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
8608 divergence signals the trait-idiomatic borrowed-input \
8609 owned-`String` forward-projection axis and the \
8610 ToString-through-Display axis have drifted onto different \
8611 emit-sets"
8612 );
8613 }
8614 let via_iter: Vec<String> = RestartStrategy::ALL.iter().map(String::from).collect();
8615 let via_method: Vec<String> = RestartStrategy::ALL
8616 .iter()
8617 .map(|s| s.as_str().to_owned())
8618 .collect();
8619 assert_eq!(
8620 via_iter, via_method,
8621 "`.iter().map(String::from)` over RestartStrategy::ALL — a \
8622 call site whose iteration axis holds `&RestartStrategy` by \
8623 construction — must byte-equal `.iter().map(|s| \
8624 s.as_str().to_owned())` on every arm — the borrowed-input \
8625 owned-`String` `From<&RestartStrategy> for String` axis is \
8626 what makes the `String::from` composition route through the \
8627 substrate-primitive `RestartStrategy::as_str` accessor \
8628 without a spurious `Copy` deref (which would only be \
8629 reachable through the owned-input `From<RestartStrategy> for \
8630 String` axis by first calling `.copied()` on the iterator)"
8631 );
8632 for &variant in RestartStrategy::ALL {
8633 let emitted: String = (&variant).into();
8634 let re_parsed: Result<RestartStrategy, ()> =
8635 <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
8636 assert_eq!(
8637 re_parsed,
8638 Ok(variant),
8639 "trait-idiomatic borrowed-input owned-`String` \
8640 forward-projection + reverse-projection axis pair must \
8641 round-trip &RestartStrategy::{variant:?} through \
8642 `.into::<String>()` on the borrowed-input surface and \
8643 back through `TryFrom<&str>` on the owned-`String`'s \
8644 String::as_str borrow — a break signals the \
8645 borrowed-input owned-`String` forward-emit and \
8646 reverse-parse axes have drifted onto different \
8647 vocabularies"
8648 );
8649 }
8650 }
8651
8652 #[test]
8653 fn restart_strategy_from_into_static_cow_str_routes_through_as_str_accessor() {
8654 // Fail-before-pass-after byte-parity pin on the newly lifted
8655 // `impl From<RestartStrategy> for std::borrow::Cow<'static, str>` —
8656 // asserts the standard-library trait impl and the substrate-
8657 // primitive [`super::RestartStrategy::as_str`] `pub const fn`
8658 // accessor resolve to the same four-arm emit-set across every
8659 // arm the exhaustive [`super::RestartStrategy::ALL`] slice
8660 // enumerates. Rust's standard library does not carry a blanket
8661 // `impl<T: AsRef<str>> From<T> for Cow<'static, str>` (nor an
8662 // `impl<T: fmt::Display> From<T> for Cow<'static, str>`), so
8663 // the `Cow<'static, str>` forward-projection axis is a
8664 // distinct trait-idiomatic surface that a
8665 // `let key: Cow<'static, str> = strategy.into();`-shaped call
8666 // site reaches through this impl and no other — the paired
8667 // sibling `From<RestartStrategy> for &'static str` and
8668 // `From<RestartStrategy> for String` impls force every
8669 // `Cow<'static, str>`-parameterized call site through a
8670 // `Cow::Borrowed(strategy.as_str())` /
8671 // `Cow::Owned(strategy.to_string())` composition whose type
8672 // bounds have no compile-time link back to the substrate
8673 // primitive.
8674 //
8675 // Also asserts the projection lands on the zero-alloc
8676 // [`std::borrow::Cow::Borrowed`] arm (not the
8677 // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
8678 // [`super::RestartStrategy::as_str`] accessor's `&'static str`
8679 // return lifetime by construction makes the borrowed arm the
8680 // type-correct projection with no runtime allocation. Any
8681 // future silent detour that routes the impl through the owned
8682 // arm (an accidental `Cow::Owned(strategy.to_string())` rewrite
8683 // that would allocate on every call site where the
8684 // `&'static str` return of [`super::RestartStrategy::as_str`]
8685 // makes the zero-alloc borrowed projection type-correct) trips
8686 // at caixa-core test time under the
8687 // [`std::borrow::Cow::Borrowed`] discriminator witness rather
8688 // than at a downstream `Cow<'static, str>`-bound consumer's
8689 // silent allocation.
8690 //
8691 // First peer on the substrate-wide trait-idiomatic
8692 // [`std::borrow::Cow<'static, str>`] forward-projection family
8693 // to extend the axis off the top-level [`super::CaixaKind`]
8694 // enum (99c1735 owned-input, d45c409 borrowed-input) onto the
8695 // first M2 OTP-shape closed-set fieldless typed enum on the
8696 // caixa surface.
8697 for &variant in RestartStrategy::ALL {
8698 let via_trait: std::borrow::Cow<'static, str> =
8699 <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
8700 let via_method: &'static str = variant.as_str();
8701 assert_eq!(
8702 via_trait.as_ref(),
8703 via_method,
8704 "From<RestartStrategy> for Cow<'static, str> impl must \
8705 round-trip RestartStrategy::{variant:?} to the same \
8706 lifted SUPERVISOR_ESTRATEGIA_* const \
8707 RestartStrategy::as_str returns — divergence signals a \
8708 silent detour off the substrate-primitive accessor"
8709 );
8710 assert!(
8711 matches!(via_trait, std::borrow::Cow::Borrowed(_)),
8712 "From<RestartStrategy> for Cow<'static, str> impl must \
8713 land on the zero-alloc Cow::Borrowed arm on \
8714 RestartStrategy::{variant:?} — a Cow::Owned outcome \
8715 signals the projection has silently allocated where \
8716 the substrate-primitive RestartStrategy::as_str \
8717 `&'static str` return makes the borrowed arm the \
8718 type-correct projection"
8719 );
8720 let via_into: std::borrow::Cow<'static, str> = variant.into();
8721 assert_eq!(
8722 via_into.as_ref(),
8723 via_method,
8724 "Into<Cow<'static, str>>::into on \
8725 RestartStrategy::{variant:?} must byte-equal \
8726 RestartStrategy::as_str on the same input — the \
8727 blanket-derived Into shape must resolve to the same \
8728 as_str dispatch as the explicit From impl"
8729 );
8730 assert!(
8731 matches!(via_into, std::borrow::Cow::Borrowed(_)),
8732 "Into<Cow<'static, str>>::into on \
8733 RestartStrategy::{variant:?} must land on the \
8734 zero-alloc Cow::Borrowed arm — the blanket-derived \
8735 Into shape must resolve to the same Cow::Borrowed \
8736 dispatch as the explicit From impl"
8737 );
8738 }
8739 }
8740
8741 #[test]
8742 fn restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
8743 // Cross-axis partition pin: the newly lifted trait-idiomatic
8744 // `From<RestartStrategy> for std::borrow::Cow<'static, str>`
8745 // (this lift), the paired owned-input `From<RestartStrategy>
8746 // for &'static str` (523157d), and the paired owned-input
8747 // `From<RestartStrategy> for String` (7baa18a) forward
8748 // projections must resolve identically on every arm, locking
8749 // the three return-shape paths together by construction so any
8750 // future detour trips at caixa-core test time. Also byte-parity
8751 // witness against the sibling [`ToString::to_string`] surface
8752 // routed through [`std::fmt::Display`] — every owned-heap-
8753 // string path (the `Cow::Owned` promotion of this axis's
8754 // `.into_owned()`, `From<RestartStrategy> for String`, and
8755 // `.to_string()`) resolves to the same lifted
8756 // [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const per arm.
8757 //
8758 // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
8759 // witness over [`super::RestartStrategy::ALL`] that
8760 // materializes the four-arm accept-set through the
8761 // [`std::borrow::Cow<'static, str>`] axis alone — the exact
8762 // shape a future `axum::response::IntoResponse` per-strategy
8763 // rejection-body composer, a future M4 admission-webhook
8764 // per-strategy rejection-reason emitter whose typing rules out
8765 // the sibling [`AsRef<str>`] borrowed return, or a future
8766 // substrate-wide per-strategy diagnostic surface that binds
8767 // through a [`Cow<'static, str>`] boundary reaches through.
8768 // The pipe witness also pins the zero-alloc discipline: every
8769 // element in the collected vector satisfies the
8770 // [`std::borrow::Cow::Borrowed`] arm predicate, so a future
8771 // accidental silent-allocation regression on the pipe's
8772 // iteration axis is a caixa-core-test-time failure.
8773 for &variant in RestartStrategy::ALL {
8774 let via_cow: std::borrow::Cow<'static, str> =
8775 <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
8776 let via_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8777 let via_string: String = <String as From<RestartStrategy>>::from(variant);
8778 assert_eq!(
8779 via_cow.as_ref(),
8780 via_static,
8781 "From<RestartStrategy> for Cow<'static, str> and \
8782 From<RestartStrategy> for &'static str must resolve \
8783 identically on RestartStrategy::{variant:?} — \
8784 divergence signals the Cow<'static, str> and \
8785 &'static str return-shape paths have drifted onto \
8786 different emit-sets"
8787 );
8788 assert_eq!(
8789 via_cow.as_ref(),
8790 via_string.as_str(),
8791 "From<RestartStrategy> for Cow<'static, str> and \
8792 From<RestartStrategy> for String must resolve \
8793 identically on RestartStrategy::{variant:?} — \
8794 divergence signals the Cow<'static, str> and String \
8795 return-shape paths have drifted onto different \
8796 emit-sets"
8797 );
8798 let via_to_string: String = variant.to_string();
8799 assert_eq!(
8800 via_cow.as_ref(),
8801 via_to_string.as_str(),
8802 "From<RestartStrategy> for Cow<'static, str> must \
8803 byte-equal RestartStrategy::to_string on \
8804 RestartStrategy::{variant:?} — divergence signals the \
8805 trait-idiomatic Cow<'static, str> forward-projection \
8806 axis and the ToString-through-Display axis have \
8807 drifted onto different emit-sets"
8808 );
8809 }
8810 let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
8811 .iter()
8812 .copied()
8813 .map(std::borrow::Cow::from)
8814 .collect();
8815 let via_method: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
8816 .iter()
8817 .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
8818 .collect();
8819 assert_eq!(
8820 via_iter, via_method,
8821 "`.iter().copied().map(Cow::from)` over \
8822 RestartStrategy::ALL must byte-equal `.iter().map(|s| \
8823 Cow::Borrowed(s.as_str()))` on every arm — the \
8824 trait-idiomatic `From<RestartStrategy> for Cow<'static, \
8825 str>` axis is what makes the `Cow::from` composition \
8826 route through the substrate-primitive \
8827 `RestartStrategy::as_str` accessor with the zero-alloc \
8828 Cow::Borrowed arm by construction, rather than a \
8829 per-call-site `Cow::Owned(strategy.to_string())` \
8830 allocation"
8831 );
8832 for cow in &via_iter {
8833 assert!(
8834 matches!(cow, std::borrow::Cow::Borrowed(_)),
8835 "every element of the \
8836 .iter().copied().map(Cow::from) pipe over \
8837 RestartStrategy::ALL must land on the zero-alloc \
8838 Cow::Borrowed arm — a Cow::Owned outcome on any arm \
8839 signals the pipe's iteration axis has silently \
8840 allocated where the substrate-primitive \
8841 RestartStrategy::as_str `&'static str` return makes \
8842 the borrowed arm the type-correct projection"
8843 );
8844 }
8845 }
8846
8847 #[test]
8848 fn restart_strategy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
8849 // Fail-before-pass-after byte-parity pin on the newly lifted
8850 // `impl From<&RestartStrategy> for std::borrow::Cow<'static, str>` —
8851 // asserts the borrowed-input standard-library trait impl and
8852 // the substrate-primitive [`super::RestartStrategy::as_str`]
8853 // `pub const fn` accessor resolve to the same four-arm emit-
8854 // set across every arm the exhaustive
8855 // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
8856 // standard library does not carry a blanket
8857 // `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor a
8858 // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
8859 // the borrowed-input `Cow<'static, str>` forward-projection
8860 // axis is a distinct trait-idiomatic surface that a
8861 // `let key: Cow<'static, str> = (&strategy).into();`-shaped
8862 // call site or a
8863 // `RestartStrategy::ALL.iter().map(Cow::from)`-shaped pipe
8864 // reaches through this impl and no other — the paired owned-
8865 // input `From<RestartStrategy> for Cow<'static, str>` impl
8866 // (7dd28b3) forces every borrowed-input call site through an
8867 // explicit `Copy` deref (`Cow::from(*strategy)`) or a
8868 // `Cow::Borrowed(strategy.as_str())` open-code whose type
8869 // bounds have no compile-time link back to the substrate
8870 // primitive.
8871 //
8872 // Also asserts the projection lands on the zero-alloc
8873 // [`std::borrow::Cow::Borrowed`] arm (not the
8874 // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
8875 // [`super::RestartStrategy::as_str`] accessor's `&'static str`
8876 // return lifetime by construction makes the borrowed arm the
8877 // type-correct projection with no runtime allocation on the
8878 // borrowed-input surface just as on the paired owned-input
8879 // surface.
8880 //
8881 // Second peer on the substrate-wide trait-idiomatic
8882 // [`std::borrow::Cow<'static, str>`] forward-projection family
8883 // on this enum — closes the `{Self, &Self}` input-shape
8884 // corner of the [`Cow<'static, str>`] axis on the first M2
8885 // OTP-shape closed-set fieldless typed enum peer on the caixa
8886 // surface (`:supervisor :estrategia`), exactly as d45c409
8887 // closed it on the top-level [`super::CaixaKind`] one commit
8888 // after the owning half (99c1735) landed. Every future
8889 // closed-set fieldless typed enum peer on the substrate is a
8890 // future target of the campaign.
8891 for &variant in RestartStrategy::ALL {
8892 let via_trait: std::borrow::Cow<'static, str> =
8893 <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
8894 let via_method: &'static str = variant.as_str();
8895 assert_eq!(
8896 via_trait.as_ref(),
8897 via_method,
8898 "From<&RestartStrategy> for Cow<'static, str> impl must \
8899 round-trip &RestartStrategy::{variant:?} to the same \
8900 lifted SUPERVISOR_ESTRATEGIA_* const \
8901 RestartStrategy::as_str returns — divergence signals a \
8902 silent detour off the substrate-primitive accessor"
8903 );
8904 assert!(
8905 matches!(via_trait, std::borrow::Cow::Borrowed(_)),
8906 "From<&RestartStrategy> for Cow<'static, str> impl must \
8907 land on the zero-alloc Cow::Borrowed arm on \
8908 &RestartStrategy::{variant:?} — a Cow::Owned outcome \
8909 signals the projection has silently allocated where \
8910 the substrate-primitive RestartStrategy::as_str \
8911 `&'static str` return makes the borrowed arm the \
8912 type-correct projection"
8913 );
8914 let via_into: std::borrow::Cow<'static, str> = (&variant).into();
8915 assert_eq!(
8916 via_into.as_ref(),
8917 via_method,
8918 "Into<Cow<'static, str>>::into on \
8919 &RestartStrategy::{variant:?} must byte-equal \
8920 RestartStrategy::as_str on the same input — the \
8921 blanket-derived Into shape must resolve to the same \
8922 as_str dispatch as the explicit From impl"
8923 );
8924 assert!(
8925 matches!(via_into, std::borrow::Cow::Borrowed(_)),
8926 "Into<Cow<'static, str>>::into on \
8927 &RestartStrategy::{variant:?} must land on the \
8928 zero-alloc Cow::Borrowed arm — the blanket-derived \
8929 Into shape must resolve to the same Cow::Borrowed \
8930 dispatch as the explicit From impl"
8931 );
8932 }
8933 }
8934
8935 #[test]
8936 fn restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
8937 // Cross-axis partition pin: the newly lifted trait-idiomatic
8938 // borrowed-input `From<&RestartStrategy> for
8939 // std::borrow::Cow<'static, str>` (this lift), the paired
8940 // owned-input `From<RestartStrategy> for
8941 // std::borrow::Cow<'static, str>` (7dd28b3), the paired
8942 // borrowed-input owned-`&'static str` `From<&RestartStrategy>
8943 // for &'static str`, and the paired borrowed-input owned-
8944 // `String` `From<&RestartStrategy> for String` must resolve
8945 // identically on every arm, locking the four
8946 // return-shape × input-shape paths together by construction so
8947 // any future detour trips at caixa-core test time. Also byte-
8948 // parity witness against the sibling [`ToString::to_string`]
8949 // surface routed through [`std::fmt::Display`] — every owned-
8950 // heap-string path (this axis's `.into_owned()` promotion, the
8951 // paired [`From<&RestartStrategy> for String`], and
8952 // `.to_string()`) resolves to the same lifted
8953 // [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const per arm.
8954 //
8955 // Then a `.iter().map(std::borrow::Cow::from)` pipe witness
8956 // over [`super::RestartStrategy::ALL`] — whose iterator yields
8957 // `&RestartStrategy` by construction, so the borrowed-input
8958 // [`Cow<'static, str>`] axis is what routes the pipe through
8959 // the substrate-primitive [`super::RestartStrategy::as_str`]
8960 // accessor without a spurious [`Copy`] deref (which would only
8961 // be reachable through the owned-input
8962 // [`From<RestartStrategy> for Cow<'static, str>`] axis by
8963 // first calling `.copied()` on the iterator). The pipe witness
8964 // also pins the zero-alloc discipline: every element in the
8965 // collected vector satisfies the [`std::borrow::Cow::Borrowed`]
8966 // arm predicate, so a future accidental silent-allocation
8967 // regression on the pipe's iteration axis is a caixa-core-
8968 // test-time failure.
8969 for &strategy in RestartStrategy::ALL {
8970 let borrowed_cow: std::borrow::Cow<'static, str> =
8971 <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&strategy);
8972 let owned_cow: std::borrow::Cow<'static, str> =
8973 <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(strategy);
8974 let borrowed_static: &'static str =
8975 <&'static str as From<&RestartStrategy>>::from(&strategy);
8976 let borrowed_string: String = <String as From<&RestartStrategy>>::from(&strategy);
8977 assert_eq!(
8978 borrowed_cow, owned_cow,
8979 "From<&RestartStrategy> for Cow<'static, str> and \
8980 From<RestartStrategy> for Cow<'static, str> must \
8981 resolve identically on RestartStrategy::{strategy:?} — \
8982 divergence signals the borrowed-input and owned-input \
8983 Cow<'static, str> forward-projection input-shape \
8984 paths have drifted onto different emit-sets"
8985 );
8986 assert_eq!(
8987 borrowed_cow.as_ref(),
8988 borrowed_static,
8989 "From<&RestartStrategy> for Cow<'static, str> and \
8990 From<&RestartStrategy> for &'static str must resolve \
8991 identically on RestartStrategy::{strategy:?} — \
8992 divergence signals the borrowed-input Cow<'static, \
8993 str> and &'static str return-shape paths have drifted \
8994 onto different emit-sets"
8995 );
8996 assert_eq!(
8997 borrowed_cow.as_ref(),
8998 borrowed_string.as_str(),
8999 "From<&RestartStrategy> for Cow<'static, str> and \
9000 From<&RestartStrategy> for String must resolve \
9001 identically on RestartStrategy::{strategy:?} — \
9002 divergence signals the borrowed-input Cow<'static, \
9003 str> and owned-`String` return-shape paths have \
9004 drifted onto different emit-sets"
9005 );
9006 let via_to_string: String = strategy.to_string();
9007 assert_eq!(
9008 borrowed_cow.as_ref(),
9009 via_to_string.as_str(),
9010 "From<&RestartStrategy> for Cow<'static, str> must \
9011 byte-equal RestartStrategy::to_string on \
9012 RestartStrategy::{strategy:?} — divergence signals \
9013 the trait-idiomatic borrowed-input Cow<'static, str> \
9014 forward-projection axis and the ToString-through-\
9015 Display axis have drifted onto different emit-sets"
9016 );
9017 }
9018 let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
9019 .iter()
9020 .map(std::borrow::Cow::from)
9021 .collect();
9022 let via_method: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
9023 .iter()
9024 .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
9025 .collect();
9026 assert_eq!(
9027 via_iter, via_method,
9028 "`.iter().map(Cow::from)` over RestartStrategy::ALL — a \
9029 call site whose iteration axis holds `&RestartStrategy` \
9030 by construction — must byte-equal `.iter().map(|s| \
9031 Cow::Borrowed(s.as_str()))` on every arm — the borrowed-\
9032 input Cow<'static, str> `From<&RestartStrategy> for \
9033 Cow<'static, str>` axis is what makes the `Cow::from` \
9034 composition route through the substrate-primitive \
9035 `RestartStrategy::as_str` accessor with the zero-alloc \
9036 Cow::Borrowed arm by construction and without a spurious \
9037 `Copy` deref (which would only be reachable through the \
9038 owned-input `From<RestartStrategy> for Cow<'static, str>` \
9039 axis by first calling `.copied()` on the iterator)"
9040 );
9041 for cow in &via_iter {
9042 assert!(
9043 matches!(cow, std::borrow::Cow::Borrowed(_)),
9044 "every element of the .iter().map(Cow::from) pipe \
9045 over RestartStrategy::ALL must land on the zero-\
9046 alloc Cow::Borrowed arm — a Cow::Owned outcome on \
9047 any arm signals the pipe's iteration axis has \
9048 silently allocated where the substrate-primitive \
9049 RestartStrategy::as_str `&'static str` return makes \
9050 the borrowed arm the type-correct projection"
9051 );
9052 }
9053 }
9054
9055 #[test]
9056 fn restart_strategy_from_into_box_str_routes_through_as_str_accessor() {
9057 // Fail-before-pass-after byte-parity pin on the newly lifted
9058 // `impl From<RestartStrategy> for Box<str>` — asserts the
9059 // owned-input standard-library trait impl and the
9060 // substrate-primitive [`super::RestartStrategy::as_str`]
9061 // `pub const fn` accessor resolve to the same four-arm emit-
9062 // set across every arm the exhaustive
9063 // [`super::RestartStrategy::ALL`] slice enumerates. Opens the
9064 // substrate-wide `Box<str>` forward-projection campaign tier
9065 // on the first M2 OTP-shape closed-set fieldless typed enum
9066 // peer on the caixa surface (`:supervisor :estrategia`),
9067 // immediately after the paired `Cow<'static, str>` axis
9068 // (7dd28b3 / ee577fd) closed the
9069 // `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
9070 // 2×3 corner on this enum. Rust's standard library carries
9071 // `impl From<&str> for Box<str>` and
9072 // `impl From<String> for Box<str>` but no blanket
9073 // `impl<T: AsRef<str>> From<T> for Box<str>`, so this axis is
9074 // a distinct trait-idiomatic surface that a
9075 // `let key: Box<str> = strategy.into();`-shaped call site
9076 // reaches through this impl and no other — a paired
9077 // `Box::from(strategy.as_str())` open-code has no compile-
9078 // time link back to the substrate primitive.
9079 for &variant in RestartStrategy::ALL {
9080 let via_trait: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
9081 let via_method: &'static str = variant.as_str();
9082 assert_eq!(
9083 via_trait.as_ref(),
9084 via_method,
9085 "From<RestartStrategy> for Box<str> impl must round-\
9086 trip RestartStrategy::{variant:?} to the same lifted \
9087 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
9088 returns — divergence signals a silent detour off the \
9089 substrate-primitive accessor"
9090 );
9091 let via_into: Box<str> = variant.into();
9092 assert_eq!(
9093 via_into.as_ref(),
9094 via_method,
9095 "Into<Box<str>>::into on RestartStrategy::{variant:?} \
9096 must byte-equal RestartStrategy::as_str on the same \
9097 input — the blanket-derived Into shape must resolve \
9098 to the same as_str dispatch as the explicit From impl"
9099 );
9100 }
9101 }
9102
9103 #[test]
9104 fn restart_strategy_from_borrowed_into_box_str_routes_through_as_str_accessor() {
9105 // Fail-before-pass-after byte-parity pin on the newly lifted
9106 // `impl From<&RestartStrategy> for Box<str>` — asserts the
9107 // borrowed-input standard-library trait impl and the
9108 // substrate-primitive [`super::RestartStrategy::as_str`]
9109 // `pub const fn` accessor resolve to the same four-arm emit-
9110 // set across every arm the exhaustive
9111 // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
9112 // standard library does not carry a blanket
9113 // `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
9114 // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
9115 // so the borrowed-input `Box<str>` forward-projection axis
9116 // is a distinct trait-idiomatic surface that a
9117 // `let key: Box<str> = (&strategy).into();`-shaped call site
9118 // or a `RestartStrategy::ALL.iter().map(Box::<str>::from)`-
9119 // shaped pipe reaches through this impl and no other — the
9120 // paired owned-input `From<RestartStrategy> for Box<str>`
9121 // impl (69ef45c) forces every borrowed-input call site
9122 // through an explicit `Copy` deref
9123 // (`Box::<str>::from((*strategy).as_str())`) or a
9124 // `Box::<str>::from(strategy.as_str())` open-code whose
9125 // type bounds have no compile-time link back to the
9126 // substrate primitive.
9127 //
9128 // Second peer on the substrate-wide trait-idiomatic
9129 // [`Box<str>`] forward-projection family on this enum —
9130 // closes the `{Self, &Self}` input-shape corner of the
9131 // [`Box<str>`] axis on the first M2 OTP-shape closed-set
9132 // fieldless typed enum peer on the caixa surface
9133 // (`:supervisor :estrategia`), exactly as ee577fd closed
9134 // the paired [`Cow<'static, str>`] axis one commit after
9135 // its owning half (7dd28b3) landed. Every future closed-
9136 // set fieldless typed enum peer on the substrate is a
9137 // future target of the campaign.
9138 //
9139 // Also byte-parity witness against the paired owned-input
9140 // [`From<RestartStrategy> for Box<str>`] and the sibling
9141 // borrowed-input [`From<&RestartStrategy> for &'static str`],
9142 // [`From<&RestartStrategy> for String`], and
9143 // [`From<&RestartStrategy> for Cow<'static, str>`]
9144 // return-shape axes — locking the four
9145 // return-shape × input-shape paths together by construction
9146 // so any future detour trips at caixa-core test time. Then a
9147 // `.iter().map(Box::<str>::from)` pipe witness over
9148 // [`super::RestartStrategy::ALL`] — whose iterator yields
9149 // `&RestartStrategy` by construction, so the borrowed-input
9150 // [`Box<str>`] axis is what routes the pipe through the
9151 // substrate-primitive [`super::RestartStrategy::as_str`]
9152 // accessor without a spurious [`Copy`] deref (which would
9153 // only be reachable through the owned-input
9154 // [`From<RestartStrategy> for Box<str>`] axis by first
9155 // calling `.copied()` on the iterator).
9156 for &variant in RestartStrategy::ALL {
9157 let via_trait: Box<str> = <Box<str> as From<&RestartStrategy>>::from(&variant);
9158 let via_method: &'static str = variant.as_str();
9159 assert_eq!(
9160 via_trait.as_ref(),
9161 via_method,
9162 "From<&RestartStrategy> for Box<str> impl must \
9163 round-trip &RestartStrategy::{variant:?} to the same \
9164 lifted SUPERVISOR_ESTRATEGIA_* const \
9165 RestartStrategy::as_str returns — divergence signals \
9166 a silent detour off the substrate-primitive accessor"
9167 );
9168 let via_into: Box<str> = (&variant).into();
9169 assert_eq!(
9170 via_into.as_ref(),
9171 via_method,
9172 "Into<Box<str>>::into on &RestartStrategy::{variant:?} \
9173 must byte-equal RestartStrategy::as_str on the same \
9174 input — the blanket-derived Into shape must resolve \
9175 to the same as_str dispatch as the explicit From impl"
9176 );
9177 let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
9178 assert_eq!(
9179 via_trait, owned_box,
9180 "From<&RestartStrategy> for Box<str> and \
9181 From<RestartStrategy> for Box<str> must resolve \
9182 identically on RestartStrategy::{variant:?} — \
9183 divergence signals the borrowed-input and owned-input \
9184 Box<str> forward-projection input-shape paths have \
9185 drifted onto different emit-sets"
9186 );
9187 let borrowed_static: &'static str =
9188 <&'static str as From<&RestartStrategy>>::from(&variant);
9189 assert_eq!(
9190 via_trait.as_ref(),
9191 borrowed_static,
9192 "From<&RestartStrategy> for Box<str> and \
9193 From<&RestartStrategy> for &'static str must resolve \
9194 identically on RestartStrategy::{variant:?} — \
9195 divergence signals the borrowed-input Box<str> and \
9196 &'static str return-shape paths have drifted onto \
9197 different emit-sets"
9198 );
9199 let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
9200 assert_eq!(
9201 via_trait.as_ref(),
9202 borrowed_string.as_str(),
9203 "From<&RestartStrategy> for Box<str> and \
9204 From<&RestartStrategy> for String must resolve \
9205 identically on RestartStrategy::{variant:?} — \
9206 divergence signals the borrowed-input Box<str> and \
9207 owned-`String` return-shape paths have drifted onto \
9208 different emit-sets"
9209 );
9210 let borrowed_cow: std::borrow::Cow<'static, str> =
9211 <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
9212 assert_eq!(
9213 via_trait.as_ref(),
9214 borrowed_cow.as_ref(),
9215 "From<&RestartStrategy> for Box<str> and \
9216 From<&RestartStrategy> for Cow<'static, str> must \
9217 resolve identically on RestartStrategy::{variant:?} — \
9218 divergence signals the borrowed-input Box<str> and \
9219 Cow<'static, str> return-shape paths have drifted \
9220 onto different emit-sets"
9221 );
9222 }
9223 let via_iter: Vec<Box<str>> = RestartStrategy::ALL.iter().map(Box::<str>::from).collect();
9224 let via_method: Vec<Box<str>> = RestartStrategy::ALL
9225 .iter()
9226 .map(|s| Box::<str>::from(s.as_str()))
9227 .collect();
9228 assert_eq!(
9229 via_iter, via_method,
9230 "`.iter().map(Box::<str>::from)` over \
9231 RestartStrategy::ALL — a call site whose iteration axis \
9232 holds `&RestartStrategy` by construction — must byte-\
9233 equal `.iter().map(|s| Box::<str>::from(s.as_str()))` \
9234 on every arm — the borrowed-input Box<str> \
9235 `From<&RestartStrategy> for Box<str>` axis is what \
9236 makes the `Box::<str>::from` composition route through \
9237 the substrate-primitive `RestartStrategy::as_str` \
9238 accessor without a spurious `Copy` deref (which would \
9239 only be reachable through the owned-input \
9240 `From<RestartStrategy> for Box<str>` axis by first \
9241 calling `.copied()` on the iterator)"
9242 );
9243 }
9244
9245 #[test]
9246 fn restart_policy_try_from_str_routes_through_from_wire_accessor() {
9247 // Fail-before-pass-after byte-parity pin on the newly lifted
9248 // `impl TryFrom<&str> for RestartPolicy` — asserts the standard-
9249 // library trait impl and the substrate-primitive
9250 // [`RestartPolicy::from_wire`] `Option<Self>` accessor resolve to
9251 // the same three-arm accept-set across every arm the exhaustive
9252 // [`RestartPolicy::ALL`] slice enumerates. Any future silent
9253 // detour that routes the trait impl through a divergent
9254 // projection (a per-arm inline `match s { "Permanent" =>
9255 // Ok(Self::Permanent), … }` re-inlining that opens a compile-time
9256 // link to the un-lifted arm-literal, a hypothetical
9257 // `#[serde(rename_all = "…")]` attribute drift that silently
9258 // splits the wire byte-string from every consumer that reaches
9259 // for this typed dispatch, an accidental swap onto the kebab-case
9260 // dispatcher-catalog axis the pre-existing [`std::str::FromStr`]
9261 // impl parses through and which would collide the two-axis
9262 // wire/catalog split the sibling [`RestartPolicy::from_wire`]
9263 // doc block makes load-bearing) trips at caixa-core test time
9264 // under `assert_eq!` rather than at a downstream
9265 // `impl TryFrom<&str>`-bound consumer's silent split. Sweeps
9266 // every one of the three arms [`RestartPolicy::ALL`] carries so
9267 // no arm's projection is covered only by the sibling method-
9268 // named `from_wire` path. Peer of the sibling
9269 // [`restart_strategy_try_from_str_routes_through_from_wire_accessor`]
9270 // (5b828ed) — extends the trait-idiomatic reverse-projection
9271 // axis onto the third and final M2-OTP-shape closed-set typed
9272 // enum on the caixa surface (the paired per-child restart-
9273 // decision-policy sibling on the same M2 `:supervisor` slot).
9274 for &variant in RestartPolicy::ALL {
9275 let wire = variant.as_str();
9276 assert_eq!(
9277 <RestartPolicy as TryFrom<&str>>::try_from(wire),
9278 Ok(variant),
9279 "TryFrom<&str> impl on RestartPolicy must round-trip \
9280 RestartPolicy::{variant:?}.as_str() = {wire:?} back to \
9281 Ok(RestartPolicy::{variant:?}) — divergence from \
9282 RestartPolicy::from_wire signals a silent detour off \
9283 the substrate-primitive accessor"
9284 );
9285 assert_eq!(
9286 <RestartPolicy as TryFrom<&str>>::try_from(wire).ok(),
9287 RestartPolicy::from_wire(wire),
9288 "TryFrom<&str> ok()-projection on {wire:?} must byte-\
9289 equal RestartPolicy::from_wire on the same input"
9290 );
9291 }
9292 }
9293
9294 #[test]
9295 fn restart_policy_try_from_str_rejects_unknown_byte_strings() {
9296 // Rejection witness on the `impl TryFrom<&str> for
9297 // RestartPolicy` — sweeps a candidate set of byte-strings
9298 // outside the three-arm PascalCase wire accept-set the sibling
9299 // [`RestartPolicy::as_str`] emits and asserts every one lands on
9300 // `Err(())`, so a future accidental widening of the trait impl's
9301 // accept-set (a stray additional
9302 // `_ if s.eq_ignore_ascii_case("Permanent") => Ok(…)` case-fold
9303 // path, a silent inclusion of the kebab-case dispatcher-catalog
9304 // byte-string the pre-existing [`std::str::FromStr`] impl the
9305 // [`gen_platform::FromStrKind`] derive installs parses onto the
9306 // wire axis — which would collide the two-axis
9307 // wire/dispatcher-catalog split the sibling
9308 // [`RestartPolicy::from_wire`] doc block makes load-bearing —
9309 // an English-rebrand or plural-arm silent alias that would widen
9310 // the wire accept-set past the OTP-canonical three) trips at
9311 // caixa-core test time. The candidate set includes the empty
9312 // string, whitespace-only padding, the kebab-case dispatcher-
9313 // catalog byte-strings on the sibling axis (a caller who
9314 // confuses the two axes trips here rather than at a downstream
9315 // consumer's silent reject), a lowercase / uppercase / mixed-case
9316 // fold of each PascalCase arm (a caller who assumes case-fold
9317 // acceptance trips here), leading/trailing whitespace padding,
9318 // the trailing-newline shape, quote-wrapped candidates, and a
9319 // residual set of plausible-but-wrong English rebrand
9320 // candidates. Peer of the sibling
9321 // [`restart_strategy_try_from_str_rejects_unknown_byte_strings`]
9322 // (5b828ed) rejection witness.
9323 let rejected: &[&str] = &[
9324 "",
9325 " ",
9326 "\n",
9327 "\t",
9328 "permanent",
9329 "temporary",
9330 "transient",
9331 "PERMANENT",
9332 "TEMPORARY",
9333 "TRANSIENT",
9334 "Permanents",
9335 "Permanent ",
9336 " Permanent",
9337 " Temporary ",
9338 "Permanent\n",
9339 "Transient\t",
9340 "\"Permanent\"",
9341 "Ephemeral",
9342 "Always",
9343 "Never",
9344 "OnAbnormalExit",
9345 "intrinsic",
9346 "?",
9347 ];
9348 for &input in rejected {
9349 assert_eq!(
9350 <RestartPolicy as TryFrom<&str>>::try_from(input),
9351 Err(()),
9352 "TryFrom<&str> impl on RestartPolicy must reject the \
9353 non-wire byte-string {input:?} — silent acceptance \
9354 signals an accept-set widening off the paired \
9355 RestartPolicy::from_wire resolver"
9356 );
9357 }
9358 }
9359
9360 #[test]
9361 fn restart_policy_try_from_str_and_from_wire_partition_the_accept_set() {
9362 // Cross-axis partition pin: the paired `TryFrom<&str>` and
9363 // `from_wire` reverse projections must resolve identically on
9364 // *every* input, not just the ones [`RestartPolicy::ALL`]
9365 // enumerates. Sweeps a mixed candidate set spanning accepted
9366 // (three-arm PascalCase wire byte-strings) and rejected (kebab-
9367 // case dispatcher-catalog byte-strings, empty, whitespace-
9368 // padded, quoted, English-rebrand candidates) inputs and asserts
9369 // the trait's `Result::ok()` projection byte-equals the method-
9370 // named resolver's `Option<Self>` return-shape on each, locking
9371 // the two paths together by construction so any future detour
9372 // (a stray `try_from` special-case that widens or narrows the
9373 // accept-set outside the paired `from_wire` resolver, an
9374 // accidental swap onto the kebab-case [`std::str::FromStr`]
9375 // impl the [`gen_platform::FromStrKind`] derive installs on the
9376 // sibling dispatcher-catalog axis) trips at caixa-core test
9377 // time. Peer of the sibling
9378 // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
9379 // pin — extends the round-trip discipline onto the M2-OTP-shape
9380 // per-child restart-policy axis.
9381 let candidates: &[&str] = &[
9382 "Permanent",
9383 "Temporary",
9384 "Transient",
9385 "",
9386 "permanent",
9387 "temporary",
9388 "transient",
9389 "PERMANENT",
9390 "unknown",
9391 "Permanent ",
9392 " Permanent",
9393 "\"Permanent\"",
9394 "Ephemeral",
9395 "OnAbnormalExit",
9396 "?",
9397 ];
9398 for &input in candidates {
9399 let via_trait: Option<RestartPolicy> =
9400 <RestartPolicy as TryFrom<&str>>::try_from(input).ok();
9401 let via_method: Option<RestartPolicy> = RestartPolicy::from_wire(input);
9402 assert_eq!(
9403 via_trait, via_method,
9404 "TryFrom<&str> and from_wire must resolve identically on \
9405 input {input:?} — divergence signals the two reverse-\
9406 projection paths have drifted onto different accept-sets"
9407 );
9408 }
9409 }
9410
9411 #[test]
9412 fn restart_policy_from_into_static_str_routes_through_as_str_accessor() {
9413 // Fail-before-pass-after byte-parity pin on the newly lifted
9414 // `impl From<RestartPolicy> for &'static str` — asserts the
9415 // standard-library trait impl and the substrate-primitive
9416 // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
9417 // the same three-arm emit-set across every arm the exhaustive
9418 // [`RestartPolicy::ALL`] slice enumerates. Any future silent
9419 // detour that routes the trait impl through a divergent
9420 // projection (a per-arm inline `match policy { Permanent =>
9421 // "Permanent", … }` re-inlining that opens a compile-time link
9422 // to the un-lifted arm-literal, an accidental swap onto the
9423 // sibling kebab-case [`Self::discriminant`] dispatcher-catalog
9424 // axis that would collide the two-axis wire/catalog split the
9425 // sibling [`RestartPolicy::from_wire`] doc block makes
9426 // load-bearing) trips at caixa-core test time under
9427 // `assert_eq!` rather than at a downstream
9428 // `impl Into<&'static str>`-bound consumer's silent split.
9429 // Sweeps every one of the three arms [`RestartPolicy::ALL`]
9430 // carries so no arm's projection is covered only by the sibling
9431 // method-named `as_str` / [`std::fmt::Display`] / [`AsRef<str>`]
9432 // paths. Materializes the `<&'static str as
9433 // From<RestartPolicy>>::from` output in a `const`-shape binding
9434 // to make the `'static` lifetime promise a build-time invariant
9435 // — a future accidental downgrade of any of the three arms'
9436 // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] constants to a
9437 // non-`&'static str` (a `String::leak()`-produced return, a
9438 // `Box::leak`-cast) trips at caixa-core build time rather than
9439 // at a downstream `'static`-bound consumer. Peer of the sibling
9440 // [`restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
9441 // (523157d) — extends the trait-idiomatic forward-projection
9442 // axis onto the second (and second-of-two-in-M2) closed-set
9443 // typed enum on the caixa surface (the paired per-child
9444 // restart-decision-policy sibling on the same M2 `:supervisor`
9445 // slot).
9446 const PERMANENT: &str = RestartPolicy::Permanent.as_str();
9447 const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
9448 const TRANSIENT: &str = RestartPolicy::Transient.as_str();
9449 for &variant in RestartPolicy::ALL {
9450 let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
9451 let via_method: &'static str = variant.as_str();
9452 assert_eq!(
9453 via_trait, via_method,
9454 "From<RestartPolicy> for &'static str impl must round-trip \
9455 RestartPolicy::{variant:?} to the same lifted \
9456 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str returns — \
9457 divergence signals a silent detour off the substrate-primitive \
9458 accessor"
9459 );
9460 let via_into: &'static str = variant.into();
9461 assert_eq!(
9462 via_into, via_method,
9463 "Into<&'static str>::into on RestartPolicy::{variant:?} must \
9464 byte-equal RestartPolicy::as_str on the same input — the \
9465 blanket-derived Into shape must resolve to the same as_str \
9466 dispatch as the explicit From impl"
9467 );
9468 }
9469 assert_eq!(
9470 [PERMANENT, TEMPORARY, TRANSIENT],
9471 [
9472 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
9473 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
9474 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
9475 ],
9476 "const-context RestartPolicy::as_str must resolve to the three \
9477 lifted SUPERVISOR_CHILD_RESTART_* consts — a future accidental \
9478 downgrade of any arm to a non-const or non-static byte-string \
9479 breaks the `&'static str`-lifetime promise the paired \
9480 From<RestartPolicy> for &'static str impl carries by \
9481 construction"
9482 );
9483 }
9484
9485 #[test]
9486 fn restart_policy_from_into_static_str_and_as_str_partition_the_emit_set() {
9487 // Cross-axis partition pin: the paired trait-idiomatic
9488 // `From<RestartPolicy> for &'static str` forward projection and
9489 // the method-named [`RestartPolicy::as_str`] forward projection
9490 // must resolve identically on *every* arm, not just the ones
9491 // named in the primary byte-parity pin above. Sweeps every
9492 // [`RestartPolicy::ALL`] arm and asserts the trait's `From::from`
9493 // output byte-equals the method-named accessor's return-value on
9494 // each, locking the two forward-projection paths together by
9495 // construction so any future detour (a stray `From` special-case
9496 // that lands on a divergent per-arm literal outside the paired
9497 // `as_str` dispatch, a hypothetical rebrand touching one axis
9498 // without the other) trips at caixa-core test time. Peer of the
9499 // sibling forward-projection partition pin
9500 // [`restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
9501 // (523157d) — extends the round-trip discipline onto the
9502 // second-of-two M2-OTP-shape closed-set typed enum on the caixa
9503 // surface, closing the two-way `Self ↔ &'static str` round-trip
9504 // on the trait-idiomatic pair (`From<Self> for &'static str` +
9505 // `TryFrom<&str> for Self`) as well as the pre-existing method-
9506 // named pair (`as_str` + `from_wire`).
9507 for &variant in RestartPolicy::ALL {
9508 let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
9509 let via_method: &'static str = variant.as_str();
9510 assert_eq!(
9511 via_trait, via_method,
9512 "From<RestartPolicy> for &'static str and \
9513 RestartPolicy::as_str must resolve identically on \
9514 RestartPolicy::{variant:?} — divergence signals the \
9515 two forward-projection paths have drifted onto different \
9516 emit-sets"
9517 );
9518 }
9519 // Round-trip witness: every arm's forward `From` output re-parses
9520 // through the paired trait-idiomatic reverse `TryFrom<&str>` back
9521 // to the original variant. Closes the two-way `RestartPolicy ↔
9522 // &'static str` round-trip on the trait-idiomatic axis pair,
9523 // mirroring the pre-existing method-named `as_str` + `from_wire`
9524 // round-trip on the substrate-primitive axis pair.
9525 for &variant in RestartPolicy::ALL {
9526 let emitted: &'static str = variant.into();
9527 let re_parsed: Result<RestartPolicy, ()> =
9528 <RestartPolicy as TryFrom<&str>>::try_from(emitted);
9529 assert_eq!(
9530 re_parsed,
9531 Ok(variant),
9532 "trait-idiomatic axis pair must round-trip \
9533 RestartPolicy::{variant:?} through `.into::<&'static \
9534 str>()` and back through `TryFrom<&str>` — a break signals \
9535 the forward-emit and reverse-parse axes have drifted onto \
9536 different vocabularies"
9537 );
9538 }
9539 }
9540
9541 #[test]
9542 fn restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
9543 // Fail-before-pass-after byte-parity pin on the newly lifted
9544 // `impl From<&RestartPolicy> for &'static str` — asserts the
9545 // borrowed-input standard-library trait impl and the substrate-
9546 // primitive [`RestartPolicy::as_str`] `pub const fn` accessor
9547 // resolve to the same three-arm emit-set across every arm the
9548 // exhaustive [`RestartPolicy::ALL`] slice enumerates. Rust's
9549 // `From` trait does not auto-derive the borrowed-input sibling
9550 // from a paired owned-input impl (no `impl<T, U> From<&T> for U
9551 // where T: Copy, U: From<T>` blanket in `core`), so the
9552 // borrowed-input axis is a distinct trait-idiomatic surface
9553 // that a `.iter().map(Into::into)` shape over
9554 // [`RestartPolicy::ALL`] (whose iterator yields
9555 // `&RestartPolicy`, not `RestartPolicy`) reaches through this
9556 // impl and no other — the paired owned-input
9557 // [`From<RestartPolicy>`] impl requires an explicit `.copied()`
9558 // / dereference before the trait fires. Materializes the
9559 // `<&'static str as From<&RestartPolicy>>::from` output in a
9560 // `const`-shape binding to make the `'static` lifetime promise
9561 // a build-time invariant.
9562 const PERMANENT: &str = RestartPolicy::Permanent.as_str();
9563 const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
9564 const TRANSIENT: &str = RestartPolicy::Transient.as_str();
9565 for variant in RestartPolicy::ALL {
9566 let via_trait: &'static str = <&'static str as From<&RestartPolicy>>::from(variant);
9567 let via_method: &'static str = variant.as_str();
9568 assert_eq!(
9569 via_trait, via_method,
9570 "From<&RestartPolicy> for &'static str impl must round-trip \
9571 &RestartPolicy::{variant:?} to the same lifted \
9572 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
9573 returns — divergence signals a silent detour off the \
9574 substrate-primitive accessor"
9575 );
9576 let via_into: &'static str = variant.into();
9577 assert_eq!(
9578 via_into, via_method,
9579 "Into<&'static str>::into on &RestartPolicy::{variant:?} \
9580 must byte-equal RestartPolicy::as_str on the same input — \
9581 the blanket-derived Into shape must resolve to the same \
9582 as_str dispatch as the explicit From impl"
9583 );
9584 }
9585 assert_eq!(
9586 [PERMANENT, TEMPORARY, TRANSIENT],
9587 [
9588 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
9589 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
9590 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
9591 ],
9592 "const-context RestartPolicy::as_str must resolve to the three \
9593 lifted SUPERVISOR_CHILD_RESTART_* consts — the borrowed-input \
9594 From<&RestartPolicy> for &'static str impl inherits its \
9595 `'static` lifetime promise from the same accessor the \
9596 owned-input sibling routes through"
9597 );
9598 }
9599
9600 #[test]
9601 fn restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
9602 // Cross-axis partition pin: the paired trait-idiomatic
9603 // owned-input `From<RestartPolicy> for &'static str` (9fb37d0
9604 // campaign-shape) and borrowed-input `From<&RestartPolicy> for
9605 // &'static str` (this lift) forward projections must resolve
9606 // identically on every arm, locking the two input-shape paths
9607 // together so any future detour trips at caixa-core test time.
9608 // Then a witness that a `.iter().map(Into::into)` pipe over
9609 // [`RestartPolicy::ALL`] (whose iterator yields
9610 // `&RestartPolicy`) materializes the three-arm accept-set
9611 // through the borrowed-input axis alone — the exact shape a
9612 // future wasm-operator per-child post-exit restart-decision
9613 // diagnostic line, a future substrate-wide per-arm diagnostic
9614 // column, or a
9615 // `HashMap::<&'static str, RestartPolicy>::from_iter(
9616 // RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
9617 // per-policy lookup reaches through — closing the two-way
9618 // owned/borrowed input-shape symmetry on the forward-projection
9619 // trait-idiomatic axis. Peer of the sibling
9620 // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9621 // (64aa742) /
9622 // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9623 // (5ab993a) /
9624 // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9625 // (807b0b5) /
9626 // [`restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9627 // (e941836) partition pins on the sibling closed-set typed-enum
9628 // discriminator axes — extends the borrowed-input axis
9629 // discipline onto the second-of-two M2 OTP-shape closed-set
9630 // typed enum on the caixa surface (per-child restart-decision
9631 // policy). Also closes the direct two-way `&Self → &'static
9632 // str → Self` round-trip via the paired [`TryFrom<&str>`] axis
9633 // — unlike the peer [`crate::CaixaKind`] axis pair (whose
9634 // forward `From` emits lowercase Portuguese diagnostic bytes
9635 // while the reverse `TryFrom` parses `PascalCase` wire bytes,
9636 // forcing the round-trip through an intermediate wire-vocab
9637 // hop), the [`RestartPolicy::as_str`] emit and
9638 // [`RestartPolicy::from_wire`] parse share the same
9639 // `PascalCase` vocabulary by construction, so the borrowed-
9640 // input forward axis and the reverse axis compose directly.
9641 for &variant in RestartPolicy::ALL {
9642 let owned: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
9643 let borrowed: &'static str = <&'static str as From<&RestartPolicy>>::from(&variant);
9644 assert_eq!(
9645 owned, borrowed,
9646 "From<RestartPolicy> and From<&RestartPolicy> for \
9647 &'static str must resolve identically on \
9648 RestartPolicy::{variant:?} — divergence signals the \
9649 owned-input and borrowed-input forward-projection paths \
9650 have drifted onto different emit-sets"
9651 );
9652 }
9653 let via_iter: Vec<&'static str> = RestartPolicy::ALL.iter().map(Into::into).collect();
9654 let via_method: Vec<&'static str> = RestartPolicy::ALL.iter().map(|p| p.as_str()).collect();
9655 assert_eq!(
9656 via_iter, via_method,
9657 "`.iter().map(Into::into)` over RestartPolicy::ALL must \
9658 byte-equal `.iter().map(|p| p.as_str())` on every arm — the \
9659 borrowed-input `From<&RestartPolicy> for &'static str` axis \
9660 is what makes the `.iter().map(Into::into)` shape route \
9661 through the substrate-primitive `RestartPolicy::as_str` \
9662 accessor rather than through a per-call-site `.copied()` / \
9663 dereference detour"
9664 );
9665 for variant in RestartPolicy::ALL {
9666 let emitted: &'static str = variant.into();
9667 let re_parsed: Result<RestartPolicy, ()> =
9668 <RestartPolicy as TryFrom<&str>>::try_from(emitted);
9669 assert_eq!(
9670 re_parsed,
9671 Ok(*variant),
9672 "trait-idiomatic borrowed-input forward-projection + \
9673 reverse-projection axis pair must round-trip \
9674 &RestartPolicy::{variant:?} through `.into::<&'static \
9675 str>()` (via the borrowed-input axis) and back through \
9676 `TryFrom<&str>` — a break signals the borrowed-input \
9677 forward-emit and reverse-parse axes have drifted onto \
9678 different vocabularies"
9679 );
9680 }
9681 }
9682
9683 #[test]
9684 fn restart_policy_from_into_owned_string_routes_through_as_str_accessor() {
9685 // Fail-before-pass-after byte-parity pin on the newly lifted
9686 // `impl From<RestartPolicy> for String` — asserts the
9687 // owned-`String`-returning standard-library trait impl and the
9688 // substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
9689 // accessor resolve to the same three-arm emit-set across every
9690 // arm the exhaustive [`RestartPolicy::ALL`] slice enumerates.
9691 // Rust's standard library does not carry a blanket
9692 // `impl<T: AsRef<str>> From<T> for String` (nor an
9693 // `impl<T: fmt::Display> From<T> for String`), so the
9694 // owned-`String` forward-projection axis is a distinct
9695 // trait-idiomatic surface that a `let key: String =
9696 // policy.into();`-shaped call site reaches through this impl
9697 // and no other — the paired sibling `From<RestartPolicy> for
9698 // &'static str` impl forces every owned-`String` call site
9699 // through an explicit `.to_owned()` / `String::from`
9700 // restatement. Peer of the first-mover
9701 // [`restart_strategy_from_into_owned_string_routes_through_as_str_accessor`]
9702 // (7baa18a) — extends the trait-idiomatic owned-`String`
9703 // forward-projection axis onto the second-of-two M2 OTP-shape
9704 // closed-set typed enums on the caixa surface (per-child
9705 // restart-decision-policy sibling on the same M2 `:supervisor`
9706 // slot).
9707 for &variant in RestartPolicy::ALL {
9708 let via_trait: String = <String as From<RestartPolicy>>::from(variant);
9709 let via_method: &'static str = variant.as_str();
9710 assert_eq!(
9711 via_trait.as_str(),
9712 via_method,
9713 "From<RestartPolicy> for String impl must round-trip \
9714 RestartPolicy::{variant:?} to the same lifted \
9715 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
9716 returns — divergence signals a silent detour off the \
9717 substrate-primitive accessor"
9718 );
9719 let via_into: String = variant.into();
9720 assert_eq!(
9721 via_into.as_str(),
9722 via_method,
9723 "Into<String>::into on RestartPolicy::{variant:?} must \
9724 byte-equal RestartPolicy::as_str on the same input — the \
9725 blanket-derived Into shape must resolve to the same as_str \
9726 dispatch as the explicit From impl"
9727 );
9728 }
9729 }
9730
9731 #[test]
9732 fn restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm() {
9733 // Cross-axis partition pin: the paired trait-idiomatic
9734 // owned-`String` `From<RestartPolicy> for String` (this lift)
9735 // and owned-`&'static str` `From<RestartPolicy> for &'static
9736 // str` (9fb37d0) forward projections must resolve identically
9737 // on every arm, locking the two return-type-shape paths
9738 // together so any future detour trips at caixa-core test time.
9739 // Also byte-parity witness against the sibling
9740 // [`ToString::to_string`] surface routed through
9741 // [`std::fmt::Display`] — the three owned-heap-string paths
9742 // (`.into::<String>()`, `String::from`, `.to_string()`) must
9743 // resolve identically on every arm so a future consumer that
9744 // picks any of the three lands on the same lifted
9745 // SUPERVISOR_CHILD_RESTART_* const. Then a `.iter().copied()
9746 // .map(String::from)` pipe witness over [`RestartPolicy::ALL`]
9747 // that materializes the three-arm accept-set through the
9748 // owned-`String` axis alone — the exact shape a future
9749 // wasm-operator per-child post-exit restart-decision
9750 // diagnostic line composer or a
9751 // `HashMap::<String, RestartPolicy>::from_iter(
9752 // RestartPolicy::ALL.iter().copied().map(|p| (p.into(), p)))`-style
9753 // owned-key per-policy lookup reaches through — closing the
9754 // owned-`String` forward-projection axis's iterator-pipe
9755 // shape. Then a direct round-trip witness through the paired
9756 // trait-idiomatic reverse [`TryFrom<&str>`] axis on the
9757 // owned-`String`'s [`String::as_str`] borrow that closes the
9758 // two-way `Self → String → Self` round-trip on the trait-
9759 // idiomatic owned-`String` forward + reverse axis pair —
9760 // unlike the peer [`crate::CaixaKind`] axis pair (whose
9761 // forward `From` emits lowercase Portuguese diagnostic bytes
9762 // while the reverse `TryFrom` parses `PascalCase` wire bytes,
9763 // forcing the round-trip through an intermediate wire-vocab
9764 // hop), the [`RestartPolicy::as_str`] emit and
9765 // [`RestartPolicy::from_wire`] parse share the same
9766 // `PascalCase` vocabulary by construction, so the owned-
9767 // `String` forward axis and the reverse axis compose directly.
9768 for &variant in RestartPolicy::ALL {
9769 let owned_string: String = <String as From<RestartPolicy>>::from(variant);
9770 let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
9771 assert_eq!(
9772 owned_string.as_str(),
9773 owned_static,
9774 "From<RestartPolicy> for String and From<RestartPolicy> \
9775 for &'static str must resolve identically on \
9776 RestartPolicy::{variant:?} — divergence signals the \
9777 owned-`String` and owned-`&'static str` forward-projection \
9778 return-type-shape paths have drifted onto different \
9779 emit-sets"
9780 );
9781 let via_to_string: String = variant.to_string();
9782 assert_eq!(
9783 owned_string, via_to_string,
9784 "From<RestartPolicy> for String must byte-equal \
9785 RestartPolicy::to_string on RestartPolicy::{variant:?} — \
9786 divergence signals the trait-idiomatic owned-`String` \
9787 forward-projection axis and the ToString-through-Display \
9788 axis have drifted onto different emit-sets"
9789 );
9790 }
9791 let via_iter: Vec<String> = RestartPolicy::ALL
9792 .iter()
9793 .copied()
9794 .map(String::from)
9795 .collect();
9796 let via_method: Vec<String> = RestartPolicy::ALL
9797 .iter()
9798 .map(|p| p.as_str().to_owned())
9799 .collect();
9800 assert_eq!(
9801 via_iter, via_method,
9802 "`.iter().copied().map(String::from)` over RestartPolicy::ALL \
9803 must byte-equal `.iter().map(|p| p.as_str().to_owned())` on \
9804 every arm — the owned-`String` `From<RestartPolicy> for \
9805 String` axis is what makes the `String::from` composition \
9806 route through the substrate-primitive `RestartPolicy::as_str` \
9807 accessor rather than through a per-call-site `.to_owned()` / \
9808 `String::from(policy.as_str())` detour"
9809 );
9810 for &variant in RestartPolicy::ALL {
9811 let emitted: String = variant.into();
9812 let re_parsed: Result<RestartPolicy, ()> =
9813 <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
9814 assert_eq!(
9815 re_parsed,
9816 Ok(variant),
9817 "trait-idiomatic owned-`String` forward-projection + \
9818 reverse-projection axis pair must round-trip \
9819 RestartPolicy::{variant:?} through `.into::<String>()` \
9820 and back through `TryFrom<&str>` on the owned-`String`'s \
9821 String::as_str borrow — a break signals the owned-`String` \
9822 forward-emit and reverse-parse axes have drifted onto \
9823 different vocabularies"
9824 );
9825 }
9826 }
9827
9828 #[test]
9829 fn restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
9830 // Fail-before-pass-after byte-parity pin on the newly lifted
9831 // `impl From<&RestartPolicy> for String` — asserts the
9832 // borrowed-input owned-`String`-returning standard-library
9833 // trait impl and the substrate-primitive
9834 // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
9835 // the same three-arm emit-set across every arm the exhaustive
9836 // [`RestartPolicy::ALL`] slice enumerates. Rust's standard
9837 // library does not carry a blanket `impl<T: AsRef<str>>
9838 // From<&T> for String` (nor an `impl<T: fmt::Display> From<&T>
9839 // for String`), so the borrowed-input owned-`String` forward-
9840 // projection axis is a distinct trait-idiomatic surface that a
9841 // `let key: String = (&policy).into();`-shaped call site
9842 // reaches through this impl and no other — the paired sibling
9843 // `From<RestartPolicy> for String` impl forces every borrowed-
9844 // input call site through an explicit `Copy` deref
9845 // (`String::from(*policy)`) or an `.as_str().to_owned()` /
9846 // `.to_string()` detour. Peer of the first-mover
9847 // [`restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
9848 // (579385f) — extends the trait-idiomatic borrowed-input
9849 // owned-`String` forward-projection axis onto the second-of-
9850 // two M2 OTP-shape closed-set typed enums on the caixa surface
9851 // (per-child restart-decision-policy sibling on the same M2
9852 // `:supervisor` slot).
9853 for &variant in RestartPolicy::ALL {
9854 let via_trait: String = <String as From<&RestartPolicy>>::from(&variant);
9855 let via_method: &'static str = variant.as_str();
9856 assert_eq!(
9857 via_trait.as_str(),
9858 via_method,
9859 "From<&RestartPolicy> for String impl must round-trip \
9860 &RestartPolicy::{variant:?} to the same lifted \
9861 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
9862 returns — divergence signals a silent detour off the \
9863 substrate-primitive accessor"
9864 );
9865 let via_into: String = (&variant).into();
9866 assert_eq!(
9867 via_into.as_str(),
9868 via_method,
9869 "Into<String>::into on &RestartPolicy::{variant:?} must \
9870 byte-equal RestartPolicy::as_str on the same input — \
9871 the blanket-derived Into shape must resolve to the \
9872 same as_str dispatch as the explicit From impl"
9873 );
9874 }
9875 }
9876
9877 #[test]
9878 fn restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
9879 // Cross-axis partition pin: the newly lifted trait-idiomatic
9880 // borrowed-input owned-`String` `From<&RestartPolicy> for
9881 // String` (this lift), the paired owned-input owned-`String`
9882 // `From<RestartPolicy> for String` (7851725), the paired
9883 // borrowed-input owned-`&'static str` `From<&RestartPolicy>
9884 // for &'static str` (842c7f3), and the paired owned-input
9885 // owned-`&'static str` `From<RestartPolicy> for &'static str`
9886 // (9fb37d0) — every corner of the `{Self, &Self} × {&'static
9887 // str, String}` 2×2 trait-idiomatic projection family — must
9888 // resolve identically on every arm, locking the four
9889 // return-shape × input-shape paths together so any future
9890 // detour trips at caixa-core test time. Also byte-parity
9891 // witness against the sibling [`ToString::to_string`] surface
9892 // routed through [`std::fmt::Display`] and a direct round-trip
9893 // witness through the paired trait-idiomatic reverse
9894 // [`TryFrom<&str>`] axis on the owned-`String`'s
9895 // [`String::as_str`] borrow that closes the two-way
9896 // `&Self → String → Self` round-trip on the trait-idiomatic
9897 // borrowed-input owned-`String` forward + reverse axis pair.
9898 // Peer of the first-mover
9899 // [`restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
9900 // (579385f) — closes the whole `{Self, &Self} × {&'static str,
9901 // String}` 2×2 projection corner on both M2 OTP-shape sibling
9902 // peers.
9903 for &variant in RestartPolicy::ALL {
9904 let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
9905 let owned_string: String = <String as From<RestartPolicy>>::from(variant);
9906 let borrowed_static: &'static str =
9907 <&'static str as From<&RestartPolicy>>::from(&variant);
9908 let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
9909 assert_eq!(
9910 borrowed_string, owned_string,
9911 "From<&RestartPolicy> for String and From<RestartPolicy> \
9912 for String must resolve identically on \
9913 RestartPolicy::{variant:?} — divergence signals the \
9914 borrowed-input and owned-input owned-`String` \
9915 forward-projection input-shape paths have drifted onto \
9916 different emit-sets"
9917 );
9918 assert_eq!(
9919 borrowed_string.as_str(),
9920 borrowed_static,
9921 "From<&RestartPolicy> for String and From<&RestartPolicy> \
9922 for &'static str must resolve identically on \
9923 RestartPolicy::{variant:?} — divergence signals the \
9924 borrowed-input `&'static str` and owned-`String` \
9925 return-shape paths have drifted onto different \
9926 emit-sets"
9927 );
9928 assert_eq!(
9929 borrowed_string.as_str(),
9930 owned_static,
9931 "From<&RestartPolicy> for String and From<RestartPolicy> \
9932 for &'static str must resolve identically on \
9933 RestartPolicy::{variant:?} — divergence signals a \
9934 break in the diagonal corner of the {{Self, &Self}} × \
9935 {{&'static str, String}} 2×2 trait-idiomatic \
9936 projection family"
9937 );
9938 let via_to_string: String = variant.to_string();
9939 assert_eq!(
9940 borrowed_string, via_to_string,
9941 "From<&RestartPolicy> for String must byte-equal \
9942 RestartPolicy::to_string on RestartPolicy::{variant:?} \
9943 — divergence signals the trait-idiomatic borrowed-input \
9944 owned-`String` forward-projection axis and the \
9945 ToString-through-Display axis have drifted onto \
9946 different emit-sets"
9947 );
9948 }
9949 let via_iter: Vec<String> = RestartPolicy::ALL.iter().map(String::from).collect();
9950 let via_method: Vec<String> = RestartPolicy::ALL
9951 .iter()
9952 .map(|p| p.as_str().to_owned())
9953 .collect();
9954 assert_eq!(
9955 via_iter, via_method,
9956 "`.iter().map(String::from)` over RestartPolicy::ALL — a \
9957 call site whose iteration axis holds `&RestartPolicy` by \
9958 construction — must byte-equal `.iter().map(|p| \
9959 p.as_str().to_owned())` on every arm — the borrowed-input \
9960 owned-`String` `From<&RestartPolicy> for String` axis is \
9961 what makes the `String::from` composition route through \
9962 the substrate-primitive `RestartPolicy::as_str` accessor \
9963 without a spurious `Copy` deref (which would only be \
9964 reachable through the owned-input `From<RestartPolicy> \
9965 for String` axis by first calling `.copied()` on the \
9966 iterator)"
9967 );
9968 for &variant in RestartPolicy::ALL {
9969 let emitted: String = (&variant).into();
9970 let re_parsed: Result<RestartPolicy, ()> =
9971 <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
9972 assert_eq!(
9973 re_parsed,
9974 Ok(variant),
9975 "trait-idiomatic borrowed-input owned-`String` \
9976 forward-projection + reverse-projection axis pair must \
9977 round-trip &RestartPolicy::{variant:?} through \
9978 `.into::<String>()` on the borrowed-input surface and \
9979 back through `TryFrom<&str>` on the owned-`String`'s \
9980 String::as_str borrow — a break signals the \
9981 borrowed-input owned-`String` forward-emit and \
9982 reverse-parse axes have drifted onto different \
9983 vocabularies"
9984 );
9985 }
9986 }
9987
9988 #[test]
9989 fn restart_policy_from_into_static_cow_str_routes_through_as_str_accessor() {
9990 // Fail-before-pass-after byte-parity pin on the newly lifted
9991 // `impl From<RestartPolicy> for std::borrow::Cow<'static, str>` —
9992 // asserts the standard-library trait impl and the substrate-
9993 // primitive [`super::RestartPolicy::as_str`] `pub const fn`
9994 // accessor resolve to the same three-arm emit-set across every
9995 // arm the exhaustive [`super::RestartPolicy::ALL`] slice
9996 // enumerates. Rust's standard library does not carry a blanket
9997 // `impl<T: AsRef<str>> From<T> for Cow<'static, str>` (nor an
9998 // `impl<T: fmt::Display> From<T> for Cow<'static, str>`), so
9999 // the `Cow<'static, str>` forward-projection axis is a
10000 // distinct trait-idiomatic surface that a
10001 // `let key: Cow<'static, str> = policy.into();`-shaped call
10002 // site reaches through this impl and no other — the paired
10003 // sibling `From<RestartPolicy> for &'static str` and
10004 // `From<RestartPolicy> for String` impls force every
10005 // `Cow<'static, str>`-parameterized call site through a
10006 // `Cow::Borrowed(policy.as_str())` /
10007 // `Cow::Owned(policy.to_string())` composition whose type
10008 // bounds have no compile-time link back to the substrate
10009 // primitive.
10010 //
10011 // Also asserts the projection lands on the zero-alloc
10012 // [`std::borrow::Cow::Borrowed`] arm (not the
10013 // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
10014 // [`super::RestartPolicy::as_str`] accessor's `&'static str`
10015 // return lifetime by construction makes the borrowed arm the
10016 // type-correct projection with no runtime allocation. Any
10017 // future silent detour that routes the impl through the owned
10018 // arm (an accidental `Cow::Owned(policy.to_string())` rewrite
10019 // that would allocate on every call site where the
10020 // `&'static str` return of [`super::RestartPolicy::as_str`]
10021 // makes the zero-alloc borrowed projection type-correct) trips
10022 // at caixa-core test time under the
10023 // [`std::borrow::Cow::Borrowed`] discriminator witness rather
10024 // than at a downstream `Cow<'static, str>`-bound consumer's
10025 // silent allocation.
10026 //
10027 // Second peer on the substrate-wide trait-idiomatic
10028 // [`std::borrow::Cow<'static, str>`] forward-projection family
10029 // to extend the axis off the top-level [`super::CaixaKind`]
10030 // enum (99c1735 owned-input, d45c409 borrowed-input) onto the
10031 // second (and second-of-two-in-M2) M2 OTP-shape closed-set
10032 // fieldless typed enum peer on the caixa surface — closes the
10033 // M2 OTP-shape tier of the campaign on the owned-input axis
10034 // (both sibling peers, `RestartStrategy` and `RestartPolicy`,
10035 // now carry the owned-input Cow<'static, str> forward
10036 // projection).
10037 for &variant in RestartPolicy::ALL {
10038 let via_trait: std::borrow::Cow<'static, str> =
10039 <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
10040 let via_method: &'static str = variant.as_str();
10041 assert_eq!(
10042 via_trait.as_ref(),
10043 via_method,
10044 "From<RestartPolicy> for Cow<'static, str> impl must \
10045 round-trip RestartPolicy::{variant:?} to the same \
10046 lifted SUPERVISOR_CHILD_RESTART_* const \
10047 RestartPolicy::as_str returns — divergence signals a \
10048 silent detour off the substrate-primitive accessor"
10049 );
10050 assert!(
10051 matches!(via_trait, std::borrow::Cow::Borrowed(_)),
10052 "From<RestartPolicy> for Cow<'static, str> impl must \
10053 land on the zero-alloc Cow::Borrowed arm on \
10054 RestartPolicy::{variant:?} — a Cow::Owned outcome \
10055 signals the projection has silently allocated where \
10056 the substrate-primitive RestartPolicy::as_str \
10057 `&'static str` return makes the borrowed arm the \
10058 type-correct projection"
10059 );
10060 let via_into: std::borrow::Cow<'static, str> = variant.into();
10061 assert_eq!(
10062 via_into.as_ref(),
10063 via_method,
10064 "Into<Cow<'static, str>>::into on \
10065 RestartPolicy::{variant:?} must byte-equal \
10066 RestartPolicy::as_str on the same input — the \
10067 blanket-derived Into shape must resolve to the same \
10068 as_str dispatch as the explicit From impl"
10069 );
10070 assert!(
10071 matches!(via_into, std::borrow::Cow::Borrowed(_)),
10072 "Into<Cow<'static, str>>::into on \
10073 RestartPolicy::{variant:?} must land on the \
10074 zero-alloc Cow::Borrowed arm — the blanket-derived \
10075 Into shape must resolve to the same Cow::Borrowed \
10076 dispatch as the explicit From impl"
10077 );
10078 }
10079 }
10080
10081 #[test]
10082 fn restart_policy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
10083 // Cross-axis partition pin: the newly lifted trait-idiomatic
10084 // `From<RestartPolicy> for std::borrow::Cow<'static, str>`
10085 // (this lift), the paired owned-input `From<RestartPolicy>
10086 // for &'static str` (9fb37d0), and the paired owned-input
10087 // `From<RestartPolicy> for String` (7851725) forward
10088 // projections must resolve identically on every arm, locking
10089 // the three return-shape paths together by construction so any
10090 // future detour trips at caixa-core test time. Also byte-parity
10091 // witness against the sibling [`ToString::to_string`] surface
10092 // routed through [`std::fmt::Display`] — every owned-heap-
10093 // string path (the `Cow::Owned` promotion of this axis's
10094 // `.into_owned()`, `From<RestartPolicy> for String`, and
10095 // `.to_string()`) resolves to the same lifted
10096 // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const per arm.
10097 //
10098 // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
10099 // witness over [`super::RestartPolicy::ALL`] that
10100 // materializes the three-arm accept-set through the
10101 // [`std::borrow::Cow<'static, str>`] axis alone — the exact
10102 // shape a future `axum::response::IntoResponse` per-policy
10103 // rejection-body composer, a future M4 admission-webhook
10104 // per-policy rejection-reason emitter whose typing rules out
10105 // the sibling [`AsRef<str>`] borrowed return, or a future
10106 // substrate-wide per-policy diagnostic surface that binds
10107 // through a [`Cow<'static, str>`] boundary reaches through.
10108 // The pipe witness also pins the zero-alloc discipline: every
10109 // element in the collected vector satisfies the
10110 // [`std::borrow::Cow::Borrowed`] arm predicate, so a future
10111 // accidental silent-allocation regression on the pipe's
10112 // iteration axis is a caixa-core-test-time failure. Peer of
10113 // the first-mover
10114 // [`restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
10115 // (7dd28b3) on the sibling M2 OTP-shape sibling-restart axis
10116 // — closes the whole owned-input `Cow<'static, str>` +
10117 // paired `{&'static str, String}` cross-axis-parity corner on
10118 // both M2 OTP-shape sibling peers.
10119 for &variant in RestartPolicy::ALL {
10120 let via_cow: std::borrow::Cow<'static, str> =
10121 <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
10122 let via_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
10123 let via_string: String = <String as From<RestartPolicy>>::from(variant);
10124 assert_eq!(
10125 via_cow.as_ref(),
10126 via_static,
10127 "From<RestartPolicy> for Cow<'static, str> and \
10128 From<RestartPolicy> for &'static str must resolve \
10129 identically on RestartPolicy::{variant:?} — \
10130 divergence signals the Cow<'static, str> and \
10131 &'static str return-shape paths have drifted onto \
10132 different emit-sets"
10133 );
10134 assert_eq!(
10135 via_cow.as_ref(),
10136 via_string.as_str(),
10137 "From<RestartPolicy> for Cow<'static, str> and \
10138 From<RestartPolicy> for String must resolve \
10139 identically on RestartPolicy::{variant:?} — \
10140 divergence signals the Cow<'static, str> and String \
10141 return-shape paths have drifted onto different \
10142 emit-sets"
10143 );
10144 let via_to_string: String = variant.to_string();
10145 assert_eq!(
10146 via_cow.as_ref(),
10147 via_to_string.as_str(),
10148 "From<RestartPolicy> for Cow<'static, str> must \
10149 byte-equal RestartPolicy::to_string on \
10150 RestartPolicy::{variant:?} — divergence signals the \
10151 trait-idiomatic Cow<'static, str> forward-projection \
10152 axis and the ToString-through-Display axis have \
10153 drifted onto different emit-sets"
10154 );
10155 }
10156 let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
10157 .iter()
10158 .copied()
10159 .map(std::borrow::Cow::from)
10160 .collect();
10161 let via_method: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
10162 .iter()
10163 .map(|p| std::borrow::Cow::Borrowed(p.as_str()))
10164 .collect();
10165 assert_eq!(
10166 via_iter, via_method,
10167 "`.iter().copied().map(Cow::from)` over \
10168 RestartPolicy::ALL must byte-equal `.iter().map(|p| \
10169 Cow::Borrowed(p.as_str()))` on every arm — the \
10170 trait-idiomatic `From<RestartPolicy> for Cow<'static, \
10171 str>` axis is what makes the `Cow::from` composition \
10172 route through the substrate-primitive \
10173 `RestartPolicy::as_str` accessor with the zero-alloc \
10174 Cow::Borrowed arm by construction, rather than a \
10175 per-call-site `Cow::Owned(policy.to_string())` \
10176 allocation"
10177 );
10178 for cow in &via_iter {
10179 assert!(
10180 matches!(cow, std::borrow::Cow::Borrowed(_)),
10181 "every element of the \
10182 .iter().copied().map(Cow::from) pipe over \
10183 RestartPolicy::ALL must land on the zero-alloc \
10184 Cow::Borrowed arm — a Cow::Owned outcome on any arm \
10185 signals the pipe's iteration axis has silently \
10186 allocated where the substrate-primitive \
10187 RestartPolicy::as_str `&'static str` return makes \
10188 the borrowed arm the type-correct projection"
10189 );
10190 }
10191 }
10192
10193 #[test]
10194 fn restart_policy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
10195 // Fail-before-pass-after byte-parity pin on the newly lifted
10196 // `impl From<&RestartPolicy> for std::borrow::Cow<'static, str>` —
10197 // asserts the borrowed-input standard-library trait impl and
10198 // the substrate-primitive [`super::RestartPolicy::as_str`]
10199 // `pub const fn` accessor resolve to the same three-arm emit-
10200 // set across every arm the exhaustive
10201 // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
10202 // standard library does not carry a blanket
10203 // `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor a
10204 // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
10205 // the borrowed-input `Cow<'static, str>` forward-projection
10206 // axis is a distinct trait-idiomatic surface that a
10207 // `let key: Cow<'static, str> = (&policy).into();`-shaped
10208 // call site or a
10209 // `RestartPolicy::ALL.iter().map(Cow::from)`-shaped pipe
10210 // reaches through this impl and no other — the paired owned-
10211 // input `From<RestartPolicy> for Cow<'static, str>` impl
10212 // (0612398) forces every borrowed-input call site through an
10213 // explicit `Copy` deref (`Cow::from(*policy)`) or a
10214 // `Cow::Borrowed(policy.as_str())` open-code whose type
10215 // bounds have no compile-time link back to the substrate
10216 // primitive.
10217 //
10218 // Also asserts the projection lands on the zero-alloc
10219 // [`std::borrow::Cow::Borrowed`] arm (not the
10220 // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
10221 // [`super::RestartPolicy::as_str`] accessor's `&'static str`
10222 // return lifetime by construction makes the borrowed arm the
10223 // type-correct projection with no runtime allocation on the
10224 // borrowed-input surface just as on the paired owned-input
10225 // surface.
10226 //
10227 // Closes the `{Self, &Self}` input-shape corner on the M2
10228 // OTP-shape per-child-restart [`Cow<'static, str>`] axis on
10229 // the second-of-two-in-M2 closed-set fieldless typed enum peer
10230 // on the caixa surface (`:supervisor :children :restart`),
10231 // exactly as d45c409 closed it on the top-level
10232 // [`super::CaixaKind`] one commit after the owning half
10233 // (99c1735) landed and as 9b3e4b3 closed it on the sibling
10234 // M2 OTP-shape [`super::RestartStrategy`] one commit after
10235 // (7dd28b3) landed. This lift closes the whole M2 OTP-shape
10236 // tier of the substrate-wide Cow<'static, str> forward-
10237 // projection campaign on both input-shape corners
10238 // ({Self, &Self}) of both M2 OTP-shape sibling peers.
10239 for &variant in RestartPolicy::ALL {
10240 let via_trait: std::borrow::Cow<'static, str> =
10241 <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
10242 let via_method: &'static str = variant.as_str();
10243 assert_eq!(
10244 via_trait.as_ref(),
10245 via_method,
10246 "From<&RestartPolicy> for Cow<'static, str> impl must \
10247 round-trip &RestartPolicy::{variant:?} to the same \
10248 lifted SUPERVISOR_CHILD_RESTART_* const \
10249 RestartPolicy::as_str returns — divergence signals a \
10250 silent detour off the substrate-primitive accessor"
10251 );
10252 assert!(
10253 matches!(via_trait, std::borrow::Cow::Borrowed(_)),
10254 "From<&RestartPolicy> for Cow<'static, str> impl must \
10255 land on the zero-alloc Cow::Borrowed arm on \
10256 &RestartPolicy::{variant:?} — a Cow::Owned outcome \
10257 signals the projection has silently allocated where \
10258 the substrate-primitive RestartPolicy::as_str \
10259 `&'static str` return makes the borrowed arm the \
10260 type-correct projection"
10261 );
10262 let via_into: std::borrow::Cow<'static, str> = (&variant).into();
10263 assert_eq!(
10264 via_into.as_ref(),
10265 via_method,
10266 "Into<Cow<'static, str>>::into on \
10267 &RestartPolicy::{variant:?} must byte-equal \
10268 RestartPolicy::as_str on the same input — the \
10269 blanket-derived Into shape must resolve to the same \
10270 as_str dispatch as the explicit From impl"
10271 );
10272 assert!(
10273 matches!(via_into, std::borrow::Cow::Borrowed(_)),
10274 "Into<Cow<'static, str>>::into on \
10275 &RestartPolicy::{variant:?} must land on the \
10276 zero-alloc Cow::Borrowed arm — the blanket-derived \
10277 Into shape must resolve to the same Cow::Borrowed \
10278 dispatch as the explicit From impl"
10279 );
10280 }
10281 }
10282
10283 #[test]
10284 fn restart_policy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
10285 // Cross-axis partition pin: the newly lifted trait-idiomatic
10286 // borrowed-input `From<&RestartPolicy> for
10287 // std::borrow::Cow<'static, str>` (this lift), the paired
10288 // owned-input `From<RestartPolicy> for
10289 // std::borrow::Cow<'static, str>` (0612398), the paired
10290 // borrowed-input owned-`&'static str` `From<&RestartPolicy>
10291 // for &'static str`, and the paired borrowed-input owned-
10292 // `String` `From<&RestartPolicy> for String` must resolve
10293 // identically on every arm, locking the four
10294 // return-shape × input-shape paths together by construction so
10295 // any future detour trips at caixa-core test time. Also byte-
10296 // parity witness against the sibling [`ToString::to_string`]
10297 // surface routed through [`std::fmt::Display`] — every owned-
10298 // heap-string path (this axis's `.into_owned()` promotion, the
10299 // paired [`From<&RestartPolicy> for String`], and
10300 // `.to_string()`) resolves to the same lifted
10301 // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const per arm.
10302 //
10303 // Then a `.iter().map(std::borrow::Cow::from)` pipe witness
10304 // over [`super::RestartPolicy::ALL`] — whose iterator yields
10305 // `&RestartPolicy` by construction, so the borrowed-input
10306 // [`Cow<'static, str>`] axis is what routes the pipe through
10307 // the substrate-primitive [`super::RestartPolicy::as_str`]
10308 // accessor without a spurious [`Copy`] deref (which would only
10309 // be reachable through the owned-input
10310 // [`From<RestartPolicy> for Cow<'static, str>`] axis by first
10311 // calling `.copied()` on the iterator). The pipe witness also
10312 // pins the zero-alloc discipline: every element in the
10313 // collected vector satisfies the [`std::borrow::Cow::Borrowed`]
10314 // arm predicate, so a future accidental silent-allocation
10315 // regression on the pipe's iteration axis is a caixa-core-
10316 // test-time failure. Peer of the sibling
10317 // [`restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
10318 // (9b3e4b3) on the M2 OTP-shape sibling-restart axis — closes
10319 // the whole borrowed-input `Cow<'static, str>` +
10320 // paired `{&'static str, String}` cross-axis-parity corner on
10321 // both M2 OTP-shape sibling peers.
10322 for &policy in RestartPolicy::ALL {
10323 let borrowed_cow: std::borrow::Cow<'static, str> =
10324 <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&policy);
10325 let owned_cow: std::borrow::Cow<'static, str> =
10326 <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(policy);
10327 let borrowed_static: &'static str =
10328 <&'static str as From<&RestartPolicy>>::from(&policy);
10329 let borrowed_string: String = <String as From<&RestartPolicy>>::from(&policy);
10330 assert_eq!(
10331 borrowed_cow, owned_cow,
10332 "From<&RestartPolicy> for Cow<'static, str> and \
10333 From<RestartPolicy> for Cow<'static, str> must \
10334 resolve identically on RestartPolicy::{policy:?} — \
10335 divergence signals the borrowed-input and owned-input \
10336 Cow<'static, str> forward-projection input-shape \
10337 paths have drifted onto different emit-sets"
10338 );
10339 assert_eq!(
10340 borrowed_cow.as_ref(),
10341 borrowed_static,
10342 "From<&RestartPolicy> for Cow<'static, str> and \
10343 From<&RestartPolicy> for &'static str must resolve \
10344 identically on RestartPolicy::{policy:?} — \
10345 divergence signals the borrowed-input Cow<'static, \
10346 str> and &'static str return-shape paths have drifted \
10347 onto different emit-sets"
10348 );
10349 assert_eq!(
10350 borrowed_cow.as_ref(),
10351 borrowed_string.as_str(),
10352 "From<&RestartPolicy> for Cow<'static, str> and \
10353 From<&RestartPolicy> for String must resolve \
10354 identically on RestartPolicy::{policy:?} — \
10355 divergence signals the borrowed-input Cow<'static, \
10356 str> and owned-`String` return-shape paths have \
10357 drifted onto different emit-sets"
10358 );
10359 let via_to_string: String = policy.to_string();
10360 assert_eq!(
10361 borrowed_cow.as_ref(),
10362 via_to_string.as_str(),
10363 "From<&RestartPolicy> for Cow<'static, str> must \
10364 byte-equal RestartPolicy::to_string on \
10365 RestartPolicy::{policy:?} — divergence signals \
10366 the trait-idiomatic borrowed-input Cow<'static, str> \
10367 forward-projection axis and the ToString-through-\
10368 Display axis have drifted onto different emit-sets"
10369 );
10370 }
10371 let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
10372 .iter()
10373 .map(std::borrow::Cow::from)
10374 .collect();
10375 let via_method: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
10376 .iter()
10377 .map(|p| std::borrow::Cow::Borrowed(p.as_str()))
10378 .collect();
10379 assert_eq!(
10380 via_iter, via_method,
10381 "`.iter().map(Cow::from)` over RestartPolicy::ALL — a \
10382 call site whose iteration axis holds `&RestartPolicy` \
10383 by construction — must byte-equal `.iter().map(|p| \
10384 Cow::Borrowed(p.as_str()))` on every arm — the borrowed-\
10385 input Cow<'static, str> `From<&RestartPolicy> for \
10386 Cow<'static, str>` axis is what makes the `Cow::from` \
10387 composition route through the substrate-primitive \
10388 `RestartPolicy::as_str` accessor with the zero-alloc \
10389 Cow::Borrowed arm by construction and without a spurious \
10390 `Copy` deref (which would only be reachable through the \
10391 owned-input `From<RestartPolicy> for Cow<'static, str>` \
10392 axis by first calling `.copied()` on the iterator)"
10393 );
10394 for cow in &via_iter {
10395 assert!(
10396 matches!(cow, std::borrow::Cow::Borrowed(_)),
10397 "every element of the .iter().map(Cow::from) pipe \
10398 over RestartPolicy::ALL must land on the zero-\
10399 alloc Cow::Borrowed arm — a Cow::Owned outcome on \
10400 any arm signals the pipe's iteration axis has \
10401 silently allocated where the substrate-primitive \
10402 RestartPolicy::as_str `&'static str` return makes \
10403 the borrowed arm the type-correct projection"
10404 );
10405 }
10406 }
10407
10408 #[test]
10409 fn restart_policy_from_into_box_str_routes_through_as_str_accessor() {
10410 // Fail-before-pass-after byte-parity pin on the newly lifted
10411 // `impl From<RestartPolicy> for Box<str>` — asserts the
10412 // owned-input standard-library trait impl and the
10413 // substrate-primitive [`super::RestartPolicy::as_str`]
10414 // `pub const fn` accessor resolve to the same three-arm emit-
10415 // set across every arm the exhaustive
10416 // [`super::RestartPolicy::ALL`] slice enumerates. Extends the
10417 // substrate-wide `Box<str>` forward-projection campaign tier
10418 // opened one commit prior (69ef45c) on the paired sibling-
10419 // restart [`RestartStrategy`] onto the second (and third-and-
10420 // final) M2 OTP-shape closed-set fieldless typed enum peer on
10421 // the caixa surface (`:children :restart`), immediately after
10422 // the paired `Cow<'static, str>` axis (0612398 / b4dc55c)
10423 // closed the
10424 // `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
10425 // 2×3 corner on this enum. Rust's standard library carries
10426 // `impl From<&str> for Box<str>` and
10427 // `impl From<String> for Box<str>` but no blanket
10428 // `impl<T: AsRef<str>> From<T> for Box<str>`, so this axis is
10429 // a distinct trait-idiomatic surface that a
10430 // `let key: Box<str> = policy.into();`-shaped call site
10431 // reaches through this impl and no other — a paired
10432 // `Box::from(policy.as_str())` open-code has no compile-time
10433 // link back to the substrate primitive. Peer of the sibling
10434 // [`restart_strategy_from_into_box_str_routes_through_as_str_accessor`]
10435 // (69ef45c) — extends the trait-idiomatic owned-input
10436 // [`Box<str>`] forward-projection axis onto the third and
10437 // final M2-OTP-shape closed-set typed enum on the caixa
10438 // surface.
10439 for &variant in RestartPolicy::ALL {
10440 let via_trait: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
10441 let via_method: &'static str = variant.as_str();
10442 assert_eq!(
10443 via_trait.as_ref(),
10444 via_method,
10445 "From<RestartPolicy> for Box<str> impl must round-\
10446 trip RestartPolicy::{variant:?} to the same lifted \
10447 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
10448 returns — divergence signals a silent detour off the \
10449 substrate-primitive accessor"
10450 );
10451 let via_into: Box<str> = variant.into();
10452 assert_eq!(
10453 via_into.as_ref(),
10454 via_method,
10455 "Into<Box<str>>::into on RestartPolicy::{variant:?} \
10456 must byte-equal RestartPolicy::as_str on the same \
10457 input — the blanket-derived Into shape must resolve \
10458 to the same as_str dispatch as the explicit From impl"
10459 );
10460 }
10461 }
10462
10463 #[test]
10464 fn restart_policy_from_borrowed_into_box_str_routes_through_as_str_accessor() {
10465 // Fail-before-pass-after byte-parity pin on the newly lifted
10466 // `impl From<&RestartPolicy> for Box<str>` — asserts the
10467 // borrowed-input standard-library trait impl and the
10468 // substrate-primitive [`super::RestartPolicy::as_str`]
10469 // `pub const fn` accessor resolve to the same three-arm emit-
10470 // set across every arm the exhaustive
10471 // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
10472 // standard library does not carry a blanket
10473 // `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
10474 // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
10475 // so the borrowed-input `Box<str>` forward-projection axis
10476 // is a distinct trait-idiomatic surface that a
10477 // `let key: Box<str> = (&policy).into();`-shaped call site
10478 // or a `RestartPolicy::ALL.iter().map(Box::<str>::from)`-
10479 // shaped pipe reaches through this impl and no other — the
10480 // paired owned-input `From<RestartPolicy> for Box<str>`
10481 // impl (0a1b313) forces every borrowed-input call site
10482 // through an explicit `Copy` deref
10483 // (`Box::<str>::from((*policy).as_str())`) or a
10484 // `Box::<str>::from(policy.as_str())` open-code whose
10485 // type bounds have no compile-time link back to the
10486 // substrate primitive.
10487 //
10488 // Fourth (and closing) peer on the substrate-wide trait-
10489 // idiomatic [`Box<str>`] forward-projection family on the
10490 // M2 OTP-shape tier — closes the `{Self, &Self}` input-
10491 // shape corner of the [`Box<str>`] axis on the second (and
10492 // third-and-final) M2 OTP-shape closed-set fieldless typed
10493 // enum peer on the caixa surface (`:children :restart`),
10494 // exactly as b4dc55c closed the paired [`Cow<'static, str>`]
10495 // axis one commit after its owning half (0612398) landed
10496 // on this enum. Every remaining closed-set fieldless typed
10497 // enum peer on the M3 mesh-shape / outside-M3 caixa-core /
10498 // render-side / outside-caixa-core tiers is a future
10499 // target of the campaign.
10500 //
10501 // Also byte-parity witness against the paired owned-input
10502 // [`From<RestartPolicy> for Box<str>`] and the sibling
10503 // borrowed-input [`From<&RestartPolicy> for &'static str`],
10504 // [`From<&RestartPolicy> for String`], and
10505 // [`From<&RestartPolicy> for Cow<'static, str>`]
10506 // return-shape axes — locking the four
10507 // return-shape × input-shape paths together by construction
10508 // so any future detour trips at caixa-core test time. Then a
10509 // `.iter().map(Box::<str>::from)` pipe witness over
10510 // [`super::RestartPolicy::ALL`] — whose iterator yields
10511 // `&RestartPolicy` by construction, so the borrowed-input
10512 // [`Box<str>`] axis is what routes the pipe through the
10513 // substrate-primitive [`super::RestartPolicy::as_str`]
10514 // accessor without a spurious [`Copy`] deref (which would
10515 // only be reachable through the owned-input
10516 // [`From<RestartPolicy> for Box<str>`] axis by first
10517 // calling `.copied()` on the iterator).
10518 for &variant in RestartPolicy::ALL {
10519 let via_trait: Box<str> = <Box<str> as From<&RestartPolicy>>::from(&variant);
10520 let via_method: &'static str = variant.as_str();
10521 assert_eq!(
10522 via_trait.as_ref(),
10523 via_method,
10524 "From<&RestartPolicy> for Box<str> impl must round-\
10525 trip &RestartPolicy::{variant:?} to the same lifted \
10526 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
10527 returns — divergence signals a silent detour off the \
10528 substrate-primitive accessor"
10529 );
10530 let via_into: Box<str> = (&variant).into();
10531 assert_eq!(
10532 via_into.as_ref(),
10533 via_method,
10534 "Into<Box<str>>::into on &RestartPolicy::{variant:?} \
10535 must byte-equal RestartPolicy::as_str on the same \
10536 input — the blanket-derived Into shape must resolve \
10537 to the same as_str dispatch as the explicit From impl"
10538 );
10539 let owned_box: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
10540 assert_eq!(
10541 via_trait, owned_box,
10542 "From<&RestartPolicy> for Box<str> and \
10543 From<RestartPolicy> for Box<str> must resolve \
10544 identically on RestartPolicy::{variant:?} — \
10545 divergence signals the borrowed-input and owned-input \
10546 Box<str> forward-projection input-shape paths have \
10547 drifted onto different emit-sets"
10548 );
10549 let borrowed_static: &'static str =
10550 <&'static str as From<&RestartPolicy>>::from(&variant);
10551 assert_eq!(
10552 via_trait.as_ref(),
10553 borrowed_static,
10554 "From<&RestartPolicy> for Box<str> and \
10555 From<&RestartPolicy> for &'static str must resolve \
10556 identically on RestartPolicy::{variant:?} — \
10557 divergence signals the borrowed-input Box<str> and \
10558 &'static str return-shape paths have drifted onto \
10559 different emit-sets"
10560 );
10561 let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
10562 assert_eq!(
10563 via_trait.as_ref(),
10564 borrowed_string.as_str(),
10565 "From<&RestartPolicy> for Box<str> and \
10566 From<&RestartPolicy> for String must resolve \
10567 identically on RestartPolicy::{variant:?} — \
10568 divergence signals the borrowed-input Box<str> and \
10569 owned-`String` return-shape paths have drifted onto \
10570 different emit-sets"
10571 );
10572 let borrowed_cow: std::borrow::Cow<'static, str> =
10573 <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
10574 assert_eq!(
10575 via_trait.as_ref(),
10576 borrowed_cow.as_ref(),
10577 "From<&RestartPolicy> for Box<str> and \
10578 From<&RestartPolicy> for Cow<'static, str> must \
10579 resolve identically on RestartPolicy::{variant:?} — \
10580 divergence signals the borrowed-input Box<str> and \
10581 Cow<'static, str> return-shape paths have drifted \
10582 onto different emit-sets"
10583 );
10584 }
10585 let via_iter: Vec<Box<str>> = RestartPolicy::ALL.iter().map(Box::<str>::from).collect();
10586 let via_method: Vec<Box<str>> = RestartPolicy::ALL
10587 .iter()
10588 .map(|p| Box::<str>::from(p.as_str()))
10589 .collect();
10590 assert_eq!(
10591 via_iter, via_method,
10592 "`.iter().map(Box::<str>::from)` over \
10593 RestartPolicy::ALL — a call site whose iteration axis \
10594 holds `&RestartPolicy` by construction — must byte-\
10595 equal `.iter().map(|p| Box::<str>::from(p.as_str()))` \
10596 on every arm — the borrowed-input Box<str> \
10597 `From<&RestartPolicy> for Box<str>` axis is what \
10598 makes the `Box::<str>::from` composition route through \
10599 the substrate-primitive `RestartPolicy::as_str` \
10600 accessor without a spurious `Copy` deref (which would \
10601 only be reachable through the owned-input \
10602 `From<RestartPolicy> for Box<str>` axis by first \
10603 calling `.copied()` on the iterator)"
10604 );
10605 }
10606
10607 // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_RESTART_* identity ─
10608
10609 #[test]
10610 fn restart_policy_variants_serialize_to_lifted_scalar_values() {
10611 // The fail-before-pass-after pin: pre-lift there was no
10612 // single-source binding between the [`RestartPolicy`] variant
10613 // name the un-`rename`d `Serialize` derive emits under
10614 // [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
10615 // byte-string every downstream cluster-side dispatcher (the
10616 // future wasm-operator's per-child post-exit restart-decision
10617 // branch, the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
10618 // materializer's admission-time enum-arm bind, the
10619 // `caixa-operator`'s hierarchical reconciliation scheduler's
10620 // per-child-policy fan-out) probes verbatim. A future
10621 // `#[serde(rename_all = "kebab-case")]` attribute on the enum —
10622 // or a per-variant `#[serde(rename = "…")]` override, or a
10623 // variant rename in the source — would silently rebrand the
10624 // emitted scalar under one spelling while every downstream
10625 // dispatcher still probed the other, with the failure surfacing
10626 // at the operator's reconcile posture (children coming up under
10627 // the `default()` `Permanent` arm rather than the typed slot's
10628 // declared policy — a `:temporary` `oneShot` child would be
10629 // restarted on clean exit, treating the successful-completion
10630 // signal as failure and re-running the completion-terminal
10631 // one-shot indefinitely; a `:transient` child that clean-exited
10632 // would be restarted, masking the clean-completion contract)
10633 // far from the source rebrand commit and with no field naming
10634 // the drift. Pinning the two paths (the `Serialize` derive's
10635 // serialized string AND the [`RestartPolicy::as_str`] helper)
10636 // to the same three lifted
10637 // [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
10638 // [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
10639 // [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
10640 // byte-strings makes any future drift on either endpoint fail
10641 // here at caixa-core build time. Peer of the sibling
10642 // [`restart_strategy_variants_serialize_to_lifted_scalar_values`]
10643 // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
10644 // and the M3
10645 // `placement_strategy_variants_serialize_to_lifted_scalar_values`
10646 // (3f0e21c) on the per-Aplicacao distribution-strategy axis —
10647 // same three-path-convergence discipline, extended to close the
10648 // third OTP-shaped closed-enum discriminator axis on the caixa
10649 // typed surface (per-child restart-decision policy).
10650 for (variant, expected) in [
10651 (
10652 RestartPolicy::Permanent,
10653 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
10654 ),
10655 (
10656 RestartPolicy::Temporary,
10657 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
10658 ),
10659 (
10660 RestartPolicy::Transient,
10661 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
10662 ),
10663 ] {
10664 let json = serde_json::to_string(&variant).unwrap();
10665 assert_eq!(
10666 json,
10667 format!("\"{expected}\""),
10668 "RestartPolicy::{variant:?} must serialize to {expected:?}"
10669 );
10670 assert_eq!(
10671 variant.as_str(),
10672 expected,
10673 "RestartPolicy::{variant:?}.as_str() must return the lifted \
10674 SUPERVISOR_CHILD_RESTART_* constant"
10675 );
10676 }
10677 }
10678
10679 #[test]
10680 fn supervisor_child_restart_consts_are_pairwise_distinct() {
10681 // Cross-arm drift-detection pin: a future collapse of two
10682 // canonical variant byte-strings onto the same value (e.g. an
10683 // accidental copy-paste flip of `SUPERVISOR_CHILD_RESTART_TRANSIENT`
10684 // to also read `"Permanent"`) would silently reroute every
10685 // downstream operator's per-child-policy dispatch onto the
10686 // sibling arm's reconcile branch and pass every propagation-probe
10687 // test that expected only the stale arm's value — a `:transient`
10688 // child would come up under the `:permanent` restart-decision
10689 // posture on every subsequent clean exit, so a completion-terminal
10690 // child would be restarted indefinitely against its declared
10691 // policy. Peer of the sibling
10692 // [`supervisor_estrategia_consts_are_pairwise_distinct`]
10693 // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
10694 // and the four-way distinct pin
10695 // `supervisor_key_consts_are_pairwise_distinct` (40cc4e5) on the
10696 // top-level `SUPERVISOR_KEY_*` axis.
10697 let all = [
10698 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
10699 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
10700 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
10701 ];
10702 for (i, a) in all.iter().enumerate() {
10703 for (j, b) in all.iter().enumerate() {
10704 if i != j {
10705 assert_ne!(
10706 a, b,
10707 "SUPERVISOR_CHILD_RESTART_* consts must be pairwise distinct \
10708 — got duplicate {a:?} at indices {i} and {j}",
10709 );
10710 }
10711 }
10712 }
10713 }
10714
10715 #[test]
10716 fn restart_policy_display_routes_through_as_str_helper() {
10717 // The fail-before-pass-after pin on the first half of the
10718 // three-path convergence: pre-convergence [`RestartPolicy`]
10719 // carried a [`std::fmt::Display`] surface via its
10720 // `#[discriminant(also_display)]` gen-platform derive route,
10721 // which arrived kebab-case as `"permanent"` / `"temporary"`
10722 // / `"transient"` on this three-arm enum (whose variant
10723 // names each collapse to their own lowercase form under the
10724 // kebab-case transform) while the wire format ran as
10725 // PascalCase `"Permanent"` / `"Temporary"` / `"Transient"`
10726 // through the un-`rename`d serde derive. Every consumer
10727 // reaching for a policy byte-string past the wire format had
10728 // to pick between three paths ([`RestartPolicy::as_str`],
10729 // the `Serialize` derive's serialized string, or
10730 // `format!("{v}")` on the discriminant-Display route), any
10731 // two of which a future variant rename or
10732 // `#[serde(rename_all = "kebab-case")]` attribute would
10733 // silently desynchronize. Wiring [`std::fmt::Display`]
10734 // through [`RestartPolicy::as_str`] closes the third path:
10735 // every `format!("{v}")` call reaches the same lifted
10736 // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the
10737 // wire format and the [`RestartPolicy::as_str`] helper
10738 // already route through, so a future variant rename lands at
10739 // exactly one place. Pin the routing here so a future
10740 // `impl std::fmt::Display for RestartPolicy`
10741 // reimplementation that hand-rolls the arms instead of
10742 // delegating to [`RestartPolicy::as_str`] fails at
10743 // caixa-core build time. Peer of the sibling
10744 // [`restart_strategy_display_routes_through_as_str_helper`]
10745 // on the per-supervisor sibling-restart-strategy axis and
10746 // the M3
10747 // `placement_strategy_display_routes_through_as_str_helper`
10748 // (cc8f749) — the third of three OTP-shape closed-enum
10749 // discriminator axes on the caixa typed surface now
10750 // converged onto the same three-path
10751 // (Display → as_str → lifted const) discipline.
10752 for variant in [
10753 RestartPolicy::Permanent,
10754 RestartPolicy::Temporary,
10755 RestartPolicy::Transient,
10756 ] {
10757 assert_eq!(
10758 variant.to_string(),
10759 variant.as_str(),
10760 "RestartPolicy::{variant:?} Display must route through \
10761 RestartPolicy::as_str (single source of truth: the lifted \
10762 SUPERVISOR_CHILD_RESTART_* const the wire format also emits)"
10763 );
10764 }
10765 }
10766
10767 #[test]
10768 fn restart_policy_display_matches_serialized_wire_byte_string() {
10769 // The fail-before-pass-after pin on the second half of the
10770 // three-path convergence: `Display` (user-facing text) agrees
10771 // byte-for-byte with the `Serialize` derive's wire format
10772 // (canonical camelCase-schema `SUPERVISOR_CHILD_KEY_RESTART`
10773 // scalar) on every variant. Pre-convergence the two paths
10774 // were structurally independent — a future
10775 // `#[serde(rename_all = "kebab-case")]` attribute on the
10776 // enum would silently rebrand the emitted wire scalar
10777 // (`permanent`, `temporary`, `transient`) while every
10778 // consumer that pretty-prints the policy (the future
10779 // wasm-operator's per-child post-exit restart-decision
10780 // diagnostic line, the future `feira app graph` per-child
10781 // restart column, the future M4
10782 // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
10783 // per-child admission-webhook rejection body) would still
10784 // emit the PascalCase form the `as_str` / `Display` route
10785 // returns, with the mismatch surfacing at consumer parse
10786 // time / operator dispatch time far from the source rebrand
10787 // commit. Pin the two paths byte-for-byte here so any future
10788 // serde-attribute or variant-rename drift is a
10789 // caixa-core-build-time test failure at this call, not a
10790 // silent per-consumer dispatch miss. Peer of the sibling
10791 // [`restart_strategy_display_matches_serialized_wire_byte_string`]
10792 // on the per-supervisor sibling-restart-strategy axis and
10793 // the M3
10794 // `placement_strategy_display_matches_serialized_wire_byte_string`
10795 // (cc8f749).
10796 for variant in [
10797 RestartPolicy::Permanent,
10798 RestartPolicy::Temporary,
10799 RestartPolicy::Transient,
10800 ] {
10801 let wire = serde_json::to_string(&variant).unwrap();
10802 let unquoted = wire
10803 .strip_prefix('"')
10804 .and_then(|s| s.strip_suffix('"'))
10805 .expect("serialized RestartPolicy is a JSON string");
10806 assert_eq!(
10807 variant.to_string(),
10808 unquoted,
10809 "RestartPolicy::{variant:?} Display byte-string must match the \
10810 Serialize derive's wire byte-string (three-path convergence: \
10811 Display + as_str + Serialize all resolve to the same \
10812 SUPERVISOR_CHILD_RESTART_* const)"
10813 );
10814 }
10815 }
10816
10817 #[test]
10818 fn restart_policy_as_ref_str_routes_through_as_str_accessor() {
10819 // Fail-before-pass-after byte-parity pin on the lifted
10820 // `impl AsRef<str> for RestartPolicy` — asserts the
10821 // standard-library trait impl and the substrate-primitive
10822 // [`RestartPolicy::as_str`] `pub const fn` accessor resolve
10823 // to the same `&str` per instance across the three-arm
10824 // closed set, so any future silent detour that routes the
10825 // impl through a divergent projection (a per-arm inline
10826 // `match self { RestartPolicy::Permanent => "Permanent", … }`
10827 // re-inlining that opens a compile-time link to the un-lifted
10828 // arm-literal, a swap onto the kebab-case
10829 // [`gen_platform::Discriminant`] catalog identity that would
10830 // collide the wire axis with the dispatcher-catalog axis) trips
10831 // at caixa-core test time under `PartialEq` rather than at a
10832 // downstream `impl AsRef<str>`-bound consumer's silent split.
10833 // Sweeps every one of the three arms
10834 // [`RestartPolicy::ALL`] carries so no arm's projection is
10835 // covered only by the sibling wire-format `Serialize` derive
10836 // path. Peer of the sibling
10837 // [`restart_strategy_as_ref_str_routes_through_as_str_accessor`]
10838 // (63eb1a4) on the paired per-supervisor sibling-restart-
10839 // strategy axis and the [`crate::CaixaVersion`]
10840 // `AsRef<str>`-byte-parity pin (16d5c7e) on the paired
10841 // top-level `:versao` typed newtype — the three pins together
10842 // cover the substrate primitive's `AsRef<str>` projection axis
10843 // on the paired newtype + M2 closed-set-typed-enum surface.
10844 for &variant in RestartPolicy::ALL {
10845 assert_eq!(
10846 <RestartPolicy as AsRef<str>>::as_ref(&variant),
10847 variant.as_str(),
10848 "AsRef<str> impl on RestartPolicy::{variant:?} must \
10849 byte-equal RestartPolicy::as_str on the same instance \
10850 — divergence signals a silent detour off the substrate-\
10851 primitive accessor"
10852 );
10853 }
10854 }
10855
10856 #[test]
10857 fn restart_policy_as_ref_str_routes_through_display_via_shared_accessor() {
10858 // Fail-before-pass-after byte-parity pin on the three-path
10859 // convergence discipline the M2 per-child-restart-policy
10860 // primitive now carries on the `&str`-projection axis:
10861 // `<RestartPolicy as AsRef<str>>::as_ref(&v)` (the newly
10862 // lifted impl), `format!("{v}")` (the pre-existing
10863 // [`fmt::Display`] impl), and `v.as_str()` (the substrate-
10864 // primitive `pub const fn` accessor both trait impls delegate
10865 // through) must resolve to the same byte-string on every
10866 // instance across the three-arm closed set. Refuses any future
10867 // divergence between the two trait impls (a stray
10868 // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
10869 // rather than delegating through the shared accessor; a
10870 // hypothetical `AsRef<str>` rewrite that inlines a per-arm
10871 // literal cascade) that would silently split the two
10872 // projection paths of the same closed-set typed enum. Mirrors
10873 // the sibling three-path-convergence discipline the peer
10874 // [`RestartStrategy`] typed enum carries on its
10875 // `AsRef<str>` / `Display` / `as_str` triple
10876 // (supervisor.rs pin
10877 // `restart_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
10878 // 63eb1a4) and the [`crate::CaixaVersion`] typed newtype
10879 // carries on the same triple (version.rs pin
10880 // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
10881 // 16d5c7e).
10882 for &variant in RestartPolicy::ALL {
10883 let via_as_ref: &str = <RestartPolicy as AsRef<str>>::as_ref(&variant);
10884 let via_display: String = format!("{variant}");
10885 let via_accessor: &str = variant.as_str();
10886 assert_eq!(via_as_ref, via_accessor);
10887 assert_eq!(via_display, via_accessor);
10888 assert_eq!(via_as_ref, via_display.as_str());
10889 }
10890 }
10891
10892 #[test]
10893 fn restart_policy_all_enumerates_every_variant_exactly_once() {
10894 // Fail-before-pass-after pin on the [`RestartPolicy::ALL`]
10895 // exhaustive-iteration surface: every variant appears exactly
10896 // once, and the slice length matches the arm count of the
10897 // closed set. Every consumer that walks the accepted-policy
10898 // set (a future `feira supervisor --restart …` CLI-side
10899 // arg-parse's "did you mean" hint, a future M4 admission-
10900 // webhook's per-child rejection body naming the accepted-
10901 // `:restart` list, the [`RestartPolicy::from_wire`] reverse-
10902 // projection consumers that iterate the accept-set for
10903 // diagnostic rendering) reads through this slice, so a future
10904 // arm addition that grows the enum but forgets to grow
10905 // [`Self::ALL`] silently truncates every downstream consumer's
10906 // accept-set at the same pre-addition boundary — this pin
10907 // fails at caixa-core build time on the pairwise-distinct +
10908 // arm-count invariants.
10909 //
10910 // Peer of the sibling [`RestartStrategy::ALL`] (4eec29c) /
10911 // [`crate::CaixaKind::ALL`] (6b1f4fb) /
10912 // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
10913 // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
10914 // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
10915 // pins on the peer closed-set typed-enum axes.
10916 let all: &[RestartPolicy] = RestartPolicy::ALL;
10917 assert_eq!(
10918 all.len(),
10919 3,
10920 "RestartPolicy::ALL must enumerate every variant of the \
10921 three-arm closed set (Permanent, Temporary, Transient); \
10922 got {all:?}"
10923 );
10924 for (i, a) in all.iter().enumerate() {
10925 for (j, b) in all.iter().enumerate() {
10926 if i != j {
10927 assert_ne!(
10928 a, b,
10929 "RestartPolicy::ALL must carry every variant exactly \
10930 once — got duplicate {a:?} at indices {i} and {j}"
10931 );
10932 }
10933 }
10934 }
10935 for variant in [
10936 RestartPolicy::Permanent,
10937 RestartPolicy::Temporary,
10938 RestartPolicy::Transient,
10939 ] {
10940 assert!(
10941 all.contains(&variant),
10942 "RestartPolicy::ALL must contain {variant:?} — a future arm \
10943 addition that grows the enum but forgets to grow the ALL slice \
10944 silently truncates every downstream consumer's accept-set at \
10945 the pre-addition boundary"
10946 );
10947 }
10948 }
10949
10950 #[test]
10951 fn restart_policy_from_wire_accepts_every_lifted_constant() {
10952 // Fail-before-pass-after pin on the forward accept-set of the
10953 // [`RestartPolicy::from_wire`] reverse projection: every
10954 // canonical [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
10955 // constant the [`RestartPolicy::as_str`] emitter walks parses
10956 // back to its paired variant. Any future arm addition that
10957 // grows the emitter's `as_str` match but forgets to grow the
10958 // parser's `from_wire` match silently splits the two halves of
10959 // the round-trip — the wire byte-string one non-serde consumer
10960 // parses from the one the emitter wrote — with the failure
10961 // surfacing at the operator's reconcile posture (a `:temporary`
10962 // `oneShot` child restarted on clean exit, a `:transient` child
10963 // restarted after clean completion) far from the rebrand
10964 // commit. Pinning the three-arm accept-set here catches the
10965 // drift at caixa-core build time.
10966 //
10967 // Peer of the sibling [`RestartStrategy::from_wire`] (4eec29c)
10968 // + [`crate::CaixaKind::from_wire`] (2aa6d23)
10969 // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
10970 // accept-set pins on the peer closed-set typed-enum `str → Self`
10971 // axes.
10972 for (wire, expected) in [
10973 (
10974 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
10975 RestartPolicy::Permanent,
10976 ),
10977 (
10978 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
10979 RestartPolicy::Temporary,
10980 ),
10981 (
10982 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
10983 RestartPolicy::Transient,
10984 ),
10985 ] {
10986 let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
10987 panic!(
10988 "RestartPolicy::from_wire({wire:?}) must accept every \
10989 SUPERVISOR_CHILD_RESTART_* constant — got None for the \
10990 lifted canonical byte-string that RestartPolicy::{expected:?} \
10991 serializes as under SUPERVISOR_CHILD_KEY_RESTART"
10992 )
10993 });
10994 assert_eq!(
10995 parsed, expected,
10996 "RestartPolicy::from_wire({wire:?}) must return \
10997 RestartPolicy::{expected:?}; got RestartPolicy::{parsed:?}"
10998 );
10999 }
11000 }
11001
11002 #[test]
11003 fn restart_policy_from_wire_round_trips_through_as_str() {
11004 // Fail-before-pass-after pin on the closed round-trip between
11005 // the forward [`RestartPolicy::as_str`] emitter and the
11006 // reverse [`RestartPolicy::from_wire`] parser: for every
11007 // variant in [`RestartPolicy::ALL`], parsing the emitter's
11008 // output must return exactly the same variant. Any per-arm
11009 // divergence — a future arm added to `as_str` but not
11010 // `from_wire`, an accidental copy-paste flip in one but not
11011 // the other — silently splits the emit and parse halves and
11012 // the failure surfaces at consumer parse time far from the
11013 // drift site. The `ALL`-iterating shape means a future arm
11014 // addition picks up the coverage by construction.
11015 //
11016 // Peer of the sibling
11017 // [`restart_strategy_from_wire_round_trips_through_as_str`]
11018 // (4eec29c) round-trip pin on
11019 // [`RestartStrategy::from_wire`] and the M3
11020 // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
11021 // (18c7342) round-trip pin on
11022 // [`crate::aplicacao::PlacementStrategy::from_wire`].
11023 for &variant in RestartPolicy::ALL {
11024 let wire = variant.as_str();
11025 let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
11026 panic!(
11027 "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
11028 must be Some({variant:?}) — the two halves of the round-trip \
11029 dispatch on the same lifted SUPERVISOR_CHILD_RESTART_* consts; \
11030 got None on wire byte-string {wire:?}"
11031 )
11032 });
11033 assert_eq!(
11034 parsed, variant,
11035 "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
11036 must round-trip to the same variant; got {parsed:?}"
11037 );
11038 }
11039 }
11040
11041 #[test]
11042 fn restart_policy_from_wire_rejects_unknown_byte_strings() {
11043 // Fail-before-pass-after pin on the closed-set refusal
11044 // discipline of [`RestartPolicy::from_wire`]: every
11045 // byte-string outside the three-arm accept-set returns `None`
11046 // rather than silently collapsing onto the [`Default`]
11047 // (`Permanent`) arm or an arbitrary neighbor. The refusal set
11048 // exercised here sweeps the load-bearing drift shapes: the
11049 // empty string (a stripped serde-attribute drift), all-
11050 // whitespace strings (the canonical text-editor accidental
11051 // padding shape), the kebab-case dispatcher-catalog identities
11052 // (`"permanent"` / `"temporary"` / `"transient"` — the
11053 // [`gen_platform::FromStrKind`]-derived [`std::str::FromStr`]
11054 // accept-set, which parses the *other* axis of this enum's
11055 // two-axis split and must not leak into the `from_wire`
11056 // PascalCase-wire accept-set — a lowercase leak here would
11057 // silently accept the operator's kebab-case
11058 // dispatcher-catalog probe under the wire-axis parser and mis-
11059 // route a `:permanent` intent), the padded canonical scalar
11060 // (`" Permanent "`), the trailing-newline shapes
11061 // (`"Permanent\n"`), the uppercase-single-word forms
11062 // (`"PERMANENT"`), and neighboring-but-unknown arms
11063 // (`"Restart"` — the canonical typo direction toward the
11064 // sibling [`RestartStrategy`] enum's own wire-arm namespace).
11065 //
11066 // Peer of the sibling
11067 // [`restart_strategy_from_wire_rejects_unknown_byte_strings`]
11068 // (4eec29c) +
11069 // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
11070 // (2aa6d23) +
11071 // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
11072 // (18c7342) refusal pins on the peer closed-set typed-enum
11073 // axes.
11074 for bad in [
11075 "",
11076 " ",
11077 "\n",
11078 "\t",
11079 "permanent",
11080 "temporary",
11081 "transient",
11082 "PERMANENT",
11083 "TEMPORARY",
11084 "TRANSIENT",
11085 "Permanents",
11086 "Permanent ",
11087 " Permanent",
11088 " Transient ",
11089 "Permanent\n",
11090 "perma",
11091 "Trans",
11092 "OneForOne",
11093 "Restart",
11094 "?",
11095 ] {
11096 assert!(
11097 RestartPolicy::from_wire(bad).is_none(),
11098 "RestartPolicy::from_wire({bad:?}) must return None — the \
11099 parser's accept-set is exactly the three RestartPolicy::as_str \
11100 outputs (Permanent, Temporary, Transient), and this \
11101 byte-string is outside that closed set"
11102 );
11103 }
11104 }
11105
11106 #[test]
11107 fn restart_policy_from_wire_matches_serialize_derive_wire_byte_string() {
11108 // Fail-before-pass-after pin on the fourth path of the four-path
11109 // convergence: `from_wire` (the reverse projection) inverts the
11110 // `Serialize` derive's wire byte-string on every variant.
11111 // Together with the pre-existing three-path convergence
11112 // (`Display` + `as_str` + `Serialize` all resolve to the same
11113 // lifted [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const,
11114 // pinned by
11115 // [`restart_policy_display_matches_serialized_wire_byte_string`])
11116 // this closes the round-trip: the wire byte-string the
11117 // `Serialize` derive emits parses back to the same variant
11118 // through `from_wire`, so any future serde-attribute or variant-
11119 // rename drift on the emit half now surfaces as a matched drift
11120 // on the parse half at caixa-core build time — the two halves
11121 // migrate as a unit through the lifted consts on any future
11122 // rename, and the round-trip cannot silently split.
11123 //
11124 // Peer of the sibling
11125 // [`restart_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
11126 // (4eec29c) wire-format pin on
11127 // [`RestartStrategy::from_wire`] and the M3
11128 // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
11129 // (18c7342) wire-format pin on
11130 // [`crate::aplicacao::PlacementStrategy::from_wire`].
11131 for &variant in RestartPolicy::ALL {
11132 let wire = serde_json::to_string(&variant).unwrap();
11133 let unquoted = wire
11134 .strip_prefix('"')
11135 .and_then(|s| s.strip_suffix('"'))
11136 .expect("serialized RestartPolicy is a JSON string");
11137 let parsed = RestartPolicy::from_wire(unquoted).unwrap_or_else(|| {
11138 panic!(
11139 "RestartPolicy::from_wire({unquoted:?}) must accept the \
11140 Serialize derive's wire byte-string for \
11141 RestartPolicy::{variant:?} — the four-path convergence \
11142 (Display + as_str + Serialize + from_wire) resolves through \
11143 the same lifted SUPERVISOR_CHILD_RESTART_* const; got None"
11144 )
11145 });
11146 assert_eq!(
11147 parsed, variant,
11148 "RestartPolicy::from_wire of the Serialize derive's wire \
11149 byte-string for RestartPolicy::{variant:?} must round-trip \
11150 to the same variant; got {parsed:?}"
11151 );
11152 }
11153 }
11154
11155 // ── drift-detection: ChildSpec::nome accessor pins ────────────────────
11156 //
11157 // The M2 supervisor-tree sibling of the M3 `Membro::nome` (4a32abf) pin
11158 // pair (`membro_nome_returns_caixa_byte_equal_across_permutations` +
11159 // `membro_nome_borrows_from_caixa_storage`) — extended here to the M2
11160 // per-`:children` child-caixa `:nome` axis, sibling to the first M2
11161 // slot scalar accessor `UpgradeFromEntry::prior_versao` (75d27a8) on
11162 // the peer per-`:upgrade-from :from` axis. The three pins jointly
11163 // brace the accessor against every future silent detour that would
11164 // desynchronize it from the raw `.caixa` field access every consumer
11165 // previously open-coded.
11166
11167 #[test]
11168 fn child_spec_nome_returns_caixa_byte_equal_across_permutations() {
11169 // The canonical per-`:children` child-caixa `:nome`-scalar pin:
11170 // [`ChildSpec::nome`] must return the `:children :caixa` field
11171 // byte-for-byte across every DNS-1123-label value the upstream
11172 // [`crate::render::require_valid_dns_1123_label`] gate at
11173 // `SupervisorSpec::validate` admits. Peer of the sibling
11174 // `membro_nome_returns_caixa_byte_equal_across_permutations`
11175 // (4a32abf) pin on the M3 per-`:membros` axis — same "the
11176 // substrate-primitive accessor must byte-equal the raw field
11177 // access verbatim across every author-declared value" discipline
11178 // extended to the M2 supervisor-tree per-`:children` arm. Pins
11179 // against a future silent detour that re-normalized the child
11180 // identity (an accidental `.to_lowercase()` — every `:children
11181 // :caixa` is validated as a DNS-1123 label upstream, so any
11182 // re-normalization is redundant + a drift surface between the
11183 // validator and the accessor), a namespace-prefix rewrite (an
11184 // accidental `format!("{namespace}/{caixa}")` per-CR
11185 // fully-qualified rewrite that didn't land on the peer axes), or
11186 // a per-cluster alias stamp the future wasm-operator's
11187 // hierarchical reconciliation scheduler authors on one consumer
11188 // without the others. Five values sweep the accept-set the
11189 // DNS-1123 gate upstream admits (short single-word / dashed /
11190 // v-suffixed / mixed-digit child names).
11191 for name in [
11192 "worker",
11193 "cache-server",
11194 "scratch-job",
11195 "orders-v2",
11196 "session-8080",
11197 ] {
11198 let c = ChildSpec {
11199 caixa: name.into(),
11200 versao: "^0.1".into(),
11201 restart: RestartPolicy::Permanent,
11202 };
11203 assert_eq!(
11204 c.nome(),
11205 name,
11206 "ChildSpec::nome must return :children :caixa verbatim \
11207 (got {:?}, expected {name:?})",
11208 c.nome(),
11209 );
11210 assert_eq!(
11211 c.nome(),
11212 c.caixa.as_str(),
11213 "ChildSpec::nome must byte-equal the .caixa field access",
11214 );
11215 }
11216 }
11217
11218 #[test]
11219 fn child_spec_nome_borrows_from_caixa_storage() {
11220 // The borrow-not-copy pin: [`ChildSpec::nome`] must return a
11221 // `&str` slice that borrows from the typed slot's own [`String`]
11222 // storage — same-address invariant with `c.caixa.as_str()`. Pins
11223 // against a future silent detour that allocated a fresh `String`
11224 // (`self.caixa.clone()` in the body would type-check but silently
11225 // drop the borrow, and every downstream consumer that assumed
11226 // the returned slice outlives `&self` would break on a stale-
11227 // reference use-after-free — the [`crate::render::insert_first_seen`]
11228 // dedup key at [`SupervisorSpec::validate`], the
11229 // [`validate_no_self_supervision`] equality check against the
11230 // parent's `:nome` string slice, the DNS-1123 gate's `&str`
11231 // borrow — each would silently misbehave if this accessor
11232 // produced a detached copy). Peer of the sibling
11233 // `membro_nome_borrows_from_caixa_storage` (4a32abf) pin on the
11234 // M3 per-`:membros` axis and the
11235 // `prior_versao_borrows_from_from_storage` (75d27a8) pin on the
11236 // first M2 slot scalar accessor.
11237 let c = ChildSpec {
11238 caixa: "worker".into(),
11239 versao: "^0.1".into(),
11240 restart: RestartPolicy::Permanent,
11241 };
11242 let name = c.nome();
11243 let caixa_slice = c.caixa.as_str();
11244 assert_eq!(
11245 name.as_ptr(),
11246 caixa_slice.as_ptr(),
11247 "ChildSpec::nome must borrow from the .caixa String's backing \
11248 storage — a fresh allocation here means the accessor no \
11249 longer names the substrate-primitive typed dispatch and \
11250 every downstream consumer would silently carry a detached \
11251 copy",
11252 );
11253 assert_eq!(
11254 name.len(),
11255 caixa_slice.len(),
11256 "ChildSpec::nome and .caixa.as_str() must byte-equal in length \
11257 as well as in address",
11258 );
11259 }
11260
11261 #[test]
11262 fn validate_gates_child_nome_through_lifted_accessor() {
11263 // Bilateral coherence pin: every `:children :caixa` that
11264 // [`SupervisorSpec::validate`] accepts is one
11265 // [`crate::render::require_valid_dns_1123_label`] accepts on the
11266 // accessor-projected value, and vice versa on the reject side.
11267 // This closes the "the validator reads through the accessor"
11268 // contract structurally — a future silent detour that made the
11269 // accessor return a different byte-string than the validator
11270 // gates against would surface here as a coverage mismatch, not
11271 // as an apply-time DNS-1123 rejection at
11272 // `metadata.name: Invalid value` far from the caixa.lisp source.
11273 // Peer of the M2 sibling
11274 // `validate_parses_prior_versao_through_lifted_accessor`
11275 // (75d27a8) on the per-`:upgrade-from :from` axis and the M3
11276 // `validate_membros` peer discipline.
11277 //
11278 // Accept-set sweep: five DNS-1123-label values the upstream gate
11279 // admits.
11280 for ok_name in ["a", "worker", "cache-server", "orders-v2", "svc-8080"] {
11281 let s = SupervisorSpec {
11282 children: vec![ChildSpec {
11283 caixa: ok_name.into(),
11284 versao: "^0.1".into(),
11285 restart: RestartPolicy::Permanent,
11286 }],
11287 ..SupervisorSpec::default()
11288 };
11289 s.validate().unwrap_or_else(|e| {
11290 panic!(
11291 "SupervisorSpec::validate must accept :children :caixa {ok_name:?} \
11292 (upstream DNS-1123 gate accepts it): got {e:?}",
11293 );
11294 });
11295 let c = ChildSpec {
11296 caixa: ok_name.into(),
11297 versao: "^0.1".into(),
11298 restart: RestartPolicy::Permanent,
11299 };
11300 crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| ())
11301 .unwrap_or_else(|()| {
11302 panic!(
11303 "require_valid_dns_1123_label must accept the accessor-projected \
11304 :children :caixa {ok_name:?}",
11305 );
11306 });
11307 }
11308 // Reject-set sweep: five DNS-1123-label-violating shapes the
11309 // upstream gate refuses (empty / uppercase / underscore / dot /
11310 // leading-hyphen). Every rejection at the validator must
11311 // correspond to a rejection when the accessor's projected value
11312 // is fed back through the shared gate.
11313 for bad_name in ["", "Worker", "my_worker", "team.worker", "-worker"] {
11314 let s = SupervisorSpec {
11315 children: vec![ChildSpec {
11316 caixa: bad_name.into(),
11317 versao: "^0.1".into(),
11318 restart: RestartPolicy::Permanent,
11319 }],
11320 ..SupervisorSpec::default()
11321 };
11322 let err = s.validate().unwrap_err();
11323 assert!(
11324 matches!(
11325 err,
11326 SupervisorError::EmptyChildName | SupervisorError::ChildCaixaInvalid { .. }
11327 ),
11328 "SupervisorSpec::validate must reject :children :caixa {bad_name:?} \
11329 via the DNS-1123 gate: got {err:?}",
11330 );
11331 let c = ChildSpec {
11332 caixa: bad_name.into(),
11333 versao: "^0.1".into(),
11334 restart: RestartPolicy::Permanent,
11335 };
11336 assert!(
11337 crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| (),)
11338 .is_err(),
11339 "require_valid_dns_1123_label must reject the accessor-projected \
11340 :children :caixa {bad_name:?}",
11341 );
11342 }
11343 }
11344
11345 // ── drift-detection: ChildSpec::versao_requirement accessor pins ──────
11346 //
11347 // Sibling of the peer per-`:membros` `membro_versao_requirement_*`
11348 // (a40b0e3) pin pair on the M3 mesh-slot surface — extended here to the
11349 // M2 supervisor-tree per-`:children` child-`:versao` axis, sibling to
11350 // the just-landed [`ChildSpec::nome`] (57c61d0) child-`:nome` pin
11351 // trio on the peer per-`:children` `String`-carry axis. The three pins
11352 // jointly brace the accessor against every future silent detour that
11353 // would desynchronize it from the raw `.versao` field access the
11354 // requirement gate + error carrier previously open-coded.
11355 //
11356 // Closes the last unlifted per-`:children` `String`-carry axis: the
11357 // pair (`nome`, `versao_requirement`) now jointly projects the
11358 // (`.caixa`, `.versao`) field pair every OTP-shape supervisor-tree
11359 // consumer that fans on per-child identity + version pin reads,
11360 // matching the peer M3 (`Membro::nome`, `Membro::versao_requirement`)
11361 // pair discipline verbatim.
11362 #[test]
11363 fn child_spec_versao_requirement_returns_versao_byte_equal_across_permutations() {
11364 // The canonical per-`:children` child-`:versao`-scalar pin:
11365 // [`ChildSpec::versao_requirement`] must return the `:children
11366 // :versao` field byte-for-byte across every Cargo-shaped semver
11367 // requirement value the upstream
11368 // [`crate::render::require_valid_versao_requirement`] gate admits.
11369 // Peer of the sibling
11370 // `membro_versao_requirement_returns_versao_byte_equal_across_permutations`
11371 // (a40b0e3) pin on the M3 per-`:membros` axis — same "the
11372 // substrate-primitive accessor must byte-equal the raw field
11373 // access verbatim across every author-declared value" discipline
11374 // extended to the M2 supervisor-tree per-`:children` arm. Pins
11375 // against a future silent detour that re-canonicalized the
11376 // requirement (an accidental `.to_string()` via
11377 // [`crate::version::parse_requirement`] → [`std::fmt::Display`]
11378 // round-trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and
11379 // silently drifted the error carrier's quoted requirement away
11380 // from the source `caixa.lisp`, an accidental whitespace trim on
11381 // `"^ 0.1"` that no consumer ever produced from the field-access
11382 // side, an accidental per-cluster lacre-projected concrete-version
11383 // rewrite that didn't land on the peer requirement-gate call).
11384 // Five values sweep the accept-set the shared
11385 // [`crate::render::require_valid_versao_requirement`] gate admits
11386 // (caret / tilde / exact / wildcard / bare-major).
11387 for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
11388 let c = ChildSpec {
11389 caixa: "worker".into(),
11390 versao: req.into(),
11391 restart: RestartPolicy::Permanent,
11392 };
11393 assert_eq!(
11394 c.versao_requirement(),
11395 req,
11396 "ChildSpec::versao_requirement must return :children :versao \
11397 verbatim (got {:?}, expected {req:?})",
11398 c.versao_requirement(),
11399 );
11400 assert_eq!(
11401 c.versao_requirement(),
11402 c.versao.as_str(),
11403 "ChildSpec::versao_requirement must byte-equal the .versao \
11404 field access",
11405 );
11406 }
11407 }
11408
11409 #[test]
11410 fn child_spec_versao_requirement_borrows_from_versao_storage() {
11411 // The borrow-not-copy pin: [`ChildSpec::versao_requirement`] must
11412 // return a `&str` slice that borrows from the typed slot's own
11413 // [`String`] storage — same-address invariant with
11414 // `c.versao.as_str()`. Pins against a future silent detour that
11415 // allocated a fresh `String` (`self.versao.clone()` in the body
11416 // would type-check but silently drop the borrow, and every
11417 // downstream consumer that assumed the returned slice outlives
11418 // `&self` — the [`crate::render::require_valid_versao_requirement`]
11419 // gate's `&str` borrow, the [`SupervisorError::ChildVersaoInvalid`]
11420 // `.to_string()` carrier's byte-length assumption — would silently
11421 // misbehave if this accessor produced a detached copy). Peer of
11422 // the sibling `child_spec_nome_borrows_from_caixa_storage`
11423 // (57c61d0) pin on the per-`:children` `:nome` axis and the M3
11424 // `membro_versao_requirement_borrows_from_versao_storage` (a40b0e3)
11425 // pin on the peer per-`:membros` `:versao` axis.
11426 let c = ChildSpec {
11427 caixa: "worker".into(),
11428 versao: "^0.1".into(),
11429 restart: RestartPolicy::Permanent,
11430 };
11431 let req = c.versao_requirement();
11432 let versao_slice = c.versao.as_str();
11433 assert_eq!(
11434 req.as_ptr(),
11435 versao_slice.as_ptr(),
11436 "ChildSpec::versao_requirement must borrow from the .versao \
11437 String's backing storage — a fresh allocation here means the \
11438 accessor no longer names the substrate-primitive typed \
11439 dispatch and every downstream consumer would silently carry \
11440 a detached copy",
11441 );
11442 assert_eq!(
11443 req.len(),
11444 versao_slice.len(),
11445 "ChildSpec::versao_requirement and .versao.as_str() must \
11446 byte-equal in length as well as in address",
11447 );
11448 }
11449
11450 #[test]
11451 fn validate_gates_child_versao_through_lifted_accessor() {
11452 // Bilateral coherence pin: every `:children :versao` that
11453 // [`SupervisorSpec::validate`] accepts is one
11454 // [`crate::render::require_valid_versao_requirement`] accepts on
11455 // the accessor-projected value, and vice versa on the reject side.
11456 // This closes the "the validator reads through the accessor"
11457 // contract structurally — a future silent detour that made the
11458 // accessor return a different byte-string than the validator gates
11459 // against would surface here as a coverage mismatch, not as a
11460 // resolver-time semver-parse rejection at lacre-closure time far
11461 // from the caixa.lisp source. Peer of the sibling
11462 // `validate_gates_child_nome_through_lifted_accessor` (57c61d0) on
11463 // the per-`:children :caixa` axis and the M2
11464 // `validate_parses_prior_versao_through_lifted_accessor` (75d27a8)
11465 // on the peer per-`:upgrade-from :from` axis.
11466 //
11467 // Accept-set sweep: five Cargo-shaped semver requirement values
11468 // the upstream gate admits (caret / tilde / exact / wildcard /
11469 // bare-major).
11470 for ok_req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
11471 let s = SupervisorSpec {
11472 children: vec![ChildSpec {
11473 caixa: "worker".into(),
11474 versao: ok_req.into(),
11475 restart: RestartPolicy::Permanent,
11476 }],
11477 ..SupervisorSpec::default()
11478 };
11479 s.validate().unwrap_or_else(|e| {
11480 panic!(
11481 "SupervisorSpec::validate must accept :children :versao {ok_req:?} \
11482 (upstream versao-requirement gate accepts it): got {e:?}",
11483 );
11484 });
11485 let c = ChildSpec {
11486 caixa: "worker".into(),
11487 versao: ok_req.into(),
11488 restart: RestartPolicy::Permanent,
11489 };
11490 crate::render::require_valid_versao_requirement(
11491 c.versao_requirement(),
11492 || (),
11493 |_reason| (),
11494 )
11495 .unwrap_or_else(|()| {
11496 panic!(
11497 "require_valid_versao_requirement must accept the accessor-projected \
11498 :children :versao {ok_req:?}",
11499 );
11500 });
11501 }
11502 // Reject-set sweep: five requirement-violating shapes the upstream
11503 // gate refuses. The empty string closes the empty-first arm of the
11504 // shared [`crate::render::require_valid_versao_requirement`]
11505 // cascade; the four non-empty arms exercise distinct semver-parse
11506 // failure modes the M3 peer per-`:membros` reject-set already pins
11507 // (`rejects_invalid_membro_versao_requirement` on `^bad-version`,
11508 // `rejects_membro_versao_with_double_caret_typo` on `^^0.1`,
11509 // `rejects_membro_versao_with_v_prefixed_tag` on `v0.1`) — the
11510 // shared parser routing means the same reject-set must fail
11511 // identically at the M2 supervisor-tree per-`:children` accessor
11512 // arm here. Every rejection at the validator must correspond to a
11513 // rejection when the accessor's projected value is fed back
11514 // through the shared gate.
11515 //
11516 // (Bare partial magnitudes like `"0.1"` and bare identifiers like
11517 // `"not-a-semver"` are intentionally *not* in the reject-set: the
11518 // semver crate accepts `"0.1"` as an implicit `^0.1` requirement,
11519 // and the identifier-tail arm's grammar admits some non-canonical
11520 // shapes — matching what the M3 peer test suite already documents
11521 // as the shared parser's accept-set edges.)
11522 for bad_req in ["", "v0.1.0", "^bad-version", "^^0.1", "v0.1"] {
11523 let s = SupervisorSpec {
11524 children: vec![ChildSpec {
11525 caixa: "worker".into(),
11526 versao: bad_req.into(),
11527 restart: RestartPolicy::Permanent,
11528 }],
11529 ..SupervisorSpec::default()
11530 };
11531 let err = s.validate().unwrap_err();
11532 assert!(
11533 matches!(
11534 err,
11535 SupervisorError::EmptyChildVersion { .. }
11536 | SupervisorError::ChildVersaoInvalid { .. }
11537 ),
11538 "SupervisorSpec::validate must reject :children :versao {bad_req:?} \
11539 via the versao-requirement gate: got {err:?}",
11540 );
11541 let c = ChildSpec {
11542 caixa: "worker".into(),
11543 versao: bad_req.into(),
11544 restart: RestartPolicy::Permanent,
11545 };
11546 assert!(
11547 crate::render::require_valid_versao_requirement(
11548 c.versao_requirement(),
11549 || (),
11550 |_reason| (),
11551 )
11552 .is_err(),
11553 "require_valid_versao_requirement must reject the accessor-projected \
11554 :children :versao {bad_req:?}",
11555 );
11556 }
11557 }
11558
11559 // ── per-`:children` `:restart` typed-accessor coherence pins ──────────
11560 //
11561 // The [`ChildSpec::restart`] accessor lift closes the last unlifted
11562 // per-`:children` axis (the pair `nome()` + `versao_requirement()`
11563 // already project the `String`-carry `(caixa, versao)` fields; the
11564 // `Copy`-composite-enum `restart` field is the third and final axis).
11565 // Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
11566 // (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
11567 // scalar accessor and the M3 mesh-slot [`crate::Placement::estrategia`]
11568 // (921fe1b) `Copy`-return [`crate::PlacementStrategy`] distribution-
11569 // strategy scalar accessor — same "one typed dispatch on the substrate
11570 // primitive, `Copy`-projected closed-set enum-arm discriminator" shape
11571 // extended onto the M2 supervisor-slot per-`:children` restart-decision
11572 // axis. The pin below covers the accessor's byte-equal projection
11573 // against the raw field access across every variant in the closed
11574 // accept-set (`Permanent`, `Transient`, `Temporary`).
11575
11576 #[test]
11577 fn child_spec_restart_returns_restart_verbatim_across_permutations() {
11578 // The canonical per-`:children` restart-decision-policy-scalar
11579 // pin: [`ChildSpec::restart`] must return the `:children :restart`
11580 // field verbatim as a [`RestartPolicy`], `Copy`-projected from the
11581 // typed slot's own [`RestartPolicy`] storage across every variant
11582 // in the closed accept-set (`Permanent`, `Transient`, `Temporary`).
11583 // Pins against a future silent detour that re-derived the policy
11584 // from a peer axis (an accidental fallback to
11585 // `if is_supervisor_child { Permanent } else { Temporary }` that
11586 // collapsed the child's kind axis into the restart discriminator),
11587 // a variant remap the operator authors on one consumer without the
11588 // other, or a stale-derive detour that substituted
11589 // [`RestartPolicy::default`] when the field held any explicit
11590 // variant (which would silently collapse the distinction between
11591 // "author explicitly declared `:restart Permanent`" and "author
11592 // omitted the slot and inherited the default" the future
11593 // per-cluster restart-decision override slot depends on).
11594 //
11595 // Peer of the sibling per-`:supervisor`
11596 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
11597 // (eafb619) pin on the M2 supervisor-slot sibling-restart-strategy
11598 // axis and the M3
11599 // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
11600 // (921fe1b) pin on the per-`:placement` distribution-strategy axis
11601 // — same "the substrate-primitive accessor must byte-equal the raw
11602 // field access verbatim across every author-declared value"
11603 // discipline extended onto the M2 supervisor-slot per-`:children`
11604 // restart-decision-policy axis, closing the last unlifted axis on
11605 // the per-`:children` [`ChildSpec`] type.
11606 for restart in [
11607 RestartPolicy::Permanent,
11608 RestartPolicy::Transient,
11609 RestartPolicy::Temporary,
11610 ] {
11611 let c = ChildSpec {
11612 caixa: "worker".into(),
11613 versao: "^0.1".into(),
11614 restart,
11615 };
11616 assert_eq!(
11617 c.restart(),
11618 restart,
11619 "ChildSpec::restart must return :children :restart \
11620 verbatim (got {:?}, expected {restart:?})",
11621 c.restart(),
11622 );
11623 assert_eq!(
11624 c.restart(),
11625 c.restart,
11626 "ChildSpec::restart accessor and .restart field access \
11627 must byte-equal — the accessor is the substrate-primitive \
11628 typed dispatch every downstream per-child restart-\
11629 decision consumer must route through",
11630 );
11631 }
11632 }
11633
11634 // ── per-`:supervisor` `:estrategia` typed-accessor coherence pins ─────
11635 //
11636 // The [`SupervisorSpec::estrategia`] accessor lift extends the peer M3
11637 // [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
11638 // distribution-strategy accessor discipline onto the M2 supervisor-slot
11639 // per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
11640 // scalar axis. The two pins below cover (1) the accessor's byte-equal
11641 // projection against the raw field access across every variant in the
11642 // closed accept-set, and (2) the two-consumer coherence between the
11643 // [`SupervisorSpec::validate`] partition-dispatch `match` arm and the
11644 // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
11645 // carrier's `estrategia:` field — peer of the sibling M3
11646 // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
11647 // / `validate_placement_reads_through_lifted_estrategia_accessor` pin
11648 // pair on the per-`:placement` distribution-strategy axis.
11649
11650 #[test]
11651 fn supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations() {
11652 // The canonical per-`:supervisor` sibling-restart-strategy-scalar
11653 // pin: [`SupervisorSpec::estrategia`] must return the
11654 // `:supervisor :estrategia` field verbatim as a
11655 // [`RestartStrategy`], `Copy`-projected from the typed slot's own
11656 // [`RestartStrategy`] storage across every variant in the closed
11657 // accept-set (`OneForOne`, `OneForAll`, `RestForOne`,
11658 // `SimpleOneForOne`). Pins against a future silent detour that
11659 // re-derived the strategy from a peer axis (an accidental
11660 // fallback to `if children.is_empty() { SimpleOneForOne } else {
11661 // OneForOne }` collapse that read the children-count axis into
11662 // the strategy discriminator), a variant remap the operator
11663 // authors on one consumer without the other, or a stale-derive
11664 // detour that substituted [`RestartStrategy::default`] when the
11665 // field held any explicit variant (which would silently collapse
11666 // the distinction between "author explicitly declared
11667 // `:estrategia OneForOne`" and "author omitted the slot and
11668 // inherited the default" the future per-cluster strategy override
11669 // slot depends on). Peer of the sibling M3
11670 // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
11671 // (921fe1b) pin on the M3 mesh-slot `Copy`-composite-enum scalar
11672 // axis — same "the substrate-primitive accessor must byte-equal
11673 // the raw field access verbatim across every author-declared
11674 // value" discipline extended onto the M2 supervisor-slot
11675 // per-`:supervisor` sibling-restart-strategy axis.
11676 for &estrategia in RestartStrategy::ALL {
11677 // `SimpleOneForOne` requires `children.is_empty()`; the peer
11678 // three strategies require a non-empty static children list.
11679 // Build each shape coherently so the pin's fixture would
11680 // itself pass [`SupervisorSpec::validate`] once fed through
11681 // the sibling coherence pin below — the byte-equal projection
11682 // asserted here is a strictly weaker property (a `Copy` field
11683 // read) that does not depend on `validate` running, but
11684 // keeping the fixture validate-clean means a future extension
11685 // of the pin to exercise `validate` end-to-end does not have
11686 // to re-author the children shape.
11687 //
11688 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
11689 // shape partition through the [`gen_platform::IsVariant`]
11690 // derive-generated
11691 // [`RestartStrategy::is_simple_one_for_one`] predicate rather
11692 // than the raw `matches!(estrategia, RestartStrategy::
11693 // SimpleOneForOne)` open-coded pattern-match — same closed-
11694 // set-typed-enum arm-discriminator dispatch discipline the
11695 // sibling [`crate::upgrade::UpgradeInstruction::is_restart`]
11696 // convergence (915a934) extended onto its two paired positive
11697 // / negated `matches!` sites and the peer
11698 // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
11699 // predicate convergence (766ec63) extended onto the M3 mesh-
11700 // slot per-`:placement` distribution-strategy discriminator
11701 // axis. See the sibling `round_trip_all_strategies` and the
11702 // peer `manifest::tests::
11703 // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
11704 // fixture for the two peer sites the same lift closes on.
11705 let children = if estrategia.is_simple_one_for_one() {
11706 Vec::new()
11707 } else {
11708 vec![ChildSpec {
11709 caixa: "worker".into(),
11710 versao: "^0.1".into(),
11711 restart: RestartPolicy::Permanent,
11712 }]
11713 };
11714 let s = SupervisorSpec {
11715 estrategia,
11716 children,
11717 ..SupervisorSpec::default()
11718 };
11719 assert_eq!(
11720 s.estrategia(),
11721 estrategia,
11722 "SupervisorSpec::estrategia must return :supervisor :estrategia \
11723 verbatim (got {:?}, expected {estrategia:?})",
11724 s.estrategia(),
11725 );
11726 assert_eq!(
11727 s.estrategia(),
11728 s.estrategia,
11729 "SupervisorSpec::estrategia accessor and .estrategia field \
11730 access must byte-equal — the accessor is the substrate-\
11731 primitive typed dispatch every downstream sibling-restart-\
11732 strategy consumer must route through",
11733 );
11734 }
11735 }
11736
11737 #[test]
11738 fn validate_reads_through_lifted_estrategia_accessor() {
11739 // Two-consumer coherence pin: the [`SupervisorSpec::validate`]
11740 // `SimpleOneForOne ↔ non-SimpleOneForOne` `match` partition
11741 // dispatch (which reads through [`SupervisorSpec::estrategia`]
11742 // to fan across the strategy-arm shape-gate cascades) and the
11743 // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
11744 // error carrier's `estrategia:` field (which reads through
11745 // [`SupervisorSpec::estrategia`] to name the strategy the empty
11746 // `:children` list was declared against) must both key off the
11747 // lifted accessor, so any future rebrand on the typed slot's
11748 // reader shape lands at exactly one place. Pins the two-site
11749 // coherence by exercising the `NoChildren` error surface end-to-
11750 // end across every non-`SimpleOneForOne` variant and asserting
11751 // the surfaced `estrategia:` field byte-equals the accessor's
11752 // return. Peer of the sibling M3
11753 // `validate_placement_reads_through_lifted_estrategia_accessor`
11754 // (921fe1b) three-consumer coherence pin on the per-`:placement`
11755 // distribution-strategy axis.
11756 for estrategia in [
11757 RestartStrategy::OneForOne,
11758 RestartStrategy::OneForAll,
11759 RestartStrategy::RestForOne,
11760 ] {
11761 let s = SupervisorSpec {
11762 estrategia,
11763 children: Vec::new(),
11764 ..SupervisorSpec::default()
11765 };
11766 let err = s.validate().unwrap_err();
11767 match err {
11768 SupervisorError::NoChildren { estrategia: e } => {
11769 assert_eq!(
11770 e,
11771 s.estrategia(),
11772 "NoChildren.estrategia must byte-equal \
11773 SupervisorSpec::estrategia() — the empty-`:children` \
11774 refusal reads through the lifted accessor",
11775 );
11776 assert_eq!(
11777 e, estrategia,
11778 "NoChildren.estrategia must carry the author-declared \
11779 :supervisor :estrategia variant verbatim (got {e:?}, \
11780 expected {estrategia:?})",
11781 );
11782 }
11783 other => panic!("expected NoChildren, got {other:?} for estrategia={estrategia:?}"),
11784 }
11785 }
11786 }
11787
11788 // ── per-`:supervisor` `:max-restarts` typed-accessor coherence pins ────
11789 //
11790 // The [`SupervisorSpec::max_restarts`] accessor lift extends the peer M3
11791 // [`crate::CircuitBreaker::max_failures`] (3a74062) `Copy`-return
11792 // required-`u32` scalar accessor discipline onto the M2 supervisor-slot
11793 // per-`:supervisor` restart-budget-count `Copy`-`u32` scalar axis.
11794 // The two pins below cover (1) the accessor's byte-equal projection
11795 // against the raw field access across every representative value in
11796 // the `u32` accept-set (`1` lower boundary, `SUPERVISOR_MAX_RESTARTS_MAX`
11797 // upper boundary, `0` past-the-guard zero sentinel, `u32::MAX`
11798 // past-the-guard cap sentinel), and (2) the [`SupervisorSpec::validate`]
11799 // zero-floor / cap composition — the validate gate and the accessor
11800 // must route through the same substrate-primitive typed dispatch, so
11801 // any future silent detour that had the accessor perform a
11802 // bounds-collapsing clamp would fail here at caixa-core build time.
11803 // Peer of the sibling M3
11804 // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
11805 // (3a74062) pin on the per-`CircuitBreaker :max-failures` axis.
11806
11807 #[test]
11808 fn supervisor_spec_max_restarts_returns_max_restarts_u32_byte_equal_across_permutations() {
11809 // The canonical per-`:supervisor` restart-budget-count scalar pin:
11810 // [`SupervisorSpec::max_restarts`] must return the `:supervisor
11811 // :max-restarts` typed `u32` verbatim, `Copy`-projected from the
11812 // typed slot's own `u32` storage, byte-equal to the raw field
11813 // access across every representative value in the accept-set —
11814 // `1` (the lower boundary of the `1..=SUPERVISOR_MAX_RESTARTS_MAX`
11815 // accept-set the surrounding [`SupervisorSpec::validate`] gate
11816 // carves out on the sibling `ZeroMaxRestarts` refusal),
11817 // `SUPERVISOR_MAX_RESTARTS_MAX` (the upper boundary the same gate
11818 // carves out on the sibling `MaxRestartsExceedsCap` refusal), `0`
11819 // (a past-the-guard sentinel that pins the accessor doesn't
11820 // perform a silent bounds-collapse into `1` on the zero arm —
11821 // validate rejects zero but the accessor must ship the raw slot
11822 // verbatim so a validate-time gate regression surfaces at the
11823 // emit boundary rather than being silently absorbed), `u32::MAX`
11824 // (a past-the-guard sentinel that pins the accessor doesn't
11825 // perform a silent bounds-collapse through
11826 // `SUPERVISOR_MAX_RESTARTS_MAX` at the return path).
11827 //
11828 // Peer of the sibling M3
11829 // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
11830 // (3a74062) pin on the M3 mesh-slot `Copy`-`u32` sub-struct
11831 // required-scalar axis — same "the substrate-primitive accessor
11832 // must byte-equal the raw field access verbatim across every
11833 // value in the `u32` accept-set" discipline extended onto the M2
11834 // supervisor-slot per-`:supervisor` restart-budget-count axis.
11835 for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX, 0, u32::MAX] {
11836 let s = SupervisorSpec {
11837 max_restarts,
11838 ..SupervisorSpec::default()
11839 };
11840 assert_eq!(
11841 s.max_restarts(),
11842 max_restarts,
11843 "SupervisorSpec::max_restarts must return :supervisor \
11844 :max-restarts verbatim (got {}, expected {max_restarts})",
11845 s.max_restarts(),
11846 );
11847 assert_eq!(
11848 s.max_restarts(),
11849 s.max_restarts,
11850 "SupervisorSpec::max_restarts accessor and .max_restarts \
11851 field access must byte-equal — the accessor is the \
11852 substrate-primitive typed dispatch every downstream \
11853 restart-budget-count consumer must route through",
11854 );
11855 }
11856 }
11857
11858 #[test]
11859 fn validate_max_restarts_zero_floor_and_cap_arms_route_through_accessor() {
11860 // Composition pin: [`SupervisorSpec::validate`]'s `:max-restarts`
11861 // zero-floor + upper-cap bracket must key off
11862 // [`SupervisorSpec::max_restarts`], not the raw `.max_restarts`
11863 // field access. Structurally: a `SupervisorSpec { max_restarts:
11864 // 0, .. }` must surface the `ZeroMaxRestarts` refusal exactly, a
11865 // `SupervisorSpec { max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
11866 // .. }` must surface the `MaxRestartsExceedsCap` refusal exactly
11867 // (with the offending count carried verbatim from the accessor
11868 // return), and a `SupervisorSpec { max_restarts: 1, .. }` (the
11869 // lower boundary of the accept-set) plus a `SupervisorSpec {
11870 // max_restarts: SUPERVISOR_MAX_RESTARTS_MAX, .. }` (the upper
11871 // boundary) must pass validate. The four together jointly pin the
11872 // accessor + validate-gate composition: any future silent detour
11873 // that had the accessor return a fresh `1` on the zero arm (a
11874 // `.max_restarts().max(1)` collapse) would silently absorb the
11875 // `ZeroMaxRestarts` refusal at the accessor boundary and the
11876 // validate gate would accept a struct-literal `SupervisorSpec {
11877 // max_restarts: 0, .. }` — the composition pin catches that at
11878 // caixa-core build time.
11879 //
11880 // Peer of the sibling M3
11881 // `validate_politicas_max_failures_zero_floor_arm_routes_through_accessor`
11882 // (3a74062) pin on the sibling per-`CircuitBreaker :max-failures`
11883 // composition axis — same "the validate / shape-gate predicate
11884 // must route through the substrate-primitive typed dispatch"
11885 // discipline extended onto the peer M2 supervisor-slot
11886 // required-`u32` composition axis.
11887 let child = ChildSpec {
11888 caixa: "worker".into(),
11889 versao: "^0.1".into(),
11890 restart: RestartPolicy::Permanent,
11891 };
11892 // Zero-floor arm.
11893 let s = SupervisorSpec {
11894 max_restarts: 0,
11895 children: vec![child.clone()],
11896 ..SupervisorSpec::default()
11897 };
11898 assert_eq!(
11899 s.validate().unwrap_err(),
11900 SupervisorError::ZeroMaxRestarts,
11901 "validate must reject max_restarts == 0 with ZeroMaxRestarts \
11902 — the accessor and the validate gate must route through the \
11903 same substrate-primitive typed dispatch on the zero-floor arm",
11904 );
11905 // Cap arm — the surfaced `max_restarts:` field must byte-equal
11906 // the accessor's return so a future rebrand on the accessor
11907 // lands in the diagnostic without a coordinated rewrite.
11908 let over_cap = SUPERVISOR_MAX_RESTARTS_MAX + 1;
11909 let s = SupervisorSpec {
11910 max_restarts: over_cap,
11911 children: vec![child.clone()],
11912 ..SupervisorSpec::default()
11913 };
11914 match s.validate().unwrap_err() {
11915 SupervisorError::MaxRestartsExceedsCap { max_restarts } => {
11916 assert_eq!(
11917 max_restarts,
11918 s.max_restarts(),
11919 "MaxRestartsExceedsCap.max_restarts must byte-equal \
11920 SupervisorSpec::max_restarts() — the cap-arm refusal \
11921 reads through the lifted accessor",
11922 );
11923 assert_eq!(
11924 max_restarts, over_cap,
11925 "MaxRestartsExceedsCap.max_restarts must carry the \
11926 author-declared :supervisor :max-restarts value \
11927 verbatim (got {max_restarts}, expected {over_cap})",
11928 );
11929 }
11930 other => panic!("expected MaxRestartsExceedsCap, got {other:?}"),
11931 }
11932 // Lower + upper accept-set boundaries.
11933 for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX] {
11934 let s = SupervisorSpec {
11935 max_restarts,
11936 children: vec![child.clone()],
11937 ..SupervisorSpec::default()
11938 };
11939 assert!(
11940 s.validate().is_ok(),
11941 "validate must accept max_restarts == {max_restarts} \
11942 (an accept-set boundary of \
11943 1..=SUPERVISOR_MAX_RESTARTS_MAX)",
11944 );
11945 }
11946 }
11947
11948 // ── per-`:supervisor` `:restart-window` typed-accessor coherence pins ─
11949 //
11950 // The [`SupervisorSpec::restart_window`] accessor lift extends the peer
11951 // M2 [`crate::LimitsSpec::wall_clock`] (8cb717b) `Option<Duration>`
11952 // accessor discipline and the peer M3 [`crate::MeshPolicy::timeout`]
11953 // (7073d0f) `Option<Duration>` accessor discipline onto the M2
11954 // supervisor-slot per-`:supervisor` restart-intensity-denominator
11955 // `Option<Duration>` scalar axis — third `Copy`-return accessor on the
11956 // M2 supervisor-slot `SupervisorSpec` type, closing the last unlifted
11957 // per-`:supervisor` scalar-value axis. The three pins below cover
11958 // (1) the accessor's byte-equal projection against the raw field
11959 // access across every representative value in the `Option<Duration>`
11960 // accept-set (`None` never-reset sentinel, `Some(Duration::from_millis(1))`
11961 // lower boundary, `Some(SUPERVISOR_RESTART_WINDOW_MAX)` upper boundary,
11962 // `Some(Duration::ZERO)` past-the-guard zero sentinel, `Some(Duration::MAX)`
11963 // past-the-guard above-cap sentinel), (2) the [`SupervisorSpec::validate`]
11964 // `if let Some(w) = self.restart_window() { … }` bracket-arm
11965 // composition — the validate gate and the accessor must route through
11966 // the same substrate-primitive typed dispatch, so any future silent
11967 // detour that had the accessor perform a bounds-collapsing clamp
11968 // would fail here at caixa-core build time, and (3) the accessor's
11969 // by-copy idempotence pin — the returned `Option<Duration>` must
11970 // outlive `&self` and two successive calls must return byte-equal
11971 // values. Peer of the sibling M2
11972 // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
11973 // (8cb717b) pin on the per-`:limits :wall-clock` axis and the sibling
11974 // M3 `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
11975 // (7073d0f) pin on the per-`:politicas :timeout` axis.
11976
11977 #[test]
11978 fn supervisor_spec_restart_window_returns_option_duration_byte_equal_across_permutations() {
11979 // The canonical per-`:supervisor` restart-intensity-denominator
11980 // scalar pin: [`SupervisorSpec::restart_window`] must return the
11981 // `:supervisor :restart-window` typed [`Duration`] verbatim as an
11982 // `Option<Duration>`, `Copy`-projected from the typed slot's own
11983 // `Option<Duration>` storage, byte-equal to the raw field access
11984 // across every representative value in the accept-set — `None`
11985 // (the "never reset — every restart across the supervisor's
11986 // lifetime counts against the sibling `:max-restarts` budget"
11987 // sentinel the field's own docstring names and the peer
11988 // `validate_accepts_none_restart_window` pin locks in on the
11989 // [`SupervisorSpec::validate`] entry-side),
11990 // `Some(Duration::from_millis(1))` (the structural minimum a
11991 // validated `:restart-window` may carry, the integer-millisecond
11992 // floor [`SupervisorError::RestartWindowNotCanonical`] rejects
11993 // everything sub-ms; `Duration::ZERO` is separately rejected by
11994 // [`SupervisorError::RestartWindowZero`]),
11995 // `Some(SUPERVISOR_RESTART_WINDOW_MAX)` (the upper boundary the
11996 // surrounding [`SupervisorSpec::validate`] gate carves out on the
11997 // sibling [`SupervisorError::RestartWindowExceedsCap`] refusal),
11998 // `Some(Duration::ZERO)` (a past-the-guard sentinel that pins the
11999 // accessor doesn't perform a silent bounds-collapse into `None` on
12000 // the zero-Duration arm — validate rejects zero but the accessor
12001 // must ship the raw slot verbatim so a validate-time gate
12002 // regression surfaces at the emit boundary rather than being
12003 // silently absorbed), and `Some(Duration::MAX)` (a past-the-guard
12004 // sentinel that pins the accessor doesn't perform a silent
12005 // bounds-collapse through [`SUPERVISOR_RESTART_WINDOW_MAX`] at the
12006 // return path).
12007 //
12008 // Peer of the sibling M2
12009 // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
12010 // (8cb717b) pin on the per-`:limits :wall-clock` axis and the
12011 // sibling M3
12012 // `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
12013 // (7073d0f) pin on the per-`:politicas :timeout` axis — same "the
12014 // substrate-primitive accessor must byte-equal the raw field
12015 // access verbatim across every value in the `Option<Duration>`
12016 // accept-set" discipline extended onto the M2 supervisor-slot
12017 // per-`:supervisor` `Option<Duration>` axis. Pins against a future
12018 // silent detour that re-derived the restart-window from a peer
12019 // axis (an accidental `.max_restarts.into()` collapse that read
12020 // the restart-budget-count as a duration — the two axes serve
12021 // different halves of the `MaxIntensity / Period` restart-
12022 // intensity ratio, and confusing them silently inverts the
12023 // ratio's numerator and denominator), a `None → Some(Duration::ZERO)`
12024 // "zero means never reset" collapse (the canonical
12025 // `Option<Duration>` → `Duration` collapse footgun the
12026 // [`SupervisorError::RestartWindowZero`] validate arm guards on
12027 // the peer zero-floor axis; a zero period either trips on the
12028 // first failure or never trips depending on operator
12029 // interpretation, neither of which is the author's "never reset"
12030 // intent that `None` expresses structurally), or a per-arm
12031 // variant swap that landed on one consumer without the other.
12032 for restart_window in [
12033 None,
12034 Some(Duration::from_millis(1)),
12035 Some(SUPERVISOR_RESTART_WINDOW_MAX),
12036 Some(Duration::ZERO),
12037 Some(Duration::MAX),
12038 ] {
12039 let s = SupervisorSpec {
12040 restart_window,
12041 ..SupervisorSpec::default()
12042 };
12043 assert_eq!(
12044 s.restart_window(),
12045 restart_window,
12046 "SupervisorSpec::restart_window must return :supervisor \
12047 :restart-window verbatim (got {:?}, expected {restart_window:?})",
12048 s.restart_window(),
12049 );
12050 assert_eq!(
12051 s.restart_window(),
12052 s.restart_window,
12053 "SupervisorSpec::restart_window accessor and \
12054 .restart_window field access must byte-equal — the \
12055 accessor is the substrate-primitive typed dispatch every \
12056 downstream restart-intensity-denominator consumer must \
12057 route through",
12058 );
12059 }
12060 }
12061
12062 #[test]
12063 fn validate_restart_window_bracket_arm_routes_through_accessor() {
12064 // Composition pin: [`SupervisorSpec::validate`]'s
12065 // `:restart-window` `if let Some(w) = self.restart_window() { … }`
12066 // zero-floor + integer-millisecond canonical-form + upper-cap
12067 // bracket-arm must key off [`SupervisorSpec::restart_window`], not
12068 // the raw `.restart_window` field access. Structurally: a
12069 // `SupervisorSpec { restart_window: None, .. }` must pass the
12070 // arm gate structurally (the `if let Some(_)` shape returns
12071 // early on the `None` arm — the accessor and the validate gate
12072 // must agree on `None → skip the bracket cascade` so an authored
12073 // `:restart-window ()` structurally routes through the "never
12074 // reset" sentinel path), a `SupervisorSpec { restart_window:
12075 // Some(Duration::ZERO), .. }` must surface the `RestartWindowZero`
12076 // refusal exactly, a `SupervisorSpec { restart_window:
12077 // Some(Duration::from_micros(1500)), .. }` must surface the
12078 // `RestartWindowNotCanonical` refusal exactly (with the offending
12079 // duration carried verbatim from the accessor return), a
12080 // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX
12081 // + Duration::from_millis(1)), .. }` must surface the
12082 // `RestartWindowExceedsCap` refusal exactly (with the offending
12083 // duration carried verbatim from the accessor return), and a
12084 // `SupervisorSpec { restart_window: Some(Duration::from_millis(1)),
12085 // .. }` (the lower boundary of the accept-set) plus a
12086 // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
12087 // .. }` (the upper boundary) must pass validate. The six together
12088 // jointly pin the accessor + validate-gate composition: any future
12089 // silent detour that had the accessor return a fresh `None` on any
12090 // `Some` arm (a `.restart_window().filter(|w| !w.is_zero())`
12091 // collapse) would silently absorb the `RestartWindowZero` refusal
12092 // at the accessor boundary and the validate gate would accept a
12093 // struct-literal `SupervisorSpec { restart_window:
12094 // Some(Duration::ZERO), .. }` — the composition pin catches that
12095 // at caixa-core build time.
12096 //
12097 // Peer of the sibling M2 [`crate::LimitsSpec::wall_clock`]
12098 // (8cb717b) validate-arm-route pin on the per-`:limits :wall-clock`
12099 // axis and the peer M3 [`crate::MeshPolicy::timeout`] (7073d0f)
12100 // accessor-composition pin on the per-`:politicas :timeout` axis —
12101 // same "the validate / shape-gate predicate must route through
12102 // the substrate-primitive typed dispatch" discipline extended
12103 // onto the peer M2 supervisor-slot optional-`Duration` axis.
12104 let child = ChildSpec {
12105 caixa: "worker".into(),
12106 versao: "^0.1".into(),
12107 restart: RestartPolicy::Permanent,
12108 };
12109 // None arm — must not surface any :restart-window-shaped refusal;
12110 // the `if let Some(_)` bracket returns early on `None` structurally.
12111 let s = SupervisorSpec {
12112 restart_window: None,
12113 children: vec![child.clone()],
12114 ..SupervisorSpec::default()
12115 };
12116 assert!(
12117 s.validate().is_ok(),
12118 "validate must accept restart_window: None (the never-reset \
12119 sentinel) — the `if let Some(_)` bracket returns early on \
12120 the None arm and the accessor must agree",
12121 );
12122 // Zero-floor arm.
12123 let s = SupervisorSpec {
12124 restart_window: Some(Duration::ZERO),
12125 children: vec![child.clone()],
12126 ..SupervisorSpec::default()
12127 };
12128 assert_eq!(
12129 s.validate().unwrap_err(),
12130 SupervisorError::RestartWindowZero,
12131 "validate must reject restart_window == Some(Duration::ZERO) \
12132 with RestartWindowZero — the accessor and the validate gate \
12133 must route through the same substrate-primitive typed \
12134 dispatch on the zero-floor arm",
12135 );
12136 // Non-canonical (sub-ms) arm — the surfaced `window:` field must
12137 // byte-equal the accessor's return so a future rebrand on the
12138 // accessor lands in the diagnostic without a coordinated rewrite.
12139 let sub_ms = Duration::from_micros(1500);
12140 let s = SupervisorSpec {
12141 restart_window: Some(sub_ms),
12142 children: vec![child.clone()],
12143 ..SupervisorSpec::default()
12144 };
12145 match s.validate().unwrap_err() {
12146 SupervisorError::RestartWindowNotCanonical { window } => {
12147 assert_eq!(
12148 Some(window),
12149 s.restart_window(),
12150 "RestartWindowNotCanonical.window must byte-equal \
12151 SupervisorSpec::restart_window().unwrap() — the \
12152 non-canonical-arm refusal reads through the lifted \
12153 accessor",
12154 );
12155 assert_eq!(
12156 window, sub_ms,
12157 "RestartWindowNotCanonical.window must carry the \
12158 author-declared :supervisor :restart-window value \
12159 verbatim (got {window:?}, expected {sub_ms:?})",
12160 );
12161 }
12162 other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
12163 }
12164 // Cap arm — the surfaced `window:` field must byte-equal the
12165 // accessor's return.
12166 let over_cap = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
12167 let s = SupervisorSpec {
12168 restart_window: Some(over_cap),
12169 children: vec![child.clone()],
12170 ..SupervisorSpec::default()
12171 };
12172 match s.validate().unwrap_err() {
12173 SupervisorError::RestartWindowExceedsCap { window } => {
12174 assert_eq!(
12175 Some(window),
12176 s.restart_window(),
12177 "RestartWindowExceedsCap.window must byte-equal \
12178 SupervisorSpec::restart_window().unwrap() — the \
12179 cap-arm refusal reads through the lifted accessor",
12180 );
12181 assert_eq!(
12182 window, over_cap,
12183 "RestartWindowExceedsCap.window must carry the \
12184 author-declared :supervisor :restart-window value \
12185 verbatim (got {window:?}, expected {over_cap:?})",
12186 );
12187 }
12188 other => panic!("expected RestartWindowExceedsCap, got {other:?}"),
12189 }
12190 // Lower + upper accept-set boundaries.
12191 for restart_window in [Duration::from_millis(1), SUPERVISOR_RESTART_WINDOW_MAX] {
12192 let s = SupervisorSpec {
12193 restart_window: Some(restart_window),
12194 children: vec![child.clone()],
12195 ..SupervisorSpec::default()
12196 };
12197 assert!(
12198 s.validate().is_ok(),
12199 "validate must accept restart_window == Some({restart_window:?}) \
12200 (an accept-set boundary of \
12201 1ms..=SUPERVISOR_RESTART_WINDOW_MAX)",
12202 );
12203 }
12204 }
12205
12206 #[test]
12207 fn supervisor_spec_restart_window_projects_option_duration_by_copy() {
12208 // The by-copy pin: [`SupervisorSpec::restart_window`] returns
12209 // `Option<Duration>` by copy — `Duration` is `Copy` (so
12210 // `Option<Duration>` is `Copy`) and the accessor must return by
12211 // value, not by reference. Peer of the sibling M2
12212 // [`crate::LimitsSpec::wall_clock`] (8cb717b) by-copy pin on the
12213 // per-`:limits :wall-clock` axis and the sibling M3
12214 // [`crate::MeshPolicy::timeout`] (7073d0f) by-copy pin on the
12215 // per-`:politicas :timeout` axis, extended onto the peer M2
12216 // supervisor-slot `Option<Duration>` copy-invariant shape — the
12217 // accessor's returned `Option<Duration>` must outlive `&self`
12218 // (multiple calls must return equal values from a dropped-`&self`
12219 // copy, since the returned Option carries no borrow), and calling
12220 // the accessor twice on the same SupervisorSpec must yield the
12221 // same `Option<Duration>` verbatim (idempotent, no side effects
12222 // on `&self`).
12223 //
12224 // Pins against a future silent detour that returned
12225 // `Option<&Duration>` (which would type-check but silently break
12226 // every downstream caller — the future wasm-operator's
12227 // per-supervisor restart-intensity counter consumes `Duration` by
12228 // value and `&Duration` would fold to a detached copy at the call
12229 // site), an accidental `Option::as_ref()` projection
12230 // (`self.restart_window.as_ref()` would also type-check but
12231 // return `Option<&Duration>`), or a one-arm-only accessor that
12232 // reads `Some(*w)` in the Some arm but reads a fresh
12233 // `Default::default()` (which would collapse to `Duration::ZERO`,
12234 // not `None`) in the None arm — a footgun the
12235 // [`SupervisorError::RestartWindowZero`] validate arm explicitly
12236 // closes since Erlang/OTP's `MaxIntensity / Period` invariant
12237 // requires `Period > 0` and `None` structurally expresses "never
12238 // reset" instead.
12239 for restart_window in [
12240 None,
12241 Some(Duration::from_millis(1)),
12242 Some(Duration::from_secs(60)),
12243 Some(SUPERVISOR_RESTART_WINDOW_MAX),
12244 ] {
12245 let s = SupervisorSpec {
12246 restart_window,
12247 ..SupervisorSpec::default()
12248 };
12249 let first = s.restart_window();
12250 let second = s.restart_window();
12251 assert_eq!(
12252 first, second,
12253 "SupervisorSpec::restart_window must be idempotent — two \
12254 successive calls on the same &self must return the \
12255 same Option<Duration>",
12256 );
12257 assert_eq!(
12258 first, restart_window,
12259 "SupervisorSpec::restart_window must return :supervisor \
12260 :restart-window verbatim by copy — got {first:?}, \
12261 expected {restart_window:?}",
12262 );
12263 }
12264 }
12265
12266 // ── per-`:supervisor` `:children` typed-accessor coherence pins ─────────
12267 //
12268 // The [`SupervisorSpec::children`] accessor lift is the seed of the
12269 // slice-return (`&[T]`) accessor discipline on the substrate — the four
12270 // peer `Vec`-carry axes ([`crate::Placement::clusters`],
12271 // [`crate::AplicacaoSpec::membros`], [`crate::AplicacaoSpec::contratos`],
12272 // [`crate::UpgradeFromEntry::instructions`]) still key off the raw field
12273 // access at the time of this seed, and inherit this pin family's
12274 // discipline as future compounding runs migrate their consumers. The
12275 // three pins below cover (1) the accessor's byte-equal projection
12276 // against the raw field access across the empty / singleton / cohort
12277 // fixtures the [`SupervisorSpec::validate`] partition-dispatch fans
12278 // between, (2) the [`SupervisorSpec::validate`] `SimpleOneForOne ↔
12279 // non-SimpleOneForOne` partition dispatch's paired `.is_empty()`
12280 // consumer routing through the accessor on both arms, and (3) the
12281 // per-child validate loop's traversal reading the same slice-view the
12282 // accessor projects. Peer of the sibling M2
12283 // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
12284 // two-consumer coherence pin on the per-`:supervisor`
12285 // sibling-restart-strategy `Copy`-composite-enum scalar axis, extended
12286 // onto the per-`:supervisor` static-child-list `Vec`-carry axis.
12287
12288 #[test]
12289 fn supervisor_spec_children_returns_children_slice_byte_equal_across_permutations() {
12290 // The canonical per-`:supervisor` static-child-list scalar-shape
12291 // pin: [`SupervisorSpec::children`] must return the `:supervisor
12292 // :children` typed `Vec<ChildSpec>` verbatim as a `&[ChildSpec]`
12293 // slice-view over the same backing buffer the raw
12294 // `self.children.as_slice()` field access borrows from, byte-
12295 // equal across every representative fixture in the accept-set —
12296 // the empty slice (the `SimpleOneForOne`-arm sentinel),
12297 // the singleton slice (the minimal non-`SimpleOneForOne` shape),
12298 // and a two-child cohort (a peer non-`SimpleOneForOne` shape
12299 // with the peer three restart-policy variants in play).
12300 //
12301 // Pins against a future silent detour that returned
12302 // `&Vec<ChildSpec>` (which would type-check but leak the
12303 // storage-side `Vec`'s grow/push/reserve surface no consumer of
12304 // the typed view reaches for), a fresh-allocated
12305 // `Vec<ChildSpec>` copy (which would type-check via a coercion
12306 // but silently break every downstream caller that relied on the
12307 // slice sharing the backing buffer's identity), or an
12308 // out-of-order or length-drifted projection (which would silently
12309 // split the per-child validate loop's traversal input from the
12310 // paired partition-dispatch `.is_empty()` probe's input).
12311 //
12312 // Peer of the sibling
12313 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
12314 // (eafb619) `Copy`-composite-enum byte-equal pin on the
12315 // per-`:supervisor` sibling-restart-strategy axis, extended onto
12316 // the per-`:supervisor` static-child-list `Vec`-carry axis.
12317 let fixtures: Vec<Vec<ChildSpec>> = vec![
12318 Vec::new(),
12319 vec![child("worker", "^0.1", RestartPolicy::Permanent)],
12320 vec![
12321 child("worker", "^0.1", RestartPolicy::Permanent),
12322 child("cache-server", "^0.1", RestartPolicy::Transient),
12323 ],
12324 vec![
12325 child("worker", "^0.1", RestartPolicy::Permanent),
12326 child("cache-server", "^0.1", RestartPolicy::Transient),
12327 child("scratch-job", "^0.1", RestartPolicy::Temporary),
12328 ],
12329 ];
12330 for children in fixtures {
12331 let s = SupervisorSpec {
12332 children: children.clone(),
12333 ..SupervisorSpec::default()
12334 };
12335 assert_eq!(
12336 s.children(),
12337 children.as_slice(),
12338 "SupervisorSpec::children must return :supervisor \
12339 :children verbatim (got {:?}, expected {:?})",
12340 s.children(),
12341 children.as_slice(),
12342 );
12343 assert_eq!(
12344 s.children(),
12345 s.children.as_slice(),
12346 "SupervisorSpec::children accessor and \
12347 .children.as_slice() field access must byte-equal — \
12348 the accessor is the substrate-primitive typed \
12349 dispatch every downstream static-child-list consumer \
12350 must route through",
12351 );
12352 assert_eq!(
12353 s.children().len(),
12354 s.children.len(),
12355 "SupervisorSpec::children().len() must byte-equal \
12356 self.children.len() — a length-drift would silently \
12357 split the paired partition-dispatch `.is_empty()` \
12358 probe input from the per-child validate loop's \
12359 traversal input",
12360 );
12361 }
12362 }
12363
12364 #[test]
12365 fn validate_reads_through_lifted_children_accessor() {
12366 // Three-consumer coherence pin: the [`SupervisorSpec::validate`]
12367 // `SimpleOneForOne`-arm `!self.children().is_empty()` refusal
12368 // probe (which must trip [`SupervisorError::SimpleOneForOneWithStaticChildren`]
12369 // when the accessor projects a non-empty slice under a
12370 // `SimpleOneForOne` estrategia), the peer non-`SimpleOneForOne`-arm
12371 // `self.children().is_empty()` refusal probe (which must trip
12372 // [`SupervisorError::NoChildren`] when the accessor projects the
12373 // empty slice under any peer estrategia), and the per-child
12374 // validate loop's `for child in self.children()` traversal
12375 // (which must reach every entry in the same order the accessor
12376 // projects) must all key off the lifted accessor, so any future
12377 // rebrand on the typed slot's reader shape lands at exactly one
12378 // place. Pins the three-site coherence by exercising each
12379 // production consumer end-to-end: (1) the
12380 // `SimpleOneForOneWithStaticChildren` refusal under a non-empty
12381 // slice + `SimpleOneForOne` estrategia, (2) the `NoChildren`
12382 // refusal under the empty slice + non-`SimpleOneForOne`
12383 // estrategia across every peer variant, and (3) the per-child
12384 // duplicate-detection surface fires on the second entry of a
12385 // two-child cohort that shares a `:caixa` name (which requires
12386 // the loop to reach both entries — a first-entry-only projection
12387 // would silently pass since the dedup HashSet has room for the
12388 // first insert).
12389 //
12390 // Peer of the sibling M2
12391 // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
12392 // two-consumer coherence pin on the per-`:supervisor`
12393 // sibling-restart-strategy axis, extended onto the
12394 // per-`:supervisor` static-child-list `Vec`-carry axis.
12395
12396 // (1) `SimpleOneForOne`-arm probe: a non-empty slice under a
12397 // `SimpleOneForOne` estrategia must trip
12398 // `SimpleOneForOneWithStaticChildren`.
12399 let s = SupervisorSpec {
12400 estrategia: RestartStrategy::SimpleOneForOne,
12401 children: vec![child("worker", "^0.1", RestartPolicy::Permanent)],
12402 ..SupervisorSpec::default()
12403 };
12404 assert_eq!(
12405 s.validate().unwrap_err(),
12406 SupervisorError::SimpleOneForOneWithStaticChildren,
12407 "SimpleOneForOne + non-empty children must trip \
12408 SimpleOneForOneWithStaticChildren — the accessor projects \
12409 a non-empty slice, and the SimpleOneForOne-arm refusal \
12410 probe reads through the lifted accessor",
12411 );
12412 assert!(
12413 !s.children().is_empty(),
12414 "the SimpleOneForOne-arm refusal input must be a non-empty \
12415 slice per the accessor's projection",
12416 );
12417
12418 // (2) Peer non-`SimpleOneForOne`-arm probe: the empty slice
12419 // under any peer estrategia must trip `NoChildren`.
12420 for estrategia in [
12421 RestartStrategy::OneForOne,
12422 RestartStrategy::OneForAll,
12423 RestartStrategy::RestForOne,
12424 ] {
12425 let s = SupervisorSpec {
12426 estrategia,
12427 children: Vec::new(),
12428 ..SupervisorSpec::default()
12429 };
12430 match s.validate().unwrap_err() {
12431 SupervisorError::NoChildren { estrategia: e } => {
12432 assert_eq!(
12433 e, estrategia,
12434 "NoChildren.estrategia must carry the author-\
12435 declared :supervisor :estrategia variant \
12436 verbatim (got {e:?}, expected {estrategia:?})",
12437 );
12438 }
12439 other => panic!(
12440 "expected NoChildren, got {other:?} for \
12441 estrategia={estrategia:?}"
12442 ),
12443 }
12444 assert!(
12445 s.children().is_empty(),
12446 "the non-SimpleOneForOne-arm refusal input must be the \
12447 empty slice per the accessor's projection",
12448 );
12449 }
12450
12451 // (3) Per-child validate loop: a two-child cohort that shares a
12452 // `:caixa` name must trip `DuplicateChildCaixa` — the loop must
12453 // reach both entries through the accessor.
12454 let s = SupervisorSpec {
12455 estrategia: RestartStrategy::OneForOne,
12456 children: vec![
12457 child("worker", "^0.1", RestartPolicy::Permanent),
12458 child("worker", "^0.2", RestartPolicy::Transient),
12459 ],
12460 ..SupervisorSpec::default()
12461 };
12462 match s.validate().unwrap_err() {
12463 SupervisorError::DuplicateChildCaixa { caixa } => {
12464 assert_eq!(
12465 caixa, "worker",
12466 "DuplicateChildCaixa.caixa must carry the shared \
12467 child `:caixa` name verbatim",
12468 );
12469 }
12470 other => panic!("expected DuplicateChildCaixa, got {other:?}"),
12471 }
12472 assert_eq!(
12473 s.children().len(),
12474 2,
12475 "the per-child validate loop's traversal input must be a \
12476 two-element slice per the accessor's projection",
12477 );
12478 }
12479
12480 // Shared helper for the M2 per-`:children` per-slot-gate ≡
12481 // `validate` equivalence pins: builds an `OneForOne`-estrategia
12482 // one-cohort spec whose peer `:estrategia`↔`:children.is_empty()`
12483 // partition, `:max-restarts` zero-floor/cap, and `:restart-window`
12484 // bracket all pass cleanly so the sole failing surface is the
12485 // per-child cascade [`SupervisorSpec::validate_children`] owns, and
12486 // pins the two-altitude equivalence on the paired probe.
12487 fn assert_validate_children_matches_gate(children: Vec<ChildSpec>, expected: &SupervisorError) {
12488 let s = SupervisorSpec {
12489 estrategia: RestartStrategy::OneForOne,
12490 children,
12491 ..SupervisorSpec::default()
12492 };
12493 let via_gate = s.validate_children().unwrap_err();
12494 let via_validate = s.validate().unwrap_err();
12495 assert_eq!(&via_gate, expected, "validate_children direct dispatch",);
12496 assert_eq!(&via_validate, expected, "validate() end-to-end dispatch",);
12497 assert_eq!(
12498 via_gate, via_validate,
12499 "per-slot gate ≡ validate() must discriminate the same \
12500 refusal shape",
12501 );
12502 }
12503
12504 #[test]
12505 fn validate_children_matches_gate_on_per_axis_refusal_shapes() {
12506 // Fail-before-pass-after equivalence pin on the M2
12507 // per-`:children` per-slot gate ≡ [`SupervisorSpec::validate`]
12508 // convergence — sibling of the M3 mesh-slot
12509 // `validate_membros_*` / `validate_contratos_*` /
12510 // `validate_entrada_*` per-slot-gate ≡ `validate` pins on the
12511 // peer per-entry axes. Sweeps four of the five refusal shapes
12512 // the per-slot gate owns: (1) `EmptyChildName` on an empty-
12513 // `:caixa` child, (2) `ChildCaixaInvalid` on a structurally
12514 // invalid `:caixa` DNS-1123 label, (3) `EmptyChildVersion` on
12515 // an empty-`:versao` child, (4) `DuplicateChildCaixa` on a
12516 // duplicate-`:caixa` fan-out. Companion pin
12517 // `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
12518 // covers `ChildVersaoInvalid` (whose parser-owned reason string
12519 // needs pattern-matching, not equality) and the clean-pass
12520 // canonical fixture; together the two pins guarantee the
12521 // per-slot gate and `validate` discriminate the same set on
12522 // every per-child-covered input.
12523 assert_validate_children_matches_gate(
12524 vec![child("", "^0.1", RestartPolicy::Permanent)],
12525 &SupervisorError::EmptyChildName,
12526 );
12527 assert_validate_children_matches_gate(
12528 vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
12529 &SupervisorError::ChildCaixaInvalid {
12530 caixa: "Worker".into(),
12531 reason: "contains uppercase character 'W' (K8s DNS-1123 label names are lowercase-only; use \"worker\")".into(),
12532 },
12533 );
12534 assert_validate_children_matches_gate(
12535 vec![child("worker", "", RestartPolicy::Permanent)],
12536 &SupervisorError::EmptyChildVersion {
12537 caixa: "worker".into(),
12538 },
12539 );
12540 assert_validate_children_matches_gate(
12541 vec![
12542 child("worker", "^0.1", RestartPolicy::Permanent),
12543 child("worker", "^0.2", RestartPolicy::Transient),
12544 ],
12545 &SupervisorError::DuplicateChildCaixa {
12546 caixa: "worker".into(),
12547 },
12548 );
12549 }
12550
12551 #[test]
12552 fn validate_children_matches_gate_on_versao_invalid_and_clean_pass() {
12553 // Second half of the two-altitude equivalence pin — covers the
12554 // one refusal shape whose reason string is parser-owned
12555 // (`ChildVersaoInvalid`, whose reason comes from the shared
12556 // [`crate::version::parse_requirement`] impl and may drift) and
12557 // the clean-pass canonical fixture. Sibling pin
12558 // `validate_children_matches_gate_on_per_axis_refusal_shapes`
12559 // covers the four equality-comparable refusal shapes.
12560 let s_bad_versao = SupervisorSpec {
12561 estrategia: RestartStrategy::OneForOne,
12562 children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
12563 ..SupervisorSpec::default()
12564 };
12565 let via_gate = s_bad_versao.validate_children().unwrap_err();
12566 let via_validate = s_bad_versao.validate().unwrap_err();
12567 match (&via_gate, &via_validate) {
12568 (
12569 SupervisorError::ChildVersaoInvalid {
12570 caixa: cg,
12571 versao: vg,
12572 ..
12573 },
12574 SupervisorError::ChildVersaoInvalid {
12575 caixa: cv,
12576 versao: vv,
12577 ..
12578 },
12579 ) => {
12580 assert_eq!(cg, "worker", "per-slot gate :caixa carrier");
12581 assert_eq!(vg, "not-a-req", "per-slot gate :versao carrier");
12582 assert_eq!(cv, "worker", "validate() :caixa carrier");
12583 assert_eq!(vv, "not-a-req", "validate() :versao carrier");
12584 }
12585 other => panic!("expected ChildVersaoInvalid on both altitudes, got {other:?}"),
12586 }
12587 assert_eq!(
12588 via_gate, via_validate,
12589 "per-slot gate ≡ validate() on ChildVersaoInvalid full envelope",
12590 );
12591
12592 let s_ok = SupervisorSpec {
12593 estrategia: RestartStrategy::OneForOne,
12594 children: vec![
12595 child("worker-a", "^0.1", RestartPolicy::Permanent),
12596 child("worker-b", "~0.2.3", RestartPolicy::Transient),
12597 child("collector", "*", RestartPolicy::Temporary),
12598 ],
12599 ..SupervisorSpec::default()
12600 };
12601 s_ok.validate_children()
12602 .expect("per-slot gate must accept the clean-pass fixture");
12603 s_ok.validate()
12604 .expect("validate() must accept the clean-pass fixture");
12605 }
12606
12607 #[test]
12608 fn validate_children_is_self_contained_on_children_slot() {
12609 // Self-containment pin: [`SupervisorSpec::validate_children`]
12610 // resolves the per-child cascade against `&self` alone, without
12611 // depending on the peer `:estrategia`/`:max-restarts`/
12612 // `:restart-window` gates having run first — same posture the M3
12613 // peer per-slot gates carry (`validate_membros`,
12614 // `validate_contratos`, `validate_entrada`, `validate_placement`,
12615 // routing through their own oracles rather than borrowing state
12616 // threaded down from `validate`). A future consumer that reaches
12617 // the per-slot gate directly on a spec whose peer slots would
12618 // fail `validate` still surfaces the per-child refusal, not the
12619 // peer refusal.
12620 //
12621 // Construct a spec whose `:max-restarts` is `0` (which would
12622 // trip [`SupervisorError::ZeroMaxRestarts`] at `validate` after
12623 // the partition-dispatch) and whose `:children` carries a
12624 // `DuplicateChildCaixa` shape: the per-slot gate called directly
12625 // must surface `DuplicateChildCaixa`, proving it does not depend
12626 // on the peer `:max-restarts` gate running first.
12627 let s = SupervisorSpec {
12628 estrategia: RestartStrategy::OneForOne,
12629 max_restarts: 0,
12630 restart_window: Some(Duration::from_secs(60)),
12631 children: vec![
12632 child("worker", "^0.1", RestartPolicy::Permanent),
12633 child("worker", "^0.2", RestartPolicy::Transient),
12634 ],
12635 };
12636 assert_eq!(
12637 s.validate_children().unwrap_err(),
12638 SupervisorError::DuplicateChildCaixa {
12639 caixa: "worker".into(),
12640 },
12641 "per-slot gate must resolve per-child refusal directly against \
12642 `&self` — a dependency on the peer `:max-restarts` gate \
12643 running first would surface ZeroMaxRestarts here instead",
12644 );
12645 // The peer gate is still the surface `validate` reaches — pin
12646 // the ordering to establish that `validate_children` truly runs
12647 // last in `validate`'s dispatch, so a direct call bypasses the
12648 // peer gates on any spec whose per-child cascade would fail.
12649 assert_eq!(
12650 s.validate().unwrap_err(),
12651 SupervisorError::ZeroMaxRestarts,
12652 "validate() must surface the peer `:max-restarts` gate before \
12653 reaching the per-child cascade — this pins the dispatch \
12654 ordering the per-slot gate's self-containment complements",
12655 );
12656 }
12657
12658 #[test]
12659 fn child_spec_restart_accessor_is_const_fn() {
12660 // The [`ChildSpec::restart`] per-`:children` restart-decision-
12661 // policy `Copy`-return scalar accessor is declared
12662 // `#[must_use] pub const fn` — matching the sibling M2
12663 // per-`:supervisor` [`SupervisorSpec::estrategia`] (pinned by
12664 // [`supervisor_spec_estrategia_accessor_is_const_fn`] below,
12665 // both converted in this commit), the sibling M2
12666 // per-`:supervisor` [`SupervisorSpec::max_restarts`] (b698ec0)
12667 // `Copy`-`u32` accessor already `pub const fn`, and the peer M3
12668 // mesh-slot per-`:entrada` [`crate::Entrada::port`] (bafa004) /
12669 // per-`:placement` [`crate::Placement::estrategia`] (bafa004)
12670 // `Copy`-return `pub const fn` scalar accessors on the sibling
12671 // M3 surface. Pin the `const`-eval posture here so a future
12672 // accidental downgrade to non-`const` (an added runtime helper
12673 // reachable only from a non-`const` context, an
12674 // `Option<RestartPolicy>`-shape migration on the per-child
12675 // restart-decision axis once heterogeneous per-cluster
12676 // restart-policy overlays land that would silently drop the
12677 // `const` qualifier, a manual hand-rolled shadow) trips at
12678 // caixa-core build time rather than surfacing as a downstream
12679 // `const`-context regression far from the declaration.
12680 //
12681 // Same shape as the sibling M3
12682 // [`crate::aplicacao::tests::placement_estrategia_accessor_is_const_fn`]
12683 // and [`crate::aplicacao::tests::entrada_port_accessor_is_const_fn`]
12684 // (bafa004) pins on the peer M3 mesh-slot `Copy`-return scalar
12685 // accessor axis — the load-bearing witness lives in the
12686 // module-scope `const fn` wrapper `restart_via_const_fn` below:
12687 // a body that calls [`ChildSpec::restart`] under a `const fn`
12688 // signature is well-formed only when the callee is itself
12689 // `const fn`, so any future accidental downgrade of
12690 // [`ChildSpec::restart`] to non-`const` fails at caixa-core
12691 // build time (const-eval E0015 `cannot call non-const method`),
12692 // strictly stronger than a runtime `assert!(CONST)` and
12693 // side-stepping the destructor-in-const restriction that
12694 // blocks direct `const _: RestartPolicy = FIXTURE.restart()`
12695 // items on `ChildSpec`'s `String` carriers.
12696 //
12697 // The runtime body sweeps every closed-set [`RestartPolicy`]
12698 // arm and asserts the wrapped and direct dispatches agree.
12699 const fn restart_via_const_fn(c: &ChildSpec) -> RestartPolicy {
12700 c.restart()
12701 }
12702 for restart in [
12703 RestartPolicy::Permanent,
12704 RestartPolicy::Transient,
12705 RestartPolicy::Temporary,
12706 ] {
12707 let c = ChildSpec {
12708 caixa: "worker".into(),
12709 versao: "^0.1".into(),
12710 restart,
12711 };
12712 assert_eq!(
12713 restart_via_const_fn(&c),
12714 c.restart(),
12715 "const-fn-wrapped and direct dispatch on \
12716 ChildSpec::restart must agree for {restart:?}",
12717 );
12718 assert_eq!(
12719 c.restart(),
12720 restart,
12721 "ChildSpec::restart must return the storage-side \
12722 RestartPolicy verbatim for {restart:?} (a violation \
12723 means the accessor stopped being a raw field-return \
12724 copy)",
12725 );
12726 }
12727 }
12728
12729 #[test]
12730 fn supervisor_spec_estrategia_accessor_is_const_fn() {
12731 // The [`SupervisorSpec::estrategia`] per-`:supervisor`
12732 // sibling-restart-strategy `Copy`-return scalar accessor is
12733 // declared `#[must_use] pub const fn` — matching the sibling M2
12734 // per-`:children` [`ChildSpec::restart`] (pinned by
12735 // [`child_spec_restart_accessor_is_const_fn`] above, both
12736 // converted in this commit), the sibling M2 per-`:supervisor`
12737 // [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32`
12738 // accessor already `pub const fn`, and mirroring the peer M3
12739 // mesh-slot per-`:placement`
12740 // [`crate::Placement::estrategia`] (bafa004) `Copy`-return
12741 // `pub const fn` scalar accessor whose method-name discipline
12742 // the [`SupervisorSpec::estrategia`] method was authored to
12743 // match. Pin the `const`-eval posture here so a future
12744 // accidental downgrade to non-`const` (an added runtime helper
12745 // reachable only from a non-`const` context, an
12746 // `Option<RestartStrategy>`-shape migration once the substrate
12747 // grows per-cluster strategy overlays that would silently drop
12748 // the `const` qualifier, a manual hand-rolled shadow) trips at
12749 // caixa-core build time rather than surfacing as a downstream
12750 // `const`-context regression far from the declaration.
12751 //
12752 // Same shape as the sibling
12753 // [`child_spec_restart_accessor_is_const_fn`] pin above — the
12754 // load-bearing witness lives in the module-scope `const fn`
12755 // wrapper `estrategia_via_const_fn` below: a body that calls
12756 // [`SupervisorSpec::estrategia`] under a `const fn` signature
12757 // is well-formed only when the callee is itself `const fn`,
12758 // side-stepping the destructor-in-const restriction that would
12759 // otherwise block a direct
12760 // `const _: RestartStrategy = FIXTURE.estrategia()` item on
12761 // `SupervisorSpec`'s `Vec<ChildSpec>` / `Option<Duration>`
12762 // carriers.
12763 //
12764 // The runtime body sweeps every closed-set [`RestartStrategy`]
12765 // arm via [`RestartStrategy::ALL`] and asserts the wrapped and
12766 // direct dispatches agree.
12767 const fn estrategia_via_const_fn(s: &SupervisorSpec) -> RestartStrategy {
12768 s.estrategia()
12769 }
12770 for &estrategia in RestartStrategy::ALL {
12771 let s = SupervisorSpec {
12772 estrategia,
12773 max_restarts: 5,
12774 restart_window: Some(Duration::from_secs(60)),
12775 children: Vec::new(),
12776 };
12777 assert_eq!(
12778 estrategia_via_const_fn(&s),
12779 s.estrategia(),
12780 "const-fn-wrapped and direct dispatch on \
12781 SupervisorSpec::estrategia must agree for {estrategia:?}",
12782 );
12783 assert_eq!(
12784 s.estrategia(),
12785 estrategia,
12786 "SupervisorSpec::estrategia must return the storage-side \
12787 RestartStrategy verbatim for {estrategia:?} (a violation \
12788 means the accessor stopped being a raw field-return \
12789 copy)",
12790 );
12791 }
12792 }
12793
12794 // Per-variant equivalence pins for the [`supervisor_caixa_only_ctors!`]
12795 // macro definition (see the paired doc-block above the macro
12796 // definition) — every generated `<ctor>(caixa: &str) -> Self`
12797 // constructor folds the uniform `Self::<Variant> { caixa:
12798 // caixa.to_string() }` one-field struct-literal onto one substrate
12799 // primitive. The three per-variant equivalence pins below
12800 // (fail-before-pass-after by construction — a byte-mismatched macro
12801 // arm would trip its equivalence pin first) lock each generated
12802 // constructor to its struct-literal peer under `PartialEq`, so
12803 // every wire-up in [`SupervisorSpec::validate_children`] and
12804 // [`validate_no_self_supervision`] on that variant produces a
12805 // byte-equal `SupervisorError` to the pre-lift open-coded
12806 // struct-literal. The cross-axis pin that follows (non-default
12807 // caixa name) routes the sole constructor input axis through
12808 // `.to_string()`, so the fold does not silently collapse onto a
12809 // fixed name.
12810 //
12811 // Peer of the sibling `<slot>_ctor_matches_tuple_literal_wrap` /
12812 // `<slot>_violation_ctor_matches_struct_literal_wrap` /
12813 // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
12814 // `missing_entry_ctor_matches_struct_literal_wrap` /
12815 // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
12816 // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
12817 // `contrato_missing_target_ctor_matches_struct_literal_wrap` /
12818 // `<variant>_ctor_matches_struct_literal_wrap` equivalence pins
12819 // on the six sibling ctor families the recent trajectory closed
12820 // on the peer `LayoutError` / `AplicacaoError` envelopes.
12821
12822 #[test]
12823 fn empty_child_version_ctor_matches_struct_literal_wrap() {
12824 assert_eq!(
12825 SupervisorError::empty_child_version("worker"),
12826 SupervisorError::EmptyChildVersion {
12827 caixa: "worker".to_string(),
12828 },
12829 "generated empty_child_version ctor must produce byte-equal \
12830 SupervisorError to the open-coded struct-literal wrap on the \
12831 same &str fixture",
12832 );
12833 }
12834
12835 #[test]
12836 fn duplicate_child_caixa_ctor_matches_struct_literal_wrap() {
12837 assert_eq!(
12838 SupervisorError::duplicate_child_caixa("worker"),
12839 SupervisorError::DuplicateChildCaixa {
12840 caixa: "worker".to_string(),
12841 },
12842 "generated duplicate_child_caixa ctor must produce byte-equal \
12843 SupervisorError to the open-coded struct-literal wrap on the \
12844 same &str fixture",
12845 );
12846 }
12847
12848 #[test]
12849 fn child_supervises_self_ctor_matches_struct_literal_wrap() {
12850 assert_eq!(
12851 SupervisorError::child_supervises_self("orquestra"),
12852 SupervisorError::ChildSupervisesSelf {
12853 caixa: "orquestra".to_string(),
12854 },
12855 "generated child_supervises_self ctor must produce byte-equal \
12856 SupervisorError to the open-coded struct-literal wrap on the \
12857 same &str fixture",
12858 );
12859 }
12860
12861 // Per-variant equivalence pins for the two lifted
12862 // [`SupervisorError::child_caixa_invalid`] /
12863 // [`SupervisorError::child_versao_invalid`] inherent constructors
12864 // (fail-before-pass-after by construction — a byte-mismatched ctor body
12865 // would trip its equivalence pin first). Each pins the ctor output to
12866 // its pre-lift struct-literal peer under `PartialEq`, so every wire-up
12867 // in [`SupervisorSpec::validate_children`] on the two variants
12868 // produces a byte-equal `SupervisorError` to the pre-lift open-coded
12869 // struct-literal on the same scalar fixtures. Peers of the sibling
12870 // `membro_caixa_invalid_ctor_matches_struct_literal_wrap` /
12871 // `entrada_para_invalid_ctor_matches_struct_literal_wrap` / … pins on
12872 // the peer `AplicacaoError` envelope's
12873 // [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold.
12874
12875 #[test]
12876 fn child_caixa_invalid_ctor_matches_struct_literal_wrap() {
12877 let caixa = "Worker";
12878 let reason = "sample reason text";
12879 assert_eq!(
12880 SupervisorError::child_caixa_invalid(caixa, reason),
12881 SupervisorError::ChildCaixaInvalid {
12882 caixa: caixa.to_string(),
12883 reason: reason.to_string(),
12884 },
12885 "lifted child_caixa_invalid ctor must produce byte-equal \
12886 SupervisorError to the open-coded struct-literal wrap on the \
12887 same (&str, reason) fixture",
12888 );
12889 }
12890
12891 #[test]
12892 fn child_versao_invalid_ctor_matches_struct_literal_wrap() {
12893 let caixa = "worker";
12894 let versao = "not-a-req";
12895 let reason = "sample reason text";
12896 assert_eq!(
12897 SupervisorError::child_versao_invalid(caixa, versao, reason),
12898 SupervisorError::ChildVersaoInvalid {
12899 caixa: caixa.to_string(),
12900 versao: versao.to_string(),
12901 reason: reason.to_string(),
12902 },
12903 "lifted child_versao_invalid ctor must produce byte-equal \
12904 SupervisorError to the open-coded struct-literal wrap on the \
12905 same (&str, &str, reason) fixture",
12906 );
12907 }
12908
12909 #[test]
12910 fn supervisor_child_reason_ctors_route_reason_through_into_uniformly() {
12911 // Cross-axis pin: sweep the two lifted `{ …, reason }` ctors
12912 // against a `&str`-literal vs. `format!(…)` reason input to pin
12913 // both constructors accept the `impl Into<String>` bound
12914 // uniformly, so neither wire-up site drifts under a per-arm
12915 // wrapper transformation on the caller-side `reason` axis. Peer
12916 // of the sibling
12917 // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
12918 // sweep on the peer `AplicacaoError` envelope.
12919 let via_literal = "literal reason text";
12920 let via_format = format!("{} reason text", "literal");
12921 assert_eq!(
12922 SupervisorError::child_caixa_invalid("Worker", via_literal),
12923 SupervisorError::child_caixa_invalid("Worker", via_format.clone()),
12924 );
12925 assert_eq!(
12926 SupervisorError::child_versao_invalid("worker", "not-a-req", via_literal),
12927 SupervisorError::child_versao_invalid("worker", "not-a-req", via_format),
12928 );
12929 }
12930
12931 #[test]
12932 fn supervisor_caixa_only_ctors_route_caixa_through_to_string() {
12933 // Cross-axis pin: sweep the sole constructor input axis (`caixa:
12934 // &str`) through a non-default fixture name against every
12935 // generated arm in the [`supervisor_caixa_only_ctors!`] macro,
12936 // so any wrapper-side lowercase / trim / truncate / re-order on
12937 // the `caixa.to_string()` sole-field construction surfaces
12938 // here rather than at a downstream diagnostic-shape mismatch.
12939 // Peer of the sibling `nome_only_ctor_routes_caixa_through_
12940 // nome_accessor` / `entrada_host_invalid_ctor_routes_host_
12941 // through_to_string` / `contrato_target_ctors_route_edge_
12942 // triple_through_verbatim` / `contrato_empty_pair_ctors_
12943 // route_edge_pair_through_verbatim` cross-axis routing pins on
12944 // the peer `LayoutError` / `AplicacaoError` envelopes; extended
12945 // here onto the `SupervisorError` `{ caixa: String }` envelope
12946 // so every substrate-primitive ctor family in caixa-core
12947 // guarantees the sole-field construction routes the caller's
12948 // `&str` through `.to_string()` verbatim.
12949 let name = "cache-v2";
12950 assert_eq!(
12951 SupervisorError::empty_child_version(name),
12952 SupervisorError::EmptyChildVersion {
12953 caixa: name.to_string(),
12954 },
12955 );
12956 assert_eq!(
12957 SupervisorError::duplicate_child_caixa(name),
12958 SupervisorError::DuplicateChildCaixa {
12959 caixa: name.to_string(),
12960 },
12961 );
12962 assert_eq!(
12963 SupervisorError::child_supervises_self(name),
12964 SupervisorError::ChildSupervisesSelf {
12965 caixa: name.to_string(),
12966 },
12967 );
12968 }
12969
12970 // ── supervisor_scalar_ctors! per-variant + cross-axis pins ──────────────
12971 //
12972 // Per-variant byte-equality pins guaranteeing every generated ctor arm in
12973 // the [`supervisor_scalar_ctors!`] macro produces a `SupervisorError`
12974 // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
12975 // one-line struct-literal on the same `Copy`-`RestartStrategy | u32 |
12976 // Duration` fixture, plus one cross-axis sweep that routes each per-variant
12977 // `<field>: <ty>` scalar through the sole `$field:ident: $ty:ty` axis the
12978 // macro exposes so any wrapper-side truncation / re-order / silent `.into()`
12979 // / silent constant-substitution on any one variant surfaces here rather
12980 // than at a downstream per-`:supervisor` diagnostic-shape drift. Peer of the
12981 // sibling per-variant pins on `aplicacao_policy_scalar_ctors!` (7ef425e,
12982 // the 8-variant `AplicacaoError` `{ <field>: Duration | u32 }` fold on the
12983 // per-`:politicas` per-axis cap / canonical-form arms), plus the sibling
12984 // `supervisor_caixa_only_ctors!` (db09650), `SupervisorError::
12985 // {child_caixa_invalid,child_versao_invalid}` (d2ef2ec), and the peer
12986 // `DepError` / `AplicacaoError` / `LayoutError` / `LimitsError` /
12987 // `BehaviorError` / `UpgradeError` per-envelope ctor-macro pins.
12988 #[test]
12989 fn no_children_ctor_matches_struct_literal_wrap() {
12990 let estrategia = RestartStrategy::OneForAll;
12991 assert_eq!(
12992 SupervisorError::no_children(estrategia),
12993 SupervisorError::NoChildren { estrategia },
12994 "generated no_children ctor must produce byte-equal \
12995 `SupervisorError::NoChildren` to the pre-lift struct-literal wrap \
12996 on the same `Copy`-`RestartStrategy` fixture",
12997 );
12998 }
12999
13000 #[test]
13001 fn max_restarts_exceeds_cap_ctor_matches_struct_literal_wrap() {
13002 let max_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 1;
13003 assert_eq!(
13004 SupervisorError::max_restarts_exceeds_cap(max_restarts),
13005 SupervisorError::MaxRestartsExceedsCap { max_restarts },
13006 "generated max_restarts_exceeds_cap ctor must produce byte-equal \
13007 `SupervisorError::MaxRestartsExceedsCap` to the pre-lift \
13008 struct-literal wrap on the same `Copy`-`u32` fixture",
13009 );
13010 }
13011
13012 #[test]
13013 fn restart_window_not_canonical_ctor_matches_struct_literal_wrap() {
13014 let window = Duration::from_micros(1_500);
13015 assert_eq!(
13016 SupervisorError::restart_window_not_canonical(window),
13017 SupervisorError::RestartWindowNotCanonical { window },
13018 "generated restart_window_not_canonical ctor must produce \
13019 byte-equal `SupervisorError::RestartWindowNotCanonical` to the \
13020 pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
13021 );
13022 }
13023
13024 #[test]
13025 fn restart_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
13026 let window = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
13027 assert_eq!(
13028 SupervisorError::restart_window_exceeds_cap(window),
13029 SupervisorError::RestartWindowExceedsCap { window },
13030 "generated restart_window_exceeds_cap ctor must produce \
13031 byte-equal `SupervisorError::RestartWindowExceedsCap` to the \
13032 pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
13033 );
13034 }
13035
13036 #[test]
13037 fn supervisor_scalar_ctors_route_field_through_copy_uniformly() {
13038 // Cross-axis routing pin: sweep each generated `<field>: <ty>`
13039 // constructor input axis through a non-default `Copy` fixture against
13040 // every arm in the [`supervisor_scalar_ctors!`] macro, so any wrapper-
13041 // side silent `.into()` / silent constant-substitution / silent field
13042 // re-name away from the canonical `estrategia | max_restarts | window`
13043 // axes on any one variant, or a `RestartStrategy | u32 | Duration`
13044 // axis silently rerouted through some other `Copy` coercion, surfaces
13045 // here rather than at a downstream per-`:supervisor` diagnostic-shape
13046 // drift. Peer of the sibling
13047 // `aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly`
13048 // (7ef425e) cross-axis routing pin on the peer `AplicacaoError`
13049 // envelope's per-`:politicas` per-axis ctor family, extended here onto
13050 // the last M2 per-`:supervisor` `Copy`-scalar `SupervisorError`
13051 // variant family folded onto a substrate primitive.
13052 //
13053 // Fixtures picked out of each variant's accept-set boundary rather
13054 // than the default value so a silent constant-substitution to a per-
13055 // variant sentinel surfaces here on the structural-equality assertion.
13056 // The `RestartStrategy` fixture picks `RestForOne` (a non-default arm
13057 // that isn't the `OneForOne` [`SUPERVISOR_ESTRATEGIA_DEFAULT`] and
13058 // isn't the `SimpleOneForOne` arm the sibling
13059 // `SimpleOneForOneWithStaticChildren` unit variant intercepts). The
13060 // `max_restarts` fixture picks an above-cap magnitude the cap arm
13061 // rejects; the two `Duration` fixtures pick the sub-millisecond and
13062 // above-cap ends of the `:restart-window` canonical-form + cap
13063 // bracket respectively.
13064 let estrategia = RestartStrategy::RestForOne;
13065 let above_cap_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 137;
13066 let sub_ms = Duration::from_micros(1_500);
13067 let above_hour = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
13068 assert_eq!(
13069 SupervisorError::no_children(estrategia),
13070 SupervisorError::NoChildren { estrategia },
13071 );
13072 assert_eq!(
13073 SupervisorError::max_restarts_exceeds_cap(above_cap_restarts),
13074 SupervisorError::MaxRestartsExceedsCap {
13075 max_restarts: above_cap_restarts,
13076 },
13077 );
13078 assert_eq!(
13079 SupervisorError::restart_window_not_canonical(sub_ms),
13080 SupervisorError::RestartWindowNotCanonical { window: sub_ms },
13081 );
13082 assert_eq!(
13083 SupervisorError::restart_window_exceeds_cap(above_hour),
13084 SupervisorError::RestartWindowExceedsCap { window: above_hour },
13085 );
13086 }
13087
13088 #[test]
13089 fn supervisor_scalar_ctors_are_const_zero_runtime_work() {
13090 // Const-eval pin: the [`supervisor_scalar_ctors!`] macro spells every
13091 // generated ctor `const fn` so a caller can pin a `SupervisorError`
13092 // at compile time — the same zero-runtime-work property the pre-lift
13093 // `|<slot>| SupervisorError::<Variant> { <slot> }` closure carried on
13094 // its `Copy`-pass-through construction path (no `.to_string()` /
13095 // `.into()` allocation, no branching). If any future edit silently
13096 // drops the `const` qualifier from the macro body the per-arm `const`
13097 // bindings below fail to compile, which surfaces the regression at
13098 // the substrate-primitive definition rather than at some downstream
13099 // consumer that had come to rely on the `const`-constructibility.
13100 // Peer of the sibling
13101 // `aplicacao_policy_scalar_ctors_are_const_zero_runtime_work`
13102 // (7ef425e) const-eval pin on the peer `AplicacaoError` envelope's
13103 // per-`:politicas` per-axis ctor family.
13104 const NO_CHILDREN: SupervisorError =
13105 SupervisorError::no_children(RestartStrategy::OneForAll);
13106 const MAX_RESTARTS_CAP: SupervisorError = SupervisorError::max_restarts_exceeds_cap(1_337);
13107 const WINDOW_NC: SupervisorError =
13108 SupervisorError::restart_window_not_canonical(Duration::from_micros(1));
13109 const WINDOW_CAP: SupervisorError =
13110 SupervisorError::restart_window_exceeds_cap(Duration::from_secs(3_601));
13111 assert!(matches!(NO_CHILDREN, SupervisorError::NoChildren { .. }));
13112 assert!(matches!(
13113 MAX_RESTARTS_CAP,
13114 SupervisorError::MaxRestartsExceedsCap { .. }
13115 ));
13116 assert!(matches!(
13117 WINDOW_NC,
13118 SupervisorError::RestartWindowNotCanonical { .. }
13119 ));
13120 assert!(matches!(
13121 WINDOW_CAP,
13122 SupervisorError::RestartWindowExceedsCap { .. }
13123 ));
13124 }
13125}