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/// Trait-idiomatic *owned-input, [`std::sync::Arc<str>`] output*
1072/// forward projection on the M2 OTP-shape sibling-restart
1073/// [`RestartStrategy`] closed-set fieldless typed enum — opens the
1074/// substrate-wide [`std::sync::Arc<str>`] forward-projection campaign
1075/// tier on the first M2 OTP-shape closed-set fieldless typed enum peer
1076/// on the caixa surface (`:supervisor :estrategia`), immediately after
1077/// the paired [`Box<str>`] axis (69ef45c / 59ae5dc) closed the
1078/// `{Self, &Self} × {&'static str, String, Cow<'static, str>, Box<str>}`
1079/// 2×4 corner on this enum. Routes byte-for-byte through the
1080/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
1081/// accessor (via [`std::sync::Arc::<str>::from`] on the returned
1082/// `&'static str`), so every consumer that binds a
1083/// [`RestartStrategy`] through the standard-library `.into()` /
1084/// [`From<Self> for std::sync::Arc<str>`] (equivalently
1085/// [`Into<std::sync::Arc<str>>`]) axis — a future admission-webhook
1086/// running under `axum` + `tokio` whose per-arm structured-log field
1087/// crosses an `.await` boundary and demands the [`Sync`] +
1088/// [`Send`]-safe shared-ownership envelope [`std::sync::Arc<str>`]
1089/// provides (the sibling [`Box<str>`] axis's owned-move return-shape
1090/// forces every downstream `.clone()` through a heap allocation, while
1091/// [`std::sync::Arc<str>`]'s reference-counted shared-ownership
1092/// resolves the same `.clone()` through a refcount bump), a future
1093/// wasm-operator's per-supervisor reconciliation scheduler that
1094/// dispatches the same per-strategy diagnostic key onto multiple
1095/// concurrent reconcile-loop tasks holding shared-ownership through
1096/// [`std::sync::Arc<str>`], a future
1097/// `tracing::field::valuable::Value::Str(strategy.into())` structured-
1098/// log recorder whose typing folds a shared-ownership envelope onto
1099/// the span-context axis, a generic
1100/// `<T: Into<std::sync::Arc<str>>>`-bound diagnostic column on a
1101/// shared-ownership per-strategy cache — reaches the same four-arm
1102/// lifted [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
1103/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
1104/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
1105/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
1106/// the sibling
1107/// `{Self, &Self} × {&'static str, String, Cow<'static, str>, Box<str>}`
1108/// forward-projection corner already returns.
1109///
1110/// First-mover on the substrate-wide trait-idiomatic
1111/// [`std::sync::Arc<str>`] forward-projection family — Rust's
1112/// standard library carries `impl From<&str> for std::sync::Arc<str>`
1113/// and `impl From<String> for std::sync::Arc<str>` but no blanket
1114/// `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor an
1115/// `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`), so every
1116/// closed-set fieldless typed enum on the substrate that carries the
1117/// paired [`AsRef<str>`] / [`std::fmt::Display`] /
1118/// [`From<Self> for &'static str`] / [`From<&Self> for &'static str`] /
1119/// [`From<Self> for String`] / [`From<&Self> for String`] /
1120/// [`From<Self> for Cow<'static, str>`] /
1121/// [`From<&Self> for Cow<'static, str>`] /
1122/// [`From<Self> for Box<str>`] / [`From<&Self> for Box<str>`] decet
1123/// but not the [`std::sync::Arc<str>`] axis forces every
1124/// `std::sync::Arc<str>`-parameterized call site through a
1125/// `std::sync::Arc::<str>::from(strategy.as_str())` open-code (or a
1126/// `std::sync::Arc::<str>::from(String::from(strategy))` two-step
1127/// composition through the owned-`String` axis that allocates
1128/// twice — once into the intermediate `String`, once into the
1129/// [`Arc<str>`] on the `From<String>` conversion) whose type bounds
1130/// have no compile-time link back to the substrate primitive. Opening
1131/// the axis on the first M2 OTP-shape closed-set fieldless typed enum
1132/// peer on the caixa substrate surface establishes the "route through
1133/// `as_str` via [`std::sync::Arc::<str>::from`] on the returned
1134/// `&'static str`" discipline; every future closed-set fieldless
1135/// typed enum peer on the substrate ([`RestartPolicy`],
1136/// [`crate::aplicacao::PlacementStrategy`],
1137/// [`crate::aplicacao::RateLimitUnit`], [`crate::aplicacao::WitShape`],
1138/// [`crate::dep::DepList`], [`crate::dialeto::CaixaDialeto`],
1139/// [`crate::kind::CaixaKind`],
1140/// [`crate::render::PathShapeViolation`], and the outside-`caixa-core`
1141/// peers `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`,
1142/// `Semantic`, `FerriteRuntime`) is a future target of the campaign,
1143/// tracking the same 14-peer emit-set every prior projection tier
1144/// ([`&'static str`], [`String`], [`Cow<'static, str>`], [`Box<str>`])
1145/// converged onto.
1146///
1147/// Peer of the sibling [`Box<str>`] forward-projection first-mover
1148/// (69ef45c) — same "opens a new substrate-wide projection tier"
1149/// discipline, extended onto the [`std::sync::Arc<str>`] axis whose
1150/// shared-ownership + [`Sync`] + [`Send`] contract is the distinct
1151/// value the [`Box<str>`] axis's owned-move return-shape cannot
1152/// provide.
1153///
1154/// Pinned load-bearing by
1155/// [`tests::restart_strategy_from_into_arc_str_routes_through_as_str_accessor`]
1156/// (byte-parity pin against [`RestartStrategy::as_str`] across the
1157/// four-arm [`RestartStrategy::ALL`] emit-set on the owned-input
1158/// surface, plus a blanket-derived [`Into`] shape witness and cross-
1159/// axis byte-parity pins against the sibling owned-input
1160/// `{&'static str, String, Cow<'static, str>, Box<str>}` return-shape
1161/// axes).
1162impl From<RestartStrategy> for std::sync::Arc<str> {
1163 fn from(strategy: RestartStrategy) -> std::sync::Arc<str> {
1164 std::sync::Arc::<str>::from(strategy.as_str())
1165 }
1166}
1167
1168/// Trait-idiomatic *borrowed-input, [`std::sync::Arc<str>`] output*
1169/// forward projection on the M2 OTP-shape sibling-restart
1170/// [`RestartStrategy`] closed-set fieldless typed enum — closes the
1171/// `{Self, &Self}` input-shape corner of the [`std::sync::Arc<str>`]
1172/// forward-projection axis on the first M2 OTP-shape closed-set
1173/// fieldless typed enum peer on the caixa surface
1174/// (`:supervisor :estrategia`), companion to the paired owned-input
1175/// [`From<RestartStrategy> for std::sync::Arc<str>`] impl one commit
1176/// prior (bca2ec8). Routes byte-for-byte through the
1177/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
1178/// accessor (via [`std::sync::Arc::<str>::from`] on the returned
1179/// `&'static str`), so every consumer that binds a
1180/// [`&RestartStrategy`] through the standard-library `.into()` /
1181/// [`From<&Self> for std::sync::Arc<str>`] (equivalently
1182/// [`Into<std::sync::Arc<str>>`]) axis — a future admission-webhook's
1183/// per-request borrowed-`&RestartStrategy` handle rendering a per-arm
1184/// `Sync` + `Send`-safe structured-log field across an `.await`
1185/// boundary through a `<T: Into<std::sync::Arc<str>>>`-bound
1186/// diagnostic-column dispatch, a future wasm-operator's per-
1187/// supervisor reconciliation pipeline whose
1188/// `.iter().map(std::sync::Arc::<str>::from)` collector reaches into
1189/// the shared-ownership per-strategy key without a spurious [`Copy`]
1190/// deref (which would only be reachable through the owned-input
1191/// [`From<RestartStrategy> for std::sync::Arc<str>`] axis by first
1192/// calling `.copied()` on the iterator), a future
1193/// `<T: Into<std::sync::Arc<str>>>`-bound `tracing`-span attributes
1194/// collector recording a borrowed-`&RestartStrategy` per-arm field
1195/// onto the parent span's shared-ownership context — reaches the
1196/// same four-arm lifted
1197/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
1198/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
1199/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
1200/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
1201/// the paired owned-input
1202/// [`From<RestartStrategy> for std::sync::Arc<str>`] impl and the
1203/// sibling `{&'static str, String, Cow<'static, str>, Box<str>}`
1204/// forward-projection corner already return.
1205///
1206/// Second peer on the substrate-wide trait-idiomatic
1207/// [`std::sync::Arc<str>`] forward-projection family opened one
1208/// commit prior (bca2ec8) on the paired owned-input
1209/// [`From<RestartStrategy> for std::sync::Arc<str>`] impl — closes
1210/// the `{Self, &Self}` input-shape corner of the
1211/// [`std::sync::Arc<str>`] axis on the first M2 OTP-shape closed-set
1212/// fieldless typed enum peer on the caixa surface, exactly as
1213/// 59ae5dc closed the paired [`Box<str>`] axis one commit after its
1214/// owning half (69ef45c) landed. Rust's standard library carries
1215/// `impl From<&str> for std::sync::Arc<str>` and
1216/// `impl From<String> for std::sync::Arc<str>` but no blanket
1217/// `impl<T: AsRef<str>> From<&T> for std::sync::Arc<str>` (nor a
1218/// `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
1219/// every closed-set fieldless typed enum peer on the substrate that
1220/// carries the paired owned-input [`std::sync::Arc<str>`] axis but
1221/// not the borrowed-input axis forces every borrowed-input
1222/// [`std::sync::Arc<str>`]-parameterized call site through a
1223/// spurious [`Copy`] deref
1224/// (`std::sync::Arc::<str>::from((*strategy).as_str())`) or a
1225/// `std::sync::Arc::<str>::from(strategy.as_str())` open-code whose
1226/// type bounds have no compile-time link back to the substrate
1227/// primitive.
1228///
1229/// Pinned load-bearing by
1230/// [`tests::restart_strategy_from_borrowed_into_arc_str_routes_through_as_str_accessor`]
1231/// (byte-parity pin against [`RestartStrategy::as_str`] across the
1232/// four-arm [`RestartStrategy::ALL`] emit-set on the borrowed-input
1233/// surface, plus a blanket-derived [`Into`] shape witness and a
1234/// cross-axis pin against the paired owned-input
1235/// [`From<RestartStrategy> for std::sync::Arc<str>`] and the sibling
1236/// borrowed-input `{&'static str, String, Cow<'static, str>,
1237/// Box<str>}` return-shape axes).
1238impl From<&RestartStrategy> for std::sync::Arc<str> {
1239 fn from(strategy: &RestartStrategy) -> std::sync::Arc<str> {
1240 std::sync::Arc::<str>::from(strategy.as_str())
1241 }
1242}
1243
1244/// Per-child restart policy.
1245///
1246/// Permanent / Temporary / Transient match Erlang/OTP semantics 1:1.
1247#[derive(
1248 Serialize,
1249 Deserialize,
1250 Debug,
1251 Clone,
1252 Copy,
1253 PartialEq,
1254 Eq,
1255 Hash,
1256 gen_platform::TypedDispatcher,
1257 gen_platform::Discriminant,
1258 gen_platform::IsVariant,
1259 gen_platform::FromStrKind,
1260)]
1261pub enum RestartPolicy {
1262 /// Always restart the child, regardless of how it died. Used for
1263 /// long-running services that must always be up.
1264 Permanent,
1265 /// Never restart. Used for one-shot work whose completion is
1266 /// itself the success signal (`oneShot` triggers map here).
1267 Temporary,
1268 /// Restart only when the child died *abnormally* (non-zero exit
1269 /// or unhandled exception). A clean exit completes the child.
1270 Transient,
1271}
1272
1273impl Default for RestartPolicy {
1274 fn default() -> Self {
1275 // Route the [`Default for RestartPolicy`] impl's return arm through
1276 // the substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed
1277 // `pub const` rather than a raw `Self::Permanent` arm — one source
1278 // of truth for the Erlang/OTP-canonical `permanent` worker-child
1279 // default across the two production consumers that currently
1280 // dispatch on it (this impl at the [`RestartPolicy::default`] call
1281 // and the serde-side `#[serde(default)]` on
1282 // [`ChildSpec::restart`] that resolves an author-omitted
1283 // `:children :restart` slot through `RestartPolicy::default()`).
1284 // Peer of the sibling per-`:supervisor` axis
1285 // [`Default for RestartStrategy`] → [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
1286 // route (95ffacc) — the two impls now share one substrate-primitive
1287 // lift discipline, so any future coherent rebrand of the OTP-shape
1288 // supervisor+child default set migrates through typed constants in
1289 // lockstep instead of splitting a lifted supervisor half against
1290 // an open-coded child half. Pinned by
1291 // `restart_policy_default_routes_through_lifted_default` +
1292 // `child_spec_serde_default_restart_routes_through_lifted_default`
1293 // in the tests module.
1294 SUPERVISOR_CHILD_RESTART_DEFAULT
1295 }
1296}
1297
1298impl RestartPolicy {
1299 /// Exhaustive iteration surface for every consumer that walks the
1300 /// closed three-arm [`RestartPolicy`] discriminator set (the future
1301 /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1302 /// per-child admission-webhook rejection body naming the accepted-
1303 /// `:restart` list, a future `feira supervisor --restart …` CLI
1304 /// arg-parse's "did you mean" hint via a [`Self::from_wire`]-scan
1305 /// over the slice, the future `feira app graph` per-child restart
1306 /// column, any future round-trip fuzz harness that sweeps every
1307 /// arm). A future arm addition (an OTP-`intrinsic` fourth arm the
1308 /// theory
1309 /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1310 /// might reach for once the three canonical OTP restart policies
1311 /// stop covering the substrate's discovered load-shape) extends
1312 /// this slice as one edit and every consumer picks up the new entry
1313 /// by construction; the compiler-checked exhaustiveness on the
1314 /// sibling method `match` arms ([`Self::as_str`] / [`Self::from_wire`])
1315 /// is the build-time guarantee that no arm forgets to grow.
1316 ///
1317 /// Peer of the sibling closed-set typed enums'
1318 /// [`RestartStrategy::ALL`] (4eec29c) /
1319 /// [`crate::CaixaKind::ALL`] (6b1f4fb) /
1320 /// [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
1321 /// [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
1322 /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
1323 /// surfaces — the sixth (and the third and final M2 OTP-shape)
1324 /// closed-set typed enum on the caixa surface to converge onto the
1325 /// same one-canonical-arm-list-per-enum discipline. Sibling axis to
1326 /// the peer [`RestartStrategy::ALL`] on the per-supervisor
1327 /// sibling-restart-strategy axis; this closes the per-child
1328 /// restart-decision-policy axis on the same M2 `:supervisor` slot.
1329 pub const ALL: &'static [Self] = &[Self::Permanent, Self::Temporary, Self::Transient];
1330
1331 /// Canonical PascalCase discriminator scalar this variant serializes
1332 /// as under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`]. The three
1333 /// arms return the paired
1334 /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1335 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1336 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] lifted
1337 /// constants so every substrate consumer that dispatches on the
1338 /// per-child restart-decision policy (the future wasm-operator's
1339 /// per-child post-exit restart-decision branch, the future M4
1340 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1341 /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
1342 /// reconciliation scheduler's per-child-policy fan-out) reads the
1343 /// same byte-string the `Serialize` derive emits — the pin test in
1344 /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
1345 /// asserts the two paths agree, peer of the M2
1346 /// [`RestartStrategy::as_str`] (09ffb2d) on the sibling per-supervisor
1347 /// sibling-restart-strategy axis and the M3
1348 /// [`crate::aplicacao::PlacementStrategy::as_str`] (cc8f749) on the
1349 /// per-Aplicacao distribution-strategy axis — the third of three
1350 /// OTP-shaped closed-enum discriminator axes on the caixa typed
1351 /// surface to converge onto the same three-path-convergence
1352 /// (`Serialize` derive → `as_str` helper → lifted constant)
1353 /// drift-detection posture.
1354 #[must_use]
1355 pub const fn as_str(self) -> &'static str {
1356 match self {
1357 Self::Permanent => crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
1358 Self::Temporary => crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
1359 Self::Transient => crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
1360 }
1361 }
1362
1363 /// Substrate-canonical reverse projection on the `:children :restart`
1364 /// closed-set axis — parses the `PascalCase` discriminator scalar
1365 /// back to the typed variant, or `None` when `s` is outside the
1366 /// closed-set arm-string set [`Self::as_str`] emits. Dispatches on
1367 /// the same lifted
1368 /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1369 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1370 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] constants
1371 /// the [`Self::as_str`] emitter walks, so the parse and emit halves
1372 /// of the round-trip migrate through one caixa-core edit on any
1373 /// future arm addition.
1374 ///
1375 /// Prior to this lift the substrate carried only the forward
1376 /// `Self → &str` projection on the OTP per-child restart-policy
1377 /// axis (the [`Self::as_str`] emitter, the [`std::fmt::Display`]
1378 /// impl routed through it, the `Serialize` derive that emits the
1379 /// same byte-string under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`])
1380 /// plus the kebab-case dispatcher-catalog identity via
1381 /// [`Self::discriminant`] — every non-serde consumer that wanted to
1382 /// parse a wire-form `PascalCase` policy scalar had to re-inline a
1383 /// three-arm `match s { "Permanent" => …, "Temporary" => …,
1384 /// "Transient" => …, _ => … }` cascade that expressed no
1385 /// compile-time link back to the typed variant's canonical lifted
1386 /// constant. A future variant rename or per-arm serde-attribute
1387 /// drift would silently split the wire byte-string one non-serde
1388 /// consumer parsed from the one the emitter wrote, with the failure
1389 /// surfacing at the operator's reconcile posture (a `:temporary`
1390 /// `oneShot` child being restarted on clean exit, treating the
1391 /// successful-completion signal as failure and re-running the
1392 /// completion-terminal one-shot indefinitely; a `:transient` child
1393 /// that clean-exited being restarted, masking the clean-completion
1394 /// contract) far from the rebrand commit and with no field naming
1395 /// the drift.
1396 ///
1397 /// Distinct axis from the [`std::str::FromStr`] impl the
1398 /// [`gen_platform::FromStrKind`] derive already installs on this
1399 /// enum by design, not by drift: `FromStr` parses the *kebab-case*
1400 /// dispatcher-catalog identity (`"permanent"` / `"temporary"` /
1401 /// `"transient"` — the inverse of [`Self::discriminant`]), while
1402 /// this method inverts the `PascalCase` wire byte-string
1403 /// [`Self::as_str`] emits. The two-axis split lets the dispatcher-
1404 /// catalog identity live in kebab-case (where every peer catalog
1405 /// identifier already lives) without forcing a wire-format rename
1406 /// on the tatara-lisp author surface (`:restart Permanent`,
1407 /// `PascalCase`) — the same two-axis distinction the sibling
1408 /// [`RestartStrategy::from_wire`] (4eec29c) /
1409 /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
1410 /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
1411 /// carry on their peer closed-set typed-enum wire round-trips.
1412 ///
1413 /// Same closed-set-reverse-projection discipline the sibling
1414 /// [`RestartStrategy::from_wire`] (4eec29c) /
1415 /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
1416 /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
1417 /// [`crate::aplicacao::RateLimitUnit::from_suffix`] typed enums
1418 /// carry on the peer wire-side `str → Self` axes — extended onto
1419 /// the M2 OTP-shape per-child restart-policy closed-set axis, the
1420 /// sixth substrate-side closed-set typed enum (and the third and
1421 /// final OTP-shape closed-enum discriminator axis) to converge on
1422 /// the two-way `str ↔ Self` round-trip. Method-named `from_wire`
1423 /// (not `from_str`) to match the peer [`RestartStrategy::from_wire`]
1424 /// shape verbatim and side-step the [`std::str::FromStr`] impl the
1425 /// derive already installs on the sibling kebab-case axis. Returns
1426 /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
1427 /// shapes: the caller picks the diagnostic form appropriate for
1428 /// its use site.
1429 #[must_use]
1430 pub fn from_wire(s: &str) -> Option<Self> {
1431 match s {
1432 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT => Some(Self::Permanent),
1433 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY => Some(Self::Temporary),
1434 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT => Some(Self::Transient),
1435 _ => None,
1436 }
1437 }
1438}
1439
1440/// [`std::fmt::Display`] routed through [`RestartPolicy::as_str`], so the
1441/// pretty-printed byte-string every consumer that formats the policy as
1442/// user-facing text lands on (the future wasm-operator's per-child
1443/// post-exit restart-decision diagnostic line, the future `feira app
1444/// graph` per-child restart column, the future M4
1445/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1446/// admission-webhook rejection body) reaches for the same lifted
1447/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1448/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1449/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1450/// wire-format `Serialize` derive already emits under
1451/// [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
1452/// [`RestartPolicy::as_str`] helper already returns.
1453///
1454/// Pre-convergence the two paths structurally disagreed — the
1455/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
1456/// route (now retired here) sent [`std::fmt::Display`] through the
1457/// gen-platform discriminant catalog string, which arrives kebab-case as
1458/// `"permanent"` / `"temporary"` / `"transient"` on this three-arm enum
1459/// (whose variant names each collapse to their own lowercase form under
1460/// the kebab-case transform), while the wire format ran as `PascalCase`
1461/// `"Permanent"` / `"Temporary"` / `"Transient"` through the un-`rename`d
1462/// serde derive. Every consumer that formatted the policy for a
1463/// diagnostic line, a graph column, or a rejection body under
1464/// `format!("{v}")` therefore landed under a different byte-string than
1465/// the wire format the operator's per-child-policy dispatch keyed off —
1466/// a silent split whose apply-time symptom (a `format!("{v}")`-carrying
1467/// diagnostic quoting `"permanent"` while the wire scalar the operator
1468/// probed was `"Permanent"`) surfaced as a confused correlate at
1469/// operator-log time far from the two-declaration site.
1470///
1471/// Routing `Display` through [`RestartPolicy::as_str`] closes the third
1472/// path: every `format!("{v}")` call reaches the same lifted
1473/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the wire format
1474/// and the [`RestartPolicy::as_str`] helper route through — `Debug` (the
1475/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
1476/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
1477/// byte-string per variant. A future variant rename or
1478/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
1479/// exactly one place, structurally.
1480///
1481/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
1482/// (from `#[derive(gen_platform::Discriminant)]`) still returns
1483/// `"permanent"` / `"temporary"` / `"transient"`, and the fleet-wide
1484/// [`gen_platform::register_dispatcher!("caixa.restart-policy", …)`]
1485/// registration keys the catalog off the same kebab identity. The two
1486/// naming worlds now live on separate typed methods (`Display` /
1487/// `as_str` for the wire byte-string, `discriminant` for the catalog
1488/// identity) rather than sharing one `Display` route that structurally
1489/// disagrees with the wire format.
1490///
1491/// Pin tests
1492/// [`tests::restart_policy_display_routes_through_as_str_helper`]
1493/// and
1494/// [`tests::restart_policy_display_matches_serialized_wire_byte_string`]
1495/// assert the three paths agree byte-for-byte on every variant, so a
1496/// future variant rename or per-arm serde attribute drift is a build
1497/// error visible at caixa-core test time, not a silent per-consumer
1498/// dispatch miss at apply / reconcile time.
1499///
1500/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
1501/// (aplicacao.rs:2306) on the per-Aplicacao distribution-strategy axis
1502/// and the sibling [`RestartStrategy`] `Display` impl on the
1503/// per-supervisor sibling-restart-strategy axis — same three-path-
1504/// convergence discipline, extended to close the third and final of
1505/// three OTP-shaped closed-enum discriminator axes on the caixa typed
1506/// surface.
1507impl std::fmt::Display for RestartPolicy {
1508 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1509 f.write_str(self.as_str())
1510 }
1511}
1512
1513/// Substrate-canonical [`AsRef<str>`] projection on the M2
1514/// per-child-restart-policy [`RestartPolicy`] closed-set typed enum —
1515/// routes through the same [`RestartPolicy::as_str`] `pub const fn`
1516/// scalar accessor the paired [`std::fmt::Display`] impl and the
1517/// un-`rename`d [`serde::Serialize`] derive already key off, so any
1518/// future consumer that binds a [`RestartPolicy`] through the
1519/// standard-library `impl AsRef<str>` bound (a future
1520/// [`caixa-feira`] `feira supervisor --restart <arm>` verb that
1521/// composes the emitted `PascalCase` wire scalar into a
1522/// [`std::process::Command::arg`] shell-out of the future
1523/// wasm-operator's per-child admission gate, a per-child structured-
1524/// log recorder on the future `caixa-operator`'s hierarchical
1525/// reconciliation surface that accepts `impl AsRef<str>` at the
1526/// `tracing::field::Value` `Str`-arm, a [`std::collections::HashMap`]
1527/// lookup keyed on the restart-policy wire byte through
1528/// `map.get::<str>(policy.as_ref())` on a future per-policy
1529/// dispatch table) reaches the paired
1530/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1531/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1532/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
1533/// lifted-const through one substrate-primitive dispatch rather
1534/// than an open-coded `.as_str()` projection at every wire-up.
1535///
1536/// Peer of the sibling [`std::fmt::Display`] impl on the same
1537/// primitive — both delegate to the shared [`RestartPolicy::as_str`]
1538/// `pub const fn` accessor, so [`format!("{v}")`], `v.as_str()`, and
1539/// `<RestartPolicy as AsRef<str>>::as_ref(&v)` resolve to the same
1540/// byte-string per instance by construction. A future variant rename
1541/// or `#[serde(rename_all = "kebab-case")]` attribute-drift on the
1542/// enum reaches every one of the three paths (plus the wire-format
1543/// `Serialize` derive that already routes through the same lifted
1544/// const) through exactly one caixa-core edit.
1545///
1546/// Same "route the trait impl through the substrate-primitive
1547/// accessor" discipline the sibling [`crate::CaixaVersion`]
1548/// [`AsRef<str>`] impl (16d5c7e) and the paired M2
1549/// [`RestartStrategy`] [`AsRef<str>`] impl (63eb1a4) carry — extends
1550/// the axis onto the paired per-child-restart-decision-policy
1551/// sibling on the same M2 `:supervisor` slot (the second M2
1552/// OTP-shape closed-set typed enum to converge onto the standard-
1553/// library [`AsRef<str>`] projection). Rust-side newtype/typed-enum
1554/// convention pairs [`AsRef<str>`] and [`fmt::Display`] on the same
1555/// primitive so a caller who has one has both; before this lift,
1556/// [`RestartPolicy`] carried [`fmt::Display`] but not the paired
1557/// [`AsRef<str>`] impl the convention names.
1558///
1559/// Pinned load-bearing by
1560/// [`tests::restart_policy_as_ref_str_routes_through_as_str_accessor`]
1561/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1562/// three-arm closed set) and
1563/// [`tests::restart_policy_as_ref_str_routes_through_display_via_shared_accessor`]
1564/// (three-path convergence: `AsRef<str>` + `Display` + `as_str` all
1565/// resolve to the same lifted `SUPERVISOR_CHILD_RESTART_*` const per
1566/// arm) — any future silent detour that routes the impl through a
1567/// divergent projection (a per-arm inline `match self { … }`
1568/// re-inlining that opens a compile-time link to the un-lifted
1569/// arm-literal, a swap onto the kebab-case
1570/// [`gen_platform::Discriminant`] catalog identity that would
1571/// collide the wire axis with the dispatcher-catalog axis) trips at
1572/// caixa-core test time under `assert_eq!` rather than at a
1573/// downstream `impl AsRef<str>`-bound consumer's silent split.
1574impl AsRef<str> for RestartPolicy {
1575 fn as_ref(&self) -> &str {
1576 self.as_str()
1577 }
1578}
1579
1580/// Trait-idiomatic reverse projection on the M2-OTP-shape per-child
1581/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
1582/// byte-for-byte through the paired substrate-primitive
1583/// [`RestartPolicy::from_wire`] `Option<Self>` accessor so every future
1584/// consumer that binds a `PascalCase` `:children :restart` wire
1585/// byte-string through the standard-library `.try_into()` / [`TryFrom`]
1586/// axis (a future [`caixa-feira`] `feira supervisor --restart
1587/// <Permanent|Temporary|Transient>` CLI arg-parse that composes into
1588/// `let restart: RestartPolicy = s.try_into()?`, a future
1589/// `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook that folds a
1590/// `spec.children[*].restart: String` field through
1591/// `RestartPolicy::try_from(&s)?`, a generic
1592/// `<T: TryFrom<&str>>`-bound loader over any of the substrate's closed-
1593/// set typed enums) reaches the same three-arm accept-set the sibling
1594/// [`RestartPolicy::from_wire`] resolver parses through and the sibling
1595/// [`RestartPolicy::as_str`] emits, rather than an open-coded per-arm
1596/// `match s { "Permanent" => …, "Temporary" => …, "Transient" => …, _ =>
1597/// … }` cascade whose arm-set has no compile-time link back to the
1598/// substrate primitive.
1599///
1600/// Complements the pre-existing forward-projection triple
1601/// ([`std::fmt::Display`], [`AsRef<str>`], [`RestartPolicy::as_str`])
1602/// with the paired trait-idiomatic reverse-projection axis: Rust-side
1603/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
1604/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so a
1605/// caller who can project *out to* a `&str` can also project *in from*
1606/// one. The [`TryFrom<&str>`] axis is deliberately chosen over
1607/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
1608/// lint the sibling method-named [`RestartPolicy::from_wire`] would
1609/// trigger under a `FromStr` impl and to avoid colliding with the
1610/// [`std::str::FromStr`] impl the [`gen_platform::FromStrKind`] derive
1611/// already installs on the paired *kebab-case dispatcher-catalog* axis
1612/// (which parses `"permanent"` / `"temporary"` / `"transient"`, the
1613/// inverse of [`Self::discriminant`]) — this impl closes the trait-
1614/// idiomatic reverse axis on the *`PascalCase` wire* half without
1615/// disturbing either the method-named `from_wire` shape every sibling
1616/// closed-set typed enum on the substrate already carries or the
1617/// pre-existing `FromStr` on the dispatcher-catalog half, keeping the
1618/// two-axis split the sibling [`Self::from_wire`] doc block motivates.
1619///
1620/// `type Error = ()` matches the sibling [`RestartPolicy::from_wire`]'s
1621/// `Option<Self>` return-shape's deliberate deferral of error typing: the
1622/// caller picks the diagnostic form appropriate for its use site (a
1623/// future `feira supervisor --restart` arg-parse composes its own
1624/// per-verb "unknown restart: <arg> — accepted: {…}" message enumerating
1625/// [`RestartPolicy::ALL`], a future M4 admission-webhook rejection body
1626/// wraps the `Err(())` outcome with the accepted-set enumeration for
1627/// operator diagnostics, a `Result::map_err` at the call site lifts the
1628/// unit-error to a per-verb error type). Same shape the peer
1629/// [`RestartStrategy`] (5b828ed) on the sibling per-supervisor axis,
1630/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136), and
1631/// [`crate::aplicacao::PlacementStrategy`] (6fd00cd) blocks motivate on
1632/// their peer closed-set typed enums' reverse projections.
1633///
1634/// The paired [`TryFrom<&str>`] impl reaches the same three-arm accept-
1635/// set the [`RestartPolicy::from_wire`] resolver dispatches through, so
1636/// any future arm addition (an OTP-`intrinsic` fourth arm the theory
1637/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1638/// might reach for once the three canonical OTP restart policies stop
1639/// covering the substrate's discovered load-shape) grows the trait-
1640/// idiomatic axis by construction — one caixa-core edit on
1641/// [`RestartPolicy::from_wire`] extends both the method-named reverse
1642/// projection every existing consumer keys off and the trait-idiomatic
1643/// reverse projection this impl exposes, without a coordinated rewrite
1644/// across every future `TryFrom<&str>`-bound consumer's arm-set.
1645///
1646/// Extends the substrate-wide closed-set-enum reverse-projection family
1647/// ([`crate::CaixaKind`] via 3c83606, [`crate::CaixaDialeto`] via
1648/// bf33136, [`crate::aplicacao::PlacementStrategy`] via 6fd00cd, and
1649/// [`RestartStrategy`] via 5b828ed) onto the third and final OTP-shape
1650/// closed-enum discriminator axis on the caixa surface — the paired
1651/// per-child `:children :restart` closed set the future wasm-operator's
1652/// hierarchical reconciliation scheduler's per-child post-exit
1653/// restart-decision branch keys off end-to-end.
1654///
1655/// Pinned load-bearing by
1656/// [`tests::restart_policy_try_from_str_routes_through_from_wire_accessor`]
1657/// (byte-parity pin against [`RestartPolicy::from_wire`] across the
1658/// three-arm accept-set),
1659/// [`tests::restart_policy_try_from_str_rejects_unknown_byte_strings`]
1660/// (rejection witness against silent accept-set widening), and
1661/// [`tests::restart_policy_try_from_str_and_from_wire_partition_the_accept_set`]
1662/// (cross-axis partition pin locking the trait and method-named
1663/// projections onto one accept-set).
1664impl TryFrom<&str> for RestartPolicy {
1665 type Error = ();
1666
1667 fn try_from(s: &str) -> Result<Self, Self::Error> {
1668 Self::from_wire(s).ok_or(())
1669 }
1670}
1671
1672/// Trait-idiomatic forward projection on the M2-OTP-shape per-child
1673/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
1674/// byte-for-byte through the paired substrate-primitive
1675/// [`RestartPolicy::as_str`] `pub const fn` accessor. Return type is
1676/// `&'static str` by construction — every [`RestartPolicy::as_str`] arm
1677/// resolves to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const
1678/// &str` with `'static` lifetime, so the trait's return-type promise is
1679/// upheld structurally without a [`String::leak`] cast or a per-arm inline
1680/// literal.
1681///
1682/// Every future consumer that specifically needs `&'static str` lifetime
1683/// bytes on the per-child restart-decision axis (a
1684/// [`tracing::field::valuable::Value::Str`] recording where the `Str`
1685/// arm's typing demands `&'static str`, a
1686/// [`std::borrow::Cow::Borrowed`]`::<'static, str>(policy.into())` composer
1687/// on the future M4 admission-webhook rejection body where the
1688/// `Cow<'static, str>` typing rules out the sibling [`AsRef<str>`]
1689/// borrowed return, a generic `<T: Into<&'static str>>`-bound serializer
1690/// or error formatter that requires the `'static` bound) reaches the same
1691/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1692/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1693/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] substrate-
1694/// primitive dispatch rather than an open-coded per-arm literal cascade
1695/// whose arm-set has no compile-time link back to the substrate primitive.
1696///
1697/// Peer of the sibling M2-OTP-shape [`RestartStrategy`] forward-projection
1698/// impl (523157d) on the per-supervisor sibling-restart-strategy axis —
1699/// the second (and second-of-two-in-M2) closed-set typed enum on the
1700/// caixa surface to converge onto the paired trait-idiomatic forward-
1701/// projection axis. With this lift the paired per-child
1702/// `:children :restart` closed-set typed enum carries the full sibling
1703/// quintet ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
1704/// [`TryFrom<&str>`] via 6fdd0d9, `From<Self> for &'static str` via this
1705/// lift) plus the round-trip witness through both the trait-idiomatic
1706/// (`From<Self> for &'static str` + `TryFrom<&str>`) and the method-named
1707/// (`as_str` + `from_wire`) axis pairs — mirrors the sibling
1708/// [`RestartStrategy`] surface arm-for-arm, so every future arm addition
1709/// (an OTP-`intrinsic` fourth arm the theory
1710/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1711/// might reach for once the three canonical OTP restart policies stop
1712/// covering the substrate's discovered load-shape) grows the trait-
1713/// idiomatic forward axis by construction: one caixa-core edit on
1714/// [`RestartPolicy::as_str`] extends every one of the five sibling
1715/// forward-projection paths ([`std::fmt::Display`], [`AsRef<str>`],
1716/// [`Self::as_str`] itself, this `From<Self> for &'static str`, and the
1717/// un-`rename`d [`serde::Serialize`] derive that also emits `as_str`'s
1718/// bytes) without a coordinated rewrite across every future
1719/// `Into<&'static str>`-bound consumer's arm-set.
1720///
1721/// Pinned load-bearing by
1722/// [`tests::restart_policy_from_into_static_str_routes_through_as_str_accessor`]
1723/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1724/// three-arm emit-set, plus a `const`-context materialization witness for
1725/// the `&'static str` lifetime promise) and
1726/// [`tests::restart_policy_from_into_static_str_and_as_str_partition_the_emit_set`]
1727/// (partition pin asserting `<&'static str as From<RestartPolicy>>::from`
1728/// and [`RestartPolicy::as_str`] agree on every arm, plus a two-way
1729/// round-trip witness through the paired trait-idiomatic reverse-
1730/// projection axis [`TryFrom<&str>`] (6fdd0d9): every
1731/// `policy.into::<&'static str>()` output re-parses back through
1732/// [`RestartPolicy::try_from`] to the original variant, closing the two-
1733/// way `Self ↔ &'static str` round-trip on the trait-idiomatic axis pair).
1734impl From<RestartPolicy> for &'static str {
1735 fn from(policy: RestartPolicy) -> &'static str {
1736 policy.as_str()
1737 }
1738}
1739
1740/// Trait-idiomatic *forward* projection on [`RestartPolicy`] from a
1741/// *borrowed* input onto the `&'static str` axis — the borrowed-input
1742/// companion to the paired owned-input [`From<RestartPolicy> for
1743/// &'static str`] impl immediately above. Routes byte-for-byte through
1744/// the same substrate-primitive [`RestartPolicy::as_str`] `pub const
1745/// fn` accessor so every consumer that binds a `&RestartPolicy`
1746/// through the standard-library `.into()` / [`From<&Self> for &'static
1747/// str`] axis (a `RestartPolicy::ALL.iter().map(<&'static
1748/// str>::from).collect::<Vec<_>>()` per-arm accept-set materializer —
1749/// whose iterator over `&'static [RestartPolicy]` yields
1750/// `&RestartPolicy`, not `RestartPolicy`, so the owned-input
1751/// [`From<RestartPolicy>`] axis alone forces every call site through
1752/// an explicit `.copied()` / dereference / [`Copy`]-bound restatement
1753/// rather than the direct trait-idiomatic projection; a future generic
1754/// `<T: Copy + for<'a> Into<&'static str>>`-bound diagnostic column
1755/// that walks the `iter().map(Into::into)` shape verbatim across every
1756/// substrate-wide closed-set typed enum; the future wasm-operator's
1757/// per-child post-exit restart-decision diagnostic line that composes
1758/// the accepted-set enumeration from an iterated
1759/// `RestartPolicy::ALL.iter().map(|p| p.into())` pipe rather than a
1760/// per-arm `match p { … }` cascade; a future
1761/// `HashMap::<&'static str, RestartPolicy>::from_iter(
1762/// RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
1763/// per-policy reverse-lookup table the sibling [`TryFrom<&str>`] impl
1764/// cannot compose without this borrowed-input axis in place) reaches
1765/// the same three-arm lifted
1766/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1767/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1768/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1769/// paired owned-input [`From<RestartPolicy> for &'static str`], the
1770/// sibling [`std::fmt::Display`], [`AsRef<str>`], and
1771/// [`RestartPolicy::as_str`] surfaces already return.
1772///
1773/// Fifth peer on the substrate-wide trait-idiomatic *borrowed-input*
1774/// forward-projection family opened on [`crate::dep::DepList`]
1775/// (64aa742) and extended onto [`crate::CaixaKind`] (5ab993a),
1776/// [`crate::CaixaDialeto`] (807b0b5), and the paired
1777/// per-supervisor sibling-restart-strategy [`RestartStrategy`]
1778/// (e941836). Rust's `From` trait does not auto-derive the
1779/// `From<&Self>` sibling from a `From<Self>` impl (the blanket
1780/// `impl<T, U> From<&T> for U where T: Copy, U: From<T>` does not
1781/// exist in `core`), so every closed-set typed enum that carries the
1782/// owned-input axis but not the borrowed-input axis forces every
1783/// borrowed-input call site through a `.copied()` /
1784/// `<&'static str>::from(*policy)` / `policy.as_str()` detour whose
1785/// type bounds have no compile-time link to the substrate primitive.
1786/// [`RestartPolicy`] is the second (and second-of-two-in-M2)
1787/// OTP-shape peer to converge onto this campaign — sibling of the
1788/// paired per-supervisor [`RestartStrategy`] borrowed-input axis, so
1789/// with this lift both closed-set typed enums on the M2 `:supervisor`
1790/// slot now carry the full sibling quintet ([`std::fmt::Display`],
1791/// [`AsRef<str>`], [`Self::as_str`], `From<Self> for &'static str`,
1792/// `From<&Self> for &'static str`) plus the paired trait-idiomatic
1793/// reverse projection [`TryFrom<&str>`], closing the borrowed-input
1794/// forward-projection axis on the M2 OTP-shape slot as a unit.
1795///
1796/// Same three-path convergence discipline as the paired owned-input
1797/// impl (this borrowed-input axis, the paired owned-input
1798/// [`From<RestartPolicy> for &'static str`], and
1799/// [`RestartPolicy::as_str`] all route through the same lifted
1800/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const), so a future
1801/// variant rename or per-arm serde-attribute drift reaches every one
1802/// of the six sibling forward-projection paths
1803/// ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
1804/// [`From<Self> for &'static str`], this [`From<&Self> for &'static
1805/// str`], and the un-`rename`d [`serde::Serialize`] derive that also
1806/// emits [`Self::as_str`]'s bytes) through exactly one caixa-core
1807/// edit.
1808///
1809/// The [`RestartPolicy::as_str`] emit and [`RestartPolicy::from_wire`]
1810/// parse share the same `PascalCase` vocabulary by construction, so
1811/// the borrowed-input forward axis and the reverse axis compose
1812/// directly — the round-trip witness pin below locks this direct
1813/// composition without the intermediate wire-vocab hop the peer
1814/// [`crate::CaixaKind`] axis pair requires.
1815///
1816/// Pinned load-bearing by
1817/// [`tests::restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
1818/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1819/// three-arm emit-set via a borrowed input, plus a `const`-context
1820/// materialization witness for the `&'static str` lifetime promise,
1821/// plus a blanket `.into()` shape) and
1822/// [`tests::restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
1823/// (cross-axis partition pin against the paired owned-input
1824/// [`From<RestartPolicy> for &'static str`] impl, plus a
1825/// `.iter().map(Into::into)` pipe witness over
1826/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
1827/// [`TryFrom<&str>`] that closes the two-way `&Self → &'static str →
1828/// Self` round-trip without the wire-vocab intermediate the peer
1829/// [`crate::CaixaKind`] axis pair requires).
1830impl From<&RestartPolicy> for &'static str {
1831 fn from(policy: &RestartPolicy) -> &'static str {
1832 policy.as_str()
1833 }
1834}
1835
1836/// Trait-idiomatic *owned-`String`* forward projection on the second
1837/// M2 OTP-shape closed-set typed enum ([`RestartPolicy`]) — the
1838/// owned-heap-string companion to the paired `&'static str`-returning
1839/// [`From<RestartPolicy> for &'static str`] / [`From<&RestartPolicy>
1840/// for &'static str`] impls immediately above. Routes byte-for-byte
1841/// through the substrate-primitive [`RestartPolicy::as_str`] `pub
1842/// const fn` accessor (via [`str::to_owned`]) so every consumer that
1843/// binds a [`RestartPolicy`] through the standard-library `.into()` /
1844/// [`From<Self> for String`] (equivalently [`Into<String>`]) axis — a
1845/// future `serde_json::Value::String(policy.into())` structured-payload
1846/// composer where the `Value::String` arm typing demands an owned
1847/// [`String`] and the sibling [`&'static str`]-returning axis forces
1848/// an explicit `.to_owned()` / `String::from` restatement at every
1849/// call site, a future `HashMap::<String, RestartPolicy>::from_iter(
1850/// RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))` per-policy
1851/// lookup where the map's key type is owned [`String`] rather than
1852/// [`&'static str`], a future `Cow::<'static, str>::Owned(policy.into())`
1853/// composer on the future M4 admission-webhook rejection body's
1854/// owned-arm, the future wasm-operator's per-child post-exit
1855/// diagnostic emit `serde_json::json!({ "restart": policy })` where the
1856/// JSON serializer's `Serialize` impl on [`String`] owns the emit-path
1857/// — reaches the same three-arm lifted
1858/// [`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 two `&'static str`-returning
1863/// forward-projection impls already return.
1864///
1865/// Extends the trait-idiomatic *owned-`String`* forward-projection
1866/// axis onto the second-of-two M2 OTP-shape closed-set typed enums on
1867/// the caixa surface — mirror of the first-mover
1868/// [`From<RestartStrategy> for String`] (7baa18a) that opened this
1869/// axis on the sibling supervisor-level strategy enum. Rust's standard
1870/// library does not carry a blanket `impl<T: AsRef<str>> From<T> for
1871/// String` (nor an `impl<T: fmt::Display> From<T> for String`), so
1872/// every closed-set typed enum that carries the paired `AsRef<str>` /
1873/// `Display` / `From<Self> for &'static str` triple but not the
1874/// owned-[`String`] axis forces every owned-string call site through a
1875/// `.to_string()` / `.as_str().to_owned()` / `String::from(policy.as_str())`
1876/// detour whose type bounds have no compile-time link to the
1877/// substrate primitive.
1878///
1879/// Deliberately routes through the human-readable
1880/// [`RestartPolicy::as_str`] axis — for this enum the wire format
1881/// (`PascalCase`, tatara-lisp author surface `:restart Permanent`) and
1882/// the diagnostic byte-string share the same vocabulary by
1883/// construction (unlike the sibling [`crate::CaixaKind`] enum whose
1884/// two axes diverge), so the owned-[`String`] projection lands
1885/// byte-identically on both the wire vocabulary the paired
1886/// [`serde::Serialize`] derive emits and the diagnostic vocabulary the
1887/// [`RestartPolicy::as_str`] helper returns, and — because the paired
1888/// [`TryFrom<&str>`] / [`RestartPolicy::from_wire`] reverse-projection
1889/// axis parses the same `PascalCase` vocabulary — the direct two-way
1890/// `Self → String → Self` round-trip composes without the wire-vocab
1891/// intermediate hop the peer [`crate::CaixaKind`] owned-[`String`]
1892/// axis pair requires.
1893///
1894/// Pinned load-bearing by
1895/// [`tests::restart_policy_from_into_owned_string_routes_through_as_str_accessor`]
1896/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1897/// three-arm emit-set, plus a blanket `.into::<String>()` shape
1898/// witness) and
1899/// [`tests::restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm`]
1900/// (cross-axis partition pin against the paired owned-input
1901/// [`From<RestartPolicy> for &'static str`] impl and the sibling
1902/// [`ToString::to_string`] surface routed through [`std::fmt::Display`],
1903/// plus a `.iter().copied().map(String::from)` pipe witness over
1904/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
1905/// [`TryFrom<&str>`] on the owned-[`String`]'s [`String::as_str`]
1906/// borrow that closes the two-way `Self → String → Self` round-trip
1907/// on the trait-idiomatic owned-[`String`] forward + reverse axis
1908/// pair).
1909impl From<RestartPolicy> for String {
1910 fn from(policy: RestartPolicy) -> String {
1911 policy.as_str().to_owned()
1912 }
1913}
1914
1915/// Trait-idiomatic *borrowed-input, owned-`String` output* forward
1916/// projection on the second-of-two M2 OTP-shape closed-set typed enum
1917/// ([`RestartPolicy`]) — the fourth (and closing) corner of the
1918/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
1919/// projection family on this enum, mirror of the first-mover
1920/// [`From<&RestartStrategy> for String`] (579385f) that opened the
1921/// 2×2-completion corner on the sibling supervisor-level strategy
1922/// enum. Routes byte-for-byte through the substrate-primitive
1923/// [`RestartPolicy::as_str`] `pub const fn` accessor (via
1924/// [`str::to_owned`]) so every consumer that holds a borrowed
1925/// [`&RestartPolicy`] and needs an owned [`String`] — a future
1926/// `serde_json::Value::String(String::from(&policy))` structured-payload
1927/// composer over a borrowed field, a future `Iterator::map` over
1928/// `&[RestartPolicy]` that projects to owned keys through
1929/// `.iter().map(String::from)`, a future `HashMap::<String,
1930/// RestartPolicy>::from_iter` that keys off a borrowed-iteration axis
1931/// where dereferencing the policy would force an unnecessary `Copy` at
1932/// every step, the future wasm-operator's per-supervisor
1933/// `child_policies.iter().map(String::from).collect()` per-child post-
1934/// exit restart-decision diagnostic emit whose iteration axis is
1935/// borrowed by construction — reaches the same three-arm lifted
1936/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1937/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1938/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1939/// paired [`std::fmt::Display`], [`AsRef<str>`],
1940/// [`RestartPolicy::as_str`], and the three other trait-idiomatic
1941/// forward-projection impls
1942/// ([`From<RestartPolicy> for &'static str`],
1943/// [`From<&RestartPolicy> for &'static str`],
1944/// [`From<RestartPolicy> for String`]) already return.
1945///
1946/// Second peer on the substrate-wide trait-idiomatic *borrowed-input,
1947/// owned-`String` output* forward-projection family opened on
1948/// [`crate::supervisor::RestartStrategy`] (579385f) — closes the
1949/// `{Self, &Self} × {&'static str, String}` 2×2 projection corner on
1950/// both M2 OTP-shape sibling peers (the paired supervisor-level
1951/// sibling-restart-strategy axis and the per-child restart-decision-
1952/// policy axis), so the whole M2 OTP-shape axis pair now carries the
1953/// full four-corner family by construction. Rust's standard library
1954/// does not carry a blanket `impl<T: AsRef<str>> From<&T> for String`
1955/// (nor an `impl<T: fmt::Display> From<&T> for String`), so every
1956/// closed-set typed enum that carries the paired `AsRef<str>` /
1957/// `Display` / `From<Self> for &'static str` / `From<&Self> for
1958/// &'static str` / `From<Self> for String` quintuple but not the
1959/// borrowed-input owned-[`String`] axis forces every borrowed-input
1960/// owned-string call site through a `policy.as_str().to_owned()` /
1961/// `String::from(*policy)` (with a spurious `Copy`) /
1962/// `policy.to_string()` (through `Display`) detour whose type bounds
1963/// have no compile-time link to the substrate primitive.
1964///
1965/// Deliberately routes through the human-readable
1966/// [`RestartPolicy::as_str`] axis — for this enum the wire format
1967/// (`PascalCase`, tatara-lisp author surface `:restart Permanent`) and
1968/// the diagnostic byte-string share the same vocabulary by
1969/// construction (unlike the sibling [`crate::CaixaKind`] enum whose
1970/// two axes diverge), so the borrowed-input owned-[`String`]
1971/// projection lands byte-identically on both the wire vocabulary the
1972/// paired [`serde::Serialize`] derive emits and the diagnostic
1973/// vocabulary the [`RestartPolicy::as_str`] helper returns, and —
1974/// because the paired [`TryFrom<&str>`] / [`RestartPolicy::from_wire`]
1975/// reverse-projection axis parses the same `PascalCase` vocabulary —
1976/// the direct two-way `&Self → String → Self` round-trip composes
1977/// without the wire-vocab intermediate hop the peer
1978/// [`crate::CaixaKind`] axis pair requires.
1979///
1980/// The remaining thirteen closed-set typed enums on the caixa
1981/// substrate surface (`CaixaKind`, `CaixaDialeto`, `DepList`,
1982/// `PlacementStrategy`, `WitShape`, `RateLimitUnit`,
1983/// `PathShapeViolation`, `InvariantKind`, `ArchVerdict`, `Severity`,
1984/// `FixSafety`, `Semantic`, `FerriteRuntime`) are the future targets
1985/// of this 2×2-completion campaign — each carries the same paired
1986/// quintuple that this borrowed-input owned-[`String`] axis extends
1987/// onto.
1988///
1989/// Pinned load-bearing by
1990/// [`tests::restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
1991/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1992/// three-arm emit-set through the borrowed-input surface) and
1993/// [`tests::restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
1994/// (cross-axis partition pin against the paired owned-input owned-
1995/// [`String`] [`From<RestartPolicy> for String`] impl, the paired
1996/// borrowed-input owned-[`&'static str`] [`From<&RestartPolicy> for
1997/// &'static str`] impl, and the sibling [`ToString::to_string`]
1998/// surface routed through [`std::fmt::Display`], plus a direct round-
1999/// trip witness through [`TryFrom<&str>`] on the owned-[`String`]'s
2000/// [`String::as_str`] borrow that closes the two-way
2001/// `&Self → String → Self` round-trip on the trait-idiomatic
2002/// borrowed-input owned-[`String`] forward + reverse axis pair).
2003impl From<&RestartPolicy> for String {
2004 fn from(policy: &RestartPolicy) -> String {
2005 policy.as_str().to_owned()
2006 }
2007}
2008
2009/// Trait-idiomatic *owned-input, [`std::borrow::Cow<'static, str>`]
2010/// output* forward projection on the M2 OTP-shape per-child-restart
2011/// [`RestartPolicy`] closed-set typed enum — extends the substrate-
2012/// wide [`std::borrow::Cow<'static, str>`] forward-projection family
2013/// opened on [`crate::CaixaKind`] (99c1735 owned-input, d45c409
2014/// borrowed-input) and first extended off it onto the sibling M2
2015/// OTP-shape sibling-restart [`RestartStrategy`] (7dd28b3 owned-input,
2016/// 9b3e4b3 borrowed-input) onto the second (and second-of-two-in-M2)
2017/// M2 OTP-shape closed-set fieldless typed enum peer on the caixa
2018/// surface (`:children :restart`). Routes byte-for-byte through the
2019/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2020/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
2021/// that binds a [`RestartPolicy`] through the trait-idiomatic
2022/// [`std::borrow::Cow<'static, str>`] axis — a future
2023/// `axum::response::IntoResponse` composer whose per-policy
2024/// diagnostic-body typing rules out the sibling [`AsRef<str>`]
2025/// borrowed return, a future M4 admission-webhook rejection body
2026/// that composes the accepted-policy enumeration through the same
2027/// `RestartPolicy::ALL.iter().map(Cow::from)` shape [`crate::CaixaKind`]
2028/// and [`RestartStrategy`] already route through, a generic `<T: for<'a>
2029/// Into<std::borrow::Cow<'static, str>>>`-bound structured-log
2030/// emitter on a per-child-policy diagnostic column — reaches the same
2031/// three-arm lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`]
2032/// / [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2033/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2034/// paired [`std::fmt::Display`], [`AsRef<str>`],
2035/// [`RestartPolicy::as_str`], and the four
2036/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
2037/// forward-projection corners already return.
2038///
2039/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
2040/// [`std::borrow::Cow::Owned`] — the substrate-primitive
2041/// [`RestartPolicy::as_str`] accessor's return carries the `&'static
2042/// str` lifetime by construction (each `match` arm resolves to a
2043/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const &str`
2044/// with static lifetime), so the zero-alloc borrowed arm is the
2045/// type-correct projection with no runtime allocation.
2046///
2047/// Rust's standard library carries no blanket `impl<T: AsRef<str>>
2048/// From<T> for Cow<'static, str>` (nor an `impl<T: fmt::Display>
2049/// From<T> for Cow<'static, str>`), so the paired sibling
2050/// [`From<RestartPolicy> for &'static str`] (9fb37d0),
2051/// [`From<RestartPolicy> for String`] (7851725), [`AsRef<str>`], and
2052/// [`std::fmt::Display`] surfaces do not implicitly extend to a
2053/// [`Cow<'static, str>`]-bound call site — every such site is forced
2054/// through a `Cow::Borrowed(policy.as_str())` /
2055/// `Cow::Owned(policy.to_string())` open-code whose type bounds have
2056/// no compile-time link back to the substrate primitive until this
2057/// lift.
2058///
2059/// Second peer to extend the substrate-wide trait-idiomatic
2060/// [`std::borrow::Cow<'static, str>`] forward-projection axis off the
2061/// top-level [`crate::CaixaKind`] enum (99c1735 owned-input, d45c409
2062/// borrowed-input) onto the wider substrate — closes the M2 OTP-shape
2063/// tier of the campaign (both sibling peers, `RestartStrategy` and
2064/// `RestartPolicy`, now carry the owned-input Cow<'static, str>
2065/// forward projection) so the remaining eleven peers
2066/// (`PlacementStrategy`, `RateLimitUnit`, `DepList`, `CaixaDialeto`,
2067/// and the outside-`caixa-core` peers `WitShape`, `PathShapeViolation`,
2068/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
2069/// `FerriteRuntime`) are the future targets. Every future arm addition
2070/// (an OTP-`intrinsic` fourth restart policy the ABSORPTION-ROADMAP
2071/// might reach for once the three canonical OTP restart policies stop
2072/// covering the substrate's discovered load-shape) grows the
2073/// Cow<'static, str> axis by construction through one caixa-core edit
2074/// on [`RestartPolicy::as_str`] — rather than a coordinated rewrite
2075/// across every future Cow<'static, str>-bound consumer site.
2076///
2077/// Pinned load-bearing by
2078/// [`tests::restart_policy_from_into_static_cow_str_routes_through_as_str_accessor`]
2079/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
2080/// against [`RestartPolicy::as_str`] across the three-arm
2081/// [`RestartPolicy::ALL`]) and
2082/// [`tests::restart_policy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
2083/// (cross-axis partition pin against the paired [`From<RestartPolicy>
2084/// for &'static str`], [`From<RestartPolicy> for String`], and
2085/// [`ToString`]-through-[`std::fmt::Display`] axes, plus a
2086/// `.iter().copied().map(Cow::from)` pipe witness over
2087/// [`RestartPolicy::ALL`] that materializes the three-arm accept-set
2088/// through the [`Cow<'static, str>`] axis alone and pins the
2089/// zero-alloc discipline on every element).
2090impl From<RestartPolicy> for std::borrow::Cow<'static, str> {
2091 fn from(policy: RestartPolicy) -> std::borrow::Cow<'static, str> {
2092 std::borrow::Cow::Borrowed(policy.as_str())
2093 }
2094}
2095
2096/// Trait-idiomatic *borrowed-input, [`std::borrow::Cow<'static, str>`]
2097/// output* forward projection on the M2 OTP-shape per-child-restart
2098/// [`RestartPolicy`] closed-set typed enum — the borrowed-input
2099/// companion to the paired owned-input
2100/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl
2101/// immediately above (0612398). Routes byte-for-byte through the same
2102/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2103/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
2104/// that holds a `&RestartPolicy` and needs a
2105/// [`std::borrow::Cow<'static, str>`] — a
2106/// `RestartPolicy::ALL.iter().map(std::borrow::Cow::from).collect::<Vec<_>>()`
2107/// per-arm accept-set materializer (whose iterator over
2108/// `&'static [RestartPolicy]` yields `&RestartPolicy`, not
2109/// `RestartPolicy`, so the paired owned-input
2110/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] axis
2111/// alone forces every call site through an explicit `.copied()` /
2112/// dereference / [`Copy`]-bound restatement rather than the direct
2113/// trait-idiomatic projection), a future generic
2114/// `<T: for<'a> Into<std::borrow::Cow<'static, str>>>`-bound emitter
2115/// on a per-child-policy diagnostic column that walks the
2116/// `iter().map(Into::into)` shape verbatim, the future M4 admission-
2117/// webhook rejection body that composes the accepted-policy
2118/// enumeration from an iterated
2119/// `RestartPolicy::ALL.iter().map(|p| p.into())` pipe rather than a
2120/// per-arm `match p { … }` cascade — reaches the same three-arm
2121/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2122/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2123/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2124/// paired [`std::fmt::Display`], [`AsRef<str>`],
2125/// [`RestartPolicy::as_str`], the four
2126/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
2127/// forward-projection corners, and the paired owned-input
2128/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl
2129/// already return.
2130///
2131/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
2132/// [`std::borrow::Cow::Owned`] — the substrate-primitive
2133/// [`RestartPolicy::as_str`] accessor's return carries the
2134/// `&'static str` lifetime by construction (each `match` arm resolves
2135/// to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const &str`
2136/// with static lifetime), so the zero-alloc borrowed arm is the
2137/// type-correct projection with no runtime allocation.
2138///
2139/// Closes the `{Self, &Self}` input-shape corner on the M2 OTP-shape
2140/// per-child-restart [`std::borrow::Cow<'static, str>`] axis opened
2141/// one commit prior (0612398) on the paired owned-input
2142/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl —
2143/// second-of-two-in-M2 closed-set fieldless typed enum peer on the
2144/// caixa surface (paired with the sibling-restart [`RestartStrategy`]
2145/// which carries both {Self, &Self} × Cow<'static, str> corners since
2146/// 7dd28b3 owned-input, 9b3e4b3 borrowed-input), exactly as d45c409
2147/// closed it on the top-level [`crate::CaixaKind`] one commit after
2148/// the owning half (99c1735) landed. This lift closes the whole M2
2149/// OTP-shape tier of the substrate-wide [`Cow<'static, str>`]
2150/// forward-projection campaign on both input-shape corners
2151/// ({Self, &Self}) of both M2 OTP-shape sibling peers
2152/// ([`RestartStrategy`] and [`RestartPolicy`]), so the remaining
2153/// eleven substrate-wide peers (`PlacementStrategy`, `RateLimitUnit`,
2154/// `DepList`, `CaixaDialeto`, `WitShape`, `PathShapeViolation`,
2155/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
2156/// `FerriteRuntime`) become the future targets of the campaign. Rust's
2157/// standard library does not carry a blanket
2158/// `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor an
2159/// `impl<T: fmt::Display> From<&T> for Cow<'static, str>`), so every
2160/// closed-set fieldless typed enum peer on the substrate that carries
2161/// the paired owned-input [`Cow<'static, str>`] axis but not the
2162/// borrowed-input axis forces every borrowed-input
2163/// [`Cow<'static, str>`]-parameterized call site through a spurious
2164/// [`Copy`] deref (`std::borrow::Cow::from(*policy)`) or a
2165/// `std::borrow::Cow::Borrowed(policy.as_str())` open-code whose type
2166/// bounds have no compile-time link to the substrate primitive.
2167///
2168/// Pinned load-bearing by
2169/// [`tests::restart_policy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor`]
2170/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
2171/// against [`RestartPolicy::as_str`] across the three-arm
2172/// [`RestartPolicy::ALL`] through the borrowed-input surface) and
2173/// [`tests::restart_policy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
2174/// (cross-axis partition pin against the paired owned-input
2175/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`], the
2176/// paired borrowed-input owned-`&'static str`
2177/// [`From<&RestartPolicy> for &'static str`], and the paired
2178/// borrowed-input owned-`String` [`From<&RestartPolicy> for String`]
2179/// impls, plus a `.iter().map(std::borrow::Cow::from)` pipe witness
2180/// over [`RestartPolicy::ALL`] — whose iterator yields
2181/// `&RestartPolicy` by construction, so the borrowed-input
2182/// [`Cow<'static, str>`] axis is what routes the pipe through the
2183/// substrate-primitive [`RestartPolicy::as_str`] accessor with the
2184/// zero-alloc [`Cow::Borrowed`] arm by construction and without a
2185/// spurious [`Copy`] deref).
2186impl From<&RestartPolicy> for std::borrow::Cow<'static, str> {
2187 fn from(policy: &RestartPolicy) -> std::borrow::Cow<'static, str> {
2188 std::borrow::Cow::Borrowed(policy.as_str())
2189 }
2190}
2191
2192/// Trait-idiomatic *owned-input, [`Box<str>`] output* forward
2193/// projection on the M2 OTP-shape per-child-restart [`RestartPolicy`]
2194/// closed-set fieldless typed enum — extends the substrate-wide
2195/// `Box<str>` forward-projection campaign tier opened one commit prior
2196/// (69ef45c) on the paired sibling-restart [`RestartStrategy`] onto
2197/// the second (and third-and-final) M2 OTP-shape closed-set fieldless
2198/// typed enum peer on the caixa surface (`:children :restart`),
2199/// immediately after the paired `Cow<'static, str>` axis (0612398 /
2200/// b4dc55c) closed the
2201/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}` 2×3
2202/// corner on this enum. Routes byte-for-byte through the
2203/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2204/// accessor via [`Box::<str>::from`] on the returned `&'static str`,
2205/// so every consumer that binds a
2206/// `let key: Box<str> = policy.into();`-shaped call site — a
2207/// per-child metric-key materializer that stashes the policy
2208/// discriminator in a `Box<str>`-typed heap-owned scalar for cheap
2209/// clone (a shared-nothing per-policy accept-set the `caixa-operator`
2210/// hierarchical reconciliation scheduler's per-child restart-decision
2211/// fan-out carries), a future admission-webhook rejection body whose
2212/// per-arm `Box<str>` field composes from an owned `RestartPolicy`
2213/// handle — reaches the same three-arm lifted
2214/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2215/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2216/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2217/// sibling
2218/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
2219/// forward-projection corner already returns. Rust's standard library
2220/// carries `impl From<&str> for Box<str>` and
2221/// `impl From<String> for Box<str>` but no blanket
2222/// `impl<T: AsRef<str>> From<T> for Box<str>` (nor any
2223/// `impl<T: Copy, U: From<T>> From<T> for U` route from the enum), so
2224/// this axis is a distinct trait-idiomatic surface that a downstream
2225/// `RestartPolicy → Box<str>` `.into()` reaches through this impl and
2226/// no other — without a `Box::from(policy.as_str())` open-code whose
2227/// type bounds have no compile-time link back to the substrate
2228/// primitive.
2229///
2230/// Second peer on the substrate-wide trait-idiomatic [`Box<str>`]
2231/// forward-projection family opened on the sibling-restart
2232/// [`RestartStrategy`] (69ef45c / 59ae5dc) — closes the whole M2
2233/// OTP-shape tier of the substrate-wide [`Box<str>`] forward-
2234/// projection campaign's owned-input corner on both M2 OTP-shape
2235/// sibling peers ([`RestartStrategy`] and [`RestartPolicy`]), the
2236/// paired borrowed-input `From<&RestartPolicy> for Box<str>` closer
2237/// and the remaining fieldless-enum peers on the M3 mesh-shape /
2238/// outside-M3 caixa-core / render-side / outside-caixa-core tiers
2239/// are the future targets of the campaign.
2240///
2241/// Pinned load-bearing by
2242/// [`tests::restart_policy_from_into_box_str_routes_through_as_str_accessor`]
2243/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2244/// three-arm [`RestartPolicy::ALL`] emit-set on the owned-input
2245/// surface, plus a blanket-derived [`Into`] shape witness).
2246impl From<RestartPolicy> for Box<str> {
2247 fn from(policy: RestartPolicy) -> Box<str> {
2248 Box::<str>::from(policy.as_str())
2249 }
2250}
2251
2252/// Trait-idiomatic *borrowed-input, [`Box<str>`] output* forward
2253/// projection on the M2 OTP-shape per-child-restart [`RestartPolicy`]
2254/// closed-set fieldless typed enum — the borrowed-input companion to
2255/// the paired owned-input [`From<RestartPolicy> for Box<str>`] impl
2256/// (0a1b313, one commit prior) that closes the `{Self, &Self}`
2257/// input-shape corner of the substrate-wide [`Box<str>`] forward-
2258/// projection axis on the second (and third-and-final) M2 OTP-shape
2259/// closed-set fieldless typed enum peer on the caixa surface
2260/// (`:children :restart`), routing byte-for-byte through the
2261/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2262/// accessor via [`Box::<str>::from`] on the returned `&'static str`.
2263/// Every consumer that holds a `&RestartPolicy` and needs a
2264/// [`Box<str>`] — a
2265/// `RestartPolicy::ALL.iter().map(Box::<str>::from).collect::<Vec<_>>()`
2266/// per-arm accept-set materializer (whose iterator over
2267/// `&'static [RestartPolicy]` yields `&RestartPolicy`, not
2268/// `RestartPolicy`, so the paired owned-input
2269/// [`From<RestartPolicy> for Box<str>`] axis alone forces every
2270/// call site through an explicit [`Copy`] deref or a
2271/// `.copied()` restatement rather than the direct trait-idiomatic
2272/// projection), a per-child metric-key materializer holding
2273/// `&RestartPolicy` through a `caixa-operator` hierarchical
2274/// reconciliation scheduler's borrow lifetime, a future admission-
2275/// webhook rejection body whose per-arm `Box<str>` field composes
2276/// from a borrowed `&RestartPolicy` handle — reaches the
2277/// substrate-primitive [`RestartPolicy::as_str`] accessor through
2278/// this impl and no other, without a
2279/// `Box::<str>::from(policy.as_str())` open-code whose type bounds
2280/// have no compile-time link back to the substrate primitive.
2281///
2282/// Rust's standard library carries `impl From<&str> for Box<str>`
2283/// and `impl From<String> for Box<str>` but no blanket
2284/// `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
2285/// `Copy`-based `impl<T: Copy, U: From<&T> for U`), so every closed-
2286/// set fieldless typed enum peer on the substrate that carries the
2287/// paired owned-input `Box<str>` axis but not the borrowed-input
2288/// axis forces every borrowed-input `Box<str>`-parameterized call
2289/// site through a spurious [`Copy`] deref
2290/// (`Box::<str>::from((*policy).as_str())`) or a
2291/// `Box::<str>::from(policy.as_str())` open-code whose type bounds
2292/// have no compile-time link back to the substrate primitive.
2293///
2294/// Fourth (and closing) peer on the substrate-wide trait-idiomatic
2295/// [`Box<str>`] forward-projection family on the M2 OTP-shape tier
2296/// — closes the whole `{Self, &Self}` input-shape corner of the
2297/// [`Box<str>`] axis on both M2 OTP-shape sibling peers
2298/// ([`RestartStrategy`] and [`RestartPolicy`]), exactly as b4dc55c
2299/// closed the paired [`Cow<'static, str>`] axis one commit after
2300/// its owning half (0612398) landed on this enum. The remaining
2301/// fieldless-enum peers on the M3 mesh-shape / outside-M3 caixa-
2302/// core / render-side / outside-caixa-core tiers are the future
2303/// targets of the [`Box<str>`] campaign.
2304///
2305/// Pinned load-bearing by
2306/// [`tests::restart_policy_from_borrowed_into_box_str_routes_through_as_str_accessor`]
2307/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2308/// three-arm [`RestartPolicy::ALL`] emit-set on the borrowed-input
2309/// surface, plus a blanket-derived [`Into`] shape witness, a
2310/// cross-axis partition pin against the paired owned-input
2311/// [`From<RestartPolicy> for Box<str>`] and the sibling borrowed-
2312/// input `{&'static str, String, Cow<'static, str>}` return-shape
2313/// axes, and a `.iter().map(Box::<str>::from)` pipe witness over
2314/// [`RestartPolicy::ALL`] — whose iterator yields `&RestartPolicy`
2315/// by construction, so the borrowed-input [`Box<str>`] axis is
2316/// what routes the pipe through the substrate-primitive
2317/// [`RestartPolicy::as_str`] accessor without a spurious [`Copy`]
2318/// deref).
2319impl From<&RestartPolicy> for Box<str> {
2320 fn from(policy: &RestartPolicy) -> Box<str> {
2321 Box::<str>::from(policy.as_str())
2322 }
2323}
2324
2325/// Trait-idiomatic *owned-input, [`std::sync::Arc<str>`] output*
2326/// forward projection on the M2 OTP-shape per-child-restart
2327/// [`RestartPolicy`] closed-set fieldless typed enum — routes byte-
2328/// for-byte through the substrate-primitive [`RestartPolicy::as_str`]
2329/// `pub const fn` accessor via [`std::sync::Arc::<str>::from`] on the
2330/// returned `&'static str`, so every consumer that binds a
2331/// [`RestartPolicy`] through the standard-library `.into()` /
2332/// [`From<Self> for std::sync::Arc<str>`] (equivalently
2333/// [`Into<std::sync::Arc<str>>`]) axis — a future admission-webhook's
2334/// per-request `Sync` + `Send`-safe structured-log field composed
2335/// across an `.await` boundary through a
2336/// `<T: Into<std::sync::Arc<str>>>`-bound diagnostic-column dispatch,
2337/// a future wasm-operator's per-child post-exit restart-decision
2338/// pipeline holding a shared-ownership per-arm cache key, a
2339/// `<T: Into<std::sync::Arc<str>>>`-bound `tracing`-span attributes
2340/// collector recording a per-child-policy field onto the parent
2341/// span's shared-ownership context — reaches the same three-arm
2342/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2343/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2344/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2345/// sibling
2346/// `{Self, &Self} × {&'static str, String, Cow<'static, str>, Box<str>}`
2347/// forward-projection corner already returns.
2348///
2349/// Second peer on the substrate-wide trait-idiomatic
2350/// [`std::sync::Arc<str>`] forward-projection family opened one
2351/// projection tier prior (bca2ec8) on the paired sibling-restart
2352/// [`RestartStrategy`] owned-input first-mover — extends the tier
2353/// onto the second (and third-and-final) M2 OTP-shape closed-set
2354/// fieldless typed enum peer on the caixa surface
2355/// (`:children :restart`), immediately after the paired [`Box<str>`]
2356/// axis (0a1b313 / cb1d068) closed the whole
2357/// `{Self, &Self} × {&'static str, String, Cow<'static, str>, Box<str>}`
2358/// 2×4 corner on this enum. Rust's standard library carries
2359/// `impl From<&str> for std::sync::Arc<str>` and
2360/// `impl From<String> for std::sync::Arc<str>` but no blanket
2361/// `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor an
2362/// `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`), so this
2363/// axis is a distinct trait-idiomatic surface that a
2364/// `let key: std::sync::Arc<str> = policy.into();`-shaped call site
2365/// reaches through this impl and no other — a paired
2366/// `std::sync::Arc::<str>::from(policy.as_str())` open-code has no
2367/// compile-time link back to the substrate primitive, and a two-step
2368/// `std::sync::Arc::<str>::from(String::from(policy))` composition
2369/// through the owned-`String` axis allocates twice (once into the
2370/// intermediate `String`, once into the [`Arc<str>`] on the
2371/// `From<String>` conversion) where the single-step trait impl
2372/// allocates once.
2373///
2374/// Peer of the sibling [`Box<str>`] second-tier extender (0a1b313) —
2375/// same "extends the substrate-wide projection tier onto the next
2376/// M2 OTP-shape peer" discipline, extended onto the
2377/// [`std::sync::Arc<str>`] axis whose shared-ownership + [`Sync`] +
2378/// [`Send`] contract is the distinct value the [`Box<str>`] axis's
2379/// owned-move return-shape cannot provide.
2380///
2381/// Pinned load-bearing by
2382/// [`tests::restart_policy_from_into_arc_str_routes_through_as_str_accessor`]
2383/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2384/// three-arm [`RestartPolicy::ALL`] emit-set on the owned-input
2385/// surface, plus a blanket-derived [`Into`] shape witness and cross-
2386/// axis byte-parity pins against the sibling owned-input
2387/// `{&'static str, String, Cow<'static, str>, Box<str>}` return-shape
2388/// axes).
2389impl From<RestartPolicy> for std::sync::Arc<str> {
2390 fn from(policy: RestartPolicy) -> std::sync::Arc<str> {
2391 std::sync::Arc::<str>::from(policy.as_str())
2392 }
2393}
2394
2395/// Trait-idiomatic *borrowed-input, [`std::sync::Arc<str>`] output*
2396/// forward projection on the M2 OTP-shape per-child-restart
2397/// [`RestartPolicy`] closed-set fieldless typed enum — closes the
2398/// `{Self, &Self}` input-shape corner of the [`std::sync::Arc<str>`]
2399/// forward-projection axis on the second (and third-and-final) M2
2400/// OTP-shape closed-set fieldless typed enum peer on the caixa
2401/// surface (`:children :restart`), companion to the paired
2402/// owned-input [`From<RestartPolicy> for std::sync::Arc<str>`] impl
2403/// one commit prior (b05724e). Routes byte-for-byte through the
2404/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2405/// accessor (via [`std::sync::Arc::<str>::from`] on the returned
2406/// `&'static str`), so every consumer that binds a
2407/// [`&RestartPolicy`] through the standard-library `.into()` /
2408/// [`From<&Self> for std::sync::Arc<str>`] (equivalently
2409/// [`Into<std::sync::Arc<str>>`]) axis — a future admission-webhook's
2410/// per-request borrowed-`&RestartPolicy` handle rendering a per-arm
2411/// `Sync` + `Send`-safe structured-log field across an `.await`
2412/// boundary through a `<T: Into<std::sync::Arc<str>>>`-bound
2413/// diagnostic-column dispatch, a future wasm-operator's per-child
2414/// post-exit restart-decision pipeline whose
2415/// `.iter().map(std::sync::Arc::<str>::from)` collector reaches
2416/// into the shared-ownership per-arm key without a spurious [`Copy`]
2417/// deref (which would only be reachable through the owned-input
2418/// [`From<RestartPolicy> for std::sync::Arc<str>`] axis by first
2419/// calling `.copied()` on the iterator), a future
2420/// `<T: Into<std::sync::Arc<str>>>`-bound `tracing`-span attributes
2421/// collector recording a borrowed-`&RestartPolicy` per-arm field
2422/// onto the parent span's shared-ownership context — reaches the
2423/// same three-arm lifted
2424/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2425/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2426/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2427/// paired owned-input [`From<RestartPolicy> for std::sync::Arc<str>`]
2428/// impl and the sibling `{&'static str, String, Cow<'static, str>,
2429/// Box<str>}` forward-projection corner already return.
2430///
2431/// Closes the substrate-wide trait-idiomatic
2432/// [`std::sync::Arc<str>`] forward-projection family opened one
2433/// commit prior (b05724e) on the paired owned-input
2434/// [`From<RestartPolicy> for std::sync::Arc<str>`] impl — closes
2435/// the `{Self, &Self}` input-shape corner of the
2436/// [`std::sync::Arc<str>`] axis on the second (and third-and-final)
2437/// M2 OTP-shape closed-set fieldless typed enum peer on the caixa
2438/// surface, exactly as b3e72d7 closed the paired
2439/// [`std::sync::Arc<str>`] corner on the sibling-restart
2440/// [`RestartStrategy`] first-mover one commit after its owning half
2441/// (bca2ec8) landed, and as cb1d068 closed the paired [`Box<str>`]
2442/// corner on this enum one commit after its owning half (0a1b313)
2443/// landed. Rust's standard library carries `impl From<&str> for
2444/// std::sync::Arc<str>` and `impl From<String> for
2445/// std::sync::Arc<str>` but no blanket `impl<T: AsRef<str>> From<&T>
2446/// for std::sync::Arc<str>` (nor a `Copy`-based `impl<T: Copy,
2447/// U: From<T>> From<&T> for U`), so every closed-set fieldless typed
2448/// enum peer on the substrate that carries the paired owned-input
2449/// [`std::sync::Arc<str>`] axis but not the borrowed-input axis
2450/// forces every borrowed-input [`std::sync::Arc<str>`]-parameterized
2451/// call site through a spurious [`Copy`] deref
2452/// (`std::sync::Arc::<str>::from((*policy).as_str())`) or a
2453/// `std::sync::Arc::<str>::from(policy.as_str())` open-code whose
2454/// type bounds have no compile-time link back to the substrate
2455/// primitive.
2456///
2457/// Pinned load-bearing by
2458/// [`tests::restart_policy_from_borrowed_into_arc_str_routes_through_as_str_accessor`]
2459/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2460/// three-arm [`RestartPolicy::ALL`] emit-set on the borrowed-input
2461/// surface, plus a blanket-derived [`Into`] shape witness, a
2462/// cross-axis pin against the paired owned-input
2463/// [`From<RestartPolicy> for std::sync::Arc<str>`] and the sibling
2464/// borrowed-input `{&'static str, String, Cow<'static, str>,
2465/// Box<str>}` return-shape axes, and a
2466/// `.iter().map(std::sync::Arc::<str>::from)` pipe witness over
2467/// [`RestartPolicy::ALL`]).
2468impl From<&RestartPolicy> for std::sync::Arc<str> {
2469 fn from(policy: &RestartPolicy) -> std::sync::Arc<str> {
2470 std::sync::Arc::<str>::from(policy.as_str())
2471 }
2472}
2473
2474// Fleet-wide dispatcher-catalog registrations for caixa's OTP
2475// supervisor surface — two more typed shadows over Erlang/OTP
2476// primitives the substrate now mechanically tracks (see
2477// theory/UNIFIED-COMPUTING-MODEL.md §VI for the roadmap +
2478// theory/TYPED-ABSORPTION.md for the absorption arc).
2479gen_platform::register_dispatcher!("caixa.restart-strategy", RestartStrategy);
2480gen_platform::register_dispatcher!("caixa.restart-policy", RestartPolicy);
2481
2482/// One child entry in the supervisor's `:children` list.
2483///
2484/// Every child references another caixa by `:caixa <nome>` + version
2485/// constraint. The supervisor materializes one ComputeUnit per entry.
2486#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2487#[serde(rename_all = "camelCase")]
2488pub struct ChildSpec {
2489 /// The child caixa's `:nome`. Must resolve via the same dependency
2490 /// resolution path as `:deps` (caixa-resolver).
2491 pub caixa: String,
2492
2493 /// Semver constraint (`"^0.1"`, `"~0.1.2"`, etc.) — same shape as
2494 /// [`crate::dep::Dep::versao`].
2495 pub versao: String,
2496
2497 /// Restart policy — an author-omitted slot degrades onto the
2498 /// substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`]
2499 /// (`permanent`, the Erlang/OTP worker-child default) through the
2500 /// [`Default for RestartPolicy`] impl this `#[serde(default)]` routes
2501 /// to.
2502 #[serde(default)]
2503 pub restart: RestartPolicy,
2504}
2505
2506impl ChildSpec {
2507 /// Substrate-canonical per-`:children` child-caixa `:nome` scalar
2508 /// accessor every consumer that reads the OTP-shape supervised
2509 /// child's identity keys off — returns the author-declared
2510 /// `:children :caixa` byte-string verbatim as a `&str`, borrowed
2511 /// from the typed slot's own [`String`] storage.
2512 ///
2513 /// The `:children :caixa` slot carries the DNS-1123 label — the
2514 /// child caixa's `:nome` — that every emitted cluster artifact
2515 /// derives its `metadata.name` from verbatim: the rendered
2516 /// `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name` per child, the
2517 /// [`crate::LABEL_PROGRAM`] label value on every child's pod
2518 /// identity, and the per-child K8s Service `metadata.name` the
2519 /// future wasm-operator (M3) provisions for inter-child supervision-
2520 /// tree wiring. Every downstream consumer that fans on the child's
2521 /// caixa-name keys off this scalar (the [`SupervisorSpec::validate`]
2522 /// per-child DNS-1123 gate at
2523 /// `require_valid_dns_1123_label(child.nome(), …)`, the per-child
2524 /// duplicate-detection [`crate::render::insert_first_seen`] key, the
2525 /// [`validate_no_self_supervision`] cross-slot equality check
2526 /// against the parent's `:nome`, every `SupervisorError` variant
2527 /// carrying the offending child caixa verbatim for `feira lint`
2528 /// rendering, the future wasm-operator's hierarchical reconciliation
2529 /// scheduler's per-child ComputeUnit-name projection, the future M4
2530 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2531 /// admission webhook).
2532 ///
2533 /// Prior to this lift the `.caixa` byte-string was accessed inline
2534 /// at seven sites in `supervisor.rs` — the DNS-1123 gate's
2535 /// `&child.caixa`, the four `SupervisorError::{ChildCaixaInvalid,
2536 /// EmptyChildVersion, ChildVersaoInvalid, DuplicateChildCaixa}`
2537 /// carriers' `child.caixa.clone()`, the dedup key's
2538 /// `child.caixa.as_str()`, and the [`validate_no_self_supervision`]
2539 /// `child.caixa == parent_nome` cross-slot check — seven open-coded
2540 /// field-accesses that expressed no compile-time link back to the
2541 /// typed slot. A future extension of the `:children :caixa` axis to
2542 /// a richer author surface (a per-cluster alias table the operator
2543 /// pins through a future `:placement`-scoped slot on the supervisor
2544 /// tree, a namespace-qualified rewrite the M4 CR materializer
2545 /// applies per-CR, a per-child overlay from the future `:children
2546 /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
2547 /// acknowledges) would have had to be threaded through every
2548 /// open-coded copy in lockstep or one consumer would silently
2549 /// disagree with the peers on which caixa a given child resolves to
2550 /// — a child-set lookup that treated the name as `"cart-worker"`
2551 /// while the peer duplicate-detector treated it as
2552 /// `"tenant-a/cart-worker"` would silently split the
2553 /// `DuplicateChildCaixa` membership-lookup diagnostic from the
2554 /// self-supervision detector's parent-equality check, a two-consumer
2555 /// split at the validator far from the source `caixa.lisp` with no
2556 /// field naming the identity-drift root cause. Lifting the resolution
2557 /// rule to a typed method on the substrate primitive means every
2558 /// downstream consumer of the Supervisor's per-`:children` identity
2559 /// surface reaches for exactly one typed dispatch — the resolver's
2560 /// accept-set migrates as a unit on any future axis addition.
2561 ///
2562 /// Sibling of the peer per-`:membros` [`crate::Membro::nome`]
2563 /// (4a32abf) member-caixa `:nome` scalar accessor on the M3
2564 /// mesh-slot surface — same "one typed dispatch on the substrate
2565 /// primitive, thin projections at each consumer" discipline extended
2566 /// onto the M2 supervisor-tree per-`:children` child-identity axis.
2567 /// The two typed axes (`Membro::nome` on the M3 Aplicacao side,
2568 /// `ChildSpec::nome` on the M2 Supervisor side) now share one
2569 /// accessor discipline for the shared substrate concept "another
2570 /// caixa referenced by `:nome`". Peer of the second M2 slot scalar
2571 /// accessor [`crate::UpgradeFromEntry::prior_versao`] (75d27a8) on
2572 /// the sibling per-`:upgrade-from :from` OTP-appup axis — the M2
2573 /// slot family's typed-accessor discipline now spans both the
2574 /// upgrade axis (`:upgrade-from`) and the supervision axis
2575 /// (`:children`), matching the closed M3 mesh-slot accessor family's
2576 /// shape. Named `nome()` to match the tatara-lisp author-surface
2577 /// term the field's docstring already reaches for ("The child
2578 /// caixa's `:nome`") and the peer [`crate::Membro::nome`] /
2579 /// [`crate::Caixa::nome`] / [`crate::dep::Dep::nome`] field-name
2580 /// discipline the substrate already carries — the accessor's name
2581 /// maps directly onto the canonical caixa-identity vocabulary rather
2582 /// than shadowing the field's storage-side `caixa` label.
2583 #[must_use]
2584 pub const fn nome(&self) -> &str {
2585 self.caixa.as_str()
2586 }
2587
2588 /// Substrate-canonical per-`:children` child-caixa `:versao` semver-
2589 /// requirement scalar accessor every consumer that reads the OTP-shape
2590 /// supervised child's version pin keys off — returns the author-declared
2591 /// `:children :versao` byte-string verbatim as a `&str`, borrowed from
2592 /// the typed slot's own [`String`] storage.
2593 ///
2594 /// The `:children :versao` slot carries the Cargo-shaped semver
2595 /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that pins
2596 /// which release of the supervised child caixa the OTP-shape supervisor
2597 /// tree materializes against — the same requirement grammar the peer
2598 /// `:deps :versao` / `:membros :versao` axes carry, resolved through the
2599 /// shared [`crate::render::require_valid_versao_requirement`] cascade
2600 /// and the shared [`crate::version::parse_requirement`] parser. Every
2601 /// downstream consumer that fans on the child's version pin keys off
2602 /// this scalar (the [`SupervisorSpec::validate`] per-child requirement
2603 /// gate at `require_valid_versao_requirement(child.versao_requirement(),
2604 /// …)`, the [`SupervisorError::ChildVersaoInvalid`] variant's carrier
2605 /// for `feira lint` rendering, every future per-cluster version-lock
2606 /// overlay the caixa-operator's hierarchical reconciliation scheduler
2607 /// pins through a future `:placement`-scoped supervisor-tree slot, the
2608 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2609 /// per-child version resolver, the future wasm-operator's per-child
2610 /// lacre BLAKE3-closure lookup at `ComputeUnit` materialization time).
2611 ///
2612 /// Prior to this lift the `.versao` byte-string was accessed inline at
2613 /// two `&str`-shaped sites in `caixa-core/src/supervisor.rs` — the
2614 /// [`SupervisorSpec::validate`] requirement-gate call
2615 /// `require_valid_versao_requirement(&child.versao, …)` and the
2616 /// [`SupervisorError::ChildVersaoInvalid`] carrier at
2617 /// `versao: child.versao.clone()` — two open-coded field-accesses that
2618 /// expressed no compile-time link back to the typed slot. A future
2619 /// extension of the `:children :versao` axis to a richer author surface
2620 /// (a per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
2621 /// flow, a lacre-projected concrete-version rewrite the operator
2622 /// materializes at CR-admission time, a future `:children :versao-lock`
2623 /// per-cluster override slot the wasm-operator's hierarchical
2624 /// reconciliation scheduler authors per-CR) would have had to be
2625 /// threaded through both open-coded copies in lockstep or one consumer
2626 /// would silently disagree with the peer on which release constraint a
2627 /// given child resolves to — the requirement-gate call reading
2628 /// `"^0.1"` while the error-body carrier read `"tenant-a-pin/^0.1"`
2629 /// would silently split the `ChildVersaoInvalid` diagnostic quote from
2630 /// the actual gate rejection input, a two-consumer split at the
2631 /// validator far from the source `caixa.lisp` with no field naming the
2632 /// version-pin drift root cause. Lifting the resolution rule to a typed
2633 /// method on the substrate primitive means every downstream
2634 /// requirement-facing consumer of the Supervisor's per-`:children`
2635 /// version-pin surface reaches for exactly one typed dispatch — the
2636 /// resolver's accept-set migrates as a unit on any future axis addition.
2637 ///
2638 /// Sibling of the peer per-`:membros` [`crate::Membro::versao_requirement`]
2639 /// (a40b0e3) member-caixa `:versao` scalar accessor on the M3 mesh-slot
2640 /// surface — same "one typed dispatch on the substrate primitive, thin
2641 /// projections at each consumer" discipline extended onto the M2
2642 /// supervisor-tree per-`:children` child-version-pin axis. The two typed
2643 /// axes (`Membro::versao_requirement` on the M3 Aplicacao side,
2644 /// `ChildSpec::versao_requirement` on the M2 Supervisor side) now share
2645 /// one accessor discipline for the shared substrate concept "another
2646 /// caixa referenced by a Cargo-shaped semver requirement". Peer of the
2647 /// sibling per-`:children` [`ChildSpec::nome`] (57c61d0) child-caixa
2648 /// `:nome` scalar accessor — the pair
2649 /// `(nome(), versao_requirement())` jointly projects the
2650 /// `(caixa, versao)` field pair every OTP-shape supervisor-tree consumer
2651 /// that fans on per-child identity + version pin keys off, closing the
2652 /// last unlifted per-`:children` `String`-carry axis so every downstream
2653 /// per-`:children` reader now routes through a typed dispatch on the
2654 /// substrate primitive. Named `versao_requirement()` rather than
2655 /// `versao()` because the field's storage-side `.versao` label is
2656 /// already the author-surface term (`:versao`); the accessor's name
2657 /// carries the semantic role — the semver *requirement* string the
2658 /// shared [`crate::version::parse_requirement`] entry-point consumes —
2659 /// so a raw field access and a typed dispatch read differently at every
2660 /// consumer site. Matches the peer [`crate::Membro::versao_requirement`]
2661 /// naming discipline verbatim.
2662 #[must_use]
2663 pub const fn versao_requirement(&self) -> &str {
2664 self.versao.as_str()
2665 }
2666
2667 /// Substrate-canonical per-`:children` `:restart` OTP-shaped
2668 /// per-child post-exit restart-decision policy scalar accessor every
2669 /// consumer that dispatches on the supervised child's post-exit
2670 /// reconcile posture keys off — returns the author-declared
2671 /// `:children :restart` variant verbatim as a [`RestartPolicy`],
2672 /// `Copy`-projected from the typed slot's own [`RestartPolicy`]
2673 /// storage.
2674 ///
2675 /// The `:children :restart` slot carries the closed-set OTP-shaped
2676 /// per-child restart-decision policy discriminator
2677 /// ([`RestartPolicy::Permanent`] — always restart, the OTP `permanent`
2678 /// worker-child default; [`RestartPolicy::Transient`] — restart only
2679 /// on abnormal exit, the OTP `transient` clean-completion-aware
2680 /// default; [`RestartPolicy::Temporary`] — never restart, the OTP
2681 /// `temporary` one-shot default) that every downstream consumer of
2682 /// the Supervisor's per-child post-exit reconcile branch keys off.
2683 /// Every future downstream consumer that fans on the per-child
2684 /// restart-decision keys off this scalar (the future `feira app
2685 /// graph` per-child restart column, the future wasm-operator's
2686 /// per-child post-exit restart-decision branch, the future M4
2687 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2688 /// admission webhook, the `caixa-operator`'s hierarchical
2689 /// reconciliation scheduler's per-child post-exit reconcile branch,
2690 /// the [`RestartPolicy::as_str`] `Serialize`-derive-pinning path the
2691 /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
2692 /// pin threads through).
2693 ///
2694 /// Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
2695 /// (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
2696 /// scalar accessor and the M3 mesh-slot
2697 /// [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
2698 /// [`crate::PlacementStrategy`] distribution-strategy scalar accessor
2699 /// — same "one typed dispatch on the substrate primitive,
2700 /// `Copy`-projected closed-set enum-arm discriminator that partitions
2701 /// the downstream renderer's per-arm fan-out" discipline extended
2702 /// onto the M2 supervisor-slot per-`:children` restart-decision-policy
2703 /// `Copy`-composite-enum scalar axis. Third axis on the per-`:children`
2704 /// [`ChildSpec`] type — companion to the sibling per-`:children`
2705 /// [`ChildSpec::nome`] (57c61d0) child-caixa `:nome` scalar accessor
2706 /// and the per-`:children` [`ChildSpec::versao_requirement`]
2707 /// (2c053c8) child-caixa `:versao` semver-requirement scalar accessor
2708 /// on the sibling `String`-carry axes. The triple
2709 /// `(nome(), versao_requirement(), restart())` jointly projects the
2710 /// `(caixa, versao, restart)` field trio every OTP-shape supervisor-
2711 /// tree consumer that fans on per-child identity + version pin +
2712 /// restart-decision keys off, closing the last unlifted per-`:children`
2713 /// axis so every downstream per-`:children` reader now routes through
2714 /// a typed dispatch on the substrate primitive. Named `restart()` to
2715 /// match the storage field's name and the author-surface
2716 /// `:children :restart` slot term verbatim; the accessor's identity
2717 /// name maps onto the canonical OTP-shape per-child restart-decision-
2718 /// policy vocabulary the [`RestartPolicy`] enum's docstring already
2719 /// carries.
2720 ///
2721 /// Declared `pub const fn` to close the last non-`const`
2722 /// `Copy`-return raw-field-getter posture on the M2
2723 /// per-`:children` [`ChildSpec`] substrate-primitive surface — peer
2724 /// of the sibling M2 per-`:supervisor`
2725 /// [`SupervisorSpec::estrategia`] (converted in this commit)
2726 /// `Copy`-composite-enum accessor, the sibling M2 per-`:supervisor`
2727 /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
2728 /// already lifted, and the peer M3 mesh-slot per-`:entrada`
2729 /// [`crate::Entrada::port`] (bafa004) / per-`:placement`
2730 /// [`crate::Placement::estrategia`] (bafa004) `Copy`-return
2731 /// `pub const fn` scalar accessors on the sibling M3 surface. Every
2732 /// downstream substrate-side `const`-context consumer of the
2733 /// per-`:children` restart-decision-policy scalar (a future
2734 /// module-scope `const _:() = assert!(matches!(child.restart(),
2735 /// RestartPolicy::Permanent))` invariant pin on a typed fixture, a
2736 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
2737 /// admission-webhook `const fn` per-child restart-decision floor
2738 /// over a typed [`ChildSpec`], any future `const fn` supervisor-tree
2739 /// composer over the substrate primitive that fans on the per-child
2740 /// restart-decision policy at compile time) now reaches through the
2741 /// same typed dispatch on the substrate primitive at const-eval
2742 /// time as at runtime. A future non-`Copy`-return promotion of the
2743 /// scalar (an `Option<RestartPolicy>`-shape migration on the
2744 /// per-child restart-decision axis once heterogeneous per-cluster
2745 /// restart-policy overlays land, a per-tenant restart-policy-alias
2746 /// table the M4 CR materializer resolves per-CR) that would drop
2747 /// the `const` qualifier fails the fail-before-pass-after pin
2748 /// [`tests::child_spec_restart_accessor_is_const_fn`] at caixa-core
2749 /// build time rather than surfacing as a downstream consumer
2750 /// regression.
2751 #[must_use]
2752 pub const fn restart(&self) -> RestartPolicy {
2753 self.restart
2754 }
2755}
2756
2757/// Supervisor-typed slots that live alongside the standard Caixa
2758/// fields when `:kind Supervisor`. Held flat in [`crate::Caixa`] so
2759/// the manifest stays a single typed form; this struct exists for
2760/// validation + conversion.
2761#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2762#[serde(rename_all = "camelCase")]
2763pub struct SupervisorSpec {
2764 /// Restart strategy. Defaults to [`RestartStrategy::OneForOne`].
2765 #[serde(default)]
2766 pub estrategia: RestartStrategy,
2767
2768 /// Max restarts within [`Self::restart_window`] before the
2769 /// supervisor itself terminates (and its parent supervisor decides
2770 /// what to do). Default 5.
2771 #[serde(default = "default_max_restarts")]
2772 pub max_restarts: u32,
2773
2774 /// Sliding window for `max_restarts`. Authored as a duration
2775 /// string (`"60s"`, `"5m"`); absent = "never reset". A `Some(0s)`
2776 /// is rejected by [`Self::validate`] — Erlang/OTP's
2777 /// `MaxIntensity / Period` invariant requires a positive window
2778 /// (a zero-period supervisor either trips on the first failure or
2779 /// never trips, depending on operator interpretation, neither of
2780 /// which is the author's intent). Omit the slot to express "no
2781 /// reset"; carry a positive duration to express the sliding window.
2782 #[serde(
2783 default,
2784 skip_serializing_if = "Option::is_none",
2785 with = "duration_codec"
2786 )]
2787 pub restart_window: Option<Duration>,
2788
2789 /// Static children. Empty for `SimpleOneForOne` (children added
2790 /// dynamically); required for the other three strategies.
2791 #[serde(default)]
2792 pub children: Vec<ChildSpec>,
2793}
2794
2795const fn default_max_restarts() -> u32 {
2796 // Route the private serde-`#[serde(default = "…")]` helper through
2797 // the substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] typed
2798 // `pub const` rather than the raw `5` literal — one source of truth
2799 // for the Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
2800 // default across the two production consumers that currently
2801 // dispatch on it (this helper via `#[serde(default = "…")]` on
2802 // `SupervisorSpec::max_restarts` and the [`Default for SupervisorSpec`]
2803 // impl at line 962). Pinned by
2804 // `default_max_restarts_helper_routes_through_lifted_default` +
2805 // `supervisor_spec_default_max_restarts_routes_through_lifted_default`
2806 // in the tests module; peer of the sibling caixa-core
2807 // [`crate::manifest::Caixa::supervisor_view`] `unwrap_or(…)` fold
2808 // that now routes its author-omitted `:max-restarts` arm through
2809 // the same lifted constant.
2810 SUPERVISOR_MAX_RESTARTS_DEFAULT
2811}
2812
2813/// Substrate-canonical Erlang/OTP-shaped `MaxIntensity` restart-budget-
2814/// count default for the `:supervisor :max-restarts` axis — the
2815/// canonical `{intensity, 5, 60}` `MaxIntensity` half of Learn You Some
2816/// Erlang's worker-supervisor default, extracted as a typed `pub const`
2817/// so every substrate-side consumer that resolves "what
2818/// [`SupervisorSpec::max_restarts`] value does an author-omitted
2819/// `:max-restarts` slot degrade onto?" reaches for exactly one
2820/// substrate-primitive `u32`.
2821///
2822/// The `:max-restarts` default axis has two production consumers on the
2823/// substrate side today (both prior to this lift folded onto raw `5`
2824/// literals with no compile-time link back to a shared truth): the
2825/// serde-`#[serde(default = "default_max_restarts")]` helper on
2826/// [`SupervisorSpec::max_restarts`] that every author-omitted
2827/// `:supervisor :max-restarts` slot lands in past the derive-macro's
2828/// wire-format compose, and the [`crate::manifest::Caixa::supervisor_view`]
2829/// `.max_restarts().unwrap_or(5)` fold that every downstream consumer of
2830/// the composed [`SupervisorSpec`] altitude reaches through
2831/// (`feira app graph`, the future wasm-operator's per-supervisor
2832/// restart-intensity counter, the future M4
2833/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2834/// webhook, the caixa-operator's hierarchical reconciliation scheduler).
2835/// A pair of open-coded `5`s across two files that expressed no
2836/// compile-time link back to the shared OTP-canonical default — a
2837/// future rebrand of the default (a tightening to Elixir's
2838/// `Supervisor.max_restarts: 3`, a widening to a per-cluster overlay
2839/// the operator pins through a future
2840/// `:supervisor :max-restarts-overrides` slot the MESH-COMPOSITION
2841/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
2842/// plain `u32` count to a richer `{MaxR, MaxT}` per-child-cohort
2843/// restart-budget-partition once the INSPIRATIONS §II.2 Erlang/OTP
2844/// per-child-cohort roadmap lands) would have had to be threaded
2845/// through both open-coded copies in lockstep or the wire-format
2846/// author-omitted arm and the view-construction author-omitted arm
2847/// would silently disagree on which restart-budget an omitted
2848/// `:max-restarts` resolves to (an author writing `:supervisor
2849/// (:max-restarts ())` would round-trip through serde with the new
2850/// default while `supervisor_view` silently continued to compose the
2851/// stale `5`, or vice versa), a two-consumer split at the composition
2852/// boundary far from the source `caixa.lisp` with no field naming the
2853/// default-drift root cause. Lifting the resolution rule to a typed
2854/// `pub const` on the substrate primitive means every downstream
2855/// consumer of the per-Supervisor default-restart-budget-count surface
2856/// reaches for exactly one substrate-primitive `u32` — the resolver's
2857/// accepted value migrates as a unit on any future axis change.
2858///
2859/// The `5` value pins Learn You Some Erlang's `{intensity, 5, 60}`
2860/// worker-supervisor default (the closest canonical OTP-shape
2861/// production reference the substrate carries, matching the sibling
2862/// `60s` `Period` default the [`Default for SupervisorSpec`] impl pairs
2863/// this constant with on the paired sliding-window axis). Two orders of
2864/// magnitude below the [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` ceiling
2865/// (the upper bracket on the same axis, sibling of this lower default;
2866/// both are typed `u32` const bounds on the `:supervisor :max-restarts`
2867/// axis and now share one accessor discipline on the substrate) and
2868/// above the OTP-`supervisor` callback-module `MaxR = 1` minimum-
2869/// restart floor — the "one restart, then escalate" default is
2870/// deliberately loose enough to absorb a short burst of transient
2871/// child failures without escalating past the supervisor's parent
2872/// while remaining tight enough to trip the `MaxIntensity / Period`
2873/// ratio's escalation on a genuinely-stuck child within the sibling
2874/// `60s` sliding window.
2875///
2876/// Lifted as a typed `pub const` so the bound has exactly one source
2877/// of truth — the serde-side wire-format author-omitted arm at
2878/// [`default_max_restarts`], the [`Default for SupervisorSpec`] impl's
2879/// struct-literal default field, and the caixa-core
2880/// [`crate::manifest::Caixa::supervisor_view`] fold's author-omitted
2881/// arm all read from one place. Same shape every other typed default
2882/// in this crate carries (the sibling
2883/// [`SUPERVISOR_MAX_RESTARTS_MAX`] upper cap on the same axis, the
2884/// paired [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the
2885/// sibling `:restart-window` axis, and the peer
2886/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
2887/// per-renderer defaults on the caixa-flux / caixa-helm rendering
2888/// axes).
2889pub const SUPERVISOR_MAX_RESTARTS_DEFAULT: u32 = 5;
2890
2891/// Upper-bound ceiling on the `:supervisor :max-restarts` axis — every
2892/// validated [`SupervisorSpec::max_restarts`] past
2893/// [`SupervisorSpec::validate`] lies in `1..=SUPERVISOR_MAX_RESTARTS_MAX`.
2894///
2895/// The typed field is `u32` (the zero-floor arm
2896/// [`SupervisorError::ZeroMaxRestarts`] already brackets the bottom edge),
2897/// so a programmatic struct literal
2898/// (`SupervisorSpec { max_restarts: u32::MAX, .. }`) and the equivalent
2899/// author-surface form (`:max-restarts 4294967295` or any
2900/// `:max-restarts 100000`-shape typo landing in the slot) both round-trip
2901/// cleanly through serde — a structurally unbounded `u32` ceiling. The
2902/// runtime substrate consuming the value (Erlang/OTP's
2903/// `MaxIntensity / Period` ratio, the future wasm-operator's
2904/// per-supervisor restart-intensity counter, the M4
2905/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook)
2906/// then turned a typed `:max-restarts` policy into a no-op supervisor: the
2907/// escalation threshold is structurally so high that no realistic
2908/// restarts-per-`:restart-window` traffic shape can reach it, the
2909/// supervisor never escalates to its parent, and a bad child can loop
2910/// inside the window indefinitely with the parent supervisor structurally
2911/// never receiving the "this subtree has exceeded its restart budget"
2912/// signal the typed slot is meant to express — the canonical
2913/// "supervisor intensity declared, no escalation" footgun, exactly the
2914/// peer of the [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap
2915/// on the `:politicas :circuit-breaker :max-failures` axis (both are
2916/// "trip the next-higher protection layer after N events in a rolling
2917/// window" counters with identical degenerate-at-the-high-end shape).
2918///
2919/// The `1000` ceiling matches the sibling
2920/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] (the closest
2921/// peer — same "events-per-window trip threshold" semantics, same `u32`
2922/// type, same no-op-at-the-high-end failure mode) so the M4
2923/// `mesh.pleme.io/v1alpha1/Supervisor` / `.../Aplicacao` CR materializers
2924/// and the future wasm-operator's per-supervisor restart-intensity
2925/// counter reach for either field knowing the value is in `1..=1000`
2926/// without re-validating at the reconciler layer. The cap sits two
2927/// orders of magnitude above every documented Erlang/OTP production
2928/// playbook recommendation (Learn You Some Erlang's
2929/// `{intensity, 5, 60}` worker-supervisor default, Elixir's `Supervisor`
2930/// `max_restarts: 3` default, OTP's `supervisor` callback module
2931/// `MaxR = 1` / `MaxT = 5` "minimal-restart" default, Riak Core's
2932/// typical `MaxR ∈ 5..=100`, RabbitMQ's broker-supervisor `MaxR = 5`
2933/// default) and below the clearly-pathological "effectively no
2934/// escalation" floor (`10_000`, `100_000`, `u32::MAX`): a value the
2935/// author can plausibly want at hyperscale (a long-running supervisor
2936/// over a very-flaky pool tolerating thousands of transient restarts
2937/// before escalating), but a hard wall above which the typed policy is
2938/// structurally a no-op carried verbatim on every emitted child-restart
2939/// reconciliation contract.
2940///
2941/// Lifted as a typed `pub const` so the bound has exactly one source of
2942/// truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
2943/// materializer's admission webhook and the wasm-operator-side
2944/// per-supervisor restart-intensity reconciler read from one place. Same
2945/// shape every other typed upper bound in this crate carries
2946/// ([`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
2947/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
2948/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
2949/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2950/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2951/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2952pub const SUPERVISOR_MAX_RESTARTS_MAX: u32 = 1000;
2953
2954/// Upper-bound ceiling on the `:supervisor :restart-window` axis —
2955/// every validated `Some(`[`SupervisorSpec::restart_window`]`)` past
2956/// [`SupervisorSpec::validate`] lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
2957/// (inclusive on both ends, integer-millisecond magnitudes by the
2958/// canonical-form gate immediately preceding).
2959///
2960/// The typed field is `Option<Duration>` (the zero-floor arm
2961/// [`SupervisorError::RestartWindowZero`] already rejects
2962/// `Some(Duration::ZERO)`, and the canonical-form arm
2963/// [`SupervisorError::RestartWindowNotCanonical`] already rejects
2964/// sub-millisecond residue), so a programmatic struct literal
2965/// (`SupervisorSpec { restart_window: Some(Duration::from_secs(86_400)),
2966/// .. }` — 24h) and the equivalent author-surface form
2967/// (`(:supervisor (:restart-window "24h"))` — the shared duration codec
2968/// emits `"<n>h"` for any integer-hour magnitude) both round-trip
2969/// cleanly through serde — a structurally unbounded `Duration` ceiling.
2970/// A `:restart-window` value far above the documented Erlang/OTP
2971/// `MaxIntensity / Period` production-playbook band (Learn You Some
2972/// Erlang's `{intensity, 5, 60}` worker-supervisor `Period = 60s`
2973/// default, Elixir's `Supervisor` `max_seconds: 5` default, OTP's
2974/// `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's
2975/// `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default)
2976/// degenerates the supervisor's restart-intensity counter into a
2977/// lifetime counter: the rolling failure-counting window is structurally
2978/// so long that transient restarts are never forgotten, so the
2979/// `MaxIntensity / Period` ratio degenerates from "trip the parent
2980/// supervisor when the child has exceeded its restart budget *within
2981/// the recent window*" to "trip the parent when the child has exceeded
2982/// its restart budget *over its lifetime*" — every transient restart
2983/// counts against the budget forever, the supervisor's reset semantic
2984/// never reaches the child, and the typed `:restart-window` slot
2985/// becomes a no-op rolling window carried on every emitted hierarchical
2986/// reconciliation contract. The canonical
2987/// rolling-window-degenerates-to-lifetime-counter footgun the sibling
2988/// [`crate::POLICY_BREAKER_WINDOW_MAX`] cap closes on the peer
2989/// `:politicas :circuit-breaker :window` axis with identical shape (both
2990/// are "rolling failure-counting window with a per-`Period` reset" Duration
2991/// axes whose lifetime-counter degenerate at the high end is the same
2992/// "the reset semantic never fires" CSE invariant violation).
2993///
2994/// The `1h` (3600s = `3_600_000` ms) ceiling matches the largest unit
2995/// the shared duration codec emits (`"<n>h"` for any integer-hour
2996/// magnitude) — every value in the canonical authoring form's
2997/// `<integer><unit>` grammar at or below this cap renders to a clean
2998/// canonical string — and matches the three sibling typed-`Duration`
2999/// caps already lifted to this surface
3000/// ([`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
3001/// [`crate::POLICY_BREAKER_WINDOW_MAX`]). All four typed-`Duration`
3002/// axes — per-process `:limits :wall-clock`, per-edge `:politicas
3003/// :timeout`, per-breaker `:politicas :circuit-breaker :window`, and
3004/// per-supervisor `:supervisor :restart-window` — now share a single
3005/// uniform top edge at the codec's largest emitted unit so the next
3006/// typed-slot wiring (the future wasm-operator's per-supervisor
3007/// `MaxIntensity / Period` reconciler, the M4
3008/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3009/// webhook, the `caixa-operator`'s hierarchical reconciliation
3010/// scheduler) reaches for any of the four knowing the value is in
3011/// `1ms..=1h` without re-validating at the renderer layer. The cap sits
3012/// two orders of magnitude above every documented Erlang/OTP / Elixir /
3013/// Riak Core / RabbitMQ production-playbook recommendation band
3014/// (`5s..=300s`) and below the clearly-pathological "rolling window
3015/// degenerates to lifetime counter" floor (`24h`, `7d`, `Duration::MAX`):
3016/// a value the author can plausibly want for a very-low-traffic
3017/// long-tail failure-restart window over a hyperscale-flaky child pool,
3018/// but a hard wall above which the rolling-window contract is
3019/// structurally a lifetime-counter contract.
3020///
3021/// Lifted as a typed `pub const` so the bound has exactly one source
3022/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
3023/// materializer's admission webhook, the wasm-operator-side
3024/// per-supervisor `MaxIntensity / Period` reconciler, and the
3025/// `caixa-operator`'s hierarchical reconciliation scheduler all read
3026/// from one place. Same shape every other typed upper bound in this
3027/// crate carries ([`SUPERVISOR_MAX_RESTARTS_MAX`],
3028/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
3029/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
3030/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
3031/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3032/// [`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
3033/// [`crate::POLICY_BREAKER_WINDOW_MAX`],
3034/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3035/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3036pub const SUPERVISOR_RESTART_WINDOW_MAX: Duration = Duration::from_secs(3600);
3037
3038/// Substrate-canonical Erlang/OTP-shaped `Period` sliding-window-duration
3039/// default for the `:supervisor :restart-window` axis — the canonical
3040/// `{intensity, 5, 60}` `Period` half of Learn You Some Erlang's
3041/// worker-supervisor default, extracted as a typed `pub const` so every
3042/// substrate-side consumer that resolves "what
3043/// [`SupervisorSpec::restart_window`] value does an author-omitted
3044/// `:restart-window` slot degrade onto?" reaches for exactly one
3045/// substrate-primitive [`Duration`].
3046///
3047/// The `:restart-window` default axis has one production consumer on the
3048/// substrate side today: the [`Default for SupervisorSpec`] impl's
3049/// struct-literal `restart_window` field, which prior to this lift folded
3050/// onto a raw `Duration::from_secs(60)` literal with no compile-time link
3051/// back to the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity`
3052/// half of the same `{intensity, 5, 60}` OTP-canonical default. The
3053/// [`crate::manifest::Caixa::supervisor_view`] fold deliberately does
3054/// *not* fall back to this default on the sibling `:restart-window` axis
3055/// — an author-omitted `:supervisor :restart-window` composes to
3056/// `restart_window: None` (the shared codec's soft-swallow shape),
3057/// keeping author-declared intent ("no reset — never escalate on rolling
3058/// window") distinct from the [`Default for SupervisorSpec`] "canonical
3059/// 60s Period" arm every programmatic `SupervisorSpec::default()` caller
3060/// resolves to. Prior to this lift the paired `{intensity, 5, 60}` OTP
3061/// default was split across two files with no compile-time link between
3062/// the halves: [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] pinned the
3063/// `MaxIntensity` half at the substrate primitive while the `Period`
3064/// half rode as an open-coded literal at the composition site, so a
3065/// future coherent rebrand of the paired canonical (a tightening to
3066/// Elixir's `{max_restarts: 3, max_seconds: 5}`, a widening to a
3067/// per-cluster overlay the operator pins through a future
3068/// `:supervisor :restart-window-overrides` slot the MESH-COMPOSITION
3069/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
3070/// paired constants to a per-child-cohort `{MaxR, MaxT}` restart-budget-
3071/// partition once the INSPIRATIONS §II.2 Erlang/OTP per-child-cohort
3072/// roadmap lands) would have had to migrate the `MaxIntensity` half
3073/// through the lifted constant and the `Period` half through a raw
3074/// literal in lockstep or the two halves of the same OTP-canonical
3075/// default would silently drift out of pairing. Lifting the resolution
3076/// rule to a typed `pub const` on the substrate primitive means the
3077/// paired OTP-canonical default migrates as one unit on any future
3078/// axis change.
3079///
3080/// The `60s` value pins Learn You Some Erlang's `{intensity, 5, 60}`
3081/// worker-supervisor default (the closest canonical OTP-shape
3082/// production reference the substrate carries, matching the paired
3083/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5` `MaxIntensity` half this
3084/// constant is the `Period` denominator of on the same
3085/// `MaxIntensity / Period` restart-intensity ratio). Two orders of
3086/// magnitude below the [`SUPERVISOR_RESTART_WINDOW_MAX`] `3600s`
3087/// (`1h`) ceiling (the upper bracket on the same axis, sibling of
3088/// this lower default; both are typed [`Duration`] const bounds on the
3089/// `:supervisor :restart-window` axis and now share one accessor
3090/// discipline on the substrate) and above the OTP-`supervisor`
3091/// callback-module `MaxT = 5` seconds "minimal-window" floor — the "60s
3092/// rolling window" default is deliberately loose enough to absorb a
3093/// short burst of transient child failures without escalating past the
3094/// supervisor's parent while remaining tight enough for the paired
3095/// `MaxIntensity / Period` ratio's escalation to trip on a genuinely-
3096/// stuck child within a human-scale observation window.
3097///
3098/// Lifted as a typed `pub const` so the paired OTP-canonical default has
3099/// exactly one source of truth on each half — the sibling
3100/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half and this
3101/// `Period` `60s` half now share the same substrate-primitive lift
3102/// discipline. Same shape every other typed default in this crate
3103/// carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] paired
3104/// `MaxIntensity` half on the same OTP-canonical `{intensity, 5, 60}`,
3105/// the sibling [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the same
3106/// axis, and the peer [`crate::render::DEFAULT_NAMESPACE`] /
3107/// [`crate::render::DEFAULT_LIBRARY_NAME`] per-renderer defaults on the
3108/// caixa-flux / caixa-helm rendering axes).
3109pub const SUPERVISOR_RESTART_WINDOW_DEFAULT: Duration = Duration::from_secs(60);
3110
3111/// Substrate-canonical Erlang/OTP-shaped sibling-restart-strategy default
3112/// for the `:supervisor :estrategia` axis — the canonical `one_for_one`
3113/// half of Learn You Some Erlang's `{one_for_one, intensity, 5, 60}`
3114/// worker-supervisor default, extracted as a typed `pub const` so every
3115/// substrate-side consumer that resolves "what
3116/// [`SupervisorSpec::estrategia`] variant does an author-omitted
3117/// `:estrategia` slot degrade onto?" reaches for exactly one substrate-
3118/// primitive [`RestartStrategy`].
3119///
3120/// The `:estrategia` default axis has three production consumers on the
3121/// substrate side today: the [`Default for RestartStrategy`] impl's
3122/// return arm, the [`Default for SupervisorSpec`] impl's struct-literal
3123/// `estrategia` field, and the
3124/// [`crate::manifest::Caixa::supervisor_view`] fold's
3125/// `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)` `Option<RestartStrategy>`
3126/// collapse arm — three entry points onto the same OTP-canonical
3127/// `one_for_one` value that prior to this lift folded onto a raw
3128/// `Self::OneForOne` arm at the [`Default for RestartStrategy`] impl and
3129/// implicit `RestartStrategy::default()` routes at the sibling consumers,
3130/// with no compile-time link back to the paired
3131/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` half + the paired
3132/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` half of the same
3133/// `{one_for_one, intensity, 5, 60}` OTP-canonical default. The paired
3134/// triple was split across three altitudes with no compile-time link
3135/// between the halves: the `MaxIntensity` half rode through the lifted
3136/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant (b698ec0) and the `Period`
3137/// half rode through the lifted [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3138/// constant (f7dcd0e) while the `one_for_one` half rode as an open-coded
3139/// discriminator at the [`Default for RestartStrategy`] impl, so a future
3140/// coherent rebrand of the triple (Elixir's `{:one_for_one,
3141/// max_restarts: 3, max_seconds: 5}` — same strategy, different
3142/// intensity/period; an OTP `rest_for_one` widening once the substrate
3143/// discovers startup-order-coupled child cohorts as the more common
3144/// worker-supervisor default; a per-cluster overlay the operator pins
3145/// through a future `:estrategia-overrides` slot the MESH-COMPOSITION
3146/// §III.2 supervision-canary roadmap acknowledges) would have had to
3147/// migrate the `MaxIntensity` + `Period` halves through the lifted
3148/// constants and the `one_for_one` half through an open-coded arm in
3149/// lockstep or the three halves of the same OTP-canonical default would
3150/// silently drift out of pairing. Lifting the resolution rule to a typed
3151/// `pub const` on the substrate primitive means the paired OTP-canonical
3152/// worker-supervisor default migrates as one unit on any future axis
3153/// change.
3154///
3155/// The [`RestartStrategy::OneForOne`] value pins Learn You Some Erlang's
3156/// `{one_for_one, intensity, 5, 60}` worker-supervisor default (the
3157/// closest canonical OTP-shape production reference the substrate
3158/// carries, matching the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5`
3159/// `MaxIntensity` half and the paired [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3160/// `60s` `Period` half). The `one_for_one` strategy — restart only the
3161/// failed child, leaving siblings untouched — is the default for tree-of-
3162/// independent-workers use cases the substrate's [`RestartStrategy`]
3163/// discriminator's own docstring already carries as the default arm; it
3164/// composes with the `{5, 60}` restart-intensity ratio to name the same
3165/// substrate-canonical "canonical worker-supervisor" shape the paired
3166/// halves close on their respective axes.
3167///
3168/// Lifted as a typed `pub const` so the paired OTP-canonical default has
3169/// exactly one source of truth on each of its three halves — the sibling
3170/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half, the
3171/// sibling [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` `60s` half, and
3172/// this `one_for_one` strategy half now share the same substrate-
3173/// primitive lift discipline. Same shape every other typed default in
3174/// this crate carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] +
3175/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] paired halves on the same OTP-
3176/// canonical `{one_for_one, intensity, 5, 60}`, the sibling
3177/// [`SUPERVISOR_MAX_RESTARTS_MAX`] + [`SUPERVISOR_RESTART_WINDOW_MAX`]
3178/// upper caps on the paired sibling axes, and the peer
3179/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
3180/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes).
3181pub const SUPERVISOR_ESTRATEGIA_DEFAULT: RestartStrategy = RestartStrategy::OneForOne;
3182
3183/// Substrate-canonical Erlang/OTP-shaped per-child restart-decision-policy
3184/// default for the `:children :restart` axis — the OTP `permanent`
3185/// worker-child default (`{ChildId, StartFunc, permanent, …}` in a
3186/// `supervisor`'s `init/1` child-spec tuple), extracted as a typed
3187/// `pub const` so every substrate-side consumer that resolves "what
3188/// [`ChildSpec::restart`] variant does an author-omitted `:children
3189/// :restart` slot degrade onto?" reaches for exactly one substrate-
3190/// primitive [`RestartPolicy`].
3191///
3192/// Completes the OTP-shape supervisor-tree default set at the substrate
3193/// primitive. The per-`:supervisor` axis already carries all three of its
3194/// halves as lifted typed constants — [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
3195/// (`one_for_one`, 95ffacc), [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
3196/// (`MaxIntensity` `5`, b698ec0), [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3197/// (`Period` `60s`, f7dcd0e) — while the per-`:children` axis's own
3198/// OTP-canonical default rode as an open-coded `Self::Permanent` arm in
3199/// the [`Default for RestartPolicy`] impl, the last un-lifted default on
3200/// the M2 `:supervisor` slot family. The split mattered because the two
3201/// axes resolve *together* on every author-omitted supervisor: a
3202/// `(defcaixa :kind Supervisor :children ((:caixa "worker" :versao
3203/// "^0.1")))` with no `:estrategia` and no per-child `:restart` degrades
3204/// onto `{one_for_one, 5, 60}` through three lifted constants and onto
3205/// `permanent` through an open-coded enum arm, so a future coherent
3206/// rebrand of the OTP-shape default set (an Elixir-shaped
3207/// `{:one_for_one, max_restarts: 3, max_seconds: 5}` tightening, a
3208/// per-cluster overlay the operator pins through the MESH-COMPOSITION
3209/// §III.2 supervision-canary roadmap slots, an OTP-`transient` widening
3210/// once the substrate discovers clean-completion-aware children as the
3211/// more common child shape) would have had to migrate three halves
3212/// through typed constants and the fourth through a raw enum arm in
3213/// lockstep or the supervisor-level and child-level defaults would
3214/// silently drift apart.
3215///
3216/// The `:children :restart` default axis has two production consumers on
3217/// the substrate side today: the [`Default for RestartPolicy`] impl's
3218/// return arm, and the serde-side `#[serde(default)]` on
3219/// [`ChildSpec::restart`] that resolves an author-omitted `:children
3220/// :restart` slot through that same impl. Both now key off this one
3221/// substrate primitive, so the future wasm-operator's per-child post-exit
3222/// restart-decision branch, the future M4
3223/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
3224/// admission webhook, and the `caixa-operator`'s hierarchical
3225/// reconciliation scheduler's per-child fan-out all reach for one typed
3226/// identifier when they resolve an omitted per-child restart posture.
3227///
3228/// The [`RestartPolicy::Permanent`] value pins Erlang/OTP's `permanent`
3229/// worker-child restart type — always restart the child regardless of how
3230/// it died, the canonical posture for long-running services that must
3231/// always be up, matching the sibling [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
3232/// `one_for_one` tree-of-independent-workers strategy this constant pairs
3233/// with under the same `{one_for_one, intensity, 5, 60}` worker-supervisor
3234/// shape. The two alternatives the closed [`RestartPolicy::ALL`] accept-set
3235/// carries ([`RestartPolicy::Transient`] — restart only on abnormal exit;
3236/// [`RestartPolicy::Temporary`] — never restart) express deliberate
3237/// one-shot / clean-completion-aware postures an author declares
3238/// explicitly, never a posture an omitted slot should silently assume.
3239pub const SUPERVISOR_CHILD_RESTART_DEFAULT: RestartPolicy = RestartPolicy::Permanent;
3240
3241/// Route the manually-authored [`Default`] impl on [`SupervisorSpec`]
3242/// through the substrate-canonical [`SupervisorSpec::otp_canonical`]
3243/// `pub const fn` constructor rather than a struct-literal cascade over
3244/// the paired [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
3245/// [`default_max_restarts`] / [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3246/// lifted consts — one source of truth for the Erlang/OTP-canonical
3247/// `{one_for_one, 5, 60}` worker-supervisor baseline across the two
3248/// paths every downstream consumer already reaches through (the
3249/// hand-authored-until-now [`Default::default`] the
3250/// `..SupervisorSpec::default()` struct-update-syntax on every
3251/// one-axis-under-test fixture in this crate's test module rests on,
3252/// and the `pub const fn` [`SupervisorSpec::otp_canonical`] constructor
3253/// every `const`-context consumer reaches through).
3254///
3255/// Extends the [`Default`]-through-const-ctor fold discipline the
3256/// [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
3257/// (abd52c2), [`crate::aplicacao::MeshPolicy`]
3258/// [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`] (91641a4),
3259/// and [`crate::BehaviorSpec`]
3260/// [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c) folds
3261/// closed on the M2 / M3 `Option`-only "canonical unset baseline"
3262/// typed-slot spec family — extended here onto the M2 supervisor-slot
3263/// [`SupervisorSpec`] whose canonical baseline is not "everything
3264/// `None`" but the OTP-canonical `{one_for_one, 5, 60}` worker-
3265/// supervisor triple. The `empty()` peer's naming did not fit
3266/// (`SupervisorSpec` carries a discriminator-shaped `estrategia` field
3267/// and a non-zero `max_restarts`/`restart_window` pair whose canonical
3268/// shape is Erlang/OTP-descended, not the "no axis declared" bottom
3269/// the sibling `Option`-only slots fold to), so this peer is named
3270/// [`SupervisorSpec::otp_canonical`] instead — the same phrasing the
3271/// existing per-arm pin tests
3272/// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`] /
3273/// [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`] /
3274/// [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
3275/// already reach for. Pinned load-bearing by
3276/// [`tests::supervisor_spec_default_routes_through_otp_canonical_ctor`]
3277/// (byte-parity pin against [`SupervisorSpec::otp_canonical`] under
3278/// [`PartialEq`], sharpening the sibling
3279/// `supervisor_spec_default_*_routes_through_lifted_default` per-arm
3280/// pins from a per-field lift into a whole-struct one-source-of-truth
3281/// pin — the derived-until-now [`Default::default`] and the
3282/// [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
3283/// construction, not by coincidence).
3284impl Default for SupervisorSpec {
3285 #[inline]
3286 fn default() -> Self {
3287 Self::otp_canonical()
3288 }
3289}
3290
3291impl SupervisorSpec {
3292 /// `const`-context peer of the [`Default for SupervisorSpec`]
3293 /// impl (which routes through this constructor) — returns the
3294 /// Erlang/OTP-canonical `{one_for_one, 5, 60}` worker-supervisor
3295 /// baseline this crate reaches for in every fixture-builder
3296 /// `..SupervisorSpec::default()` struct-update expression and
3297 /// every downstream `SupervisorSpec::default()` seed.
3298 ///
3299 /// Each field routes through the same substrate-canonical
3300 /// [`SUPERVISOR_ESTRATEGIA_DEFAULT`] / [`default_max_restarts`] /
3301 /// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] lifted consts the
3302 /// per-arm pin tests
3303 /// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`]
3304 /// / [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`]
3305 /// / [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
3306 /// already assert, so a future coherent rebrand of the OTP-canonical
3307 /// triple (Elixir's `{max_restarts: 3, max_seconds: 5}`, a per-
3308 /// cluster overlay via a future `:restart-window-overrides` slot, a
3309 /// per-child-cohort promotion the INSPIRATIONS.md §II.2 Erlang/OTP
3310 /// absorption roadmap acknowledges) migrates through three typed
3311 /// constants in lockstep, and the paired [`Default`] impl inherits
3312 /// every future extension by construction.
3313 ///
3314 /// `pub const fn` rather than the derived-style `Default::default`
3315 /// or a `pub const SUPERVISOR_SPEC_DEFAULT: SupervisorSpec` item —
3316 /// [`Default::default`] is not `const` on stable Rust, and
3317 /// `SupervisorSpec` is non-`Copy` so a `pub const` item would force
3318 /// every consumer through a [`Clone::clone`]. The `pub const fn`
3319 /// discipline lets `const`-context callers construct the OTP-
3320 /// canonical baseline at compile time without runtime dispatch on
3321 /// the derived [`Default::default`], the same posture the sibling
3322 /// [`crate::LimitsSpec::empty`] (9739971) /
3323 /// [`crate::aplicacao::MeshPolicy::empty`] (6df969b) /
3324 /// [`crate::BehaviorSpec::empty`] (f9b18e3) `Option`-only typed-slot
3325 /// spec `pub const fn` constructors carry on the sibling
3326 /// "everything `None`" baseline axis.
3327 ///
3328 /// Fourth peer on the M2 / M3 typed-slot-spec "const-context peer
3329 /// of the derived-style [`Default`]" family — sibling of the
3330 /// [`crate::LimitsSpec::empty`] / [`crate::aplicacao::MeshPolicy::empty`]
3331 /// / [`crate::BehaviorSpec::empty`] `Option`-only "canonical unset
3332 /// baseline" trio, extended here onto the M2 supervisor-slot
3333 /// [`SupervisorSpec`] whose canonical baseline is not "everything
3334 /// `None`" but the Erlang/OTP-canonical `{one_for_one, 5, 60}`
3335 /// worker-supervisor triple. Named [`Self::otp_canonical`] rather
3336 /// than `empty()` to name the actual invariant the return value
3337 /// pins — the same phrasing already used in the per-arm pin tests
3338 /// on this file. Pinned load-bearing by
3339 /// [`tests::supervisor_spec_otp_canonical_byte_equals_default`] and
3340 /// [`tests::supervisor_spec_otp_canonical_is_usable_in_const_context`].
3341 #[must_use]
3342 pub const fn otp_canonical() -> Self {
3343 Self {
3344 estrategia: SUPERVISOR_ESTRATEGIA_DEFAULT,
3345 max_restarts: default_max_restarts(),
3346 restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3347 children: Vec::new(),
3348 }
3349 }
3350
3351 /// Substrate-canonical per-`:supervisor` `:estrategia` OTP-shaped
3352 /// sibling-restart-strategy scalar accessor every consumer that
3353 /// dispatches on the supervisor's per-sibling restart-decision shape
3354 /// keys off — returns the author-declared `:supervisor :estrategia`
3355 /// variant verbatim as a [`RestartStrategy`], `Copy`-projected from
3356 /// the typed slot's own [`RestartStrategy`] storage.
3357 ///
3358 /// The `:supervisor :estrategia` slot carries the closed-set
3359 /// OTP-shaped sibling-restart-strategy discriminator ([`RestartStrategy::OneForOne`]
3360 /// — restart only the failed child, the Erlang/OTP `one_for_one` default;
3361 /// [`RestartStrategy::OneForAll`] — restart every child on any child
3362 /// failure, the Erlang/OTP `one_for_all` shared-state cohort default;
3363 /// [`RestartStrategy::RestForOne`] — restart the failed child and
3364 /// every child started after it, the Erlang/OTP `rest_for_one`
3365 /// startup-order default; [`RestartStrategy::SimpleOneForOne`] —
3366 /// dynamic children of the same shape, the Erlang/OTP
3367 /// `simple_one_for_one` per-session default) that every downstream
3368 /// consumer of the Supervisor's per-sibling restart-decision fan-out
3369 /// shape keys off. Validated by [`SupervisorSpec::validate`] to be
3370 /// paired coherently with the sibling `:children` axis
3371 /// (`SimpleOneForOne ↔ children.is_empty()` — the cross-slot
3372 /// partition the strategy-arm's [`SupervisorError::SimpleOneForOneWithStaticChildren`]
3373 /// / [`SupervisorError::NoChildren`] refusal cascade pins), and every
3374 /// downstream consumer that reads the strategy keys off this scalar
3375 /// (the [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
3376 /// partition-dispatch `match` arm, the non-`SimpleOneForOne`-arm
3377 /// declared-but-empty [`SupervisorError::NoChildren`] error carrier's
3378 /// `estrategia:` field, the future `feira app graph` per-Supervisor
3379 /// strategy print line, the future wasm-operator's per-supervisor
3380 /// sibling-restart-strategy branch, the future M4
3381 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-strategy
3382 /// admission-webhook resolver, the `caixa-operator`'s hierarchical
3383 /// reconciliation scheduler's per-strategy fan-out).
3384 ///
3385 /// Prior to this lift the `.estrategia` field was accessed inline at
3386 /// two production sites in `caixa-core/src/supervisor.rs` — the
3387 /// [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
3388 /// `match self.estrategia { … }` partition dispatch, and the
3389 /// non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
3390 /// carrier at `estrategia: self.estrategia` — two open-coded
3391 /// field-accesses that expressed no compile-time link back to the
3392 /// typed slot. A future extension of the `:supervisor :estrategia`
3393 /// axis to a richer author surface (a per-cluster strategy override
3394 /// the operator pins through a future `:supervisor :estrategia-overrides`
3395 /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
3396 /// acknowledges, a per-tenant strategy-alias table the M4 CR
3397 /// materializer resolves per-CR, a per-Supervisor dynamic strategy
3398 /// derivation the future adaptive-supervision engine computes from
3399 /// child-failure-history topology, a per-child-cohort strategy split
3400 /// the future `RestForCohort` extension acknowledged by the
3401 /// INSPIRATIONS.md §II.2 Erlang/OTP absorption roadmap acknowledges)
3402 /// would have had to be threaded through every open-coded copy in
3403 /// lockstep — one consumer reading the raw variant while a peer read
3404 /// the operator-resolved variant would silently split the
3405 /// [`SupervisorError::NoChildren`] diagnostic's quoted strategy from
3406 /// the actual partition-dispatch input the empty-children refusal
3407 /// arm reached under, a two-consumer split at the validator far from
3408 /// the source `caixa.lisp` with no field naming the strategy-drift
3409 /// root cause. Lifting the resolution rule to a typed method on the
3410 /// substrate primitive means every downstream consumer of the
3411 /// Supervisor's per-`:supervisor` sibling-restart-strategy surface
3412 /// reaches for exactly one typed dispatch — the resolver's accept-set
3413 /// migrates as a unit on any future axis addition.
3414 ///
3415 /// Peer of the sibling M3 mesh-slot [`crate::Placement::estrategia`]
3416 /// (921fe1b) `Copy`-return `PlacementStrategy` scalar accessor on the
3417 /// per-`:placement` distribution-strategy axis — same "one typed
3418 /// dispatch on the substrate primitive, thin projections at each
3419 /// consumer" discipline extended onto the M2 supervisor-slot
3420 /// per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
3421 /// scalar axis. The two typed axes (`Placement::estrategia` on the
3422 /// M3 Aplicacao side, `SupervisorSpec::estrategia` on the M2
3423 /// Supervisor side) now share one accessor discipline for the shared
3424 /// substrate concept "a `Copy`-projected closed-set enum-arm
3425 /// discriminator that partitions the downstream renderer's per-arm
3426 /// fan-out". First `Copy`-return accessor on the M2 supervisor-slot
3427 /// `SupervisorSpec` type — companion to the sibling per-`:children`
3428 /// [`crate::ChildSpec::nome`] (57c61d0) /
3429 /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
3430 /// scalar accessors on the sibling per-`:children` `String`-carry
3431 /// axes. Named `estrategia()` to match the storage field's name and
3432 /// the peer [`crate::Placement::estrategia`] method-name discipline
3433 /// verbatim; the accessor's identity name maps onto the canonical
3434 /// OTP-shape supervision vocabulary the [`RestartStrategy`] enum's
3435 /// docstring already carries.
3436 ///
3437 /// Declared `pub const fn` to close the M2 supervisor-slot
3438 /// `Copy`-return raw-field-getter `const`-eval-surface pass —
3439 /// sibling of the peer M2 per-`:children` [`ChildSpec::restart`]
3440 /// (converted in this commit) `Copy`-composite-enum accessor, peer
3441 /// of the sibling M2 per-`:supervisor`
3442 /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
3443 /// already lifted, and mirror of the peer M3 mesh-slot
3444 /// per-`:placement` [`crate::Placement::estrategia`] (bafa004)
3445 /// `Copy`-return `pub const fn` scalar accessor whose method-name
3446 /// discipline this accessor was authored to match. Every downstream
3447 /// substrate-side `const`-context consumer of the per-`:supervisor`
3448 /// sibling-restart-strategy scalar (a future module-scope `const
3449 /// _:() = assert!(matches!(sup.estrategia(),
3450 /// RestartStrategy::OneForOne))` invariant pin on a typed fixture,
3451 /// a future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
3452 /// admission-webhook `const fn` per-supervisor strategy-arm floor
3453 /// over a typed [`SupervisorSpec`], any future `const fn`
3454 /// supervisor-tree composer over the substrate primitive that fans
3455 /// on the sibling-restart-strategy at compile time) now reaches
3456 /// through the same typed dispatch on the substrate primitive at
3457 /// const-eval time as at runtime. A future non-`Copy`-return
3458 /// promotion of the scalar (an `Option<RestartStrategy>`-shape
3459 /// migration once the substrate grows per-cluster strategy overlays
3460 /// the [`SupervisorSpec`] docstring already anticipates, a
3461 /// per-tenant strategy-alias table the M4 CR materializer resolves
3462 /// per-CR) that would drop the `const` qualifier fails the
3463 /// fail-before-pass-after pin
3464 /// [`tests::supervisor_spec_estrategia_accessor_is_const_fn`] at
3465 /// caixa-core build time rather than surfacing as a downstream
3466 /// consumer regression.
3467 #[must_use]
3468 pub const fn estrategia(&self) -> RestartStrategy {
3469 self.estrategia
3470 }
3471
3472 /// Substrate-canonical per-`:supervisor` `:max-restarts` OTP-shaped
3473 /// `MaxIntensity` restart-budget scalar accessor every consumer that
3474 /// reads the supervisor's per-`:restart-window` restart-budget count
3475 /// keys off — returns the author-declared `:supervisor :max-restarts`
3476 /// typed `u32` verbatim, `Copy`-projected from the typed slot's own
3477 /// `u32` storage (`u32` is `Copy`, so the accessor returns by value; no
3478 /// borrow of `&self` past the call). Non-optional (the `u32` field
3479 /// carries the restart-budget count as a required axis with a
3480 /// [`default_max_restarts`]-supplied default; the zero-floor arm
3481 /// [`SupervisorError::ZeroMaxRestarts`] and the cap arm
3482 /// [`SupervisorError::MaxRestartsExceedsCap`] jointly bracket the
3483 /// accept-set to `1..=SUPERVISOR_MAX_RESTARTS_MAX`).
3484 ///
3485 /// The `:supervisor :max-restarts` slot carries the Erlang/OTP
3486 /// `MaxIntensity` restart-budget count that pairs with the sibling
3487 /// `:restart-window` `Period` to form the `MaxIntensity / Period`
3488 /// restart-intensity ratio the supervisor trips its own escalation on
3489 /// (`theory/RUNTIME-PATTERNS.md` §II.2, Learn You Some Erlang's
3490 /// `{intensity, 5, 60}` worker-supervisor default). Every downstream
3491 /// consumer of the Supervisor's per-`:supervisor` restart-budget count
3492 /// keys off this scalar (the [`SupervisorSpec::validate`] zero-floor +
3493 /// upper-cap bracket at
3494 /// `require_positive_bounded_u32(self.max_restarts(), …)`, the future
3495 /// wasm-operator's per-supervisor restart-intensity counter's
3496 /// budget-vs-count comparator, the future M4
3497 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3498 /// webhook, the `caixa-operator`'s hierarchical reconciliation
3499 /// scheduler's per-supervisor escalation-decision branch, every
3500 /// `SupervisorError::MaxRestartsExceedsCap` variant carrying the
3501 /// offending count verbatim for `feira lint` rendering).
3502 ///
3503 /// Prior to this lift the `.max_restarts` field was accessed inline at
3504 /// one production site in `caixa-core/src/supervisor.rs` — the
3505 /// [`SupervisorSpec::validate`] `require_positive_bounded_u32(self
3506 /// .max_restarts, …)` bracket-gate call — one open-coded field-access
3507 /// that expressed no compile-time link back to the typed slot. A
3508 /// future extension of the `:max-restarts` axis to a richer author
3509 /// surface (a per-cluster restart-budget override the operator pins
3510 /// through a future `:supervisor :max-restarts-overrides` slot the
3511 /// MESH-COMPOSITION §III.2 supervision-canary roadmap acknowledges,
3512 /// a per-tenant restart-budget-alias table the M4 CR materializer
3513 /// resolves per-CR, a per-supervisor dynamic restart-budget derivation
3514 /// the future adaptive-supervision engine computes from child-failure-
3515 /// history topology, a promotion of the plain `u32` count to a richer
3516 /// `{MaxR, MaxT}` tuple once Erlang/OTP's per-child-cohort restart-
3517 /// budget-partition slot comes into scope) would have had to be
3518 /// threaded through every open-coded copy in lockstep or the validate
3519 /// gate and the future M4 emit path would silently disagree on which
3520 /// restart-budget count a given supervisor resolves to — an author's
3521 /// `:max-restarts 5` would satisfy validate while the emit path
3522 /// silently read a drifted other value (a `:max-restarts 10000`
3523 /// no-op supervisor at the emit boundary would carry the author's
3524 /// declared `5` verbatim in `feira lint` output while the future
3525 /// wasm-operator's restart-intensity counter operated under the
3526 /// drifted count), a two-consumer split at the validator far from the
3527 /// source `caixa.lisp` with no field naming the restart-budget-drift
3528 /// root cause. Lifting the resolution rule to a typed method on the
3529 /// substrate primitive means every downstream consumer of the
3530 /// Supervisor's per-`:supervisor` restart-budget-count surface reaches
3531 /// for exactly one typed dispatch — the resolver's accept-set migrates
3532 /// as a unit on any future axis addition.
3533 ///
3534 /// Peer of the sibling M3 mesh-slot [`crate::CircuitBreaker::max_failures`]
3535 /// (3a74062) `Copy`-return `u32` sub-struct required-scalar accessor
3536 /// on the per-`:politicas :circuit-breaker :max-failures` Envoy-
3537 /// outlier-detection trip-threshold axis — same "one typed dispatch on
3538 /// the substrate primitive, thin projections at each consumer"
3539 /// discipline extended onto the M2 supervisor-slot per-`:supervisor`
3540 /// restart-budget-count `Copy`-`u32` scalar axis. The two typed axes
3541 /// (`CircuitBreaker::max_failures` on the M3 Aplicacao side,
3542 /// `SupervisorSpec::max_restarts` on the M2 Supervisor side) now share
3543 /// one accessor discipline for the shared substrate concept "a
3544 /// `Copy`-projected required `u32` count that trips the next-higher
3545 /// protection layer after N events in a rolling window" — both are
3546 /// counters with identical degenerate-at-the-high-end shape and share
3547 /// the paired [`crate::POLICY_BREAKER_MAX_FAILURES_MAX`] /
3548 /// [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` cap. Second `Copy`-return
3549 /// accessor on the M2 supervisor-slot `SupervisorSpec` type, sibling
3550 /// to the [`SupervisorSpec::estrategia`] (eafb619) `Copy`-composite-
3551 /// enum `RestartStrategy` accessor. Named `max_restarts()` to match
3552 /// the storage field's name verbatim and the peer
3553 /// [`crate::CircuitBreaker::max_failures`] method-name discipline; the
3554 /// accessor's identity maps onto the canonical OTP-shape supervision
3555 /// vocabulary the [`SupervisorSpec::max_restarts`] field's docstring
3556 /// already carries.
3557 #[must_use]
3558 pub const fn max_restarts(&self) -> u32 {
3559 self.max_restarts
3560 }
3561
3562 /// Substrate-canonical per-`:supervisor` `:restart-window` OTP-shaped
3563 /// `Period` sliding-window scalar accessor every consumer of the
3564 /// supervisor's `MaxIntensity / Period` restart-intensity denominator
3565 /// keys off — returns the author-declared `:supervisor :restart-window`
3566 /// typed [`Duration`] verbatim as an `Option<Duration>`, copied out of
3567 /// the typed slot's own `Option<Duration>` storage (`Duration` is
3568 /// `Copy`, so `Option<Duration>` is `Copy` and the accessor returns by
3569 /// value; no borrow of `&self` past the call). `None` when the slot is
3570 /// absent (the canonical "never reset — every restart across the
3571 /// supervisor's lifetime counts against the sibling `:max-restarts`
3572 /// budget" sentinel the field's own docstring names and the peer
3573 /// `validate_accepts_none_restart_window` pin locks in on the
3574 /// [`SupervisorSpec::validate`] entry-side).
3575 ///
3576 /// The `:supervisor :restart-window` slot carries the Erlang/OTP
3577 /// `Period` sliding-observation-interval that pairs with the sibling
3578 /// `:max-restarts` `MaxIntensity` restart-budget count to form the
3579 /// `MaxIntensity / Period` restart-intensity ratio the supervisor
3580 /// trips its own escalation on (`theory/RUNTIME-PATTERNS.md` §II.2,
3581 /// Learn You Some Erlang's `{intensity, 5, 60}` worker-supervisor
3582 /// default). The typed slot's `Option<Duration>` accept-set —
3583 /// zero-floor rejected through [`SupervisorError::RestartWindowZero`]
3584 /// (Erlang/OTP's `MaxIntensity / Period` invariant requires
3585 /// `Period > 0`; a zero period either trips on the first failure or
3586 /// never trips depending on operator interpretation, neither of which
3587 /// is the author's intent — omit the slot to express "no reset";
3588 /// carry a positive duration to express the sliding window),
3589 /// integer-millisecond canonical form enforced through
3590 /// [`SupervisorError::RestartWindowNotCanonical`] (the duration
3591 /// codec's canonical form emits `"1500ms"` not `"1.5s"` and the
3592 /// future wasm-operator's per-supervisor restart-intensity counter
3593 /// quantizes at milliseconds), upper-bounded by
3594 /// [`SUPERVISOR_RESTART_WINDOW_MAX`] (1h — the coarsest per-
3595 /// supervisor rolling window any operationally-reachable supervisor
3596 /// can honor without spanning multiple scheduler epochs the
3597 /// hierarchical-reconciliation scheduler treats as independent) —
3598 /// maps onto the future wasm-operator (M3) per-supervisor
3599 /// restart-intensity counter's rolling-observation-interval, the
3600 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
3601 /// per-`spec.restartWindow` admission webhook, and the sibling
3602 /// `duration_codec`-serialized wire scalar every downstream consumer
3603 /// of the supervisor's per-`:supervisor` restart-intensity denominator
3604 /// keys off.
3605 ///
3606 /// Prior to this lift the `.restart_window` field was accessed inline
3607 /// at one production site in `caixa-core/src/supervisor.rs` — the
3608 /// [`SupervisorSpec::validate`] `if let Some(w) = self.restart_window {
3609 /// … }` zero-floor + canonical-form + upper-cap bracket arm — one
3610 /// open-coded field-access that expressed no compile-time link back to
3611 /// the typed slot. A future extension of the `:restart-window` axis to
3612 /// a richer author surface (a per-cluster restart-window override the
3613 /// operator pins through a future `:supervisor :restart-window-overrides`
3614 /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
3615 /// acknowledges, a per-tenant restart-window-alias table the M4 CR
3616 /// materializer resolves per-CR, a per-supervisor dynamic
3617 /// restart-window derivation the future adaptive-supervision engine
3618 /// computes from child-failure-history topology, a promotion of the
3619 /// plain `Option<Duration>` window to a richer `{observation, cooldown}`
3620 /// pair once Erlang/OTP's per-child-cohort observation-interval-
3621 /// partition slot comes into scope) would have had to be threaded
3622 /// through every open-coded copy in lockstep or the validate gate and
3623 /// the future M4 emit path would silently disagree on which
3624 /// restart-window a given supervisor resolves to — an author's
3625 /// `:restart-window "60s"` would satisfy validate while the emit path
3626 /// silently read a drifted other value (a `Some(Duration::from_secs(60))`
3627 /// authored slot at the emit boundary would carry the author's
3628 /// declared window verbatim in `feira lint` output while the future
3629 /// wasm-operator's restart-intensity counter operated under a
3630 /// drifted window, or vice versa: an author's `:restart-window ()`
3631 /// would carry the "never reset" sentinel through validate while the
3632 /// emit path silently substituted a default sliding window), a
3633 /// two-consumer split at the validator far from the source
3634 /// `caixa.lisp` with no field naming the restart-window-drift root
3635 /// cause. Lifting the resolution rule to a typed method on the
3636 /// substrate primitive means every downstream consumer of the
3637 /// Supervisor's per-`:supervisor` restart-intensity-denominator
3638 /// surface reaches for exactly one typed dispatch — the resolver's
3639 /// accept-set migrates as a unit on any future axis addition.
3640 ///
3641 /// Third `Copy`-return accessor on the M2 supervisor-slot
3642 /// `SupervisorSpec` type, closing the last unlifted per-`:supervisor`
3643 /// scalar-value axis (`children: Vec<ChildSpec>` carries a `Vec`
3644 /// payload rather than a `Copy`-scalar, and the per-`:children`
3645 /// [`crate::ChildSpec::nome`] (57c61d0) /
3646 /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
3647 /// scalar accessors already close the per-element `String`-carry
3648 /// axes). Sibling to the peer M2 [`crate::LimitsSpec::wall_clock`]
3649 /// (8cb717b) `Option<Duration>` accessor on the `:limits` slot's
3650 /// per-outermost-call wall-clock-deadline axis and the peer M3
3651 /// [`crate::MeshPolicy::timeout`] (7073d0f) `Option<Duration>`
3652 /// accessor on the `:politicas` slot's per-call-deadline axis — all
3653 /// three share the shared substrate concept "a `Copy`-projected
3654 /// optional `Duration` that carries a positive integer-millisecond
3655 /// canonical value with a `1ms..=<axis-specific>_MAX` accept-set and
3656 /// the paired zero-floor / non-canonical / above-cap refusal cascade"
3657 /// through the same [`crate::render::require_positive_canonical_bounded_duration`]
3658 /// bracket-helper the three axes each route through. Named
3659 /// `restart_window()` to match the storage field's name verbatim and
3660 /// the peer [`crate::LimitsSpec::wall_clock`] /
3661 /// [`crate::MeshPolicy::timeout`] method-name discipline; the
3662 /// accessor's identity maps onto the canonical OTP-shape supervision
3663 /// vocabulary the [`SupervisorSpec::restart_window`] field's docstring
3664 /// already carries.
3665 #[must_use]
3666 pub const fn restart_window(&self) -> Option<Duration> {
3667 self.restart_window
3668 }
3669
3670 /// Substrate-canonical per-`:supervisor` `:children` OTP-shaped
3671 /// static-child-list slice accessor every consumer that walks the
3672 /// supervisor's declared child set keys off — returns the author-
3673 /// declared `:supervisor :children` `Vec<ChildSpec>` verbatim as a
3674 /// `&[ChildSpec]` slice-view, borrowed from the typed slot's own
3675 /// `Vec<ChildSpec>` storage (a zero-copy slice-view over the same
3676 /// backing buffer the `Serialize`/`Deserialize` derives round-trip
3677 /// through). Non-optional: an empty slice is the load-bearing
3678 /// "author declared `:children ()`" sentinel every consumer of the
3679 /// cross-slot `SimpleOneForOne ↔ children.is_empty()` partition
3680 /// keys off (`SimpleOneForOne` requires the empty slice; the peer
3681 /// three strategies require a non-empty slice — the paired
3682 /// [`SupervisorError::SimpleOneForOneWithStaticChildren`] /
3683 /// [`SupervisorError::NoChildren`] refusal cascade pins the
3684 /// partition on both arms).
3685 ///
3686 /// The `:supervisor :children` slot carries the OTP-shaped static
3687 /// child list the supervisor materializes one ComputeUnit per
3688 /// entry from — the Erlang/OTP `supervisor:init/1`'s
3689 /// `{ok, {SupFlags, ChildSpecs}}` `ChildSpecs` list, projected
3690 /// through the tatara-lisp `:children` author surface onto a typed
3691 /// `Vec<ChildSpec>` whose per-element `(nome(),
3692 /// versao_requirement(), restart)` triple the per-child
3693 /// [`SupervisorSpec::validate`] loop already gates through the
3694 /// lifted [`ChildSpec::nome`] (57c61d0) /
3695 /// [`ChildSpec::versao_requirement`] (2c053c8) scalar accessors.
3696 /// Every downstream consumer that fans on the static child list
3697 /// keys off this slice (the [`SupervisorSpec::validate`]
3698 /// `SimpleOneForOne ↔ non-SimpleOneForOne` partition dispatch's
3699 /// `.is_empty()` probe on both arms, the [`SupervisorSpec::validate`]
3700 /// per-child DNS-1123 / semver-requirement / duplicate-detection
3701 /// fan-out loop, every future wasm-operator (M3) per-supervisor
3702 /// hierarchical-reconciliation scheduler's per-child ComputeUnit
3703 /// materialization loop, the future M4
3704 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
3705 /// admission-webhook fan-out, the future `feira app graph`
3706 /// per-supervisor tree-print traversal).
3707 ///
3708 /// Prior to this lift the `.children` `Vec<ChildSpec>` was accessed
3709 /// inline at three production sites in `caixa-core/src/supervisor.rs`
3710 /// — the [`SupervisorSpec::validate`] `SimpleOneForOne`-arm
3711 /// `!self.children.is_empty()` cross-slot refusal probe, the peer
3712 /// non-`SimpleOneForOne`-arm `self.children.is_empty()`
3713 /// [`SupervisorError::NoChildren`] refusal probe, and the per-child
3714 /// validate loop's `for child in &self.children` traversal head —
3715 /// three open-coded field-accesses that expressed no compile-time
3716 /// link back to the typed slot. A future extension of the
3717 /// `:supervisor :children` axis to a richer author surface (a
3718 /// per-cluster child-set overlay the operator pins through a future
3719 /// `:supervisor :children-overrides` slot the MESH-COMPOSITION §III.2
3720 /// supervision-canary roadmap acknowledges, a per-tenant
3721 /// child-set-alias table the M4 CR materializer resolves per-CR,
3722 /// a per-supervisor dynamic-child derivation the future adaptive-
3723 /// supervision engine computes from child-failure-history topology,
3724 /// a promotion of the plain `Vec<ChildSpec>` to a richer
3725 /// `{static, dynamic}` partition once Erlang/OTP's
3726 /// `simple_one_for_one` dynamic-child slot comes into typed scope)
3727 /// would have had to be threaded through all three open-coded copies
3728 /// in lockstep or one consumer would silently disagree with the
3729 /// peers on which child-set a given supervisor resolves to — the
3730 /// `SimpleOneForOne`-arm probe reading the raw slot while the peer
3731 /// non-`SimpleOneForOne`-arm probe read an operator-resolved slot
3732 /// would silently split the partition-dispatch's two-arm coherence
3733 /// (a supervisor that satisfies neither arm's precondition, or that
3734 /// satisfies both, at the cost of the paired
3735 /// `SimpleOneForOneWithStaticChildren`/`NoChildren` refusal cascade
3736 /// silently drifting from the per-child validate loop's actual
3737 /// traversal input), a three-consumer split at the validator far
3738 /// from the source `caixa.lisp` with no field naming the
3739 /// child-set-drift root cause. Lifting the resolution rule to a
3740 /// typed method on the substrate primitive means every downstream
3741 /// consumer of the Supervisor's per-`:supervisor` static-child-list
3742 /// surface reaches for exactly one typed dispatch — the resolver's
3743 /// accept-set migrates as a unit on any future axis addition.
3744 ///
3745 /// First slice-return (`&[T]`) accessor on any M2 or M3 typed slot
3746 /// — the seed for the same "one typed dispatch on the substrate
3747 /// primitive, thin projections at each consumer" discipline the
3748 /// closed [`crate::LimitsSpec`] / [`BehaviorSpec`] /
3749 /// [`crate::UpgradeFromEntry`] scalar-accessor families each carry
3750 /// on their `Copy` / `Option<Copy>` / `Option<&str>` axes, extended
3751 /// onto the first `Vec`-carry axis on the substrate. The four peer
3752 /// `Vec`-carry axes still unlifted at the time of this seed —
3753 /// [`crate::Placement::clusters`] (`Vec<String>` per-cluster
3754 /// distribution-target list), [`crate::AplicacaoSpec::membros`]
3755 /// (`Vec<Membro>` per-Aplicacao member list),
3756 /// [`crate::AplicacaoSpec::contratos`] (`Vec<WitContract>`
3757 /// per-Aplicacao WIT-typed edge list),
3758 /// [`crate::UpgradeFromEntry::instructions`]
3759 /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
3760 /// — inherit this accessor's discipline as future compounding runs
3761 /// migrate their consumers onto the shared slice-return shape.
3762 /// Fourth (and final) accessor on the M2 supervisor-slot
3763 /// `SupervisorSpec` type, sibling to the three `Copy`-return
3764 /// [`SupervisorSpec::estrategia`] (eafb619) /
3765 /// [`SupervisorSpec::max_restarts`] (7844f4e) /
3766 /// [`SupervisorSpec::restart_window`] (7e7b32f) accessors — closes
3767 /// the last unlifted per-`:supervisor` field axis (the
3768 /// `Vec<ChildSpec>` static-child-list carrier) so every downstream
3769 /// per-`:supervisor` reader now routes through a typed dispatch on
3770 /// the substrate primitive. Named `children()` to match the storage
3771 /// field's name verbatim and the tatara-lisp author-surface term
3772 /// (`:children`) the field's own docstring already carries; the
3773 /// accessor's identity maps onto the canonical OTP-shape
3774 /// supervision vocabulary the [`SupervisorSpec::children`] field's
3775 /// docstring already reaches for ("Static children ..."). Returns
3776 /// `&[ChildSpec]` (not `&Vec<ChildSpec>`) because every downstream
3777 /// consumer of the child list treats it as a read-only sequence —
3778 /// the slice-view is the narrowest borrow that supports every
3779 /// present + roadmapped consumer (`.is_empty()`, `.iter()`,
3780 /// index, `.len()`) without leaking the backing `Vec`'s
3781 /// grow/push/reserve surface that no consumer of the typed view
3782 /// reaches for (the storage-side `Vec` remains reachable through
3783 /// the `pub children` field for the mutation-carrying
3784 /// `Caixa::supervisor_view` fold-in path in
3785 /// `manifest.rs:supervisor_view`).
3786 #[must_use]
3787 pub const fn children(&self) -> &[ChildSpec] {
3788 self.children.as_slice()
3789 }
3790
3791 /// Validate the supervisor's typed shape — strategy ↔ children
3792 /// invariants, max_restarts > 0, restart_window > 0 when set,
3793 /// per-child non-empty + duplicate-free names.
3794 ///
3795 /// Mirrors the value-shape discipline applied to every other
3796 /// typed slot:
3797 ///
3798 /// - `Some(Duration::ZERO)` on a Duration-bearing axis is the
3799 /// same "0 means the opposite of what you think" footgun
3800 /// closed for `:politicas :timeout` (Envoy interprets a zero
3801 /// timeout as `infinite`), `:politicas :circuit-breaker
3802 /// :window`, and `:limits :wall-clock`. The
3803 /// `MaxIntensity / Period` ratio in Erlang/OTP's
3804 /// `supervisor` requires `Period > 0`; a zero period either
3805 /// trips on the first failure or never trips depending on
3806 /// operator interpretation, neither of which is the
3807 /// author's intent. Omit `:restart-window` to express "no
3808 /// reset"; carry a positive duration to express the window.
3809 /// - duplicate `:children` `:caixa` names are the same
3810 /// graph-node-set / multiset distinction closed for
3811 /// `:membros` (4bb3f3d), `:placement :clusters` (c7c7799),
3812 /// and `:entrada :paths` (eb3456d). Two children with the
3813 /// same `:caixa` materialize as two ComputeUnits with the
3814 /// same name in the cluster's HelmRelease values, one
3815 /// silently overwriting the other. Erlang/OTP's
3816 /// `child_spec.id` is required-unique per supervisor;
3817 /// pleme-io enforces the same set-not-multiset shape on
3818 /// `:caixa` (the load-bearing identity in our renderer).
3819 pub fn validate(&self) -> Result<(), SupervisorError> {
3820 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition
3821 // dispatch and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
3822 // error carrier's `estrategia:` field through the lifted
3823 // [`SupervisorSpec::estrategia`] accessor rather than the raw
3824 // `self.estrategia` field access — the two production consumers
3825 // of the per-`:supervisor` sibling-restart-strategy scalar now
3826 // key off exactly one typed dispatch on the substrate primitive,
3827 // so any future rebrand on the axis (a per-cluster strategy
3828 // override the operator pins through a future `:supervisor
3829 // :estrategia-overrides` slot, a per-tenant strategy-alias table
3830 // the M4 CR materializer resolves per-CR) migrates as a single
3831 // caixa-core edit rather than a coordinated rewrite of the two
3832 // call sites — sibling of the peer M3 [`crate::Placement::estrategia`]
3833 // (921fe1b) four-consumer migration on the per-`:placement`
3834 // distribution-strategy axis.
3835 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition-
3836 // dispatch's paired `.is_empty()` cross-slot refusal probes
3837 // (the `SimpleOneForOne`-arm
3838 // [`SupervisorError::SimpleOneForOneWithStaticChildren`] refusal
3839 // and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
3840 // refusal) through the lifted [`SupervisorSpec::children`]
3841 // slice-return accessor rather than the raw `self.children`
3842 // field access — the two paired production consumers of the
3843 // per-`:supervisor` static-child-list scalar-shape now key off
3844 // exactly one typed dispatch on the substrate primitive, so any
3845 // future rebrand on the axis (a per-cluster child-set overlay
3846 // the operator pins through a future `:supervisor
3847 // :children-overrides` slot, a per-tenant child-set-alias table
3848 // the M4 CR materializer resolves per-CR) migrates as a single
3849 // caixa-core edit rather than a coordinated rewrite of the
3850 // paired arms — first slice-return migration on any typed slot,
3851 // seed for the peer per-`:placement :clusters`,
3852 // per-`:membros`, per-`:contratos`, and per-`:upgrade-from
3853 // :instructions` `Vec`-carry axes.
3854 match self.estrategia() {
3855 RestartStrategy::SimpleOneForOne => {
3856 // SimpleOneForOne: children added at runtime. Static
3857 // list must be empty (one shape declared elsewhere).
3858 if !self.children().is_empty() {
3859 return Err(SupervisorError::SimpleOneForOneWithStaticChildren);
3860 }
3861 }
3862 _ => {
3863 if self.children().is_empty() {
3864 return Err(SupervisorError::no_children(self.estrategia()));
3865 }
3866 }
3867 }
3868 // Zero-floor + upper-cap bracket on the typed `:max-restarts`
3869 // axis. See [`crate::render::require_positive_bounded_u32`] for
3870 // the ordering discipline (zero-floor arm strictly precedes cap
3871 // arm so `0` surfaces the self-locating `ZeroMaxRestarts`
3872 // diagnostic with its counter-axis remediation directly named,
3873 // not the misleading `0 > SUPERVISOR_MAX_RESTARTS_MAX == false`
3874 // cap-arm miss). Until this bracket landed the top edge ran all
3875 // the way to `u32::MAX` and a struct-literal
3876 // `SupervisorSpec { max_restarts: 100_000, .. }` (or the
3877 // equivalent author-surface `:max-restarts 100000` /
3878 // `:max-restarts 4294967295` typo landing in the slot) silently
3879 // passed validate. The runtime substrate consuming the value
3880 // (Erlang/OTP's `MaxIntensity / Period` ratio, the future
3881 // wasm-operator's per-supervisor restart-intensity counter, the
3882 // M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
3883 // admission webhook) then turned a typed `:max-restarts`
3884 // policy into a no-op supervisor: the escalation threshold is
3885 // structurally so high that no realistic
3886 // restarts-per-`:restart-window` traffic shape can reach it,
3887 // the supervisor never escalates to its parent, and a bad
3888 // child can loop inside the window indefinitely with the
3889 // parent supervisor structurally never receiving the "this
3890 // subtree has exceeded its restart budget" signal the typed
3891 // slot is meant to express. The bracket set is
3892 // `1..=SUPERVISOR_MAX_RESTARTS_MAX`, peer with the
3893 // [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap on
3894 // the sibling `:politicas :circuit-breaker :max-failures` axis:
3895 // both are "trip the next-higher protection layer after N
3896 // events in a rolling window" counters with identical
3897 // degenerate-at-the-high-end shape and now share one canonical
3898 // bracket helper. The bracket precedes the sibling
3899 // `:restart-window` zero-floor / canonical-millisecond arms so
3900 // an over-cap `max_restarts` paired with a structurally invalid
3901 // window surfaces the bracket diagnostic first, mirroring the
3902 // `PolicyBreakerMaxFailuresExceedsCap` / window-axis cross-arm
3903 // ordering on the peer `:politicas :circuit-breaker` slot.
3904 // Route the [`SupervisorSpec::validate`] `:max-restarts` zero-floor +
3905 // upper-cap bracket-gate through the lifted [`SupervisorSpec::max_restarts`]
3906 // accessor rather than the raw `self.max_restarts` field access —
3907 // the one production consumer of the per-`:supervisor`
3908 // restart-budget-count scalar now keys off exactly one typed
3909 // dispatch on the substrate primitive, so any future rebrand on
3910 // the axis (a per-cluster restart-budget override the operator
3911 // pins through a future `:supervisor :max-restarts-overrides`
3912 // slot, a per-tenant restart-budget-alias table the M4 CR
3913 // materializer resolves per-CR) migrates as a single caixa-core
3914 // edit rather than a coordinated rewrite — sibling of the peer M3
3915 // [`crate::CircuitBreaker::max_failures`] (3a74062) migration on
3916 // the per-`:politicas :circuit-breaker :max-failures` axis.
3917 crate::render::require_positive_bounded_u32(
3918 self.max_restarts(),
3919 SUPERVISOR_MAX_RESTARTS_MAX,
3920 || SupervisorError::ZeroMaxRestarts,
3921 SupervisorError::max_restarts_exceeds_cap,
3922 )?;
3923 // Route the [`SupervisorSpec::validate`] `:restart-window`
3924 // zero-floor + integer-millisecond canonical-form + upper-cap
3925 // bracket-gate through the lifted [`SupervisorSpec::restart_window`]
3926 // accessor rather than the raw `self.restart_window` field access —
3927 // the one production consumer of the per-`:supervisor`
3928 // restart-intensity-denominator scalar now keys off exactly one
3929 // typed dispatch on the substrate primitive, so any future rebrand
3930 // on the axis (a per-cluster restart-window override the operator
3931 // pins through a future `:supervisor :restart-window-overrides`
3932 // slot, a per-tenant restart-window-alias table the M4 CR
3933 // materializer resolves per-CR) migrates as a single caixa-core
3934 // edit rather than a coordinated rewrite — sibling of the peer M2
3935 // [`crate::LimitsSpec::wall_clock`] (8cb717b) validate-arm-route
3936 // on the per-`:limits :wall-clock` axis and the peer M3
3937 // [`crate::MeshPolicy::timeout`] (7073d0f) accessor-route on the
3938 // per-`:politicas :timeout` axis.
3939 if let Some(w) = self.restart_window() {
3940 // Zero-floor + integer-millisecond canonical-form +
3941 // upper-cap bracket on the typed `:restart-window` axis.
3942 // See
3943 // [`crate::render::require_positive_canonical_bounded_duration`]
3944 // for the full three-arm ordering discipline (zero-floor
3945 // strictly precedes canonical-form so `Duration::ZERO`
3946 // surfaces the self-locating `RestartWindowZero`
3947 // diagnostic; canonical-form strictly precedes the cap arm
3948 // so a sub-millisecond above-cap value surfaces the more
3949 // fundamental round-trip-shape diagnostic first) and the
3950 // three peer typed-`Duration` sites that share this
3951 // canonical bracket ([`crate::MeshPolicy::timeout`],
3952 // [`crate::CircuitBreaker::window`],
3953 // [`crate::LimitsSpec::wall_clock`]). Every validated
3954 // value lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
3955 // (1ms..=1h), integer-millisecond granularity.
3956 crate::render::require_positive_canonical_bounded_duration(
3957 w,
3958 SUPERVISOR_RESTART_WINDOW_MAX,
3959 || SupervisorError::RestartWindowZero,
3960 SupervisorError::restart_window_not_canonical,
3961 SupervisorError::restart_window_exceeds_cap,
3962 )?;
3963 }
3964 // Route the per-child DNS-1123 / semver-requirement / duplicate-
3965 // detection fan-out loop through the lifted named per-slot gate
3966 // [`SupervisorSpec::validate_children`] rather than an inline
3967 // three-per-child cascade — every future consumer that wants to
3968 // re-check only the `:children` slot's per-entry axes (the M4
3969 // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
3970 // admission webhook re-validating one added/renamed child, the
3971 // future wasm-operator's per-child dynamic-add re-validator on
3972 // the `SimpleOneForOne` runtime-add path once dynamic-children
3973 // graduate to a typed slot, a future partial re-validator on a
3974 // per-`:children`-entry patch) reaches every per-entry axis
3975 // through one dispatch rather than re-inlining the three-arm
3976 // cascade in lockstep with `validate` or paying the peer
3977 // `:estrategia`/`:max-restarts`/`:restart-window` gates to
3978 // reach one entry check. Sibling of the peer M3 mesh-slot
3979 // per-slot gate family (`validate_membros` — the exact peer on
3980 // the M3 side, [`crate::AplicacaoSpec::validate_membros`];
3981 // `validate_contratos` — 906a5c6; `validate_entrada` — 20cd523;
3982 // `validate_placement`; `validate_politicas` routing through
3983 // `MeshPolicy::validate` — f03a154) — the M2 supervisor-slot
3984 // per-slot gate discipline now spans both the M3 mesh-slot
3985 // family and the M2 `:children` per-child-cascade axis on one
3986 // shape: one named per-slot gate per typed per-entry loop.
3987 self.validate_children()?;
3988 Ok(())
3989 }
3990
3991 /// Named per-slot gate on the M2 `:supervisor :children` per-entry
3992 /// axis — folds the per-child DNS-1123 name gate, semver-requirement
3993 /// gate, and duplicate-`:caixa` dedup arm into one call every
3994 /// consumer that wants to re-validate one `:children` entry (or the
3995 /// whole list) against the same accept-set [`SupervisorSpec::validate`]
3996 /// admits reaches through.
3997 ///
3998 /// Peer of the M3 mesh-slot [`crate::AplicacaoSpec::validate_membros`]
3999 /// per-slot gate on the analogous per-entry axis (`:membros`) — same
4000 /// three-per-entry shape (DNS-1123 name + semver-requirement +
4001 /// duplicate-`:caixa` dedup), lifted to one named substrate
4002 /// primitive per slot. The M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
4003 /// materializer's admission webhook re-checking one added or renamed
4004 /// child, the future wasm-operator's per-child dynamic-add
4005 /// re-validator on the `SimpleOneForOne` runtime-add path once
4006 /// dynamic-children graduate to a typed slot, a future partial
4007 /// re-validator on a per-`:children`-entry patch — each reaches the
4008 /// three per-entry axes through this one dispatch rather than
4009 /// re-inlining the three-arm cascade in lockstep with `validate`
4010 /// (the duplication the PRIME DIRECTIVE names as a bug) or paying
4011 /// the peer `:estrategia`/`:max-restarts`/`:restart-window` gates to
4012 /// reach one entry check.
4013 ///
4014 /// Self-contained on `&self` — resolves its own dedup `HashSet`
4015 /// through [`SupervisorSpec::children`] rather than borrowing one
4016 /// threaded down from `validate`, the same posture the peer M3
4017 /// mesh-slot per-slot gates ([`crate::AplicacaoSpec::validate_membros`],
4018 /// [`crate::AplicacaoSpec::validate_contratos`],
4019 /// [`crate::AplicacaoSpec::validate_entrada`],
4020 /// [`crate::AplicacaoSpec::validate_placement`]) each carry, so a
4021 /// consumer that reaches this gate directly (without first calling
4022 /// `validate`) still runs the full per-child cascade — pinned by
4023 /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
4024 /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
4025 /// + `validate_children_is_self_contained_on_children_slot`.
4026 ///
4027 /// The three per-entry arms run in the same canonical order the
4028 /// pre-lift inline cascade encoded (DNS-1123 → semver → dedup), so
4029 /// the diagnostic every author-declared per-`:children` entry surfaces
4030 /// through `validate` is byte-equal to the diagnostic this gate
4031 /// surfaces when called directly — the equivalence-pin pair
4032 /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
4033 /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
4034 /// asserts the two altitudes discriminate the same set on every
4035 /// per-entry-covered input.
4036 pub fn validate_children(&self) -> Result<(), SupervisorError> {
4037 let mut seen = std::collections::HashSet::new();
4038 for child in self.children() {
4039 // Every emitted cluster artifact's `metadata.name` for a
4040 // supervised child derives from this `:children :caixa` value
4041 // verbatim — the rendered `wasm.pleme.io/v1alpha1/ComputeUnit
4042 // .metadata.name` per child, the [`crate::LABEL_PROGRAM`]
4043 // label value on every child's pod identity, and the per-
4044 // child K8s [`Service`][svc] `metadata.name` the future
4045 // wasm-operator (M3) provisions for inter-child supervision
4046 // tree wiring. Each apiserver-side schema on each landing
4047 // site enforces the DNS-1123 label rule on admission; a
4048 // structurally invalid child name (`"Worker"`, `"my_worker"`,
4049 // `"team.worker"`, `"-worker"`, `"worker-"`, the >63-byte
4050 // UUID-shaped mistaken-identity slug) silently passes the
4051 // prior empty-/duplicate-only gate and the failure surfaces
4052 // at `kubectl apply` time as a `metadata.name: Invalid value`
4053 // rejection, far from the source caixa.lisp, with no field
4054 // naming the offending `:children` entry. Lifting the gate
4055 // to caixa-build time mirrors the `:membros :caixa` value-
4056 // shape trajectory (3f9d7a0) and the `:placement :clusters`
4057 // trajectory (6cbb900) onto the third DNS-1123-label-shaped
4058 // identifier axis — the supervisor tree's child names —
4059 // through the lifted
4060 // [`crate::render::require_valid_dns_1123_label`] gate the
4061 // seven peer name axes (`:membros :caixa`, `:placement
4062 // :clusters`, `:placement :affinity`, `:contratos :de`/`:para`,
4063 // `:entrada :para`, `:nome`, `:upgrade-from :module`) each
4064 // route through, so drift between the eight axes' accepted
4065 // DNS-1123-label sets is structurally impossible.
4066 //
4067 // [svc]: https://kubernetes.io/docs/concepts/services-networking/service/
4068 crate::render::require_valid_dns_1123_label(
4069 child.nome(),
4070 || SupervisorError::EmptyChildName,
4071 |reason| SupervisorError::child_caixa_invalid(child.nome(), reason),
4072 )?;
4073 // The author surface for `:children :versao` is the same
4074 // Cargo-shaped semver requirement string `:deps :versao` and
4075 // `:membros :versao` carry — and the lacre pipeline resolves
4076 // all three axes through the same
4077 // [`crate::version::parse_requirement`] entry-point. The
4078 // shared [`crate::render::require_valid_versao_requirement`]
4079 // helper brackets the empty-first + parse cascade both peer
4080 // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
4081 // [`crate::AplicacaoSpec::validate_membros`] on `:membros
4082 // :versao`) route through, so drift between the three axes'
4083 // accepted requirement sets is structurally impossible and
4084 // the parse-side no-op the empty-first arm closes (semver's
4085 // empty parse yields an implicit `*`) lives in exactly one
4086 // predicate. Every `ChildSpec::versao` past validate is
4087 // round-trippable through [`crate::parse_requirement`]
4088 // without re-checking at the resolver layer, and the three
4089 // `:versao` typed surfaces (`:deps`, `:membros`, `:children`)
4090 // are now structurally equivalent by construction.
4091 crate::render::require_valid_versao_requirement(
4092 child.versao_requirement(),
4093 || SupervisorError::empty_child_version(child.nome()),
4094 |reason| {
4095 SupervisorError::child_versao_invalid(
4096 child.nome(),
4097 child.versao_requirement(),
4098 reason,
4099 )
4100 },
4101 )?;
4102 crate::render::insert_first_seen(&mut seen, child.nome(), || {
4103 SupervisorError::duplicate_child_caixa(child.nome())
4104 })?;
4105 }
4106 Ok(())
4107 }
4108}
4109
4110/// Cross-slot coherence gate on the supervision tree: no
4111/// `:children :caixa` entry may name the supervisor's own `:nome`.
4112///
4113/// A supervisor that lists itself as a child is a degenerate self-parent
4114/// — the supervision tree is a DAG rooted at the supervisor (OTP child
4115/// specs reference *distinct* child processes; a supervisor is never its
4116/// own child), and the wasm-operator's hierarchical reconciliation would
4117/// otherwise be handed a node that is its own parent: a one-node cycle it
4118/// either rejects far from the source `caixa.lisp` or recurses on. Because
4119/// every `:nome` is a globally-unique substrate identity (DNS-1123 label +
4120/// lacre closure root), a child whose `:caixa` equals the supervisor's
4121/// `:nome` *is* the supervisor itself, not a coincidentally-named peer.
4122///
4123/// Lives outside [`SupervisorSpec::validate`] because the typed view
4124/// carries the children but not the parent `:nome`; mirrors the
4125/// cross-slot precedence gate `validate_upgrade_from_against_versao`
4126/// (which likewise reads one slot against another at the
4127/// [`crate::layout`] wire-up site) and the mesh self-edge gate
4128/// `AplicacaoSpec`'s `ContratoSelfLoop` — the same "an edge from a graph
4129/// node to itself is structurally not a tree/mesh edge" discipline, here
4130/// on the supervision-tree axis.
4131pub fn validate_no_self_supervision(
4132 children: &[ChildSpec],
4133 parent_nome: &str,
4134) -> Result<(), SupervisorError> {
4135 for child in children {
4136 if child.nome() == parent_nome {
4137 return Err(SupervisorError::child_supervises_self(parent_nome));
4138 }
4139 }
4140 Ok(())
4141}
4142
4143#[derive(Debug, Error, PartialEq, Eq)]
4144pub enum SupervisorError {
4145 #[error("supervisor :estrategia {estrategia:?} requires at least one :children entry")]
4146 NoChildren { estrategia: RestartStrategy },
4147 #[error(
4148 "SimpleOneForOne supervisors must declare zero static children (children spawn dynamically)"
4149 )]
4150 SimpleOneForOneWithStaticChildren,
4151 #[error(":max-restarts must be > 0")]
4152 ZeroMaxRestarts,
4153 #[error(
4154 ":supervisor :max-restarts ({max_restarts}) exceeds the supervisor-policy ceiling \
4155 (SUPERVISOR_MAX_RESTARTS_MAX = 1000) — a value above this cap turns the typed \
4156 restart-intensity policy into a no-op supervisor: the escalation threshold is \
4157 structurally so high that no realistic restarts-per-:restart-window traffic shape \
4158 can reach it, so the supervisor never escalates to its parent and a bad child can \
4159 loop inside the window indefinitely. Every typed-slot consumer (Erlang/OTP's \
4160 MaxIntensity/Period ratio, the future wasm-operator's per-supervisor \
4161 restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
4162 materializer's admission webhook) emits a `:max-restarts` declaration that is \
4163 structurally never reached. Pin a value in 1..=1000 (Erlang/OTP / Elixir / Riak \
4164 Core / RabbitMQ production playbooks recommend 3..=100; the OTP `supervisor` \
4165 callback module's `MaxR = 1` minimal-restart default sits at the bottom of the \
4166 band) or restructure the supervision tree (split the flaky child into its own \
4167 sub-supervisor with a tighter budget) if you need a higher restart tolerance."
4168 )]
4169 MaxRestartsExceedsCap { max_restarts: u32 },
4170 #[error(
4171 ":restart-window must be > 0 when set — Erlang/OTP's MaxIntensity/Period \
4172 requires Period > 0; a zero window either trips on the first failure or \
4173 never trips depending on operator interpretation. Omit :restart-window to \
4174 express `never reset`; carry a positive duration to express the window."
4175 )]
4176 RestartWindowZero,
4177 #[error(
4178 ":supervisor :restart-window ({window:?}) carries a sub-millisecond residue the shared `duration_codec` cannot round-trip — \
4179 the codec truncates to `as_millis()` before picking the canonical unit, so a value with `subsec_nanos() % 1_000_000 != 0` either \
4180 truncates on first serialize (e.g. `Duration::from_micros(1500)` → \"1ms\" → `Duration::from_millis(1)` ≠ original) or renders \
4181 as \"0s\" the `RestartWindowZero` arm then rejects on re-validate. Pin an integer-millisecond magnitude in the canonical authoring form \
4182 (`<integer><unit>` for unit ∈ {{ms, s, m, h}}, e.g. `\"500ms\"`, `\"30s\"`, `\"2m\"`, `\"1h\"`) or omit the field for `never reset`"
4183 )]
4184 RestartWindowNotCanonical { window: Duration },
4185 #[error(
4186 ":supervisor :restart-window ({window:?}) exceeds the supervisor-policy ceiling \
4187 (SUPERVISOR_RESTART_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
4188 per-supervisor rolling-window restart-intensity counter into a lifetime counter: the \
4189 failure-counting window is structurally so long that transient restarts are never \
4190 forgotten, the MaxIntensity/Period ratio degenerates from `trip the parent supervisor \
4191 when the child has exceeded its restart budget within the recent window` to `trip the \
4192 parent when the child has exceeded its restart budget over its lifetime`, and the \
4193 supervisor's reset semantic never reaches the child — every typed-slot consumer \
4194 (Erlang/OTP's MaxIntensity/Period reconciler, the future wasm-operator's \
4195 per-supervisor restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
4196 materializer's admission webhook, the caixa-operator's hierarchical reconciliation \
4197 scheduler) emits a `:restart-window` declaration that is structurally a no-op rolling \
4198 window. Pin a value in 1ms..=1h (Learn You Some Erlang's `{{intensity, 5, 60}}` \
4199 worker-supervisor `Period = 60s` default, Elixir's `Supervisor` `max_seconds: 5` \
4200 default, OTP's `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's \
4201 `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default — every Erlang/OTP \
4202 / Elixir production playbook sits in the 5s..=300s band; the longest documented \
4203 per-supervisor restart-window any pleme-io substrate playbook recommends maxes at \
4204 ~30m) or omit :restart-window to express `never reset` (the supervisor's restart \
4205 budget then becomes a strict lifetime counter by design, not a degenerate one — the \
4206 author surfaces the lifetime-counter semantic explicitly at the slot, rather than \
4207 hiding it behind a rolling-window declaration the cap arm rejects)"
4208 )]
4209 RestartWindowExceedsCap { window: Duration },
4210 #[error("child entry has empty :caixa name")]
4211 EmptyChildName,
4212 #[error(
4213 "child :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
4214 (the K8s apiserver enforces this rule on every `metadata.name` / Service \
4215 name / label value the child name lands in — the per-child \
4216 `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name`, the `LABEL_PROGRAM` \
4217 label value, and the future wasm-operator per-child Service `metadata.name` \
4218 — each apiserver-side schema rejects names that don't match; use a \
4219 lowercase alphanumeric + hyphen identifier like `\"worker\"` or `\"cache-v2\"`)"
4220 )]
4221 ChildCaixaInvalid { caixa: String, reason: String },
4222 #[error("child {caixa:?} has empty :versao constraint")]
4223 EmptyChildVersion { caixa: String },
4224 #[error(
4225 "child {caixa:?} :versao {versao:?} is not a valid semver requirement: \
4226 {reason} (use Cargo-shaped forms like `\"^0.1\"`, `\"~0.1.2\"`, \
4227 `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` and \
4228 `:membros :versao` carry; the lacre pipeline resolves all three \
4229 through the same parser)"
4230 )]
4231 ChildVersaoInvalid {
4232 caixa: String,
4233 versao: String,
4234 reason: String,
4235 },
4236 #[error(
4237 "child {caixa:?} appears more than once (Erlang/OTP requires unique \
4238 child_spec.id per supervisor; duplicate children materialize as duplicate \
4239 ComputeUnits in the rendered chart, one silently overwriting the other)"
4240 )]
4241 DuplicateChildCaixa { caixa: String },
4242 #[error(
4243 "supervisor {caixa:?} lists itself as a :children entry — a supervisor is \
4244 never its own child (the supervision tree is a DAG rooted at the supervisor; \
4245 OTP child specs reference distinct child processes). Since every :nome is a \
4246 globally-unique substrate identity, a child naming the supervisor's own :nome \
4247 is a one-node reconciliation cycle, not a coincidentally-named peer; drop the \
4248 self-referential :children entry or rename it to the actual child caixa."
4249 )]
4250 ChildSupervisesSelf { caixa: String },
4251}
4252
4253// Fold the three `SupervisorError::<Variant> { caixa: <&str>.to_string() }`
4254// caixa-only struct-variant wire-up sites at [`SupervisorSpec::validate_children`]
4255// and [`validate_no_self_supervision`] onto one substrate primitive per
4256// typed variant — the sibling on `SupervisorError` of the four uniform-shape
4257// `LayoutError`-envelope constructor families the peer
4258// [`crate::layout::layout_violation_ctors!`] macro closed (131ca0d, 16
4259// variants on `{ caixa, issue }`), the [`crate::layout::layout_slot_kind_ctors!`]
4260// macro closed (0419438, 4 variants on `{ caixa, kind, slots }`), the
4261// [`crate::LayoutError::missing_entry`] one-variant ctor closed (1b09f9d,
4262// on `{ kind, path }`), and the [`crate::layout::layout_nome_only_ctors!`]
4263// macro closed (3fe3dd7, 6 variants on `<Variant>(String)`), plus the
4264// [`crate::AplicacaoError::entrada_host_invalid`] one-variant ctor
4265// (17dd504, `{ host, reason }`), the [`crate::aplicacao::contrato_target_ctors!`]
4266// macro (14b81d5, 2 variants on `{ de, para, wit, expected }`), and the
4267// [`crate::aplicacao::contrato_empty_pair_ctors!`] macro (8580068, 4
4268// variants on `{ de, para }`) already at that discipline on the peer
4269// `AplicacaoError` envelopes.
4270//
4271// Each of the three wire-up sites on this shape (`EmptyChildVersion` at
4272// the per-`:children` semver-requirement empty-first arm, `DuplicateChildCaixa`
4273// at the per-`:children` dedup arm, `ChildSupervisesSelf` at the cross-slot
4274// self-supervision arm) opened the identical
4275// `SupervisorError::<Variant> { caixa: <&str>.to_string() }` struct-literal —
4276// the exact "same block re-inlined at every consumer" shape the PRIME
4277// DIRECTIVE names as a bug, on the same altitude the peer `LayoutError` /
4278// `AplicacaoError` families each closed on their sibling envelopes. The
4279// three variants share one `{ caixa: String }` shape, so the fold routes
4280// each wire-up site through one dispatch per typed variant.
4281//
4282// The macro below generates one static constructor per variant of shape
4283// `fn <slot>(caixa: &str) -> SupervisorError`, so every wire-up site
4284// collapses onto one dispatch:
4285// `SupervisorError::<slot>(<&str>)`, byte-equal to the pre-lift
4286// struct-literal on the same `&str` fixture. The uniform one-field
4287// construction (`caixa: caixa.to_string()`) is spelled once — inside the
4288// macro — rather than at every wire-up site. Every constructor is
4289// `#[must_use]` so a caller who mistakenly discards the constructed error
4290// trips a compile warning at the wire-up site.
4291//
4292// Every future consumer that wants to construct one of these three
4293// variants outside `SupervisorSpec::validate_children` /
4294// `validate_no_self_supervision` — a deferred
4295// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
4296// webhook re-checking one added/renamed child, a future
4297// `feira validate --supervisor` per-caixa admission verb, a per-child
4298// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path
4299// once dynamic-children graduate to a typed slot, a per-Supervisor
4300// overlay resolver rejecting a duplicate/self-supervising child against
4301// a cluster-local snapshot — now reaches each variant through one call
4302// rather than re-inlining the three-line struct-literal in lockstep
4303// with the three in-crate wire-up sites.
4304macro_rules! supervisor_caixa_only_ctors {
4305 ($($ctor:ident => $variant:ident),* $(,)?) => {
4306 impl SupervisorError {
4307 $(
4308 #[doc = concat!(
4309 "Construct a [`SupervisorError::",
4310 stringify!($variant),
4311 "`] naming the offending `:children :caixa` (or ",
4312 "supervisor `:nome`, on the self-supervision arm). ",
4313 "Folds the uniform `Self::",
4314 stringify!($variant),
4315 " { caixa: caixa.to_string() }` one-field ",
4316 "struct-literal onto one substrate primitive so ",
4317 "every [`SupervisorSpec::validate_children`] / ",
4318 "[`validate_no_self_supervision`] wire-up on this ",
4319 "variant reads through one dispatch rather than the ",
4320 "pre-lift open-coded struct-literal block."
4321 )]
4322 #[must_use]
4323 pub fn $ctor(caixa: &str) -> Self {
4324 Self::$variant { caixa: caixa.to_string() }
4325 }
4326 )*
4327 }
4328 };
4329}
4330
4331supervisor_caixa_only_ctors! {
4332 empty_child_version => EmptyChildVersion,
4333 duplicate_child_caixa => DuplicateChildCaixa,
4334 child_supervises_self => ChildSupervisesSelf,
4335}
4336
4337// Fold the two `SupervisorError::{ChildCaixaInvalid, ChildVersaoInvalid}`
4338// struct-variant wire-up sites at [`SupervisorSpec::validate_children`] onto
4339// one substrate primitive per typed variant — the M2 supervisor-side siblings
4340// of the peer [`crate::AplicacaoError::membro_caixa_invalid`] two-slot ctor
4341// already lifted through the sibling
4342// [`crate::aplicacao::aplicacao_field_reason_ctors!`] macro (981060b) on the
4343// peer `AplicacaoError { caixa: String, reason: String }` envelope. The
4344// `ChildCaixaInvalid` variant carries the same `{ <name>: String, reason:
4345// String }` two-slot shape the peer seven-variant
4346// [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold closed on the
4347// `AplicacaoError` envelope (`MembroCaixaInvalid`, `EntradaParaInvalid`,
4348// `EntradaHostInvalid`, `EntradaPathInvalid`, `PlacementClusterInvalid`,
4349// `PlacementAffinityInvalid`, `ShardKeyInvalid`); the `ChildVersaoInvalid`
4350// variant carries the `{ caixa: String, versao: String, reason: String }`
4351// three-slot shape the sibling `AplicacaoError::MembroVersaoInvalid` axis
4352// carries on the same `:versao` value-shape.
4353//
4354// Each of the two wire-up sites opened the same closure-shaped
4355// `|reason| SupervisorError::<Variant> { caixa: child.nome().to_string(),
4356// [versao: child.versao_requirement().to_string(),] reason }` block inside
4357// the paired [`crate::render::require_valid_dns_1123_label`] and
4358// [`crate::render::require_valid_versao_requirement`] callbacks — the exact
4359// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE names
4360// as a bug, on the same altitude the peer `AplicacaoError` /
4361// `SupervisorError` / `LayoutError` / `DepError` / `LimitsError` ctor
4362// families already closed on their sibling envelopes.
4363//
4364// The two `#[must_use]` inherent constructors below fold each wire-up onto
4365// one dispatch: `SupervisorError::child_caixa_invalid(<name>, <reason>)`
4366// and `SupervisorError::child_versao_invalid(<name>, <versao>, <reason>)`,
4367// byte-equal to the pre-lift struct-literal on the same scalar fixtures.
4368// The uniform per-field `.to_string()` / `.into()` construction is spelled
4369// once — inside each ctor body — rather than at every wire-up site. The
4370// `reason: impl Into<String>` bound accepts both `&str` literals and
4371// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
4372// diagnostic shape at the lift, matching the peer
4373// [`aplicacao_field_reason_ctors!`] and
4374// [`crate::aplicacao::contrato_pair_value_reason_ctors!`] bounds on the
4375// sibling envelopes.
4376//
4377// Every future consumer that wants to construct one of these two variants
4378// outside `SupervisorSpec::validate_children` — a deferred
4379// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook
4380// re-checking one added/renamed child's `:caixa` or `:versao`, a future
4381// `feira validate --supervisor` per-caixa admission verb, a per-child
4382// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path once
4383// dynamic-children graduate to a typed slot, a per-Supervisor overlay
4384// resolver rejecting a shape-invalid child `:caixa`/`:versao` against a
4385// cluster-local snapshot — now reaches each variant through one call rather
4386// than re-inlining the per-shape struct-literal block in lockstep with the
4387// two in-crate wire-up sites.
4388impl SupervisorError {
4389 /// Construct a [`SupervisorError::ChildCaixaInvalid`] naming the
4390 /// offending `:children :caixa` value under the given `reason`. Folds
4391 /// the uniform `Self::ChildCaixaInvalid { caixa: caixa.to_string(),
4392 /// reason: reason.into() }` two-slot struct-literal onto one substrate
4393 /// primitive so every wire-up on this variant reads through one
4394 /// dispatch, matching the peer
4395 /// [`crate::AplicacaoError::membro_caixa_invalid`] ctor's shape on the
4396 /// sibling `AplicacaoError { caixa: String, reason: String }`
4397 /// envelope. `reason` accepts both `&str` literals and `format!(…)`
4398 /// outputs through the `impl Into<String>` bound.
4399 #[must_use]
4400 pub fn child_caixa_invalid(caixa: &str, reason: impl Into<String>) -> Self {
4401 Self::ChildCaixaInvalid {
4402 caixa: caixa.to_string(),
4403 reason: reason.into(),
4404 }
4405 }
4406
4407 /// Construct a [`SupervisorError::ChildVersaoInvalid`] naming the
4408 /// offending `:children :caixa` and its `:versao` requirement under
4409 /// the given `reason`. Folds the uniform `Self::ChildVersaoInvalid {
4410 /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
4411 /// reason.into() }` three-slot struct-literal onto one substrate
4412 /// primitive so every wire-up on this variant reads through one
4413 /// dispatch, matching the sibling `AplicacaoError::MembroVersaoInvalid
4414 /// { caixa, versao, reason }` three-slot axis on the peer
4415 /// `AplicacaoError` envelope. `reason` accepts both `&str` literals
4416 /// and `format!(…)` outputs through the `impl Into<String>` bound.
4417 #[must_use]
4418 pub fn child_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
4419 Self::ChildVersaoInvalid {
4420 caixa: caixa.to_string(),
4421 versao: versao.to_string(),
4422 reason: reason.into(),
4423 }
4424 }
4425}
4426
4427// Fold the four `SupervisorError::<Variant> { <field>: <Copy> }` one-field
4428// Copy-scalar struct-variant wire-up sites at [`SupervisorSpec::validate`]'s
4429// three bracket-arms — one struct-literal at the `:children`-empty
4430// non-`SimpleOneForOne` refusal cascade (`NoChildren { estrategia }`) plus
4431// three `impl FnOnce(<ty>) -> SupervisorError` bracket-closures at the
4432// [`crate::render::require_positive_bounded_u32`] `:max-restarts` cap arm
4433// (`MaxRestartsExceedsCap { max_restarts }`) and the paired
4434// [`crate::render::require_positive_canonical_bounded_duration`]
4435// `:restart-window` canonical-form + cap arms (`RestartWindowNotCanonical
4436// { window }`, `RestartWindowExceedsCap { window }`) — onto one substrate
4437// primitive per typed variant, matching the sibling
4438// [`crate::aplicacao::aplicacao_policy_scalar_ctors!`] macro (7ef425e, 8
4439// variants on the same `{ <field>: Duration | u32 }` shape) at that
4440// discipline on the peer `AplicacaoError` envelope's per-`:politicas`
4441// scalar axis. Every variant is a one-field `Copy`-pass-through struct-
4442// literal — `RestartStrategy | u32 | Duration` — so the fold routes each
4443// wire-up site through one dispatch per typed variant without a runtime-
4444// work delta.
4445//
4446// Each of the four wire-up sites opened the identical
4447// `SupervisorError::<Variant> { <field>: <val> }` struct-literal — the
4448// exact "same block re-inlined at every consumer" shape the PRIME
4449// DIRECTIVE names as a bug, on the same altitude the peer
4450// `aplicacao_policy_scalar_ctors!` fold closed on the sibling
4451// `AplicacaoError` envelope's per-`:politicas` per-axis cap / canonical-
4452// form arms. The four variants share one `{ <field>: <Copy> }` shape, so
4453// the fold routes each wire-up site through one dispatch per typed
4454// variant.
4455//
4456// The macro below generates one static constructor per variant of shape
4457// `const fn <ctor>(<field>: <ty>) -> SupervisorError`, so every wire-up
4458// site collapses onto one dispatch: `SupervisorError::<ctor>(<val>)`,
4459// byte-equal to the pre-lift struct-literal on the same `Copy`-`<ty>`
4460// fixture — as a direct call at the [`SupervisorSpec::validate`]
4461// `:children`-empty refusal, or as a bare function pointer in the
4462// `impl FnOnce(<ty>) -> SupervisorError` bracket-closure slot every
4463// [`crate::render::require_positive_bounded_u32`] /
4464// [`crate::render::require_positive_canonical_bounded_duration`] gate
4465// carries — rather than the pre-lift open-coded one-line closure over
4466// the same one-field struct-literal. `const fn` preserves the `Copy`-
4467// pass-through's zero-runtime-work property verbatim. Every constructor
4468// is `#[must_use]` so a caller who mistakenly discards the constructed
4469// error trips a compile warning at the wire-up site.
4470//
4471// Every future consumer that wants to construct one of these four
4472// variants outside `SupervisorSpec::validate` — a deferred
4473// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
4474// webhook re-checking one edited `:estrategia` / `:max-restarts` /
4475// `:restart-window` slot against the cap + canonical-form cascade, a
4476// future `feira validate --supervisor` per-caixa admission verb re-
4477// running the shape gates on demand, a per-Supervisor overlay resolver
4478// rejecting an author-supplied slot against a cluster-local snapshot —
4479// now reaches each variant through one call rather than re-inlining the
4480// per-shape struct-literal block in lockstep with the four in-crate
4481// wire-up sites.
4482macro_rules! supervisor_scalar_ctors {
4483 ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
4484 impl SupervisorError {
4485 $(
4486 #[doc = concat!(
4487 "Construct a [`SupervisorError::",
4488 stringify!($variant),
4489 "`] naming the offending per-`:supervisor` `",
4490 stringify!($field),
4491 "` scalar. Folds the uniform `Self::",
4492 stringify!($variant),
4493 " { ",
4494 stringify!($field),
4495 " }` one-field `Copy`-pass-through struct-literal onto ",
4496 "one substrate primitive so every per-axis wire-up on ",
4497 "this variant reads through one dispatch — as a direct ",
4498 "call (`SupervisorError::",
4499 stringify!($ctor),
4500 "(<val>)`, byte-equal to the pre-lift struct-literal on ",
4501 "the same `Copy`-`",
4502 stringify!($ty),
4503 "` fixture) or as a bare function pointer in the ",
4504 "`impl FnOnce(",
4505 stringify!($ty),
4506 ") -> SupervisorError` bracket-closure slot every ",
4507 "`crate::render::require_positive_bounded_*` / ",
4508 "`crate::render::require_positive_canonical_bounded_*` ",
4509 "gate carries — rather than the pre-lift open-coded ",
4510 "one-line closure over the same one-field struct-",
4511 "literal. `const fn` preserves the `Copy`-pass-through's ",
4512 "zero-runtime-work property verbatim."
4513 )]
4514 #[must_use]
4515 pub const fn $ctor($field: $ty) -> Self {
4516 Self::$variant { $field }
4517 }
4518 )*
4519 }
4520 };
4521}
4522
4523supervisor_scalar_ctors! {
4524 no_children => NoChildren { estrategia: RestartStrategy },
4525 max_restarts_exceeds_cap => MaxRestartsExceedsCap { max_restarts: u32 },
4526 restart_window_not_canonical => RestartWindowNotCanonical { window: Duration },
4527 restart_window_exceeds_cap => RestartWindowExceedsCap { window: Duration },
4528}
4529
4530/// Shared duration string codec for the typed slots that take a
4531/// duration (`restart_window`, `MeshPolicy::timeout`,
4532/// `CircuitBreaker::window`, …). Public so [`crate::aplicacao`] can
4533/// reuse it without duplicating the parser.
4534pub mod duration_codec {
4535 use super::Duration;
4536 use serde::{Deserializer, Serializer};
4537
4538 pub fn serialize<S: Serializer>(v: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
4539 // Route through the canonical [`crate::render::serialize_option_via_str`]
4540 // — the substrate-side single-owner primitive for the forward
4541 // arm of the typed-magnitude codec family. See its docstring
4542 // for the full sibling roster.
4543 crate::render::serialize_option_via_str(v, s, render)
4544 }
4545
4546 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
4547 // Route through the canonical [`crate::render::deserialize_option_via_str`]
4548 // — the substrate-side single-owner primitive for the reverse
4549 // arm of the typed-magnitude codec family. See its docstring
4550 // for the full sibling roster.
4551 crate::render::deserialize_option_via_str(d, parse)
4552 }
4553
4554 pub(crate) fn parse(s: &str) -> Result<Duration, String> {
4555 // Paired whitespace-rejection arm — same canonical-form
4556 // render-determinism discipline as the peer
4557 // `limits::parse_byte_size` / `limits::parse_duration` /
4558 // `limits::parse_millicores` /
4559 // `aplicacao::rate_limit_codec::parse` sites: the ASCII
4560 // byte-scan closes the WhatWG-conformant whitespace bytes
4561 // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
4562 // `char::is_whitespace` scan closes the strictly-complementary
4563 // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
4564 // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
4565 // codepoints) that `str::trim` at parse entry silently strips.
4566 // Either drift class would round-trip through `render` to a
4567 // *different* canonical form on next emit — breaking the
4568 // THEORY.md Part V render-determinism contract on three typed-
4569 // duration slots at once (`:supervisor :restart-window`,
4570 // `:politicas :timeout`, `:politicas :circuit-breaker :window`)
4571 // via the shared codec.
4572 //
4573 // Routed through the lifted [`crate::render::reject_whitespace`]
4574 // primitive — the substrate-side single-owner paired-arm gate
4575 // every typed-magnitude codec in caixa-core shares.
4576 crate::render::reject_whitespace::<String, _, _>(
4577 s,
4578 |b| {
4579 format!(
4580 "duration: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
4581 authoring form for the typed duration slots routed through this shared codec \
4582 (`:supervisor :restart-window`, `:politicas :timeout`, \
4583 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
4584 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no whitespace bytes \
4585 anywhere. A whitespace-carrying shape (`\" 30s\"`, `\"30s \"`, `\"30 s\"`, \
4586 `\"\\t30s\"`, `\"30s\\n\"`) round-trips through `render` to a *different* \
4587 canonical form (`\"30s\"`) on first serialize — breaking the THEORY.md \
4588 Part V render-determinism contract every typed slot carries. Strip every \
4589 whitespace byte (write `\"30s\"` verbatim)"
4590 )
4591 },
4592 |ch| {
4593 format!(
4594 "duration: value {s:?} contains non-ASCII Unicode whitespace character \
4595 {ch:?} (U+{cp:04X}) — the canonical authoring form for the typed \
4596 duration slots routed through this shared codec (`:supervisor \
4597 :restart-window`, `:politicas :timeout`, `:politicas :circuit-breaker \
4598 :window`) is `<integer><unit>` (e.g. `\"30s\"`, `\"500ms\"`, `\"2m\"`, \
4599 `\"1h\"`) with no whitespace characters anywhere (ASCII or Unicode). A \
4600 non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}30s\"`, \
4601 `\"30s\\u{{2028}}\"`, `\"30\\u{{2003}}s\"`) survives the ASCII byte-scan \
4602 but `str::trim` (which uses `char::is_whitespace` — the Unicode \
4603 `White_Space` property, strictly wider than the ASCII byte set) silently \
4604 strips it at parse entry, and the value round-trips through `render` to \
4605 a *different* canonical form (`\"30s\"`) on first serialize — breaking \
4606 the THEORY.md Part V render-determinism contract every typed slot \
4607 carries. Strip every non-ASCII whitespace character (write `\"30s\"` \
4608 verbatim with only ASCII bytes)",
4609 cp = ch as u32
4610 )
4611 },
4612 )?;
4613 let s = s.trim();
4614 // Routed through the lifted
4615 // [`crate::render::split_magnitude_and_alpha_unit`] primitive —
4616 // the single-owner split every ASCII-alphabetic-unit typed-
4617 // magnitude codec in caixa-core (`limits::parse_byte_size` /
4618 // `limits::parse_duration` / this shared duration codec) shares.
4619 // See its docstring for the full sibling roster on the same
4620 // primitive altitude.
4621 let (num_part, unit) = crate::render::split_magnitude_and_alpha_unit(s);
4622 let num_trim = num_part.trim();
4623 // The canonical authoring form for every typed slot routed
4624 // through this shared codec — `:supervisor :restart-window`,
4625 // `:politicas :timeout`, `:politicas :circuit-breaker :window`
4626 // — is `<integer><unit>`. Every magnitude [`render`] emits is a
4627 // non-negative integer with no decimal point and no leading
4628 // sign, so the parser's accepted set must match for
4629 // serialize/deserialize to round-trip without canonical-form
4630 // drift. Until this gate landed the parser accepted any
4631 // `f64`-shaped magnitude (`"1.5s"` → 1500ms, `"1.0s"` → 1s,
4632 // `"0.5m"` → 30s, `"+30s"` → 30s) and serde silently round-
4633 // tripped the value to a *different* canonical string on the
4634 // next emit (`"1.5s"` → 1500ms → `"1500ms"`, `"1.0s"` → 1s →
4635 // `"1s"`, `"0.5m"` → 30s → `"30s"`, `"+30s"` → 30s → `"30s"`)
4636 // — breaking the THEORY.md Part V render-determinism contract
4637 // on three typed slots at once. Same canonical-form discipline
4638 // `crate::limits::parse_duration` (818dd38, the immediate
4639 // predecessor on the peer `:limits :wall-clock` codec) applies;
4640 // this gate lifts the discipline onto the shared codec that
4641 // backs the remaining three typed-duration slots in caixa-core.
4642 //
4643 // Strict canonical form: every byte of the magnitude is an
4644 // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
4645 // inputs the gate distinguishes "non-canonical-but-numeric"
4646 // (parses as f64 or i64 — surfaced with a self-locating
4647 // diagnostic naming the canonical authoring form, the
4648 // round-trip drift each rejected shape would produce on first
4649 // serialize, and the canonical-form remediation) from
4650 // "garbage" (parses as neither — surfaced with the existing
4651 // narrower "bad duration magnitude" wording so its diagnostic
4652 // shape remains stable for the parser-shape footgun case).
4653 // The pre-existing `num < 0.0` arm is now unreachable — the
4654 // digit-only gate strictly precedes magnitude parsing, and a
4655 // leading `-` is not an ASCII digit, so `"-30s"` lands on the
4656 // non-canonical-but-numeric branch with the `-30` named
4657 // verbatim in the diagnostic rather than the prior
4658 // value-laundered "negative duration in \"-30s\"" wording.
4659 //
4660 // Routed through the lifted
4661 // [`crate::render::is_digit_only_magnitude`] predicate — the
4662 // same source of truth the four peer typed-magnitude codec
4663 // sites share.
4664 let digit_only = crate::render::is_digit_only_magnitude(num_trim);
4665 if !digit_only {
4666 let numeric = num_trim.parse::<f64>().is_ok() || num_trim.parse::<i64>().is_ok();
4667 if numeric {
4668 return Err(format!(
4669 "duration: magnitude {num_trim:?} is not a non-negative integer — the \
4670 canonical authoring form for the typed duration slots routed through \
4671 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
4672 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
4673 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no decimal point and \
4674 no leading `+` / `-` sign. A fractional / decimal-shaped magnitude \
4675 (`\"1.5s\"`, `\"1.0s\"`, `\"0.5m\"`, `\"+30s\"`, `\"-30s\"`) round-trips \
4676 through `render` to a *different* canonical form (`\"1500ms\"`, `\"1s\"`, \
4677 `\"30s\"`, `\"30s\"`, `\"30s\"`) on first serialize — breaking the \
4678 THEORY.md Part V render-determinism contract every typed slot carries. \
4679 Pick an integer magnitude in the unit that divides cleanly (write \
4680 `\"1500ms\"` instead of `\"1.5s\"`; `\"30s\"` instead of `\"0.5m\"`)"
4681 ));
4682 }
4683 return Err(format!("bad duration magnitude in {s:?}"));
4684 }
4685 // Leading-zero arm — peer with the `rate_limit_codec` leading-
4686 // zero arm (4f46830) on the same canonical-form render-
4687 // determinism axis. The digit-only gate accepts `"030s"`,
4688 // `"00s"`, `"01h"`, `"0500ms"` as `u64::from_str` parses them
4689 // losslessly (= 30, 0, 1, 500), but `render` emits the leading-
4690 // zero-stripped form (`"30s"`, `"0s"`, `"1h"`, `"500ms"`) — a
4691 // *different* canonical string on the next emit, breaking the
4692 // THEORY.md Part V render-determinism contract the same way
4693 // `"+30s"` did before the leading-`+` arm landed. The single-
4694 // byte magnitude `"0"` (or `"0s"` / `"0ms"`) round-trips
4695 // losslessly through `render` (`render(Duration::ZERO)` emits
4696 // `"0s"`) — the downstream semantic-zero gates (e.g.
4697 // `SupervisorError::ZeroRestartWindow` on
4698 // `:supervisor :restart-window`,
4699 // `AplicacaoError::PolicyTimeoutZero` /
4700 // `PolicyCircuitBreakerWindowZero` on the typed `:politicas`
4701 // duration slots) refuse zero-magnitude authoring at the typed-
4702 // validate layer above, so the single-byte `"0"` stays in the
4703 // accepted set at this codec layer and the diagnostic
4704 // partitioning between canonical-form drift (this arm) and
4705 // semantic-zero (the downstream gates) remains stable.
4706 // Peer with the future leading-zero arms on the two remaining
4707 // typed-magnitude codecs the trajectory acknowledges:
4708 // `limits::parse_duration` backing `:limits :wall-clock`,
4709 // `limits::parse_byte_size` backing `:limits :memory` — each
4710 // carries the same canonical-form-drift class today; this
4711 // gate lands the discipline on the shared duration codec
4712 // first because the `rate_limit_codec` predecessor on the
4713 // same canonical-form-drift axis is the closest peer on the
4714 // trajectory.
4715 //
4716 // Routed through the lifted
4717 // [`crate::render::is_leading_zero_padded_magnitude`]
4718 // predicate — the same source of truth the four peer
4719 // typed-magnitude codec sites share.
4720 if crate::render::is_leading_zero_padded_magnitude(num_trim) {
4721 return Err(format!(
4722 "duration: magnitude {num_trim:?} has a non-canonical leading zero — the \
4723 canonical authoring form for the typed duration slots routed through \
4724 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
4725 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
4726 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no leading-zero padding \
4727 on the magnitude. A leading-zero magnitude (`\"030s\"`, `\"00s\"`, \
4728 `\"01h\"`, `\"0500ms\"`) round-trips through `render` to a *different* \
4729 canonical form (`\"30s\"`, `\"0s\"`, `\"1h\"`, `\"500ms\"`) on first \
4730 serialize — breaking the THEORY.md Part V render-determinism contract \
4731 every typed slot carries. Strip the leading zeros (write \
4732 `\"30s\"` instead of `\"030s\"`)"
4733 ));
4734 }
4735 // The digit-only gate guarantees every byte is `[0-9]`, and
4736 // the leading-zero arm above guarantees the magnitude is
4737 // either the single byte `"0"` or starts with `[1-9]`, so
4738 // the only way `u64::from_str` can fail here is overflow (the
4739 // magnitude exceeds `u64::MAX`). Surface that with an
4740 // overflow-shaped wording so the diagnostic names the offending
4741 // magnitude verbatim rather than collapsing onto the
4742 // non-canonical arm. The codec now operates on `u64` end-to-end
4743 // — every accepted magnitude is integer-exact; no f64 mantissa
4744 // drift between author-supplied magnitude and the consumer's
4745 // `Duration` value. Same shape `crate::limits::parse_duration`
4746 // (818dd38) carries on the peer `:limits :wall-clock` axis.
4747 let num: u64 = num_trim.parse::<u64>().map_err(|_| {
4748 format!("bad duration magnitude in {s:?} (digit-only magnitude overflows u64)")
4749 })?;
4750 // Route the `{"ms" | "s" | "" | "m" | "h"} → Duration`
4751 // unit-arm dispatch through the canonical
4752 // [`crate::render::duration_from_integer_magnitude_and_unit`]
4753 // primitive — the substrate-side single-owner unit-dispatch
4754 // table every typed-duration codec in caixa-core routes
4755 // through (peer: `crate::limits::parse_duration` backing
4756 // `:limits :wall-clock`). Every unit conversion is integer-
4757 // exact for an integer magnitude; overflow surfaces via the
4758 // typed `DurationUnitError::Overflow { multiplier }`
4759 // discriminant so this arm reconstructs the pre-lift
4760 // `"duration <num><unit> overflows u64 (magnitude × 60 …)"`
4761 // wording verbatim from `num` / `unit_trim` / the returned
4762 // `multiplier`, and the unknown-unit arm reconstructs the
4763 // pre-lift `"unknown duration unit \"<other>\""` wording from
4764 // the caller-scoped `unit_trim`. Load-bearing pinned by
4765 // `crate::render::tests::duration_from_integer_magnitude_and_unit_matches_pre_lift_unit_dispatch_table`.
4766 let unit_trim = unit.trim();
4767 let dur = crate::render::duration_from_integer_magnitude_and_unit(num, unit_trim).map_err(
4768 |e| match e {
4769 crate::render::DurationUnitError::Overflow { multiplier } => format!(
4770 "duration {num}{unit_trim} overflows u64 (magnitude × {multiplier} > 2^64-1)"
4771 ),
4772 crate::render::DurationUnitError::UnknownUnit => {
4773 format!("unknown duration unit {unit_trim:?}")
4774 }
4775 },
4776 )?;
4777 Ok(dur)
4778 }
4779
4780 /// Render a [`Duration`] in the canonical pleme-io duration string
4781 /// form (`"30s"`, `"1m"`, `"1h"`, `"500ms"`). The same form every
4782 /// caixa typed-duration slot serializes to and the same form K8s
4783 /// Gateway API HTTPRoute `timeouts` / `backendRequest` and Cilium
4784 /// EnvoyConfig per-route timeouts both expect (an integer
4785 /// followed by `s`/`m`/`h`/`ms`, no fractional values, no leading
4786 /// `+`). Lifted to `pub` so caixa-side renderers
4787 /// (`caixa-mesh::gateway_routes`'s :politicas :timeout overlay,
4788 /// the future per-:politicas `CiliumClusterwideEnvoyConfig`
4789 /// emitter, the future caixa-otel collector pipeline emitter) can
4790 /// consume the same canonical formatter without re-inlining the
4791 /// magnitude/unit decision tree (and inheriting the same drift
4792 /// footguns: a subtly different `300ms` vs `0.3s` rendering breaks
4793 /// downstream apply-time parsing in non-obvious ways).
4794 pub fn render(d: Duration) -> String {
4795 let total_ms = d.as_millis();
4796 if total_ms == 0 {
4797 return "0s".into();
4798 }
4799 if total_ms.is_multiple_of(3600 * 1000) {
4800 return format!("{}h", total_ms / (3600 * 1000));
4801 }
4802 if total_ms.is_multiple_of(60 * 1000) {
4803 return format!("{}m", total_ms / (60 * 1000));
4804 }
4805 if total_ms.is_multiple_of(1000) {
4806 return format!("{}s", total_ms / 1000);
4807 }
4808 format!("{total_ms}ms")
4809 }
4810
4811 /// True iff `d` round-trips losslessly through [`render`] + [`parse`].
4812 ///
4813 /// [`render`] truncates a `Duration` to `as_millis()` before picking the
4814 /// largest divisor unit, so any sub-millisecond residue
4815 /// (`d.subsec_nanos() % 1_000_000 != 0`) silently breaks the THEORY.md
4816 /// §V.2.7 render-determinism contract:
4817 ///
4818 /// - `Duration::from_micros(1500)` (= `1_500_000` ns) → `as_millis() == 1`
4819 /// → renders `"1ms"` → parses back to `Duration::from_millis(1)` =
4820 /// `1_000_000` ns ≠ original `1_500_000` ns;
4821 /// - `Duration::from_nanos(1)` (= 1 ns) → `as_millis() == 0` →
4822 /// renders the literal `"0s"`, which the per-axis zero-floor gate
4823 /// on every typed-`Duration` slot then rejects on re-validate.
4824 ///
4825 /// Lifted to a `pub` predicate next to the [`render`] / [`parse`] pair so
4826 /// the codec's round-trippable accepted set lives in exactly one place —
4827 /// every typed-`Duration` slot that routes through this shared codec
4828 /// (`SupervisorSpec::restart_window` via [`super::duration_codec`],
4829 /// [`crate::MeshPolicy::timeout`] / [`crate::CircuitBreaker::window`] via
4830 /// `supervisor::duration_codec` + [`super::duration_codec_required`]) and
4831 /// every typed-`Duration` slot whose own codec shares the same
4832 /// `as_millis()`-truncation shape ([`crate::LimitsSpec::wall_clock`] via
4833 /// [`crate::limits`]'s in-module `parse_duration` / `render_duration`
4834 /// pair) calls this predicate from its `validate()` to bracket the
4835 /// accepted set against the codec's accepted set, structurally. Drift
4836 /// between the codec's granularity and any typed slot's accepted set is
4837 /// then a single-source-of-truth edit at this predicate rather than a
4838 /// silent round-trip break the next consumer discovers at apply time.
4839 ///
4840 /// Peer of [`crate::aplicacao::POLICY_RETRIES_MAX`] /
4841 /// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] and the
4842 /// `is_dns_1123_label` / `is_canonical_rate_limit_window` predicate
4843 /// family — same "typed-slot's valid set matches its codec's accepted
4844 /// set, structurally" discipline carried at the codec layer.
4845 #[must_use]
4846 pub fn is_integer_millisecond_duration(d: Duration) -> bool {
4847 d.subsec_nanos().is_multiple_of(1_000_000)
4848 }
4849}
4850
4851/// Required-Duration variant for fields that aren't Option<Duration>.
4852pub mod duration_codec_required {
4853 use super::Duration;
4854 use serde::{Deserialize, Deserializer, Serializer};
4855
4856 pub fn serialize<S: Serializer>(v: &Duration, s: S) -> Result<S::Ok, S::Error> {
4857 s.serialize_str(&super::duration_codec::render(*v))
4858 }
4859
4860 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
4861 let s = String::deserialize(d)?;
4862 super::duration_codec::parse(&s).map_err(serde::de::Error::custom)
4863 }
4864}
4865
4866#[cfg(test)]
4867mod tests {
4868 use super::*;
4869
4870 fn child(name: &str, ver: &str, restart: RestartPolicy) -> ChildSpec {
4871 ChildSpec {
4872 caixa: name.into(),
4873 versao: ver.into(),
4874 restart,
4875 }
4876 }
4877
4878 #[test]
4879 fn child_spec_string_scalar_accessor_pair_is_const_fn() {
4880 // Fail-before-pass-after pin on [`ChildSpec::nome`] +
4881 // [`ChildSpec::versao_requirement`]'s `const`-eval-surface
4882 // posture. Each accessor projects the per-`:children :caixa`
4883 // / per-`:children :versao` [`String`] storage through the
4884 // `pub const fn` [`String::as_str`] (const-stable since Rust
4885 // 1.87, well within the workspace MSRV) — any future
4886 // accidental downgrade to non-`const` fails the corresponding
4887 // `<name>_via_const_fn` wrapper at caixa-core build time with
4888 // E0015 (`cannot call non-const method`), strictly stronger
4889 // than a runtime `assert!`. Sibling of the peer
4890 // per-M2/M3/universal-axis `String → &str` scalar-accessor
4891 // family pins on the sibling `const`-eval-surface passes
4892 // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
4893 // top-level manifest, [`crate::CaixaVersion::as_str`] at the
4894 // typed-newtype wrapper, [`crate::aplicacao::Membro::nome`] /
4895 // [`crate::aplicacao::Membro::versao_requirement`] at the M3
4896 // membership axis, [`crate::aplicacao::Entrada::hostname`] /
4897 // [`crate::aplicacao::Entrada::destination`] at the M3
4898 // ingress axis,
4899 // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
4900 // M2 upgrade axis, [`crate::dep::Dep::nome`] /
4901 // [`crate::dep::Dep::versao_requirement`] at the dep-graph
4902 // axis, and the per-`:contratos`
4903 // [`crate::aplicacao::WitContract::source`] /
4904 // [`crate::aplicacao::WitContract::destination`] /
4905 // [`crate::aplicacao::WitContract::world_ref`] trio the
4906 // sibling pin at 279823b already anchors).
4907 const fn nome_via_const_fn(c: &ChildSpec) -> &str {
4908 c.nome()
4909 }
4910 const fn versao_via_const_fn(c: &ChildSpec) -> &str {
4911 c.versao_requirement()
4912 }
4913 for (caixa, versao) in [
4914 ("worker-a", "^0.1"),
4915 ("worker-b", "~0.2.3"),
4916 ("collector", "*"),
4917 ] {
4918 let c = child(caixa, versao, RestartPolicy::Permanent);
4919 assert_eq!(nome_via_const_fn(&c), c.nome());
4920 assert_eq!(versao_via_const_fn(&c), c.versao_requirement());
4921 assert_eq!(c.nome(), caixa);
4922 assert_eq!(c.versao_requirement(), versao);
4923 }
4924 }
4925
4926 #[test]
4927 fn supervisor_children_slice_return_accessor_is_const_fn() {
4928 // Fail-before-pass-after pin on [`SupervisorSpec::children`]'s
4929 // `const`-eval-surface posture. The accessor destructures the
4930 // per-`:children` `Vec<ChildSpec>` storage through the
4931 // `pub const fn` [`Vec::as_slice`] (const-stable since Rust
4932 // 1.66, well within the workspace MSRV) — any future
4933 // accidental downgrade to non-`const` fails
4934 // `children_via_const_fn` at caixa-core build time with E0015
4935 // (`cannot call non-const method`), strictly stronger than a
4936 // runtime `assert!`. Sibling of the peer per-M3-mesh-slot
4937 // `Vec → &[T]` slice-return accessor family pin
4938 // [`crate::aplicacao::tests::m3_reference_return_accessor_family_is_const_fn`]
4939 // on the M3 mesh-slot per-`:clusters` / per-`:paths` /
4940 // per-`:membros` / per-`:contratos` slice-return axes, and of
4941 // the peer M2 upgrade-appup axis pin
4942 // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
4943 // on the per-`:upgrade-from :instructions` slice-return axis.
4944 const fn children_via_const_fn(s: &SupervisorSpec) -> &[ChildSpec] {
4945 s.children()
4946 }
4947 // Sweep both the empty-children (leaf-supervisor with no
4948 // static children — the `SimpleOneForOne` dynamic-child
4949 // arm's canonical shape) and the populated-children
4950 // (`OneForOne` / `OneForAll` / `RestForOne` static-child
4951 // arm's canonical shape) axes so the accessor carries a
4952 // const-dispatch pin on both arms.
4953 let s_empty = SupervisorSpec {
4954 estrategia: RestartStrategy::SimpleOneForOne,
4955 max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
4956 restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4957 children: vec![],
4958 };
4959 assert!(children_via_const_fn(&s_empty).is_empty());
4960 assert_eq!(children_via_const_fn(&s_empty), s_empty.children());
4961 let s_full = SupervisorSpec {
4962 estrategia: RestartStrategy::OneForOne,
4963 max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
4964 restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4965 children: vec![
4966 child("worker-a", "^0.1", RestartPolicy::Permanent),
4967 child("worker-b", "~0.2.3", RestartPolicy::Transient),
4968 child("collector", "*", RestartPolicy::Temporary),
4969 ],
4970 };
4971 assert_eq!(children_via_const_fn(&s_full).len(), 3);
4972 assert_eq!(children_via_const_fn(&s_full), s_full.children());
4973 }
4974
4975 #[test]
4976 fn default_has_one_for_one_and_5_restarts_in_60s() {
4977 let s = SupervisorSpec::default();
4978 assert_eq!(s.estrategia, RestartStrategy::OneForOne);
4979 assert_eq!(s.max_restarts, 5);
4980 assert_eq!(s.restart_window, Some(Duration::from_secs(60)));
4981 assert!(s.children.is_empty());
4982 }
4983
4984 #[test]
4985 fn validate_one_for_one_requires_children() {
4986 let mut s = SupervisorSpec::default();
4987 s.children = vec![];
4988 assert!(matches!(
4989 s.validate().unwrap_err(),
4990 SupervisorError::NoChildren { .. }
4991 ));
4992 s.children = vec![child("worker", "^0.1", RestartPolicy::Permanent)];
4993 s.validate().unwrap();
4994 }
4995
4996 #[test]
4997 fn validate_simple_one_for_one_forbids_static_children() {
4998 let mut s = SupervisorSpec {
4999 estrategia: RestartStrategy::SimpleOneForOne,
5000 ..SupervisorSpec::default()
5001 };
5002 s.children
5003 .push(child("w", "^0.1", RestartPolicy::Permanent));
5004 assert_eq!(
5005 s.validate().unwrap_err(),
5006 SupervisorError::SimpleOneForOneWithStaticChildren
5007 );
5008 s.children.clear();
5009 s.validate().unwrap();
5010 }
5011
5012 #[test]
5013 fn validate_rejects_zero_max_restarts() {
5014 let s = SupervisorSpec {
5015 max_restarts: 0,
5016 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5017 ..SupervisorSpec::default()
5018 };
5019 assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
5020 }
5021
5022 // ── upper-cap: SUPERVISOR_MAX_RESTARTS_MAX brackets the typed slot ─────
5023 //
5024 // The cap arm lifts the `:politicas :circuit-breaker :max-failures` /
5025 // `POLICY_BREAKER_MAX_FAILURES_MAX` (2b51ace) discipline onto the peer
5026 // `:supervisor :max-restarts` axis — both fields are "trip the
5027 // next-higher protection layer after N events in a rolling window"
5028 // counters with identical degenerate-at-the-high-end shape, so the
5029 // typed-slot's accepted set lies in `1..=1000` on the supervisor side
5030 // exactly as it lies in `1..=1000` on the breaker side.
5031
5032 #[test]
5033 fn validate_rejects_max_restarts_above_cap() {
5034 // The fail-before-pass-after pin: `SUPERVISOR_MAX_RESTARTS_MAX +
5035 // 1` is structurally one past the cap and silently passed
5036 // validate on every pre-gate codebase because the typed slot's
5037 // only check was the zero-floor arm. The no-op-supervisor vector
5038 // only surfaced at the runtime substrate (Erlang/OTP
5039 // MaxIntensity/Period ratio, the future wasm-operator's
5040 // per-supervisor restart-intensity counter) far from the source
5041 // caixa.lisp with no field naming the offending supervisor.
5042 let s = SupervisorSpec {
5043 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5044 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5045 ..SupervisorSpec::default()
5046 };
5047 assert_eq!(
5048 s.validate().unwrap_err(),
5049 SupervisorError::MaxRestartsExceedsCap {
5050 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5051 }
5052 );
5053 }
5054
5055 #[test]
5056 fn validate_rejects_max_restarts_far_above_cap() {
5057 // The `u32::MAX` worst case — the four-billion-restart
5058 // threshold a typo (`:max-restarts 4294967295`) or a
5059 // struct-literal copy-paste lands in the slot. Pin the cap
5060 // arm's coverage explicitly across the full `u32` overflow so
5061 // a future relaxation that drops the upper bound surfaces
5062 // here. Same shape every other typed-cap arm on this surface
5063 // carries (POLICY_BREAKER_MAX_FAILURES_MAX,
5064 // POLICY_RETRIES_MAX, POLICY_RATE_LIMIT_MAX).
5065 let s = SupervisorSpec {
5066 max_restarts: u32::MAX,
5067 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5068 ..SupervisorSpec::default()
5069 };
5070 assert_eq!(
5071 s.validate().unwrap_err(),
5072 SupervisorError::MaxRestartsExceedsCap {
5073 max_restarts: u32::MAX,
5074 }
5075 );
5076 }
5077
5078 #[test]
5079 fn validate_accepts_max_restarts_at_cap() {
5080 // The boundary value — exactly SUPERVISOR_MAX_RESTARTS_MAX —
5081 // must validate. The cap is inclusive on the top edge,
5082 // matching the POLICY_BREAKER_MAX_FAILURES_MAX /
5083 // POLICY_RETRIES_MAX / LIMITS_MEMORY_WASM32_MAX_BYTES
5084 // discipline on the sibling capped axes. Pin the boundary
5085 // explicitly so a future off-by-one tightening
5086 // (`>= SUPERVISOR_MAX_RESTARTS_MAX` instead of `>`) surfaces
5087 // here as a test failure rather than a silent contract
5088 // narrowing.
5089 let s = SupervisorSpec {
5090 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX,
5091 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5092 ..SupervisorSpec::default()
5093 };
5094 s.validate()
5095 .expect("max_restarts == SUPERVISOR_MAX_RESTARTS_MAX must validate");
5096 }
5097
5098 #[test]
5099 fn validate_accepts_max_restarts_typical_values() {
5100 // The documented production-playbook band positive-control
5101 // sweep — every value Erlang/OTP / Elixir / Riak Core /
5102 // RabbitMQ recommend (1..=100) must pass, plus a sweep
5103 // through the hyperscale band (200, 500, 1000) the cap
5104 // accepts. Pin the inclusive validated set explicitly so a
5105 // future tightening of the ceiling surfaces here.
5106 for n in [1u32, 3, 5, 10, 20, 50, 100, 200, 500, 1000] {
5107 let s = SupervisorSpec {
5108 max_restarts: n,
5109 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5110 ..SupervisorSpec::default()
5111 };
5112 s.validate()
5113 .unwrap_or_else(|e| panic!("max_restarts={n} must validate; got {e:?}"));
5114 }
5115 }
5116
5117 #[test]
5118 fn zero_max_restarts_takes_precedence_over_cap() {
5119 // The cross-arm ordering pin: `0` is structurally outside
5120 // both `1..` (zero-floor) and `..=SUPERVISOR_MAX_RESTARTS_MAX`
5121 // (cap), but the zero-floor diagnostic is the more
5122 // self-locating one (it directly names the counter-axis
5123 // remediation), so the validate gate must fire on zero first.
5124 // Same shape every other zero-then-shape ordering on this
5125 // surface uses (PolicyRetriesZero then
5126 // PolicyRetriesExceedsCap; PolicyBreakerZeroFailures then
5127 // PolicyBreakerMaxFailuresExceedsCap).
5128 let s = SupervisorSpec {
5129 max_restarts: 0,
5130 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5131 ..SupervisorSpec::default()
5132 };
5133 assert_eq!(
5134 s.validate().unwrap_err(),
5135 SupervisorError::ZeroMaxRestarts,
5136 "max_restarts == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
5137 );
5138 }
5139
5140 #[test]
5141 fn max_restarts_cap_takes_precedence_over_restart_window_gates() {
5142 // The cross-arm ordering pin between the cap and the sibling
5143 // `:restart-window` gates (zero-window, canonical-window). A
5144 // supervisor carrying both an over-cap `max_restarts` AND a
5145 // structurally invalid window (zero, sub-ms) must surface the
5146 // cap diagnostic first — the cap arm is wired immediately
5147 // after the zero-restart arm and strictly before the window
5148 // arms, so the offending value the diagnostic names matches
5149 // the order the author would discover the gates by reading
5150 // top-to-bottom through `SupervisorSpec::validate`. Pin the
5151 // order so a future refactor that reorders the arms surfaces
5152 // here as a test failure rather than a silent diagnostic
5153 // regression. Peer of
5154 // `circuit_breaker_max_failures_cap_takes_precedence_over_window_gates`
5155 // on the sibling `:politicas :circuit-breaker` slot.
5156 let s = SupervisorSpec {
5157 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5158 restart_window: Some(Duration::ZERO),
5159 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5160 ..SupervisorSpec::default()
5161 };
5162 assert_eq!(
5163 s.validate().unwrap_err(),
5164 SupervisorError::MaxRestartsExceedsCap {
5165 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5166 },
5167 "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
5168 );
5169 }
5170
5171 #[test]
5172 fn max_restarts_cap_diagnostic_carries_offending_value() {
5173 // The diagnostic-shape pin: the offending `u32` is carried
5174 // verbatim into the `SupervisorError::MaxRestartsExceedsCap`
5175 // variant so the surfaced error message names the value the
5176 // author wrote (`":supervisor :max-restarts (50000) exceeds the
5177 // supervisor-policy ceiling …"`), not just the cap. Same
5178 // self-locating diagnostic shape every other typed-cap arm on
5179 // this surface carries
5180 // (`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` carries
5181 // the offending failure count verbatim,
5182 // `AplicacaoError::PolicyRetriesExceedsCap` carries the offending
5183 // retries count verbatim).
5184 let s = SupervisorSpec {
5185 max_restarts: 50_000,
5186 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5187 ..SupervisorSpec::default()
5188 };
5189 let err = s.validate().unwrap_err();
5190 assert!(
5191 matches!(
5192 err,
5193 SupervisorError::MaxRestartsExceedsCap {
5194 max_restarts: 50_000
5195 }
5196 ),
5197 "got {err:?}"
5198 );
5199 let msg = err.to_string();
5200 assert!(
5201 msg.contains("50000"),
5202 ":supervisor :max-restarts cap diagnostic must carry the offending value verbatim (got: {msg})"
5203 );
5204 }
5205
5206 #[test]
5207 fn supervisor_max_restarts_default_pins_otp_canonical_value() {
5208 // Pin [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] at `5` — the
5209 // Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
5210 // half of Learn You Some Erlang's worker-supervisor default,
5211 // sibling of the `60s` `Period` half that the paired
5212 // [`Default for SupervisorSpec`] impl already pins on the
5213 // sibling `restart_window` axis. Pinning the literal here
5214 // surfaces a future rebrand (a tightening to Elixir's `3`,
5215 // a widening to a per-cluster overlay the operator pins
5216 // through a future `:max-restarts-overrides` slot) as a
5217 // deliberate test edit, not a silent contract migration.
5218 // Peer of the sibling
5219 // [`supervisor_max_restarts_cap_pins_canonical_value`]
5220 // upper-bracket pin on the same axis.
5221 assert_eq!(SUPERVISOR_MAX_RESTARTS_DEFAULT, 5);
5222 }
5223
5224 #[test]
5225 fn default_max_restarts_helper_routes_through_lifted_default() {
5226 // Composition pin: the private `default_max_restarts()`
5227 // serde-`#[serde(default = "…")]` helper on
5228 // [`SupervisorSpec::max_restarts`] must route through the
5229 // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
5230 // typed `pub const` rather than a raw `5` literal. Prior to
5231 // the lift the helper carried an inline `5` with no compile-
5232 // time link back to the shared default, so the wire-format
5233 // author-omitted arm and the caixa-core
5234 // [`crate::manifest::Caixa::supervisor_view`] fold's `unwrap_or(5)`
5235 // arm could silently split on any future default rebrand.
5236 // Byte-parity against the lifted constant closes the split.
5237 assert_eq!(default_max_restarts(), SUPERVISOR_MAX_RESTARTS_DEFAULT);
5238 }
5239
5240 #[test]
5241 fn supervisor_spec_default_max_restarts_routes_through_lifted_default() {
5242 // Composition pin: the [`Default for SupervisorSpec`] impl's
5243 // struct-literal `max_restarts` field must route through the
5244 // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
5245 // typed `pub const` (via the private helper this test's
5246 // sibling `default_max_restarts_helper_routes_through_lifted_default`
5247 // already pins onto the constant). Structurally: every
5248 // `SupervisorSpec::default()` call must yield a
5249 // `max_restarts` field byte-equal to the lifted constant
5250 // (the two paired defaults — the serde-side wire-format arm
5251 // and the struct-literal default arm — cannot silently split
5252 // on any future default rebrand). Peer of the sibling
5253 // `default_has_one_for_one_and_5_restarts_in_60s` shape pin
5254 // — this pin closes the byte-parity arm on the two paired
5255 // altitude entry points onto the shared substrate constant.
5256 assert_eq!(
5257 SupervisorSpec::default().max_restarts(),
5258 SUPERVISOR_MAX_RESTARTS_DEFAULT,
5259 );
5260 }
5261
5262 #[test]
5263 fn supervisor_restart_window_default_pins_otp_canonical_value() {
5264 // Pin [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] at `60s` — the
5265 // Erlang/OTP-canonical `{intensity, 5, 60}` `Period` half of
5266 // Learn You Some Erlang's worker-supervisor default, paired
5267 // with the sibling `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5`
5268 // `MaxIntensity` half this constant is the sliding-window
5269 // denominator of on the same `MaxIntensity / Period`
5270 // restart-intensity ratio. Pinning the literal here surfaces a
5271 // future coherent rebrand of the paired default (Elixir's
5272 // `{max_restarts: 3, max_seconds: 5}`, a per-cluster overlay
5273 // the operator pins through a future
5274 // `:restart-window-overrides` slot) as a deliberate test edit,
5275 // not a silent contract migration. Peer of the sibling
5276 // [`supervisor_max_restarts_default_pins_otp_canonical_value`]
5277 // paired-half pin on the same OTP-canonical default and the
5278 // [`supervisor_restart_window_cap_pins_canonical_value`]
5279 // upper-bracket pin on the same axis.
5280 assert_eq!(SUPERVISOR_RESTART_WINDOW_DEFAULT, Duration::from_secs(60),);
5281 }
5282
5283 #[test]
5284 fn supervisor_spec_default_restart_window_routes_through_lifted_default() {
5285 // Composition pin: the [`Default for SupervisorSpec`] impl's
5286 // struct-literal `restart_window` field must route through the
5287 // substrate-canonical [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
5288 // typed `pub const` rather than a raw
5289 // `Duration::from_secs(60)` literal. Prior to this lift the
5290 // paired `{intensity, 5, 60}` OTP-canonical default was split
5291 // across two altitudes with no compile-time link between the
5292 // halves — the `MaxIntensity` half rode through the lifted
5293 // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant while the
5294 // `Period` half rode as an open-coded literal at the
5295 // composition site, so a future coherent rebrand of the paired
5296 // canonical would have had to migrate one half through the
5297 // constant and the other through a raw literal in lockstep.
5298 // Byte-parity against the lifted constant on the `Period` half
5299 // closes the split — the paired OTP-canonical default now
5300 // migrates as one unit on any future axis change. Peer of the
5301 // sibling
5302 // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
5303 // byte-parity pin on the paired `MaxIntensity` half.
5304 assert_eq!(
5305 SupervisorSpec::default().restart_window(),
5306 Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
5307 );
5308 }
5309
5310 #[test]
5311 fn supervisor_estrategia_default_pins_otp_canonical_value() {
5312 // Pin [`SUPERVISOR_ESTRATEGIA_DEFAULT`] at [`RestartStrategy::OneForOne`]
5313 // — the Erlang/OTP-canonical `one_for_one` half of Learn You Some
5314 // Erlang's `{one_for_one, intensity, 5, 60}` worker-supervisor
5315 // canonical default, paired with the sibling
5316 // `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5` `MaxIntensity` half and the
5317 // sibling `SUPERVISOR_RESTART_WINDOW_DEFAULT` `60s` `Period` half
5318 // this constant is the strategy discriminator of on the same
5319 // OTP-canonical worker-supervisor default. Pinning the arm here
5320 // surfaces a future coherent rebrand of the paired triple (Elixir's
5321 // `{:one_for_one, max_restarts: 3, max_seconds: 5}` on the sibling
5322 // intensity/period axes leaving this strategy arm untouched, an OTP
5323 // `rest_for_one` widening once the substrate discovers startup-
5324 // order-coupled child cohorts as the more common worker-supervisor
5325 // shape, a per-cluster overlay the operator pins through a future
5326 // `:estrategia-overrides` slot the MESH-COMPOSITION §III.2
5327 // supervision-canary roadmap acknowledges) as a deliberate test
5328 // edit, not a silent contract migration. Peer of the sibling
5329 // [`supervisor_max_restarts_default_pins_otp_canonical_value`] +
5330 // [`supervisor_restart_window_default_pins_otp_canonical_value`]
5331 // paired-half pins on the same OTP-canonical default.
5332 assert_eq!(SUPERVISOR_ESTRATEGIA_DEFAULT, RestartStrategy::OneForOne);
5333 }
5334
5335 #[test]
5336 fn restart_strategy_default_routes_through_lifted_default() {
5337 // Composition pin: the [`Default for RestartStrategy`] impl's
5338 // return arm must route through the substrate-canonical
5339 // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
5340 // a raw `Self::OneForOne` arm. Prior to the lift the impl carried
5341 // an inline `Self::OneForOne` with no compile-time link back to
5342 // the shared OTP-canonical `one_for_one` strategy the paired
5343 // [`Default for SupervisorSpec`] impl's struct-literal `estrategia`
5344 // field and the [`crate::manifest::Caixa::supervisor_view`] fold's
5345 // `.unwrap_or_default()` (now
5346 // `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)`) arm both key off —
5347 // so a future rebrand of the OTP-canonical strategy default (an
5348 // OTP `rest_for_one` widening once the substrate discovers
5349 // startup-order-coupled child cohorts as the more common worker-
5350 // supervisor shape, a per-cluster overlay the operator pins
5351 // through a future `:estrategia-overrides` slot) would have had to
5352 // be threaded through the `Default` impl and the two peer routes
5353 // in lockstep or the three consumers would silently split. Byte-
5354 // parity against the lifted constant closes the split. Peer of
5355 // the sibling
5356 // [`default_max_restarts_helper_routes_through_lifted_default`] +
5357 // [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
5358 // composition pins on the paired `MaxIntensity` + `Period` halves.
5359 assert_eq!(RestartStrategy::default(), SUPERVISOR_ESTRATEGIA_DEFAULT,);
5360 }
5361
5362 #[test]
5363 fn supervisor_spec_default_estrategia_routes_through_lifted_default() {
5364 // Composition pin: the [`Default for SupervisorSpec`] impl's
5365 // struct-literal `estrategia` field must route through the
5366 // substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed
5367 // `pub const` (either directly, or via the
5368 // [`RestartStrategy::default`] impl that the sibling
5369 // `restart_strategy_default_routes_through_lifted_default` pin
5370 // already routes onto the constant). Structurally: every
5371 // `SupervisorSpec::default()` call must yield an `estrategia`
5372 // field byte-equal to the lifted constant (the three paired
5373 // defaults — the [`Default for RestartStrategy`] impl arm, the
5374 // struct-literal default arm here, and the
5375 // [`crate::manifest::Caixa::supervisor_view`] fold arm — cannot
5376 // silently split on any future default rebrand). Peer of the
5377 // sibling
5378 // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
5379 // + [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
5380 // byte-parity pins on the paired `MaxIntensity` + `Period` halves
5381 // of the same `SupervisorSpec::default()` composed altitude.
5382 assert_eq!(
5383 SupervisorSpec::default().estrategia(),
5384 SUPERVISOR_ESTRATEGIA_DEFAULT,
5385 );
5386 }
5387
5388 #[test]
5389 fn supervisor_spec_default_routes_through_otp_canonical_ctor() {
5390 // Composition pin: the [`Default for SupervisorSpec`] impl must
5391 // route through the substrate-canonical
5392 // [`SupervisorSpec::otp_canonical`] `pub const fn` constructor
5393 // rather than a re-hand-authored struct-literal cascade. Sharpens
5394 // the sibling per-arm
5395 // `supervisor_spec_default_*_routes_through_lifted_default` pins
5396 // from a per-field lift into a whole-struct one-source-of-truth
5397 // pin — the derived-until-now [`Default::default`] and the
5398 // [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
5399 // construction, not by coincidence.
5400 //
5401 // A future extension of the OTP-canonical baseline (a fifth
5402 // `restart_intensity` field the Erlang/OTP `#supervisor` record
5403 // grows, a per-child-cohort split of the `restart_window` /
5404 // `max_restarts` pair, an M4 `mesh.pleme.io/v1alpha1/Supervisor`
5405 // CR materializer's admission-time overlay pass) reaches both
5406 // paths through exactly one edit on
5407 // [`SupervisorSpec::otp_canonical`] — the derived path could
5408 // silently disagree with the constructor's shape on any new
5409 // field whose [`Default::default`] resolves to a different arm
5410 // than the OTP-canonical baseline the constructor names, while
5411 // this delegated impl reaches the constructor directly and
5412 // picks up every future extension by construction.
5413 //
5414 // Fourth peer on the M2 / M3 typed-slot-spec
5415 // [`Default`]-through-const-ctor fold family — sibling of the
5416 // [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
5417 // (abd52c2), [`crate::aplicacao::MeshPolicy`]
5418 // [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`]
5419 // (91641a4), and [`crate::BehaviorSpec`]
5420 // [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c)
5421 // per-`Option`-only-typed-slot folds — extended here onto the
5422 // M2 supervisor-slot [`SupervisorSpec`] whose canonical baseline
5423 // is not "everything `None`" but the Erlang/OTP-canonical
5424 // `{one_for_one, 5, 60}` worker-supervisor triple.
5425 assert_eq!(SupervisorSpec::default(), SupervisorSpec::otp_canonical());
5426 }
5427
5428 #[test]
5429 fn supervisor_spec_otp_canonical_byte_equals_default() {
5430 // Value pin: [`SupervisorSpec::otp_canonical`] must byte-equal
5431 // the hand-authored `{one_for_one, 5, 60, []}` OTP-canonical
5432 // baseline the sibling `default_has_one_for_one_and_5_restarts_in_60s`
5433 // pin already asserts against the [`Default::default`] path.
5434 // Sharpens the pair-invariant into a per-constructor pin so a
5435 // future extension of [`SupervisorSpec`] with a fifth field
5436 // whose OTP-canonical shape is non-`Default::default`-equivalent
5437 // trips at caixa-core test time rather than at a downstream
5438 // consumer that composed [`SupervisorSpec::otp_canonical`] with
5439 // [`SupervisorSpec::validate`] as its "canonical baseline
5440 // seed".
5441 let canonical = SupervisorSpec::otp_canonical();
5442 assert_eq!(canonical.estrategia, RestartStrategy::OneForOne);
5443 assert_eq!(canonical.max_restarts, 5);
5444 assert_eq!(canonical.restart_window, Some(Duration::from_secs(60)));
5445 assert!(canonical.children.is_empty());
5446 }
5447
5448 #[test]
5449 fn supervisor_spec_otp_canonical_is_usable_in_const_context() {
5450 // Const-context pin: [`SupervisorSpec::otp_canonical`] must
5451 // remain callable from a `const`-bound position so downstream
5452 // `const`-context callers wanting a canonical OTP-baseline seed
5453 // can construct one at compile time without runtime dispatch on
5454 // the derived [`Default::default`]. Peer of the sibling
5455 // `pub const fn` [`crate::LimitsSpec::empty`] /
5456 // [`crate::aplicacao::MeshPolicy::empty`] /
5457 // [`crate::BehaviorSpec::empty`] constructors on the sibling
5458 // typed-slot-spec `pub const fn` axis. If a future edit breaks
5459 // the `const`-eligibility of [`SupervisorSpec::otp_canonical`]
5460 // (a non-`const` field-default helper, a non-`const`-stable
5461 // container type promotion), this evaluation fails at
5462 // build time on this file rather than at a downstream
5463 // `const`-context call site.
5464 const CANONICAL: SupervisorSpec = SupervisorSpec::otp_canonical();
5465 assert_eq!(CANONICAL.estrategia, SUPERVISOR_ESTRATEGIA_DEFAULT);
5466 assert_eq!(CANONICAL.max_restarts, SUPERVISOR_MAX_RESTARTS_DEFAULT);
5467 assert_eq!(
5468 CANONICAL.restart_window,
5469 Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
5470 );
5471 assert!(CANONICAL.children.is_empty());
5472 }
5473
5474 #[test]
5475 fn supervisor_child_restart_default_pins_otp_canonical_value() {
5476 // Pin [`SUPERVISOR_CHILD_RESTART_DEFAULT`] at
5477 // [`RestartPolicy::Permanent`] — Erlang/OTP's `permanent`
5478 // worker-child restart type (`{ChildId, StartFunc, permanent, …}`
5479 // in a `supervisor`'s `init/1` child-spec tuple), the per-child
5480 // half of the same OTP-shape supervisor-tree default set whose
5481 // per-`:supervisor` halves the sibling
5482 // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
5483 // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] /
5484 // [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] constants pin. Pinning the
5485 // arm here surfaces a future rebrand of the per-child default (an
5486 // OTP-`transient` widening once the substrate discovers clean-
5487 // completion-aware children as the more common child shape, a
5488 // per-cluster overlay the operator pins through a future
5489 // `:restart-overrides` slot the MESH-COMPOSITION §III.2
5490 // supervision-canary roadmap acknowledges) as a deliberate test
5491 // edit, not a silent contract migration. Peer of the sibling
5492 // [`supervisor_estrategia_default_pins_otp_canonical_value`] /
5493 // [`supervisor_max_restarts_default_pins_otp_canonical_value`] /
5494 // [`supervisor_restart_window_default_pins_otp_canonical_value`]
5495 // value pins on the per-`:supervisor` halves.
5496 assert_eq!(SUPERVISOR_CHILD_RESTART_DEFAULT, RestartPolicy::Permanent);
5497 }
5498
5499 #[test]
5500 fn restart_policy_default_routes_through_lifted_default() {
5501 // Composition pin: the [`Default for RestartPolicy`] impl's return
5502 // arm must route through the substrate-canonical
5503 // [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const` rather
5504 // than a raw `Self::Permanent` arm. Prior to the lift the impl
5505 // carried an inline `Self::Permanent` with no compile-time link
5506 // back to the OTP-shape supervisor-tree default set whose three
5507 // per-`:supervisor` halves already rode through lifted constants
5508 // — so a future coherent rebrand of the set would have had to
5509 // migrate three halves through typed constants and this fourth
5510 // through a raw enum arm in lockstep or the supervisor-level and
5511 // child-level defaults would silently drift apart. Byte-parity
5512 // against the lifted constant closes the split. Peer of the
5513 // sibling
5514 // [`restart_strategy_default_routes_through_lifted_default`]
5515 // composition pin on the per-`:supervisor` `:estrategia` axis.
5516 assert_eq!(RestartPolicy::default(), SUPERVISOR_CHILD_RESTART_DEFAULT);
5517 }
5518
5519 #[test]
5520 fn child_spec_serde_default_restart_routes_through_lifted_default() {
5521 // Composition pin: the serde-side `#[serde(default)]` on
5522 // [`ChildSpec::restart`] — the wire-format author-omitted
5523 // `:children :restart` arm — must resolve onto the substrate-
5524 // canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const`
5525 // (via the [`Default for RestartPolicy`] impl the sibling
5526 // `restart_policy_default_routes_through_lifted_default` pin
5527 // already routes onto the constant). Structurally: a `ChildSpec`
5528 // deserialized from a payload that omits the `restart` key must
5529 // yield a `restart` field byte-equal to the lifted constant, so
5530 // the wire-format author-omitted arm and the
5531 // [`RestartPolicy::default`] impl arm cannot silently split on any
5532 // future default rebrand. Peer of the sibling
5533 // [`supervisor_spec_default_estrategia_routes_through_lifted_default`]
5534 // / [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
5535 // / [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
5536 // byte-parity pins on the per-`:supervisor` halves of the same
5537 // author-omitted-slot resolution surface.
5538 let omitted: ChildSpec = serde_json::from_str(r#"{"caixa":"worker","versao":"^0.1"}"#)
5539 .expect("ChildSpec must deserialize with the restart key omitted");
5540 assert_eq!(
5541 omitted.restart(),
5542 SUPERVISOR_CHILD_RESTART_DEFAULT,
5543 "an author-omitted :children :restart slot must degrade onto \
5544 the SUPERVISOR_CHILD_RESTART_DEFAULT typed pub const (got \
5545 {:?}, expected {:?})",
5546 omitted.restart(),
5547 SUPERVISOR_CHILD_RESTART_DEFAULT,
5548 );
5549 }
5550
5551 #[test]
5552 fn supervisor_max_restarts_cap_pins_canonical_value() {
5553 // The SUPERVISOR_MAX_RESTARTS_MAX constant pins the value at
5554 // 1000 — the same ceiling the peer
5555 // POLICY_BREAKER_MAX_FAILURES_MAX cap carries on the
5556 // `:politicas :circuit-breaker :max-failures` axis (both are
5557 // "trip the next-higher protection layer after N events in a
5558 // rolling window" counters with identical
5559 // degenerate-at-the-high-end shape; uniform top edge so the
5560 // M4 CR materializers and the wasm-operator reconciler reach
5561 // for either field knowing the value is in `1..=1000`). Two
5562 // orders of magnitude above every documented Erlang/OTP /
5563 // Elixir / Riak Core / RabbitMQ production-playbook
5564 // recommendation band and below the clearly-pathological
5565 // "effectively no escalation" floor (10_000, 100_000,
5566 // u32::MAX). Pinning the literal value here surfaces a future
5567 // drift (a relaxation to 10_000, a tightening to 100) as a
5568 // deliberate test edit, not a silent contract narrowing.
5569 assert_eq!(SUPERVISOR_MAX_RESTARTS_MAX, 1000);
5570 }
5571
5572 #[test]
5573 fn validate_rejects_empty_child_name() {
5574 let s = SupervisorSpec {
5575 children: vec![child("", "^0.1", RestartPolicy::Permanent)],
5576 ..SupervisorSpec::default()
5577 };
5578 assert_eq!(s.validate().unwrap_err(), SupervisorError::EmptyChildName);
5579 }
5580
5581 #[test]
5582 fn validate_rejects_empty_child_version() {
5583 let s = SupervisorSpec {
5584 children: vec![child("w", "", RestartPolicy::Permanent)],
5585 ..SupervisorSpec::default()
5586 };
5587 assert!(matches!(
5588 s.validate().unwrap_err(),
5589 SupervisorError::EmptyChildVersion { .. }
5590 ));
5591 }
5592
5593 // ── value-shape: parse-as-VersionReq on :children :versao ─────────────
5594
5595 #[test]
5596 fn validate_rejects_invalid_child_versao_requirement() {
5597 // The fail-before-pass-after pin: a non-empty but malformed
5598 // semver requirement (`"^bad-version"`) silently passed
5599 // `validate()` on every pre-gate codebase because the prior
5600 // shape only refused the empty string. The parse failure
5601 // surfaced far downstream at lacre-resolve time with a
5602 // `semver::Error` that didn't name which `:children` entry
5603 // carried the typo. The new gate moves the check to caixa-build
5604 // time at the source caixa.lisp — the third `:versao` typed
5605 // axis (`:children`) joins `:deps` and `:membros` (9888b13) at
5606 // structural parity.
5607 let s = SupervisorSpec {
5608 children: vec![
5609 child("worker", "^0.1", RestartPolicy::Permanent),
5610 child("cache", "^bad-version", RestartPolicy::Transient),
5611 ],
5612 ..SupervisorSpec::default()
5613 };
5614 let err = s.validate().unwrap_err();
5615 assert!(
5616 matches!(
5617 err,
5618 SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
5619 if caixa == "cache" && versao == "^bad-version"
5620 ),
5621 "got {err:?}"
5622 );
5623 }
5624
5625 #[test]
5626 fn validate_rejects_child_versao_with_double_caret_typo() {
5627 // `"^^0.1"` is the canonical doubled-caret typo — looks
5628 // Cargo-shaped on first glance but fails the parser because
5629 // semver doesn't accept stacked operators. Pin this
5630 // adjacent-shape footgun explicitly so a future relaxation that
5631 // accepts "looks-canonical-but-isn't" forms surfaces here.
5632 let s = SupervisorSpec {
5633 children: vec![child("worker", "^^0.1", RestartPolicy::Permanent)],
5634 ..SupervisorSpec::default()
5635 };
5636 let err = s.validate().unwrap_err();
5637 assert!(
5638 matches!(
5639 err,
5640 SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
5641 if caixa == "worker" && versao == "^^0.1"
5642 ),
5643 "got {err:?}"
5644 );
5645 }
5646
5647 #[test]
5648 fn validate_rejects_child_versao_with_v_prefixed_tag() {
5649 // `"v0.1"` is the canonical "git-tag-shape leaking into the
5650 // semver requirement slot" typo — an author copies the
5651 // publish-side git-tag string verbatim into `:versao`, but
5652 // Cargo's semver parser rejects the leading `v`. Same
5653 // adjacent-shape footgun pinned for `:membros :versao`
5654 // (9888b13).
5655 let s = SupervisorSpec {
5656 children: vec![child("worker", "v0.1", RestartPolicy::Permanent)],
5657 ..SupervisorSpec::default()
5658 };
5659 let err = s.validate().unwrap_err();
5660 assert!(
5661 matches!(
5662 err,
5663 SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
5664 if caixa == "worker" && versao == "v0.1"
5665 ),
5666 "got {err:?}"
5667 );
5668 }
5669
5670 #[test]
5671 fn validate_accepts_canonical_child_versao_forms() {
5672 // The Cargo-shaped requirement forms `:deps :versao` and
5673 // `:membros :versao` already accept via
5674 // `crate::parse_requirement` must pass the children gate
5675 // without re-validating at the resolver layer. Pin every leg so
5676 // a future tightening of the canonical set surfaces here as a
5677 // test failure.
5678 for form in [
5679 "^0.1", // caret — minor-range pin (the most common shape)
5680 "~0.1.2", // tilde — patch-range pin
5681 "0.1.0", // exact — single-version pin
5682 "*", // wildcard — any version (semver::VersionReq::STAR)
5683 ">=0.1, <2", // multi-range — comma-separated comparators
5684 ] {
5685 let s = SupervisorSpec {
5686 children: vec![child("worker", form, RestartPolicy::Permanent)],
5687 ..SupervisorSpec::default()
5688 };
5689 s.validate()
5690 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
5691 }
5692 }
5693
5694 #[test]
5695 fn child_versao_empty_takes_precedence_over_invalid() {
5696 // Order pin: the existing `EmptyChildVersion` diagnostic (which
5697 // doesn't try to parse) fires before the new
5698 // `ChildVersaoInvalid` parse-side diagnostic, so an empty
5699 // `:versao` keeps its narrower error message —
5700 // `parse_requirement` would also reject `""`, but the
5701 // empty-string arm is the more self-locating diagnostic for the
5702 // author. Same ordering discipline as
5703 // `membro_versao_empty_takes_precedence_over_invalid` in
5704 // aplicacao.rs.
5705 let s = SupervisorSpec {
5706 children: vec![child("worker", "", RestartPolicy::Permanent)],
5707 ..SupervisorSpec::default()
5708 };
5709 let err = s.validate().unwrap_err();
5710 assert!(
5711 matches!(err, SupervisorError::EmptyChildVersion { ref caixa } if caixa == "worker"),
5712 "got {err:?}"
5713 );
5714 }
5715
5716 #[test]
5717 fn child_versao_invalid_fires_before_duplicate_check() {
5718 // Order pin: a malformed requirement on a non-duplicate entry
5719 // surfaces *its own* diagnostic (which names the offending
5720 // `:versao` string), even when a later entry would otherwise
5721 // collapse onto an earlier name. The per-entry shape gate runs
5722 // inline before the duplicate-key insert — parallel to
5723 // `membro_versao_invalid_fires_before_duplicate_check` in
5724 // aplicacao.rs and the b0c8389 / c4213a4 ordering discipline.
5725 let s = SupervisorSpec {
5726 children: vec![
5727 child("worker", "^bad", RestartPolicy::Permanent),
5728 child("cache", "^0.1", RestartPolicy::Transient),
5729 child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
5730 ],
5731 ..SupervisorSpec::default()
5732 };
5733 let err = s.validate().unwrap_err();
5734 assert!(
5735 matches!(
5736 err,
5737 SupervisorError::ChildVersaoInvalid { ref caixa, .. } if caixa == "worker"
5738 ),
5739 "got {err:?}"
5740 );
5741 }
5742
5743 #[test]
5744 fn child_versao_invalid_diagnostic_carries_offending_versao() {
5745 // The diagnostic-shape pin: the error names the offending
5746 // `:versao` value verbatim so the author can grep their
5747 // caixa.lisp without re-running the build, and carries a
5748 // non-empty `reason` from `semver::VersionReq::parse` so the
5749 // parser's own wording flows through to the diagnostic.
5750 let s = SupervisorSpec {
5751 children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
5752 ..SupervisorSpec::default()
5753 };
5754 let err = s.validate().unwrap_err();
5755 let SupervisorError::ChildVersaoInvalid {
5756 caixa,
5757 versao,
5758 reason,
5759 } = err
5760 else {
5761 panic!("expected ChildVersaoInvalid, got other variant");
5762 };
5763 assert_eq!(caixa, "worker");
5764 assert_eq!(versao, "not-a-req");
5765 assert!(
5766 !reason.is_empty(),
5767 "ChildVersaoInvalid `reason` must carry the parser's wording verbatim"
5768 );
5769 }
5770
5771 // ── value-shape: DNS-1123 label rule on :children :caixa ──────────────
5772
5773 #[test]
5774 fn validate_rejects_child_caixa_with_uppercase() {
5775 // The canonical "I copied the Servico's display name verbatim"
5776 // typo — child caixa names are lowercase per K8s DNS-1123 label
5777 // rule. The diagnostic names the offending name and suggests the
5778 // lower-cased fix in one edit, mirroring the
5779 // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0).
5780 let s = SupervisorSpec {
5781 children: vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
5782 ..SupervisorSpec::default()
5783 };
5784 let err = s.validate().unwrap_err();
5785 let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
5786 panic!("expected ChildCaixaInvalid, got other variant");
5787 };
5788 assert_eq!(caixa, "Worker");
5789 assert!(
5790 reason.contains("uppercase"),
5791 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
5792 );
5793 assert!(
5794 reason.contains("\"worker\""),
5795 "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
5796 );
5797 }
5798
5799 #[test]
5800 fn validate_rejects_child_caixa_with_underscore() {
5801 // The canonical "I'm thinking of a Python module / Postgres
5802 // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
5803 // label schema. K8s rejects `metadata.name: my_worker` at
5804 // admission time with an opaque `field is invalid` (no source-
5805 // citing diagnostic). The gate moves it to caixa-build time.
5806 let s = SupervisorSpec {
5807 children: vec![child("my_worker", "^0.1", RestartPolicy::Permanent)],
5808 ..SupervisorSpec::default()
5809 };
5810 let err = s.validate().unwrap_err();
5811 assert!(
5812 matches!(
5813 err,
5814 SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
5815 if caixa == "my_worker" && reason.contains('_')
5816 ),
5817 "got {err:?}"
5818 );
5819 }
5820
5821 #[test]
5822 fn validate_rejects_child_caixa_with_dot() {
5823 // A `:children :caixa` entry is a single DNS-1123 label, not a
5824 // subdomain. The K8s Service / ComputeUnit `metadata.name` rules
5825 // forbid dots. Same shape as `rejects_membro_caixa_with_dot`
5826 // (3f9d7a0) on the peer name axis.
5827 let s = SupervisorSpec {
5828 children: vec![child("team.worker", "^0.1", RestartPolicy::Permanent)],
5829 ..SupervisorSpec::default()
5830 };
5831 let err = s.validate().unwrap_err();
5832 assert!(
5833 matches!(
5834 err,
5835 SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
5836 if caixa == "team.worker" && reason.contains('.')
5837 ),
5838 "got {err:?}"
5839 );
5840 }
5841
5842 #[test]
5843 fn validate_rejects_child_caixa_with_leading_hyphen() {
5844 // DNS-1123 / DNS-1035 boundary rule: labels must start and end
5845 // with an alphanumeric. The K8s apiserver rejects `-worker`
5846 // outright; the renderer would emit a `metadata.name: "-worker"`
5847 // that fails admission far from the source caixa.lisp.
5848 let s = SupervisorSpec {
5849 children: vec![child("-worker", "^0.1", RestartPolicy::Permanent)],
5850 ..SupervisorSpec::default()
5851 };
5852 let err = s.validate().unwrap_err();
5853 assert!(
5854 matches!(
5855 err,
5856 SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
5857 if caixa == "-worker" && reason.contains("start and end")
5858 ),
5859 "got {err:?}"
5860 );
5861 }
5862
5863 #[test]
5864 fn validate_rejects_child_caixa_with_trailing_hyphen() {
5865 // The symmetric arm of the boundary rule. Pin separately so
5866 // both ends of the label are covered against a future relaxation
5867 // that only checks one boundary.
5868 let s = SupervisorSpec {
5869 children: vec![child("worker-", "^0.1", RestartPolicy::Permanent)],
5870 ..SupervisorSpec::default()
5871 };
5872 let err = s.validate().unwrap_err();
5873 assert!(
5874 matches!(
5875 err,
5876 SupervisorError::ChildCaixaInvalid { ref caixa, .. }
5877 if caixa == "worker-"
5878 ),
5879 "got {err:?}"
5880 );
5881 }
5882
5883 #[test]
5884 fn validate_rejects_child_caixa_with_unicode() {
5885 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
5886 // (`xn--…`) by the author before it reaches K8s. The byte-by-
5887 // byte ASCII validity check rejects multi-byte UTF-8 sequences
5888 // by the first byte that fails the `[a-z0-9-]` predicate.
5889 let s = SupervisorSpec {
5890 children: vec![child("café", "^0.1", RestartPolicy::Permanent)],
5891 ..SupervisorSpec::default()
5892 };
5893 let err = s.validate().unwrap_err();
5894 assert!(
5895 matches!(
5896 err,
5897 SupervisorError::ChildCaixaInvalid { ref caixa, .. }
5898 if caixa == "café"
5899 ),
5900 "got {err:?}"
5901 );
5902 }
5903
5904 #[test]
5905 fn validate_rejects_child_caixa_with_whitespace() {
5906 // Whitespace is the canonical "I pasted from a sketch / doc"
5907 // footgun. The apiserver rejects every `metadata.name` value
5908 // carrying whitespace; pin the gate fires at the right boundary.
5909 let s = SupervisorSpec {
5910 children: vec![child("my worker", "^0.1", RestartPolicy::Permanent)],
5911 ..SupervisorSpec::default()
5912 };
5913 let err = s.validate().unwrap_err();
5914 assert!(
5915 matches!(
5916 err,
5917 SupervisorError::ChildCaixaInvalid { ref caixa, .. }
5918 if caixa == "my worker"
5919 ),
5920 "got {err:?}"
5921 );
5922 }
5923
5924 #[test]
5925 fn validate_rejects_child_caixa_too_long() {
5926 // The 64-byte boundary pin. DNS-1123 / DNS-1035 cap labels at
5927 // 63 bytes; the K8s apiserver rejects every `metadata.name`
5928 // axis over the limit at admission time. The diagnostic names
5929 // both the cap and the actual length so the author can shorten
5930 // in one edit, mirroring `rejects_membro_caixa_too_long`
5931 // (3f9d7a0) and `rejects_placement_cluster_too_long` (6cbb900).
5932 let too_long = "a".repeat(64);
5933 let s = SupervisorSpec {
5934 children: vec![child(&too_long, "^0.1", RestartPolicy::Permanent)],
5935 ..SupervisorSpec::default()
5936 };
5937 let err = s.validate().unwrap_err();
5938 let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
5939 panic!("expected ChildCaixaInvalid, got other variant");
5940 };
5941 assert_eq!(caixa, too_long);
5942 assert!(
5943 reason.contains("63"),
5944 "diagnostic must name the 63-byte cap (got: {reason:?})"
5945 );
5946 assert!(
5947 reason.contains("64"),
5948 "diagnostic must name the actual length (got: {reason:?})"
5949 );
5950 }
5951
5952 #[test]
5953 fn child_caixa_max_length_validates() {
5954 // The 63-byte boundary control pin — exactly-at-the-cap is
5955 // accepted, mirroring `membro_caixa_max_length_validates`
5956 // (3f9d7a0) and `placement_cluster_max_length_validates`
5957 // (6cbb900). Pinned separately so a future off-by-one tightening
5958 // surfaces here.
5959 let max_label = "a".repeat(63);
5960 let s = SupervisorSpec {
5961 children: vec![child(&max_label, "^0.1", RestartPolicy::Permanent)],
5962 ..SupervisorSpec::default()
5963 };
5964 s.validate().unwrap();
5965 }
5966
5967 #[test]
5968 fn validate_accepts_canonical_child_caixa_forms() {
5969 // The realistic shapes a supervised child's `:caixa` carries —
5970 // single-word `worker`, version-suffixed `cache-v2`, single-char
5971 // `a`, two-char `db`, digit-start `2-pool`, longer hyphen-joined
5972 // `payment-retry`, all-digit `0`. Pin every leg so a future
5973 // tightening (e.g. requiring a leading lowercase letter) surfaces
5974 // here as a test failure. Mirrors `accepts_canonical_membro_caixa_forms`
5975 // (3f9d7a0) and `accepts_canonical_placement_cluster_forms`
5976 // (6cbb900).
5977 for form in [
5978 "worker",
5979 "cache-v2",
5980 "a",
5981 "db",
5982 "2-pool",
5983 "payment-retry",
5984 "0",
5985 ] {
5986 let s = SupervisorSpec {
5987 children: vec![child(form, "^0.1", RestartPolicy::Permanent)],
5988 ..SupervisorSpec::default()
5989 };
5990 s.validate()
5991 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
5992 }
5993 }
5994
5995 #[test]
5996 fn child_caixa_empty_takes_precedence_over_invalid() {
5997 // Order pin: the existing `EmptyChildName` diagnostic (which
5998 // doesn't try to parse the DNS-1123 shape) fires before the new
5999 // `ChildCaixaInvalid` per-axis gate, so an empty `:caixa` keeps
6000 // its narrower error message — `is_dns_1123_label` would reject
6001 // the empty string too (boundary check on the first byte), but
6002 // the empty-string arm is the more self-locating diagnostic for
6003 // the author. Same ordering discipline as
6004 // `membro_caixa_empty_takes_precedence_over_invalid` in
6005 // aplicacao.rs.
6006 let s = SupervisorSpec {
6007 children: vec![child("", "^0.1", RestartPolicy::Permanent)],
6008 ..SupervisorSpec::default()
6009 };
6010 let err = s.validate().unwrap_err();
6011 assert_eq!(err, SupervisorError::EmptyChildName);
6012 }
6013
6014 #[test]
6015 fn child_caixa_invalid_fires_before_versao_check() {
6016 // Order pin: the per-axis shape gate runs inline before the
6017 // per-entry versao check, so a malformed `:caixa` on an entry
6018 // whose `:versao` would also fail surfaces the more self-
6019 // locating name-axis diagnostic first. Parallel to
6020 // `membro_versao_invalid_fires_before_duplicate_check` (9888b13)
6021 // and `placement_cluster_invalid_fires_before_duplicate_check`
6022 // (6cbb900).
6023 let s = SupervisorSpec {
6024 children: vec![child("My_Worker", "", RestartPolicy::Permanent)],
6025 ..SupervisorSpec::default()
6026 };
6027 let err = s.validate().unwrap_err();
6028 assert!(
6029 matches!(
6030 err,
6031 SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "My_Worker"
6032 ),
6033 "got {err:?}"
6034 );
6035 }
6036
6037 #[test]
6038 fn child_caixa_invalid_fires_before_duplicate_check() {
6039 // Order pin: a malformed name on a non-duplicate entry surfaces
6040 // its own diagnostic, even when a later entry would otherwise
6041 // collapse onto an earlier name. The per-entry shape gate runs
6042 // inline before the duplicate-key HashSet insert, mirroring
6043 // `placement_cluster_invalid_fires_before_duplicate_check`
6044 // (6cbb900).
6045 let s = SupervisorSpec {
6046 children: vec![
6047 child("Worker", "^0.1", RestartPolicy::Permanent),
6048 child("cache", "^0.1", RestartPolicy::Transient),
6049 child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
6050 ],
6051 ..SupervisorSpec::default()
6052 };
6053 let err = s.validate().unwrap_err();
6054 assert!(
6055 matches!(
6056 err,
6057 SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "Worker"
6058 ),
6059 "got {err:?}"
6060 );
6061 }
6062
6063 #[test]
6064 fn child_caixa_invalid_diagnostic_carries_offending_caixa() {
6065 // The diagnostic-shape pin: the error names the offending
6066 // `:caixa` verbatim plus a non-empty parser-shaped `reason` so
6067 // the author can grep their caixa.lisp without re-running the
6068 // build. Mirrors the diagnostic-shape sweep on every prior
6069 // value-shape gate (3f9d7a0, 6cbb900, c7d05ec).
6070 let s = SupervisorSpec {
6071 children: vec![child("My_Worker", "^0.1", RestartPolicy::Permanent)],
6072 ..SupervisorSpec::default()
6073 };
6074 let err = s.validate().unwrap_err();
6075 let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
6076 panic!("expected ChildCaixaInvalid, got other variant");
6077 };
6078 assert_eq!(caixa, "My_Worker");
6079 assert!(
6080 !reason.is_empty(),
6081 "ChildCaixaInvalid `reason` must carry the parser's wording verbatim"
6082 );
6083 }
6084
6085 // ── value-shape: zero restart_window + duplicate child names ──────────
6086
6087 #[test]
6088 fn validate_accepts_none_restart_window() {
6089 // Omitted `:restart-window` is the "never reset" sentinel —
6090 // valid by design. Mirrors :limits axes where None = unbounded.
6091 let s = SupervisorSpec {
6092 restart_window: None,
6093 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6094 ..SupervisorSpec::default()
6095 };
6096 s.validate().unwrap();
6097 }
6098
6099 #[test]
6100 fn validate_rejects_zero_restart_window() {
6101 // Same "0 means the opposite of what you think" footgun closed
6102 // for :politicas :timeout (Envoy treats 0s as infinite) and
6103 // :limits :wall-clock (wasmtime traps before the call starts).
6104 // Erlang/OTP's MaxIntensity/Period requires Period > 0.
6105 let s = SupervisorSpec {
6106 restart_window: Some(Duration::ZERO),
6107 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6108 ..SupervisorSpec::default()
6109 };
6110 assert_eq!(
6111 s.validate().unwrap_err(),
6112 SupervisorError::RestartWindowZero
6113 );
6114 }
6115
6116 // ── value-shape: integer-ms canonical-form on :restart-window ─────────
6117 //
6118 // The fourth (and last) typed-`Duration` axis in caixa-core to get
6119 // the integer-millisecond canonical-form gate — peer with
6120 // `:limits :wall-clock` (82fc3ef), `:politicas :timeout` (a4ae535),
6121 // and `:politicas :circuit-breaker :window` (a4ae535). The serde
6122 // path is already gated at the shared codec layer (see
6123 // `restart_window_serde_rejects_fractional_seconds`); this arm
6124 // closes the programmatic-struct-literal path the codec gate can't
6125 // see.
6126
6127 #[test]
6128 fn validate_rejects_sub_millisecond_restart_window() {
6129 // The fail-before-pass-after pin: a programmatic
6130 // `Duration::from_micros(1500)` (= 1_500_000 ns) silently passed
6131 // `validate` on every pre-gate codebase, then truncated to
6132 // `as_millis() == 1` on first serialize — the shared codec
6133 // emits `"1ms"`, parses it back to `Duration::from_millis(1)` =
6134 // 1_000_000 ns, the typed `restart_window` no longer matches
6135 // its rendered form.
6136 let s = SupervisorSpec {
6137 restart_window: Some(Duration::from_micros(1500)),
6138 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6139 ..SupervisorSpec::default()
6140 };
6141 match s.validate().unwrap_err() {
6142 SupervisorError::RestartWindowNotCanonical { window } => {
6143 assert_eq!(window, Duration::from_micros(1500));
6144 }
6145 other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
6146 }
6147 }
6148
6149 #[test]
6150 fn validate_rejects_one_nanosecond_restart_window() {
6151 // The far-sub-ms case: `Duration::from_nanos(1)` is non-zero
6152 // (so `RestartWindowZero` doesn't fire) but `as_millis() == 0`,
6153 // so the shared codec emits the literal `"0s"` — the next
6154 // serde round-trip would parse back to `Duration::ZERO`, which
6155 // the `RestartWindowZero` arm then rejects on re-validate. The
6156 // canonical-form gate at this layer surfaces a self-locating
6157 // diagnostic naming the offending Duration verbatim rather
6158 // than a downstream `RestartWindowZero` whose remediation
6159 // points at omitting the slot.
6160 let s = SupervisorSpec {
6161 restart_window: Some(Duration::from_nanos(1)),
6162 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6163 ..SupervisorSpec::default()
6164 };
6165 match s.validate().unwrap_err() {
6166 SupervisorError::RestartWindowNotCanonical { window } => {
6167 assert_eq!(window, Duration::from_nanos(1));
6168 }
6169 other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
6170 }
6171 }
6172
6173 #[test]
6174 fn validate_rejects_nanosecond_past_canonical_boundary_restart_window() {
6175 // The 1-ns-past-1ms boundary case: a `Duration` carrying
6176 // 1_000_001 ns is structurally past the integer-ms granularity
6177 // floor — `subsec_nanos() % 1_000_000 == 1`. The codec round-
6178 // trip would truncate to `1ms` and the consumer would observe
6179 // a 1-ns drift on every emit. Same boundary the peer
6180 // `validate_rejects_nanosecond_past_canonical_boundary` test
6181 // in limits.rs pins for the `:limits :wall-clock` axis.
6182 let w = Duration::from_nanos(1_000_001);
6183 let s = SupervisorSpec {
6184 restart_window: Some(w),
6185 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6186 ..SupervisorSpec::default()
6187 };
6188 assert_eq!(
6189 s.validate().unwrap_err(),
6190 SupervisorError::RestartWindowNotCanonical { window: w }
6191 );
6192 }
6193
6194 #[test]
6195 fn validate_accepts_integer_millisecond_restart_window_values() {
6196 // The positive-control sweep: every `Duration` the shared
6197 // codec can round-trip losslessly — the canonical
6198 // `<integer>{ms,s,m,h}` set the codec's `render` / `parse`
6199 // pair emits and accepts — passes `validate` without
6200 // surfacing the new canonical-form arm. Mirrors
6201 // `validate_accepts_integer_millisecond_wall_clock_values` on
6202 // the sibling `:limits :wall-clock` axis.
6203 for w in [
6204 Duration::from_millis(1),
6205 Duration::from_millis(500),
6206 Duration::from_millis(1500),
6207 Duration::from_secs(1),
6208 Duration::from_secs(30),
6209 Duration::from_secs(60),
6210 Duration::from_secs(120),
6211 Duration::from_secs(3600),
6212 ] {
6213 let s = SupervisorSpec {
6214 restart_window: Some(w),
6215 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6216 ..SupervisorSpec::default()
6217 };
6218 s.validate()
6219 .unwrap_or_else(|e| panic!("integer-ms {w:?} must validate, got {e:?}"));
6220 }
6221 }
6222
6223 #[test]
6224 fn validate_restart_window_zero_takes_precedence_over_canonical_gate() {
6225 // Cross-arm ordering pin: `Duration::ZERO` has
6226 // `subsec_nanos() == 0` and would otherwise pass the
6227 // canonical-form arm — the zero-floor arm must fire first so
6228 // the more self-locating `RestartWindowZero` diagnostic (with
6229 // its omit-axis remediation directly named) leads. Same
6230 // posture every peer zero-then-shape gate uses
6231 // (`WallClockZero` → `WallClockNotCanonical`,
6232 // `PolicyTimeoutZero` → `PolicyTimeoutNotCanonical`,
6233 // `PolicyBreakerZeroWindow` → `PolicyBreakerWindowNotCanonical`).
6234 let s = SupervisorSpec {
6235 restart_window: Some(Duration::ZERO),
6236 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6237 ..SupervisorSpec::default()
6238 };
6239 assert_eq!(
6240 s.validate().unwrap_err(),
6241 SupervisorError::RestartWindowZero
6242 );
6243 }
6244
6245 #[test]
6246 fn restart_window_canonical_diagnostic_carries_offending_duration() {
6247 // Diagnostic-shape pin: the canonical-form arm names the
6248 // offending `Duration` verbatim so the author's grep lands on
6249 // the field's value, not a generic "duration not canonical"
6250 // message. Same shape every other typed-canonical-form arm
6251 // on this surface carries (`WallClockNotCanonical` carries
6252 // the offending `Duration` verbatim,
6253 // `PolicyTimeoutNotCanonical` carries the offending
6254 // `Duration` verbatim).
6255 let w = Duration::from_micros(500);
6256 let s = SupervisorSpec {
6257 restart_window: Some(w),
6258 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6259 ..SupervisorSpec::default()
6260 };
6261 let err = s.validate().unwrap_err();
6262 let msg = err.to_string();
6263 assert!(
6264 msg.contains("500"),
6265 "diagnostic must carry the offending magnitude verbatim (got {msg:?})"
6266 );
6267 assert!(
6268 msg.contains("sub-millisecond"),
6269 "diagnostic must name the sub-millisecond residue class (got {msg:?})"
6270 );
6271 }
6272
6273 #[test]
6274 fn restart_window_validated_value_round_trips_through_codec() {
6275 // The structural property the canonical-ms gate enforces:
6276 // every `SupervisorSpec::restart_window` past
6277 // `SupervisorSpec::validate` round-trips losslessly through
6278 // the shared duration codec (serialize → string →
6279 // deserialize → equal value). Pin this end-to-end so a future
6280 // change to either side (the validate gate's accepted
6281 // granularity, the codec's parse/render unit set) that breaks
6282 // the alignment surfaces here. Peer of
6283 // `wall_clock_validated_value_round_trips_through_codec` on
6284 // the sibling `:limits :wall-clock` axis.
6285 for w in [
6286 Duration::from_millis(1),
6287 Duration::from_millis(1500),
6288 Duration::from_secs(30),
6289 Duration::from_secs(3600),
6290 ] {
6291 let s = SupervisorSpec {
6292 restart_window: Some(w),
6293 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6294 ..SupervisorSpec::default()
6295 };
6296 s.validate().unwrap();
6297 let json = serde_json::to_string(&s).unwrap();
6298 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6299 assert_eq!(back.restart_window, Some(w));
6300 }
6301 }
6302
6303 // ── value-shape: upper cap on :restart-window ─────────────────────────
6304 //
6305 // The fourth (and last) typed-`Duration` axis in caixa-core to get
6306 // the 1h upper cap — peer with `:limits :wall-clock` (51e0dbd),
6307 // `:politicas :timeout` (2e8ee7e), and `:politicas
6308 // :circuit-breaker :window` (379a814). Brackets the typed
6309 // `:restart-window` axis structurally: every validated value lies
6310 // in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`, integer-millisecond
6311 // granularity, closing the
6312 // rolling-window-degenerates-to-lifetime-counter footgun the prior
6313 // zero-floor-and-canonical-form-only checks left open.
6314
6315 #[test]
6316 fn validate_rejects_restart_window_above_cap() {
6317 // The fail-before-pass-after pin: 3601s = 1h + 1s is
6318 // structurally one canonical-tick past the
6319 // [`SUPERVISOR_RESTART_WINDOW_MAX`] ceiling (1h = 3600s) — an
6320 // integer-millisecond magnitude the canonical-form arm above
6321 // accepts cleanly, that the shared duration codec round-trips
6322 // losslessly as `"3601s"`, and that silently passed validate on
6323 // every pre-gate codebase because the typed slot's only checks
6324 // were the zero-floor and canonical-form arms. The runtime
6325 // substrate consuming the value (Erlang/OTP's MaxIntensity/
6326 // Period reconciler, the future wasm-operator's per-supervisor
6327 // restart-intensity counter) reaches for a `Duration` so long
6328 // no realistic restart-recovery pattern resets the counter,
6329 // far from the source caixa.lisp.
6330 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
6331 let s = SupervisorSpec {
6332 restart_window: Some(w),
6333 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6334 ..SupervisorSpec::default()
6335 };
6336 assert_eq!(
6337 s.validate().unwrap_err(),
6338 SupervisorError::RestartWindowExceedsCap { window: w }
6339 );
6340 }
6341
6342 #[test]
6343 fn validate_rejects_restart_window_one_millisecond_above_cap() {
6344 // Boundary case: exactly 1ms past the cap (the granularity the
6345 // canonical-form gate enforces). Catches a future "strictly
6346 // less than" half-measure and pins the diagnostic to name the
6347 // offending `Duration` verbatim. Peer of
6348 // `validate_rejects_wall_clock_one_millisecond_above_cap` /
6349 // `rejects_policy_timeout_one_millisecond_above_cap` /
6350 // `rejects_circuit_breaker_window_one_millisecond_above_cap`
6351 // on the sibling typed-`Duration` axes' top edges.
6352 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
6353 let s = SupervisorSpec {
6354 restart_window: Some(w),
6355 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6356 ..SupervisorSpec::default()
6357 };
6358 assert_eq!(
6359 s.validate().unwrap_err(),
6360 SupervisorError::RestartWindowExceedsCap { window: w }
6361 );
6362 }
6363
6364 #[test]
6365 fn validate_rejects_restart_window_far_above_cap() {
6366 // The "obvious authoring footgun" case: a `(:restart-window "24h")`,
6367 // `(:restart-window "7d")`, or any "I want a lifetime counter
6368 // but wrote a `<integer>h` magnitude anyway" typo — values the
6369 // canonical-form arm accepts as integer-millisecond magnitudes,
6370 // the codec round-trips losslessly through serde, but the
6371 // operator's `MaxIntensity / Period` reconciler cannot honor
6372 // as a meaningful rolling window. Until this gate landed
6373 // validate accepted them. Pin the common above-cap values (24h,
6374 // 7d, ~11.5d) so a future relaxation that drops the upper bound
6375 // surfaces here.
6376 for w in [
6377 Duration::from_secs(86_400), // 24h
6378 Duration::from_secs(604_800), // 7d
6379 Duration::from_secs(1_000_000), // ~11.5 days
6380 ] {
6381 let s = SupervisorSpec {
6382 restart_window: Some(w),
6383 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6384 ..SupervisorSpec::default()
6385 };
6386 assert_eq!(
6387 s.validate().unwrap_err(),
6388 SupervisorError::RestartWindowExceedsCap { window: w }
6389 );
6390 }
6391 }
6392
6393 #[test]
6394 fn validate_accepts_restart_window_at_cap() {
6395 // The boundary value — exactly [`SUPERVISOR_RESTART_WINDOW_MAX`]
6396 // (1h) — must validate. The cap is inclusive on the top edge,
6397 // matching the [`crate::LIMITS_WALL_CLOCK_MAX`] /
6398 // [`crate::POLICY_TIMEOUT_MAX`] /
6399 // [`crate::POLICY_BREAKER_WINDOW_MAX`] discipline on the sibling
6400 // capped axes. Pin the boundary explicitly so a future
6401 // off-by-one tightening (`>= SUPERVISOR_RESTART_WINDOW_MAX`
6402 // instead of `>`) surfaces here as a test failure rather than a
6403 // silent contract narrowing.
6404 let s = SupervisorSpec {
6405 restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
6406 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6407 ..SupervisorSpec::default()
6408 };
6409 s.validate()
6410 .expect("restart_window == SUPERVISOR_RESTART_WINDOW_MAX must validate");
6411 }
6412
6413 #[test]
6414 fn validate_accepts_restart_window_typical_values() {
6415 // The documented Erlang/OTP / Elixir / Riak Core / RabbitMQ
6416 // per-supervisor production-playbook band positive-control
6417 // sweep — every value Learn You Some Erlang's `{intensity, 5,
6418 // 60}` worker-supervisor `Period = 60s` default, Elixir's
6419 // `Supervisor` `max_seconds: 5` default, OTP's `supervisor`
6420 // callback module `MaxT = 5..=60` typical, Riak Core's `MaxT ∈
6421 // 10s..=300s`, and RabbitMQ broker-supervisor `MaxT = 5s`
6422 // default recommend (5s..=300s) must pass, plus a sweep
6423 // through the long-tail-flaky-pool band (5m, 15m, 30m, 1h) the
6424 // cap accepts. Mirrors `validate_accepts_wall_clock_typical_values`
6425 // on the sibling `:limits :wall-clock` axis.
6426 for w in [
6427 Duration::from_millis(1),
6428 Duration::from_millis(500),
6429 Duration::from_secs(1),
6430 Duration::from_secs(5), // RabbitMQ broker-supervisor default
6431 Duration::from_secs(10), // Riak Core lower
6432 Duration::from_secs(30),
6433 Duration::from_secs(60), // Learn You Some Erlang default
6434 Duration::from_secs(120), // OTP supervisor MaxT typical
6435 Duration::from_secs(300), // Riak Core upper
6436 Duration::from_secs(900), // 15m
6437 Duration::from_secs(1800),
6438 Duration::from_secs(3600), // exactly 1h, the cap
6439 ] {
6440 let s = SupervisorSpec {
6441 restart_window: Some(w),
6442 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6443 ..SupervisorSpec::default()
6444 };
6445 s.validate()
6446 .unwrap_or_else(|e| panic!("restart_window={w:?} must validate; got {e:?}"));
6447 }
6448 }
6449
6450 #[test]
6451 fn restart_window_zero_takes_precedence_over_cap() {
6452 // The cross-arm ordering pin: `Duration::ZERO` is structurally
6453 // outside both `>= 1ms` (zero-floor) and `<=
6454 // SUPERVISOR_RESTART_WINDOW_MAX` (cap), but the zero-floor
6455 // diagnostic is the more self-locating one (it directly names
6456 // the omit-axis remediation), so the validate gate must fire
6457 // on zero first. Same shape every other zero-then-cap ordering
6458 // on this surface uses (`WallClockZero` then
6459 // `WallClockExceedsCap`, `PolicyTimeoutZero` then
6460 // `PolicyTimeoutExceedsCap`, `PolicyBreakerZeroWindow` then
6461 // `PolicyBreakerWindowExceedsCap`).
6462 let s = SupervisorSpec {
6463 restart_window: Some(Duration::ZERO),
6464 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6465 ..SupervisorSpec::default()
6466 };
6467 assert_eq!(
6468 s.validate().unwrap_err(),
6469 SupervisorError::RestartWindowZero,
6470 "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
6471 );
6472 }
6473
6474 #[test]
6475 fn restart_window_canonical_takes_precedence_over_cap() {
6476 // The cross-arm ordering pin: a `Duration` that is *both*
6477 // sub-millisecond (non-canonical-form) and structurally above
6478 // the cap surfaces the canonical-form diagnostic first,
6479 // because the round-trip-shape break is the more fundamental
6480 // issue (the value can't even round-trip through the codec,
6481 // so the cap diagnostic naming `1ms..=1h` would be misleading
6482 // — there's no integer-ms form of the offending value). Pin
6483 // the order so a future refactor that reorders the arms
6484 // surfaces here as a test failure rather than a silent
6485 // diagnostic regression. Peer of
6486 // `wall_clock_canonical_takes_precedence_over_cap` /
6487 // `policy_timeout_canonical_takes_precedence_over_cap`.
6488 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_nanos(1);
6489 let s = SupervisorSpec {
6490 restart_window: Some(w),
6491 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6492 ..SupervisorSpec::default()
6493 };
6494 assert_eq!(
6495 s.validate().unwrap_err(),
6496 SupervisorError::RestartWindowNotCanonical { window: w },
6497 "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
6498 );
6499 }
6500
6501 #[test]
6502 fn max_restarts_cap_takes_precedence_over_restart_window_cap() {
6503 // The cross-arm ordering pin between the `:max-restarts` cap
6504 // and the sibling `:restart-window` cap. A supervisor carrying
6505 // both an over-cap `max_restarts` AND an over-cap window must
6506 // surface the `MaxRestartsExceedsCap` diagnostic first — the
6507 // cap arm is wired immediately after the zero-restart arm and
6508 // strictly before every window-axis arm (zero / canonical /
6509 // cap), so the offending value the diagnostic names matches
6510 // the order the author would discover the gates by reading
6511 // top-to-bottom through `SupervisorSpec::validate`. Pin the
6512 // order so a future refactor that reorders the arms surfaces
6513 // here as a test failure rather than a silent diagnostic
6514 // regression. Peer of
6515 // `max_restarts_cap_takes_precedence_over_restart_window_gates`
6516 // on the sibling zero / canonical window arms.
6517 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
6518 let s = SupervisorSpec {
6519 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
6520 restart_window: Some(w),
6521 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6522 ..SupervisorSpec::default()
6523 };
6524 assert_eq!(
6525 s.validate().unwrap_err(),
6526 SupervisorError::MaxRestartsExceedsCap {
6527 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
6528 },
6529 "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
6530 );
6531 }
6532
6533 #[test]
6534 fn restart_window_cap_diagnostic_carries_offending_value() {
6535 // The diagnostic-shape pin: the offending `Duration` is
6536 // carried verbatim into the
6537 // [`SupervisorError::RestartWindowExceedsCap`] variant so the
6538 // surfaced error message names the value the author wrote,
6539 // not just the cap. Same self-locating diagnostic shape every
6540 // other typed-cap arm on this surface carries
6541 // (`WallClockExceedsCap` carries the offending `Duration`
6542 // verbatim, `PolicyTimeoutExceedsCap` carries the offending
6543 // `Duration` verbatim, `PolicyBreakerWindowExceedsCap` carries
6544 // the offending `Duration` verbatim).
6545 let w = Duration::from_secs(7200); // 2h
6546 let s = SupervisorSpec {
6547 restart_window: Some(w),
6548 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6549 ..SupervisorSpec::default()
6550 };
6551 let err = s.validate().unwrap_err();
6552 assert!(
6553 matches!(err, SupervisorError::RestartWindowExceedsCap { window } if window == w),
6554 "got {err:?}"
6555 );
6556 let msg = err.to_string();
6557 assert!(
6558 msg.contains("7200"),
6559 ":supervisor :restart-window cap diagnostic must carry the offending value verbatim (got: {msg})"
6560 );
6561 }
6562
6563 #[test]
6564 fn supervisor_restart_window_cap_pins_canonical_value() {
6565 // The SUPERVISOR_RESTART_WINDOW_MAX constant pins the value at
6566 // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
6567 // shared duration codec emits as a clean canonical string
6568 // (`"<n>h"`). Pinning the literal value here surfaces a future
6569 // drift (a relaxation to 24h, a tightening to 5m) as a
6570 // deliberate test edit, not a silent contract narrowing.
6571 //
6572 // The four typed-`Duration` caps on the validation surface
6573 // (`LIMITS_WALL_CLOCK_MAX` per-process, `POLICY_TIMEOUT_MAX`
6574 // per-edge, `POLICY_BREAKER_WINDOW_MAX` per-breaker,
6575 // `SUPERVISOR_RESTART_WINDOW_MAX` per-supervisor) share a
6576 // single uniform top edge at the codec's largest emitted unit
6577 // — a structural-property invariant the equality assertions
6578 // here enshrine, so a future drift on any of the four
6579 // surfaces as a deliberate test edit. Same shape every other
6580 // typed-cap value pin uses
6581 // (`wall_clock_cap_pins_canonical_value`,
6582 // `policy_timeout_cap_pins_canonical_value`,
6583 // `circuit_breaker_window_cap_pins_canonical_value`).
6584 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, Duration::from_secs(3600));
6585 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX.as_millis(), 3_600_000);
6586 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::LIMITS_WALL_CLOCK_MAX);
6587 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::POLICY_TIMEOUT_MAX);
6588 assert_eq!(
6589 SUPERVISOR_RESTART_WINDOW_MAX,
6590 crate::POLICY_BREAKER_WINDOW_MAX
6591 );
6592 }
6593
6594 #[test]
6595 fn restart_window_cap_value_round_trips_through_codec() {
6596 // The codec round-trip property the cap arm preserves: the
6597 // [`SUPERVISOR_RESTART_WINDOW_MAX`] constant itself round-trips
6598 // through the shared duration codec — every value at the cap
6599 // serializes to the canonical `"1h"` form and parses back
6600 // identically. Pin the round-trip so a future change to the
6601 // codec's unit set or to the cap's magnitude that breaks the
6602 // round-trip property surfaces here. Peer of
6603 // `wall_clock_cap_value_round_trips_through_codec` on the
6604 // sibling `:limits :wall-clock` axis.
6605 let s = SupervisorSpec {
6606 restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
6607 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6608 ..SupervisorSpec::default()
6609 };
6610 s.validate().unwrap();
6611 let json = serde_json::to_string(&s).unwrap();
6612 assert!(
6613 json.contains("\"1h\""),
6614 "SUPERVISOR_RESTART_WINDOW_MAX must serialize to the canonical `\"1h\"` form (got {json})"
6615 );
6616 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6617 assert_eq!(back.restart_window, Some(SUPERVISOR_RESTART_WINDOW_MAX));
6618 }
6619
6620 #[test]
6621 fn validate_rejects_duplicate_child_caixa() {
6622 // Two children with the same :caixa render to two ComputeUnits
6623 // with the same name in the cluster's HelmRelease values —
6624 // one silently overwrites the other. Erlang/OTP's child_spec.id
6625 // is required-unique per supervisor; same set-not-multiset
6626 // discipline applied here as for :membros / :placement
6627 // :clusters / :entrada :paths.
6628 let s = SupervisorSpec {
6629 children: vec![
6630 child("worker", "^0.1", RestartPolicy::Permanent),
6631 child("cache", "^0.1", RestartPolicy::Transient),
6632 child("worker", "^0.2", RestartPolicy::Permanent),
6633 ],
6634 ..SupervisorSpec::default()
6635 };
6636 let err = s.validate().unwrap_err();
6637 assert!(
6638 matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "worker"),
6639 "got {err:?}"
6640 );
6641 }
6642
6643 #[test]
6644 fn validate_duplicate_child_diagnostic_names_first_collision() {
6645 // Iteration walks the :children list in declaration order —
6646 // the diagnostic names the first repeat, deterministically,
6647 // even when multiple names duplicate.
6648 let s = SupervisorSpec {
6649 children: vec![
6650 child("a", "^0.1", RestartPolicy::Permanent),
6651 child("b", "^0.1", RestartPolicy::Permanent),
6652 child("a", "^0.1", RestartPolicy::Permanent),
6653 child("b", "^0.1", RestartPolicy::Permanent),
6654 ],
6655 ..SupervisorSpec::default()
6656 };
6657 let err = s.validate().unwrap_err();
6658 assert!(
6659 matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "a"),
6660 "got {err:?}"
6661 );
6662 }
6663
6664 // ── self-supervision cross-slot gate ──────────────────────────
6665
6666 #[test]
6667 fn validate_no_self_supervision_rejects_self_referential_child() {
6668 // A supervisor whose `:children` lists its own `:nome` is a
6669 // one-node reconciliation cycle — rejected, naming the parent.
6670 let children = vec![
6671 child("worker", "^0.1", RestartPolicy::Permanent),
6672 child("orquestra", "^0.1", RestartPolicy::Permanent),
6673 ];
6674 let err = validate_no_self_supervision(&children, "orquestra").unwrap_err();
6675 assert!(
6676 matches!(err, SupervisorError::ChildSupervisesSelf { ref caixa } if caixa == "orquestra"),
6677 "got {err:?}"
6678 );
6679 }
6680
6681 #[test]
6682 fn validate_no_self_supervision_accepts_distinct_children() {
6683 // Positive control: distinct child names (including a child that
6684 // is itself a supervisor — nested trees are valid OTP) pass.
6685 let children = vec![
6686 child("worker", "^0.1", RestartPolicy::Permanent),
6687 child("sub-tree", "^0.1", RestartPolicy::Permanent),
6688 ];
6689 validate_no_self_supervision(&children, "orquestra").unwrap();
6690 }
6691
6692 #[test]
6693 fn validate_no_self_supervision_empty_children_is_ok() {
6694 // SimpleOneForOne / no-static-children supervisors have nothing
6695 // to self-reference — the gate is vacuously satisfied.
6696 validate_no_self_supervision(&[], "orquestra").unwrap();
6697 }
6698
6699 #[test]
6700 fn validate_simple_one_for_one_skips_uniqueness_check() {
6701 // SimpleOneForOne supervisors carry no static children — the
6702 // duplicate-child loop never runs. A zero-window declaration
6703 // on a SimpleOneForOne supervisor still trips the window check
6704 // (window applies to dynamic children too).
6705 let s = SupervisorSpec {
6706 estrategia: RestartStrategy::SimpleOneForOne,
6707 restart_window: None,
6708 children: vec![],
6709 ..SupervisorSpec::default()
6710 };
6711 s.validate().unwrap();
6712 let s_zero = SupervisorSpec {
6713 estrategia: RestartStrategy::SimpleOneForOne,
6714 restart_window: Some(Duration::ZERO),
6715 children: vec![],
6716 ..SupervisorSpec::default()
6717 };
6718 assert_eq!(
6719 s_zero.validate().unwrap_err(),
6720 SupervisorError::RestartWindowZero
6721 );
6722 }
6723
6724 #[test]
6725 fn validate_zero_window_runs_after_max_restarts_check() {
6726 // Pin the order: max_restarts == 0 fires before
6727 // restart_window == 0s, so an author with both wrong sees the
6728 // counter-axis diagnostic first (matches the order in the
6729 // struct and in the doc comment).
6730 let s = SupervisorSpec {
6731 max_restarts: 0,
6732 restart_window: Some(Duration::ZERO),
6733 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6734 ..SupervisorSpec::default()
6735 };
6736 assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
6737 }
6738
6739 #[test]
6740 fn round_trip_all_strategies() {
6741 for &strat in RestartStrategy::ALL {
6742 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
6743 // shape partition through the [`gen_platform::IsVariant`]
6744 // derive-generated [`RestartStrategy::is_simple_one_for_one`]
6745 // predicate rather than the raw
6746 // `matches!(strat, RestartStrategy::SimpleOneForOne)`
6747 // open-coded pattern-match — same closed-set-typed-enum
6748 // arm-discriminator dispatch discipline the sibling
6749 // [`crate::upgrade::UpgradeInstruction::is_restart`] convergence
6750 // (915a934) extended onto its two paired positive / negated
6751 // `matches!` filter sites, and the sibling
6752 // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
6753 // predicate convergence (766ec63) extended onto the M3 mesh-
6754 // slot per-`:placement` distribution-strategy `matches!`
6755 // discriminator axis. See the sibling
6756 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
6757 // fixture and the peer `manifest::tests::
6758 // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
6759 // fixture — all three sites (the last unlifted
6760 // `matches!`-based arm-discriminator axis on the OTP-shape
6761 // supervisor sibling-restart-strategy closed-set typed enum,
6762 // acknowledged in 915a934's Prior-commits footnote as the
6763 // outstanding follow-up) now consult one typed dispatch on
6764 // the substrate primitive.
6765 let s = SupervisorSpec {
6766 estrategia: strat,
6767 children: if strat.is_simple_one_for_one() {
6768 vec![]
6769 } else {
6770 vec![child("w", "^0.1", RestartPolicy::Permanent)]
6771 },
6772 ..SupervisorSpec::default()
6773 };
6774 let json = serde_json::to_string(&s).unwrap();
6775 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6776 assert_eq!(s, back);
6777 }
6778 }
6779
6780 #[test]
6781 fn round_trip_all_restart_policies() {
6782 for policy in [
6783 RestartPolicy::Permanent,
6784 RestartPolicy::Temporary,
6785 RestartPolicy::Transient,
6786 ] {
6787 let c = child("w", "^0.1", policy);
6788 let json = serde_json::to_string(&c).unwrap();
6789 let back: ChildSpec = serde_json::from_str(&json).unwrap();
6790 assert_eq!(c, back);
6791 }
6792 }
6793
6794 #[test]
6795 fn restart_strategy_is_simple_one_for_one_predicate_partitions_the_arm_set() {
6796 // The fail-before-pass-after pin on the `gen_platform::IsVariant`
6797 // derive's [`RestartStrategy::is_simple_one_for_one`] arm-
6798 // discriminator predicate: [`RestartStrategy::SimpleOneForOne`]
6799 // is the only variant that satisfies `.is_simple_one_for_one()`;
6800 // every static-children-bearing arm (`OneForOne` / `OneForAll`
6801 // / `RestForOne`) returns `false`. This pin makes the partition
6802 // invariant load-bearing at caixa-core test time so a future
6803 // derive regression (a hole that returns `false` for
6804 // `SimpleOneForOne` too, or a byte-collision that flips a second
6805 // variant to `true`) trips here rather than laundering the arm
6806 // at the three test-fixture builder sites (a hole flips the
6807 // `SimpleOneForOne` fixture to carry a non-empty children list
6808 // and the subsequent `SupervisorSpec::validate` would refuse the
6809 // fixture with [`SupervisorError::SimpleOneForOneWithStaticChildren`];
6810 // a collision flips a peer strategy's fixture to carry an empty
6811 // children list and the subsequent `validate` would refuse with
6812 // [`SupervisorError::NoChildren`] — either way, the pin fires
6813 // here, at the derive site, rather than at the fixture-refusal
6814 // site far away). Peer of the sibling
6815 // [`crate::upgrade::tests::upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
6816 // (915a934) pin on the M2 OTP-appup axis and the sibling
6817 // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
6818 // pin on the M0 `:kind` axis.
6819 let cases: &[(RestartStrategy, bool)] = &[
6820 (RestartStrategy::OneForOne, false),
6821 (RestartStrategy::OneForAll, false),
6822 (RestartStrategy::RestForOne, false),
6823 (RestartStrategy::SimpleOneForOne, true),
6824 ];
6825 for (variant, expected) in cases {
6826 assert_eq!(
6827 variant.is_simple_one_for_one(),
6828 *expected,
6829 "RestartStrategy::{variant:?}.is_simple_one_for_one() must \
6830 return {expected} (partition invariant on the \
6831 IsVariant-derived arm-discriminator predicate — every \
6832 test-fixture site that partitions the `:children` slot \
6833 shape on `SimpleOneForOne ↔ non-SimpleOneForOne` keys \
6834 off this typed dispatch, so a derive regression must \
6835 surface here rather than at the fixture-refusal site)"
6836 );
6837 }
6838 }
6839
6840 #[test]
6841 fn restart_strategy_fixture_partition_routes_through_is_simple_one_for_one_predicate() {
6842 // Byte-identity pin on the `SimpleOneForOne ↔ non-SimpleOneForOne`
6843 // fixture-shape partition against the pre-lift
6844 // `matches!(strat, RestartStrategy::SimpleOneForOne)` open-coded
6845 // pattern-match every test-fixture builder site previously
6846 // coupled to inline. Asserts the two projections agree byte-for-
6847 // byte on every arm of the enum, so a future derive regression
6848 // that flipped either predicate's arm-set would surface here at
6849 // caixa-core test time rather than at the three fixture-builder
6850 // sites (`supervisor::tests::round_trip_all_strategies`,
6851 // `supervisor::tests::supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`,
6852 // `manifest::tests::caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`)
6853 // far from the derive site. Same peer-shape byte-identity pin
6854 // every sibling `IsVariant`-derive-routed convergence carries on
6855 // the substrate's closed-set typed-enum surface (peer of
6856 // [`crate::upgrade::tests::validate_restart_exclusive_routes_through_is_restart_predicate`]
6857 // on the M2 OTP-appup axis).
6858 for &strat in RestartStrategy::ALL {
6859 let via_predicate = strat.is_simple_one_for_one();
6860 let via_matches = matches!(strat, RestartStrategy::SimpleOneForOne);
6861 assert_eq!(
6862 via_predicate, via_matches,
6863 "RestartStrategy::{strat:?}: is_simple_one_for_one() must \
6864 byte-equal matches!(_, RestartStrategy::SimpleOneForOne) — \
6865 the pre-lift open-coded pattern and the \
6866 IsVariant-derived predicate are the same axis, \
6867 one typed dispatch"
6868 );
6869 }
6870 }
6871
6872 #[test]
6873 fn duration_codec_round_trip_canonical_units() {
6874 // Note the canonical-form rule: durations serialize to the
6875 // *largest* unit that divides cleanly, so 60s ↔ "1m" and not
6876 // "60s" — but the round-trip preserves the underlying Duration.
6877 let cases = [
6878 ("30s", Duration::from_secs(30)),
6879 ("5m", Duration::from_secs(300)),
6880 ("1h", Duration::from_secs(3600)),
6881 ("500ms", Duration::from_millis(500)),
6882 ];
6883 for (lit, dur) in cases {
6884 let s = SupervisorSpec {
6885 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6886 restart_window: Some(dur),
6887 ..SupervisorSpec::default()
6888 };
6889 let json = serde_json::to_string(&s).unwrap();
6890 assert!(
6891 json.contains(&format!("\"{lit}\"")),
6892 "expected \"{lit}\" in {json}"
6893 );
6894 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6895 assert_eq!(back.restart_window, Some(dur));
6896 }
6897 }
6898
6899 #[test]
6900 fn duration_canonicalizes_to_largest_unit() {
6901 // 60 seconds → "1m" (largest cleanly-divisible unit), but the
6902 // typed Duration still equals 60s on the way back.
6903 let s = SupervisorSpec {
6904 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6905 restart_window: Some(Duration::from_secs(60)),
6906 ..SupervisorSpec::default()
6907 };
6908 let json = serde_json::to_string(&s).unwrap();
6909 assert!(json.contains("\"1m\""), "{json}");
6910 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6911 assert_eq!(back.restart_window, Some(Duration::from_secs(60)));
6912 }
6913
6914 #[test]
6915 fn three_child_one_for_one_validates() {
6916 let s = SupervisorSpec {
6917 estrategia: RestartStrategy::OneForOne,
6918 max_restarts: 5,
6919 restart_window: Some(Duration::from_secs(60)),
6920 children: vec![
6921 child("worker", "^0.1", RestartPolicy::Permanent),
6922 child("cache", "^0.1", RestartPolicy::Transient),
6923 child("scratch", "^0.1", RestartPolicy::Temporary),
6924 ],
6925 };
6926 s.validate().unwrap();
6927 }
6928
6929 #[test]
6930 fn json_uses_pascal_case_for_strategy_and_policy() {
6931 // Variant names are PascalCase by default in serde, matching
6932 // tatara-lisp's enum convention (`:estrategia OneForOne`).
6933 let c = child("w", "^0.1", RestartPolicy::Permanent);
6934 let json = serde_json::to_string(&c).unwrap();
6935 assert!(json.contains("\"Permanent\""));
6936 assert!(!json.contains("\"permanent\""));
6937
6938 let s = SupervisorSpec {
6939 estrategia: RestartStrategy::OneForOne,
6940 children: vec![c],
6941 ..SupervisorSpec::default()
6942 };
6943 let json = serde_json::to_string(&s).unwrap();
6944 assert!(json.contains("\"estrategia\":\"OneForOne\""));
6945 }
6946
6947 // ── shared duration codec: integer-magnitude canonical-form gate ──
6948 //
6949 // The gate lifts the discipline `crate::limits::parse_duration`
6950 // (818dd38) carries on the peer `:limits :wall-clock` codec onto
6951 // the shared codec backing the remaining three typed-duration
6952 // slots: `:supervisor :restart-window`, `:politicas :timeout`, and
6953 // `:politicas :circuit-breaker :window`. Every magnitude `render`
6954 // emits is a non-negative integer with no decimal point and no
6955 // leading sign, so the codec's accepted set must match for
6956 // serialize/deserialize to round-trip without canonical-form
6957 // drift.
6958
6959 #[test]
6960 fn parse_accepts_integer_canonical_units() {
6961 // Pin the happy-path: every canonical author shape `render`
6962 // ever emits parses to the same `Duration` value, so the
6963 // codec's accepted set is at least a superset of its emitted
6964 // set on the canonical-unit axis.
6965 for (lit, dur) in [
6966 ("30s", Duration::from_secs(30)),
6967 ("500ms", Duration::from_millis(500)),
6968 ("2m", Duration::from_secs(120)),
6969 ("1h", Duration::from_secs(3600)),
6970 ("0s", Duration::ZERO),
6971 ] {
6972 assert_eq!(
6973 duration_codec::parse(lit).unwrap(),
6974 dur,
6975 "parse({lit:?}) should be {dur:?}"
6976 );
6977 }
6978 }
6979
6980 #[test]
6981 fn parse_accepts_bare_integer_as_seconds() {
6982 // The `"s" | ""` arm: a bare integer with no unit is read as
6983 // seconds. Pin this so the unit-empty form keeps parsing (it
6984 // renders to `"<n>s"` on serialize — that's a unit-choice
6985 // drift the integer-magnitude gate does NOT close, matching
6986 // the `parse_byte_size` `"1024"` → `"1KiB"` scope decision in
6987 // the peer `:limits :memory` codec).
6988 assert_eq!(
6989 duration_codec::parse("30").unwrap(),
6990 Duration::from_secs(30)
6991 );
6992 }
6993
6994 #[test]
6995 fn parse_rejects_fractional_seconds_with_canonical_form_diagnostic() {
6996 // `"1.5s"` parses as f64 to 1.5 → renders back as `"1500ms"`
6997 // on first serialize — DRIFT. The integer-magnitude gate names
6998 // the offending `"1.5"` verbatim and points at the canonical
6999 // remediation `"1500ms"`.
7000 let err = duration_codec::parse("1.5s").unwrap_err();
7001 assert!(err.contains("\"1.5\""), "missing magnitude in {err:?}");
7002 assert!(
7003 err.contains("not a non-negative integer"),
7004 "missing canonical-form reason in {err:?}"
7005 );
7006 assert!(
7007 err.contains("\"1500ms\""),
7008 "missing canonical-form remediation in {err:?}"
7009 );
7010 }
7011
7012 #[test]
7013 fn parse_rejects_decimal_shaped_integer_seconds() {
7014 // `"1.0s"` is the trickiest drift class: numerically `1.0s` is
7015 // `1s` exactly, so the round-trip looks correct — but the
7016 // emitted canonical form is `"1s"`, not `"1.0s"`. Gate the
7017 // decimal-shape-with-integer-value form so author intent is
7018 // never silently rewritten.
7019 let err = duration_codec::parse("1.0s").unwrap_err();
7020 assert!(err.contains("\"1.0\""), "missing magnitude in {err:?}");
7021 assert!(
7022 err.contains("not a non-negative integer"),
7023 "missing canonical-form reason in {err:?}"
7024 );
7025 }
7026
7027 #[test]
7028 fn parse_rejects_half_unit_minute() {
7029 // `"0.5m"` is the unit-fraction footgun — author writes a
7030 // human-readable half-minute, serde silently rewrites to
7031 // `"30s"` on next emit. The gate names the offending
7032 // magnitude `"0.5"` and points at the integer-in-smaller-unit
7033 // form.
7034 let err = duration_codec::parse("0.5m").unwrap_err();
7035 assert!(err.contains("\"0.5\""), "missing magnitude in {err:?}");
7036 assert!(
7037 err.contains("\"30s\""),
7038 "missing canonical-form remediation in {err:?}"
7039 );
7040 }
7041
7042 #[test]
7043 fn parse_rejects_leading_plus_sign() {
7044 // `u64::from_str` rejects `"+30"` but `f64::from_str` accepts
7045 // it as `30.0` — the prior parser used f64 so `"+30s"` parsed
7046 // cleanly to 30s and round-tripped to `"30s"` on next emit
7047 // (DRIFT). The digit-only gate closes the leading-sign class
7048 // first; the diagnostic names `"+30"` verbatim.
7049 let err = duration_codec::parse("+30s").unwrap_err();
7050 assert!(err.contains("\"+30\""), "missing magnitude in {err:?}");
7051 assert!(
7052 err.contains("not a non-negative integer"),
7053 "missing canonical-form reason in {err:?}"
7054 );
7055 }
7056
7057 #[test]
7058 fn parse_rejects_leading_minus_sign() {
7059 // The former `num < 0.0` arm: `"-30s"` parsed as f64 to -30,
7060 // rejected with `"negative duration in \"-30s\""`. Under the
7061 // integer-magnitude gate the diagnostic is unified — `-30` is
7062 // non-digit-only, f64-numeric, and surfaces with the canonical-
7063 // form reason (no leading `+` / `-` sign) naming the offending
7064 // `"-30"` verbatim. Same diagnostic shape as every other
7065 // rejected non-integer magnitude.
7066 let err = duration_codec::parse("-30s").unwrap_err();
7067 assert!(err.contains("\"-30\""), "missing magnitude in {err:?}");
7068 assert!(
7069 err.contains("not a non-negative integer"),
7070 "missing canonical-form reason in {err:?}"
7071 );
7072 }
7073
7074 #[test]
7075 fn parse_garbage_still_falls_through_to_bad_magnitude() {
7076 // Non-digit-only AND non-numeric (`"--1s"`, `"abc"`) falls
7077 // through to the narrower "bad duration magnitude" arm — the
7078 // canonical-form diagnostic is reserved for the parser-shape
7079 // footgun case, not the "not a number at all" case. Same
7080 // shape `parse_byte_size`'s `BadByteMagnitude` arm carries on
7081 // the peer `:limits :memory` codec.
7082 let err = duration_codec::parse("--1s").unwrap_err();
7083 assert!(
7084 err.contains("bad duration magnitude"),
7085 "expected bad-magnitude wording in {err:?}"
7086 );
7087 }
7088
7089 #[test]
7090 fn parse_digit_only_magnitude_carries_zero_f64_drift() {
7091 // The accepted set is now closed under `u64`-exact integer
7092 // arithmetic: `"500ms"` → `Duration::from_millis(500)` exactly,
7093 // `"3600s"` → `Duration::from_secs(3600)` exactly, `"1h"` →
7094 // `Duration::from_secs(3600)` exactly, no f64 mantissa drift
7095 // possible. Pin the integer-exact arms across the four unit
7096 // suffixes so a future refactor that reaches back for f64
7097 // (`from_secs_f64`, `mul_f64`) surfaces here.
7098 assert_eq!(
7099 duration_codec::parse("3600s").unwrap(),
7100 Duration::from_secs(3600)
7101 );
7102 assert_eq!(
7103 duration_codec::parse("60m").unwrap(),
7104 Duration::from_secs(3600)
7105 );
7106 assert_eq!(
7107 duration_codec::parse("1h").unwrap(),
7108 Duration::from_secs(3600)
7109 );
7110 assert_eq!(
7111 duration_codec::parse("999ms").unwrap(),
7112 Duration::from_millis(999)
7113 );
7114 }
7115
7116 #[test]
7117 fn restart_window_serde_rejects_fractional_seconds() {
7118 // The shared codec backs `SupervisorSpec::restart_window`
7119 // (`with = "duration_codec"`) — so the gate applies on serde
7120 // deserialize for the typed Supervisor slot. A
7121 // `{"restartWindow":"1.5s"}` payload that previously round-
7122 // tripped to a different canonical string on next serialize
7123 // is now refused at deserialize with the integer-magnitude
7124 // diagnostic.
7125 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
7126 "restartWindow":"1.5s",
7127 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
7128 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7129 let msg = err.to_string();
7130 assert!(
7131 msg.contains("not a non-negative integer"),
7132 "expected integer-magnitude diagnostic in {msg:?}"
7133 );
7134 assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
7135 }
7136
7137 #[test]
7138 fn restart_window_serde_rejects_leading_plus() {
7139 // The `u64::from_str` leading-`+` permissiveness gap that
7140 // motivated the digit-only gate (the `f64`-side accepted
7141 // `"+30"`, the prior parser silently round-tripped to `"30s"`)
7142 // is now closed on the shared codec — surfaces as a structured
7143 // diagnostic at the serde layer for every typed-duration slot.
7144 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
7145 "restartWindow":"+30s",
7146 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
7147 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7148 let msg = err.to_string();
7149 assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
7150 assert!(
7151 msg.contains("not a non-negative integer"),
7152 "missing canonical-form reason in {msg:?}"
7153 );
7154 }
7155
7156 #[test]
7157 fn parse_rejects_leading_zero_magnitude() {
7158 // `"030s"` is digit-only, so the existing non-digit-only / sign
7159 // / fractional arm doesn't catch it — `u64::from_str("030")`
7160 // returns `Ok(30)`, so before this gate `"030s"` parsed to
7161 // `Duration::from_secs(30)` and round-tripped through `render`
7162 // to `"30s"` — a *different* canonical string on the next emit,
7163 // breaking the THEORY.md Part V render-determinism contract
7164 // exactly the way `"+30s"` did before the leading-`+` arm
7165 // landed. Peer with the `rate_limit_codec` leading-zero arm
7166 // (4f46830) on the same canonical-form-drift axis.
7167 let err = duration_codec::parse("030s").unwrap_err();
7168 assert!(
7169 err.contains("non-canonical leading zero"),
7170 "expected leading-zero diagnostic in {err:?}"
7171 );
7172 assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
7173 assert!(
7174 err.contains("\"30s\""),
7175 "missing canonical-form remediation in {err:?}"
7176 );
7177 assert!(
7178 err.contains("THEORY.md"),
7179 "missing render-determinism citation in {err:?}"
7180 );
7181 }
7182
7183 #[test]
7184 fn parse_rejects_multi_digit_zero_magnitude() {
7185 // `"00s"` and `"00ms"` are the all-zero leading-zero footgun —
7186 // digit-only, parse losslessly to `Duration::ZERO`, but render
7187 // back to `"0s"` (the single-byte canonical form) on the next
7188 // emit. The leading-zero arm refuses the drift class at the
7189 // codec layer; the semantic-zero gate downstream
7190 // (`SupervisorError::ZeroRestartWindow`, etc.) would refuse
7191 // the single-byte canonical form `"0s"` separately on the
7192 // typed-validate layer.
7193 let err = duration_codec::parse("00s").unwrap_err();
7194 assert!(
7195 err.contains("non-canonical leading zero"),
7196 "expected leading-zero diagnostic in {err:?}"
7197 );
7198 assert!(err.contains("\"00\""), "missing magnitude in {err:?}");
7199 }
7200
7201 #[test]
7202 fn parse_rejects_leading_zero_per_hour_window() {
7203 // `"01h"` is the per-hour-window footgun — multi-byte magnitude
7204 // starting with `0`, parses losslessly to `Duration::from_secs(3600)`,
7205 // renders to `"1h"` (DRIFT). The arm is unit-agnostic: every
7206 // canonical unit suffix the codec accepts (`ms` / `s` / `m` /
7207 // `h` / bare-integer-as-seconds) inherits the same gate.
7208 let err = duration_codec::parse("01h").unwrap_err();
7209 assert!(
7210 err.contains("non-canonical leading zero"),
7211 "expected leading-zero diagnostic in {err:?}"
7212 );
7213 assert!(err.contains("\"01\""), "missing magnitude in {err:?}");
7214 }
7215
7216 #[test]
7217 fn parse_rejects_leading_zero_bare_integer_as_seconds() {
7218 // The `parse_accepts_bare_integer_as_seconds` happy-path
7219 // (`"30"` → 30s) inherits the leading-zero arm: `"030"` is
7220 // multi-byte starts-with-`0`, parses losslessly to
7221 // `Duration::from_secs(30)`, renders to `"30s"` (DRIFT). The
7222 // bare-integer surface accepts permissive unit-empty
7223 // shorthand but still must reject leading-zero padding.
7224 let err = duration_codec::parse("030").unwrap_err();
7225 assert!(
7226 err.contains("non-canonical leading zero"),
7227 "expected leading-zero diagnostic in {err:?}"
7228 );
7229 assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
7230 }
7231
7232 #[test]
7233 fn parse_accepts_single_zero_magnitude_at_codec_layer() {
7234 // The codec-layer / typed-validate-layer boundary: `"0s"` /
7235 // `"0ms"` / `"0"` are the single-byte canonical-zero forms —
7236 // each round-trips losslessly through `render`
7237 // (`render(Duration::ZERO)` → `"0s"`), so the codec layer
7238 // accepts them. The downstream semantic-zero gates
7239 // (`SupervisorError::ZeroRestartWindow`,
7240 // `AplicacaoError::PolicyTimeoutZero`,
7241 // `AplicacaoError::PolicyCircuitBreakerWindowZero`) refuse
7242 // zero-magnitude authoring at the typed-validate layer above,
7243 // peer with the `rate_limit_codec` codec-layer / typed-
7244 // validate-layer partition for `"0/s"`.
7245 assert_eq!(duration_codec::parse("0s").unwrap(), Duration::ZERO);
7246 assert_eq!(duration_codec::parse("0ms").unwrap(), Duration::ZERO);
7247 assert_eq!(duration_codec::parse("0").unwrap(), Duration::ZERO);
7248 }
7249
7250 #[test]
7251 fn parse_accepts_canonical_magnitude_with_leading_one() {
7252 // The complementary boundary: a future tightening cannot
7253 // drift into rejecting valid canonical magnitudes that
7254 // happen to start with `1` (or any digit `[1-9]`). Pin
7255 // every canonical-unit suffix so the leading-zero arm
7256 // remains strictly narrower than the digit-only arm.
7257 assert_eq!(
7258 duration_codec::parse("100ms").unwrap(),
7259 Duration::from_millis(100)
7260 );
7261 assert_eq!(
7262 duration_codec::parse("100s").unwrap(),
7263 Duration::from_secs(100)
7264 );
7265 assert_eq!(
7266 duration_codec::parse("10m").unwrap(),
7267 Duration::from_secs(600)
7268 );
7269 assert_eq!(
7270 duration_codec::parse("10h").unwrap(),
7271 Duration::from_secs(36_000)
7272 );
7273 }
7274
7275 #[test]
7276 fn restart_window_serde_rejects_leading_zero() {
7277 // The shared codec backs `SupervisorSpec::restart_window`
7278 // (`with = "duration_codec"`) — so the leading-zero arm
7279 // applies on serde deserialize for the typed Supervisor slot.
7280 // A `{"restartWindow":"030s"}` payload that previously round-
7281 // tripped to a different canonical string on next serialize
7282 // is now refused at deserialize with the leading-zero
7283 // diagnostic. Peer with `restart_window_serde_rejects_leading_plus`
7284 // / `restart_window_serde_rejects_fractional_seconds` on the
7285 // same canonical-form-drift axis.
7286 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
7287 "restartWindow":"030s",
7288 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
7289 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7290 let msg = err.to_string();
7291 assert!(
7292 msg.contains("non-canonical leading zero"),
7293 "expected leading-zero diagnostic in {msg:?}"
7294 );
7295 assert!(msg.contains("\"030\""), "missing magnitude in {msg:?}");
7296 }
7297
7298 #[test]
7299 fn parse_rejects_leading_whitespace() {
7300 // `" 30s"` — the canonical paste-from-aligned-doc /
7301 // paste-from-YAML-quoted-plain-scalar footgun. Before this
7302 // gate the top-level `s.trim()` at parse entry silently ate
7303 // the leading space and parsed the value to
7304 // `Duration::from_secs(30)`, which then round-tripped through
7305 // `render` to `"30s"` (a *different* canonical string on the
7306 // next emit) — the exact canonical-form-drift class the
7307 // leading-`+` / leading-zero arms already close, extended
7308 // to the whitespace-byte class. Peer with the sibling
7309 // `rate_limit_codec` whitespace-rejection arm (1ad7755) on
7310 // the M3 `:politicas` axis.
7311 let err = duration_codec::parse(" 30s").unwrap_err();
7312 assert!(
7313 err.contains("contains whitespace byte"),
7314 "expected whitespace diagnostic in {err:?}"
7315 );
7316 assert!(err.contains("0x20"), "missing offending byte in {err:?}");
7317 assert!(
7318 err.contains("THEORY.md"),
7319 "missing render-determinism contract citation in {err:?}"
7320 );
7321 }
7322
7323 #[test]
7324 fn parse_rejects_trailing_whitespace() {
7325 // `"30s "` — the canonical shell-history / trailing-space
7326 // paste footgun. Before this gate the top-level `s.trim()`
7327 // silently ate the trailing space and parsed to
7328 // `Duration::from_secs(30)`, round-tripping to `"30s"` on the
7329 // next emit — same canonical-form drift as the leading-space
7330 // sibling, closed on the same whitespace-byte arm.
7331 let err = duration_codec::parse("30s ").unwrap_err();
7332 assert!(
7333 err.contains("contains whitespace byte"),
7334 "expected whitespace diagnostic in {err:?}"
7335 );
7336 assert!(err.contains("0x20"), "missing offending byte in {err:?}");
7337 }
7338
7339 #[test]
7340 fn parse_rejects_internal_whitespace_between_magnitude_and_unit() {
7341 // `"30 s"` — the canonical typographically-spaced author
7342 // shape (the same idiom every prose reference to a duration
7343 // renders as, mistakenly retained when the value is pasted
7344 // into a codec-shaped slot). Before this gate the per-part
7345 // `num_part.trim()` / `unit.trim()` calls silently ate the
7346 // whitespace between the magnitude and the unit and parsed
7347 // the value to `Duration::from_secs(30)`, round-tripping to
7348 // `"30s"` — the codec's *internal* whitespace-tolerance
7349 // vector, orthogonal to the leading / trailing surface but
7350 // the same canonical-form-drift class. Pins the arm as
7351 // strictly stronger than the pre-existing top-level
7352 // `s.trim()` behavior: it fires on whitespace anywhere in
7353 // the value, not just at the string boundary.
7354 let err = duration_codec::parse("30 s").unwrap_err();
7355 assert!(
7356 err.contains("contains whitespace byte"),
7357 "expected whitespace diagnostic in {err:?}"
7358 );
7359 assert!(err.contains("0x20"), "missing offending byte in {err:?}");
7360 }
7361
7362 #[test]
7363 fn parse_rejects_tab_byte() {
7364 // `"\t30s"` — the canonical paste-from-indented-doc /
7365 // paste-from-YAML-block-scalar footgun where a tab byte leads
7366 // the magnitude. Pins that the gate covers tab (`0x09`) as
7367 // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
7368 // members and both would be silently swallowed by `s.trim()`
7369 // pre-gate. The `is_ascii_whitespace` coverage extends beyond
7370 // space alone to the full ASCII-whitespace set (space `0x20`,
7371 // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
7372 // the tab arm as a representative of the non-space members.
7373 let err = duration_codec::parse("\t30s").unwrap_err();
7374 assert!(
7375 err.contains("contains whitespace byte"),
7376 "expected whitespace diagnostic in {err:?}"
7377 );
7378 assert!(
7379 err.contains("0x09"),
7380 "missing offending tab byte in {err:?}"
7381 );
7382 }
7383
7384 #[test]
7385 fn restart_window_serde_rejects_whitespace() {
7386 // The shared codec backs `SupervisorSpec::restart_window`
7387 // (`with = "duration_codec"`) — so the whitespace arm
7388 // applies on serde deserialize for the typed Supervisor slot.
7389 // A `{"restartWindow":" 30s"}` payload that previously round-
7390 // tripped to a different canonical string on next serialize
7391 // is now refused at deserialize with the whitespace-byte
7392 // diagnostic. Peer with `restart_window_serde_rejects_leading_zero`
7393 // / `restart_window_serde_rejects_leading_plus` /
7394 // `restart_window_serde_rejects_fractional_seconds` on the
7395 // same canonical-form-drift axis.
7396 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
7397 "restartWindow":" 30s",
7398 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
7399 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7400 let msg = err.to_string();
7401 assert!(
7402 msg.contains("contains whitespace byte"),
7403 "expected whitespace diagnostic in {msg:?}"
7404 );
7405 assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
7406 }
7407
7408 // ── canonical-form: non-ASCII Unicode `White_Space` duration gate ─────
7409 //
7410 // Successor to the ASCII-whitespace arm (a7ae622) on the shared
7411 // duration codec — closes the strictly-complementary class the
7412 // byte-scan cannot see, through the lifted
7413 // [`crate::render::find_non_ascii_whitespace_char`] predicate.
7414 // Applies to `:supervisor :restart-window`, `:politicas :timeout`,
7415 // and `:politicas :circuit-breaker :window` simultaneously via
7416 // this shared codec.
7417
7418 #[test]
7419 fn duration_codec_parse_rejects_leading_nbsp() {
7420 // NBSP prefix — the strictly-complementary drift class the
7421 // ASCII byte-scan cannot see. `str::trim` strips it silently
7422 // and the value drifts to `"30s"` on next serialize.
7423 let err = duration_codec::parse("\u{00A0}30s").unwrap_err();
7424 assert!(
7425 err.contains("non-ASCII Unicode whitespace character"),
7426 "expected non-ASCII whitespace diagnostic in {err:?}"
7427 );
7428 assert!(err.contains("U+00A0"), "missing codepoint in {err:?}");
7429 }
7430
7431 #[test]
7432 fn duration_codec_parse_rejects_trailing_line_separator() {
7433 // LINE SEPARATOR (`\u{2028}`) trailing — paste-from-web-doc
7434 // footgun.
7435 let err = duration_codec::parse("30s\u{2028}").unwrap_err();
7436 assert!(
7437 err.contains("non-ASCII Unicode whitespace character"),
7438 "expected non-ASCII whitespace diagnostic in {err:?}"
7439 );
7440 assert!(err.contains("U+2028"), "missing codepoint in {err:?}");
7441 }
7442
7443 #[test]
7444 fn duration_codec_parse_accepts_ascii_only_forms_after_unicode_arm() {
7445 // Positive-control pin: every ASCII-only canonical form the
7446 // renderer emits stays accepted through the new arm.
7447 assert_eq!(
7448 duration_codec::parse("30s").unwrap(),
7449 Duration::from_secs(30)
7450 );
7451 assert_eq!(
7452 duration_codec::parse("500ms").unwrap(),
7453 Duration::from_millis(500)
7454 );
7455 assert_eq!(
7456 duration_codec::parse("1h").unwrap(),
7457 Duration::from_secs(3600)
7458 );
7459 }
7460
7461 #[test]
7462 fn restart_window_serde_rejects_non_ascii_whitespace() {
7463 // The shared codec backs `SupervisorSpec::restart_window` — so
7464 // the new non-ASCII Unicode whitespace arm applies on serde
7465 // deserialize for the typed Supervisor slot. A
7466 // `{"restartWindow":" 30s"}` payload that previously
7467 // survived the ASCII byte-scan (only ASCII whitespace was
7468 // refused) is now refused at deserialize with the
7469 // non-ASCII-whitespace-and-codepoint diagnostic.
7470 let payload = "{\"estrategia\":\"OneForOne\",\"maxRestarts\":5,\
7471 \"restartWindow\":\"\u{00A0}30s\",\
7472 \"children\":[{\"caixa\":\"w\",\"versao\":\"^0.1\",\"restart\":\"Permanent\"}]}";
7473 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7474 let msg = err.to_string();
7475 assert!(
7476 msg.contains("non-ASCII Unicode whitespace character"),
7477 "expected non-ASCII whitespace diagnostic in {msg:?}"
7478 );
7479 assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
7480 }
7481
7482 // ── drift-detection: serde-derive-to-SUPERVISOR_KEY_* identity ────────
7483
7484 #[test]
7485 fn supervisor_spec_serde_keys_match_lifted_supervisor_key_consts() {
7486 // Load-bearing invariant: the four `SUPERVISOR_KEY_*` consts
7487 // (`SUPERVISOR_KEY_ESTRATEGIA` / `SUPERVISOR_KEY_MAX_RESTARTS` /
7488 // `SUPERVISOR_KEY_RESTART_WINDOW` / `SUPERVISOR_KEY_CHILDREN`)
7489 // name the exact camelCase JSON keys the
7490 // `#[serde(rename_all = "camelCase")]` attribute on
7491 // `SupervisorSpec` emits. Serialize a fully-populated spec (each
7492 // field carries `Some(_)` / non-empty) and pin that each canonical
7493 // byte-sequence appears verbatim in the JSON — a future accidental
7494 // `rename_all = "snake_case"` / `"kebab-case"` / verbatim-field-
7495 // name flip at the derive attribute (any of which would silently
7496 // break every downstream JSON consumer that reaches for one of the
7497 // four consts via `Value::get(...)`) surfaces here as a build-time
7498 // test failure at `supervisor.rs`, not as an apply-time
7499 // `.get(<stale-canonical-const>)` returning `None` far from the
7500 // derive-attr drift's commit. Peer with the sibling
7501 // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
7502 // (d8b8b4f) pin on the M2 `:limits` axis — same discipline the
7503 // M2 typed-slot family established, extended here to close the
7504 // top-level Supervisor axis.
7505 let spec = SupervisorSpec {
7506 estrategia: RestartStrategy::OneForOne,
7507 max_restarts: 5,
7508 restart_window: Some(Duration::from_secs(60)),
7509 children: vec![ChildSpec {
7510 caixa: "w".into(),
7511 versao: "^0.1".into(),
7512 restart: RestartPolicy::Permanent,
7513 }],
7514 };
7515 let json = serde_json::to_string(&spec).unwrap();
7516 for key in [
7517 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7518 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7519 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7520 crate::render::SUPERVISOR_KEY_CHILDREN,
7521 ] {
7522 let quoted = format!("\"{key}\"");
7523 assert!(
7524 json.contains("ed),
7525 "serialized SupervisorSpec must carry the lifted \
7526 SUPERVISOR_KEY_* byte-sequence {quoted} verbatim in \
7527 the JSON emission (got: {json})",
7528 );
7529 }
7530 }
7531
7532 #[test]
7533 fn supervisor_key_consts_are_pairwise_distinct() {
7534 // Cross-axis drift-detection pin: a future collapse of two
7535 // canonical top-level byte-strings onto the same value (e.g. an
7536 // accidental copy-paste flip of `SUPERVISOR_KEY_CHILDREN` to
7537 // also read `"estrategia"`) would silently reroute every
7538 // downstream probe on one axis onto the sibling axis's overlay
7539 // entry and pass every propagation-probe test that expected only
7540 // the stale axis's value. Peer of the sibling four-way distinct
7541 // pin on the `M2_LIMITS_KEY_*` tetrad (d8b8b4f).
7542 let all = [
7543 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7544 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7545 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7546 crate::render::SUPERVISOR_KEY_CHILDREN,
7547 ];
7548 for (i, a) in all.iter().enumerate() {
7549 for b in all.iter().skip(i + 1) {
7550 assert_ne!(
7551 a, b,
7552 "SUPERVISOR_KEY_* consts must be pairwise-distinct \
7553 canonical byte-sequences — got `{a}` == `{b}`",
7554 );
7555 }
7556 }
7557 }
7558
7559 #[test]
7560 fn supervisor_key_consts_are_lower_camel_case_shape() {
7561 // Shape-pin: every `SUPERVISOR_KEY_*` const must be a
7562 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
7563 // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
7564 // capital, no whitespace / dots) — the canonical shape the
7565 // `#[serde(rename_all = "camelCase")]` derive produces on
7566 // `SupervisorSpec`. A future flip to a non-camelCase attribute
7567 // at the derive surfaces both here (this test fails on the
7568 // stale-constant shape) and at
7569 // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
7570 // (that test fails on the mismatch between const and derive).
7571 // Peer with `m2_limits_key_consts_are_lower_camel_case_shape`
7572 // (d8b8b4f) on the sibling M2 `:limits` axis.
7573 for key in [
7574 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7575 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7576 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7577 crate::render::SUPERVISOR_KEY_CHILDREN,
7578 ] {
7579 assert!(
7580 !key.is_empty(),
7581 "SUPERVISOR_KEY_* must be non-empty (got {key:?})"
7582 );
7583 let first = key.chars().next().unwrap();
7584 assert!(
7585 first.is_ascii_lowercase(),
7586 "SUPERVISOR_KEY_* must lead with an ASCII-lowercase byte \
7587 (got {key:?}, leads with {first:?})",
7588 );
7589 assert!(
7590 key.chars().all(|c| c.is_ascii_alphanumeric()),
7591 "SUPERVISOR_KEY_* must be ASCII-alphanumeric only \
7592 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
7593 );
7594 }
7595 }
7596
7597 #[test]
7598 fn supervisor_key_consts_are_byte_distinct_from_supervisor_author_key_peers() {
7599 // Cross-axis drift pin: the four `SUPERVISOR_KEY_*` consts
7600 // (camelCase JSON keys, no leading colon) must never collide
7601 // byte-for-byte with the four peer `SUPERVISOR_AUTHOR_KEY_*`
7602 // consts (kebab-case author-facing labels with leading colon)
7603 // that sit next to them at `caixa_core::render`. Both families
7604 // cover the same four typed Supervisor slots on two distinct
7605 // axes (author-side kebab vs renderer-side camelCase);
7606 // collapsing either family onto the other's byte-shape would
7607 // silently reroute the render-side probe onto the author-facing
7608 // surface, or vice versa. Peer of the byte-distinctness
7609 // discipline the `M3_PLACEMENT_KEY_ESTRATEGIA` docstring names
7610 // against the peer `M3_AUTHOR_KEY_PLACEMENT`.
7611 let pairs = [
7612 (
7613 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7614 crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA,
7615 ),
7616 (
7617 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7618 crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS,
7619 ),
7620 (
7621 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7622 crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW,
7623 ),
7624 (
7625 crate::render::SUPERVISOR_KEY_CHILDREN,
7626 crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN,
7627 ),
7628 ];
7629 for (json_key, author_key) in pairs {
7630 assert_ne!(
7631 json_key, author_key,
7632 "SUPERVISOR_KEY_* (JSON side) must differ byte-for-byte \
7633 from the peer SUPERVISOR_AUTHOR_KEY_* (author side); \
7634 got JSON `{json_key}` == author `{author_key}`",
7635 );
7636 }
7637 }
7638
7639 // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_KEY_* identity ──
7640
7641 #[test]
7642 fn child_spec_serde_keys_match_lifted_supervisor_child_key_consts() {
7643 // Load-bearing invariant: the three `SUPERVISOR_CHILD_KEY_*` consts
7644 // (`SUPERVISOR_CHILD_KEY_CAIXA` / `SUPERVISOR_CHILD_KEY_VERSAO` /
7645 // `SUPERVISOR_CHILD_KEY_RESTART`) name the exact camelCase JSON
7646 // keys the `#[serde(rename_all = "camelCase")]` attribute on
7647 // `ChildSpec` emits. Serialize a fully-populated `ChildSpec` and
7648 // pin that each canonical byte-sequence appears verbatim in the
7649 // JSON — a future accidental `rename_all = "snake_case"` /
7650 // `"kebab-case"` / verbatim-field-name flip at the derive
7651 // attribute (any of which would silently break every downstream
7652 // JSON consumer that reaches for one of the three consts via
7653 // `Value::get(...)`) surfaces here as a build-time test failure at
7654 // `supervisor.rs`, not as an apply-time
7655 // `.get(<stale-canonical-const>)` returning `None` far from the
7656 // derive-attr drift's commit. Peer with the enclosing
7657 // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
7658 // (40cc4e5) pin on the M2 supervision-tree top-level axis — same
7659 // discipline the SupervisorSpec top-level lift established,
7660 // extended here to the sibling per-`:children` entry `ChildSpec`
7661 // derive so the last M2 typed-struct sub-block
7662 // `#[serde(rename_all = "camelCase")]` axis on the Supervisor
7663 // surface without a lifted serde-key peer joins the substrate's
7664 // "one canonical byte-string per typed serialized-key axis"
7665 // discipline.
7666 let c = ChildSpec {
7667 caixa: "worker".into(),
7668 versao: "^0.1".into(),
7669 restart: RestartPolicy::Permanent,
7670 };
7671 let json = serde_json::to_string(&c).unwrap();
7672 for key in [
7673 crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
7674 crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
7675 crate::render::SUPERVISOR_CHILD_KEY_RESTART,
7676 ] {
7677 let quoted = format!("\"{key}\"");
7678 assert!(
7679 json.contains("ed),
7680 "serialized ChildSpec must carry the lifted \
7681 SUPERVISOR_CHILD_KEY_* byte-sequence {quoted} verbatim \
7682 in the JSON emission (got: {json})",
7683 );
7684 }
7685 }
7686
7687 #[test]
7688 fn supervisor_child_key_consts_are_pairwise_distinct() {
7689 // Cross-axis drift-detection pin: a future collapse of two
7690 // canonical `ChildSpec` per-entry byte-strings onto the same
7691 // value (e.g. an accidental copy-paste flip of
7692 // `SUPERVISOR_CHILD_KEY_RESTART` to also read `"caixa"`) would
7693 // silently reroute every downstream probe on one axis onto the
7694 // sibling axis's overlay entry and pass every propagation-probe
7695 // test that expected only the stale axis's value. Peer of the
7696 // sibling three-way distinct pin on the `CONTRATO_KEY_*` triad
7697 // (ca463a4) and the two-way distinct pin on the `MEMBRO_KEY_*`
7698 // pair (ce80ca0).
7699 let all = [
7700 crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
7701 crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
7702 crate::render::SUPERVISOR_CHILD_KEY_RESTART,
7703 ];
7704 for (i, a) in all.iter().enumerate() {
7705 for b in all.iter().skip(i + 1) {
7706 assert_ne!(
7707 a, b,
7708 "SUPERVISOR_CHILD_KEY_* consts must be pairwise-\
7709 distinct canonical byte-sequences — got `{a}` == `{b}`",
7710 );
7711 }
7712 }
7713 }
7714
7715 #[test]
7716 fn supervisor_child_key_consts_are_lower_camel_case_shape() {
7717 // Shape-pin: every `SUPERVISOR_CHILD_KEY_*` const must be a
7718 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
7719 // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
7720 // capital, no whitespace / dots) — the canonical shape the
7721 // `#[serde(rename_all = "camelCase")]` derive produces on
7722 // `ChildSpec`. A future flip to a non-camelCase attribute at the
7723 // derive surfaces both here (this test fails on the
7724 // stale-constant shape) and at
7725 // `child_spec_serde_keys_match_lifted_supervisor_child_key_consts`
7726 // (that test fails on the mismatch between const and derive).
7727 // Peer with `supervisor_key_consts_are_lower_camel_case_shape`
7728 // (40cc4e5) on the sibling `SupervisorSpec` top-level axis.
7729 for key in [
7730 crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
7731 crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
7732 crate::render::SUPERVISOR_CHILD_KEY_RESTART,
7733 ] {
7734 assert!(
7735 !key.is_empty(),
7736 "SUPERVISOR_CHILD_KEY_* must be non-empty (got {key:?})"
7737 );
7738 let first = key.chars().next().unwrap();
7739 assert!(
7740 first.is_ascii_lowercase(),
7741 "SUPERVISOR_CHILD_KEY_* must lead with an ASCII-lowercase \
7742 byte (got {key:?}, leads with {first:?})",
7743 );
7744 assert!(
7745 key.chars().all(|c| c.is_ascii_alphanumeric()),
7746 "SUPERVISOR_CHILD_KEY_* must be ASCII-alphanumeric only \
7747 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
7748 );
7749 }
7750 }
7751
7752 // ── drift-detection: serde-derive-to-SUPERVISOR_ESTRATEGIA_* identity ────
7753
7754 #[test]
7755 fn restart_strategy_variants_serialize_to_lifted_scalar_values() {
7756 // The fail-before-pass-after pin: pre-lift there was no
7757 // single-source binding between the [`RestartStrategy`] variant
7758 // name the un-`rename`d `Serialize` derive emits under
7759 // [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the byte-string
7760 // every downstream cluster-side dispatcher (the future
7761 // wasm-operator's per-supervisor sibling-restart branch, the
7762 // future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
7763 // admission-time enum-arm bind, the `caixa-operator`'s
7764 // hierarchical reconciliation scheduler's per-strategy fan-out)
7765 // probes verbatim. A future `#[serde(rename_all = "kebab-case")]`
7766 // attribute on the enum — or a per-variant `#[serde(rename = "…")]`
7767 // override, or a variant rename in the source — would silently
7768 // rebrand the emitted scalar under one spelling while every
7769 // downstream dispatcher still probed the other, with the failure
7770 // surfacing at the operator's reconcile posture (subtrees coming
7771 // up under the `default()` `OneForOne` arm rather than the typed
7772 // slot's declared strategy — a bad child would then only take
7773 // itself down instead of the sibling set the author intended, so
7774 // shared-state children fall out of sync) far from the source
7775 // rebrand commit and with no field naming the drift. Pinning the
7776 // two paths (the `Serialize` derive's serialized string AND the
7777 // [`RestartStrategy::as_str`] helper) to the same four lifted
7778 // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
7779 // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
7780 // [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
7781 // [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
7782 // byte-strings makes any future drift on either endpoint fail
7783 // here at caixa-core build time. Peer of the M3
7784 // `placement_strategy_variants_serialize_to_lifted_scalar_values`
7785 // (3f0e21c) on the sibling `PlacementStrategy` axis — same
7786 // three-path-convergence discipline, extended to close the
7787 // OTP-shaped per-supervisor sibling-restart axis.
7788 for (variant, expected) in [
7789 (
7790 RestartStrategy::OneForOne,
7791 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7792 ),
7793 (
7794 RestartStrategy::OneForAll,
7795 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7796 ),
7797 (
7798 RestartStrategy::RestForOne,
7799 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7800 ),
7801 (
7802 RestartStrategy::SimpleOneForOne,
7803 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7804 ),
7805 ] {
7806 let json = serde_json::to_string(&variant).unwrap();
7807 assert_eq!(
7808 json,
7809 format!("\"{expected}\""),
7810 "RestartStrategy::{variant:?} must serialize to {expected:?}"
7811 );
7812 assert_eq!(
7813 variant.as_str(),
7814 expected,
7815 "RestartStrategy::{variant:?}.as_str() must return the lifted \
7816 SUPERVISOR_ESTRATEGIA_* constant"
7817 );
7818 }
7819 }
7820
7821 #[test]
7822 fn supervisor_estrategia_consts_are_pairwise_distinct() {
7823 // Cross-arm drift-detection pin: a future collapse of two
7824 // canonical variant byte-strings onto the same value (e.g. an
7825 // accidental copy-paste flip of `SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`
7826 // to also read `"OneForOne"`) would silently reroute every
7827 // downstream operator's per-strategy dispatch onto the sibling
7828 // arm's reconcile branch and pass every propagation-probe test
7829 // that expected only the stale arm's value — the mis-strategied
7830 // subtree would come up with the wrong sibling-restart posture
7831 // on every subsequent failure. Peer of the sibling four-way
7832 // distinct pin `supervisor_key_consts_are_pairwise_distinct`
7833 // (40cc4e5) on the top-level `SUPERVISOR_KEY_*` axis.
7834 let all = [
7835 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7836 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7837 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7838 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7839 ];
7840 for (i, a) in all.iter().enumerate() {
7841 for (j, b) in all.iter().enumerate() {
7842 if i != j {
7843 assert_ne!(
7844 a, b,
7845 "SUPERVISOR_ESTRATEGIA_* consts must be pairwise distinct \
7846 — got duplicate {a:?} at indices {i} and {j}",
7847 );
7848 }
7849 }
7850 }
7851 }
7852
7853 #[test]
7854 fn restart_strategy_display_routes_through_as_str_helper() {
7855 // The fail-before-pass-after pin on the first half of the
7856 // three-path convergence: pre-convergence the sibling
7857 // OTP-shape typed enum [`RestartStrategy`] carried a
7858 // [`std::fmt::Display`] surface via its
7859 // `#[discriminant(also_display)]` gen-platform derive route,
7860 // which arrived kebab-case as `"one-for-one"` /
7861 // `"one-for-all"` / `"rest-for-one"` /
7862 // `"simple-one-for-one"` while the wire format ran as
7863 // PascalCase `"OneForOne"` / `"OneForAll"` / `"RestForOne"` /
7864 // `"SimpleOneForOne"` through the un-`rename`d serde derive.
7865 // Every consumer reaching for a strategy byte-string past the
7866 // wire format had to pick between three paths
7867 // ([`RestartStrategy::as_str`], the `Serialize` derive's
7868 // serialized string, or `format!("{v}")` on the
7869 // discriminant-Display route), any two of which a future
7870 // variant rename or `#[serde(rename_all = "kebab-case")]`
7871 // attribute would silently desynchronize. Wiring
7872 // [`std::fmt::Display`] through [`RestartStrategy::as_str`]
7873 // closes the third path: every `format!("{v}")` call reaches
7874 // the same lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
7875 // const the wire format and the [`RestartStrategy::as_str`]
7876 // helper already route through, so a future variant rename
7877 // lands at exactly one place. Pin the routing here so a future
7878 // `impl std::fmt::Display for RestartStrategy`
7879 // reimplementation that hand-rolls the arms instead of
7880 // delegating to [`RestartStrategy::as_str`] fails at
7881 // caixa-core build time. Peer of the M3
7882 // `placement_strategy_display_routes_through_as_str_helper`
7883 // (cc8f749) which the M3 axis converged first.
7884 for &variant in RestartStrategy::ALL {
7885 assert_eq!(
7886 variant.to_string(),
7887 variant.as_str(),
7888 "RestartStrategy::{variant:?} Display must route through \
7889 RestartStrategy::as_str (single source of truth: the lifted \
7890 SUPERVISOR_ESTRATEGIA_* const the wire format also emits)"
7891 );
7892 }
7893 }
7894
7895 #[test]
7896 fn restart_strategy_display_matches_serialized_wire_byte_string() {
7897 // The fail-before-pass-after pin on the second half of the
7898 // three-path convergence: `Display` (user-facing text) agrees
7899 // byte-for-byte with the `Serialize` derive's wire format
7900 // (canonical camelCase-schema `SUPERVISOR_KEY_ESTRATEGIA`
7901 // scalar) on every variant. Pre-convergence the two paths
7902 // were structurally independent — a future
7903 // `#[serde(rename_all = "kebab-case")]` attribute on the
7904 // enum would silently rebrand the emitted wire scalar
7905 // (`one-for-one`, `one-for-all`, `rest-for-one`,
7906 // `simple-one-for-one`) while every consumer that
7907 // pretty-prints the strategy (the future wasm-operator's
7908 // per-supervisor sibling-restart-strategy diagnostic line,
7909 // the future `feira app graph` per-supervisor strategy line,
7910 // the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
7911 // materializer's admission-webhook rejection body) would
7912 // still emit the PascalCase form the `as_str` / `Display`
7913 // route returns, with the mismatch surfacing at consumer
7914 // parse time / operator dispatch time far from the source
7915 // rebrand commit. Pin the two paths byte-for-byte here so any
7916 // future serde-attribute or variant-rename drift is a
7917 // caixa-core-build-time test failure at this call, not a
7918 // silent per-consumer dispatch miss. Peer of the M3
7919 // `placement_strategy_display_matches_serialized_wire_byte_string`
7920 // (cc8f749) which the M3 axis converged first.
7921 for &variant in RestartStrategy::ALL {
7922 let wire = serde_json::to_string(&variant).unwrap();
7923 let unquoted = wire
7924 .strip_prefix('"')
7925 .and_then(|s| s.strip_suffix('"'))
7926 .expect("serialized RestartStrategy is a JSON string");
7927 assert_eq!(
7928 variant.to_string(),
7929 unquoted,
7930 "RestartStrategy::{variant:?} Display byte-string must match the \
7931 Serialize derive's wire byte-string (three-path convergence: \
7932 Display + as_str + Serialize all resolve to the same \
7933 SUPERVISOR_ESTRATEGIA_* const)"
7934 );
7935 }
7936 }
7937
7938 #[test]
7939 fn restart_strategy_as_ref_str_routes_through_as_str_accessor() {
7940 // Fail-before-pass-after byte-parity pin on the lifted
7941 // `impl AsRef<str> for RestartStrategy` — asserts the
7942 // standard-library trait impl and the substrate-primitive
7943 // [`RestartStrategy::as_str`] `pub const fn` accessor resolve
7944 // to the same `&str` per instance across the four-arm
7945 // closed set, so any future silent detour that routes the
7946 // impl through a divergent projection (a per-arm inline
7947 // `match self { RestartStrategy::OneForOne => "OneForOne", … }`
7948 // re-inlining that opens a compile-time link to the un-lifted
7949 // arm-literal, a swap onto the kebab-case
7950 // [`gen_platform::Discriminant`] catalog identity that would
7951 // collide the wire axis with the dispatcher-catalog axis) trips
7952 // at caixa-core test time under `PartialEq` rather than at a
7953 // downstream `impl AsRef<str>`-bound consumer's silent split.
7954 // Sweeps every one of the four arms
7955 // [`RestartStrategy::ALL`] carries so no arm's projection is
7956 // covered only by the sibling wire-format `Serialize` derive
7957 // path. Peer of the sibling
7958 // [`crate::version::tests::caixa_version_as_ref_str_routes_through_as_str_accessor`]
7959 // (16d5c7e) `AsRef<str>`-byte-parity pin on the paired
7960 // top-level `:versao` typed newtype — the two pins together
7961 // cover the substrate primitive's `AsRef<str>` projection axis
7962 // on the paired newtype + closed-set-typed-enum surface.
7963 for &variant in RestartStrategy::ALL {
7964 assert_eq!(
7965 <RestartStrategy as AsRef<str>>::as_ref(&variant),
7966 variant.as_str(),
7967 "AsRef<str> impl on RestartStrategy::{variant:?} must \
7968 byte-equal RestartStrategy::as_str on the same instance \
7969 — divergence signals a silent detour off the substrate-\
7970 primitive accessor"
7971 );
7972 }
7973 }
7974
7975 #[test]
7976 fn restart_strategy_as_ref_str_routes_through_display_via_shared_accessor() {
7977 // Fail-before-pass-after byte-parity pin on the three-path
7978 // convergence discipline the M2 sibling-restart primitive now
7979 // carries on the `&str`-projection axis:
7980 // `<RestartStrategy as AsRef<str>>::as_ref(&s)` (the newly
7981 // lifted impl), `format!("{s}")` (the pre-existing
7982 // [`fmt::Display`] impl), and `s.as_str()` (the substrate-
7983 // primitive `pub const fn` accessor both trait impls delegate
7984 // through) must resolve to the same byte-string on every
7985 // instance across the four-arm closed set. Refuses any future
7986 // divergence between the two trait impls (a stray
7987 // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
7988 // rather than delegating through the shared accessor; a
7989 // hypothetical `AsRef<str>` rewrite that inlines a per-arm
7990 // literal cascade) that would silently split the two
7991 // projection paths of the same closed-set typed enum. Mirrors
7992 // the sibling three-path-convergence discipline the peer
7993 // [`crate::CaixaVersion`] typed newtype carries on its
7994 // `AsRef<str>` / `Display` / `as_str` triple
7995 // (version.rs pin
7996 // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
7997 // 16d5c7e).
7998 for &variant in RestartStrategy::ALL {
7999 let via_as_ref: &str = <RestartStrategy as AsRef<str>>::as_ref(&variant);
8000 let via_display: String = format!("{variant}");
8001 let via_accessor: &str = variant.as_str();
8002 assert_eq!(via_as_ref, via_accessor);
8003 assert_eq!(via_display, via_accessor);
8004 assert_eq!(via_as_ref, via_display.as_str());
8005 }
8006 }
8007
8008 #[test]
8009 fn restart_strategy_all_enumerates_every_variant_exactly_once() {
8010 // Fail-before-pass-after pin on the [`RestartStrategy::ALL`]
8011 // exhaustive-iteration surface: every variant appears exactly
8012 // once, and the slice length matches the arm count of the
8013 // closed set. Every consumer that walks the accepted-strategy
8014 // set (a future `feira supervisor --estrategia …` CLI-side
8015 // arg-parse's "did you mean" hint, a future M4 admission-
8016 // webhook's rejection body naming the accepted-`:estrategia`
8017 // list, the [`RestartStrategy::from_wire`] reverse-projection
8018 // consumers that iterate the accept-set for diagnostic
8019 // rendering) reads through this slice, so a future arm addition
8020 // that grows the enum but forgets to grow [`Self::ALL`]
8021 // silently truncates every downstream consumer's accept-set at
8022 // the same pre-addition boundary — this pin fails at caixa-core
8023 // build time on the pairwise-distinct + arm-count invariants.
8024 //
8025 // Peer of the sibling [`crate::CaixaKind::ALL`] (6b1f4fb) /
8026 // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
8027 // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
8028 // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
8029 // pins on the peer closed-set typed-enum axes.
8030 let all: &[RestartStrategy] = RestartStrategy::ALL;
8031 assert_eq!(
8032 all.len(),
8033 4,
8034 "RestartStrategy::ALL must enumerate every variant of the \
8035 four-arm closed set (OneForOne, OneForAll, RestForOne, \
8036 SimpleOneForOne); got {all:?}"
8037 );
8038 for (i, a) in all.iter().enumerate() {
8039 for (j, b) in all.iter().enumerate() {
8040 if i != j {
8041 assert_ne!(
8042 a, b,
8043 "RestartStrategy::ALL must carry every variant exactly \
8044 once — got duplicate {a:?} at indices {i} and {j}"
8045 );
8046 }
8047 }
8048 }
8049 for variant in [
8050 RestartStrategy::OneForOne,
8051 RestartStrategy::OneForAll,
8052 RestartStrategy::RestForOne,
8053 RestartStrategy::SimpleOneForOne,
8054 ] {
8055 assert!(
8056 all.contains(&variant),
8057 "RestartStrategy::ALL must contain {variant:?} — a future arm \
8058 addition that grows the enum but forgets to grow the ALL slice \
8059 silently truncates every downstream consumer's accept-set at \
8060 the pre-addition boundary"
8061 );
8062 }
8063 }
8064
8065 #[test]
8066 fn restart_strategy_from_wire_accepts_every_lifted_constant() {
8067 // Fail-before-pass-after pin on the forward accept-set of the
8068 // [`RestartStrategy::from_wire`] reverse projection: every
8069 // canonical [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
8070 // constant the [`RestartStrategy::as_str`] emitter walks parses
8071 // back to its paired variant. Any future arm addition that
8072 // grows the emitter's `as_str` match but forgets to grow the
8073 // parser's `from_wire` match silently splits the two halves of
8074 // the round-trip — the wire byte-string one non-serde consumer
8075 // parses from the one the emitter wrote — with the failure
8076 // surfacing at parse time far from the rebrand commit. Pinning
8077 // the four-arm accept-set here catches the drift at caixa-core
8078 // build time.
8079 //
8080 // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
8081 // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
8082 // accept-set pins on the peer closed-set typed-enum `str → Self`
8083 // axes.
8084 for (wire, expected) in [
8085 (
8086 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8087 RestartStrategy::OneForOne,
8088 ),
8089 (
8090 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8091 RestartStrategy::OneForAll,
8092 ),
8093 (
8094 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8095 RestartStrategy::RestForOne,
8096 ),
8097 (
8098 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8099 RestartStrategy::SimpleOneForOne,
8100 ),
8101 ] {
8102 let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
8103 panic!(
8104 "RestartStrategy::from_wire({wire:?}) must accept every \
8105 SUPERVISOR_ESTRATEGIA_* constant — got None for the \
8106 lifted canonical byte-string that RestartStrategy::{expected:?} \
8107 serializes as under SUPERVISOR_KEY_ESTRATEGIA"
8108 )
8109 });
8110 assert_eq!(
8111 parsed, expected,
8112 "RestartStrategy::from_wire({wire:?}) must return \
8113 RestartStrategy::{expected:?}; got RestartStrategy::{parsed:?}"
8114 );
8115 }
8116 }
8117
8118 #[test]
8119 fn restart_strategy_from_wire_round_trips_through_as_str() {
8120 // Fail-before-pass-after pin on the closed round-trip between
8121 // the forward [`RestartStrategy::as_str`] emitter and the
8122 // reverse [`RestartStrategy::from_wire`] parser: for every
8123 // variant in [`RestartStrategy::ALL`], parsing the emitter's
8124 // output must return exactly the same variant. Any per-arm
8125 // divergence — a future arm added to `as_str` but not
8126 // `from_wire`, an accidental copy-paste flip in one but not
8127 // the other — silently splits the emit and parse halves and
8128 // the failure surfaces at consumer parse time far from the
8129 // drift site. The `ALL`-iterating shape means a future arm
8130 // addition picks up the coverage by construction.
8131 //
8132 // Peer of the sibling
8133 // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
8134 // (18c7342) round-trip pin on
8135 // [`crate::aplicacao::PlacementStrategy::from_wire`] and
8136 // [`crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`]
8137 // (6b1f4fb) round-trip pin on [`crate::CaixaKind::from_wire`].
8138 for &variant in RestartStrategy::ALL {
8139 let wire = variant.as_str();
8140 let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
8141 panic!(
8142 "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
8143 must be Some({variant:?}) — the two halves of the round-trip \
8144 dispatch on the same lifted SUPERVISOR_ESTRATEGIA_* consts; \
8145 got None on wire byte-string {wire:?}"
8146 )
8147 });
8148 assert_eq!(
8149 parsed, variant,
8150 "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
8151 must round-trip to the same variant; got {parsed:?}"
8152 );
8153 }
8154 }
8155
8156 #[test]
8157 fn restart_strategy_from_wire_rejects_unknown_byte_strings() {
8158 // Fail-before-pass-after pin on the closed-set refusal
8159 // discipline of [`RestartStrategy::from_wire`]: every
8160 // byte-string outside the four-arm accept-set returns `None`
8161 // rather than silently collapsing onto the [`Default`]
8162 // (`OneForOne`) arm or an arbitrary neighbor. The refusal set
8163 // exercised here sweeps the load-bearing drift shapes: the
8164 // empty string (a stripped serde-attribute drift), all-
8165 // whitespace strings (the canonical text-editor accidental
8166 // padding shape), the kebab-case dispatcher-catalog identities
8167 // (`"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
8168 // `"simple-one-for-one"` — the [`gen_platform::FromStrKind`]-
8169 // derived [`std::str::FromStr`] accept-set, which parses the
8170 // *other* axis of this enum's two-axis split and must not leak
8171 // into the `from_wire` PascalCase-wire accept-set), the
8172 // lowercased single-word forms (`"oneforone"`), the padded
8173 // canonical scalar (`" OneForOne "`), the trailing-newline
8174 // shapes (`"OneForOne\n"`), and neighboring-but-unknown arms
8175 // (`"AllForOne"` — the canonical typo direction).
8176 //
8177 // Peer of the sibling
8178 // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
8179 // (2aa6d23) +
8180 // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
8181 // (18c7342) refusal pins on the peer closed-set typed-enum
8182 // axes.
8183 for bad in [
8184 "",
8185 " ",
8186 "\n",
8187 "\t",
8188 "one-for-one",
8189 "one-for-all",
8190 "rest-for-one",
8191 "simple-one-for-one",
8192 "oneforone",
8193 "OneForOnes",
8194 "one_for_one",
8195 "one for one",
8196 "ONEFORONE",
8197 "OneForOne ",
8198 " OneForOne",
8199 " SimpleOneForOne ",
8200 "OneForOne\n",
8201 "restforone",
8202 "REST_FOR_ONE",
8203 "AllForOne",
8204 "Simple",
8205 "?",
8206 ] {
8207 assert!(
8208 RestartStrategy::from_wire(bad).is_none(),
8209 "RestartStrategy::from_wire({bad:?}) must return None — the \
8210 parser's accept-set is exactly the four RestartStrategy::as_str \
8211 outputs (OneForOne, OneForAll, RestForOne, SimpleOneForOne), \
8212 and this byte-string is outside that closed set"
8213 );
8214 }
8215 }
8216
8217 #[test]
8218 fn restart_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
8219 // Fail-before-pass-after pin on the fourth path of the four-path
8220 // convergence: `from_wire` (the reverse projection) inverts the
8221 // `Serialize` derive's wire byte-string on every variant.
8222 // Together with the pre-existing three-path convergence
8223 // (`Display` + `as_str` + `Serialize` all resolve to the same
8224 // lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const,
8225 // pinned by
8226 // [`restart_strategy_display_matches_serialized_wire_byte_string`])
8227 // this closes the round-trip: the wire byte-string the
8228 // `Serialize` derive emits parses back to the same variant
8229 // through `from_wire`, so any future serde-attribute or variant-
8230 // rename drift on the emit half now surfaces as a matched drift
8231 // on the parse half at caixa-core build time — the two halves
8232 // migrate as a unit through the lifted consts on any future
8233 // rename, and the round-trip cannot silently split.
8234 //
8235 // Peer of the sibling
8236 // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
8237 // (18c7342) wire-format pin on
8238 // [`crate::aplicacao::PlacementStrategy::from_wire`].
8239 for &variant in RestartStrategy::ALL {
8240 let wire = serde_json::to_string(&variant).unwrap();
8241 let unquoted = wire
8242 .strip_prefix('"')
8243 .and_then(|s| s.strip_suffix('"'))
8244 .expect("serialized RestartStrategy is a JSON string");
8245 let parsed = RestartStrategy::from_wire(unquoted).unwrap_or_else(|| {
8246 panic!(
8247 "RestartStrategy::from_wire({unquoted:?}) must accept the \
8248 Serialize derive's wire byte-string for \
8249 RestartStrategy::{variant:?} — the four-path convergence \
8250 (Display + as_str + Serialize + from_wire) resolves through \
8251 the same lifted SUPERVISOR_ESTRATEGIA_* const; got None"
8252 )
8253 });
8254 assert_eq!(
8255 parsed, variant,
8256 "RestartStrategy::from_wire of the Serialize derive's wire \
8257 byte-string for RestartStrategy::{variant:?} must round-trip \
8258 to the same variant; got {parsed:?}"
8259 );
8260 }
8261 }
8262
8263 #[test]
8264 fn restart_strategy_try_from_str_routes_through_from_wire_accessor() {
8265 // Fail-before-pass-after byte-parity pin on the newly lifted
8266 // `impl TryFrom<&str> for RestartStrategy` — asserts the standard-
8267 // library trait impl and the substrate-primitive
8268 // [`RestartStrategy::from_wire`] `Option<Self>` accessor resolve to
8269 // the same four-arm accept-set across every arm the exhaustive
8270 // [`RestartStrategy::ALL`] slice enumerates. Any future silent
8271 // detour that routes the trait impl through a divergent projection
8272 // (a per-arm inline `match s { "OneForOne" => Ok(Self::OneForOne),
8273 // … }` re-inlining that opens a compile-time link to the un-
8274 // lifted arm-literal, a hypothetical `#[serde(rename_all = "…")]`
8275 // attribute drift that silently splits the wire byte-string from
8276 // every consumer that reaches for this typed dispatch, an
8277 // accidental swap onto the kebab-case dispatcher-catalog axis the
8278 // pre-existing [`std::str::FromStr`] impl parses through and which
8279 // would collide the two-axis wire/catalog split the sibling
8280 // [`RestartStrategy::from_wire`] doc block makes load-bearing)
8281 // trips at caixa-core test time under `assert_eq!` rather than at
8282 // a downstream `impl TryFrom<&str>`-bound consumer's silent split.
8283 // Sweeps every one of the four arms [`RestartStrategy::ALL`]
8284 // carries so no arm's projection is covered only by the sibling
8285 // method-named `from_wire` path. Peer of the sibling
8286 // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
8287 // (3c83606),
8288 // [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
8289 // (bf33136), and the M3
8290 // [`crate::aplicacao::tests::placement_strategy_try_from_str_routes_through_from_wire_accessor`]
8291 // (6fd00cd) — extends the trait-idiomatic reverse-projection axis
8292 // onto the first M2-OTP-shape closed-set typed enum on the caixa
8293 // surface.
8294 for &variant in RestartStrategy::ALL {
8295 let wire = variant.as_str();
8296 assert_eq!(
8297 <RestartStrategy as TryFrom<&str>>::try_from(wire),
8298 Ok(variant),
8299 "TryFrom<&str> impl on RestartStrategy must round-trip \
8300 RestartStrategy::{variant:?}.as_str() = {wire:?} back to \
8301 Ok(RestartStrategy::{variant:?}) — divergence from \
8302 RestartStrategy::from_wire signals a silent detour off \
8303 the substrate-primitive accessor"
8304 );
8305 assert_eq!(
8306 <RestartStrategy as TryFrom<&str>>::try_from(wire).ok(),
8307 RestartStrategy::from_wire(wire),
8308 "TryFrom<&str> ok()-projection on {wire:?} must byte-equal \
8309 RestartStrategy::from_wire on the same input"
8310 );
8311 }
8312 }
8313
8314 #[test]
8315 fn restart_strategy_try_from_str_rejects_unknown_byte_strings() {
8316 // Rejection witness on the `impl TryFrom<&str> for
8317 // RestartStrategy` — sweeps a candidate set of byte-strings
8318 // outside the four-arm PascalCase wire accept-set the sibling
8319 // [`RestartStrategy::as_str`] emits and asserts every one lands on
8320 // `Err(())`, so a future accidental widening of the trait impl's
8321 // accept-set (a stray additional
8322 // `_ if s.eq_ignore_ascii_case("OneForOne") => Ok(…)` case-fold
8323 // path, a silent inclusion of the kebab-case dispatcher-catalog
8324 // byte-string the pre-existing [`std::str::FromStr`] impl the
8325 // [`gen_platform::FromStrKind`] derive installs parses onto the
8326 // wire axis — which would collide the two-axis
8327 // wire/dispatcher-catalog split the sibling
8328 // [`RestartStrategy::from_wire`] doc block makes load-bearing —
8329 // an English-rebrand or plural-arm silent alias that would
8330 // widen the wire accept-set past the OTP-canonical four) trips at
8331 // caixa-core test time. The candidate set includes the empty
8332 // string, whitespace-only padding, the kebab-case dispatcher-
8333 // catalog byte-strings on the sibling axis (a caller who confuses
8334 // the two axes trips here rather than at a downstream consumer's
8335 // silent reject), a lowercase / uppercase / mixed-case fold of
8336 // each PascalCase arm (a caller who assumes case-fold acceptance
8337 // trips here), leading/trailing whitespace padding, the trailing-
8338 // newline shape, quote-wrapped candidates, and a residual set of
8339 // plausible-but-wrong English rebrand candidates. Peer of the
8340 // sibling
8341 // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
8342 // (3c83606) and
8343 // [`crate::aplicacao::tests::placement_strategy_try_from_str_rejects_unknown_byte_strings`]
8344 // (6fd00cd) rejection witnesses.
8345 let rejected: &[&str] = &[
8346 "",
8347 " ",
8348 "\n",
8349 "\t",
8350 "one-for-one",
8351 "one-for-all",
8352 "rest-for-one",
8353 "simple-one-for-one",
8354 "oneforone",
8355 "one_for_one",
8356 "OneForOnes",
8357 "ONEFORONE",
8358 "oneforall",
8359 "restforone",
8360 "simpleoneforone",
8361 "OneForOne ",
8362 " OneForOne",
8363 " OneForAll ",
8364 "OneForOne\n",
8365 "RestForOne\t",
8366 "OneForEach",
8367 "AllForOne",
8368 "one for one",
8369 "\"OneForOne\"",
8370 "?",
8371 ];
8372 for &input in rejected {
8373 assert_eq!(
8374 <RestartStrategy as TryFrom<&str>>::try_from(input),
8375 Err(()),
8376 "TryFrom<&str> impl on RestartStrategy must reject the \
8377 non-wire byte-string {input:?} — silent acceptance signals \
8378 an accept-set widening off the paired \
8379 RestartStrategy::from_wire resolver"
8380 );
8381 }
8382 }
8383
8384 #[test]
8385 fn restart_strategy_try_from_str_and_from_wire_partition_the_accept_set() {
8386 // Cross-axis partition pin: the paired `TryFrom<&str>` and
8387 // `from_wire` reverse projections must resolve identically on
8388 // *every* input, not just the ones [`RestartStrategy::ALL`]
8389 // enumerates. Sweeps a mixed candidate set spanning accepted
8390 // (four-arm PascalCase wire byte-strings) and rejected (kebab-case
8391 // dispatcher-catalog byte-strings, empty, whitespace-padded,
8392 // quoted, English-rebrand candidates) inputs and asserts the
8393 // trait's `Result::ok()` projection byte-equals the method-named
8394 // resolver's `Option<Self>` return-shape on each, locking the two
8395 // paths together by construction so any future detour (a stray
8396 // `try_from` special-case that widens or narrows the accept-set
8397 // outside the paired `from_wire` resolver, an accidental swap
8398 // onto the kebab-case [`std::str::FromStr`] impl the
8399 // [`gen_platform::FromStrKind`] derive installs on the sibling
8400 // dispatcher-catalog axis) trips at caixa-core test time. Peer of
8401 // the sibling
8402 // [`crate::kind::tests::caixa_kind_try_from_str_and_from_wire_partition_the_accept_set`]
8403 // pin — extends the round-trip discipline onto the M2-OTP-shape
8404 // sibling-restart axis.
8405 let candidates: &[&str] = &[
8406 "OneForOne",
8407 "OneForAll",
8408 "RestForOne",
8409 "SimpleOneForOne",
8410 "",
8411 "one-for-one",
8412 "one-for-all",
8413 "rest-for-one",
8414 "simple-one-for-one",
8415 "oneforone",
8416 "unknown",
8417 "OneForOne ",
8418 " OneForOne",
8419 "\"OneForOne\"",
8420 "OneForEach",
8421 "?",
8422 ];
8423 for &input in candidates {
8424 let via_trait: Option<RestartStrategy> =
8425 <RestartStrategy as TryFrom<&str>>::try_from(input).ok();
8426 let via_method: Option<RestartStrategy> = RestartStrategy::from_wire(input);
8427 assert_eq!(
8428 via_trait, via_method,
8429 "TryFrom<&str> and from_wire must resolve identically on \
8430 input {input:?} — divergence signals the two reverse-\
8431 projection paths have drifted onto different accept-sets"
8432 );
8433 }
8434 }
8435
8436 #[test]
8437 fn restart_strategy_from_into_static_str_routes_through_as_str_accessor() {
8438 // Fail-before-pass-after byte-parity pin on the newly lifted
8439 // `impl From<RestartStrategy> for &'static str` — asserts the
8440 // standard-library trait impl and the substrate-primitive
8441 // [`RestartStrategy::as_str`] `pub const fn` accessor resolve to
8442 // the same four-arm emit-set across every arm the exhaustive
8443 // [`RestartStrategy::ALL`] slice enumerates. Any future silent
8444 // detour that routes the trait impl through a divergent
8445 // projection (a per-arm inline `match strategy { OneForOne =>
8446 // "OneForOne", … }` re-inlining that opens a compile-time link to
8447 // the un-lifted arm-literal, an accidental swap onto the sibling
8448 // kebab-case [`Self::discriminant`] dispatcher-catalog axis that
8449 // would collide the two-axis wire/catalog split the sibling
8450 // [`RestartStrategy::from_wire`] doc block makes load-bearing) trips
8451 // at caixa-core test time under `assert_eq!` rather than at a
8452 // downstream `impl Into<&'static str>`-bound consumer's silent
8453 // split. Sweeps every one of the four arms
8454 // [`RestartStrategy::ALL`] carries so no arm's projection is
8455 // covered only by the sibling method-named `as_str` /
8456 // [`std::fmt::Display`] / [`AsRef<str>`] paths. Materializes the
8457 // `<&'static str as From<RestartStrategy>>::from` output in a
8458 // `const`-shape binding to make the `'static` lifetime promise a
8459 // build-time invariant — a future accidental downgrade of any of
8460 // the four arms' [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
8461 // constants to a non-`&'static str` (a `String::leak()`-produced
8462 // return, a `Box::leak`-cast) trips at caixa-core build time
8463 // rather than at a downstream `'static`-bound consumer.
8464 const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
8465 const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
8466 const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
8467 const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
8468 for &variant in RestartStrategy::ALL {
8469 let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8470 let via_method: &'static str = variant.as_str();
8471 assert_eq!(
8472 via_trait, via_method,
8473 "From<RestartStrategy> for &'static str impl must round-trip \
8474 RestartStrategy::{variant:?} to the same lifted \
8475 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str returns — \
8476 divergence signals a silent detour off the substrate-primitive \
8477 accessor"
8478 );
8479 let via_into: &'static str = variant.into();
8480 assert_eq!(
8481 via_into, via_method,
8482 "Into<&'static str>::into on RestartStrategy::{variant:?} must \
8483 byte-equal RestartStrategy::as_str on the same input — the \
8484 blanket-derived Into shape must resolve to the same as_str \
8485 dispatch as the explicit From impl"
8486 );
8487 }
8488 assert_eq!(
8489 [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
8490 [
8491 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8492 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8493 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8494 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8495 ],
8496 "const-context RestartStrategy::as_str must resolve to the four \
8497 lifted SUPERVISOR_ESTRATEGIA_* consts — a future accidental \
8498 downgrade of any arm to a non-const or non-static byte-string \
8499 breaks the `&'static str`-lifetime promise the paired \
8500 From<RestartStrategy> for &'static str impl carries by \
8501 construction"
8502 );
8503 }
8504
8505 #[test]
8506 fn restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set() {
8507 // Cross-axis partition pin: the paired trait-idiomatic
8508 // `From<RestartStrategy> for &'static str` forward projection and
8509 // the method-named [`RestartStrategy::as_str`] forward projection
8510 // must resolve identically on *every* arm, not just the ones
8511 // named in the primary byte-parity pin above. Sweeps every
8512 // [`RestartStrategy::ALL`] arm and asserts the trait's `From::from`
8513 // output byte-equals the method-named accessor's return-value on
8514 // each, locking the two forward-projection paths together by
8515 // construction so any future detour (a stray `From` special-case
8516 // that lands on a divergent per-arm literal outside the paired
8517 // `as_str` dispatch, a hypothetical rebrand touching one axis
8518 // without the other) trips at caixa-core test time. Peer of the
8519 // sibling reverse-projection partition pin
8520 // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
8521 // — extends the round-trip discipline onto the trait-idiomatic
8522 // *forward* axis, closing the two-way `Self ↔ &'static str`
8523 // round-trip on the trait-idiomatic pair
8524 // (`From<Self> for &'static str` + `TryFrom<&str> for Self`) as
8525 // well as the pre-existing method-named pair
8526 // (`as_str` + `from_wire`).
8527 for &variant in RestartStrategy::ALL {
8528 let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8529 let via_method: &'static str = variant.as_str();
8530 assert_eq!(
8531 via_trait, via_method,
8532 "From<RestartStrategy> for &'static str and \
8533 RestartStrategy::as_str must resolve identically on \
8534 RestartStrategy::{variant:?} — divergence signals the \
8535 two forward-projection paths have drifted onto different \
8536 emit-sets"
8537 );
8538 }
8539 // Round-trip witness: every arm's forward `From` output re-parses
8540 // through the paired trait-idiomatic reverse `TryFrom<&str>` back
8541 // to the original variant. Closes the two-way `RestartStrategy ↔
8542 // &'static str` round-trip on the trait-idiomatic axis pair,
8543 // mirroring the pre-existing method-named `as_str` + `from_wire`
8544 // round-trip on the substrate-primitive axis pair.
8545 for &variant in RestartStrategy::ALL {
8546 let emitted: &'static str = variant.into();
8547 let re_parsed: Result<RestartStrategy, ()> =
8548 <RestartStrategy as TryFrom<&str>>::try_from(emitted);
8549 assert_eq!(
8550 re_parsed,
8551 Ok(variant),
8552 "trait-idiomatic axis pair must round-trip \
8553 RestartStrategy::{variant:?} through `.into::<&'static \
8554 str>()` and back through `TryFrom<&str>` — a break signals \
8555 the forward-emit and reverse-parse axes have drifted onto \
8556 different vocabularies"
8557 );
8558 }
8559 }
8560
8561 #[test]
8562 fn restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
8563 // Fail-before-pass-after byte-parity pin on the newly lifted
8564 // `impl From<&RestartStrategy> for &'static str` — asserts the
8565 // borrowed-input standard-library trait impl and the substrate-
8566 // primitive [`RestartStrategy::as_str`] `pub const fn` accessor
8567 // resolve to the same four-arm emit-set across every arm the
8568 // exhaustive [`RestartStrategy::ALL`] slice enumerates. Rust's
8569 // `From` trait does not auto-derive the borrowed-input sibling
8570 // from a paired owned-input impl (no `impl<T, U> From<&T> for U
8571 // where T: Copy, U: From<T>` blanket in `core`), so the
8572 // borrowed-input axis is a distinct trait-idiomatic surface
8573 // that a `.iter().map(Into::into)` shape over
8574 // [`RestartStrategy::ALL`] (whose iterator yields
8575 // `&RestartStrategy`, not `RestartStrategy`) reaches through
8576 // this impl and no other — the paired owned-input
8577 // [`From<RestartStrategy>`] impl requires an explicit
8578 // `.copied()` / dereference before the trait fires.
8579 // Materializes the `<&'static str as
8580 // From<&RestartStrategy>>::from` output in a `const`-shape
8581 // binding to make the `'static` lifetime promise a build-time
8582 // invariant.
8583 const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
8584 const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
8585 const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
8586 const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
8587 for variant in RestartStrategy::ALL {
8588 let via_trait: &'static str = <&'static str as From<&RestartStrategy>>::from(variant);
8589 let via_method: &'static str = variant.as_str();
8590 assert_eq!(
8591 via_trait, via_method,
8592 "From<&RestartStrategy> for &'static str impl must \
8593 round-trip &RestartStrategy::{variant:?} to the same \
8594 lifted SUPERVISOR_ESTRATEGIA_* const \
8595 RestartStrategy::as_str returns — divergence signals a \
8596 silent detour off the substrate-primitive accessor"
8597 );
8598 let via_into: &'static str = variant.into();
8599 assert_eq!(
8600 via_into, via_method,
8601 "Into<&'static str>::into on &RestartStrategy::{variant:?} \
8602 must byte-equal RestartStrategy::as_str on the same input — \
8603 the blanket-derived Into shape must resolve to the same \
8604 as_str dispatch as the explicit From impl"
8605 );
8606 }
8607 assert_eq!(
8608 [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
8609 [
8610 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8611 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8612 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8613 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8614 ],
8615 "const-context RestartStrategy::as_str must resolve to the \
8616 four lifted SUPERVISOR_ESTRATEGIA_* consts — the borrowed-\
8617 input From<&RestartStrategy> for &'static str impl inherits \
8618 its `'static` lifetime promise from the same accessor the \
8619 owned-input sibling routes through"
8620 );
8621 }
8622
8623 #[test]
8624 fn restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
8625 // Cross-axis partition pin: the paired trait-idiomatic
8626 // owned-input `From<RestartStrategy> for &'static str` (523157d
8627 // campaign-shape) and borrowed-input `From<&RestartStrategy> for
8628 // &'static str` (this lift) forward projections must resolve
8629 // identically on every arm, locking the two input-shape paths
8630 // together so any future detour trips at caixa-core test time.
8631 // Then a witness that a `.iter().map(Into::into)` pipe over
8632 // [`RestartStrategy::ALL`] (whose iterator yields
8633 // `&RestartStrategy`) materializes the four-arm accept-set
8634 // through the borrowed-input axis alone — the exact shape a
8635 // future wasm-operator per-supervisor sibling-restart-strategy
8636 // diagnostic line, a future substrate-wide per-arm diagnostic
8637 // column, or a
8638 // `HashMap::<&'static str, RestartStrategy>::from_iter(
8639 // RestartStrategy::ALL.iter().map(|s| (s.into(), *s)))`-style
8640 // per-strategy lookup reaches through — closing the two-way
8641 // owned/borrowed input-shape symmetry on the forward-projection
8642 // trait-idiomatic axis. Peer of the sibling
8643 // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8644 // (64aa742) /
8645 // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8646 // (5ab993a) /
8647 // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8648 // (807b0b5) partition pins on the sibling closed-set typed-enum
8649 // discriminator axes — extends the borrowed-input axis
8650 // discipline onto the first M2 OTP-shape sibling-restart
8651 // closed-set typed enum on the caixa surface. Also closes the
8652 // direct two-way `&Self → &'static str → Self` round-trip via
8653 // the paired [`TryFrom<&str>`] axis — unlike the peer
8654 // [`crate::CaixaKind`] axis pair (whose forward `From` emits
8655 // lowercase Portuguese diagnostic bytes while the reverse
8656 // `TryFrom` parses `PascalCase` wire bytes, forcing the round-
8657 // trip through an intermediate wire-vocab hop), the
8658 // [`RestartStrategy::as_str`] emit and
8659 // [`RestartStrategy::from_wire`] parse share the same
8660 // `PascalCase` vocabulary by construction, so the borrowed-
8661 // input forward axis and the reverse axis compose directly.
8662 for &variant in RestartStrategy::ALL {
8663 let owned: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8664 let borrowed: &'static str = <&'static str as From<&RestartStrategy>>::from(&variant);
8665 assert_eq!(
8666 owned, borrowed,
8667 "From<RestartStrategy> and From<&RestartStrategy> for \
8668 &'static str must resolve identically on \
8669 RestartStrategy::{variant:?} — divergence signals the \
8670 owned-input and borrowed-input forward-projection paths \
8671 have drifted onto different emit-sets"
8672 );
8673 }
8674 let via_iter: Vec<&'static str> = RestartStrategy::ALL.iter().map(Into::into).collect();
8675 let via_method: Vec<&'static str> =
8676 RestartStrategy::ALL.iter().map(|s| s.as_str()).collect();
8677 assert_eq!(
8678 via_iter, via_method,
8679 "`.iter().map(Into::into)` over RestartStrategy::ALL must \
8680 byte-equal `.iter().map(|s| s.as_str())` on every arm — the \
8681 borrowed-input `From<&RestartStrategy> for &'static str` \
8682 axis is what makes the `.iter().map(Into::into)` shape route \
8683 through the substrate-primitive `RestartStrategy::as_str` \
8684 accessor rather than through a per-call-site `.copied()` / \
8685 dereference detour"
8686 );
8687 for variant in RestartStrategy::ALL {
8688 let emitted: &'static str = variant.into();
8689 let re_parsed: Result<RestartStrategy, ()> =
8690 <RestartStrategy as TryFrom<&str>>::try_from(emitted);
8691 assert_eq!(
8692 re_parsed,
8693 Ok(*variant),
8694 "trait-idiomatic borrowed-input forward-projection + \
8695 reverse-projection axis pair must round-trip \
8696 &RestartStrategy::{variant:?} through `.into::<&'static \
8697 str>()` (via the borrowed-input axis) and back through \
8698 `TryFrom<&str>` — a break signals the borrowed-input \
8699 forward-emit and reverse-parse axes have drifted onto \
8700 different vocabularies"
8701 );
8702 }
8703 }
8704
8705 #[test]
8706 fn restart_strategy_from_into_owned_string_routes_through_as_str_accessor() {
8707 // Fail-before-pass-after byte-parity pin on the newly lifted
8708 // `impl From<RestartStrategy> for String` — asserts the
8709 // owned-`String`-returning standard-library trait impl and the
8710 // substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
8711 // accessor resolve to the same four-arm emit-set across every
8712 // arm the exhaustive [`RestartStrategy::ALL`] slice enumerates.
8713 // Rust's standard library does not carry a blanket
8714 // `impl<T: AsRef<str>> From<T> for String` (nor an
8715 // `impl<T: fmt::Display> From<T> for String`), so the
8716 // owned-`String` forward-projection axis is a distinct
8717 // trait-idiomatic surface that a
8718 // `let key: String = strategy.into();`-shaped call site
8719 // reaches through this impl and no other — the paired sibling
8720 // `From<RestartStrategy> for &'static str` impl forces every
8721 // owned-`String` call site through an explicit
8722 // `.to_owned()` / `String::from` restatement.
8723 for &variant in RestartStrategy::ALL {
8724 let via_trait: String = <String as From<RestartStrategy>>::from(variant);
8725 let via_method: &'static str = variant.as_str();
8726 assert_eq!(
8727 via_trait.as_str(),
8728 via_method,
8729 "From<RestartStrategy> for String impl must round-trip \
8730 RestartStrategy::{variant:?} to the same lifted \
8731 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
8732 returns — divergence signals a silent detour off the \
8733 substrate-primitive accessor"
8734 );
8735 let via_into: String = variant.into();
8736 assert_eq!(
8737 via_into.as_str(),
8738 via_method,
8739 "Into<String>::into on RestartStrategy::{variant:?} must \
8740 byte-equal RestartStrategy::as_str on the same input — the \
8741 blanket-derived Into shape must resolve to the same as_str \
8742 dispatch as the explicit From impl"
8743 );
8744 }
8745 }
8746
8747 #[test]
8748 fn restart_strategy_from_into_owned_string_and_static_str_agree_on_every_arm() {
8749 // Cross-axis partition pin: the paired trait-idiomatic
8750 // owned-`String` `From<RestartStrategy> for String` (this lift)
8751 // and owned-`&'static str` `From<RestartStrategy> for &'static
8752 // str` (523157d) forward projections must resolve identically
8753 // on every arm, locking the two return-type-shape paths
8754 // together so any future detour trips at caixa-core test time.
8755 // Also byte-parity witness against the sibling
8756 // [`ToString::to_string`] surface routed through
8757 // [`std::fmt::Display`] — the three owned-heap-string paths
8758 // (`.into::<String>()`, `String::from`, `.to_string()`) must
8759 // resolve identically on every arm so a future consumer that
8760 // picks any of the three lands on the same lifted
8761 // SUPERVISOR_ESTRATEGIA_* const. Then a direct round-trip
8762 // witness through the paired trait-idiomatic reverse
8763 // [`TryFrom<&str>`] axis on the owned-`String`'s
8764 // [`String::as_str`] borrow that closes the two-way
8765 // `Self → String → Self` round-trip on the trait-idiomatic
8766 // owned-`String` forward + reverse axis pair.
8767 for &variant in RestartStrategy::ALL {
8768 let owned_string: String = <String as From<RestartStrategy>>::from(variant);
8769 let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8770 assert_eq!(
8771 owned_string.as_str(),
8772 owned_static,
8773 "From<RestartStrategy> for String and From<RestartStrategy> \
8774 for &'static str must resolve identically on \
8775 RestartStrategy::{variant:?} — divergence signals the \
8776 owned-`String` and owned-`&'static str` forward-projection \
8777 return-type-shape paths have drifted onto different \
8778 emit-sets"
8779 );
8780 let via_to_string: String = variant.to_string();
8781 assert_eq!(
8782 owned_string, via_to_string,
8783 "From<RestartStrategy> for String must byte-equal \
8784 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
8785 divergence signals the trait-idiomatic owned-`String` \
8786 forward-projection axis and the ToString-through-Display \
8787 axis have drifted onto different emit-sets"
8788 );
8789 }
8790 let via_iter: Vec<String> = RestartStrategy::ALL
8791 .iter()
8792 .copied()
8793 .map(String::from)
8794 .collect();
8795 let via_method: Vec<String> = RestartStrategy::ALL
8796 .iter()
8797 .map(|s| s.as_str().to_owned())
8798 .collect();
8799 assert_eq!(
8800 via_iter, via_method,
8801 "`.iter().copied().map(String::from)` over RestartStrategy::ALL \
8802 must byte-equal `.iter().map(|s| s.as_str().to_owned())` on \
8803 every arm — the owned-`String` `From<RestartStrategy> for \
8804 String` axis is what makes the `String::from` composition \
8805 route through the substrate-primitive `RestartStrategy::as_str` \
8806 accessor rather than through a per-call-site `.to_owned()` / \
8807 `String::from(strategy.as_str())` detour"
8808 );
8809 for &variant in RestartStrategy::ALL {
8810 let emitted: String = variant.into();
8811 let re_parsed: Result<RestartStrategy, ()> =
8812 <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
8813 assert_eq!(
8814 re_parsed,
8815 Ok(variant),
8816 "trait-idiomatic owned-`String` forward-projection + \
8817 reverse-projection axis pair must round-trip \
8818 RestartStrategy::{variant:?} through `.into::<String>()` \
8819 and back through `TryFrom<&str>` on the owned-`String`'s \
8820 String::as_str borrow — a break signals the owned-`String` \
8821 forward-emit and reverse-parse axes have drifted onto \
8822 different vocabularies"
8823 );
8824 }
8825 }
8826
8827 #[test]
8828 fn restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
8829 // Fail-before-pass-after byte-parity pin on the newly lifted
8830 // `impl From<&RestartStrategy> for String` — asserts the
8831 // borrowed-input owned-`String`-returning standard-library trait
8832 // impl and the substrate-primitive [`RestartStrategy::as_str`]
8833 // `pub const fn` accessor resolve to the same four-arm emit-set
8834 // across every arm the exhaustive [`RestartStrategy::ALL`] slice
8835 // enumerates. Rust's standard library does not carry a blanket
8836 // `impl<T: AsRef<str>> From<&T> for String` (nor an
8837 // `impl<T: fmt::Display> From<&T> for String`), so the
8838 // borrowed-input owned-`String` forward-projection axis is a
8839 // distinct trait-idiomatic surface that a
8840 // `let key: String = (&strategy).into();`-shaped call site
8841 // reaches through this impl and no other — the paired sibling
8842 // `From<RestartStrategy> for String` impl forces every
8843 // borrowed-input call site through an explicit `Copy` deref
8844 // (`String::from(*strategy)`) or an `.as_str().to_owned()` /
8845 // `.to_string()` detour.
8846 for &variant in RestartStrategy::ALL {
8847 let via_trait: String = <String as From<&RestartStrategy>>::from(&variant);
8848 let via_method: &'static str = variant.as_str();
8849 assert_eq!(
8850 via_trait.as_str(),
8851 via_method,
8852 "From<&RestartStrategy> for String impl must round-trip \
8853 &RestartStrategy::{variant:?} to the same lifted \
8854 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
8855 returns — divergence signals a silent detour off the \
8856 substrate-primitive accessor"
8857 );
8858 let via_into: String = (&variant).into();
8859 assert_eq!(
8860 via_into.as_str(),
8861 via_method,
8862 "Into<String>::into on &RestartStrategy::{variant:?} must \
8863 byte-equal RestartStrategy::as_str on the same input — the \
8864 blanket-derived Into shape must resolve to the same as_str \
8865 dispatch as the explicit From impl"
8866 );
8867 }
8868 }
8869
8870 #[test]
8871 fn restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
8872 // Cross-axis partition pin: the newly lifted trait-idiomatic
8873 // borrowed-input owned-`String` `From<&RestartStrategy> for
8874 // String` (this lift), the paired owned-input owned-`String`
8875 // `From<RestartStrategy> for String` (7baa18a), the paired
8876 // borrowed-input owned-`&'static str` `From<&RestartStrategy>
8877 // for &'static str` (e941836), and the paired owned-input
8878 // owned-`&'static str` `From<RestartStrategy> for &'static str`
8879 // (523157d) — every corner of the `{Self, &Self} × {&'static
8880 // str, String}` 2×2 trait-idiomatic projection family — must
8881 // resolve identically on every arm, locking the four
8882 // return-shape × input-shape paths together so any future
8883 // detour trips at caixa-core test time. Also byte-parity
8884 // witness against the sibling [`ToString::to_string`] surface
8885 // routed through [`std::fmt::Display`] and a direct round-trip
8886 // witness through the paired trait-idiomatic reverse
8887 // [`TryFrom<&str>`] axis on the owned-`String`'s
8888 // [`String::as_str`] borrow that closes the two-way
8889 // `&Self → String → Self` round-trip on the trait-idiomatic
8890 // borrowed-input owned-`String` forward + reverse axis pair.
8891 for &variant in RestartStrategy::ALL {
8892 let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
8893 let owned_string: String = <String as From<RestartStrategy>>::from(variant);
8894 let borrowed_static: &'static str =
8895 <&'static str as From<&RestartStrategy>>::from(&variant);
8896 let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8897 assert_eq!(
8898 borrowed_string, owned_string,
8899 "From<&RestartStrategy> for String and From<RestartStrategy> \
8900 for String must resolve identically on \
8901 RestartStrategy::{variant:?} — divergence signals the \
8902 borrowed-input and owned-input owned-`String` \
8903 forward-projection input-shape paths have drifted onto \
8904 different emit-sets"
8905 );
8906 assert_eq!(
8907 borrowed_string.as_str(),
8908 borrowed_static,
8909 "From<&RestartStrategy> for String and From<&RestartStrategy> \
8910 for &'static str must resolve identically on \
8911 RestartStrategy::{variant:?} — divergence signals the \
8912 borrowed-input `&'static str` and owned-`String` \
8913 return-shape paths have drifted onto different emit-sets"
8914 );
8915 assert_eq!(
8916 borrowed_string.as_str(),
8917 owned_static,
8918 "From<&RestartStrategy> for String and From<RestartStrategy> \
8919 for &'static str must resolve identically on \
8920 RestartStrategy::{variant:?} — divergence signals a break \
8921 in the diagonal corner of the {{Self, &Self}} × \
8922 {{&'static str, String}} 2×2 trait-idiomatic \
8923 projection family"
8924 );
8925 let via_to_string: String = variant.to_string();
8926 assert_eq!(
8927 borrowed_string, via_to_string,
8928 "From<&RestartStrategy> for String must byte-equal \
8929 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
8930 divergence signals the trait-idiomatic borrowed-input \
8931 owned-`String` forward-projection axis and the \
8932 ToString-through-Display axis have drifted onto different \
8933 emit-sets"
8934 );
8935 }
8936 let via_iter: Vec<String> = RestartStrategy::ALL.iter().map(String::from).collect();
8937 let via_method: Vec<String> = RestartStrategy::ALL
8938 .iter()
8939 .map(|s| s.as_str().to_owned())
8940 .collect();
8941 assert_eq!(
8942 via_iter, via_method,
8943 "`.iter().map(String::from)` over RestartStrategy::ALL — a \
8944 call site whose iteration axis holds `&RestartStrategy` by \
8945 construction — must byte-equal `.iter().map(|s| \
8946 s.as_str().to_owned())` on every arm — the borrowed-input \
8947 owned-`String` `From<&RestartStrategy> for String` axis is \
8948 what makes the `String::from` composition route through the \
8949 substrate-primitive `RestartStrategy::as_str` accessor \
8950 without a spurious `Copy` deref (which would only be \
8951 reachable through the owned-input `From<RestartStrategy> for \
8952 String` axis by first calling `.copied()` on the iterator)"
8953 );
8954 for &variant in RestartStrategy::ALL {
8955 let emitted: String = (&variant).into();
8956 let re_parsed: Result<RestartStrategy, ()> =
8957 <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
8958 assert_eq!(
8959 re_parsed,
8960 Ok(variant),
8961 "trait-idiomatic borrowed-input owned-`String` \
8962 forward-projection + reverse-projection axis pair must \
8963 round-trip &RestartStrategy::{variant:?} through \
8964 `.into::<String>()` on the borrowed-input surface and \
8965 back through `TryFrom<&str>` on the owned-`String`'s \
8966 String::as_str borrow — a break signals the \
8967 borrowed-input owned-`String` forward-emit and \
8968 reverse-parse axes have drifted onto different \
8969 vocabularies"
8970 );
8971 }
8972 }
8973
8974 #[test]
8975 fn restart_strategy_from_into_static_cow_str_routes_through_as_str_accessor() {
8976 // Fail-before-pass-after byte-parity pin on the newly lifted
8977 // `impl From<RestartStrategy> for std::borrow::Cow<'static, str>` —
8978 // asserts the standard-library trait impl and the substrate-
8979 // primitive [`super::RestartStrategy::as_str`] `pub const fn`
8980 // accessor resolve to the same four-arm emit-set across every
8981 // arm the exhaustive [`super::RestartStrategy::ALL`] slice
8982 // enumerates. Rust's standard library does not carry a blanket
8983 // `impl<T: AsRef<str>> From<T> for Cow<'static, str>` (nor an
8984 // `impl<T: fmt::Display> From<T> for Cow<'static, str>`), so
8985 // the `Cow<'static, str>` forward-projection axis is a
8986 // distinct trait-idiomatic surface that a
8987 // `let key: Cow<'static, str> = strategy.into();`-shaped call
8988 // site reaches through this impl and no other — the paired
8989 // sibling `From<RestartStrategy> for &'static str` and
8990 // `From<RestartStrategy> for String` impls force every
8991 // `Cow<'static, str>`-parameterized call site through a
8992 // `Cow::Borrowed(strategy.as_str())` /
8993 // `Cow::Owned(strategy.to_string())` composition whose type
8994 // bounds have no compile-time link back to the substrate
8995 // primitive.
8996 //
8997 // Also asserts the projection lands on the zero-alloc
8998 // [`std::borrow::Cow::Borrowed`] arm (not the
8999 // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
9000 // [`super::RestartStrategy::as_str`] accessor's `&'static str`
9001 // return lifetime by construction makes the borrowed arm the
9002 // type-correct projection with no runtime allocation. Any
9003 // future silent detour that routes the impl through the owned
9004 // arm (an accidental `Cow::Owned(strategy.to_string())` rewrite
9005 // that would allocate on every call site where the
9006 // `&'static str` return of [`super::RestartStrategy::as_str`]
9007 // makes the zero-alloc borrowed projection type-correct) trips
9008 // at caixa-core test time under the
9009 // [`std::borrow::Cow::Borrowed`] discriminator witness rather
9010 // than at a downstream `Cow<'static, str>`-bound consumer's
9011 // silent allocation.
9012 //
9013 // First peer on the substrate-wide trait-idiomatic
9014 // [`std::borrow::Cow<'static, str>`] forward-projection family
9015 // to extend the axis off the top-level [`super::CaixaKind`]
9016 // enum (99c1735 owned-input, d45c409 borrowed-input) onto the
9017 // first M2 OTP-shape closed-set fieldless typed enum on the
9018 // caixa surface.
9019 for &variant in RestartStrategy::ALL {
9020 let via_trait: std::borrow::Cow<'static, str> =
9021 <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
9022 let via_method: &'static str = variant.as_str();
9023 assert_eq!(
9024 via_trait.as_ref(),
9025 via_method,
9026 "From<RestartStrategy> for Cow<'static, str> impl must \
9027 round-trip RestartStrategy::{variant:?} to the same \
9028 lifted SUPERVISOR_ESTRATEGIA_* const \
9029 RestartStrategy::as_str returns — divergence signals a \
9030 silent detour off the substrate-primitive accessor"
9031 );
9032 assert!(
9033 matches!(via_trait, std::borrow::Cow::Borrowed(_)),
9034 "From<RestartStrategy> for Cow<'static, str> impl must \
9035 land on the zero-alloc Cow::Borrowed arm on \
9036 RestartStrategy::{variant:?} — a Cow::Owned outcome \
9037 signals the projection has silently allocated where \
9038 the substrate-primitive RestartStrategy::as_str \
9039 `&'static str` return makes the borrowed arm the \
9040 type-correct projection"
9041 );
9042 let via_into: std::borrow::Cow<'static, str> = variant.into();
9043 assert_eq!(
9044 via_into.as_ref(),
9045 via_method,
9046 "Into<Cow<'static, str>>::into on \
9047 RestartStrategy::{variant:?} must byte-equal \
9048 RestartStrategy::as_str on the same input — the \
9049 blanket-derived Into shape must resolve to the same \
9050 as_str dispatch as the explicit From impl"
9051 );
9052 assert!(
9053 matches!(via_into, std::borrow::Cow::Borrowed(_)),
9054 "Into<Cow<'static, str>>::into on \
9055 RestartStrategy::{variant:?} must land on the \
9056 zero-alloc Cow::Borrowed arm — the blanket-derived \
9057 Into shape must resolve to the same Cow::Borrowed \
9058 dispatch as the explicit From impl"
9059 );
9060 }
9061 }
9062
9063 #[test]
9064 fn restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
9065 // Cross-axis partition pin: the newly lifted trait-idiomatic
9066 // `From<RestartStrategy> for std::borrow::Cow<'static, str>`
9067 // (this lift), the paired owned-input `From<RestartStrategy>
9068 // for &'static str` (523157d), and the paired owned-input
9069 // `From<RestartStrategy> for String` (7baa18a) forward
9070 // projections must resolve identically on every arm, locking
9071 // the three return-shape paths together by construction so any
9072 // future detour trips at caixa-core test time. Also byte-parity
9073 // witness against the sibling [`ToString::to_string`] surface
9074 // routed through [`std::fmt::Display`] — every owned-heap-
9075 // string path (the `Cow::Owned` promotion of this axis's
9076 // `.into_owned()`, `From<RestartStrategy> for String`, and
9077 // `.to_string()`) resolves to the same lifted
9078 // [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const per arm.
9079 //
9080 // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
9081 // witness over [`super::RestartStrategy::ALL`] that
9082 // materializes the four-arm accept-set through the
9083 // [`std::borrow::Cow<'static, str>`] axis alone — the exact
9084 // shape a future `axum::response::IntoResponse` per-strategy
9085 // rejection-body composer, a future M4 admission-webhook
9086 // per-strategy rejection-reason emitter whose typing rules out
9087 // the sibling [`AsRef<str>`] borrowed return, or a future
9088 // substrate-wide per-strategy diagnostic surface that binds
9089 // through a [`Cow<'static, str>`] boundary reaches through.
9090 // The pipe witness also pins the zero-alloc discipline: every
9091 // element in the collected vector satisfies the
9092 // [`std::borrow::Cow::Borrowed`] arm predicate, so a future
9093 // accidental silent-allocation regression on the pipe's
9094 // iteration axis is a caixa-core-test-time failure.
9095 for &variant in RestartStrategy::ALL {
9096 let via_cow: std::borrow::Cow<'static, str> =
9097 <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
9098 let via_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
9099 let via_string: String = <String as From<RestartStrategy>>::from(variant);
9100 assert_eq!(
9101 via_cow.as_ref(),
9102 via_static,
9103 "From<RestartStrategy> for Cow<'static, str> and \
9104 From<RestartStrategy> for &'static str must resolve \
9105 identically on RestartStrategy::{variant:?} — \
9106 divergence signals the Cow<'static, str> and \
9107 &'static str return-shape paths have drifted onto \
9108 different emit-sets"
9109 );
9110 assert_eq!(
9111 via_cow.as_ref(),
9112 via_string.as_str(),
9113 "From<RestartStrategy> for Cow<'static, str> and \
9114 From<RestartStrategy> for String must resolve \
9115 identically on RestartStrategy::{variant:?} — \
9116 divergence signals the Cow<'static, str> and String \
9117 return-shape paths have drifted onto different \
9118 emit-sets"
9119 );
9120 let via_to_string: String = variant.to_string();
9121 assert_eq!(
9122 via_cow.as_ref(),
9123 via_to_string.as_str(),
9124 "From<RestartStrategy> for Cow<'static, str> must \
9125 byte-equal RestartStrategy::to_string on \
9126 RestartStrategy::{variant:?} — divergence signals the \
9127 trait-idiomatic Cow<'static, str> forward-projection \
9128 axis and the ToString-through-Display axis have \
9129 drifted onto different emit-sets"
9130 );
9131 }
9132 let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
9133 .iter()
9134 .copied()
9135 .map(std::borrow::Cow::from)
9136 .collect();
9137 let via_method: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
9138 .iter()
9139 .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
9140 .collect();
9141 assert_eq!(
9142 via_iter, via_method,
9143 "`.iter().copied().map(Cow::from)` over \
9144 RestartStrategy::ALL must byte-equal `.iter().map(|s| \
9145 Cow::Borrowed(s.as_str()))` on every arm — the \
9146 trait-idiomatic `From<RestartStrategy> for Cow<'static, \
9147 str>` axis is what makes the `Cow::from` composition \
9148 route through the substrate-primitive \
9149 `RestartStrategy::as_str` accessor with the zero-alloc \
9150 Cow::Borrowed arm by construction, rather than a \
9151 per-call-site `Cow::Owned(strategy.to_string())` \
9152 allocation"
9153 );
9154 for cow in &via_iter {
9155 assert!(
9156 matches!(cow, std::borrow::Cow::Borrowed(_)),
9157 "every element of the \
9158 .iter().copied().map(Cow::from) pipe over \
9159 RestartStrategy::ALL must land on the zero-alloc \
9160 Cow::Borrowed arm — a Cow::Owned outcome on any arm \
9161 signals the pipe's iteration axis has silently \
9162 allocated where the substrate-primitive \
9163 RestartStrategy::as_str `&'static str` return makes \
9164 the borrowed arm the type-correct projection"
9165 );
9166 }
9167 }
9168
9169 #[test]
9170 fn restart_strategy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
9171 // Fail-before-pass-after byte-parity pin on the newly lifted
9172 // `impl From<&RestartStrategy> for std::borrow::Cow<'static, str>` —
9173 // asserts the borrowed-input standard-library trait impl and
9174 // the substrate-primitive [`super::RestartStrategy::as_str`]
9175 // `pub const fn` accessor resolve to the same four-arm emit-
9176 // set across every arm the exhaustive
9177 // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
9178 // standard library does not carry a blanket
9179 // `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor a
9180 // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
9181 // the borrowed-input `Cow<'static, str>` forward-projection
9182 // axis is a distinct trait-idiomatic surface that a
9183 // `let key: Cow<'static, str> = (&strategy).into();`-shaped
9184 // call site or a
9185 // `RestartStrategy::ALL.iter().map(Cow::from)`-shaped pipe
9186 // reaches through this impl and no other — the paired owned-
9187 // input `From<RestartStrategy> for Cow<'static, str>` impl
9188 // (7dd28b3) forces every borrowed-input call site through an
9189 // explicit `Copy` deref (`Cow::from(*strategy)`) or a
9190 // `Cow::Borrowed(strategy.as_str())` open-code whose type
9191 // bounds have no compile-time link back to the substrate
9192 // primitive.
9193 //
9194 // Also asserts the projection lands on the zero-alloc
9195 // [`std::borrow::Cow::Borrowed`] arm (not the
9196 // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
9197 // [`super::RestartStrategy::as_str`] accessor's `&'static str`
9198 // return lifetime by construction makes the borrowed arm the
9199 // type-correct projection with no runtime allocation on the
9200 // borrowed-input surface just as on the paired owned-input
9201 // surface.
9202 //
9203 // Second peer on the substrate-wide trait-idiomatic
9204 // [`std::borrow::Cow<'static, str>`] forward-projection family
9205 // on this enum — closes the `{Self, &Self}` input-shape
9206 // corner of the [`Cow<'static, str>`] axis on the first M2
9207 // OTP-shape closed-set fieldless typed enum peer on the caixa
9208 // surface (`:supervisor :estrategia`), exactly as d45c409
9209 // closed it on the top-level [`super::CaixaKind`] one commit
9210 // after the owning half (99c1735) landed. Every future
9211 // closed-set fieldless typed enum peer on the substrate is a
9212 // future target of the campaign.
9213 for &variant in RestartStrategy::ALL {
9214 let via_trait: std::borrow::Cow<'static, str> =
9215 <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
9216 let via_method: &'static str = variant.as_str();
9217 assert_eq!(
9218 via_trait.as_ref(),
9219 via_method,
9220 "From<&RestartStrategy> for Cow<'static, str> impl must \
9221 round-trip &RestartStrategy::{variant:?} to the same \
9222 lifted SUPERVISOR_ESTRATEGIA_* const \
9223 RestartStrategy::as_str returns — divergence signals a \
9224 silent detour off the substrate-primitive accessor"
9225 );
9226 assert!(
9227 matches!(via_trait, std::borrow::Cow::Borrowed(_)),
9228 "From<&RestartStrategy> for Cow<'static, str> impl must \
9229 land on the zero-alloc Cow::Borrowed arm on \
9230 &RestartStrategy::{variant:?} — a Cow::Owned outcome \
9231 signals the projection has silently allocated where \
9232 the substrate-primitive RestartStrategy::as_str \
9233 `&'static str` return makes the borrowed arm the \
9234 type-correct projection"
9235 );
9236 let via_into: std::borrow::Cow<'static, str> = (&variant).into();
9237 assert_eq!(
9238 via_into.as_ref(),
9239 via_method,
9240 "Into<Cow<'static, str>>::into on \
9241 &RestartStrategy::{variant:?} must byte-equal \
9242 RestartStrategy::as_str on the same input — the \
9243 blanket-derived Into shape must resolve to the same \
9244 as_str dispatch as the explicit From impl"
9245 );
9246 assert!(
9247 matches!(via_into, std::borrow::Cow::Borrowed(_)),
9248 "Into<Cow<'static, str>>::into on \
9249 &RestartStrategy::{variant:?} must land on the \
9250 zero-alloc Cow::Borrowed arm — the blanket-derived \
9251 Into shape must resolve to the same Cow::Borrowed \
9252 dispatch as the explicit From impl"
9253 );
9254 }
9255 }
9256
9257 #[test]
9258 fn restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
9259 // Cross-axis partition pin: the newly lifted trait-idiomatic
9260 // borrowed-input `From<&RestartStrategy> for
9261 // std::borrow::Cow<'static, str>` (this lift), the paired
9262 // owned-input `From<RestartStrategy> for
9263 // std::borrow::Cow<'static, str>` (7dd28b3), the paired
9264 // borrowed-input owned-`&'static str` `From<&RestartStrategy>
9265 // for &'static str`, and the paired borrowed-input owned-
9266 // `String` `From<&RestartStrategy> for String` must resolve
9267 // identically on every arm, locking the four
9268 // return-shape × input-shape paths together by construction so
9269 // any future detour trips at caixa-core test time. Also byte-
9270 // parity witness against the sibling [`ToString::to_string`]
9271 // surface routed through [`std::fmt::Display`] — every owned-
9272 // heap-string path (this axis's `.into_owned()` promotion, the
9273 // paired [`From<&RestartStrategy> for String`], and
9274 // `.to_string()`) resolves to the same lifted
9275 // [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const per arm.
9276 //
9277 // Then a `.iter().map(std::borrow::Cow::from)` pipe witness
9278 // over [`super::RestartStrategy::ALL`] — whose iterator yields
9279 // `&RestartStrategy` by construction, so the borrowed-input
9280 // [`Cow<'static, str>`] axis is what routes the pipe through
9281 // the substrate-primitive [`super::RestartStrategy::as_str`]
9282 // accessor without a spurious [`Copy`] deref (which would only
9283 // be reachable through the owned-input
9284 // [`From<RestartStrategy> for Cow<'static, str>`] axis by
9285 // first calling `.copied()` on the iterator). The pipe witness
9286 // also pins the zero-alloc discipline: every element in the
9287 // collected vector satisfies the [`std::borrow::Cow::Borrowed`]
9288 // arm predicate, so a future accidental silent-allocation
9289 // regression on the pipe's iteration axis is a caixa-core-
9290 // test-time failure.
9291 for &strategy in RestartStrategy::ALL {
9292 let borrowed_cow: std::borrow::Cow<'static, str> =
9293 <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&strategy);
9294 let owned_cow: std::borrow::Cow<'static, str> =
9295 <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(strategy);
9296 let borrowed_static: &'static str =
9297 <&'static str as From<&RestartStrategy>>::from(&strategy);
9298 let borrowed_string: String = <String as From<&RestartStrategy>>::from(&strategy);
9299 assert_eq!(
9300 borrowed_cow, owned_cow,
9301 "From<&RestartStrategy> for Cow<'static, str> and \
9302 From<RestartStrategy> for Cow<'static, str> must \
9303 resolve identically on RestartStrategy::{strategy:?} — \
9304 divergence signals the borrowed-input and owned-input \
9305 Cow<'static, str> forward-projection input-shape \
9306 paths have drifted onto different emit-sets"
9307 );
9308 assert_eq!(
9309 borrowed_cow.as_ref(),
9310 borrowed_static,
9311 "From<&RestartStrategy> for Cow<'static, str> and \
9312 From<&RestartStrategy> for &'static str must resolve \
9313 identically on RestartStrategy::{strategy:?} — \
9314 divergence signals the borrowed-input Cow<'static, \
9315 str> and &'static str return-shape paths have drifted \
9316 onto different emit-sets"
9317 );
9318 assert_eq!(
9319 borrowed_cow.as_ref(),
9320 borrowed_string.as_str(),
9321 "From<&RestartStrategy> for Cow<'static, str> and \
9322 From<&RestartStrategy> for String must resolve \
9323 identically on RestartStrategy::{strategy:?} — \
9324 divergence signals the borrowed-input Cow<'static, \
9325 str> and owned-`String` return-shape paths have \
9326 drifted onto different emit-sets"
9327 );
9328 let via_to_string: String = strategy.to_string();
9329 assert_eq!(
9330 borrowed_cow.as_ref(),
9331 via_to_string.as_str(),
9332 "From<&RestartStrategy> for Cow<'static, str> must \
9333 byte-equal RestartStrategy::to_string on \
9334 RestartStrategy::{strategy:?} — divergence signals \
9335 the trait-idiomatic borrowed-input Cow<'static, str> \
9336 forward-projection axis and the ToString-through-\
9337 Display axis have drifted onto different emit-sets"
9338 );
9339 }
9340 let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
9341 .iter()
9342 .map(std::borrow::Cow::from)
9343 .collect();
9344 let via_method: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
9345 .iter()
9346 .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
9347 .collect();
9348 assert_eq!(
9349 via_iter, via_method,
9350 "`.iter().map(Cow::from)` over RestartStrategy::ALL — a \
9351 call site whose iteration axis holds `&RestartStrategy` \
9352 by construction — must byte-equal `.iter().map(|s| \
9353 Cow::Borrowed(s.as_str()))` on every arm — the borrowed-\
9354 input Cow<'static, str> `From<&RestartStrategy> for \
9355 Cow<'static, str>` axis is what makes the `Cow::from` \
9356 composition route through the substrate-primitive \
9357 `RestartStrategy::as_str` accessor with the zero-alloc \
9358 Cow::Borrowed arm by construction and without a spurious \
9359 `Copy` deref (which would only be reachable through the \
9360 owned-input `From<RestartStrategy> for Cow<'static, str>` \
9361 axis by first calling `.copied()` on the iterator)"
9362 );
9363 for cow in &via_iter {
9364 assert!(
9365 matches!(cow, std::borrow::Cow::Borrowed(_)),
9366 "every element of the .iter().map(Cow::from) pipe \
9367 over RestartStrategy::ALL must land on the zero-\
9368 alloc Cow::Borrowed arm — a Cow::Owned outcome on \
9369 any arm signals the pipe's iteration axis has \
9370 silently allocated where the substrate-primitive \
9371 RestartStrategy::as_str `&'static str` return makes \
9372 the borrowed arm the type-correct projection"
9373 );
9374 }
9375 }
9376
9377 #[test]
9378 fn restart_strategy_from_into_box_str_routes_through_as_str_accessor() {
9379 // Fail-before-pass-after byte-parity pin on the newly lifted
9380 // `impl From<RestartStrategy> for Box<str>` — asserts the
9381 // owned-input standard-library trait impl and the
9382 // substrate-primitive [`super::RestartStrategy::as_str`]
9383 // `pub const fn` accessor resolve to the same four-arm emit-
9384 // set across every arm the exhaustive
9385 // [`super::RestartStrategy::ALL`] slice enumerates. Opens the
9386 // substrate-wide `Box<str>` forward-projection campaign tier
9387 // on the first M2 OTP-shape closed-set fieldless typed enum
9388 // peer on the caixa surface (`:supervisor :estrategia`),
9389 // immediately after the paired `Cow<'static, str>` axis
9390 // (7dd28b3 / ee577fd) closed the
9391 // `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
9392 // 2×3 corner on this enum. Rust's standard library carries
9393 // `impl From<&str> for Box<str>` and
9394 // `impl From<String> for Box<str>` but no blanket
9395 // `impl<T: AsRef<str>> From<T> for Box<str>`, so this axis is
9396 // a distinct trait-idiomatic surface that a
9397 // `let key: Box<str> = strategy.into();`-shaped call site
9398 // reaches through this impl and no other — a paired
9399 // `Box::from(strategy.as_str())` open-code has no compile-
9400 // time link back to the substrate primitive.
9401 for &variant in RestartStrategy::ALL {
9402 let via_trait: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
9403 let via_method: &'static str = variant.as_str();
9404 assert_eq!(
9405 via_trait.as_ref(),
9406 via_method,
9407 "From<RestartStrategy> for Box<str> impl must round-\
9408 trip RestartStrategy::{variant:?} to the same lifted \
9409 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
9410 returns — divergence signals a silent detour off the \
9411 substrate-primitive accessor"
9412 );
9413 let via_into: Box<str> = variant.into();
9414 assert_eq!(
9415 via_into.as_ref(),
9416 via_method,
9417 "Into<Box<str>>::into on RestartStrategy::{variant:?} \
9418 must byte-equal RestartStrategy::as_str on the same \
9419 input — the blanket-derived Into shape must resolve \
9420 to the same as_str dispatch as the explicit From impl"
9421 );
9422 }
9423 }
9424
9425 #[test]
9426 fn restart_strategy_from_borrowed_into_box_str_routes_through_as_str_accessor() {
9427 // Fail-before-pass-after byte-parity pin on the newly lifted
9428 // `impl From<&RestartStrategy> for Box<str>` — asserts the
9429 // borrowed-input standard-library trait impl and the
9430 // substrate-primitive [`super::RestartStrategy::as_str`]
9431 // `pub const fn` accessor resolve to the same four-arm emit-
9432 // set across every arm the exhaustive
9433 // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
9434 // standard library does not carry a blanket
9435 // `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
9436 // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
9437 // so the borrowed-input `Box<str>` forward-projection axis
9438 // is a distinct trait-idiomatic surface that a
9439 // `let key: Box<str> = (&strategy).into();`-shaped call site
9440 // or a `RestartStrategy::ALL.iter().map(Box::<str>::from)`-
9441 // shaped pipe reaches through this impl and no other — the
9442 // paired owned-input `From<RestartStrategy> for Box<str>`
9443 // impl (69ef45c) forces every borrowed-input call site
9444 // through an explicit `Copy` deref
9445 // (`Box::<str>::from((*strategy).as_str())`) or a
9446 // `Box::<str>::from(strategy.as_str())` open-code whose
9447 // type bounds have no compile-time link back to the
9448 // substrate primitive.
9449 //
9450 // Second peer on the substrate-wide trait-idiomatic
9451 // [`Box<str>`] forward-projection family on this enum —
9452 // closes the `{Self, &Self}` input-shape corner of the
9453 // [`Box<str>`] axis on the first M2 OTP-shape closed-set
9454 // fieldless typed enum peer on the caixa surface
9455 // (`:supervisor :estrategia`), exactly as ee577fd closed
9456 // the paired [`Cow<'static, str>`] axis one commit after
9457 // its owning half (7dd28b3) landed. Every future closed-
9458 // set fieldless typed enum peer on the substrate is a
9459 // future target of the campaign.
9460 //
9461 // Also byte-parity witness against the paired owned-input
9462 // [`From<RestartStrategy> for Box<str>`] and the sibling
9463 // borrowed-input [`From<&RestartStrategy> for &'static str`],
9464 // [`From<&RestartStrategy> for String`], and
9465 // [`From<&RestartStrategy> for Cow<'static, str>`]
9466 // return-shape axes — locking the four
9467 // return-shape × input-shape paths together by construction
9468 // so any future detour trips at caixa-core test time. Then a
9469 // `.iter().map(Box::<str>::from)` pipe witness over
9470 // [`super::RestartStrategy::ALL`] — whose iterator yields
9471 // `&RestartStrategy` by construction, so the borrowed-input
9472 // [`Box<str>`] axis is what routes the pipe through the
9473 // substrate-primitive [`super::RestartStrategy::as_str`]
9474 // accessor without a spurious [`Copy`] deref (which would
9475 // only be reachable through the owned-input
9476 // [`From<RestartStrategy> for Box<str>`] axis by first
9477 // calling `.copied()` on the iterator).
9478 for &variant in RestartStrategy::ALL {
9479 let via_trait: Box<str> = <Box<str> as From<&RestartStrategy>>::from(&variant);
9480 let via_method: &'static str = variant.as_str();
9481 assert_eq!(
9482 via_trait.as_ref(),
9483 via_method,
9484 "From<&RestartStrategy> for Box<str> impl must \
9485 round-trip &RestartStrategy::{variant:?} to the same \
9486 lifted SUPERVISOR_ESTRATEGIA_* const \
9487 RestartStrategy::as_str returns — divergence signals \
9488 a silent detour off the substrate-primitive accessor"
9489 );
9490 let via_into: Box<str> = (&variant).into();
9491 assert_eq!(
9492 via_into.as_ref(),
9493 via_method,
9494 "Into<Box<str>>::into on &RestartStrategy::{variant:?} \
9495 must byte-equal RestartStrategy::as_str on the same \
9496 input — the blanket-derived Into shape must resolve \
9497 to the same as_str dispatch as the explicit From impl"
9498 );
9499 let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
9500 assert_eq!(
9501 via_trait, owned_box,
9502 "From<&RestartStrategy> for Box<str> and \
9503 From<RestartStrategy> for Box<str> must resolve \
9504 identically on RestartStrategy::{variant:?} — \
9505 divergence signals the borrowed-input and owned-input \
9506 Box<str> forward-projection input-shape paths have \
9507 drifted onto different emit-sets"
9508 );
9509 let borrowed_static: &'static str =
9510 <&'static str as From<&RestartStrategy>>::from(&variant);
9511 assert_eq!(
9512 via_trait.as_ref(),
9513 borrowed_static,
9514 "From<&RestartStrategy> for Box<str> and \
9515 From<&RestartStrategy> for &'static str must resolve \
9516 identically on RestartStrategy::{variant:?} — \
9517 divergence signals the borrowed-input Box<str> and \
9518 &'static str return-shape paths have drifted onto \
9519 different emit-sets"
9520 );
9521 let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
9522 assert_eq!(
9523 via_trait.as_ref(),
9524 borrowed_string.as_str(),
9525 "From<&RestartStrategy> for Box<str> and \
9526 From<&RestartStrategy> for String must resolve \
9527 identically on RestartStrategy::{variant:?} — \
9528 divergence signals the borrowed-input Box<str> and \
9529 owned-`String` return-shape paths have drifted onto \
9530 different emit-sets"
9531 );
9532 let borrowed_cow: std::borrow::Cow<'static, str> =
9533 <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
9534 assert_eq!(
9535 via_trait.as_ref(),
9536 borrowed_cow.as_ref(),
9537 "From<&RestartStrategy> for Box<str> and \
9538 From<&RestartStrategy> for Cow<'static, str> must \
9539 resolve identically on RestartStrategy::{variant:?} — \
9540 divergence signals the borrowed-input Box<str> and \
9541 Cow<'static, str> return-shape paths have drifted \
9542 onto different emit-sets"
9543 );
9544 }
9545 let via_iter: Vec<Box<str>> = RestartStrategy::ALL.iter().map(Box::<str>::from).collect();
9546 let via_method: Vec<Box<str>> = RestartStrategy::ALL
9547 .iter()
9548 .map(|s| Box::<str>::from(s.as_str()))
9549 .collect();
9550 assert_eq!(
9551 via_iter, via_method,
9552 "`.iter().map(Box::<str>::from)` over \
9553 RestartStrategy::ALL — a call site whose iteration axis \
9554 holds `&RestartStrategy` by construction — must byte-\
9555 equal `.iter().map(|s| Box::<str>::from(s.as_str()))` \
9556 on every arm — the borrowed-input Box<str> \
9557 `From<&RestartStrategy> for Box<str>` axis is what \
9558 makes the `Box::<str>::from` composition route through \
9559 the substrate-primitive `RestartStrategy::as_str` \
9560 accessor without a spurious `Copy` deref (which would \
9561 only be reachable through the owned-input \
9562 `From<RestartStrategy> for Box<str>` axis by first \
9563 calling `.copied()` on the iterator)"
9564 );
9565 }
9566
9567 #[test]
9568 fn restart_strategy_from_into_arc_str_routes_through_as_str_accessor() {
9569 // Fail-before-pass-after byte-parity pin on the newly lifted
9570 // `impl From<RestartStrategy> for std::sync::Arc<str>` — asserts
9571 // the owned-input standard-library trait impl and the
9572 // substrate-primitive [`super::RestartStrategy::as_str`]
9573 // `pub const fn` accessor resolve to the same four-arm emit-
9574 // set across every arm the exhaustive
9575 // [`super::RestartStrategy::ALL`] slice enumerates. Opens the
9576 // substrate-wide [`std::sync::Arc<str>`] forward-projection
9577 // campaign tier on the first M2 OTP-shape closed-set fieldless
9578 // typed enum peer on the caixa surface
9579 // (`:supervisor :estrategia`), immediately after the paired
9580 // [`Box<str>`] axis (69ef45c / 59ae5dc) closed the
9581 // `{Self, &Self} × {&'static str, String, Cow<'static, str>,
9582 // Box<str>}` 2×4 corner on this enum. Rust's standard library
9583 // carries `impl From<&str> for std::sync::Arc<str>` and
9584 // `impl From<String> for std::sync::Arc<str>` but no blanket
9585 // `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor
9586 // an `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`),
9587 // so this axis is a distinct trait-idiomatic surface that a
9588 // `let key: std::sync::Arc<str> = strategy.into();`-shaped call
9589 // site reaches through this impl and no other — a paired
9590 // `std::sync::Arc::<str>::from(strategy.as_str())` open-code
9591 // has no compile-time link back to the substrate primitive,
9592 // and a two-step `std::sync::Arc::<str>::from(String::from(
9593 // strategy))` composition through the owned-`String` axis
9594 // allocates twice (once into the intermediate `String`, once
9595 // into the [`Arc<str>`] on the `From<String>` conversion)
9596 // where the single-step trait impl allocates once.
9597 //
9598 // Cross-axis byte-parity witness against the sibling owned-
9599 // input `{&'static str, String, Cow<'static, str>, Box<str>}`
9600 // return-shape axes — locking the five return-shape paths on
9601 // the owned-input surface together by construction so any
9602 // future detour off the substrate-primitive
9603 // [`super::RestartStrategy::as_str`] accessor trips at caixa-
9604 // core test time.
9605 for &variant in RestartStrategy::ALL {
9606 let via_trait: std::sync::Arc<str> =
9607 <std::sync::Arc<str> as From<RestartStrategy>>::from(variant);
9608 let via_method: &'static str = variant.as_str();
9609 assert_eq!(
9610 via_trait.as_ref(),
9611 via_method,
9612 "From<RestartStrategy> for std::sync::Arc<str> impl \
9613 must round-trip RestartStrategy::{variant:?} to the \
9614 same lifted SUPERVISOR_ESTRATEGIA_* const \
9615 RestartStrategy::as_str returns — divergence signals \
9616 a silent detour off the substrate-primitive accessor"
9617 );
9618 let via_into: std::sync::Arc<str> = variant.into();
9619 assert_eq!(
9620 via_into.as_ref(),
9621 via_method,
9622 "Into<std::sync::Arc<str>>::into on \
9623 RestartStrategy::{variant:?} must byte-equal \
9624 RestartStrategy::as_str on the same input — the \
9625 blanket-derived Into shape must resolve to the same \
9626 as_str dispatch as the explicit From impl"
9627 );
9628 let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
9629 assert_eq!(
9630 via_trait.as_ref(),
9631 owned_static,
9632 "From<RestartStrategy> for std::sync::Arc<str> and \
9633 From<RestartStrategy> for &'static str must resolve \
9634 identically on RestartStrategy::{variant:?} — \
9635 divergence signals the owned-input std::sync::Arc<str> \
9636 and &'static str return-shape paths have drifted onto \
9637 different emit-sets"
9638 );
9639 let owned_string: String = <String as From<RestartStrategy>>::from(variant);
9640 assert_eq!(
9641 via_trait.as_ref(),
9642 owned_string.as_str(),
9643 "From<RestartStrategy> for std::sync::Arc<str> and \
9644 From<RestartStrategy> for String must resolve \
9645 identically on RestartStrategy::{variant:?} — \
9646 divergence signals the owned-input std::sync::Arc<str> \
9647 and owned-`String` return-shape paths have drifted \
9648 onto different emit-sets"
9649 );
9650 let owned_cow: std::borrow::Cow<'static, str> =
9651 <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
9652 assert_eq!(
9653 via_trait.as_ref(),
9654 owned_cow.as_ref(),
9655 "From<RestartStrategy> for std::sync::Arc<str> and \
9656 From<RestartStrategy> for Cow<'static, str> must \
9657 resolve identically on RestartStrategy::{variant:?} — \
9658 divergence signals the owned-input std::sync::Arc<str> \
9659 and Cow<'static, str> return-shape paths have drifted \
9660 onto different emit-sets"
9661 );
9662 let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
9663 assert_eq!(
9664 via_trait.as_ref(),
9665 owned_box.as_ref(),
9666 "From<RestartStrategy> for std::sync::Arc<str> and \
9667 From<RestartStrategy> for Box<str> must resolve \
9668 identically on RestartStrategy::{variant:?} — \
9669 divergence signals the owned-input std::sync::Arc<str> \
9670 and Box<str> return-shape paths have drifted onto \
9671 different emit-sets"
9672 );
9673 }
9674 }
9675
9676 #[test]
9677 fn restart_strategy_from_borrowed_into_arc_str_routes_through_as_str_accessor() {
9678 // Fail-before-pass-after byte-parity pin on the newly lifted
9679 // `impl From<&RestartStrategy> for std::sync::Arc<str>` —
9680 // asserts the borrowed-input standard-library trait impl and
9681 // the substrate-primitive [`super::RestartStrategy::as_str`]
9682 // `pub const fn` accessor resolve to the same four-arm emit-
9683 // set across every arm the exhaustive
9684 // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
9685 // standard library does not carry a blanket
9686 // `impl<T: AsRef<str>> From<&T> for std::sync::Arc<str>` (nor
9687 // a `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
9688 // so the borrowed-input [`std::sync::Arc<str>`] forward-
9689 // projection axis is a distinct trait-idiomatic surface that a
9690 // `let key: std::sync::Arc<str> = (&strategy).into();`-shaped
9691 // call site or a
9692 // `RestartStrategy::ALL.iter().map(std::sync::Arc::<str>::from)`-
9693 // shaped pipe reaches through this impl and no other — the
9694 // paired owned-input
9695 // `From<RestartStrategy> for std::sync::Arc<str>` impl
9696 // (bca2ec8) forces every borrowed-input call site through an
9697 // explicit `Copy` deref
9698 // (`std::sync::Arc::<str>::from((*strategy).as_str())`) or a
9699 // `std::sync::Arc::<str>::from(strategy.as_str())` open-code
9700 // whose type bounds have no compile-time link back to the
9701 // substrate primitive.
9702 //
9703 // Second peer on the substrate-wide trait-idiomatic
9704 // [`std::sync::Arc<str>`] forward-projection family on this
9705 // enum — closes the `{Self, &Self}` input-shape corner of
9706 // the [`std::sync::Arc<str>`] axis on the first M2 OTP-shape
9707 // closed-set fieldless typed enum peer on the caixa surface
9708 // (`:supervisor :estrategia`), exactly as 59ae5dc closed the
9709 // paired [`Box<str>`] axis one commit after its owning half
9710 // (69ef45c) landed. Every future closed-set fieldless typed
9711 // enum peer on the substrate is a future target of the
9712 // campaign.
9713 //
9714 // Also byte-parity witness against the paired owned-input
9715 // [`From<RestartStrategy> for std::sync::Arc<str>`] and the
9716 // sibling borrowed-input
9717 // [`From<&RestartStrategy> for &'static str`],
9718 // [`From<&RestartStrategy> for String`],
9719 // [`From<&RestartStrategy> for Cow<'static, str>`], and
9720 // [`From<&RestartStrategy> for Box<str>`] return-shape axes —
9721 // locking the five return-shape × input-shape paths together
9722 // by construction so any future detour trips at caixa-core
9723 // test time. Then a
9724 // `.iter().map(std::sync::Arc::<str>::from)` pipe witness over
9725 // [`super::RestartStrategy::ALL`] — whose iterator yields
9726 // `&RestartStrategy` by construction, so the borrowed-input
9727 // [`std::sync::Arc<str>`] axis is what routes the pipe
9728 // through the substrate-primitive
9729 // [`super::RestartStrategy::as_str`] accessor without a
9730 // spurious [`Copy`] deref (which would only be reachable
9731 // through the owned-input
9732 // [`From<RestartStrategy> for std::sync::Arc<str>`] axis by
9733 // first calling `.copied()` on the iterator).
9734 for &variant in RestartStrategy::ALL {
9735 let via_trait: std::sync::Arc<str> =
9736 <std::sync::Arc<str> as From<&RestartStrategy>>::from(&variant);
9737 let via_method: &'static str = variant.as_str();
9738 assert_eq!(
9739 via_trait.as_ref(),
9740 via_method,
9741 "From<&RestartStrategy> for std::sync::Arc<str> impl \
9742 must round-trip &RestartStrategy::{variant:?} to the \
9743 same lifted SUPERVISOR_ESTRATEGIA_* const \
9744 RestartStrategy::as_str returns — divergence signals \
9745 a silent detour off the substrate-primitive accessor"
9746 );
9747 let via_into: std::sync::Arc<str> = (&variant).into();
9748 assert_eq!(
9749 via_into.as_ref(),
9750 via_method,
9751 "Into<std::sync::Arc<str>>::into on \
9752 &RestartStrategy::{variant:?} must byte-equal \
9753 RestartStrategy::as_str on the same input — the \
9754 blanket-derived Into shape must resolve to the same \
9755 as_str dispatch as the explicit From impl"
9756 );
9757 let owned_arc: std::sync::Arc<str> =
9758 <std::sync::Arc<str> as From<RestartStrategy>>::from(variant);
9759 assert_eq!(
9760 via_trait, owned_arc,
9761 "From<&RestartStrategy> for std::sync::Arc<str> and \
9762 From<RestartStrategy> for std::sync::Arc<str> must \
9763 resolve identically on RestartStrategy::{variant:?} — \
9764 divergence signals the borrowed-input and owned-input \
9765 std::sync::Arc<str> forward-projection input-shape \
9766 paths have drifted onto different emit-sets"
9767 );
9768 let borrowed_static: &'static str =
9769 <&'static str as From<&RestartStrategy>>::from(&variant);
9770 assert_eq!(
9771 via_trait.as_ref(),
9772 borrowed_static,
9773 "From<&RestartStrategy> for std::sync::Arc<str> and \
9774 From<&RestartStrategy> for &'static str must resolve \
9775 identically on RestartStrategy::{variant:?} — \
9776 divergence signals the borrowed-input \
9777 std::sync::Arc<str> and &'static str return-shape \
9778 paths have drifted onto different emit-sets"
9779 );
9780 let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
9781 assert_eq!(
9782 via_trait.as_ref(),
9783 borrowed_string.as_str(),
9784 "From<&RestartStrategy> for std::sync::Arc<str> and \
9785 From<&RestartStrategy> for String must resolve \
9786 identically on RestartStrategy::{variant:?} — \
9787 divergence signals the borrowed-input \
9788 std::sync::Arc<str> and owned-`String` return-shape \
9789 paths have drifted onto different emit-sets"
9790 );
9791 let borrowed_cow: std::borrow::Cow<'static, str> =
9792 <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
9793 assert_eq!(
9794 via_trait.as_ref(),
9795 borrowed_cow.as_ref(),
9796 "From<&RestartStrategy> for std::sync::Arc<str> and \
9797 From<&RestartStrategy> for Cow<'static, str> must \
9798 resolve identically on RestartStrategy::{variant:?} — \
9799 divergence signals the borrowed-input \
9800 std::sync::Arc<str> and Cow<'static, str> return-shape \
9801 paths have drifted onto different emit-sets"
9802 );
9803 let borrowed_box: Box<str> = <Box<str> as From<&RestartStrategy>>::from(&variant);
9804 assert_eq!(
9805 via_trait.as_ref(),
9806 borrowed_box.as_ref(),
9807 "From<&RestartStrategy> for std::sync::Arc<str> and \
9808 From<&RestartStrategy> for Box<str> must resolve \
9809 identically on RestartStrategy::{variant:?} — \
9810 divergence signals the borrowed-input \
9811 std::sync::Arc<str> and Box<str> return-shape paths \
9812 have drifted onto different emit-sets"
9813 );
9814 }
9815 let via_iter: Vec<std::sync::Arc<str>> = RestartStrategy::ALL
9816 .iter()
9817 .map(std::sync::Arc::<str>::from)
9818 .collect();
9819 let via_method: Vec<std::sync::Arc<str>> = RestartStrategy::ALL
9820 .iter()
9821 .map(|s| std::sync::Arc::<str>::from(s.as_str()))
9822 .collect();
9823 assert_eq!(
9824 via_iter, via_method,
9825 "`.iter().map(std::sync::Arc::<str>::from)` over \
9826 RestartStrategy::ALL — a call site whose iteration axis \
9827 holds `&RestartStrategy` by construction — must byte-\
9828 equal `.iter().map(|s| std::sync::Arc::<str>::from(s.as_str()))` \
9829 on every arm — the borrowed-input std::sync::Arc<str> \
9830 `From<&RestartStrategy> for std::sync::Arc<str>` axis is \
9831 what makes the `std::sync::Arc::<str>::from` composition \
9832 route through the substrate-primitive \
9833 `RestartStrategy::as_str` accessor without a spurious \
9834 `Copy` deref (which would only be reachable through the \
9835 owned-input `From<RestartStrategy> for std::sync::Arc<str>` \
9836 axis by first calling `.copied()` on the iterator)"
9837 );
9838 }
9839
9840 #[test]
9841 fn restart_policy_try_from_str_routes_through_from_wire_accessor() {
9842 // Fail-before-pass-after byte-parity pin on the newly lifted
9843 // `impl TryFrom<&str> for RestartPolicy` — asserts the standard-
9844 // library trait impl and the substrate-primitive
9845 // [`RestartPolicy::from_wire`] `Option<Self>` accessor resolve to
9846 // the same three-arm accept-set across every arm the exhaustive
9847 // [`RestartPolicy::ALL`] slice enumerates. Any future silent
9848 // detour that routes the trait impl through a divergent
9849 // projection (a per-arm inline `match s { "Permanent" =>
9850 // Ok(Self::Permanent), … }` re-inlining that opens a compile-time
9851 // link to the un-lifted arm-literal, a hypothetical
9852 // `#[serde(rename_all = "…")]` attribute drift that silently
9853 // splits the wire byte-string from every consumer that reaches
9854 // for this typed dispatch, an accidental swap onto the kebab-case
9855 // dispatcher-catalog axis the pre-existing [`std::str::FromStr`]
9856 // impl parses through and which would collide the two-axis
9857 // wire/catalog split the sibling [`RestartPolicy::from_wire`]
9858 // doc block makes load-bearing) trips at caixa-core test time
9859 // under `assert_eq!` rather than at a downstream
9860 // `impl TryFrom<&str>`-bound consumer's silent split. Sweeps
9861 // every one of the three arms [`RestartPolicy::ALL`] carries so
9862 // no arm's projection is covered only by the sibling method-
9863 // named `from_wire` path. Peer of the sibling
9864 // [`restart_strategy_try_from_str_routes_through_from_wire_accessor`]
9865 // (5b828ed) — extends the trait-idiomatic reverse-projection
9866 // axis onto the third and final M2-OTP-shape closed-set typed
9867 // enum on the caixa surface (the paired per-child restart-
9868 // decision-policy sibling on the same M2 `:supervisor` slot).
9869 for &variant in RestartPolicy::ALL {
9870 let wire = variant.as_str();
9871 assert_eq!(
9872 <RestartPolicy as TryFrom<&str>>::try_from(wire),
9873 Ok(variant),
9874 "TryFrom<&str> impl on RestartPolicy must round-trip \
9875 RestartPolicy::{variant:?}.as_str() = {wire:?} back to \
9876 Ok(RestartPolicy::{variant:?}) — divergence from \
9877 RestartPolicy::from_wire signals a silent detour off \
9878 the substrate-primitive accessor"
9879 );
9880 assert_eq!(
9881 <RestartPolicy as TryFrom<&str>>::try_from(wire).ok(),
9882 RestartPolicy::from_wire(wire),
9883 "TryFrom<&str> ok()-projection on {wire:?} must byte-\
9884 equal RestartPolicy::from_wire on the same input"
9885 );
9886 }
9887 }
9888
9889 #[test]
9890 fn restart_policy_try_from_str_rejects_unknown_byte_strings() {
9891 // Rejection witness on the `impl TryFrom<&str> for
9892 // RestartPolicy` — sweeps a candidate set of byte-strings
9893 // outside the three-arm PascalCase wire accept-set the sibling
9894 // [`RestartPolicy::as_str`] emits and asserts every one lands on
9895 // `Err(())`, so a future accidental widening of the trait impl's
9896 // accept-set (a stray additional
9897 // `_ if s.eq_ignore_ascii_case("Permanent") => Ok(…)` case-fold
9898 // path, a silent inclusion of the kebab-case dispatcher-catalog
9899 // byte-string the pre-existing [`std::str::FromStr`] impl the
9900 // [`gen_platform::FromStrKind`] derive installs parses onto the
9901 // wire axis — which would collide the two-axis
9902 // wire/dispatcher-catalog split the sibling
9903 // [`RestartPolicy::from_wire`] doc block makes load-bearing —
9904 // an English-rebrand or plural-arm silent alias that would widen
9905 // the wire accept-set past the OTP-canonical three) trips at
9906 // caixa-core test time. The candidate set includes the empty
9907 // string, whitespace-only padding, the kebab-case dispatcher-
9908 // catalog byte-strings on the sibling axis (a caller who
9909 // confuses the two axes trips here rather than at a downstream
9910 // consumer's silent reject), a lowercase / uppercase / mixed-case
9911 // fold of each PascalCase arm (a caller who assumes case-fold
9912 // acceptance trips here), leading/trailing whitespace padding,
9913 // the trailing-newline shape, quote-wrapped candidates, and a
9914 // residual set of plausible-but-wrong English rebrand
9915 // candidates. Peer of the sibling
9916 // [`restart_strategy_try_from_str_rejects_unknown_byte_strings`]
9917 // (5b828ed) rejection witness.
9918 let rejected: &[&str] = &[
9919 "",
9920 " ",
9921 "\n",
9922 "\t",
9923 "permanent",
9924 "temporary",
9925 "transient",
9926 "PERMANENT",
9927 "TEMPORARY",
9928 "TRANSIENT",
9929 "Permanents",
9930 "Permanent ",
9931 " Permanent",
9932 " Temporary ",
9933 "Permanent\n",
9934 "Transient\t",
9935 "\"Permanent\"",
9936 "Ephemeral",
9937 "Always",
9938 "Never",
9939 "OnAbnormalExit",
9940 "intrinsic",
9941 "?",
9942 ];
9943 for &input in rejected {
9944 assert_eq!(
9945 <RestartPolicy as TryFrom<&str>>::try_from(input),
9946 Err(()),
9947 "TryFrom<&str> impl on RestartPolicy must reject the \
9948 non-wire byte-string {input:?} — silent acceptance \
9949 signals an accept-set widening off the paired \
9950 RestartPolicy::from_wire resolver"
9951 );
9952 }
9953 }
9954
9955 #[test]
9956 fn restart_policy_try_from_str_and_from_wire_partition_the_accept_set() {
9957 // Cross-axis partition pin: the paired `TryFrom<&str>` and
9958 // `from_wire` reverse projections must resolve identically on
9959 // *every* input, not just the ones [`RestartPolicy::ALL`]
9960 // enumerates. Sweeps a mixed candidate set spanning accepted
9961 // (three-arm PascalCase wire byte-strings) and rejected (kebab-
9962 // case dispatcher-catalog byte-strings, empty, whitespace-
9963 // padded, quoted, English-rebrand candidates) inputs and asserts
9964 // the trait's `Result::ok()` projection byte-equals the method-
9965 // named resolver's `Option<Self>` return-shape on each, locking
9966 // the two paths together by construction so any future detour
9967 // (a stray `try_from` special-case that widens or narrows the
9968 // accept-set outside the paired `from_wire` resolver, an
9969 // accidental swap onto the kebab-case [`std::str::FromStr`]
9970 // impl the [`gen_platform::FromStrKind`] derive installs on the
9971 // sibling dispatcher-catalog axis) trips at caixa-core test
9972 // time. Peer of the sibling
9973 // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
9974 // pin — extends the round-trip discipline onto the M2-OTP-shape
9975 // per-child restart-policy axis.
9976 let candidates: &[&str] = &[
9977 "Permanent",
9978 "Temporary",
9979 "Transient",
9980 "",
9981 "permanent",
9982 "temporary",
9983 "transient",
9984 "PERMANENT",
9985 "unknown",
9986 "Permanent ",
9987 " Permanent",
9988 "\"Permanent\"",
9989 "Ephemeral",
9990 "OnAbnormalExit",
9991 "?",
9992 ];
9993 for &input in candidates {
9994 let via_trait: Option<RestartPolicy> =
9995 <RestartPolicy as TryFrom<&str>>::try_from(input).ok();
9996 let via_method: Option<RestartPolicy> = RestartPolicy::from_wire(input);
9997 assert_eq!(
9998 via_trait, via_method,
9999 "TryFrom<&str> and from_wire must resolve identically on \
10000 input {input:?} — divergence signals the two reverse-\
10001 projection paths have drifted onto different accept-sets"
10002 );
10003 }
10004 }
10005
10006 #[test]
10007 fn restart_policy_from_into_static_str_routes_through_as_str_accessor() {
10008 // Fail-before-pass-after byte-parity pin on the newly lifted
10009 // `impl From<RestartPolicy> for &'static str` — asserts the
10010 // standard-library trait impl and the substrate-primitive
10011 // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
10012 // the same three-arm emit-set across every arm the exhaustive
10013 // [`RestartPolicy::ALL`] slice enumerates. Any future silent
10014 // detour that routes the trait impl through a divergent
10015 // projection (a per-arm inline `match policy { Permanent =>
10016 // "Permanent", … }` re-inlining that opens a compile-time link
10017 // to the un-lifted arm-literal, an accidental swap onto the
10018 // sibling kebab-case [`Self::discriminant`] dispatcher-catalog
10019 // axis that would collide the two-axis wire/catalog split the
10020 // sibling [`RestartPolicy::from_wire`] doc block makes
10021 // load-bearing) trips at caixa-core test time under
10022 // `assert_eq!` rather than at a downstream
10023 // `impl Into<&'static str>`-bound consumer's silent split.
10024 // Sweeps every one of the three arms [`RestartPolicy::ALL`]
10025 // carries so no arm's projection is covered only by the sibling
10026 // method-named `as_str` / [`std::fmt::Display`] / [`AsRef<str>`]
10027 // paths. Materializes the `<&'static str as
10028 // From<RestartPolicy>>::from` output in a `const`-shape binding
10029 // to make the `'static` lifetime promise a build-time invariant
10030 // — a future accidental downgrade of any of the three arms'
10031 // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] constants to a
10032 // non-`&'static str` (a `String::leak()`-produced return, a
10033 // `Box::leak`-cast) trips at caixa-core build time rather than
10034 // at a downstream `'static`-bound consumer. Peer of the sibling
10035 // [`restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
10036 // (523157d) — extends the trait-idiomatic forward-projection
10037 // axis onto the second (and second-of-two-in-M2) closed-set
10038 // typed enum on the caixa surface (the paired per-child
10039 // restart-decision-policy sibling on the same M2 `:supervisor`
10040 // slot).
10041 const PERMANENT: &str = RestartPolicy::Permanent.as_str();
10042 const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
10043 const TRANSIENT: &str = RestartPolicy::Transient.as_str();
10044 for &variant in RestartPolicy::ALL {
10045 let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
10046 let via_method: &'static str = variant.as_str();
10047 assert_eq!(
10048 via_trait, via_method,
10049 "From<RestartPolicy> for &'static str impl must round-trip \
10050 RestartPolicy::{variant:?} to the same lifted \
10051 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str returns — \
10052 divergence signals a silent detour off the substrate-primitive \
10053 accessor"
10054 );
10055 let via_into: &'static str = variant.into();
10056 assert_eq!(
10057 via_into, via_method,
10058 "Into<&'static str>::into on RestartPolicy::{variant:?} must \
10059 byte-equal RestartPolicy::as_str on the same input — the \
10060 blanket-derived Into shape must resolve to the same as_str \
10061 dispatch as the explicit From impl"
10062 );
10063 }
10064 assert_eq!(
10065 [PERMANENT, TEMPORARY, TRANSIENT],
10066 [
10067 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
10068 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
10069 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
10070 ],
10071 "const-context RestartPolicy::as_str must resolve to the three \
10072 lifted SUPERVISOR_CHILD_RESTART_* consts — a future accidental \
10073 downgrade of any arm to a non-const or non-static byte-string \
10074 breaks the `&'static str`-lifetime promise the paired \
10075 From<RestartPolicy> for &'static str impl carries by \
10076 construction"
10077 );
10078 }
10079
10080 #[test]
10081 fn restart_policy_from_into_static_str_and_as_str_partition_the_emit_set() {
10082 // Cross-axis partition pin: the paired trait-idiomatic
10083 // `From<RestartPolicy> for &'static str` forward projection and
10084 // the method-named [`RestartPolicy::as_str`] forward projection
10085 // must resolve identically on *every* arm, not just the ones
10086 // named in the primary byte-parity pin above. Sweeps every
10087 // [`RestartPolicy::ALL`] arm and asserts the trait's `From::from`
10088 // output byte-equals the method-named accessor's return-value on
10089 // each, locking the two forward-projection paths together by
10090 // construction so any future detour (a stray `From` special-case
10091 // that lands on a divergent per-arm literal outside the paired
10092 // `as_str` dispatch, a hypothetical rebrand touching one axis
10093 // without the other) trips at caixa-core test time. Peer of the
10094 // sibling forward-projection partition pin
10095 // [`restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
10096 // (523157d) — extends the round-trip discipline onto the
10097 // second-of-two M2-OTP-shape closed-set typed enum on the caixa
10098 // surface, closing the two-way `Self ↔ &'static str` round-trip
10099 // on the trait-idiomatic pair (`From<Self> for &'static str` +
10100 // `TryFrom<&str> for Self`) as well as the pre-existing method-
10101 // named pair (`as_str` + `from_wire`).
10102 for &variant in RestartPolicy::ALL {
10103 let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
10104 let via_method: &'static str = variant.as_str();
10105 assert_eq!(
10106 via_trait, via_method,
10107 "From<RestartPolicy> for &'static str and \
10108 RestartPolicy::as_str must resolve identically on \
10109 RestartPolicy::{variant:?} — divergence signals the \
10110 two forward-projection paths have drifted onto different \
10111 emit-sets"
10112 );
10113 }
10114 // Round-trip witness: every arm's forward `From` output re-parses
10115 // through the paired trait-idiomatic reverse `TryFrom<&str>` back
10116 // to the original variant. Closes the two-way `RestartPolicy ↔
10117 // &'static str` round-trip on the trait-idiomatic axis pair,
10118 // mirroring the pre-existing method-named `as_str` + `from_wire`
10119 // round-trip on the substrate-primitive axis pair.
10120 for &variant in RestartPolicy::ALL {
10121 let emitted: &'static str = variant.into();
10122 let re_parsed: Result<RestartPolicy, ()> =
10123 <RestartPolicy as TryFrom<&str>>::try_from(emitted);
10124 assert_eq!(
10125 re_parsed,
10126 Ok(variant),
10127 "trait-idiomatic axis pair must round-trip \
10128 RestartPolicy::{variant:?} through `.into::<&'static \
10129 str>()` and back through `TryFrom<&str>` — a break signals \
10130 the forward-emit and reverse-parse axes have drifted onto \
10131 different vocabularies"
10132 );
10133 }
10134 }
10135
10136 #[test]
10137 fn restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
10138 // Fail-before-pass-after byte-parity pin on the newly lifted
10139 // `impl From<&RestartPolicy> for &'static str` — asserts the
10140 // borrowed-input standard-library trait impl and the substrate-
10141 // primitive [`RestartPolicy::as_str`] `pub const fn` accessor
10142 // resolve to the same three-arm emit-set across every arm the
10143 // exhaustive [`RestartPolicy::ALL`] slice enumerates. Rust's
10144 // `From` trait does not auto-derive the borrowed-input sibling
10145 // from a paired owned-input impl (no `impl<T, U> From<&T> for U
10146 // where T: Copy, U: From<T>` blanket in `core`), so the
10147 // borrowed-input axis is a distinct trait-idiomatic surface
10148 // that a `.iter().map(Into::into)` shape over
10149 // [`RestartPolicy::ALL`] (whose iterator yields
10150 // `&RestartPolicy`, not `RestartPolicy`) reaches through this
10151 // impl and no other — the paired owned-input
10152 // [`From<RestartPolicy>`] impl requires an explicit `.copied()`
10153 // / dereference before the trait fires. Materializes the
10154 // `<&'static str as From<&RestartPolicy>>::from` output in a
10155 // `const`-shape binding to make the `'static` lifetime promise
10156 // a build-time invariant.
10157 const PERMANENT: &str = RestartPolicy::Permanent.as_str();
10158 const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
10159 const TRANSIENT: &str = RestartPolicy::Transient.as_str();
10160 for variant in RestartPolicy::ALL {
10161 let via_trait: &'static str = <&'static str as From<&RestartPolicy>>::from(variant);
10162 let via_method: &'static str = variant.as_str();
10163 assert_eq!(
10164 via_trait, via_method,
10165 "From<&RestartPolicy> for &'static str impl must round-trip \
10166 &RestartPolicy::{variant:?} to the same lifted \
10167 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
10168 returns — divergence signals a silent detour off the \
10169 substrate-primitive accessor"
10170 );
10171 let via_into: &'static str = variant.into();
10172 assert_eq!(
10173 via_into, via_method,
10174 "Into<&'static str>::into on &RestartPolicy::{variant:?} \
10175 must byte-equal RestartPolicy::as_str on the same input — \
10176 the blanket-derived Into shape must resolve to the same \
10177 as_str dispatch as the explicit From impl"
10178 );
10179 }
10180 assert_eq!(
10181 [PERMANENT, TEMPORARY, TRANSIENT],
10182 [
10183 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
10184 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
10185 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
10186 ],
10187 "const-context RestartPolicy::as_str must resolve to the three \
10188 lifted SUPERVISOR_CHILD_RESTART_* consts — the borrowed-input \
10189 From<&RestartPolicy> for &'static str impl inherits its \
10190 `'static` lifetime promise from the same accessor the \
10191 owned-input sibling routes through"
10192 );
10193 }
10194
10195 #[test]
10196 fn restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
10197 // Cross-axis partition pin: the paired trait-idiomatic
10198 // owned-input `From<RestartPolicy> for &'static str` (9fb37d0
10199 // campaign-shape) and borrowed-input `From<&RestartPolicy> for
10200 // &'static str` (this lift) forward projections must resolve
10201 // identically on every arm, locking the two input-shape paths
10202 // together so any future detour trips at caixa-core test time.
10203 // Then a witness that a `.iter().map(Into::into)` pipe over
10204 // [`RestartPolicy::ALL`] (whose iterator yields
10205 // `&RestartPolicy`) materializes the three-arm accept-set
10206 // through the borrowed-input axis alone — the exact shape a
10207 // future wasm-operator per-child post-exit restart-decision
10208 // diagnostic line, a future substrate-wide per-arm diagnostic
10209 // column, or a
10210 // `HashMap::<&'static str, RestartPolicy>::from_iter(
10211 // RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
10212 // per-policy lookup reaches through — closing the two-way
10213 // owned/borrowed input-shape symmetry on the forward-projection
10214 // trait-idiomatic axis. Peer of the sibling
10215 // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
10216 // (64aa742) /
10217 // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
10218 // (5ab993a) /
10219 // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
10220 // (807b0b5) /
10221 // [`restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
10222 // (e941836) partition pins on the sibling closed-set typed-enum
10223 // discriminator axes — extends the borrowed-input axis
10224 // discipline onto the second-of-two M2 OTP-shape closed-set
10225 // typed enum on the caixa surface (per-child restart-decision
10226 // policy). Also closes the direct two-way `&Self → &'static
10227 // str → Self` round-trip via the paired [`TryFrom<&str>`] axis
10228 // — unlike the peer [`crate::CaixaKind`] axis pair (whose
10229 // forward `From` emits lowercase Portuguese diagnostic bytes
10230 // while the reverse `TryFrom` parses `PascalCase` wire bytes,
10231 // forcing the round-trip through an intermediate wire-vocab
10232 // hop), the [`RestartPolicy::as_str`] emit and
10233 // [`RestartPolicy::from_wire`] parse share the same
10234 // `PascalCase` vocabulary by construction, so the borrowed-
10235 // input forward axis and the reverse axis compose directly.
10236 for &variant in RestartPolicy::ALL {
10237 let owned: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
10238 let borrowed: &'static str = <&'static str as From<&RestartPolicy>>::from(&variant);
10239 assert_eq!(
10240 owned, borrowed,
10241 "From<RestartPolicy> and From<&RestartPolicy> for \
10242 &'static str must resolve identically on \
10243 RestartPolicy::{variant:?} — divergence signals the \
10244 owned-input and borrowed-input forward-projection paths \
10245 have drifted onto different emit-sets"
10246 );
10247 }
10248 let via_iter: Vec<&'static str> = RestartPolicy::ALL.iter().map(Into::into).collect();
10249 let via_method: Vec<&'static str> = RestartPolicy::ALL.iter().map(|p| p.as_str()).collect();
10250 assert_eq!(
10251 via_iter, via_method,
10252 "`.iter().map(Into::into)` over RestartPolicy::ALL must \
10253 byte-equal `.iter().map(|p| p.as_str())` on every arm — the \
10254 borrowed-input `From<&RestartPolicy> for &'static str` axis \
10255 is what makes the `.iter().map(Into::into)` shape route \
10256 through the substrate-primitive `RestartPolicy::as_str` \
10257 accessor rather than through a per-call-site `.copied()` / \
10258 dereference detour"
10259 );
10260 for variant in RestartPolicy::ALL {
10261 let emitted: &'static str = variant.into();
10262 let re_parsed: Result<RestartPolicy, ()> =
10263 <RestartPolicy as TryFrom<&str>>::try_from(emitted);
10264 assert_eq!(
10265 re_parsed,
10266 Ok(*variant),
10267 "trait-idiomatic borrowed-input forward-projection + \
10268 reverse-projection axis pair must round-trip \
10269 &RestartPolicy::{variant:?} through `.into::<&'static \
10270 str>()` (via the borrowed-input axis) and back through \
10271 `TryFrom<&str>` — a break signals the borrowed-input \
10272 forward-emit and reverse-parse axes have drifted onto \
10273 different vocabularies"
10274 );
10275 }
10276 }
10277
10278 #[test]
10279 fn restart_policy_from_into_owned_string_routes_through_as_str_accessor() {
10280 // Fail-before-pass-after byte-parity pin on the newly lifted
10281 // `impl From<RestartPolicy> for String` — asserts the
10282 // owned-`String`-returning standard-library trait impl and the
10283 // substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
10284 // accessor resolve to the same three-arm emit-set across every
10285 // arm the exhaustive [`RestartPolicy::ALL`] slice enumerates.
10286 // Rust's standard library does not carry a blanket
10287 // `impl<T: AsRef<str>> From<T> for String` (nor an
10288 // `impl<T: fmt::Display> From<T> for String`), so the
10289 // owned-`String` forward-projection axis is a distinct
10290 // trait-idiomatic surface that a `let key: String =
10291 // policy.into();`-shaped call site reaches through this impl
10292 // and no other — the paired sibling `From<RestartPolicy> for
10293 // &'static str` impl forces every owned-`String` call site
10294 // through an explicit `.to_owned()` / `String::from`
10295 // restatement. Peer of the first-mover
10296 // [`restart_strategy_from_into_owned_string_routes_through_as_str_accessor`]
10297 // (7baa18a) — extends the trait-idiomatic owned-`String`
10298 // forward-projection axis onto the second-of-two M2 OTP-shape
10299 // closed-set typed enums on the caixa surface (per-child
10300 // restart-decision-policy sibling on the same M2 `:supervisor`
10301 // slot).
10302 for &variant in RestartPolicy::ALL {
10303 let via_trait: String = <String as From<RestartPolicy>>::from(variant);
10304 let via_method: &'static str = variant.as_str();
10305 assert_eq!(
10306 via_trait.as_str(),
10307 via_method,
10308 "From<RestartPolicy> for String impl must round-trip \
10309 RestartPolicy::{variant:?} to the same lifted \
10310 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
10311 returns — divergence signals a silent detour off the \
10312 substrate-primitive accessor"
10313 );
10314 let via_into: String = variant.into();
10315 assert_eq!(
10316 via_into.as_str(),
10317 via_method,
10318 "Into<String>::into on RestartPolicy::{variant:?} must \
10319 byte-equal RestartPolicy::as_str on the same input — the \
10320 blanket-derived Into shape must resolve to the same as_str \
10321 dispatch as the explicit From impl"
10322 );
10323 }
10324 }
10325
10326 #[test]
10327 fn restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm() {
10328 // Cross-axis partition pin: the paired trait-idiomatic
10329 // owned-`String` `From<RestartPolicy> for String` (this lift)
10330 // and owned-`&'static str` `From<RestartPolicy> for &'static
10331 // str` (9fb37d0) forward projections must resolve identically
10332 // on every arm, locking the two return-type-shape paths
10333 // together so any future detour trips at caixa-core test time.
10334 // Also byte-parity witness against the sibling
10335 // [`ToString::to_string`] surface routed through
10336 // [`std::fmt::Display`] — the three owned-heap-string paths
10337 // (`.into::<String>()`, `String::from`, `.to_string()`) must
10338 // resolve identically on every arm so a future consumer that
10339 // picks any of the three lands on the same lifted
10340 // SUPERVISOR_CHILD_RESTART_* const. Then a `.iter().copied()
10341 // .map(String::from)` pipe witness over [`RestartPolicy::ALL`]
10342 // that materializes the three-arm accept-set through the
10343 // owned-`String` axis alone — the exact shape a future
10344 // wasm-operator per-child post-exit restart-decision
10345 // diagnostic line composer or a
10346 // `HashMap::<String, RestartPolicy>::from_iter(
10347 // RestartPolicy::ALL.iter().copied().map(|p| (p.into(), p)))`-style
10348 // owned-key per-policy lookup reaches through — closing the
10349 // owned-`String` forward-projection axis's iterator-pipe
10350 // shape. Then a direct round-trip witness through the paired
10351 // trait-idiomatic reverse [`TryFrom<&str>`] axis on the
10352 // owned-`String`'s [`String::as_str`] borrow that closes the
10353 // two-way `Self → String → Self` round-trip on the trait-
10354 // idiomatic owned-`String` forward + reverse axis pair —
10355 // unlike the peer [`crate::CaixaKind`] axis pair (whose
10356 // forward `From` emits lowercase Portuguese diagnostic bytes
10357 // while the reverse `TryFrom` parses `PascalCase` wire bytes,
10358 // forcing the round-trip through an intermediate wire-vocab
10359 // hop), the [`RestartPolicy::as_str`] emit and
10360 // [`RestartPolicy::from_wire`] parse share the same
10361 // `PascalCase` vocabulary by construction, so the owned-
10362 // `String` forward axis and the reverse axis compose directly.
10363 for &variant in RestartPolicy::ALL {
10364 let owned_string: String = <String as From<RestartPolicy>>::from(variant);
10365 let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
10366 assert_eq!(
10367 owned_string.as_str(),
10368 owned_static,
10369 "From<RestartPolicy> for String and From<RestartPolicy> \
10370 for &'static str must resolve identically on \
10371 RestartPolicy::{variant:?} — divergence signals the \
10372 owned-`String` and owned-`&'static str` forward-projection \
10373 return-type-shape paths have drifted onto different \
10374 emit-sets"
10375 );
10376 let via_to_string: String = variant.to_string();
10377 assert_eq!(
10378 owned_string, via_to_string,
10379 "From<RestartPolicy> for String must byte-equal \
10380 RestartPolicy::to_string on RestartPolicy::{variant:?} — \
10381 divergence signals the trait-idiomatic owned-`String` \
10382 forward-projection axis and the ToString-through-Display \
10383 axis have drifted onto different emit-sets"
10384 );
10385 }
10386 let via_iter: Vec<String> = RestartPolicy::ALL
10387 .iter()
10388 .copied()
10389 .map(String::from)
10390 .collect();
10391 let via_method: Vec<String> = RestartPolicy::ALL
10392 .iter()
10393 .map(|p| p.as_str().to_owned())
10394 .collect();
10395 assert_eq!(
10396 via_iter, via_method,
10397 "`.iter().copied().map(String::from)` over RestartPolicy::ALL \
10398 must byte-equal `.iter().map(|p| p.as_str().to_owned())` on \
10399 every arm — the owned-`String` `From<RestartPolicy> for \
10400 String` axis is what makes the `String::from` composition \
10401 route through the substrate-primitive `RestartPolicy::as_str` \
10402 accessor rather than through a per-call-site `.to_owned()` / \
10403 `String::from(policy.as_str())` detour"
10404 );
10405 for &variant in RestartPolicy::ALL {
10406 let emitted: String = variant.into();
10407 let re_parsed: Result<RestartPolicy, ()> =
10408 <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
10409 assert_eq!(
10410 re_parsed,
10411 Ok(variant),
10412 "trait-idiomatic owned-`String` forward-projection + \
10413 reverse-projection axis pair must round-trip \
10414 RestartPolicy::{variant:?} through `.into::<String>()` \
10415 and back through `TryFrom<&str>` on the owned-`String`'s \
10416 String::as_str borrow — a break signals the owned-`String` \
10417 forward-emit and reverse-parse axes have drifted onto \
10418 different vocabularies"
10419 );
10420 }
10421 }
10422
10423 #[test]
10424 fn restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
10425 // Fail-before-pass-after byte-parity pin on the newly lifted
10426 // `impl From<&RestartPolicy> for String` — asserts the
10427 // borrowed-input owned-`String`-returning standard-library
10428 // trait impl and the substrate-primitive
10429 // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
10430 // the same three-arm emit-set across every arm the exhaustive
10431 // [`RestartPolicy::ALL`] slice enumerates. Rust's standard
10432 // library does not carry a blanket `impl<T: AsRef<str>>
10433 // From<&T> for String` (nor an `impl<T: fmt::Display> From<&T>
10434 // for String`), so the borrowed-input owned-`String` forward-
10435 // projection axis is a distinct trait-idiomatic surface that a
10436 // `let key: String = (&policy).into();`-shaped call site
10437 // reaches through this impl and no other — the paired sibling
10438 // `From<RestartPolicy> for String` impl forces every borrowed-
10439 // input call site through an explicit `Copy` deref
10440 // (`String::from(*policy)`) or an `.as_str().to_owned()` /
10441 // `.to_string()` detour. Peer of the first-mover
10442 // [`restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
10443 // (579385f) — extends the trait-idiomatic borrowed-input
10444 // owned-`String` forward-projection axis onto the second-of-
10445 // two M2 OTP-shape closed-set typed enums on the caixa surface
10446 // (per-child restart-decision-policy sibling on the same M2
10447 // `:supervisor` slot).
10448 for &variant in RestartPolicy::ALL {
10449 let via_trait: String = <String as From<&RestartPolicy>>::from(&variant);
10450 let via_method: &'static str = variant.as_str();
10451 assert_eq!(
10452 via_trait.as_str(),
10453 via_method,
10454 "From<&RestartPolicy> for String impl must round-trip \
10455 &RestartPolicy::{variant:?} to the same lifted \
10456 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
10457 returns — divergence signals a silent detour off the \
10458 substrate-primitive accessor"
10459 );
10460 let via_into: String = (&variant).into();
10461 assert_eq!(
10462 via_into.as_str(),
10463 via_method,
10464 "Into<String>::into on &RestartPolicy::{variant:?} must \
10465 byte-equal RestartPolicy::as_str on the same input — \
10466 the blanket-derived Into shape must resolve to the \
10467 same as_str dispatch as the explicit From impl"
10468 );
10469 }
10470 }
10471
10472 #[test]
10473 fn restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
10474 // Cross-axis partition pin: the newly lifted trait-idiomatic
10475 // borrowed-input owned-`String` `From<&RestartPolicy> for
10476 // String` (this lift), the paired owned-input owned-`String`
10477 // `From<RestartPolicy> for String` (7851725), the paired
10478 // borrowed-input owned-`&'static str` `From<&RestartPolicy>
10479 // for &'static str` (842c7f3), and the paired owned-input
10480 // owned-`&'static str` `From<RestartPolicy> for &'static str`
10481 // (9fb37d0) — every corner of the `{Self, &Self} × {&'static
10482 // str, String}` 2×2 trait-idiomatic projection family — must
10483 // resolve identically on every arm, locking the four
10484 // return-shape × input-shape paths together so any future
10485 // detour trips at caixa-core test time. Also byte-parity
10486 // witness against the sibling [`ToString::to_string`] surface
10487 // routed through [`std::fmt::Display`] and a direct round-trip
10488 // witness through the paired trait-idiomatic reverse
10489 // [`TryFrom<&str>`] axis on the owned-`String`'s
10490 // [`String::as_str`] borrow that closes the two-way
10491 // `&Self → String → Self` round-trip on the trait-idiomatic
10492 // borrowed-input owned-`String` forward + reverse axis pair.
10493 // Peer of the first-mover
10494 // [`restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
10495 // (579385f) — closes the whole `{Self, &Self} × {&'static str,
10496 // String}` 2×2 projection corner on both M2 OTP-shape sibling
10497 // peers.
10498 for &variant in RestartPolicy::ALL {
10499 let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
10500 let owned_string: String = <String as From<RestartPolicy>>::from(variant);
10501 let borrowed_static: &'static str =
10502 <&'static str as From<&RestartPolicy>>::from(&variant);
10503 let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
10504 assert_eq!(
10505 borrowed_string, owned_string,
10506 "From<&RestartPolicy> for String and From<RestartPolicy> \
10507 for String must resolve identically on \
10508 RestartPolicy::{variant:?} — divergence signals the \
10509 borrowed-input and owned-input owned-`String` \
10510 forward-projection input-shape paths have drifted onto \
10511 different emit-sets"
10512 );
10513 assert_eq!(
10514 borrowed_string.as_str(),
10515 borrowed_static,
10516 "From<&RestartPolicy> for String and From<&RestartPolicy> \
10517 for &'static str must resolve identically on \
10518 RestartPolicy::{variant:?} — divergence signals the \
10519 borrowed-input `&'static str` and owned-`String` \
10520 return-shape paths have drifted onto different \
10521 emit-sets"
10522 );
10523 assert_eq!(
10524 borrowed_string.as_str(),
10525 owned_static,
10526 "From<&RestartPolicy> for String and From<RestartPolicy> \
10527 for &'static str must resolve identically on \
10528 RestartPolicy::{variant:?} — divergence signals a \
10529 break in the diagonal corner of the {{Self, &Self}} × \
10530 {{&'static str, String}} 2×2 trait-idiomatic \
10531 projection family"
10532 );
10533 let via_to_string: String = variant.to_string();
10534 assert_eq!(
10535 borrowed_string, via_to_string,
10536 "From<&RestartPolicy> for String must byte-equal \
10537 RestartPolicy::to_string on RestartPolicy::{variant:?} \
10538 — divergence signals the trait-idiomatic borrowed-input \
10539 owned-`String` forward-projection axis and the \
10540 ToString-through-Display axis have drifted onto \
10541 different emit-sets"
10542 );
10543 }
10544 let via_iter: Vec<String> = RestartPolicy::ALL.iter().map(String::from).collect();
10545 let via_method: Vec<String> = RestartPolicy::ALL
10546 .iter()
10547 .map(|p| p.as_str().to_owned())
10548 .collect();
10549 assert_eq!(
10550 via_iter, via_method,
10551 "`.iter().map(String::from)` over RestartPolicy::ALL — a \
10552 call site whose iteration axis holds `&RestartPolicy` by \
10553 construction — must byte-equal `.iter().map(|p| \
10554 p.as_str().to_owned())` on every arm — the borrowed-input \
10555 owned-`String` `From<&RestartPolicy> for String` axis is \
10556 what makes the `String::from` composition route through \
10557 the substrate-primitive `RestartPolicy::as_str` accessor \
10558 without a spurious `Copy` deref (which would only be \
10559 reachable through the owned-input `From<RestartPolicy> \
10560 for String` axis by first calling `.copied()` on the \
10561 iterator)"
10562 );
10563 for &variant in RestartPolicy::ALL {
10564 let emitted: String = (&variant).into();
10565 let re_parsed: Result<RestartPolicy, ()> =
10566 <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
10567 assert_eq!(
10568 re_parsed,
10569 Ok(variant),
10570 "trait-idiomatic borrowed-input owned-`String` \
10571 forward-projection + reverse-projection axis pair must \
10572 round-trip &RestartPolicy::{variant:?} through \
10573 `.into::<String>()` on the borrowed-input surface and \
10574 back through `TryFrom<&str>` on the owned-`String`'s \
10575 String::as_str borrow — a break signals the \
10576 borrowed-input owned-`String` forward-emit and \
10577 reverse-parse axes have drifted onto different \
10578 vocabularies"
10579 );
10580 }
10581 }
10582
10583 #[test]
10584 fn restart_policy_from_into_static_cow_str_routes_through_as_str_accessor() {
10585 // Fail-before-pass-after byte-parity pin on the newly lifted
10586 // `impl From<RestartPolicy> for std::borrow::Cow<'static, str>` —
10587 // asserts the standard-library trait impl and the substrate-
10588 // primitive [`super::RestartPolicy::as_str`] `pub const fn`
10589 // accessor resolve to the same three-arm emit-set across every
10590 // arm the exhaustive [`super::RestartPolicy::ALL`] slice
10591 // enumerates. Rust's standard library does not carry a blanket
10592 // `impl<T: AsRef<str>> From<T> for Cow<'static, str>` (nor an
10593 // `impl<T: fmt::Display> From<T> for Cow<'static, str>`), so
10594 // the `Cow<'static, str>` forward-projection axis is a
10595 // distinct trait-idiomatic surface that a
10596 // `let key: Cow<'static, str> = policy.into();`-shaped call
10597 // site reaches through this impl and no other — the paired
10598 // sibling `From<RestartPolicy> for &'static str` and
10599 // `From<RestartPolicy> for String` impls force every
10600 // `Cow<'static, str>`-parameterized call site through a
10601 // `Cow::Borrowed(policy.as_str())` /
10602 // `Cow::Owned(policy.to_string())` composition whose type
10603 // bounds have no compile-time link back to the substrate
10604 // primitive.
10605 //
10606 // Also asserts the projection lands on the zero-alloc
10607 // [`std::borrow::Cow::Borrowed`] arm (not the
10608 // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
10609 // [`super::RestartPolicy::as_str`] accessor's `&'static str`
10610 // return lifetime by construction makes the borrowed arm the
10611 // type-correct projection with no runtime allocation. Any
10612 // future silent detour that routes the impl through the owned
10613 // arm (an accidental `Cow::Owned(policy.to_string())` rewrite
10614 // that would allocate on every call site where the
10615 // `&'static str` return of [`super::RestartPolicy::as_str`]
10616 // makes the zero-alloc borrowed projection type-correct) trips
10617 // at caixa-core test time under the
10618 // [`std::borrow::Cow::Borrowed`] discriminator witness rather
10619 // than at a downstream `Cow<'static, str>`-bound consumer's
10620 // silent allocation.
10621 //
10622 // Second peer on the substrate-wide trait-idiomatic
10623 // [`std::borrow::Cow<'static, str>`] forward-projection family
10624 // to extend the axis off the top-level [`super::CaixaKind`]
10625 // enum (99c1735 owned-input, d45c409 borrowed-input) onto the
10626 // second (and second-of-two-in-M2) M2 OTP-shape closed-set
10627 // fieldless typed enum peer on the caixa surface — closes the
10628 // M2 OTP-shape tier of the campaign on the owned-input axis
10629 // (both sibling peers, `RestartStrategy` and `RestartPolicy`,
10630 // now carry the owned-input Cow<'static, str> forward
10631 // projection).
10632 for &variant in RestartPolicy::ALL {
10633 let via_trait: std::borrow::Cow<'static, str> =
10634 <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
10635 let via_method: &'static str = variant.as_str();
10636 assert_eq!(
10637 via_trait.as_ref(),
10638 via_method,
10639 "From<RestartPolicy> for Cow<'static, str> impl must \
10640 round-trip RestartPolicy::{variant:?} to the same \
10641 lifted SUPERVISOR_CHILD_RESTART_* const \
10642 RestartPolicy::as_str returns — divergence signals a \
10643 silent detour off the substrate-primitive accessor"
10644 );
10645 assert!(
10646 matches!(via_trait, std::borrow::Cow::Borrowed(_)),
10647 "From<RestartPolicy> for Cow<'static, str> impl must \
10648 land on the zero-alloc Cow::Borrowed arm on \
10649 RestartPolicy::{variant:?} — a Cow::Owned outcome \
10650 signals the projection has silently allocated where \
10651 the substrate-primitive RestartPolicy::as_str \
10652 `&'static str` return makes the borrowed arm the \
10653 type-correct projection"
10654 );
10655 let via_into: std::borrow::Cow<'static, str> = variant.into();
10656 assert_eq!(
10657 via_into.as_ref(),
10658 via_method,
10659 "Into<Cow<'static, str>>::into on \
10660 RestartPolicy::{variant:?} must byte-equal \
10661 RestartPolicy::as_str on the same input — the \
10662 blanket-derived Into shape must resolve to the same \
10663 as_str dispatch as the explicit From impl"
10664 );
10665 assert!(
10666 matches!(via_into, std::borrow::Cow::Borrowed(_)),
10667 "Into<Cow<'static, str>>::into on \
10668 RestartPolicy::{variant:?} must land on the \
10669 zero-alloc Cow::Borrowed arm — the blanket-derived \
10670 Into shape must resolve to the same Cow::Borrowed \
10671 dispatch as the explicit From impl"
10672 );
10673 }
10674 }
10675
10676 #[test]
10677 fn restart_policy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
10678 // Cross-axis partition pin: the newly lifted trait-idiomatic
10679 // `From<RestartPolicy> for std::borrow::Cow<'static, str>`
10680 // (this lift), the paired owned-input `From<RestartPolicy>
10681 // for &'static str` (9fb37d0), and the paired owned-input
10682 // `From<RestartPolicy> for String` (7851725) forward
10683 // projections must resolve identically on every arm, locking
10684 // the three return-shape paths together by construction so any
10685 // future detour trips at caixa-core test time. Also byte-parity
10686 // witness against the sibling [`ToString::to_string`] surface
10687 // routed through [`std::fmt::Display`] — every owned-heap-
10688 // string path (the `Cow::Owned` promotion of this axis's
10689 // `.into_owned()`, `From<RestartPolicy> for String`, and
10690 // `.to_string()`) resolves to the same lifted
10691 // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const per arm.
10692 //
10693 // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
10694 // witness over [`super::RestartPolicy::ALL`] that
10695 // materializes the three-arm accept-set through the
10696 // [`std::borrow::Cow<'static, str>`] axis alone — the exact
10697 // shape a future `axum::response::IntoResponse` per-policy
10698 // rejection-body composer, a future M4 admission-webhook
10699 // per-policy rejection-reason emitter whose typing rules out
10700 // the sibling [`AsRef<str>`] borrowed return, or a future
10701 // substrate-wide per-policy diagnostic surface that binds
10702 // through a [`Cow<'static, str>`] boundary reaches through.
10703 // The pipe witness also pins the zero-alloc discipline: every
10704 // element in the collected vector satisfies the
10705 // [`std::borrow::Cow::Borrowed`] arm predicate, so a future
10706 // accidental silent-allocation regression on the pipe's
10707 // iteration axis is a caixa-core-test-time failure. Peer of
10708 // the first-mover
10709 // [`restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
10710 // (7dd28b3) on the sibling M2 OTP-shape sibling-restart axis
10711 // — closes the whole owned-input `Cow<'static, str>` +
10712 // paired `{&'static str, String}` cross-axis-parity corner on
10713 // both M2 OTP-shape sibling peers.
10714 for &variant in RestartPolicy::ALL {
10715 let via_cow: std::borrow::Cow<'static, str> =
10716 <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
10717 let via_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
10718 let via_string: String = <String as From<RestartPolicy>>::from(variant);
10719 assert_eq!(
10720 via_cow.as_ref(),
10721 via_static,
10722 "From<RestartPolicy> for Cow<'static, str> and \
10723 From<RestartPolicy> for &'static str must resolve \
10724 identically on RestartPolicy::{variant:?} — \
10725 divergence signals the Cow<'static, str> and \
10726 &'static str return-shape paths have drifted onto \
10727 different emit-sets"
10728 );
10729 assert_eq!(
10730 via_cow.as_ref(),
10731 via_string.as_str(),
10732 "From<RestartPolicy> for Cow<'static, str> and \
10733 From<RestartPolicy> for String must resolve \
10734 identically on RestartPolicy::{variant:?} — \
10735 divergence signals the Cow<'static, str> and String \
10736 return-shape paths have drifted onto different \
10737 emit-sets"
10738 );
10739 let via_to_string: String = variant.to_string();
10740 assert_eq!(
10741 via_cow.as_ref(),
10742 via_to_string.as_str(),
10743 "From<RestartPolicy> for Cow<'static, str> must \
10744 byte-equal RestartPolicy::to_string on \
10745 RestartPolicy::{variant:?} — divergence signals the \
10746 trait-idiomatic Cow<'static, str> forward-projection \
10747 axis and the ToString-through-Display axis have \
10748 drifted onto different emit-sets"
10749 );
10750 }
10751 let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
10752 .iter()
10753 .copied()
10754 .map(std::borrow::Cow::from)
10755 .collect();
10756 let via_method: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
10757 .iter()
10758 .map(|p| std::borrow::Cow::Borrowed(p.as_str()))
10759 .collect();
10760 assert_eq!(
10761 via_iter, via_method,
10762 "`.iter().copied().map(Cow::from)` over \
10763 RestartPolicy::ALL must byte-equal `.iter().map(|p| \
10764 Cow::Borrowed(p.as_str()))` on every arm — the \
10765 trait-idiomatic `From<RestartPolicy> for Cow<'static, \
10766 str>` axis is what makes the `Cow::from` composition \
10767 route through the substrate-primitive \
10768 `RestartPolicy::as_str` accessor with the zero-alloc \
10769 Cow::Borrowed arm by construction, rather than a \
10770 per-call-site `Cow::Owned(policy.to_string())` \
10771 allocation"
10772 );
10773 for cow in &via_iter {
10774 assert!(
10775 matches!(cow, std::borrow::Cow::Borrowed(_)),
10776 "every element of the \
10777 .iter().copied().map(Cow::from) pipe over \
10778 RestartPolicy::ALL must land on the zero-alloc \
10779 Cow::Borrowed arm — a Cow::Owned outcome on any arm \
10780 signals the pipe's iteration axis has silently \
10781 allocated where the substrate-primitive \
10782 RestartPolicy::as_str `&'static str` return makes \
10783 the borrowed arm the type-correct projection"
10784 );
10785 }
10786 }
10787
10788 #[test]
10789 fn restart_policy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
10790 // Fail-before-pass-after byte-parity pin on the newly lifted
10791 // `impl From<&RestartPolicy> for std::borrow::Cow<'static, str>` —
10792 // asserts the borrowed-input standard-library trait impl and
10793 // the substrate-primitive [`super::RestartPolicy::as_str`]
10794 // `pub const fn` accessor resolve to the same three-arm emit-
10795 // set across every arm the exhaustive
10796 // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
10797 // standard library does not carry a blanket
10798 // `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor a
10799 // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
10800 // the borrowed-input `Cow<'static, str>` forward-projection
10801 // axis is a distinct trait-idiomatic surface that a
10802 // `let key: Cow<'static, str> = (&policy).into();`-shaped
10803 // call site or a
10804 // `RestartPolicy::ALL.iter().map(Cow::from)`-shaped pipe
10805 // reaches through this impl and no other — the paired owned-
10806 // input `From<RestartPolicy> for Cow<'static, str>` impl
10807 // (0612398) forces every borrowed-input call site through an
10808 // explicit `Copy` deref (`Cow::from(*policy)`) or a
10809 // `Cow::Borrowed(policy.as_str())` open-code whose type
10810 // bounds have no compile-time link back to the substrate
10811 // primitive.
10812 //
10813 // Also asserts the projection lands on the zero-alloc
10814 // [`std::borrow::Cow::Borrowed`] arm (not the
10815 // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
10816 // [`super::RestartPolicy::as_str`] accessor's `&'static str`
10817 // return lifetime by construction makes the borrowed arm the
10818 // type-correct projection with no runtime allocation on the
10819 // borrowed-input surface just as on the paired owned-input
10820 // surface.
10821 //
10822 // Closes the `{Self, &Self}` input-shape corner on the M2
10823 // OTP-shape per-child-restart [`Cow<'static, str>`] axis on
10824 // the second-of-two-in-M2 closed-set fieldless typed enum peer
10825 // on the caixa surface (`:supervisor :children :restart`),
10826 // exactly as d45c409 closed it on the top-level
10827 // [`super::CaixaKind`] one commit after the owning half
10828 // (99c1735) landed and as 9b3e4b3 closed it on the sibling
10829 // M2 OTP-shape [`super::RestartStrategy`] one commit after
10830 // (7dd28b3) landed. This lift closes the whole M2 OTP-shape
10831 // tier of the substrate-wide Cow<'static, str> forward-
10832 // projection campaign on both input-shape corners
10833 // ({Self, &Self}) of both M2 OTP-shape sibling peers.
10834 for &variant in RestartPolicy::ALL {
10835 let via_trait: std::borrow::Cow<'static, str> =
10836 <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
10837 let via_method: &'static str = variant.as_str();
10838 assert_eq!(
10839 via_trait.as_ref(),
10840 via_method,
10841 "From<&RestartPolicy> for Cow<'static, str> impl must \
10842 round-trip &RestartPolicy::{variant:?} to the same \
10843 lifted SUPERVISOR_CHILD_RESTART_* const \
10844 RestartPolicy::as_str returns — divergence signals a \
10845 silent detour off the substrate-primitive accessor"
10846 );
10847 assert!(
10848 matches!(via_trait, std::borrow::Cow::Borrowed(_)),
10849 "From<&RestartPolicy> for Cow<'static, str> impl must \
10850 land on the zero-alloc Cow::Borrowed arm on \
10851 &RestartPolicy::{variant:?} — a Cow::Owned outcome \
10852 signals the projection has silently allocated where \
10853 the substrate-primitive RestartPolicy::as_str \
10854 `&'static str` return makes the borrowed arm the \
10855 type-correct projection"
10856 );
10857 let via_into: std::borrow::Cow<'static, str> = (&variant).into();
10858 assert_eq!(
10859 via_into.as_ref(),
10860 via_method,
10861 "Into<Cow<'static, str>>::into on \
10862 &RestartPolicy::{variant:?} must byte-equal \
10863 RestartPolicy::as_str on the same input — the \
10864 blanket-derived Into shape must resolve to the same \
10865 as_str dispatch as the explicit From impl"
10866 );
10867 assert!(
10868 matches!(via_into, std::borrow::Cow::Borrowed(_)),
10869 "Into<Cow<'static, str>>::into on \
10870 &RestartPolicy::{variant:?} must land on the \
10871 zero-alloc Cow::Borrowed arm — the blanket-derived \
10872 Into shape must resolve to the same Cow::Borrowed \
10873 dispatch as the explicit From impl"
10874 );
10875 }
10876 }
10877
10878 #[test]
10879 fn restart_policy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
10880 // Cross-axis partition pin: the newly lifted trait-idiomatic
10881 // borrowed-input `From<&RestartPolicy> for
10882 // std::borrow::Cow<'static, str>` (this lift), the paired
10883 // owned-input `From<RestartPolicy> for
10884 // std::borrow::Cow<'static, str>` (0612398), the paired
10885 // borrowed-input owned-`&'static str` `From<&RestartPolicy>
10886 // for &'static str`, and the paired borrowed-input owned-
10887 // `String` `From<&RestartPolicy> for String` must resolve
10888 // identically on every arm, locking the four
10889 // return-shape × input-shape paths together by construction so
10890 // any future detour trips at caixa-core test time. Also byte-
10891 // parity witness against the sibling [`ToString::to_string`]
10892 // surface routed through [`std::fmt::Display`] — every owned-
10893 // heap-string path (this axis's `.into_owned()` promotion, the
10894 // paired [`From<&RestartPolicy> for String`], and
10895 // `.to_string()`) resolves to the same lifted
10896 // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const per arm.
10897 //
10898 // Then a `.iter().map(std::borrow::Cow::from)` pipe witness
10899 // over [`super::RestartPolicy::ALL`] — whose iterator yields
10900 // `&RestartPolicy` by construction, so the borrowed-input
10901 // [`Cow<'static, str>`] axis is what routes the pipe through
10902 // the substrate-primitive [`super::RestartPolicy::as_str`]
10903 // accessor without a spurious [`Copy`] deref (which would only
10904 // be reachable through the owned-input
10905 // [`From<RestartPolicy> for Cow<'static, str>`] axis by first
10906 // calling `.copied()` on the iterator). The pipe witness also
10907 // pins the zero-alloc discipline: every element in the
10908 // collected vector satisfies the [`std::borrow::Cow::Borrowed`]
10909 // arm predicate, so a future accidental silent-allocation
10910 // regression on the pipe's iteration axis is a caixa-core-
10911 // test-time failure. Peer of the sibling
10912 // [`restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
10913 // (9b3e4b3) on the M2 OTP-shape sibling-restart axis — closes
10914 // the whole borrowed-input `Cow<'static, str>` +
10915 // paired `{&'static str, String}` cross-axis-parity corner on
10916 // both M2 OTP-shape sibling peers.
10917 for &policy in RestartPolicy::ALL {
10918 let borrowed_cow: std::borrow::Cow<'static, str> =
10919 <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&policy);
10920 let owned_cow: std::borrow::Cow<'static, str> =
10921 <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(policy);
10922 let borrowed_static: &'static str =
10923 <&'static str as From<&RestartPolicy>>::from(&policy);
10924 let borrowed_string: String = <String as From<&RestartPolicy>>::from(&policy);
10925 assert_eq!(
10926 borrowed_cow, owned_cow,
10927 "From<&RestartPolicy> for Cow<'static, str> and \
10928 From<RestartPolicy> for Cow<'static, str> must \
10929 resolve identically on RestartPolicy::{policy:?} — \
10930 divergence signals the borrowed-input and owned-input \
10931 Cow<'static, str> forward-projection input-shape \
10932 paths have drifted onto different emit-sets"
10933 );
10934 assert_eq!(
10935 borrowed_cow.as_ref(),
10936 borrowed_static,
10937 "From<&RestartPolicy> for Cow<'static, str> and \
10938 From<&RestartPolicy> for &'static str must resolve \
10939 identically on RestartPolicy::{policy:?} — \
10940 divergence signals the borrowed-input Cow<'static, \
10941 str> and &'static str return-shape paths have drifted \
10942 onto different emit-sets"
10943 );
10944 assert_eq!(
10945 borrowed_cow.as_ref(),
10946 borrowed_string.as_str(),
10947 "From<&RestartPolicy> for Cow<'static, str> and \
10948 From<&RestartPolicy> for String must resolve \
10949 identically on RestartPolicy::{policy:?} — \
10950 divergence signals the borrowed-input Cow<'static, \
10951 str> and owned-`String` return-shape paths have \
10952 drifted onto different emit-sets"
10953 );
10954 let via_to_string: String = policy.to_string();
10955 assert_eq!(
10956 borrowed_cow.as_ref(),
10957 via_to_string.as_str(),
10958 "From<&RestartPolicy> for Cow<'static, str> must \
10959 byte-equal RestartPolicy::to_string on \
10960 RestartPolicy::{policy:?} — divergence signals \
10961 the trait-idiomatic borrowed-input Cow<'static, str> \
10962 forward-projection axis and the ToString-through-\
10963 Display axis have drifted onto different emit-sets"
10964 );
10965 }
10966 let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
10967 .iter()
10968 .map(std::borrow::Cow::from)
10969 .collect();
10970 let via_method: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
10971 .iter()
10972 .map(|p| std::borrow::Cow::Borrowed(p.as_str()))
10973 .collect();
10974 assert_eq!(
10975 via_iter, via_method,
10976 "`.iter().map(Cow::from)` over RestartPolicy::ALL — a \
10977 call site whose iteration axis holds `&RestartPolicy` \
10978 by construction — must byte-equal `.iter().map(|p| \
10979 Cow::Borrowed(p.as_str()))` on every arm — the borrowed-\
10980 input Cow<'static, str> `From<&RestartPolicy> for \
10981 Cow<'static, str>` axis is what makes the `Cow::from` \
10982 composition route through the substrate-primitive \
10983 `RestartPolicy::as_str` accessor with the zero-alloc \
10984 Cow::Borrowed arm by construction and without a spurious \
10985 `Copy` deref (which would only be reachable through the \
10986 owned-input `From<RestartPolicy> for Cow<'static, str>` \
10987 axis by first calling `.copied()` on the iterator)"
10988 );
10989 for cow in &via_iter {
10990 assert!(
10991 matches!(cow, std::borrow::Cow::Borrowed(_)),
10992 "every element of the .iter().map(Cow::from) pipe \
10993 over RestartPolicy::ALL must land on the zero-\
10994 alloc Cow::Borrowed arm — a Cow::Owned outcome on \
10995 any arm signals the pipe's iteration axis has \
10996 silently allocated where the substrate-primitive \
10997 RestartPolicy::as_str `&'static str` return makes \
10998 the borrowed arm the type-correct projection"
10999 );
11000 }
11001 }
11002
11003 #[test]
11004 fn restart_policy_from_into_box_str_routes_through_as_str_accessor() {
11005 // Fail-before-pass-after byte-parity pin on the newly lifted
11006 // `impl From<RestartPolicy> for Box<str>` — asserts the
11007 // owned-input standard-library trait impl and the
11008 // substrate-primitive [`super::RestartPolicy::as_str`]
11009 // `pub const fn` accessor resolve to the same three-arm emit-
11010 // set across every arm the exhaustive
11011 // [`super::RestartPolicy::ALL`] slice enumerates. Extends the
11012 // substrate-wide `Box<str>` forward-projection campaign tier
11013 // opened one commit prior (69ef45c) on the paired sibling-
11014 // restart [`RestartStrategy`] onto the second (and third-and-
11015 // final) M2 OTP-shape closed-set fieldless typed enum peer on
11016 // the caixa surface (`:children :restart`), immediately after
11017 // the paired `Cow<'static, str>` axis (0612398 / b4dc55c)
11018 // closed the
11019 // `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
11020 // 2×3 corner on this enum. Rust's standard library carries
11021 // `impl From<&str> for Box<str>` and
11022 // `impl From<String> for Box<str>` but no blanket
11023 // `impl<T: AsRef<str>> From<T> for Box<str>`, so this axis is
11024 // a distinct trait-idiomatic surface that a
11025 // `let key: Box<str> = policy.into();`-shaped call site
11026 // reaches through this impl and no other — a paired
11027 // `Box::from(policy.as_str())` open-code has no compile-time
11028 // link back to the substrate primitive. Peer of the sibling
11029 // [`restart_strategy_from_into_box_str_routes_through_as_str_accessor`]
11030 // (69ef45c) — extends the trait-idiomatic owned-input
11031 // [`Box<str>`] forward-projection axis onto the third and
11032 // final M2-OTP-shape closed-set typed enum on the caixa
11033 // surface.
11034 for &variant in RestartPolicy::ALL {
11035 let via_trait: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
11036 let via_method: &'static str = variant.as_str();
11037 assert_eq!(
11038 via_trait.as_ref(),
11039 via_method,
11040 "From<RestartPolicy> for Box<str> impl must round-\
11041 trip RestartPolicy::{variant:?} to the same lifted \
11042 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
11043 returns — divergence signals a silent detour off the \
11044 substrate-primitive accessor"
11045 );
11046 let via_into: Box<str> = variant.into();
11047 assert_eq!(
11048 via_into.as_ref(),
11049 via_method,
11050 "Into<Box<str>>::into on RestartPolicy::{variant:?} \
11051 must byte-equal RestartPolicy::as_str on the same \
11052 input — the blanket-derived Into shape must resolve \
11053 to the same as_str dispatch as the explicit From impl"
11054 );
11055 }
11056 }
11057
11058 #[test]
11059 fn restart_policy_from_borrowed_into_box_str_routes_through_as_str_accessor() {
11060 // Fail-before-pass-after byte-parity pin on the newly lifted
11061 // `impl From<&RestartPolicy> for Box<str>` — asserts the
11062 // borrowed-input standard-library trait impl and the
11063 // substrate-primitive [`super::RestartPolicy::as_str`]
11064 // `pub const fn` accessor resolve to the same three-arm emit-
11065 // set across every arm the exhaustive
11066 // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
11067 // standard library does not carry a blanket
11068 // `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
11069 // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
11070 // so the borrowed-input `Box<str>` forward-projection axis
11071 // is a distinct trait-idiomatic surface that a
11072 // `let key: Box<str> = (&policy).into();`-shaped call site
11073 // or a `RestartPolicy::ALL.iter().map(Box::<str>::from)`-
11074 // shaped pipe reaches through this impl and no other — the
11075 // paired owned-input `From<RestartPolicy> for Box<str>`
11076 // impl (0a1b313) forces every borrowed-input call site
11077 // through an explicit `Copy` deref
11078 // (`Box::<str>::from((*policy).as_str())`) or a
11079 // `Box::<str>::from(policy.as_str())` open-code whose
11080 // type bounds have no compile-time link back to the
11081 // substrate primitive.
11082 //
11083 // Fourth (and closing) peer on the substrate-wide trait-
11084 // idiomatic [`Box<str>`] forward-projection family on the
11085 // M2 OTP-shape tier — closes the `{Self, &Self}` input-
11086 // shape corner of the [`Box<str>`] axis on the second (and
11087 // third-and-final) M2 OTP-shape closed-set fieldless typed
11088 // enum peer on the caixa surface (`:children :restart`),
11089 // exactly as b4dc55c closed the paired [`Cow<'static, str>`]
11090 // axis one commit after its owning half (0612398) landed
11091 // on this enum. Every remaining closed-set fieldless typed
11092 // enum peer on the M3 mesh-shape / outside-M3 caixa-core /
11093 // render-side / outside-caixa-core tiers is a future
11094 // target of the campaign.
11095 //
11096 // Also byte-parity witness against the paired owned-input
11097 // [`From<RestartPolicy> for Box<str>`] and the sibling
11098 // borrowed-input [`From<&RestartPolicy> for &'static str`],
11099 // [`From<&RestartPolicy> for String`], and
11100 // [`From<&RestartPolicy> for Cow<'static, str>`]
11101 // return-shape axes — locking the four
11102 // return-shape × input-shape paths together by construction
11103 // so any future detour trips at caixa-core test time. Then a
11104 // `.iter().map(Box::<str>::from)` pipe witness over
11105 // [`super::RestartPolicy::ALL`] — whose iterator yields
11106 // `&RestartPolicy` by construction, so the borrowed-input
11107 // [`Box<str>`] axis is what routes the pipe through the
11108 // substrate-primitive [`super::RestartPolicy::as_str`]
11109 // accessor without a spurious [`Copy`] deref (which would
11110 // only be reachable through the owned-input
11111 // [`From<RestartPolicy> for Box<str>`] axis by first
11112 // calling `.copied()` on the iterator).
11113 for &variant in RestartPolicy::ALL {
11114 let via_trait: Box<str> = <Box<str> as From<&RestartPolicy>>::from(&variant);
11115 let via_method: &'static str = variant.as_str();
11116 assert_eq!(
11117 via_trait.as_ref(),
11118 via_method,
11119 "From<&RestartPolicy> for Box<str> impl must round-\
11120 trip &RestartPolicy::{variant:?} to the same lifted \
11121 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
11122 returns — divergence signals a silent detour off the \
11123 substrate-primitive accessor"
11124 );
11125 let via_into: Box<str> = (&variant).into();
11126 assert_eq!(
11127 via_into.as_ref(),
11128 via_method,
11129 "Into<Box<str>>::into on &RestartPolicy::{variant:?} \
11130 must byte-equal RestartPolicy::as_str on the same \
11131 input — the blanket-derived Into shape must resolve \
11132 to the same as_str dispatch as the explicit From impl"
11133 );
11134 let owned_box: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
11135 assert_eq!(
11136 via_trait, owned_box,
11137 "From<&RestartPolicy> for Box<str> and \
11138 From<RestartPolicy> for Box<str> must resolve \
11139 identically on RestartPolicy::{variant:?} — \
11140 divergence signals the borrowed-input and owned-input \
11141 Box<str> forward-projection input-shape paths have \
11142 drifted onto different emit-sets"
11143 );
11144 let borrowed_static: &'static str =
11145 <&'static str as From<&RestartPolicy>>::from(&variant);
11146 assert_eq!(
11147 via_trait.as_ref(),
11148 borrowed_static,
11149 "From<&RestartPolicy> for Box<str> and \
11150 From<&RestartPolicy> for &'static str must resolve \
11151 identically on RestartPolicy::{variant:?} — \
11152 divergence signals the borrowed-input Box<str> and \
11153 &'static str return-shape paths have drifted onto \
11154 different emit-sets"
11155 );
11156 let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
11157 assert_eq!(
11158 via_trait.as_ref(),
11159 borrowed_string.as_str(),
11160 "From<&RestartPolicy> for Box<str> and \
11161 From<&RestartPolicy> for String must resolve \
11162 identically on RestartPolicy::{variant:?} — \
11163 divergence signals the borrowed-input Box<str> and \
11164 owned-`String` return-shape paths have drifted onto \
11165 different emit-sets"
11166 );
11167 let borrowed_cow: std::borrow::Cow<'static, str> =
11168 <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
11169 assert_eq!(
11170 via_trait.as_ref(),
11171 borrowed_cow.as_ref(),
11172 "From<&RestartPolicy> for Box<str> and \
11173 From<&RestartPolicy> for Cow<'static, str> must \
11174 resolve identically on RestartPolicy::{variant:?} — \
11175 divergence signals the borrowed-input Box<str> and \
11176 Cow<'static, str> return-shape paths have drifted \
11177 onto different emit-sets"
11178 );
11179 }
11180 let via_iter: Vec<Box<str>> = RestartPolicy::ALL.iter().map(Box::<str>::from).collect();
11181 let via_method: Vec<Box<str>> = RestartPolicy::ALL
11182 .iter()
11183 .map(|p| Box::<str>::from(p.as_str()))
11184 .collect();
11185 assert_eq!(
11186 via_iter, via_method,
11187 "`.iter().map(Box::<str>::from)` over \
11188 RestartPolicy::ALL — a call site whose iteration axis \
11189 holds `&RestartPolicy` by construction — must byte-\
11190 equal `.iter().map(|p| Box::<str>::from(p.as_str()))` \
11191 on every arm — the borrowed-input Box<str> \
11192 `From<&RestartPolicy> for Box<str>` axis is what \
11193 makes the `Box::<str>::from` composition route through \
11194 the substrate-primitive `RestartPolicy::as_str` \
11195 accessor without a spurious `Copy` deref (which would \
11196 only be reachable through the owned-input \
11197 `From<RestartPolicy> for Box<str>` axis by first \
11198 calling `.copied()` on the iterator)"
11199 );
11200 }
11201
11202 #[test]
11203 fn restart_policy_from_into_arc_str_routes_through_as_str_accessor() {
11204 // Fail-before-pass-after byte-parity pin on the newly lifted
11205 // `impl From<RestartPolicy> for std::sync::Arc<str>` — asserts
11206 // the owned-input standard-library trait impl and the
11207 // substrate-primitive [`super::RestartPolicy::as_str`]
11208 // `pub const fn` accessor resolve to the same three-arm emit-
11209 // set across every arm the exhaustive
11210 // [`super::RestartPolicy::ALL`] slice enumerates. Extends the
11211 // substrate-wide [`std::sync::Arc<str>`] forward-projection
11212 // campaign tier opened one projection tier prior (bca2ec8) on
11213 // the paired sibling-restart [`RestartStrategy`] owned-input
11214 // first-mover onto the second (and third-and-final) M2 OTP-
11215 // shape closed-set fieldless typed enum peer on the caixa
11216 // surface (`:children :restart`), immediately after the paired
11217 // [`Box<str>`] axis (0a1b313 / cb1d068) closed the
11218 // `{Self, &Self} × {&'static str, String, Cow<'static, str>,
11219 // Box<str>}` 2×4 corner on this enum. Rust's standard library
11220 // carries `impl From<&str> for std::sync::Arc<str>` and
11221 // `impl From<String> for std::sync::Arc<str>` but no blanket
11222 // `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor
11223 // an `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`),
11224 // so this axis is a distinct trait-idiomatic surface that a
11225 // `let key: std::sync::Arc<str> = policy.into();`-shaped call
11226 // site reaches through this impl and no other — a paired
11227 // `std::sync::Arc::<str>::from(policy.as_str())` open-code
11228 // has no compile-time link back to the substrate primitive,
11229 // and a two-step `std::sync::Arc::<str>::from(String::from(
11230 // policy))` composition through the owned-`String` axis
11231 // allocates twice (once into the intermediate `String`, once
11232 // into the [`Arc<str>`] on the `From<String>` conversion)
11233 // where the single-step trait impl allocates once.
11234 //
11235 // Cross-axis byte-parity witness against the sibling owned-
11236 // input `{&'static str, String, Cow<'static, str>, Box<str>}`
11237 // return-shape axes — locking the five return-shape paths on
11238 // the owned-input surface together by construction so any
11239 // future detour off the substrate-primitive
11240 // [`super::RestartPolicy::as_str`] accessor trips at caixa-
11241 // core test time.
11242 for &variant in RestartPolicy::ALL {
11243 let via_trait: std::sync::Arc<str> =
11244 <std::sync::Arc<str> as From<RestartPolicy>>::from(variant);
11245 let via_method: &'static str = variant.as_str();
11246 assert_eq!(
11247 via_trait.as_ref(),
11248 via_method,
11249 "From<RestartPolicy> for std::sync::Arc<str> impl \
11250 must round-trip RestartPolicy::{variant:?} to the \
11251 same lifted SUPERVISOR_CHILD_RESTART_* const \
11252 RestartPolicy::as_str returns — divergence signals \
11253 a silent detour off the substrate-primitive accessor"
11254 );
11255 let via_into: std::sync::Arc<str> = variant.into();
11256 assert_eq!(
11257 via_into.as_ref(),
11258 via_method,
11259 "Into<std::sync::Arc<str>>::into on \
11260 RestartPolicy::{variant:?} must byte-equal \
11261 RestartPolicy::as_str on the same input — the \
11262 blanket-derived Into shape must resolve to the same \
11263 as_str dispatch as the explicit From impl"
11264 );
11265 let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
11266 assert_eq!(
11267 via_trait.as_ref(),
11268 owned_static,
11269 "From<RestartPolicy> for std::sync::Arc<str> and \
11270 From<RestartPolicy> for &'static str must resolve \
11271 identically on RestartPolicy::{variant:?} — \
11272 divergence signals the owned-input std::sync::Arc<str> \
11273 and &'static str return-shape paths have drifted onto \
11274 different emit-sets"
11275 );
11276 let owned_string: String = <String as From<RestartPolicy>>::from(variant);
11277 assert_eq!(
11278 via_trait.as_ref(),
11279 owned_string.as_str(),
11280 "From<RestartPolicy> for std::sync::Arc<str> and \
11281 From<RestartPolicy> for String must resolve \
11282 identically on RestartPolicy::{variant:?} — \
11283 divergence signals the owned-input std::sync::Arc<str> \
11284 and owned-`String` return-shape paths have drifted \
11285 onto different emit-sets"
11286 );
11287 let owned_cow: std::borrow::Cow<'static, str> =
11288 <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
11289 assert_eq!(
11290 via_trait.as_ref(),
11291 owned_cow.as_ref(),
11292 "From<RestartPolicy> for std::sync::Arc<str> and \
11293 From<RestartPolicy> for Cow<'static, str> must \
11294 resolve identically on RestartPolicy::{variant:?} — \
11295 divergence signals the owned-input std::sync::Arc<str> \
11296 and Cow<'static, str> return-shape paths have drifted \
11297 onto different emit-sets"
11298 );
11299 let owned_box: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
11300 assert_eq!(
11301 via_trait.as_ref(),
11302 owned_box.as_ref(),
11303 "From<RestartPolicy> for std::sync::Arc<str> and \
11304 From<RestartPolicy> for Box<str> must resolve \
11305 identically on RestartPolicy::{variant:?} — \
11306 divergence signals the owned-input std::sync::Arc<str> \
11307 and Box<str> return-shape paths have drifted onto \
11308 different emit-sets"
11309 );
11310 }
11311 }
11312
11313 #[test]
11314 fn restart_policy_from_borrowed_into_arc_str_routes_through_as_str_accessor() {
11315 // Fail-before-pass-after byte-parity pin on the newly lifted
11316 // `impl From<&RestartPolicy> for std::sync::Arc<str>` —
11317 // asserts the borrowed-input standard-library trait impl and
11318 // the substrate-primitive [`super::RestartPolicy::as_str`]
11319 // `pub const fn` accessor resolve to the same three-arm
11320 // emit-set across every arm the exhaustive
11321 // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
11322 // standard library carries `impl From<&str> for
11323 // std::sync::Arc<str>` and `impl From<String> for
11324 // std::sync::Arc<str>` but no blanket
11325 // `impl<T: AsRef<str>> From<&T> for std::sync::Arc<str>` (nor
11326 // a `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
11327 // so the borrowed-input [`std::sync::Arc<str>`] forward-
11328 // projection axis is a distinct trait-idiomatic surface that
11329 // a `let key: std::sync::Arc<str> = (&policy).into();`-shaped
11330 // call site or a
11331 // `RestartPolicy::ALL.iter().map(std::sync::Arc::<str>::from)`-
11332 // shaped pipe reaches through this impl and no other — the
11333 // paired owned-input [`From<RestartPolicy> for
11334 // std::sync::Arc<str>`] impl (b05724e) forces every borrowed-
11335 // input call site through an explicit [`Copy`] deref
11336 // (`std::sync::Arc::<str>::from((*policy).as_str())`) or a
11337 // `std::sync::Arc::<str>::from(policy.as_str())` open-code
11338 // whose type bounds have no compile-time link back to the
11339 // substrate primitive.
11340 //
11341 // Closes the `{Self, &Self}` input-shape corner of the
11342 // substrate-wide trait-idiomatic [`std::sync::Arc<str>`]
11343 // forward-projection family on the second (and third-and-
11344 // final) M2 OTP-shape closed-set fieldless typed enum peer
11345 // on the caixa surface (`:children :restart`), one commit
11346 // after b05724e opened the owned-input half — exactly as
11347 // b3e72d7 closed the paired [`std::sync::Arc<str>`] corner on
11348 // the sibling-restart [`RestartStrategy`] first-mover one
11349 // commit after its owning half (bca2ec8) landed, and as
11350 // cb1d068 closed the paired [`Box<str>`] corner on this
11351 // enum one commit after its owning half (0a1b313) landed.
11352 //
11353 // Also byte-parity witness against the paired owned-input
11354 // [`From<RestartPolicy> for std::sync::Arc<str>`] and the
11355 // sibling borrowed-input [`From<&RestartPolicy> for
11356 // &'static str`], [`From<&RestartPolicy> for String`],
11357 // [`From<&RestartPolicy> for Cow<'static, str>`], and
11358 // [`From<&RestartPolicy> for Box<str>`] return-shape axes —
11359 // locking the five return-shape × input-shape paths together
11360 // by construction so any future detour off the substrate-
11361 // primitive [`super::RestartPolicy::as_str`] accessor trips
11362 // at caixa-core test time. Then a
11363 // `.iter().map(std::sync::Arc::<str>::from)` pipe witness
11364 // over [`super::RestartPolicy::ALL`] — whose iterator yields
11365 // `&RestartPolicy` by construction, so the borrowed-input
11366 // [`std::sync::Arc<str>`] axis is what routes the pipe
11367 // through the substrate-primitive
11368 // [`super::RestartPolicy::as_str`] accessor without a
11369 // spurious [`Copy`] deref (which would only be reachable
11370 // through the owned-input
11371 // [`From<RestartPolicy> for std::sync::Arc<str>`] axis by
11372 // first calling `.copied()` on the iterator).
11373 for &variant in RestartPolicy::ALL {
11374 let via_trait: std::sync::Arc<str> =
11375 <std::sync::Arc<str> as From<&RestartPolicy>>::from(&variant);
11376 let via_method: &'static str = variant.as_str();
11377 assert_eq!(
11378 via_trait.as_ref(),
11379 via_method,
11380 "From<&RestartPolicy> for std::sync::Arc<str> impl \
11381 must round-trip &RestartPolicy::{variant:?} to the \
11382 same lifted SUPERVISOR_CHILD_RESTART_* const \
11383 RestartPolicy::as_str returns — divergence signals \
11384 a silent detour off the substrate-primitive accessor"
11385 );
11386 let via_into: std::sync::Arc<str> = (&variant).into();
11387 assert_eq!(
11388 via_into.as_ref(),
11389 via_method,
11390 "Into<std::sync::Arc<str>>::into on \
11391 &RestartPolicy::{variant:?} must byte-equal \
11392 RestartPolicy::as_str on the same input — the \
11393 blanket-derived Into shape must resolve to the same \
11394 as_str dispatch as the explicit From impl"
11395 );
11396 let owned_arc: std::sync::Arc<str> =
11397 <std::sync::Arc<str> as From<RestartPolicy>>::from(variant);
11398 assert_eq!(
11399 via_trait, owned_arc,
11400 "From<&RestartPolicy> for std::sync::Arc<str> and \
11401 From<RestartPolicy> for std::sync::Arc<str> must \
11402 resolve identically on RestartPolicy::{variant:?} — \
11403 divergence signals the borrowed-input and owned-input \
11404 std::sync::Arc<str> forward-projection input-shape \
11405 paths have drifted onto different emit-sets"
11406 );
11407 let borrowed_static: &'static str =
11408 <&'static str as From<&RestartPolicy>>::from(&variant);
11409 assert_eq!(
11410 via_trait.as_ref(),
11411 borrowed_static,
11412 "From<&RestartPolicy> for std::sync::Arc<str> and \
11413 From<&RestartPolicy> for &'static str must resolve \
11414 identically on RestartPolicy::{variant:?} — \
11415 divergence signals the borrowed-input std::sync::Arc<str> \
11416 and &'static str return-shape paths have drifted onto \
11417 different emit-sets"
11418 );
11419 let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
11420 assert_eq!(
11421 via_trait.as_ref(),
11422 borrowed_string.as_str(),
11423 "From<&RestartPolicy> for std::sync::Arc<str> and \
11424 From<&RestartPolicy> for String must resolve \
11425 identically on RestartPolicy::{variant:?} — \
11426 divergence signals the borrowed-input std::sync::Arc<str> \
11427 and owned-`String` return-shape paths have drifted \
11428 onto different emit-sets"
11429 );
11430 let borrowed_cow: std::borrow::Cow<'static, str> =
11431 <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
11432 assert_eq!(
11433 via_trait.as_ref(),
11434 borrowed_cow.as_ref(),
11435 "From<&RestartPolicy> for std::sync::Arc<str> and \
11436 From<&RestartPolicy> for Cow<'static, str> must \
11437 resolve identically on RestartPolicy::{variant:?} — \
11438 divergence signals the borrowed-input std::sync::Arc<str> \
11439 and Cow<'static, str> return-shape paths have drifted \
11440 onto different emit-sets"
11441 );
11442 let borrowed_box: Box<str> = <Box<str> as From<&RestartPolicy>>::from(&variant);
11443 assert_eq!(
11444 via_trait.as_ref(),
11445 borrowed_box.as_ref(),
11446 "From<&RestartPolicy> for std::sync::Arc<str> and \
11447 From<&RestartPolicy> for Box<str> must resolve \
11448 identically on RestartPolicy::{variant:?} — \
11449 divergence signals the borrowed-input std::sync::Arc<str> \
11450 and Box<str> return-shape paths have drifted onto \
11451 different emit-sets"
11452 );
11453 }
11454 let via_iter: Vec<std::sync::Arc<str>> = RestartPolicy::ALL
11455 .iter()
11456 .map(std::sync::Arc::<str>::from)
11457 .collect();
11458 let via_method: Vec<std::sync::Arc<str>> = RestartPolicy::ALL
11459 .iter()
11460 .map(|p| std::sync::Arc::<str>::from(p.as_str()))
11461 .collect();
11462 assert_eq!(
11463 via_iter, via_method,
11464 "`.iter().map(std::sync::Arc::<str>::from)` over \
11465 RestartPolicy::ALL — a call site whose iteration axis \
11466 holds `&RestartPolicy` by construction — must byte-\
11467 equal `.iter().map(|p| std::sync::Arc::<str>::from(p.as_str()))` \
11468 on every arm — the borrowed-input std::sync::Arc<str> \
11469 `From<&RestartPolicy> for std::sync::Arc<str>` axis is \
11470 what makes the `std::sync::Arc::<str>::from` composition \
11471 route through the substrate-primitive \
11472 `RestartPolicy::as_str` accessor without a spurious \
11473 `Copy` deref (which would only be reachable through the \
11474 owned-input `From<RestartPolicy> for std::sync::Arc<str>` \
11475 axis by first calling `.copied()` on the iterator)"
11476 );
11477 }
11478
11479 // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_RESTART_* identity ─
11480
11481 #[test]
11482 fn restart_policy_variants_serialize_to_lifted_scalar_values() {
11483 // The fail-before-pass-after pin: pre-lift there was no
11484 // single-source binding between the [`RestartPolicy`] variant
11485 // name the un-`rename`d `Serialize` derive emits under
11486 // [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
11487 // byte-string every downstream cluster-side dispatcher (the
11488 // future wasm-operator's per-child post-exit restart-decision
11489 // branch, the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
11490 // materializer's admission-time enum-arm bind, the
11491 // `caixa-operator`'s hierarchical reconciliation scheduler's
11492 // per-child-policy fan-out) probes verbatim. A future
11493 // `#[serde(rename_all = "kebab-case")]` attribute on the enum —
11494 // or a per-variant `#[serde(rename = "…")]` override, or a
11495 // variant rename in the source — would silently rebrand the
11496 // emitted scalar under one spelling while every downstream
11497 // dispatcher still probed the other, with the failure surfacing
11498 // at the operator's reconcile posture (children coming up under
11499 // the `default()` `Permanent` arm rather than the typed slot's
11500 // declared policy — a `:temporary` `oneShot` child would be
11501 // restarted on clean exit, treating the successful-completion
11502 // signal as failure and re-running the completion-terminal
11503 // one-shot indefinitely; a `:transient` child that clean-exited
11504 // would be restarted, masking the clean-completion contract)
11505 // far from the source rebrand commit and with no field naming
11506 // the drift. Pinning the two paths (the `Serialize` derive's
11507 // serialized string AND the [`RestartPolicy::as_str`] helper)
11508 // to the same three lifted
11509 // [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
11510 // [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
11511 // [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
11512 // byte-strings makes any future drift on either endpoint fail
11513 // here at caixa-core build time. Peer of the sibling
11514 // [`restart_strategy_variants_serialize_to_lifted_scalar_values`]
11515 // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
11516 // and the M3
11517 // `placement_strategy_variants_serialize_to_lifted_scalar_values`
11518 // (3f0e21c) on the per-Aplicacao distribution-strategy axis —
11519 // same three-path-convergence discipline, extended to close the
11520 // third OTP-shaped closed-enum discriminator axis on the caixa
11521 // typed surface (per-child restart-decision policy).
11522 for (variant, expected) in [
11523 (
11524 RestartPolicy::Permanent,
11525 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
11526 ),
11527 (
11528 RestartPolicy::Temporary,
11529 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
11530 ),
11531 (
11532 RestartPolicy::Transient,
11533 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
11534 ),
11535 ] {
11536 let json = serde_json::to_string(&variant).unwrap();
11537 assert_eq!(
11538 json,
11539 format!("\"{expected}\""),
11540 "RestartPolicy::{variant:?} must serialize to {expected:?}"
11541 );
11542 assert_eq!(
11543 variant.as_str(),
11544 expected,
11545 "RestartPolicy::{variant:?}.as_str() must return the lifted \
11546 SUPERVISOR_CHILD_RESTART_* constant"
11547 );
11548 }
11549 }
11550
11551 #[test]
11552 fn supervisor_child_restart_consts_are_pairwise_distinct() {
11553 // Cross-arm drift-detection pin: a future collapse of two
11554 // canonical variant byte-strings onto the same value (e.g. an
11555 // accidental copy-paste flip of `SUPERVISOR_CHILD_RESTART_TRANSIENT`
11556 // to also read `"Permanent"`) would silently reroute every
11557 // downstream operator's per-child-policy dispatch onto the
11558 // sibling arm's reconcile branch and pass every propagation-probe
11559 // test that expected only the stale arm's value — a `:transient`
11560 // child would come up under the `:permanent` restart-decision
11561 // posture on every subsequent clean exit, so a completion-terminal
11562 // child would be restarted indefinitely against its declared
11563 // policy. Peer of the sibling
11564 // [`supervisor_estrategia_consts_are_pairwise_distinct`]
11565 // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
11566 // and the four-way distinct pin
11567 // `supervisor_key_consts_are_pairwise_distinct` (40cc4e5) on the
11568 // top-level `SUPERVISOR_KEY_*` axis.
11569 let all = [
11570 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
11571 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
11572 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
11573 ];
11574 for (i, a) in all.iter().enumerate() {
11575 for (j, b) in all.iter().enumerate() {
11576 if i != j {
11577 assert_ne!(
11578 a, b,
11579 "SUPERVISOR_CHILD_RESTART_* consts must be pairwise distinct \
11580 — got duplicate {a:?} at indices {i} and {j}",
11581 );
11582 }
11583 }
11584 }
11585 }
11586
11587 #[test]
11588 fn restart_policy_display_routes_through_as_str_helper() {
11589 // The fail-before-pass-after pin on the first half of the
11590 // three-path convergence: pre-convergence [`RestartPolicy`]
11591 // carried a [`std::fmt::Display`] surface via its
11592 // `#[discriminant(also_display)]` gen-platform derive route,
11593 // which arrived kebab-case as `"permanent"` / `"temporary"`
11594 // / `"transient"` on this three-arm enum (whose variant
11595 // names each collapse to their own lowercase form under the
11596 // kebab-case transform) while the wire format ran as
11597 // PascalCase `"Permanent"` / `"Temporary"` / `"Transient"`
11598 // through the un-`rename`d serde derive. Every consumer
11599 // reaching for a policy byte-string past the wire format had
11600 // to pick between three paths ([`RestartPolicy::as_str`],
11601 // the `Serialize` derive's serialized string, or
11602 // `format!("{v}")` on the discriminant-Display route), any
11603 // two of which a future variant rename or
11604 // `#[serde(rename_all = "kebab-case")]` attribute would
11605 // silently desynchronize. Wiring [`std::fmt::Display`]
11606 // through [`RestartPolicy::as_str`] closes the third path:
11607 // every `format!("{v}")` call reaches the same lifted
11608 // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the
11609 // wire format and the [`RestartPolicy::as_str`] helper
11610 // already route through, so a future variant rename lands at
11611 // exactly one place. Pin the routing here so a future
11612 // `impl std::fmt::Display for RestartPolicy`
11613 // reimplementation that hand-rolls the arms instead of
11614 // delegating to [`RestartPolicy::as_str`] fails at
11615 // caixa-core build time. Peer of the sibling
11616 // [`restart_strategy_display_routes_through_as_str_helper`]
11617 // on the per-supervisor sibling-restart-strategy axis and
11618 // the M3
11619 // `placement_strategy_display_routes_through_as_str_helper`
11620 // (cc8f749) — the third of three OTP-shape closed-enum
11621 // discriminator axes on the caixa typed surface now
11622 // converged onto the same three-path
11623 // (Display → as_str → lifted const) discipline.
11624 for variant in [
11625 RestartPolicy::Permanent,
11626 RestartPolicy::Temporary,
11627 RestartPolicy::Transient,
11628 ] {
11629 assert_eq!(
11630 variant.to_string(),
11631 variant.as_str(),
11632 "RestartPolicy::{variant:?} Display must route through \
11633 RestartPolicy::as_str (single source of truth: the lifted \
11634 SUPERVISOR_CHILD_RESTART_* const the wire format also emits)"
11635 );
11636 }
11637 }
11638
11639 #[test]
11640 fn restart_policy_display_matches_serialized_wire_byte_string() {
11641 // The fail-before-pass-after pin on the second half of the
11642 // three-path convergence: `Display` (user-facing text) agrees
11643 // byte-for-byte with the `Serialize` derive's wire format
11644 // (canonical camelCase-schema `SUPERVISOR_CHILD_KEY_RESTART`
11645 // scalar) on every variant. Pre-convergence the two paths
11646 // were structurally independent — a future
11647 // `#[serde(rename_all = "kebab-case")]` attribute on the
11648 // enum would silently rebrand the emitted wire scalar
11649 // (`permanent`, `temporary`, `transient`) while every
11650 // consumer that pretty-prints the policy (the future
11651 // wasm-operator's per-child post-exit restart-decision
11652 // diagnostic line, the future `feira app graph` per-child
11653 // restart column, the future M4
11654 // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
11655 // per-child admission-webhook rejection body) would still
11656 // emit the PascalCase form the `as_str` / `Display` route
11657 // returns, with the mismatch surfacing at consumer parse
11658 // time / operator dispatch time far from the source rebrand
11659 // commit. Pin the two paths byte-for-byte here so any future
11660 // serde-attribute or variant-rename drift is a
11661 // caixa-core-build-time test failure at this call, not a
11662 // silent per-consumer dispatch miss. Peer of the sibling
11663 // [`restart_strategy_display_matches_serialized_wire_byte_string`]
11664 // on the per-supervisor sibling-restart-strategy axis and
11665 // the M3
11666 // `placement_strategy_display_matches_serialized_wire_byte_string`
11667 // (cc8f749).
11668 for variant in [
11669 RestartPolicy::Permanent,
11670 RestartPolicy::Temporary,
11671 RestartPolicy::Transient,
11672 ] {
11673 let wire = serde_json::to_string(&variant).unwrap();
11674 let unquoted = wire
11675 .strip_prefix('"')
11676 .and_then(|s| s.strip_suffix('"'))
11677 .expect("serialized RestartPolicy is a JSON string");
11678 assert_eq!(
11679 variant.to_string(),
11680 unquoted,
11681 "RestartPolicy::{variant:?} Display byte-string must match the \
11682 Serialize derive's wire byte-string (three-path convergence: \
11683 Display + as_str + Serialize all resolve to the same \
11684 SUPERVISOR_CHILD_RESTART_* const)"
11685 );
11686 }
11687 }
11688
11689 #[test]
11690 fn restart_policy_as_ref_str_routes_through_as_str_accessor() {
11691 // Fail-before-pass-after byte-parity pin on the lifted
11692 // `impl AsRef<str> for RestartPolicy` — asserts the
11693 // standard-library trait impl and the substrate-primitive
11694 // [`RestartPolicy::as_str`] `pub const fn` accessor resolve
11695 // to the same `&str` per instance across the three-arm
11696 // closed set, so any future silent detour that routes the
11697 // impl through a divergent projection (a per-arm inline
11698 // `match self { RestartPolicy::Permanent => "Permanent", … }`
11699 // re-inlining that opens a compile-time link to the un-lifted
11700 // arm-literal, a swap onto the kebab-case
11701 // [`gen_platform::Discriminant`] catalog identity that would
11702 // collide the wire axis with the dispatcher-catalog axis) trips
11703 // at caixa-core test time under `PartialEq` rather than at a
11704 // downstream `impl AsRef<str>`-bound consumer's silent split.
11705 // Sweeps every one of the three arms
11706 // [`RestartPolicy::ALL`] carries so no arm's projection is
11707 // covered only by the sibling wire-format `Serialize` derive
11708 // path. Peer of the sibling
11709 // [`restart_strategy_as_ref_str_routes_through_as_str_accessor`]
11710 // (63eb1a4) on the paired per-supervisor sibling-restart-
11711 // strategy axis and the [`crate::CaixaVersion`]
11712 // `AsRef<str>`-byte-parity pin (16d5c7e) on the paired
11713 // top-level `:versao` typed newtype — the three pins together
11714 // cover the substrate primitive's `AsRef<str>` projection axis
11715 // on the paired newtype + M2 closed-set-typed-enum surface.
11716 for &variant in RestartPolicy::ALL {
11717 assert_eq!(
11718 <RestartPolicy as AsRef<str>>::as_ref(&variant),
11719 variant.as_str(),
11720 "AsRef<str> impl on RestartPolicy::{variant:?} must \
11721 byte-equal RestartPolicy::as_str on the same instance \
11722 — divergence signals a silent detour off the substrate-\
11723 primitive accessor"
11724 );
11725 }
11726 }
11727
11728 #[test]
11729 fn restart_policy_as_ref_str_routes_through_display_via_shared_accessor() {
11730 // Fail-before-pass-after byte-parity pin on the three-path
11731 // convergence discipline the M2 per-child-restart-policy
11732 // primitive now carries on the `&str`-projection axis:
11733 // `<RestartPolicy as AsRef<str>>::as_ref(&v)` (the newly
11734 // lifted impl), `format!("{v}")` (the pre-existing
11735 // [`fmt::Display`] impl), and `v.as_str()` (the substrate-
11736 // primitive `pub const fn` accessor both trait impls delegate
11737 // through) must resolve to the same byte-string on every
11738 // instance across the three-arm closed set. Refuses any future
11739 // divergence between the two trait impls (a stray
11740 // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
11741 // rather than delegating through the shared accessor; a
11742 // hypothetical `AsRef<str>` rewrite that inlines a per-arm
11743 // literal cascade) that would silently split the two
11744 // projection paths of the same closed-set typed enum. Mirrors
11745 // the sibling three-path-convergence discipline the peer
11746 // [`RestartStrategy`] typed enum carries on its
11747 // `AsRef<str>` / `Display` / `as_str` triple
11748 // (supervisor.rs pin
11749 // `restart_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
11750 // 63eb1a4) and the [`crate::CaixaVersion`] typed newtype
11751 // carries on the same triple (version.rs pin
11752 // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
11753 // 16d5c7e).
11754 for &variant in RestartPolicy::ALL {
11755 let via_as_ref: &str = <RestartPolicy as AsRef<str>>::as_ref(&variant);
11756 let via_display: String = format!("{variant}");
11757 let via_accessor: &str = variant.as_str();
11758 assert_eq!(via_as_ref, via_accessor);
11759 assert_eq!(via_display, via_accessor);
11760 assert_eq!(via_as_ref, via_display.as_str());
11761 }
11762 }
11763
11764 #[test]
11765 fn restart_policy_all_enumerates_every_variant_exactly_once() {
11766 // Fail-before-pass-after pin on the [`RestartPolicy::ALL`]
11767 // exhaustive-iteration surface: every variant appears exactly
11768 // once, and the slice length matches the arm count of the
11769 // closed set. Every consumer that walks the accepted-policy
11770 // set (a future `feira supervisor --restart …` CLI-side
11771 // arg-parse's "did you mean" hint, a future M4 admission-
11772 // webhook's per-child rejection body naming the accepted-
11773 // `:restart` list, the [`RestartPolicy::from_wire`] reverse-
11774 // projection consumers that iterate the accept-set for
11775 // diagnostic rendering) reads through this slice, so a future
11776 // arm addition that grows the enum but forgets to grow
11777 // [`Self::ALL`] silently truncates every downstream consumer's
11778 // accept-set at the same pre-addition boundary — this pin
11779 // fails at caixa-core build time on the pairwise-distinct +
11780 // arm-count invariants.
11781 //
11782 // Peer of the sibling [`RestartStrategy::ALL`] (4eec29c) /
11783 // [`crate::CaixaKind::ALL`] (6b1f4fb) /
11784 // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
11785 // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
11786 // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
11787 // pins on the peer closed-set typed-enum axes.
11788 let all: &[RestartPolicy] = RestartPolicy::ALL;
11789 assert_eq!(
11790 all.len(),
11791 3,
11792 "RestartPolicy::ALL must enumerate every variant of the \
11793 three-arm closed set (Permanent, Temporary, Transient); \
11794 got {all:?}"
11795 );
11796 for (i, a) in all.iter().enumerate() {
11797 for (j, b) in all.iter().enumerate() {
11798 if i != j {
11799 assert_ne!(
11800 a, b,
11801 "RestartPolicy::ALL must carry every variant exactly \
11802 once — got duplicate {a:?} at indices {i} and {j}"
11803 );
11804 }
11805 }
11806 }
11807 for variant in [
11808 RestartPolicy::Permanent,
11809 RestartPolicy::Temporary,
11810 RestartPolicy::Transient,
11811 ] {
11812 assert!(
11813 all.contains(&variant),
11814 "RestartPolicy::ALL must contain {variant:?} — a future arm \
11815 addition that grows the enum but forgets to grow the ALL slice \
11816 silently truncates every downstream consumer's accept-set at \
11817 the pre-addition boundary"
11818 );
11819 }
11820 }
11821
11822 #[test]
11823 fn restart_policy_from_wire_accepts_every_lifted_constant() {
11824 // Fail-before-pass-after pin on the forward accept-set of the
11825 // [`RestartPolicy::from_wire`] reverse projection: every
11826 // canonical [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
11827 // constant the [`RestartPolicy::as_str`] emitter walks parses
11828 // back to its paired variant. Any future arm addition that
11829 // grows the emitter's `as_str` match but forgets to grow the
11830 // parser's `from_wire` match silently splits the two halves of
11831 // the round-trip — the wire byte-string one non-serde consumer
11832 // parses from the one the emitter wrote — with the failure
11833 // surfacing at the operator's reconcile posture (a `:temporary`
11834 // `oneShot` child restarted on clean exit, a `:transient` child
11835 // restarted after clean completion) far from the rebrand
11836 // commit. Pinning the three-arm accept-set here catches the
11837 // drift at caixa-core build time.
11838 //
11839 // Peer of the sibling [`RestartStrategy::from_wire`] (4eec29c)
11840 // + [`crate::CaixaKind::from_wire`] (2aa6d23)
11841 // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
11842 // accept-set pins on the peer closed-set typed-enum `str → Self`
11843 // axes.
11844 for (wire, expected) in [
11845 (
11846 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
11847 RestartPolicy::Permanent,
11848 ),
11849 (
11850 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
11851 RestartPolicy::Temporary,
11852 ),
11853 (
11854 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
11855 RestartPolicy::Transient,
11856 ),
11857 ] {
11858 let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
11859 panic!(
11860 "RestartPolicy::from_wire({wire:?}) must accept every \
11861 SUPERVISOR_CHILD_RESTART_* constant — got None for the \
11862 lifted canonical byte-string that RestartPolicy::{expected:?} \
11863 serializes as under SUPERVISOR_CHILD_KEY_RESTART"
11864 )
11865 });
11866 assert_eq!(
11867 parsed, expected,
11868 "RestartPolicy::from_wire({wire:?}) must return \
11869 RestartPolicy::{expected:?}; got RestartPolicy::{parsed:?}"
11870 );
11871 }
11872 }
11873
11874 #[test]
11875 fn restart_policy_from_wire_round_trips_through_as_str() {
11876 // Fail-before-pass-after pin on the closed round-trip between
11877 // the forward [`RestartPolicy::as_str`] emitter and the
11878 // reverse [`RestartPolicy::from_wire`] parser: for every
11879 // variant in [`RestartPolicy::ALL`], parsing the emitter's
11880 // output must return exactly the same variant. Any per-arm
11881 // divergence — a future arm added to `as_str` but not
11882 // `from_wire`, an accidental copy-paste flip in one but not
11883 // the other — silently splits the emit and parse halves and
11884 // the failure surfaces at consumer parse time far from the
11885 // drift site. The `ALL`-iterating shape means a future arm
11886 // addition picks up the coverage by construction.
11887 //
11888 // Peer of the sibling
11889 // [`restart_strategy_from_wire_round_trips_through_as_str`]
11890 // (4eec29c) round-trip pin on
11891 // [`RestartStrategy::from_wire`] and the M3
11892 // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
11893 // (18c7342) round-trip pin on
11894 // [`crate::aplicacao::PlacementStrategy::from_wire`].
11895 for &variant in RestartPolicy::ALL {
11896 let wire = variant.as_str();
11897 let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
11898 panic!(
11899 "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
11900 must be Some({variant:?}) — the two halves of the round-trip \
11901 dispatch on the same lifted SUPERVISOR_CHILD_RESTART_* consts; \
11902 got None on wire byte-string {wire:?}"
11903 )
11904 });
11905 assert_eq!(
11906 parsed, variant,
11907 "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
11908 must round-trip to the same variant; got {parsed:?}"
11909 );
11910 }
11911 }
11912
11913 #[test]
11914 fn restart_policy_from_wire_rejects_unknown_byte_strings() {
11915 // Fail-before-pass-after pin on the closed-set refusal
11916 // discipline of [`RestartPolicy::from_wire`]: every
11917 // byte-string outside the three-arm accept-set returns `None`
11918 // rather than silently collapsing onto the [`Default`]
11919 // (`Permanent`) arm or an arbitrary neighbor. The refusal set
11920 // exercised here sweeps the load-bearing drift shapes: the
11921 // empty string (a stripped serde-attribute drift), all-
11922 // whitespace strings (the canonical text-editor accidental
11923 // padding shape), the kebab-case dispatcher-catalog identities
11924 // (`"permanent"` / `"temporary"` / `"transient"` — the
11925 // [`gen_platform::FromStrKind`]-derived [`std::str::FromStr`]
11926 // accept-set, which parses the *other* axis of this enum's
11927 // two-axis split and must not leak into the `from_wire`
11928 // PascalCase-wire accept-set — a lowercase leak here would
11929 // silently accept the operator's kebab-case
11930 // dispatcher-catalog probe under the wire-axis parser and mis-
11931 // route a `:permanent` intent), the padded canonical scalar
11932 // (`" Permanent "`), the trailing-newline shapes
11933 // (`"Permanent\n"`), the uppercase-single-word forms
11934 // (`"PERMANENT"`), and neighboring-but-unknown arms
11935 // (`"Restart"` — the canonical typo direction toward the
11936 // sibling [`RestartStrategy`] enum's own wire-arm namespace).
11937 //
11938 // Peer of the sibling
11939 // [`restart_strategy_from_wire_rejects_unknown_byte_strings`]
11940 // (4eec29c) +
11941 // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
11942 // (2aa6d23) +
11943 // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
11944 // (18c7342) refusal pins on the peer closed-set typed-enum
11945 // axes.
11946 for bad in [
11947 "",
11948 " ",
11949 "\n",
11950 "\t",
11951 "permanent",
11952 "temporary",
11953 "transient",
11954 "PERMANENT",
11955 "TEMPORARY",
11956 "TRANSIENT",
11957 "Permanents",
11958 "Permanent ",
11959 " Permanent",
11960 " Transient ",
11961 "Permanent\n",
11962 "perma",
11963 "Trans",
11964 "OneForOne",
11965 "Restart",
11966 "?",
11967 ] {
11968 assert!(
11969 RestartPolicy::from_wire(bad).is_none(),
11970 "RestartPolicy::from_wire({bad:?}) must return None — the \
11971 parser's accept-set is exactly the three RestartPolicy::as_str \
11972 outputs (Permanent, Temporary, Transient), and this \
11973 byte-string is outside that closed set"
11974 );
11975 }
11976 }
11977
11978 #[test]
11979 fn restart_policy_from_wire_matches_serialize_derive_wire_byte_string() {
11980 // Fail-before-pass-after pin on the fourth path of the four-path
11981 // convergence: `from_wire` (the reverse projection) inverts the
11982 // `Serialize` derive's wire byte-string on every variant.
11983 // Together with the pre-existing three-path convergence
11984 // (`Display` + `as_str` + `Serialize` all resolve to the same
11985 // lifted [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const,
11986 // pinned by
11987 // [`restart_policy_display_matches_serialized_wire_byte_string`])
11988 // this closes the round-trip: the wire byte-string the
11989 // `Serialize` derive emits parses back to the same variant
11990 // through `from_wire`, so any future serde-attribute or variant-
11991 // rename drift on the emit half now surfaces as a matched drift
11992 // on the parse half at caixa-core build time — the two halves
11993 // migrate as a unit through the lifted consts on any future
11994 // rename, and the round-trip cannot silently split.
11995 //
11996 // Peer of the sibling
11997 // [`restart_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
11998 // (4eec29c) wire-format pin on
11999 // [`RestartStrategy::from_wire`] and the M3
12000 // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
12001 // (18c7342) wire-format pin on
12002 // [`crate::aplicacao::PlacementStrategy::from_wire`].
12003 for &variant in RestartPolicy::ALL {
12004 let wire = serde_json::to_string(&variant).unwrap();
12005 let unquoted = wire
12006 .strip_prefix('"')
12007 .and_then(|s| s.strip_suffix('"'))
12008 .expect("serialized RestartPolicy is a JSON string");
12009 let parsed = RestartPolicy::from_wire(unquoted).unwrap_or_else(|| {
12010 panic!(
12011 "RestartPolicy::from_wire({unquoted:?}) must accept the \
12012 Serialize derive's wire byte-string for \
12013 RestartPolicy::{variant:?} — the four-path convergence \
12014 (Display + as_str + Serialize + from_wire) resolves through \
12015 the same lifted SUPERVISOR_CHILD_RESTART_* const; got None"
12016 )
12017 });
12018 assert_eq!(
12019 parsed, variant,
12020 "RestartPolicy::from_wire of the Serialize derive's wire \
12021 byte-string for RestartPolicy::{variant:?} must round-trip \
12022 to the same variant; got {parsed:?}"
12023 );
12024 }
12025 }
12026
12027 // ── drift-detection: ChildSpec::nome accessor pins ────────────────────
12028 //
12029 // The M2 supervisor-tree sibling of the M3 `Membro::nome` (4a32abf) pin
12030 // pair (`membro_nome_returns_caixa_byte_equal_across_permutations` +
12031 // `membro_nome_borrows_from_caixa_storage`) — extended here to the M2
12032 // per-`:children` child-caixa `:nome` axis, sibling to the first M2
12033 // slot scalar accessor `UpgradeFromEntry::prior_versao` (75d27a8) on
12034 // the peer per-`:upgrade-from :from` axis. The three pins jointly
12035 // brace the accessor against every future silent detour that would
12036 // desynchronize it from the raw `.caixa` field access every consumer
12037 // previously open-coded.
12038
12039 #[test]
12040 fn child_spec_nome_returns_caixa_byte_equal_across_permutations() {
12041 // The canonical per-`:children` child-caixa `:nome`-scalar pin:
12042 // [`ChildSpec::nome`] must return the `:children :caixa` field
12043 // byte-for-byte across every DNS-1123-label value the upstream
12044 // [`crate::render::require_valid_dns_1123_label`] gate at
12045 // `SupervisorSpec::validate` admits. Peer of the sibling
12046 // `membro_nome_returns_caixa_byte_equal_across_permutations`
12047 // (4a32abf) pin on the M3 per-`:membros` axis — same "the
12048 // substrate-primitive accessor must byte-equal the raw field
12049 // access verbatim across every author-declared value" discipline
12050 // extended to the M2 supervisor-tree per-`:children` arm. Pins
12051 // against a future silent detour that re-normalized the child
12052 // identity (an accidental `.to_lowercase()` — every `:children
12053 // :caixa` is validated as a DNS-1123 label upstream, so any
12054 // re-normalization is redundant + a drift surface between the
12055 // validator and the accessor), a namespace-prefix rewrite (an
12056 // accidental `format!("{namespace}/{caixa}")` per-CR
12057 // fully-qualified rewrite that didn't land on the peer axes), or
12058 // a per-cluster alias stamp the future wasm-operator's
12059 // hierarchical reconciliation scheduler authors on one consumer
12060 // without the others. Five values sweep the accept-set the
12061 // DNS-1123 gate upstream admits (short single-word / dashed /
12062 // v-suffixed / mixed-digit child names).
12063 for name in [
12064 "worker",
12065 "cache-server",
12066 "scratch-job",
12067 "orders-v2",
12068 "session-8080",
12069 ] {
12070 let c = ChildSpec {
12071 caixa: name.into(),
12072 versao: "^0.1".into(),
12073 restart: RestartPolicy::Permanent,
12074 };
12075 assert_eq!(
12076 c.nome(),
12077 name,
12078 "ChildSpec::nome must return :children :caixa verbatim \
12079 (got {:?}, expected {name:?})",
12080 c.nome(),
12081 );
12082 assert_eq!(
12083 c.nome(),
12084 c.caixa.as_str(),
12085 "ChildSpec::nome must byte-equal the .caixa field access",
12086 );
12087 }
12088 }
12089
12090 #[test]
12091 fn child_spec_nome_borrows_from_caixa_storage() {
12092 // The borrow-not-copy pin: [`ChildSpec::nome`] must return a
12093 // `&str` slice that borrows from the typed slot's own [`String`]
12094 // storage — same-address invariant with `c.caixa.as_str()`. Pins
12095 // against a future silent detour that allocated a fresh `String`
12096 // (`self.caixa.clone()` in the body would type-check but silently
12097 // drop the borrow, and every downstream consumer that assumed
12098 // the returned slice outlives `&self` would break on a stale-
12099 // reference use-after-free — the [`crate::render::insert_first_seen`]
12100 // dedup key at [`SupervisorSpec::validate`], the
12101 // [`validate_no_self_supervision`] equality check against the
12102 // parent's `:nome` string slice, the DNS-1123 gate's `&str`
12103 // borrow — each would silently misbehave if this accessor
12104 // produced a detached copy). Peer of the sibling
12105 // `membro_nome_borrows_from_caixa_storage` (4a32abf) pin on the
12106 // M3 per-`:membros` axis and the
12107 // `prior_versao_borrows_from_from_storage` (75d27a8) pin on the
12108 // first M2 slot scalar accessor.
12109 let c = ChildSpec {
12110 caixa: "worker".into(),
12111 versao: "^0.1".into(),
12112 restart: RestartPolicy::Permanent,
12113 };
12114 let name = c.nome();
12115 let caixa_slice = c.caixa.as_str();
12116 assert_eq!(
12117 name.as_ptr(),
12118 caixa_slice.as_ptr(),
12119 "ChildSpec::nome must borrow from the .caixa String's backing \
12120 storage — a fresh allocation here means the accessor no \
12121 longer names the substrate-primitive typed dispatch and \
12122 every downstream consumer would silently carry a detached \
12123 copy",
12124 );
12125 assert_eq!(
12126 name.len(),
12127 caixa_slice.len(),
12128 "ChildSpec::nome and .caixa.as_str() must byte-equal in length \
12129 as well as in address",
12130 );
12131 }
12132
12133 #[test]
12134 fn validate_gates_child_nome_through_lifted_accessor() {
12135 // Bilateral coherence pin: every `:children :caixa` that
12136 // [`SupervisorSpec::validate`] accepts is one
12137 // [`crate::render::require_valid_dns_1123_label`] accepts on the
12138 // accessor-projected value, and vice versa on the reject side.
12139 // This closes the "the validator reads through the accessor"
12140 // contract structurally — a future silent detour that made the
12141 // accessor return a different byte-string than the validator
12142 // gates against would surface here as a coverage mismatch, not
12143 // as an apply-time DNS-1123 rejection at
12144 // `metadata.name: Invalid value` far from the caixa.lisp source.
12145 // Peer of the M2 sibling
12146 // `validate_parses_prior_versao_through_lifted_accessor`
12147 // (75d27a8) on the per-`:upgrade-from :from` axis and the M3
12148 // `validate_membros` peer discipline.
12149 //
12150 // Accept-set sweep: five DNS-1123-label values the upstream gate
12151 // admits.
12152 for ok_name in ["a", "worker", "cache-server", "orders-v2", "svc-8080"] {
12153 let s = SupervisorSpec {
12154 children: vec![ChildSpec {
12155 caixa: ok_name.into(),
12156 versao: "^0.1".into(),
12157 restart: RestartPolicy::Permanent,
12158 }],
12159 ..SupervisorSpec::default()
12160 };
12161 s.validate().unwrap_or_else(|e| {
12162 panic!(
12163 "SupervisorSpec::validate must accept :children :caixa {ok_name:?} \
12164 (upstream DNS-1123 gate accepts it): got {e:?}",
12165 );
12166 });
12167 let c = ChildSpec {
12168 caixa: ok_name.into(),
12169 versao: "^0.1".into(),
12170 restart: RestartPolicy::Permanent,
12171 };
12172 crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| ())
12173 .unwrap_or_else(|()| {
12174 panic!(
12175 "require_valid_dns_1123_label must accept the accessor-projected \
12176 :children :caixa {ok_name:?}",
12177 );
12178 });
12179 }
12180 // Reject-set sweep: five DNS-1123-label-violating shapes the
12181 // upstream gate refuses (empty / uppercase / underscore / dot /
12182 // leading-hyphen). Every rejection at the validator must
12183 // correspond to a rejection when the accessor's projected value
12184 // is fed back through the shared gate.
12185 for bad_name in ["", "Worker", "my_worker", "team.worker", "-worker"] {
12186 let s = SupervisorSpec {
12187 children: vec![ChildSpec {
12188 caixa: bad_name.into(),
12189 versao: "^0.1".into(),
12190 restart: RestartPolicy::Permanent,
12191 }],
12192 ..SupervisorSpec::default()
12193 };
12194 let err = s.validate().unwrap_err();
12195 assert!(
12196 matches!(
12197 err,
12198 SupervisorError::EmptyChildName | SupervisorError::ChildCaixaInvalid { .. }
12199 ),
12200 "SupervisorSpec::validate must reject :children :caixa {bad_name:?} \
12201 via the DNS-1123 gate: got {err:?}",
12202 );
12203 let c = ChildSpec {
12204 caixa: bad_name.into(),
12205 versao: "^0.1".into(),
12206 restart: RestartPolicy::Permanent,
12207 };
12208 assert!(
12209 crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| (),)
12210 .is_err(),
12211 "require_valid_dns_1123_label must reject the accessor-projected \
12212 :children :caixa {bad_name:?}",
12213 );
12214 }
12215 }
12216
12217 // ── drift-detection: ChildSpec::versao_requirement accessor pins ──────
12218 //
12219 // Sibling of the peer per-`:membros` `membro_versao_requirement_*`
12220 // (a40b0e3) pin pair on the M3 mesh-slot surface — extended here to the
12221 // M2 supervisor-tree per-`:children` child-`:versao` axis, sibling to
12222 // the just-landed [`ChildSpec::nome`] (57c61d0) child-`:nome` pin
12223 // trio on the peer per-`:children` `String`-carry axis. The three pins
12224 // jointly brace the accessor against every future silent detour that
12225 // would desynchronize it from the raw `.versao` field access the
12226 // requirement gate + error carrier previously open-coded.
12227 //
12228 // Closes the last unlifted per-`:children` `String`-carry axis: the
12229 // pair (`nome`, `versao_requirement`) now jointly projects the
12230 // (`.caixa`, `.versao`) field pair every OTP-shape supervisor-tree
12231 // consumer that fans on per-child identity + version pin reads,
12232 // matching the peer M3 (`Membro::nome`, `Membro::versao_requirement`)
12233 // pair discipline verbatim.
12234 #[test]
12235 fn child_spec_versao_requirement_returns_versao_byte_equal_across_permutations() {
12236 // The canonical per-`:children` child-`:versao`-scalar pin:
12237 // [`ChildSpec::versao_requirement`] must return the `:children
12238 // :versao` field byte-for-byte across every Cargo-shaped semver
12239 // requirement value the upstream
12240 // [`crate::render::require_valid_versao_requirement`] gate admits.
12241 // Peer of the sibling
12242 // `membro_versao_requirement_returns_versao_byte_equal_across_permutations`
12243 // (a40b0e3) pin on the M3 per-`:membros` axis — same "the
12244 // substrate-primitive accessor must byte-equal the raw field
12245 // access verbatim across every author-declared value" discipline
12246 // extended to the M2 supervisor-tree per-`:children` arm. Pins
12247 // against a future silent detour that re-canonicalized the
12248 // requirement (an accidental `.to_string()` via
12249 // [`crate::version::parse_requirement`] → [`std::fmt::Display`]
12250 // round-trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and
12251 // silently drifted the error carrier's quoted requirement away
12252 // from the source `caixa.lisp`, an accidental whitespace trim on
12253 // `"^ 0.1"` that no consumer ever produced from the field-access
12254 // side, an accidental per-cluster lacre-projected concrete-version
12255 // rewrite that didn't land on the peer requirement-gate call).
12256 // Five values sweep the accept-set the shared
12257 // [`crate::render::require_valid_versao_requirement`] gate admits
12258 // (caret / tilde / exact / wildcard / bare-major).
12259 for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
12260 let c = ChildSpec {
12261 caixa: "worker".into(),
12262 versao: req.into(),
12263 restart: RestartPolicy::Permanent,
12264 };
12265 assert_eq!(
12266 c.versao_requirement(),
12267 req,
12268 "ChildSpec::versao_requirement must return :children :versao \
12269 verbatim (got {:?}, expected {req:?})",
12270 c.versao_requirement(),
12271 );
12272 assert_eq!(
12273 c.versao_requirement(),
12274 c.versao.as_str(),
12275 "ChildSpec::versao_requirement must byte-equal the .versao \
12276 field access",
12277 );
12278 }
12279 }
12280
12281 #[test]
12282 fn child_spec_versao_requirement_borrows_from_versao_storage() {
12283 // The borrow-not-copy pin: [`ChildSpec::versao_requirement`] must
12284 // return a `&str` slice that borrows from the typed slot's own
12285 // [`String`] storage — same-address invariant with
12286 // `c.versao.as_str()`. Pins against a future silent detour that
12287 // allocated a fresh `String` (`self.versao.clone()` in the body
12288 // would type-check but silently drop the borrow, and every
12289 // downstream consumer that assumed the returned slice outlives
12290 // `&self` — the [`crate::render::require_valid_versao_requirement`]
12291 // gate's `&str` borrow, the [`SupervisorError::ChildVersaoInvalid`]
12292 // `.to_string()` carrier's byte-length assumption — would silently
12293 // misbehave if this accessor produced a detached copy). Peer of
12294 // the sibling `child_spec_nome_borrows_from_caixa_storage`
12295 // (57c61d0) pin on the per-`:children` `:nome` axis and the M3
12296 // `membro_versao_requirement_borrows_from_versao_storage` (a40b0e3)
12297 // pin on the peer per-`:membros` `:versao` axis.
12298 let c = ChildSpec {
12299 caixa: "worker".into(),
12300 versao: "^0.1".into(),
12301 restart: RestartPolicy::Permanent,
12302 };
12303 let req = c.versao_requirement();
12304 let versao_slice = c.versao.as_str();
12305 assert_eq!(
12306 req.as_ptr(),
12307 versao_slice.as_ptr(),
12308 "ChildSpec::versao_requirement must borrow from the .versao \
12309 String's backing storage — a fresh allocation here means the \
12310 accessor no longer names the substrate-primitive typed \
12311 dispatch and every downstream consumer would silently carry \
12312 a detached copy",
12313 );
12314 assert_eq!(
12315 req.len(),
12316 versao_slice.len(),
12317 "ChildSpec::versao_requirement and .versao.as_str() must \
12318 byte-equal in length as well as in address",
12319 );
12320 }
12321
12322 #[test]
12323 fn validate_gates_child_versao_through_lifted_accessor() {
12324 // Bilateral coherence pin: every `:children :versao` that
12325 // [`SupervisorSpec::validate`] accepts is one
12326 // [`crate::render::require_valid_versao_requirement`] accepts on
12327 // the accessor-projected value, and vice versa on the reject side.
12328 // This closes the "the validator reads through the accessor"
12329 // contract structurally — a future silent detour that made the
12330 // accessor return a different byte-string than the validator gates
12331 // against would surface here as a coverage mismatch, not as a
12332 // resolver-time semver-parse rejection at lacre-closure time far
12333 // from the caixa.lisp source. Peer of the sibling
12334 // `validate_gates_child_nome_through_lifted_accessor` (57c61d0) on
12335 // the per-`:children :caixa` axis and the M2
12336 // `validate_parses_prior_versao_through_lifted_accessor` (75d27a8)
12337 // on the peer per-`:upgrade-from :from` axis.
12338 //
12339 // Accept-set sweep: five Cargo-shaped semver requirement values
12340 // the upstream gate admits (caret / tilde / exact / wildcard /
12341 // bare-major).
12342 for ok_req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
12343 let s = SupervisorSpec {
12344 children: vec![ChildSpec {
12345 caixa: "worker".into(),
12346 versao: ok_req.into(),
12347 restart: RestartPolicy::Permanent,
12348 }],
12349 ..SupervisorSpec::default()
12350 };
12351 s.validate().unwrap_or_else(|e| {
12352 panic!(
12353 "SupervisorSpec::validate must accept :children :versao {ok_req:?} \
12354 (upstream versao-requirement gate accepts it): got {e:?}",
12355 );
12356 });
12357 let c = ChildSpec {
12358 caixa: "worker".into(),
12359 versao: ok_req.into(),
12360 restart: RestartPolicy::Permanent,
12361 };
12362 crate::render::require_valid_versao_requirement(
12363 c.versao_requirement(),
12364 || (),
12365 |_reason| (),
12366 )
12367 .unwrap_or_else(|()| {
12368 panic!(
12369 "require_valid_versao_requirement must accept the accessor-projected \
12370 :children :versao {ok_req:?}",
12371 );
12372 });
12373 }
12374 // Reject-set sweep: five requirement-violating shapes the upstream
12375 // gate refuses. The empty string closes the empty-first arm of the
12376 // shared [`crate::render::require_valid_versao_requirement`]
12377 // cascade; the four non-empty arms exercise distinct semver-parse
12378 // failure modes the M3 peer per-`:membros` reject-set already pins
12379 // (`rejects_invalid_membro_versao_requirement` on `^bad-version`,
12380 // `rejects_membro_versao_with_double_caret_typo` on `^^0.1`,
12381 // `rejects_membro_versao_with_v_prefixed_tag` on `v0.1`) — the
12382 // shared parser routing means the same reject-set must fail
12383 // identically at the M2 supervisor-tree per-`:children` accessor
12384 // arm here. Every rejection at the validator must correspond to a
12385 // rejection when the accessor's projected value is fed back
12386 // through the shared gate.
12387 //
12388 // (Bare partial magnitudes like `"0.1"` and bare identifiers like
12389 // `"not-a-semver"` are intentionally *not* in the reject-set: the
12390 // semver crate accepts `"0.1"` as an implicit `^0.1` requirement,
12391 // and the identifier-tail arm's grammar admits some non-canonical
12392 // shapes — matching what the M3 peer test suite already documents
12393 // as the shared parser's accept-set edges.)
12394 for bad_req in ["", "v0.1.0", "^bad-version", "^^0.1", "v0.1"] {
12395 let s = SupervisorSpec {
12396 children: vec![ChildSpec {
12397 caixa: "worker".into(),
12398 versao: bad_req.into(),
12399 restart: RestartPolicy::Permanent,
12400 }],
12401 ..SupervisorSpec::default()
12402 };
12403 let err = s.validate().unwrap_err();
12404 assert!(
12405 matches!(
12406 err,
12407 SupervisorError::EmptyChildVersion { .. }
12408 | SupervisorError::ChildVersaoInvalid { .. }
12409 ),
12410 "SupervisorSpec::validate must reject :children :versao {bad_req:?} \
12411 via the versao-requirement gate: got {err:?}",
12412 );
12413 let c = ChildSpec {
12414 caixa: "worker".into(),
12415 versao: bad_req.into(),
12416 restart: RestartPolicy::Permanent,
12417 };
12418 assert!(
12419 crate::render::require_valid_versao_requirement(
12420 c.versao_requirement(),
12421 || (),
12422 |_reason| (),
12423 )
12424 .is_err(),
12425 "require_valid_versao_requirement must reject the accessor-projected \
12426 :children :versao {bad_req:?}",
12427 );
12428 }
12429 }
12430
12431 // ── per-`:children` `:restart` typed-accessor coherence pins ──────────
12432 //
12433 // The [`ChildSpec::restart`] accessor lift closes the last unlifted
12434 // per-`:children` axis (the pair `nome()` + `versao_requirement()`
12435 // already project the `String`-carry `(caixa, versao)` fields; the
12436 // `Copy`-composite-enum `restart` field is the third and final axis).
12437 // Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
12438 // (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
12439 // scalar accessor and the M3 mesh-slot [`crate::Placement::estrategia`]
12440 // (921fe1b) `Copy`-return [`crate::PlacementStrategy`] distribution-
12441 // strategy scalar accessor — same "one typed dispatch on the substrate
12442 // primitive, `Copy`-projected closed-set enum-arm discriminator" shape
12443 // extended onto the M2 supervisor-slot per-`:children` restart-decision
12444 // axis. The pin below covers the accessor's byte-equal projection
12445 // against the raw field access across every variant in the closed
12446 // accept-set (`Permanent`, `Transient`, `Temporary`).
12447
12448 #[test]
12449 fn child_spec_restart_returns_restart_verbatim_across_permutations() {
12450 // The canonical per-`:children` restart-decision-policy-scalar
12451 // pin: [`ChildSpec::restart`] must return the `:children :restart`
12452 // field verbatim as a [`RestartPolicy`], `Copy`-projected from the
12453 // typed slot's own [`RestartPolicy`] storage across every variant
12454 // in the closed accept-set (`Permanent`, `Transient`, `Temporary`).
12455 // Pins against a future silent detour that re-derived the policy
12456 // from a peer axis (an accidental fallback to
12457 // `if is_supervisor_child { Permanent } else { Temporary }` that
12458 // collapsed the child's kind axis into the restart discriminator),
12459 // a variant remap the operator authors on one consumer without the
12460 // other, or a stale-derive detour that substituted
12461 // [`RestartPolicy::default`] when the field held any explicit
12462 // variant (which would silently collapse the distinction between
12463 // "author explicitly declared `:restart Permanent`" and "author
12464 // omitted the slot and inherited the default" the future
12465 // per-cluster restart-decision override slot depends on).
12466 //
12467 // Peer of the sibling per-`:supervisor`
12468 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
12469 // (eafb619) pin on the M2 supervisor-slot sibling-restart-strategy
12470 // axis and the M3
12471 // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
12472 // (921fe1b) pin on the per-`:placement` distribution-strategy axis
12473 // — same "the substrate-primitive accessor must byte-equal the raw
12474 // field access verbatim across every author-declared value"
12475 // discipline extended onto the M2 supervisor-slot per-`:children`
12476 // restart-decision-policy axis, closing the last unlifted axis on
12477 // the per-`:children` [`ChildSpec`] type.
12478 for restart in [
12479 RestartPolicy::Permanent,
12480 RestartPolicy::Transient,
12481 RestartPolicy::Temporary,
12482 ] {
12483 let c = ChildSpec {
12484 caixa: "worker".into(),
12485 versao: "^0.1".into(),
12486 restart,
12487 };
12488 assert_eq!(
12489 c.restart(),
12490 restart,
12491 "ChildSpec::restart must return :children :restart \
12492 verbatim (got {:?}, expected {restart:?})",
12493 c.restart(),
12494 );
12495 assert_eq!(
12496 c.restart(),
12497 c.restart,
12498 "ChildSpec::restart accessor and .restart field access \
12499 must byte-equal — the accessor is the substrate-primitive \
12500 typed dispatch every downstream per-child restart-\
12501 decision consumer must route through",
12502 );
12503 }
12504 }
12505
12506 // ── per-`:supervisor` `:estrategia` typed-accessor coherence pins ─────
12507 //
12508 // The [`SupervisorSpec::estrategia`] accessor lift extends the peer M3
12509 // [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
12510 // distribution-strategy accessor discipline onto the M2 supervisor-slot
12511 // per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
12512 // scalar axis. The two pins below cover (1) the accessor's byte-equal
12513 // projection against the raw field access across every variant in the
12514 // closed accept-set, and (2) the two-consumer coherence between the
12515 // [`SupervisorSpec::validate`] partition-dispatch `match` arm and the
12516 // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
12517 // carrier's `estrategia:` field — peer of the sibling M3
12518 // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
12519 // / `validate_placement_reads_through_lifted_estrategia_accessor` pin
12520 // pair on the per-`:placement` distribution-strategy axis.
12521
12522 #[test]
12523 fn supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations() {
12524 // The canonical per-`:supervisor` sibling-restart-strategy-scalar
12525 // pin: [`SupervisorSpec::estrategia`] must return the
12526 // `:supervisor :estrategia` field verbatim as a
12527 // [`RestartStrategy`], `Copy`-projected from the typed slot's own
12528 // [`RestartStrategy`] storage across every variant in the closed
12529 // accept-set (`OneForOne`, `OneForAll`, `RestForOne`,
12530 // `SimpleOneForOne`). Pins against a future silent detour that
12531 // re-derived the strategy from a peer axis (an accidental
12532 // fallback to `if children.is_empty() { SimpleOneForOne } else {
12533 // OneForOne }` collapse that read the children-count axis into
12534 // the strategy discriminator), a variant remap the operator
12535 // authors on one consumer without the other, or a stale-derive
12536 // detour that substituted [`RestartStrategy::default`] when the
12537 // field held any explicit variant (which would silently collapse
12538 // the distinction between "author explicitly declared
12539 // `:estrategia OneForOne`" and "author omitted the slot and
12540 // inherited the default" the future per-cluster strategy override
12541 // slot depends on). Peer of the sibling M3
12542 // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
12543 // (921fe1b) pin on the M3 mesh-slot `Copy`-composite-enum scalar
12544 // axis — same "the substrate-primitive accessor must byte-equal
12545 // the raw field access verbatim across every author-declared
12546 // value" discipline extended onto the M2 supervisor-slot
12547 // per-`:supervisor` sibling-restart-strategy axis.
12548 for &estrategia in RestartStrategy::ALL {
12549 // `SimpleOneForOne` requires `children.is_empty()`; the peer
12550 // three strategies require a non-empty static children list.
12551 // Build each shape coherently so the pin's fixture would
12552 // itself pass [`SupervisorSpec::validate`] once fed through
12553 // the sibling coherence pin below — the byte-equal projection
12554 // asserted here is a strictly weaker property (a `Copy` field
12555 // read) that does not depend on `validate` running, but
12556 // keeping the fixture validate-clean means a future extension
12557 // of the pin to exercise `validate` end-to-end does not have
12558 // to re-author the children shape.
12559 //
12560 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
12561 // shape partition through the [`gen_platform::IsVariant`]
12562 // derive-generated
12563 // [`RestartStrategy::is_simple_one_for_one`] predicate rather
12564 // than the raw `matches!(estrategia, RestartStrategy::
12565 // SimpleOneForOne)` open-coded pattern-match — same closed-
12566 // set-typed-enum arm-discriminator dispatch discipline the
12567 // sibling [`crate::upgrade::UpgradeInstruction::is_restart`]
12568 // convergence (915a934) extended onto its two paired positive
12569 // / negated `matches!` sites and the peer
12570 // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
12571 // predicate convergence (766ec63) extended onto the M3 mesh-
12572 // slot per-`:placement` distribution-strategy discriminator
12573 // axis. See the sibling `round_trip_all_strategies` and the
12574 // peer `manifest::tests::
12575 // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
12576 // fixture for the two peer sites the same lift closes on.
12577 let children = if estrategia.is_simple_one_for_one() {
12578 Vec::new()
12579 } else {
12580 vec![ChildSpec {
12581 caixa: "worker".into(),
12582 versao: "^0.1".into(),
12583 restart: RestartPolicy::Permanent,
12584 }]
12585 };
12586 let s = SupervisorSpec {
12587 estrategia,
12588 children,
12589 ..SupervisorSpec::default()
12590 };
12591 assert_eq!(
12592 s.estrategia(),
12593 estrategia,
12594 "SupervisorSpec::estrategia must return :supervisor :estrategia \
12595 verbatim (got {:?}, expected {estrategia:?})",
12596 s.estrategia(),
12597 );
12598 assert_eq!(
12599 s.estrategia(),
12600 s.estrategia,
12601 "SupervisorSpec::estrategia accessor and .estrategia field \
12602 access must byte-equal — the accessor is the substrate-\
12603 primitive typed dispatch every downstream sibling-restart-\
12604 strategy consumer must route through",
12605 );
12606 }
12607 }
12608
12609 #[test]
12610 fn validate_reads_through_lifted_estrategia_accessor() {
12611 // Two-consumer coherence pin: the [`SupervisorSpec::validate`]
12612 // `SimpleOneForOne ↔ non-SimpleOneForOne` `match` partition
12613 // dispatch (which reads through [`SupervisorSpec::estrategia`]
12614 // to fan across the strategy-arm shape-gate cascades) and the
12615 // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
12616 // error carrier's `estrategia:` field (which reads through
12617 // [`SupervisorSpec::estrategia`] to name the strategy the empty
12618 // `:children` list was declared against) must both key off the
12619 // lifted accessor, so any future rebrand on the typed slot's
12620 // reader shape lands at exactly one place. Pins the two-site
12621 // coherence by exercising the `NoChildren` error surface end-to-
12622 // end across every non-`SimpleOneForOne` variant and asserting
12623 // the surfaced `estrategia:` field byte-equals the accessor's
12624 // return. Peer of the sibling M3
12625 // `validate_placement_reads_through_lifted_estrategia_accessor`
12626 // (921fe1b) three-consumer coherence pin on the per-`:placement`
12627 // distribution-strategy axis.
12628 for estrategia in [
12629 RestartStrategy::OneForOne,
12630 RestartStrategy::OneForAll,
12631 RestartStrategy::RestForOne,
12632 ] {
12633 let s = SupervisorSpec {
12634 estrategia,
12635 children: Vec::new(),
12636 ..SupervisorSpec::default()
12637 };
12638 let err = s.validate().unwrap_err();
12639 match err {
12640 SupervisorError::NoChildren { estrategia: e } => {
12641 assert_eq!(
12642 e,
12643 s.estrategia(),
12644 "NoChildren.estrategia must byte-equal \
12645 SupervisorSpec::estrategia() — the empty-`:children` \
12646 refusal reads through the lifted accessor",
12647 );
12648 assert_eq!(
12649 e, estrategia,
12650 "NoChildren.estrategia must carry the author-declared \
12651 :supervisor :estrategia variant verbatim (got {e:?}, \
12652 expected {estrategia:?})",
12653 );
12654 }
12655 other => panic!("expected NoChildren, got {other:?} for estrategia={estrategia:?}"),
12656 }
12657 }
12658 }
12659
12660 // ── per-`:supervisor` `:max-restarts` typed-accessor coherence pins ────
12661 //
12662 // The [`SupervisorSpec::max_restarts`] accessor lift extends the peer M3
12663 // [`crate::CircuitBreaker::max_failures`] (3a74062) `Copy`-return
12664 // required-`u32` scalar accessor discipline onto the M2 supervisor-slot
12665 // per-`:supervisor` restart-budget-count `Copy`-`u32` scalar axis.
12666 // The two pins below cover (1) the accessor's byte-equal projection
12667 // against the raw field access across every representative value in
12668 // the `u32` accept-set (`1` lower boundary, `SUPERVISOR_MAX_RESTARTS_MAX`
12669 // upper boundary, `0` past-the-guard zero sentinel, `u32::MAX`
12670 // past-the-guard cap sentinel), and (2) the [`SupervisorSpec::validate`]
12671 // zero-floor / cap composition — the validate gate and the accessor
12672 // must route through the same substrate-primitive typed dispatch, so
12673 // any future silent detour that had the accessor perform a
12674 // bounds-collapsing clamp would fail here at caixa-core build time.
12675 // Peer of the sibling M3
12676 // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
12677 // (3a74062) pin on the per-`CircuitBreaker :max-failures` axis.
12678
12679 #[test]
12680 fn supervisor_spec_max_restarts_returns_max_restarts_u32_byte_equal_across_permutations() {
12681 // The canonical per-`:supervisor` restart-budget-count scalar pin:
12682 // [`SupervisorSpec::max_restarts`] must return the `:supervisor
12683 // :max-restarts` typed `u32` verbatim, `Copy`-projected from the
12684 // typed slot's own `u32` storage, byte-equal to the raw field
12685 // access across every representative value in the accept-set —
12686 // `1` (the lower boundary of the `1..=SUPERVISOR_MAX_RESTARTS_MAX`
12687 // accept-set the surrounding [`SupervisorSpec::validate`] gate
12688 // carves out on the sibling `ZeroMaxRestarts` refusal),
12689 // `SUPERVISOR_MAX_RESTARTS_MAX` (the upper boundary the same gate
12690 // carves out on the sibling `MaxRestartsExceedsCap` refusal), `0`
12691 // (a past-the-guard sentinel that pins the accessor doesn't
12692 // perform a silent bounds-collapse into `1` on the zero arm —
12693 // validate rejects zero but the accessor must ship the raw slot
12694 // verbatim so a validate-time gate regression surfaces at the
12695 // emit boundary rather than being silently absorbed), `u32::MAX`
12696 // (a past-the-guard sentinel that pins the accessor doesn't
12697 // perform a silent bounds-collapse through
12698 // `SUPERVISOR_MAX_RESTARTS_MAX` at the return path).
12699 //
12700 // Peer of the sibling M3
12701 // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
12702 // (3a74062) pin on the M3 mesh-slot `Copy`-`u32` sub-struct
12703 // required-scalar axis — same "the substrate-primitive accessor
12704 // must byte-equal the raw field access verbatim across every
12705 // value in the `u32` accept-set" discipline extended onto the M2
12706 // supervisor-slot per-`:supervisor` restart-budget-count axis.
12707 for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX, 0, u32::MAX] {
12708 let s = SupervisorSpec {
12709 max_restarts,
12710 ..SupervisorSpec::default()
12711 };
12712 assert_eq!(
12713 s.max_restarts(),
12714 max_restarts,
12715 "SupervisorSpec::max_restarts must return :supervisor \
12716 :max-restarts verbatim (got {}, expected {max_restarts})",
12717 s.max_restarts(),
12718 );
12719 assert_eq!(
12720 s.max_restarts(),
12721 s.max_restarts,
12722 "SupervisorSpec::max_restarts accessor and .max_restarts \
12723 field access must byte-equal — the accessor is the \
12724 substrate-primitive typed dispatch every downstream \
12725 restart-budget-count consumer must route through",
12726 );
12727 }
12728 }
12729
12730 #[test]
12731 fn validate_max_restarts_zero_floor_and_cap_arms_route_through_accessor() {
12732 // Composition pin: [`SupervisorSpec::validate`]'s `:max-restarts`
12733 // zero-floor + upper-cap bracket must key off
12734 // [`SupervisorSpec::max_restarts`], not the raw `.max_restarts`
12735 // field access. Structurally: a `SupervisorSpec { max_restarts:
12736 // 0, .. }` must surface the `ZeroMaxRestarts` refusal exactly, a
12737 // `SupervisorSpec { max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
12738 // .. }` must surface the `MaxRestartsExceedsCap` refusal exactly
12739 // (with the offending count carried verbatim from the accessor
12740 // return), and a `SupervisorSpec { max_restarts: 1, .. }` (the
12741 // lower boundary of the accept-set) plus a `SupervisorSpec {
12742 // max_restarts: SUPERVISOR_MAX_RESTARTS_MAX, .. }` (the upper
12743 // boundary) must pass validate. The four together jointly pin the
12744 // accessor + validate-gate composition: any future silent detour
12745 // that had the accessor return a fresh `1` on the zero arm (a
12746 // `.max_restarts().max(1)` collapse) would silently absorb the
12747 // `ZeroMaxRestarts` refusal at the accessor boundary and the
12748 // validate gate would accept a struct-literal `SupervisorSpec {
12749 // max_restarts: 0, .. }` — the composition pin catches that at
12750 // caixa-core build time.
12751 //
12752 // Peer of the sibling M3
12753 // `validate_politicas_max_failures_zero_floor_arm_routes_through_accessor`
12754 // (3a74062) pin on the sibling per-`CircuitBreaker :max-failures`
12755 // composition axis — same "the validate / shape-gate predicate
12756 // must route through the substrate-primitive typed dispatch"
12757 // discipline extended onto the peer M2 supervisor-slot
12758 // required-`u32` composition axis.
12759 let child = ChildSpec {
12760 caixa: "worker".into(),
12761 versao: "^0.1".into(),
12762 restart: RestartPolicy::Permanent,
12763 };
12764 // Zero-floor arm.
12765 let s = SupervisorSpec {
12766 max_restarts: 0,
12767 children: vec![child.clone()],
12768 ..SupervisorSpec::default()
12769 };
12770 assert_eq!(
12771 s.validate().unwrap_err(),
12772 SupervisorError::ZeroMaxRestarts,
12773 "validate must reject max_restarts == 0 with ZeroMaxRestarts \
12774 — the accessor and the validate gate must route through the \
12775 same substrate-primitive typed dispatch on the zero-floor arm",
12776 );
12777 // Cap arm — the surfaced `max_restarts:` field must byte-equal
12778 // the accessor's return so a future rebrand on the accessor
12779 // lands in the diagnostic without a coordinated rewrite.
12780 let over_cap = SUPERVISOR_MAX_RESTARTS_MAX + 1;
12781 let s = SupervisorSpec {
12782 max_restarts: over_cap,
12783 children: vec![child.clone()],
12784 ..SupervisorSpec::default()
12785 };
12786 match s.validate().unwrap_err() {
12787 SupervisorError::MaxRestartsExceedsCap { max_restarts } => {
12788 assert_eq!(
12789 max_restarts,
12790 s.max_restarts(),
12791 "MaxRestartsExceedsCap.max_restarts must byte-equal \
12792 SupervisorSpec::max_restarts() — the cap-arm refusal \
12793 reads through the lifted accessor",
12794 );
12795 assert_eq!(
12796 max_restarts, over_cap,
12797 "MaxRestartsExceedsCap.max_restarts must carry the \
12798 author-declared :supervisor :max-restarts value \
12799 verbatim (got {max_restarts}, expected {over_cap})",
12800 );
12801 }
12802 other => panic!("expected MaxRestartsExceedsCap, got {other:?}"),
12803 }
12804 // Lower + upper accept-set boundaries.
12805 for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX] {
12806 let s = SupervisorSpec {
12807 max_restarts,
12808 children: vec![child.clone()],
12809 ..SupervisorSpec::default()
12810 };
12811 assert!(
12812 s.validate().is_ok(),
12813 "validate must accept max_restarts == {max_restarts} \
12814 (an accept-set boundary of \
12815 1..=SUPERVISOR_MAX_RESTARTS_MAX)",
12816 );
12817 }
12818 }
12819
12820 // ── per-`:supervisor` `:restart-window` typed-accessor coherence pins ─
12821 //
12822 // The [`SupervisorSpec::restart_window`] accessor lift extends the peer
12823 // M2 [`crate::LimitsSpec::wall_clock`] (8cb717b) `Option<Duration>`
12824 // accessor discipline and the peer M3 [`crate::MeshPolicy::timeout`]
12825 // (7073d0f) `Option<Duration>` accessor discipline onto the M2
12826 // supervisor-slot per-`:supervisor` restart-intensity-denominator
12827 // `Option<Duration>` scalar axis — third `Copy`-return accessor on the
12828 // M2 supervisor-slot `SupervisorSpec` type, closing the last unlifted
12829 // per-`:supervisor` scalar-value axis. The three pins below cover
12830 // (1) the accessor's byte-equal projection against the raw field
12831 // access across every representative value in the `Option<Duration>`
12832 // accept-set (`None` never-reset sentinel, `Some(Duration::from_millis(1))`
12833 // lower boundary, `Some(SUPERVISOR_RESTART_WINDOW_MAX)` upper boundary,
12834 // `Some(Duration::ZERO)` past-the-guard zero sentinel, `Some(Duration::MAX)`
12835 // past-the-guard above-cap sentinel), (2) the [`SupervisorSpec::validate`]
12836 // `if let Some(w) = self.restart_window() { … }` bracket-arm
12837 // composition — the validate gate and the accessor must route through
12838 // the same substrate-primitive typed dispatch, so any future silent
12839 // detour that had the accessor perform a bounds-collapsing clamp
12840 // would fail here at caixa-core build time, and (3) the accessor's
12841 // by-copy idempotence pin — the returned `Option<Duration>` must
12842 // outlive `&self` and two successive calls must return byte-equal
12843 // values. Peer of the sibling M2
12844 // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
12845 // (8cb717b) pin on the per-`:limits :wall-clock` axis and the sibling
12846 // M3 `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
12847 // (7073d0f) pin on the per-`:politicas :timeout` axis.
12848
12849 #[test]
12850 fn supervisor_spec_restart_window_returns_option_duration_byte_equal_across_permutations() {
12851 // The canonical per-`:supervisor` restart-intensity-denominator
12852 // scalar pin: [`SupervisorSpec::restart_window`] must return the
12853 // `:supervisor :restart-window` typed [`Duration`] verbatim as an
12854 // `Option<Duration>`, `Copy`-projected from the typed slot's own
12855 // `Option<Duration>` storage, byte-equal to the raw field access
12856 // across every representative value in the accept-set — `None`
12857 // (the "never reset — every restart across the supervisor's
12858 // lifetime counts against the sibling `:max-restarts` budget"
12859 // sentinel the field's own docstring names and the peer
12860 // `validate_accepts_none_restart_window` pin locks in on the
12861 // [`SupervisorSpec::validate`] entry-side),
12862 // `Some(Duration::from_millis(1))` (the structural minimum a
12863 // validated `:restart-window` may carry, the integer-millisecond
12864 // floor [`SupervisorError::RestartWindowNotCanonical`] rejects
12865 // everything sub-ms; `Duration::ZERO` is separately rejected by
12866 // [`SupervisorError::RestartWindowZero`]),
12867 // `Some(SUPERVISOR_RESTART_WINDOW_MAX)` (the upper boundary the
12868 // surrounding [`SupervisorSpec::validate`] gate carves out on the
12869 // sibling [`SupervisorError::RestartWindowExceedsCap`] refusal),
12870 // `Some(Duration::ZERO)` (a past-the-guard sentinel that pins the
12871 // accessor doesn't perform a silent bounds-collapse into `None` on
12872 // the zero-Duration arm — validate rejects zero but the accessor
12873 // must ship the raw slot verbatim so a validate-time gate
12874 // regression surfaces at the emit boundary rather than being
12875 // silently absorbed), and `Some(Duration::MAX)` (a past-the-guard
12876 // sentinel that pins the accessor doesn't perform a silent
12877 // bounds-collapse through [`SUPERVISOR_RESTART_WINDOW_MAX`] at the
12878 // return path).
12879 //
12880 // Peer of the sibling M2
12881 // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
12882 // (8cb717b) pin on the per-`:limits :wall-clock` axis and the
12883 // sibling M3
12884 // `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
12885 // (7073d0f) pin on the per-`:politicas :timeout` axis — same "the
12886 // substrate-primitive accessor must byte-equal the raw field
12887 // access verbatim across every value in the `Option<Duration>`
12888 // accept-set" discipline extended onto the M2 supervisor-slot
12889 // per-`:supervisor` `Option<Duration>` axis. Pins against a future
12890 // silent detour that re-derived the restart-window from a peer
12891 // axis (an accidental `.max_restarts.into()` collapse that read
12892 // the restart-budget-count as a duration — the two axes serve
12893 // different halves of the `MaxIntensity / Period` restart-
12894 // intensity ratio, and confusing them silently inverts the
12895 // ratio's numerator and denominator), a `None → Some(Duration::ZERO)`
12896 // "zero means never reset" collapse (the canonical
12897 // `Option<Duration>` → `Duration` collapse footgun the
12898 // [`SupervisorError::RestartWindowZero`] validate arm guards on
12899 // the peer zero-floor axis; a zero period either trips on the
12900 // first failure or never trips depending on operator
12901 // interpretation, neither of which is the author's "never reset"
12902 // intent that `None` expresses structurally), or a per-arm
12903 // variant swap that landed on one consumer without the other.
12904 for restart_window in [
12905 None,
12906 Some(Duration::from_millis(1)),
12907 Some(SUPERVISOR_RESTART_WINDOW_MAX),
12908 Some(Duration::ZERO),
12909 Some(Duration::MAX),
12910 ] {
12911 let s = SupervisorSpec {
12912 restart_window,
12913 ..SupervisorSpec::default()
12914 };
12915 assert_eq!(
12916 s.restart_window(),
12917 restart_window,
12918 "SupervisorSpec::restart_window must return :supervisor \
12919 :restart-window verbatim (got {:?}, expected {restart_window:?})",
12920 s.restart_window(),
12921 );
12922 assert_eq!(
12923 s.restart_window(),
12924 s.restart_window,
12925 "SupervisorSpec::restart_window accessor and \
12926 .restart_window field access must byte-equal — the \
12927 accessor is the substrate-primitive typed dispatch every \
12928 downstream restart-intensity-denominator consumer must \
12929 route through",
12930 );
12931 }
12932 }
12933
12934 #[test]
12935 fn validate_restart_window_bracket_arm_routes_through_accessor() {
12936 // Composition pin: [`SupervisorSpec::validate`]'s
12937 // `:restart-window` `if let Some(w) = self.restart_window() { … }`
12938 // zero-floor + integer-millisecond canonical-form + upper-cap
12939 // bracket-arm must key off [`SupervisorSpec::restart_window`], not
12940 // the raw `.restart_window` field access. Structurally: a
12941 // `SupervisorSpec { restart_window: None, .. }` must pass the
12942 // arm gate structurally (the `if let Some(_)` shape returns
12943 // early on the `None` arm — the accessor and the validate gate
12944 // must agree on `None → skip the bracket cascade` so an authored
12945 // `:restart-window ()` structurally routes through the "never
12946 // reset" sentinel path), a `SupervisorSpec { restart_window:
12947 // Some(Duration::ZERO), .. }` must surface the `RestartWindowZero`
12948 // refusal exactly, a `SupervisorSpec { restart_window:
12949 // Some(Duration::from_micros(1500)), .. }` must surface the
12950 // `RestartWindowNotCanonical` refusal exactly (with the offending
12951 // duration carried verbatim from the accessor return), a
12952 // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX
12953 // + Duration::from_millis(1)), .. }` must surface the
12954 // `RestartWindowExceedsCap` refusal exactly (with the offending
12955 // duration carried verbatim from the accessor return), and a
12956 // `SupervisorSpec { restart_window: Some(Duration::from_millis(1)),
12957 // .. }` (the lower boundary of the accept-set) plus a
12958 // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
12959 // .. }` (the upper boundary) must pass validate. The six together
12960 // jointly pin the accessor + validate-gate composition: any future
12961 // silent detour that had the accessor return a fresh `None` on any
12962 // `Some` arm (a `.restart_window().filter(|w| !w.is_zero())`
12963 // collapse) would silently absorb the `RestartWindowZero` refusal
12964 // at the accessor boundary and the validate gate would accept a
12965 // struct-literal `SupervisorSpec { restart_window:
12966 // Some(Duration::ZERO), .. }` — the composition pin catches that
12967 // at caixa-core build time.
12968 //
12969 // Peer of the sibling M2 [`crate::LimitsSpec::wall_clock`]
12970 // (8cb717b) validate-arm-route pin on the per-`:limits :wall-clock`
12971 // axis and the peer M3 [`crate::MeshPolicy::timeout`] (7073d0f)
12972 // accessor-composition pin on the per-`:politicas :timeout` axis —
12973 // same "the validate / shape-gate predicate must route through
12974 // the substrate-primitive typed dispatch" discipline extended
12975 // onto the peer M2 supervisor-slot optional-`Duration` axis.
12976 let child = ChildSpec {
12977 caixa: "worker".into(),
12978 versao: "^0.1".into(),
12979 restart: RestartPolicy::Permanent,
12980 };
12981 // None arm — must not surface any :restart-window-shaped refusal;
12982 // the `if let Some(_)` bracket returns early on `None` structurally.
12983 let s = SupervisorSpec {
12984 restart_window: None,
12985 children: vec![child.clone()],
12986 ..SupervisorSpec::default()
12987 };
12988 assert!(
12989 s.validate().is_ok(),
12990 "validate must accept restart_window: None (the never-reset \
12991 sentinel) — the `if let Some(_)` bracket returns early on \
12992 the None arm and the accessor must agree",
12993 );
12994 // Zero-floor arm.
12995 let s = SupervisorSpec {
12996 restart_window: Some(Duration::ZERO),
12997 children: vec![child.clone()],
12998 ..SupervisorSpec::default()
12999 };
13000 assert_eq!(
13001 s.validate().unwrap_err(),
13002 SupervisorError::RestartWindowZero,
13003 "validate must reject restart_window == Some(Duration::ZERO) \
13004 with RestartWindowZero — the accessor and the validate gate \
13005 must route through the same substrate-primitive typed \
13006 dispatch on the zero-floor arm",
13007 );
13008 // Non-canonical (sub-ms) arm — the surfaced `window:` field must
13009 // byte-equal the accessor's return so a future rebrand on the
13010 // accessor lands in the diagnostic without a coordinated rewrite.
13011 let sub_ms = Duration::from_micros(1500);
13012 let s = SupervisorSpec {
13013 restart_window: Some(sub_ms),
13014 children: vec![child.clone()],
13015 ..SupervisorSpec::default()
13016 };
13017 match s.validate().unwrap_err() {
13018 SupervisorError::RestartWindowNotCanonical { window } => {
13019 assert_eq!(
13020 Some(window),
13021 s.restart_window(),
13022 "RestartWindowNotCanonical.window must byte-equal \
13023 SupervisorSpec::restart_window().unwrap() — the \
13024 non-canonical-arm refusal reads through the lifted \
13025 accessor",
13026 );
13027 assert_eq!(
13028 window, sub_ms,
13029 "RestartWindowNotCanonical.window must carry the \
13030 author-declared :supervisor :restart-window value \
13031 verbatim (got {window:?}, expected {sub_ms:?})",
13032 );
13033 }
13034 other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
13035 }
13036 // Cap arm — the surfaced `window:` field must byte-equal the
13037 // accessor's return.
13038 let over_cap = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
13039 let s = SupervisorSpec {
13040 restart_window: Some(over_cap),
13041 children: vec![child.clone()],
13042 ..SupervisorSpec::default()
13043 };
13044 match s.validate().unwrap_err() {
13045 SupervisorError::RestartWindowExceedsCap { window } => {
13046 assert_eq!(
13047 Some(window),
13048 s.restart_window(),
13049 "RestartWindowExceedsCap.window must byte-equal \
13050 SupervisorSpec::restart_window().unwrap() — the \
13051 cap-arm refusal reads through the lifted accessor",
13052 );
13053 assert_eq!(
13054 window, over_cap,
13055 "RestartWindowExceedsCap.window must carry the \
13056 author-declared :supervisor :restart-window value \
13057 verbatim (got {window:?}, expected {over_cap:?})",
13058 );
13059 }
13060 other => panic!("expected RestartWindowExceedsCap, got {other:?}"),
13061 }
13062 // Lower + upper accept-set boundaries.
13063 for restart_window in [Duration::from_millis(1), SUPERVISOR_RESTART_WINDOW_MAX] {
13064 let s = SupervisorSpec {
13065 restart_window: Some(restart_window),
13066 children: vec![child.clone()],
13067 ..SupervisorSpec::default()
13068 };
13069 assert!(
13070 s.validate().is_ok(),
13071 "validate must accept restart_window == Some({restart_window:?}) \
13072 (an accept-set boundary of \
13073 1ms..=SUPERVISOR_RESTART_WINDOW_MAX)",
13074 );
13075 }
13076 }
13077
13078 #[test]
13079 fn supervisor_spec_restart_window_projects_option_duration_by_copy() {
13080 // The by-copy pin: [`SupervisorSpec::restart_window`] returns
13081 // `Option<Duration>` by copy — `Duration` is `Copy` (so
13082 // `Option<Duration>` is `Copy`) and the accessor must return by
13083 // value, not by reference. Peer of the sibling M2
13084 // [`crate::LimitsSpec::wall_clock`] (8cb717b) by-copy pin on the
13085 // per-`:limits :wall-clock` axis and the sibling M3
13086 // [`crate::MeshPolicy::timeout`] (7073d0f) by-copy pin on the
13087 // per-`:politicas :timeout` axis, extended onto the peer M2
13088 // supervisor-slot `Option<Duration>` copy-invariant shape — the
13089 // accessor's returned `Option<Duration>` must outlive `&self`
13090 // (multiple calls must return equal values from a dropped-`&self`
13091 // copy, since the returned Option carries no borrow), and calling
13092 // the accessor twice on the same SupervisorSpec must yield the
13093 // same `Option<Duration>` verbatim (idempotent, no side effects
13094 // on `&self`).
13095 //
13096 // Pins against a future silent detour that returned
13097 // `Option<&Duration>` (which would type-check but silently break
13098 // every downstream caller — the future wasm-operator's
13099 // per-supervisor restart-intensity counter consumes `Duration` by
13100 // value and `&Duration` would fold to a detached copy at the call
13101 // site), an accidental `Option::as_ref()` projection
13102 // (`self.restart_window.as_ref()` would also type-check but
13103 // return `Option<&Duration>`), or a one-arm-only accessor that
13104 // reads `Some(*w)` in the Some arm but reads a fresh
13105 // `Default::default()` (which would collapse to `Duration::ZERO`,
13106 // not `None`) in the None arm — a footgun the
13107 // [`SupervisorError::RestartWindowZero`] validate arm explicitly
13108 // closes since Erlang/OTP's `MaxIntensity / Period` invariant
13109 // requires `Period > 0` and `None` structurally expresses "never
13110 // reset" instead.
13111 for restart_window in [
13112 None,
13113 Some(Duration::from_millis(1)),
13114 Some(Duration::from_secs(60)),
13115 Some(SUPERVISOR_RESTART_WINDOW_MAX),
13116 ] {
13117 let s = SupervisorSpec {
13118 restart_window,
13119 ..SupervisorSpec::default()
13120 };
13121 let first = s.restart_window();
13122 let second = s.restart_window();
13123 assert_eq!(
13124 first, second,
13125 "SupervisorSpec::restart_window must be idempotent — two \
13126 successive calls on the same &self must return the \
13127 same Option<Duration>",
13128 );
13129 assert_eq!(
13130 first, restart_window,
13131 "SupervisorSpec::restart_window must return :supervisor \
13132 :restart-window verbatim by copy — got {first:?}, \
13133 expected {restart_window:?}",
13134 );
13135 }
13136 }
13137
13138 // ── per-`:supervisor` `:children` typed-accessor coherence pins ─────────
13139 //
13140 // The [`SupervisorSpec::children`] accessor lift is the seed of the
13141 // slice-return (`&[T]`) accessor discipline on the substrate — the four
13142 // peer `Vec`-carry axes ([`crate::Placement::clusters`],
13143 // [`crate::AplicacaoSpec::membros`], [`crate::AplicacaoSpec::contratos`],
13144 // [`crate::UpgradeFromEntry::instructions`]) still key off the raw field
13145 // access at the time of this seed, and inherit this pin family's
13146 // discipline as future compounding runs migrate their consumers. The
13147 // three pins below cover (1) the accessor's byte-equal projection
13148 // against the raw field access across the empty / singleton / cohort
13149 // fixtures the [`SupervisorSpec::validate`] partition-dispatch fans
13150 // between, (2) the [`SupervisorSpec::validate`] `SimpleOneForOne ↔
13151 // non-SimpleOneForOne` partition dispatch's paired `.is_empty()`
13152 // consumer routing through the accessor on both arms, and (3) the
13153 // per-child validate loop's traversal reading the same slice-view the
13154 // accessor projects. Peer of the sibling M2
13155 // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
13156 // two-consumer coherence pin on the per-`:supervisor`
13157 // sibling-restart-strategy `Copy`-composite-enum scalar axis, extended
13158 // onto the per-`:supervisor` static-child-list `Vec`-carry axis.
13159
13160 #[test]
13161 fn supervisor_spec_children_returns_children_slice_byte_equal_across_permutations() {
13162 // The canonical per-`:supervisor` static-child-list scalar-shape
13163 // pin: [`SupervisorSpec::children`] must return the `:supervisor
13164 // :children` typed `Vec<ChildSpec>` verbatim as a `&[ChildSpec]`
13165 // slice-view over the same backing buffer the raw
13166 // `self.children.as_slice()` field access borrows from, byte-
13167 // equal across every representative fixture in the accept-set —
13168 // the empty slice (the `SimpleOneForOne`-arm sentinel),
13169 // the singleton slice (the minimal non-`SimpleOneForOne` shape),
13170 // and a two-child cohort (a peer non-`SimpleOneForOne` shape
13171 // with the peer three restart-policy variants in play).
13172 //
13173 // Pins against a future silent detour that returned
13174 // `&Vec<ChildSpec>` (which would type-check but leak the
13175 // storage-side `Vec`'s grow/push/reserve surface no consumer of
13176 // the typed view reaches for), a fresh-allocated
13177 // `Vec<ChildSpec>` copy (which would type-check via a coercion
13178 // but silently break every downstream caller that relied on the
13179 // slice sharing the backing buffer's identity), or an
13180 // out-of-order or length-drifted projection (which would silently
13181 // split the per-child validate loop's traversal input from the
13182 // paired partition-dispatch `.is_empty()` probe's input).
13183 //
13184 // Peer of the sibling
13185 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
13186 // (eafb619) `Copy`-composite-enum byte-equal pin on the
13187 // per-`:supervisor` sibling-restart-strategy axis, extended onto
13188 // the per-`:supervisor` static-child-list `Vec`-carry axis.
13189 let fixtures: Vec<Vec<ChildSpec>> = vec![
13190 Vec::new(),
13191 vec![child("worker", "^0.1", RestartPolicy::Permanent)],
13192 vec![
13193 child("worker", "^0.1", RestartPolicy::Permanent),
13194 child("cache-server", "^0.1", RestartPolicy::Transient),
13195 ],
13196 vec![
13197 child("worker", "^0.1", RestartPolicy::Permanent),
13198 child("cache-server", "^0.1", RestartPolicy::Transient),
13199 child("scratch-job", "^0.1", RestartPolicy::Temporary),
13200 ],
13201 ];
13202 for children in fixtures {
13203 let s = SupervisorSpec {
13204 children: children.clone(),
13205 ..SupervisorSpec::default()
13206 };
13207 assert_eq!(
13208 s.children(),
13209 children.as_slice(),
13210 "SupervisorSpec::children must return :supervisor \
13211 :children verbatim (got {:?}, expected {:?})",
13212 s.children(),
13213 children.as_slice(),
13214 );
13215 assert_eq!(
13216 s.children(),
13217 s.children.as_slice(),
13218 "SupervisorSpec::children accessor and \
13219 .children.as_slice() field access must byte-equal — \
13220 the accessor is the substrate-primitive typed \
13221 dispatch every downstream static-child-list consumer \
13222 must route through",
13223 );
13224 assert_eq!(
13225 s.children().len(),
13226 s.children.len(),
13227 "SupervisorSpec::children().len() must byte-equal \
13228 self.children.len() — a length-drift would silently \
13229 split the paired partition-dispatch `.is_empty()` \
13230 probe input from the per-child validate loop's \
13231 traversal input",
13232 );
13233 }
13234 }
13235
13236 #[test]
13237 fn validate_reads_through_lifted_children_accessor() {
13238 // Three-consumer coherence pin: the [`SupervisorSpec::validate`]
13239 // `SimpleOneForOne`-arm `!self.children().is_empty()` refusal
13240 // probe (which must trip [`SupervisorError::SimpleOneForOneWithStaticChildren`]
13241 // when the accessor projects a non-empty slice under a
13242 // `SimpleOneForOne` estrategia), the peer non-`SimpleOneForOne`-arm
13243 // `self.children().is_empty()` refusal probe (which must trip
13244 // [`SupervisorError::NoChildren`] when the accessor projects the
13245 // empty slice under any peer estrategia), and the per-child
13246 // validate loop's `for child in self.children()` traversal
13247 // (which must reach every entry in the same order the accessor
13248 // projects) must all key off the lifted accessor, so any future
13249 // rebrand on the typed slot's reader shape lands at exactly one
13250 // place. Pins the three-site coherence by exercising each
13251 // production consumer end-to-end: (1) the
13252 // `SimpleOneForOneWithStaticChildren` refusal under a non-empty
13253 // slice + `SimpleOneForOne` estrategia, (2) the `NoChildren`
13254 // refusal under the empty slice + non-`SimpleOneForOne`
13255 // estrategia across every peer variant, and (3) the per-child
13256 // duplicate-detection surface fires on the second entry of a
13257 // two-child cohort that shares a `:caixa` name (which requires
13258 // the loop to reach both entries — a first-entry-only projection
13259 // would silently pass since the dedup HashSet has room for the
13260 // first insert).
13261 //
13262 // Peer of the sibling M2
13263 // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
13264 // two-consumer coherence pin on the per-`:supervisor`
13265 // sibling-restart-strategy axis, extended onto the
13266 // per-`:supervisor` static-child-list `Vec`-carry axis.
13267
13268 // (1) `SimpleOneForOne`-arm probe: a non-empty slice under a
13269 // `SimpleOneForOne` estrategia must trip
13270 // `SimpleOneForOneWithStaticChildren`.
13271 let s = SupervisorSpec {
13272 estrategia: RestartStrategy::SimpleOneForOne,
13273 children: vec![child("worker", "^0.1", RestartPolicy::Permanent)],
13274 ..SupervisorSpec::default()
13275 };
13276 assert_eq!(
13277 s.validate().unwrap_err(),
13278 SupervisorError::SimpleOneForOneWithStaticChildren,
13279 "SimpleOneForOne + non-empty children must trip \
13280 SimpleOneForOneWithStaticChildren — the accessor projects \
13281 a non-empty slice, and the SimpleOneForOne-arm refusal \
13282 probe reads through the lifted accessor",
13283 );
13284 assert!(
13285 !s.children().is_empty(),
13286 "the SimpleOneForOne-arm refusal input must be a non-empty \
13287 slice per the accessor's projection",
13288 );
13289
13290 // (2) Peer non-`SimpleOneForOne`-arm probe: the empty slice
13291 // under any peer estrategia must trip `NoChildren`.
13292 for estrategia in [
13293 RestartStrategy::OneForOne,
13294 RestartStrategy::OneForAll,
13295 RestartStrategy::RestForOne,
13296 ] {
13297 let s = SupervisorSpec {
13298 estrategia,
13299 children: Vec::new(),
13300 ..SupervisorSpec::default()
13301 };
13302 match s.validate().unwrap_err() {
13303 SupervisorError::NoChildren { estrategia: e } => {
13304 assert_eq!(
13305 e, estrategia,
13306 "NoChildren.estrategia must carry the author-\
13307 declared :supervisor :estrategia variant \
13308 verbatim (got {e:?}, expected {estrategia:?})",
13309 );
13310 }
13311 other => panic!(
13312 "expected NoChildren, got {other:?} for \
13313 estrategia={estrategia:?}"
13314 ),
13315 }
13316 assert!(
13317 s.children().is_empty(),
13318 "the non-SimpleOneForOne-arm refusal input must be the \
13319 empty slice per the accessor's projection",
13320 );
13321 }
13322
13323 // (3) Per-child validate loop: a two-child cohort that shares a
13324 // `:caixa` name must trip `DuplicateChildCaixa` — the loop must
13325 // reach both entries through the accessor.
13326 let s = SupervisorSpec {
13327 estrategia: RestartStrategy::OneForOne,
13328 children: vec![
13329 child("worker", "^0.1", RestartPolicy::Permanent),
13330 child("worker", "^0.2", RestartPolicy::Transient),
13331 ],
13332 ..SupervisorSpec::default()
13333 };
13334 match s.validate().unwrap_err() {
13335 SupervisorError::DuplicateChildCaixa { caixa } => {
13336 assert_eq!(
13337 caixa, "worker",
13338 "DuplicateChildCaixa.caixa must carry the shared \
13339 child `:caixa` name verbatim",
13340 );
13341 }
13342 other => panic!("expected DuplicateChildCaixa, got {other:?}"),
13343 }
13344 assert_eq!(
13345 s.children().len(),
13346 2,
13347 "the per-child validate loop's traversal input must be a \
13348 two-element slice per the accessor's projection",
13349 );
13350 }
13351
13352 // Shared helper for the M2 per-`:children` per-slot-gate ≡
13353 // `validate` equivalence pins: builds an `OneForOne`-estrategia
13354 // one-cohort spec whose peer `:estrategia`↔`:children.is_empty()`
13355 // partition, `:max-restarts` zero-floor/cap, and `:restart-window`
13356 // bracket all pass cleanly so the sole failing surface is the
13357 // per-child cascade [`SupervisorSpec::validate_children`] owns, and
13358 // pins the two-altitude equivalence on the paired probe.
13359 fn assert_validate_children_matches_gate(children: Vec<ChildSpec>, expected: &SupervisorError) {
13360 let s = SupervisorSpec {
13361 estrategia: RestartStrategy::OneForOne,
13362 children,
13363 ..SupervisorSpec::default()
13364 };
13365 let via_gate = s.validate_children().unwrap_err();
13366 let via_validate = s.validate().unwrap_err();
13367 assert_eq!(&via_gate, expected, "validate_children direct dispatch",);
13368 assert_eq!(&via_validate, expected, "validate() end-to-end dispatch",);
13369 assert_eq!(
13370 via_gate, via_validate,
13371 "per-slot gate ≡ validate() must discriminate the same \
13372 refusal shape",
13373 );
13374 }
13375
13376 #[test]
13377 fn validate_children_matches_gate_on_per_axis_refusal_shapes() {
13378 // Fail-before-pass-after equivalence pin on the M2
13379 // per-`:children` per-slot gate ≡ [`SupervisorSpec::validate`]
13380 // convergence — sibling of the M3 mesh-slot
13381 // `validate_membros_*` / `validate_contratos_*` /
13382 // `validate_entrada_*` per-slot-gate ≡ `validate` pins on the
13383 // peer per-entry axes. Sweeps four of the five refusal shapes
13384 // the per-slot gate owns: (1) `EmptyChildName` on an empty-
13385 // `:caixa` child, (2) `ChildCaixaInvalid` on a structurally
13386 // invalid `:caixa` DNS-1123 label, (3) `EmptyChildVersion` on
13387 // an empty-`:versao` child, (4) `DuplicateChildCaixa` on a
13388 // duplicate-`:caixa` fan-out. Companion pin
13389 // `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
13390 // covers `ChildVersaoInvalid` (whose parser-owned reason string
13391 // needs pattern-matching, not equality) and the clean-pass
13392 // canonical fixture; together the two pins guarantee the
13393 // per-slot gate and `validate` discriminate the same set on
13394 // every per-child-covered input.
13395 assert_validate_children_matches_gate(
13396 vec![child("", "^0.1", RestartPolicy::Permanent)],
13397 &SupervisorError::EmptyChildName,
13398 );
13399 assert_validate_children_matches_gate(
13400 vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
13401 &SupervisorError::ChildCaixaInvalid {
13402 caixa: "Worker".into(),
13403 reason: "contains uppercase character 'W' (K8s DNS-1123 label names are lowercase-only; use \"worker\")".into(),
13404 },
13405 );
13406 assert_validate_children_matches_gate(
13407 vec![child("worker", "", RestartPolicy::Permanent)],
13408 &SupervisorError::EmptyChildVersion {
13409 caixa: "worker".into(),
13410 },
13411 );
13412 assert_validate_children_matches_gate(
13413 vec![
13414 child("worker", "^0.1", RestartPolicy::Permanent),
13415 child("worker", "^0.2", RestartPolicy::Transient),
13416 ],
13417 &SupervisorError::DuplicateChildCaixa {
13418 caixa: "worker".into(),
13419 },
13420 );
13421 }
13422
13423 #[test]
13424 fn validate_children_matches_gate_on_versao_invalid_and_clean_pass() {
13425 // Second half of the two-altitude equivalence pin — covers the
13426 // one refusal shape whose reason string is parser-owned
13427 // (`ChildVersaoInvalid`, whose reason comes from the shared
13428 // [`crate::version::parse_requirement`] impl and may drift) and
13429 // the clean-pass canonical fixture. Sibling pin
13430 // `validate_children_matches_gate_on_per_axis_refusal_shapes`
13431 // covers the four equality-comparable refusal shapes.
13432 let s_bad_versao = SupervisorSpec {
13433 estrategia: RestartStrategy::OneForOne,
13434 children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
13435 ..SupervisorSpec::default()
13436 };
13437 let via_gate = s_bad_versao.validate_children().unwrap_err();
13438 let via_validate = s_bad_versao.validate().unwrap_err();
13439 match (&via_gate, &via_validate) {
13440 (
13441 SupervisorError::ChildVersaoInvalid {
13442 caixa: cg,
13443 versao: vg,
13444 ..
13445 },
13446 SupervisorError::ChildVersaoInvalid {
13447 caixa: cv,
13448 versao: vv,
13449 ..
13450 },
13451 ) => {
13452 assert_eq!(cg, "worker", "per-slot gate :caixa carrier");
13453 assert_eq!(vg, "not-a-req", "per-slot gate :versao carrier");
13454 assert_eq!(cv, "worker", "validate() :caixa carrier");
13455 assert_eq!(vv, "not-a-req", "validate() :versao carrier");
13456 }
13457 other => panic!("expected ChildVersaoInvalid on both altitudes, got {other:?}"),
13458 }
13459 assert_eq!(
13460 via_gate, via_validate,
13461 "per-slot gate ≡ validate() on ChildVersaoInvalid full envelope",
13462 );
13463
13464 let s_ok = SupervisorSpec {
13465 estrategia: RestartStrategy::OneForOne,
13466 children: vec![
13467 child("worker-a", "^0.1", RestartPolicy::Permanent),
13468 child("worker-b", "~0.2.3", RestartPolicy::Transient),
13469 child("collector", "*", RestartPolicy::Temporary),
13470 ],
13471 ..SupervisorSpec::default()
13472 };
13473 s_ok.validate_children()
13474 .expect("per-slot gate must accept the clean-pass fixture");
13475 s_ok.validate()
13476 .expect("validate() must accept the clean-pass fixture");
13477 }
13478
13479 #[test]
13480 fn validate_children_is_self_contained_on_children_slot() {
13481 // Self-containment pin: [`SupervisorSpec::validate_children`]
13482 // resolves the per-child cascade against `&self` alone, without
13483 // depending on the peer `:estrategia`/`:max-restarts`/
13484 // `:restart-window` gates having run first — same posture the M3
13485 // peer per-slot gates carry (`validate_membros`,
13486 // `validate_contratos`, `validate_entrada`, `validate_placement`,
13487 // routing through their own oracles rather than borrowing state
13488 // threaded down from `validate`). A future consumer that reaches
13489 // the per-slot gate directly on a spec whose peer slots would
13490 // fail `validate` still surfaces the per-child refusal, not the
13491 // peer refusal.
13492 //
13493 // Construct a spec whose `:max-restarts` is `0` (which would
13494 // trip [`SupervisorError::ZeroMaxRestarts`] at `validate` after
13495 // the partition-dispatch) and whose `:children` carries a
13496 // `DuplicateChildCaixa` shape: the per-slot gate called directly
13497 // must surface `DuplicateChildCaixa`, proving it does not depend
13498 // on the peer `:max-restarts` gate running first.
13499 let s = SupervisorSpec {
13500 estrategia: RestartStrategy::OneForOne,
13501 max_restarts: 0,
13502 restart_window: Some(Duration::from_secs(60)),
13503 children: vec![
13504 child("worker", "^0.1", RestartPolicy::Permanent),
13505 child("worker", "^0.2", RestartPolicy::Transient),
13506 ],
13507 };
13508 assert_eq!(
13509 s.validate_children().unwrap_err(),
13510 SupervisorError::DuplicateChildCaixa {
13511 caixa: "worker".into(),
13512 },
13513 "per-slot gate must resolve per-child refusal directly against \
13514 `&self` — a dependency on the peer `:max-restarts` gate \
13515 running first would surface ZeroMaxRestarts here instead",
13516 );
13517 // The peer gate is still the surface `validate` reaches — pin
13518 // the ordering to establish that `validate_children` truly runs
13519 // last in `validate`'s dispatch, so a direct call bypasses the
13520 // peer gates on any spec whose per-child cascade would fail.
13521 assert_eq!(
13522 s.validate().unwrap_err(),
13523 SupervisorError::ZeroMaxRestarts,
13524 "validate() must surface the peer `:max-restarts` gate before \
13525 reaching the per-child cascade — this pins the dispatch \
13526 ordering the per-slot gate's self-containment complements",
13527 );
13528 }
13529
13530 #[test]
13531 fn child_spec_restart_accessor_is_const_fn() {
13532 // The [`ChildSpec::restart`] per-`:children` restart-decision-
13533 // policy `Copy`-return scalar accessor is declared
13534 // `#[must_use] pub const fn` — matching the sibling M2
13535 // per-`:supervisor` [`SupervisorSpec::estrategia`] (pinned by
13536 // [`supervisor_spec_estrategia_accessor_is_const_fn`] below,
13537 // both converted in this commit), the sibling M2
13538 // per-`:supervisor` [`SupervisorSpec::max_restarts`] (b698ec0)
13539 // `Copy`-`u32` accessor already `pub const fn`, and the peer M3
13540 // mesh-slot per-`:entrada` [`crate::Entrada::port`] (bafa004) /
13541 // per-`:placement` [`crate::Placement::estrategia`] (bafa004)
13542 // `Copy`-return `pub const fn` scalar accessors on the sibling
13543 // M3 surface. Pin the `const`-eval posture here so a future
13544 // accidental downgrade to non-`const` (an added runtime helper
13545 // reachable only from a non-`const` context, an
13546 // `Option<RestartPolicy>`-shape migration on the per-child
13547 // restart-decision axis once heterogeneous per-cluster
13548 // restart-policy overlays land that would silently drop the
13549 // `const` qualifier, a manual hand-rolled shadow) trips at
13550 // caixa-core build time rather than surfacing as a downstream
13551 // `const`-context regression far from the declaration.
13552 //
13553 // Same shape as the sibling M3
13554 // [`crate::aplicacao::tests::placement_estrategia_accessor_is_const_fn`]
13555 // and [`crate::aplicacao::tests::entrada_port_accessor_is_const_fn`]
13556 // (bafa004) pins on the peer M3 mesh-slot `Copy`-return scalar
13557 // accessor axis — the load-bearing witness lives in the
13558 // module-scope `const fn` wrapper `restart_via_const_fn` below:
13559 // a body that calls [`ChildSpec::restart`] under a `const fn`
13560 // signature is well-formed only when the callee is itself
13561 // `const fn`, so any future accidental downgrade of
13562 // [`ChildSpec::restart`] to non-`const` fails at caixa-core
13563 // build time (const-eval E0015 `cannot call non-const method`),
13564 // strictly stronger than a runtime `assert!(CONST)` and
13565 // side-stepping the destructor-in-const restriction that
13566 // blocks direct `const _: RestartPolicy = FIXTURE.restart()`
13567 // items on `ChildSpec`'s `String` carriers.
13568 //
13569 // The runtime body sweeps every closed-set [`RestartPolicy`]
13570 // arm and asserts the wrapped and direct dispatches agree.
13571 const fn restart_via_const_fn(c: &ChildSpec) -> RestartPolicy {
13572 c.restart()
13573 }
13574 for restart in [
13575 RestartPolicy::Permanent,
13576 RestartPolicy::Transient,
13577 RestartPolicy::Temporary,
13578 ] {
13579 let c = ChildSpec {
13580 caixa: "worker".into(),
13581 versao: "^0.1".into(),
13582 restart,
13583 };
13584 assert_eq!(
13585 restart_via_const_fn(&c),
13586 c.restart(),
13587 "const-fn-wrapped and direct dispatch on \
13588 ChildSpec::restart must agree for {restart:?}",
13589 );
13590 assert_eq!(
13591 c.restart(),
13592 restart,
13593 "ChildSpec::restart must return the storage-side \
13594 RestartPolicy verbatim for {restart:?} (a violation \
13595 means the accessor stopped being a raw field-return \
13596 copy)",
13597 );
13598 }
13599 }
13600
13601 #[test]
13602 fn supervisor_spec_estrategia_accessor_is_const_fn() {
13603 // The [`SupervisorSpec::estrategia`] per-`:supervisor`
13604 // sibling-restart-strategy `Copy`-return scalar accessor is
13605 // declared `#[must_use] pub const fn` — matching the sibling M2
13606 // per-`:children` [`ChildSpec::restart`] (pinned by
13607 // [`child_spec_restart_accessor_is_const_fn`] above, both
13608 // converted in this commit), the sibling M2 per-`:supervisor`
13609 // [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32`
13610 // accessor already `pub const fn`, and mirroring the peer M3
13611 // mesh-slot per-`:placement`
13612 // [`crate::Placement::estrategia`] (bafa004) `Copy`-return
13613 // `pub const fn` scalar accessor whose method-name discipline
13614 // the [`SupervisorSpec::estrategia`] method was authored to
13615 // match. Pin the `const`-eval posture here so a future
13616 // accidental downgrade to non-`const` (an added runtime helper
13617 // reachable only from a non-`const` context, an
13618 // `Option<RestartStrategy>`-shape migration once the substrate
13619 // grows per-cluster strategy overlays that would silently drop
13620 // the `const` qualifier, a manual hand-rolled shadow) trips at
13621 // caixa-core build time rather than surfacing as a downstream
13622 // `const`-context regression far from the declaration.
13623 //
13624 // Same shape as the sibling
13625 // [`child_spec_restart_accessor_is_const_fn`] pin above — the
13626 // load-bearing witness lives in the module-scope `const fn`
13627 // wrapper `estrategia_via_const_fn` below: a body that calls
13628 // [`SupervisorSpec::estrategia`] under a `const fn` signature
13629 // is well-formed only when the callee is itself `const fn`,
13630 // side-stepping the destructor-in-const restriction that would
13631 // otherwise block a direct
13632 // `const _: RestartStrategy = FIXTURE.estrategia()` item on
13633 // `SupervisorSpec`'s `Vec<ChildSpec>` / `Option<Duration>`
13634 // carriers.
13635 //
13636 // The runtime body sweeps every closed-set [`RestartStrategy`]
13637 // arm via [`RestartStrategy::ALL`] and asserts the wrapped and
13638 // direct dispatches agree.
13639 const fn estrategia_via_const_fn(s: &SupervisorSpec) -> RestartStrategy {
13640 s.estrategia()
13641 }
13642 for &estrategia in RestartStrategy::ALL {
13643 let s = SupervisorSpec {
13644 estrategia,
13645 max_restarts: 5,
13646 restart_window: Some(Duration::from_secs(60)),
13647 children: Vec::new(),
13648 };
13649 assert_eq!(
13650 estrategia_via_const_fn(&s),
13651 s.estrategia(),
13652 "const-fn-wrapped and direct dispatch on \
13653 SupervisorSpec::estrategia must agree for {estrategia:?}",
13654 );
13655 assert_eq!(
13656 s.estrategia(),
13657 estrategia,
13658 "SupervisorSpec::estrategia must return the storage-side \
13659 RestartStrategy verbatim for {estrategia:?} (a violation \
13660 means the accessor stopped being a raw field-return \
13661 copy)",
13662 );
13663 }
13664 }
13665
13666 // Per-variant equivalence pins for the [`supervisor_caixa_only_ctors!`]
13667 // macro definition (see the paired doc-block above the macro
13668 // definition) — every generated `<ctor>(caixa: &str) -> Self`
13669 // constructor folds the uniform `Self::<Variant> { caixa:
13670 // caixa.to_string() }` one-field struct-literal onto one substrate
13671 // primitive. The three per-variant equivalence pins below
13672 // (fail-before-pass-after by construction — a byte-mismatched macro
13673 // arm would trip its equivalence pin first) lock each generated
13674 // constructor to its struct-literal peer under `PartialEq`, so
13675 // every wire-up in [`SupervisorSpec::validate_children`] and
13676 // [`validate_no_self_supervision`] on that variant produces a
13677 // byte-equal `SupervisorError` to the pre-lift open-coded
13678 // struct-literal. The cross-axis pin that follows (non-default
13679 // caixa name) routes the sole constructor input axis through
13680 // `.to_string()`, so the fold does not silently collapse onto a
13681 // fixed name.
13682 //
13683 // Peer of the sibling `<slot>_ctor_matches_tuple_literal_wrap` /
13684 // `<slot>_violation_ctor_matches_struct_literal_wrap` /
13685 // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
13686 // `missing_entry_ctor_matches_struct_literal_wrap` /
13687 // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
13688 // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
13689 // `contrato_missing_target_ctor_matches_struct_literal_wrap` /
13690 // `<variant>_ctor_matches_struct_literal_wrap` equivalence pins
13691 // on the six sibling ctor families the recent trajectory closed
13692 // on the peer `LayoutError` / `AplicacaoError` envelopes.
13693
13694 #[test]
13695 fn empty_child_version_ctor_matches_struct_literal_wrap() {
13696 assert_eq!(
13697 SupervisorError::empty_child_version("worker"),
13698 SupervisorError::EmptyChildVersion {
13699 caixa: "worker".to_string(),
13700 },
13701 "generated empty_child_version ctor must produce byte-equal \
13702 SupervisorError to the open-coded struct-literal wrap on the \
13703 same &str fixture",
13704 );
13705 }
13706
13707 #[test]
13708 fn duplicate_child_caixa_ctor_matches_struct_literal_wrap() {
13709 assert_eq!(
13710 SupervisorError::duplicate_child_caixa("worker"),
13711 SupervisorError::DuplicateChildCaixa {
13712 caixa: "worker".to_string(),
13713 },
13714 "generated duplicate_child_caixa ctor must produce byte-equal \
13715 SupervisorError to the open-coded struct-literal wrap on the \
13716 same &str fixture",
13717 );
13718 }
13719
13720 #[test]
13721 fn child_supervises_self_ctor_matches_struct_literal_wrap() {
13722 assert_eq!(
13723 SupervisorError::child_supervises_self("orquestra"),
13724 SupervisorError::ChildSupervisesSelf {
13725 caixa: "orquestra".to_string(),
13726 },
13727 "generated child_supervises_self ctor must produce byte-equal \
13728 SupervisorError to the open-coded struct-literal wrap on the \
13729 same &str fixture",
13730 );
13731 }
13732
13733 // Per-variant equivalence pins for the two lifted
13734 // [`SupervisorError::child_caixa_invalid`] /
13735 // [`SupervisorError::child_versao_invalid`] inherent constructors
13736 // (fail-before-pass-after by construction — a byte-mismatched ctor body
13737 // would trip its equivalence pin first). Each pins the ctor output to
13738 // its pre-lift struct-literal peer under `PartialEq`, so every wire-up
13739 // in [`SupervisorSpec::validate_children`] on the two variants
13740 // produces a byte-equal `SupervisorError` to the pre-lift open-coded
13741 // struct-literal on the same scalar fixtures. Peers of the sibling
13742 // `membro_caixa_invalid_ctor_matches_struct_literal_wrap` /
13743 // `entrada_para_invalid_ctor_matches_struct_literal_wrap` / … pins on
13744 // the peer `AplicacaoError` envelope's
13745 // [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold.
13746
13747 #[test]
13748 fn child_caixa_invalid_ctor_matches_struct_literal_wrap() {
13749 let caixa = "Worker";
13750 let reason = "sample reason text";
13751 assert_eq!(
13752 SupervisorError::child_caixa_invalid(caixa, reason),
13753 SupervisorError::ChildCaixaInvalid {
13754 caixa: caixa.to_string(),
13755 reason: reason.to_string(),
13756 },
13757 "lifted child_caixa_invalid ctor must produce byte-equal \
13758 SupervisorError to the open-coded struct-literal wrap on the \
13759 same (&str, reason) fixture",
13760 );
13761 }
13762
13763 #[test]
13764 fn child_versao_invalid_ctor_matches_struct_literal_wrap() {
13765 let caixa = "worker";
13766 let versao = "not-a-req";
13767 let reason = "sample reason text";
13768 assert_eq!(
13769 SupervisorError::child_versao_invalid(caixa, versao, reason),
13770 SupervisorError::ChildVersaoInvalid {
13771 caixa: caixa.to_string(),
13772 versao: versao.to_string(),
13773 reason: reason.to_string(),
13774 },
13775 "lifted child_versao_invalid ctor must produce byte-equal \
13776 SupervisorError to the open-coded struct-literal wrap on the \
13777 same (&str, &str, reason) fixture",
13778 );
13779 }
13780
13781 #[test]
13782 fn supervisor_child_reason_ctors_route_reason_through_into_uniformly() {
13783 // Cross-axis pin: sweep the two lifted `{ …, reason }` ctors
13784 // against a `&str`-literal vs. `format!(…)` reason input to pin
13785 // both constructors accept the `impl Into<String>` bound
13786 // uniformly, so neither wire-up site drifts under a per-arm
13787 // wrapper transformation on the caller-side `reason` axis. Peer
13788 // of the sibling
13789 // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
13790 // sweep on the peer `AplicacaoError` envelope.
13791 let via_literal = "literal reason text";
13792 let via_format = format!("{} reason text", "literal");
13793 assert_eq!(
13794 SupervisorError::child_caixa_invalid("Worker", via_literal),
13795 SupervisorError::child_caixa_invalid("Worker", via_format.clone()),
13796 );
13797 assert_eq!(
13798 SupervisorError::child_versao_invalid("worker", "not-a-req", via_literal),
13799 SupervisorError::child_versao_invalid("worker", "not-a-req", via_format),
13800 );
13801 }
13802
13803 #[test]
13804 fn supervisor_caixa_only_ctors_route_caixa_through_to_string() {
13805 // Cross-axis pin: sweep the sole constructor input axis (`caixa:
13806 // &str`) through a non-default fixture name against every
13807 // generated arm in the [`supervisor_caixa_only_ctors!`] macro,
13808 // so any wrapper-side lowercase / trim / truncate / re-order on
13809 // the `caixa.to_string()` sole-field construction surfaces
13810 // here rather than at a downstream diagnostic-shape mismatch.
13811 // Peer of the sibling `nome_only_ctor_routes_caixa_through_
13812 // nome_accessor` / `entrada_host_invalid_ctor_routes_host_
13813 // through_to_string` / `contrato_target_ctors_route_edge_
13814 // triple_through_verbatim` / `contrato_empty_pair_ctors_
13815 // route_edge_pair_through_verbatim` cross-axis routing pins on
13816 // the peer `LayoutError` / `AplicacaoError` envelopes; extended
13817 // here onto the `SupervisorError` `{ caixa: String }` envelope
13818 // so every substrate-primitive ctor family in caixa-core
13819 // guarantees the sole-field construction routes the caller's
13820 // `&str` through `.to_string()` verbatim.
13821 let name = "cache-v2";
13822 assert_eq!(
13823 SupervisorError::empty_child_version(name),
13824 SupervisorError::EmptyChildVersion {
13825 caixa: name.to_string(),
13826 },
13827 );
13828 assert_eq!(
13829 SupervisorError::duplicate_child_caixa(name),
13830 SupervisorError::DuplicateChildCaixa {
13831 caixa: name.to_string(),
13832 },
13833 );
13834 assert_eq!(
13835 SupervisorError::child_supervises_self(name),
13836 SupervisorError::ChildSupervisesSelf {
13837 caixa: name.to_string(),
13838 },
13839 );
13840 }
13841
13842 // ── supervisor_scalar_ctors! per-variant + cross-axis pins ──────────────
13843 //
13844 // Per-variant byte-equality pins guaranteeing every generated ctor arm in
13845 // the [`supervisor_scalar_ctors!`] macro produces a `SupervisorError`
13846 // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
13847 // one-line struct-literal on the same `Copy`-`RestartStrategy | u32 |
13848 // Duration` fixture, plus one cross-axis sweep that routes each per-variant
13849 // `<field>: <ty>` scalar through the sole `$field:ident: $ty:ty` axis the
13850 // macro exposes so any wrapper-side truncation / re-order / silent `.into()`
13851 // / silent constant-substitution on any one variant surfaces here rather
13852 // than at a downstream per-`:supervisor` diagnostic-shape drift. Peer of the
13853 // sibling per-variant pins on `aplicacao_policy_scalar_ctors!` (7ef425e,
13854 // the 8-variant `AplicacaoError` `{ <field>: Duration | u32 }` fold on the
13855 // per-`:politicas` per-axis cap / canonical-form arms), plus the sibling
13856 // `supervisor_caixa_only_ctors!` (db09650), `SupervisorError::
13857 // {child_caixa_invalid,child_versao_invalid}` (d2ef2ec), and the peer
13858 // `DepError` / `AplicacaoError` / `LayoutError` / `LimitsError` /
13859 // `BehaviorError` / `UpgradeError` per-envelope ctor-macro pins.
13860 #[test]
13861 fn no_children_ctor_matches_struct_literal_wrap() {
13862 let estrategia = RestartStrategy::OneForAll;
13863 assert_eq!(
13864 SupervisorError::no_children(estrategia),
13865 SupervisorError::NoChildren { estrategia },
13866 "generated no_children ctor must produce byte-equal \
13867 `SupervisorError::NoChildren` to the pre-lift struct-literal wrap \
13868 on the same `Copy`-`RestartStrategy` fixture",
13869 );
13870 }
13871
13872 #[test]
13873 fn max_restarts_exceeds_cap_ctor_matches_struct_literal_wrap() {
13874 let max_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 1;
13875 assert_eq!(
13876 SupervisorError::max_restarts_exceeds_cap(max_restarts),
13877 SupervisorError::MaxRestartsExceedsCap { max_restarts },
13878 "generated max_restarts_exceeds_cap ctor must produce byte-equal \
13879 `SupervisorError::MaxRestartsExceedsCap` to the pre-lift \
13880 struct-literal wrap on the same `Copy`-`u32` fixture",
13881 );
13882 }
13883
13884 #[test]
13885 fn restart_window_not_canonical_ctor_matches_struct_literal_wrap() {
13886 let window = Duration::from_micros(1_500);
13887 assert_eq!(
13888 SupervisorError::restart_window_not_canonical(window),
13889 SupervisorError::RestartWindowNotCanonical { window },
13890 "generated restart_window_not_canonical ctor must produce \
13891 byte-equal `SupervisorError::RestartWindowNotCanonical` to the \
13892 pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
13893 );
13894 }
13895
13896 #[test]
13897 fn restart_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
13898 let window = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
13899 assert_eq!(
13900 SupervisorError::restart_window_exceeds_cap(window),
13901 SupervisorError::RestartWindowExceedsCap { window },
13902 "generated restart_window_exceeds_cap ctor must produce \
13903 byte-equal `SupervisorError::RestartWindowExceedsCap` to the \
13904 pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
13905 );
13906 }
13907
13908 #[test]
13909 fn supervisor_scalar_ctors_route_field_through_copy_uniformly() {
13910 // Cross-axis routing pin: sweep each generated `<field>: <ty>`
13911 // constructor input axis through a non-default `Copy` fixture against
13912 // every arm in the [`supervisor_scalar_ctors!`] macro, so any wrapper-
13913 // side silent `.into()` / silent constant-substitution / silent field
13914 // re-name away from the canonical `estrategia | max_restarts | window`
13915 // axes on any one variant, or a `RestartStrategy | u32 | Duration`
13916 // axis silently rerouted through some other `Copy` coercion, surfaces
13917 // here rather than at a downstream per-`:supervisor` diagnostic-shape
13918 // drift. Peer of the sibling
13919 // `aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly`
13920 // (7ef425e) cross-axis routing pin on the peer `AplicacaoError`
13921 // envelope's per-`:politicas` per-axis ctor family, extended here onto
13922 // the last M2 per-`:supervisor` `Copy`-scalar `SupervisorError`
13923 // variant family folded onto a substrate primitive.
13924 //
13925 // Fixtures picked out of each variant's accept-set boundary rather
13926 // than the default value so a silent constant-substitution to a per-
13927 // variant sentinel surfaces here on the structural-equality assertion.
13928 // The `RestartStrategy` fixture picks `RestForOne` (a non-default arm
13929 // that isn't the `OneForOne` [`SUPERVISOR_ESTRATEGIA_DEFAULT`] and
13930 // isn't the `SimpleOneForOne` arm the sibling
13931 // `SimpleOneForOneWithStaticChildren` unit variant intercepts). The
13932 // `max_restarts` fixture picks an above-cap magnitude the cap arm
13933 // rejects; the two `Duration` fixtures pick the sub-millisecond and
13934 // above-cap ends of the `:restart-window` canonical-form + cap
13935 // bracket respectively.
13936 let estrategia = RestartStrategy::RestForOne;
13937 let above_cap_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 137;
13938 let sub_ms = Duration::from_micros(1_500);
13939 let above_hour = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
13940 assert_eq!(
13941 SupervisorError::no_children(estrategia),
13942 SupervisorError::NoChildren { estrategia },
13943 );
13944 assert_eq!(
13945 SupervisorError::max_restarts_exceeds_cap(above_cap_restarts),
13946 SupervisorError::MaxRestartsExceedsCap {
13947 max_restarts: above_cap_restarts,
13948 },
13949 );
13950 assert_eq!(
13951 SupervisorError::restart_window_not_canonical(sub_ms),
13952 SupervisorError::RestartWindowNotCanonical { window: sub_ms },
13953 );
13954 assert_eq!(
13955 SupervisorError::restart_window_exceeds_cap(above_hour),
13956 SupervisorError::RestartWindowExceedsCap { window: above_hour },
13957 );
13958 }
13959
13960 #[test]
13961 fn supervisor_scalar_ctors_are_const_zero_runtime_work() {
13962 // Const-eval pin: the [`supervisor_scalar_ctors!`] macro spells every
13963 // generated ctor `const fn` so a caller can pin a `SupervisorError`
13964 // at compile time — the same zero-runtime-work property the pre-lift
13965 // `|<slot>| SupervisorError::<Variant> { <slot> }` closure carried on
13966 // its `Copy`-pass-through construction path (no `.to_string()` /
13967 // `.into()` allocation, no branching). If any future edit silently
13968 // drops the `const` qualifier from the macro body the per-arm `const`
13969 // bindings below fail to compile, which surfaces the regression at
13970 // the substrate-primitive definition rather than at some downstream
13971 // consumer that had come to rely on the `const`-constructibility.
13972 // Peer of the sibling
13973 // `aplicacao_policy_scalar_ctors_are_const_zero_runtime_work`
13974 // (7ef425e) const-eval pin on the peer `AplicacaoError` envelope's
13975 // per-`:politicas` per-axis ctor family.
13976 const NO_CHILDREN: SupervisorError =
13977 SupervisorError::no_children(RestartStrategy::OneForAll);
13978 const MAX_RESTARTS_CAP: SupervisorError = SupervisorError::max_restarts_exceeds_cap(1_337);
13979 const WINDOW_NC: SupervisorError =
13980 SupervisorError::restart_window_not_canonical(Duration::from_micros(1));
13981 const WINDOW_CAP: SupervisorError =
13982 SupervisorError::restart_window_exceeds_cap(Duration::from_secs(3_601));
13983 assert!(matches!(NO_CHILDREN, SupervisorError::NoChildren { .. }));
13984 assert!(matches!(
13985 MAX_RESTARTS_CAP,
13986 SupervisorError::MaxRestartsExceedsCap { .. }
13987 ));
13988 assert!(matches!(
13989 WINDOW_NC,
13990 SupervisorError::RestartWindowNotCanonical { .. }
13991 ));
13992 assert!(matches!(
13993 WINDOW_CAP,
13994 SupervisorError::RestartWindowExceedsCap { .. }
13995 ));
13996 }
13997}