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/// Per-child restart policy.
1169///
1170/// Permanent / Temporary / Transient match Erlang/OTP semantics 1:1.
1171#[derive(
1172 Serialize,
1173 Deserialize,
1174 Debug,
1175 Clone,
1176 Copy,
1177 PartialEq,
1178 Eq,
1179 Hash,
1180 gen_platform::TypedDispatcher,
1181 gen_platform::Discriminant,
1182 gen_platform::IsVariant,
1183 gen_platform::FromStrKind,
1184)]
1185pub enum RestartPolicy {
1186 /// Always restart the child, regardless of how it died. Used for
1187 /// long-running services that must always be up.
1188 Permanent,
1189 /// Never restart. Used for one-shot work whose completion is
1190 /// itself the success signal (`oneShot` triggers map here).
1191 Temporary,
1192 /// Restart only when the child died *abnormally* (non-zero exit
1193 /// or unhandled exception). A clean exit completes the child.
1194 Transient,
1195}
1196
1197impl Default for RestartPolicy {
1198 fn default() -> Self {
1199 // Route the [`Default for RestartPolicy`] impl's return arm through
1200 // the substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed
1201 // `pub const` rather than a raw `Self::Permanent` arm — one source
1202 // of truth for the Erlang/OTP-canonical `permanent` worker-child
1203 // default across the two production consumers that currently
1204 // dispatch on it (this impl at the [`RestartPolicy::default`] call
1205 // and the serde-side `#[serde(default)]` on
1206 // [`ChildSpec::restart`] that resolves an author-omitted
1207 // `:children :restart` slot through `RestartPolicy::default()`).
1208 // Peer of the sibling per-`:supervisor` axis
1209 // [`Default for RestartStrategy`] → [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
1210 // route (95ffacc) — the two impls now share one substrate-primitive
1211 // lift discipline, so any future coherent rebrand of the OTP-shape
1212 // supervisor+child default set migrates through typed constants in
1213 // lockstep instead of splitting a lifted supervisor half against
1214 // an open-coded child half. Pinned by
1215 // `restart_policy_default_routes_through_lifted_default` +
1216 // `child_spec_serde_default_restart_routes_through_lifted_default`
1217 // in the tests module.
1218 SUPERVISOR_CHILD_RESTART_DEFAULT
1219 }
1220}
1221
1222impl RestartPolicy {
1223 /// Exhaustive iteration surface for every consumer that walks the
1224 /// closed three-arm [`RestartPolicy`] discriminator set (the future
1225 /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1226 /// per-child admission-webhook rejection body naming the accepted-
1227 /// `:restart` list, a future `feira supervisor --restart …` CLI
1228 /// arg-parse's "did you mean" hint via a [`Self::from_wire`]-scan
1229 /// over the slice, the future `feira app graph` per-child restart
1230 /// column, any future round-trip fuzz harness that sweeps every
1231 /// arm). A future arm addition (an OTP-`intrinsic` fourth arm the
1232 /// theory
1233 /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1234 /// might reach for once the three canonical OTP restart policies
1235 /// stop covering the substrate's discovered load-shape) extends
1236 /// this slice as one edit and every consumer picks up the new entry
1237 /// by construction; the compiler-checked exhaustiveness on the
1238 /// sibling method `match` arms ([`Self::as_str`] / [`Self::from_wire`])
1239 /// is the build-time guarantee that no arm forgets to grow.
1240 ///
1241 /// Peer of the sibling closed-set typed enums'
1242 /// [`RestartStrategy::ALL`] (4eec29c) /
1243 /// [`crate::CaixaKind::ALL`] (6b1f4fb) /
1244 /// [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
1245 /// [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
1246 /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
1247 /// surfaces — the sixth (and the third and final M2 OTP-shape)
1248 /// closed-set typed enum on the caixa surface to converge onto the
1249 /// same one-canonical-arm-list-per-enum discipline. Sibling axis to
1250 /// the peer [`RestartStrategy::ALL`] on the per-supervisor
1251 /// sibling-restart-strategy axis; this closes the per-child
1252 /// restart-decision-policy axis on the same M2 `:supervisor` slot.
1253 pub const ALL: &'static [Self] = &[Self::Permanent, Self::Temporary, Self::Transient];
1254
1255 /// Canonical PascalCase discriminator scalar this variant serializes
1256 /// as under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`]. The three
1257 /// arms return the paired
1258 /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1259 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1260 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] lifted
1261 /// constants so every substrate consumer that dispatches on the
1262 /// per-child restart-decision policy (the future wasm-operator's
1263 /// per-child post-exit restart-decision branch, the future M4
1264 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1265 /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
1266 /// reconciliation scheduler's per-child-policy fan-out) reads the
1267 /// same byte-string the `Serialize` derive emits — the pin test in
1268 /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
1269 /// asserts the two paths agree, peer of the M2
1270 /// [`RestartStrategy::as_str`] (09ffb2d) on the sibling per-supervisor
1271 /// sibling-restart-strategy axis and the M3
1272 /// [`crate::aplicacao::PlacementStrategy::as_str`] (cc8f749) on the
1273 /// per-Aplicacao distribution-strategy axis — the third of three
1274 /// OTP-shaped closed-enum discriminator axes on the caixa typed
1275 /// surface to converge onto the same three-path-convergence
1276 /// (`Serialize` derive → `as_str` helper → lifted constant)
1277 /// drift-detection posture.
1278 #[must_use]
1279 pub const fn as_str(self) -> &'static str {
1280 match self {
1281 Self::Permanent => crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
1282 Self::Temporary => crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
1283 Self::Transient => crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
1284 }
1285 }
1286
1287 /// Substrate-canonical reverse projection on the `:children :restart`
1288 /// closed-set axis — parses the `PascalCase` discriminator scalar
1289 /// back to the typed variant, or `None` when `s` is outside the
1290 /// closed-set arm-string set [`Self::as_str`] emits. Dispatches on
1291 /// the same lifted
1292 /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1293 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1294 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] constants
1295 /// the [`Self::as_str`] emitter walks, so the parse and emit halves
1296 /// of the round-trip migrate through one caixa-core edit on any
1297 /// future arm addition.
1298 ///
1299 /// Prior to this lift the substrate carried only the forward
1300 /// `Self → &str` projection on the OTP per-child restart-policy
1301 /// axis (the [`Self::as_str`] emitter, the [`std::fmt::Display`]
1302 /// impl routed through it, the `Serialize` derive that emits the
1303 /// same byte-string under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`])
1304 /// plus the kebab-case dispatcher-catalog identity via
1305 /// [`Self::discriminant`] — every non-serde consumer that wanted to
1306 /// parse a wire-form `PascalCase` policy scalar had to re-inline a
1307 /// three-arm `match s { "Permanent" => …, "Temporary" => …,
1308 /// "Transient" => …, _ => … }` cascade that expressed no
1309 /// compile-time link back to the typed variant's canonical lifted
1310 /// constant. A future variant rename or per-arm serde-attribute
1311 /// drift would silently split the wire byte-string one non-serde
1312 /// consumer parsed from the one the emitter wrote, with the failure
1313 /// surfacing at the operator's reconcile posture (a `:temporary`
1314 /// `oneShot` child being restarted on clean exit, treating the
1315 /// successful-completion signal as failure and re-running the
1316 /// completion-terminal one-shot indefinitely; a `:transient` child
1317 /// that clean-exited being restarted, masking the clean-completion
1318 /// contract) far from the rebrand commit and with no field naming
1319 /// the drift.
1320 ///
1321 /// Distinct axis from the [`std::str::FromStr`] impl the
1322 /// [`gen_platform::FromStrKind`] derive already installs on this
1323 /// enum by design, not by drift: `FromStr` parses the *kebab-case*
1324 /// dispatcher-catalog identity (`"permanent"` / `"temporary"` /
1325 /// `"transient"` — the inverse of [`Self::discriminant`]), while
1326 /// this method inverts the `PascalCase` wire byte-string
1327 /// [`Self::as_str`] emits. The two-axis split lets the dispatcher-
1328 /// catalog identity live in kebab-case (where every peer catalog
1329 /// identifier already lives) without forcing a wire-format rename
1330 /// on the tatara-lisp author surface (`:restart Permanent`,
1331 /// `PascalCase`) — the same two-axis distinction the sibling
1332 /// [`RestartStrategy::from_wire`] (4eec29c) /
1333 /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
1334 /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
1335 /// carry on their peer closed-set typed-enum wire round-trips.
1336 ///
1337 /// Same closed-set-reverse-projection discipline the sibling
1338 /// [`RestartStrategy::from_wire`] (4eec29c) /
1339 /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
1340 /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
1341 /// [`crate::aplicacao::RateLimitUnit::from_suffix`] typed enums
1342 /// carry on the peer wire-side `str → Self` axes — extended onto
1343 /// the M2 OTP-shape per-child restart-policy closed-set axis, the
1344 /// sixth substrate-side closed-set typed enum (and the third and
1345 /// final OTP-shape closed-enum discriminator axis) to converge on
1346 /// the two-way `str ↔ Self` round-trip. Method-named `from_wire`
1347 /// (not `from_str`) to match the peer [`RestartStrategy::from_wire`]
1348 /// shape verbatim and side-step the [`std::str::FromStr`] impl the
1349 /// derive already installs on the sibling kebab-case axis. Returns
1350 /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
1351 /// shapes: the caller picks the diagnostic form appropriate for
1352 /// its use site.
1353 #[must_use]
1354 pub fn from_wire(s: &str) -> Option<Self> {
1355 match s {
1356 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT => Some(Self::Permanent),
1357 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY => Some(Self::Temporary),
1358 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT => Some(Self::Transient),
1359 _ => None,
1360 }
1361 }
1362}
1363
1364/// [`std::fmt::Display`] routed through [`RestartPolicy::as_str`], so the
1365/// pretty-printed byte-string every consumer that formats the policy as
1366/// user-facing text lands on (the future wasm-operator's per-child
1367/// post-exit restart-decision diagnostic line, the future `feira app
1368/// graph` per-child restart column, the future M4
1369/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1370/// admission-webhook rejection body) reaches for the same lifted
1371/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1372/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1373/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1374/// wire-format `Serialize` derive already emits under
1375/// [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
1376/// [`RestartPolicy::as_str`] helper already returns.
1377///
1378/// Pre-convergence the two paths structurally disagreed — the
1379/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
1380/// route (now retired here) sent [`std::fmt::Display`] through the
1381/// gen-platform discriminant catalog string, which arrives kebab-case as
1382/// `"permanent"` / `"temporary"` / `"transient"` on this three-arm enum
1383/// (whose variant names each collapse to their own lowercase form under
1384/// the kebab-case transform), while the wire format ran as `PascalCase`
1385/// `"Permanent"` / `"Temporary"` / `"Transient"` through the un-`rename`d
1386/// serde derive. Every consumer that formatted the policy for a
1387/// diagnostic line, a graph column, or a rejection body under
1388/// `format!("{v}")` therefore landed under a different byte-string than
1389/// the wire format the operator's per-child-policy dispatch keyed off —
1390/// a silent split whose apply-time symptom (a `format!("{v}")`-carrying
1391/// diagnostic quoting `"permanent"` while the wire scalar the operator
1392/// probed was `"Permanent"`) surfaced as a confused correlate at
1393/// operator-log time far from the two-declaration site.
1394///
1395/// Routing `Display` through [`RestartPolicy::as_str`] closes the third
1396/// path: every `format!("{v}")` call reaches the same lifted
1397/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the wire format
1398/// and the [`RestartPolicy::as_str`] helper route through — `Debug` (the
1399/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
1400/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
1401/// byte-string per variant. A future variant rename or
1402/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
1403/// exactly one place, structurally.
1404///
1405/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
1406/// (from `#[derive(gen_platform::Discriminant)]`) still returns
1407/// `"permanent"` / `"temporary"` / `"transient"`, and the fleet-wide
1408/// [`gen_platform::register_dispatcher!("caixa.restart-policy", …)`]
1409/// registration keys the catalog off the same kebab identity. The two
1410/// naming worlds now live on separate typed methods (`Display` /
1411/// `as_str` for the wire byte-string, `discriminant` for the catalog
1412/// identity) rather than sharing one `Display` route that structurally
1413/// disagrees with the wire format.
1414///
1415/// Pin tests
1416/// [`tests::restart_policy_display_routes_through_as_str_helper`]
1417/// and
1418/// [`tests::restart_policy_display_matches_serialized_wire_byte_string`]
1419/// assert the three paths agree byte-for-byte on every variant, so a
1420/// future variant rename or per-arm serde attribute drift is a build
1421/// error visible at caixa-core test time, not a silent per-consumer
1422/// dispatch miss at apply / reconcile time.
1423///
1424/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
1425/// (aplicacao.rs:2306) on the per-Aplicacao distribution-strategy axis
1426/// and the sibling [`RestartStrategy`] `Display` impl on the
1427/// per-supervisor sibling-restart-strategy axis — same three-path-
1428/// convergence discipline, extended to close the third and final of
1429/// three OTP-shaped closed-enum discriminator axes on the caixa typed
1430/// surface.
1431impl std::fmt::Display for RestartPolicy {
1432 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1433 f.write_str(self.as_str())
1434 }
1435}
1436
1437/// Substrate-canonical [`AsRef<str>`] projection on the M2
1438/// per-child-restart-policy [`RestartPolicy`] closed-set typed enum —
1439/// routes through the same [`RestartPolicy::as_str`] `pub const fn`
1440/// scalar accessor the paired [`std::fmt::Display`] impl and the
1441/// un-`rename`d [`serde::Serialize`] derive already key off, so any
1442/// future consumer that binds a [`RestartPolicy`] through the
1443/// standard-library `impl AsRef<str>` bound (a future
1444/// [`caixa-feira`] `feira supervisor --restart <arm>` verb that
1445/// composes the emitted `PascalCase` wire scalar into a
1446/// [`std::process::Command::arg`] shell-out of the future
1447/// wasm-operator's per-child admission gate, a per-child structured-
1448/// log recorder on the future `caixa-operator`'s hierarchical
1449/// reconciliation surface that accepts `impl AsRef<str>` at the
1450/// `tracing::field::Value` `Str`-arm, a [`std::collections::HashMap`]
1451/// lookup keyed on the restart-policy wire byte through
1452/// `map.get::<str>(policy.as_ref())` on a future per-policy
1453/// dispatch table) reaches the paired
1454/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1455/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1456/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
1457/// lifted-const through one substrate-primitive dispatch rather
1458/// than an open-coded `.as_str()` projection at every wire-up.
1459///
1460/// Peer of the sibling [`std::fmt::Display`] impl on the same
1461/// primitive — both delegate to the shared [`RestartPolicy::as_str`]
1462/// `pub const fn` accessor, so [`format!("{v}")`], `v.as_str()`, and
1463/// `<RestartPolicy as AsRef<str>>::as_ref(&v)` resolve to the same
1464/// byte-string per instance by construction. A future variant rename
1465/// or `#[serde(rename_all = "kebab-case")]` attribute-drift on the
1466/// enum reaches every one of the three paths (plus the wire-format
1467/// `Serialize` derive that already routes through the same lifted
1468/// const) through exactly one caixa-core edit.
1469///
1470/// Same "route the trait impl through the substrate-primitive
1471/// accessor" discipline the sibling [`crate::CaixaVersion`]
1472/// [`AsRef<str>`] impl (16d5c7e) and the paired M2
1473/// [`RestartStrategy`] [`AsRef<str>`] impl (63eb1a4) carry — extends
1474/// the axis onto the paired per-child-restart-decision-policy
1475/// sibling on the same M2 `:supervisor` slot (the second M2
1476/// OTP-shape closed-set typed enum to converge onto the standard-
1477/// library [`AsRef<str>`] projection). Rust-side newtype/typed-enum
1478/// convention pairs [`AsRef<str>`] and [`fmt::Display`] on the same
1479/// primitive so a caller who has one has both; before this lift,
1480/// [`RestartPolicy`] carried [`fmt::Display`] but not the paired
1481/// [`AsRef<str>`] impl the convention names.
1482///
1483/// Pinned load-bearing by
1484/// [`tests::restart_policy_as_ref_str_routes_through_as_str_accessor`]
1485/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1486/// three-arm closed set) and
1487/// [`tests::restart_policy_as_ref_str_routes_through_display_via_shared_accessor`]
1488/// (three-path convergence: `AsRef<str>` + `Display` + `as_str` all
1489/// resolve to the same lifted `SUPERVISOR_CHILD_RESTART_*` const per
1490/// arm) — any future silent detour that routes the impl through a
1491/// divergent projection (a per-arm inline `match self { … }`
1492/// re-inlining that opens a compile-time link to the un-lifted
1493/// arm-literal, a swap onto the kebab-case
1494/// [`gen_platform::Discriminant`] catalog identity that would
1495/// collide the wire axis with the dispatcher-catalog axis) trips at
1496/// caixa-core test time under `assert_eq!` rather than at a
1497/// downstream `impl AsRef<str>`-bound consumer's silent split.
1498impl AsRef<str> for RestartPolicy {
1499 fn as_ref(&self) -> &str {
1500 self.as_str()
1501 }
1502}
1503
1504/// Trait-idiomatic reverse projection on the M2-OTP-shape per-child
1505/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
1506/// byte-for-byte through the paired substrate-primitive
1507/// [`RestartPolicy::from_wire`] `Option<Self>` accessor so every future
1508/// consumer that binds a `PascalCase` `:children :restart` wire
1509/// byte-string through the standard-library `.try_into()` / [`TryFrom`]
1510/// axis (a future [`caixa-feira`] `feira supervisor --restart
1511/// <Permanent|Temporary|Transient>` CLI arg-parse that composes into
1512/// `let restart: RestartPolicy = s.try_into()?`, a future
1513/// `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook that folds a
1514/// `spec.children[*].restart: String` field through
1515/// `RestartPolicy::try_from(&s)?`, a generic
1516/// `<T: TryFrom<&str>>`-bound loader over any of the substrate's closed-
1517/// set typed enums) reaches the same three-arm accept-set the sibling
1518/// [`RestartPolicy::from_wire`] resolver parses through and the sibling
1519/// [`RestartPolicy::as_str`] emits, rather than an open-coded per-arm
1520/// `match s { "Permanent" => …, "Temporary" => …, "Transient" => …, _ =>
1521/// … }` cascade whose arm-set has no compile-time link back to the
1522/// substrate primitive.
1523///
1524/// Complements the pre-existing forward-projection triple
1525/// ([`std::fmt::Display`], [`AsRef<str>`], [`RestartPolicy::as_str`])
1526/// with the paired trait-idiomatic reverse-projection axis: Rust-side
1527/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
1528/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so a
1529/// caller who can project *out to* a `&str` can also project *in from*
1530/// one. The [`TryFrom<&str>`] axis is deliberately chosen over
1531/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
1532/// lint the sibling method-named [`RestartPolicy::from_wire`] would
1533/// trigger under a `FromStr` impl and to avoid colliding with the
1534/// [`std::str::FromStr`] impl the [`gen_platform::FromStrKind`] derive
1535/// already installs on the paired *kebab-case dispatcher-catalog* axis
1536/// (which parses `"permanent"` / `"temporary"` / `"transient"`, the
1537/// inverse of [`Self::discriminant`]) — this impl closes the trait-
1538/// idiomatic reverse axis on the *`PascalCase` wire* half without
1539/// disturbing either the method-named `from_wire` shape every sibling
1540/// closed-set typed enum on the substrate already carries or the
1541/// pre-existing `FromStr` on the dispatcher-catalog half, keeping the
1542/// two-axis split the sibling [`Self::from_wire`] doc block motivates.
1543///
1544/// `type Error = ()` matches the sibling [`RestartPolicy::from_wire`]'s
1545/// `Option<Self>` return-shape's deliberate deferral of error typing: the
1546/// caller picks the diagnostic form appropriate for its use site (a
1547/// future `feira supervisor --restart` arg-parse composes its own
1548/// per-verb "unknown restart: <arg> — accepted: {…}" message enumerating
1549/// [`RestartPolicy::ALL`], a future M4 admission-webhook rejection body
1550/// wraps the `Err(())` outcome with the accepted-set enumeration for
1551/// operator diagnostics, a `Result::map_err` at the call site lifts the
1552/// unit-error to a per-verb error type). Same shape the peer
1553/// [`RestartStrategy`] (5b828ed) on the sibling per-supervisor axis,
1554/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136), and
1555/// [`crate::aplicacao::PlacementStrategy`] (6fd00cd) blocks motivate on
1556/// their peer closed-set typed enums' reverse projections.
1557///
1558/// The paired [`TryFrom<&str>`] impl reaches the same three-arm accept-
1559/// set the [`RestartPolicy::from_wire`] resolver dispatches through, so
1560/// any future arm addition (an OTP-`intrinsic` fourth arm the theory
1561/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1562/// might reach for once the three canonical OTP restart policies stop
1563/// covering the substrate's discovered load-shape) grows the trait-
1564/// idiomatic axis by construction — one caixa-core edit on
1565/// [`RestartPolicy::from_wire`] extends both the method-named reverse
1566/// projection every existing consumer keys off and the trait-idiomatic
1567/// reverse projection this impl exposes, without a coordinated rewrite
1568/// across every future `TryFrom<&str>`-bound consumer's arm-set.
1569///
1570/// Extends the substrate-wide closed-set-enum reverse-projection family
1571/// ([`crate::CaixaKind`] via 3c83606, [`crate::CaixaDialeto`] via
1572/// bf33136, [`crate::aplicacao::PlacementStrategy`] via 6fd00cd, and
1573/// [`RestartStrategy`] via 5b828ed) onto the third and final OTP-shape
1574/// closed-enum discriminator axis on the caixa surface — the paired
1575/// per-child `:children :restart` closed set the future wasm-operator's
1576/// hierarchical reconciliation scheduler's per-child post-exit
1577/// restart-decision branch keys off end-to-end.
1578///
1579/// Pinned load-bearing by
1580/// [`tests::restart_policy_try_from_str_routes_through_from_wire_accessor`]
1581/// (byte-parity pin against [`RestartPolicy::from_wire`] across the
1582/// three-arm accept-set),
1583/// [`tests::restart_policy_try_from_str_rejects_unknown_byte_strings`]
1584/// (rejection witness against silent accept-set widening), and
1585/// [`tests::restart_policy_try_from_str_and_from_wire_partition_the_accept_set`]
1586/// (cross-axis partition pin locking the trait and method-named
1587/// projections onto one accept-set).
1588impl TryFrom<&str> for RestartPolicy {
1589 type Error = ();
1590
1591 fn try_from(s: &str) -> Result<Self, Self::Error> {
1592 Self::from_wire(s).ok_or(())
1593 }
1594}
1595
1596/// Trait-idiomatic forward projection on the M2-OTP-shape per-child
1597/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
1598/// byte-for-byte through the paired substrate-primitive
1599/// [`RestartPolicy::as_str`] `pub const fn` accessor. Return type is
1600/// `&'static str` by construction — every [`RestartPolicy::as_str`] arm
1601/// resolves to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const
1602/// &str` with `'static` lifetime, so the trait's return-type promise is
1603/// upheld structurally without a [`String::leak`] cast or a per-arm inline
1604/// literal.
1605///
1606/// Every future consumer that specifically needs `&'static str` lifetime
1607/// bytes on the per-child restart-decision axis (a
1608/// [`tracing::field::valuable::Value::Str`] recording where the `Str`
1609/// arm's typing demands `&'static str`, a
1610/// [`std::borrow::Cow::Borrowed`]`::<'static, str>(policy.into())` composer
1611/// on the future M4 admission-webhook rejection body where the
1612/// `Cow<'static, str>` typing rules out the sibling [`AsRef<str>`]
1613/// borrowed return, a generic `<T: Into<&'static str>>`-bound serializer
1614/// or error formatter that requires the `'static` bound) reaches the same
1615/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1616/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1617/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] substrate-
1618/// primitive dispatch rather than an open-coded per-arm literal cascade
1619/// whose arm-set has no compile-time link back to the substrate primitive.
1620///
1621/// Peer of the sibling M2-OTP-shape [`RestartStrategy`] forward-projection
1622/// impl (523157d) on the per-supervisor sibling-restart-strategy axis —
1623/// the second (and second-of-two-in-M2) closed-set typed enum on the
1624/// caixa surface to converge onto the paired trait-idiomatic forward-
1625/// projection axis. With this lift the paired per-child
1626/// `:children :restart` closed-set typed enum carries the full sibling
1627/// quintet ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
1628/// [`TryFrom<&str>`] via 6fdd0d9, `From<Self> for &'static str` via this
1629/// lift) plus the round-trip witness through both the trait-idiomatic
1630/// (`From<Self> for &'static str` + `TryFrom<&str>`) and the method-named
1631/// (`as_str` + `from_wire`) axis pairs — mirrors the sibling
1632/// [`RestartStrategy`] surface arm-for-arm, so every future arm addition
1633/// (an OTP-`intrinsic` fourth arm the theory
1634/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1635/// might reach for once the three canonical OTP restart policies stop
1636/// covering the substrate's discovered load-shape) grows the trait-
1637/// idiomatic forward axis by construction: one caixa-core edit on
1638/// [`RestartPolicy::as_str`] extends every one of the five sibling
1639/// forward-projection paths ([`std::fmt::Display`], [`AsRef<str>`],
1640/// [`Self::as_str`] itself, this `From<Self> for &'static str`, and the
1641/// un-`rename`d [`serde::Serialize`] derive that also emits `as_str`'s
1642/// bytes) without a coordinated rewrite across every future
1643/// `Into<&'static str>`-bound consumer's arm-set.
1644///
1645/// Pinned load-bearing by
1646/// [`tests::restart_policy_from_into_static_str_routes_through_as_str_accessor`]
1647/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1648/// three-arm emit-set, plus a `const`-context materialization witness for
1649/// the `&'static str` lifetime promise) and
1650/// [`tests::restart_policy_from_into_static_str_and_as_str_partition_the_emit_set`]
1651/// (partition pin asserting `<&'static str as From<RestartPolicy>>::from`
1652/// and [`RestartPolicy::as_str`] agree on every arm, plus a two-way
1653/// round-trip witness through the paired trait-idiomatic reverse-
1654/// projection axis [`TryFrom<&str>`] (6fdd0d9): every
1655/// `policy.into::<&'static str>()` output re-parses back through
1656/// [`RestartPolicy::try_from`] to the original variant, closing the two-
1657/// way `Self ↔ &'static str` round-trip on the trait-idiomatic axis pair).
1658impl From<RestartPolicy> for &'static str {
1659 fn from(policy: RestartPolicy) -> &'static str {
1660 policy.as_str()
1661 }
1662}
1663
1664/// Trait-idiomatic *forward* projection on [`RestartPolicy`] from a
1665/// *borrowed* input onto the `&'static str` axis — the borrowed-input
1666/// companion to the paired owned-input [`From<RestartPolicy> for
1667/// &'static str`] impl immediately above. Routes byte-for-byte through
1668/// the same substrate-primitive [`RestartPolicy::as_str`] `pub const
1669/// fn` accessor so every consumer that binds a `&RestartPolicy`
1670/// through the standard-library `.into()` / [`From<&Self> for &'static
1671/// str`] axis (a `RestartPolicy::ALL.iter().map(<&'static
1672/// str>::from).collect::<Vec<_>>()` per-arm accept-set materializer —
1673/// whose iterator over `&'static [RestartPolicy]` yields
1674/// `&RestartPolicy`, not `RestartPolicy`, so the owned-input
1675/// [`From<RestartPolicy>`] axis alone forces every call site through
1676/// an explicit `.copied()` / dereference / [`Copy`]-bound restatement
1677/// rather than the direct trait-idiomatic projection; a future generic
1678/// `<T: Copy + for<'a> Into<&'static str>>`-bound diagnostic column
1679/// that walks the `iter().map(Into::into)` shape verbatim across every
1680/// substrate-wide closed-set typed enum; the future wasm-operator's
1681/// per-child post-exit restart-decision diagnostic line that composes
1682/// the accepted-set enumeration from an iterated
1683/// `RestartPolicy::ALL.iter().map(|p| p.into())` pipe rather than a
1684/// per-arm `match p { … }` cascade; a future
1685/// `HashMap::<&'static str, RestartPolicy>::from_iter(
1686/// RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
1687/// per-policy reverse-lookup table the sibling [`TryFrom<&str>`] impl
1688/// cannot compose without this borrowed-input axis in place) reaches
1689/// the same three-arm lifted
1690/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1691/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1692/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1693/// paired owned-input [`From<RestartPolicy> for &'static str`], the
1694/// sibling [`std::fmt::Display`], [`AsRef<str>`], and
1695/// [`RestartPolicy::as_str`] surfaces already return.
1696///
1697/// Fifth peer on the substrate-wide trait-idiomatic *borrowed-input*
1698/// forward-projection family opened on [`crate::dep::DepList`]
1699/// (64aa742) and extended onto [`crate::CaixaKind`] (5ab993a),
1700/// [`crate::CaixaDialeto`] (807b0b5), and the paired
1701/// per-supervisor sibling-restart-strategy [`RestartStrategy`]
1702/// (e941836). Rust's `From` trait does not auto-derive the
1703/// `From<&Self>` sibling from a `From<Self>` impl (the blanket
1704/// `impl<T, U> From<&T> for U where T: Copy, U: From<T>` does not
1705/// exist in `core`), so every closed-set typed enum that carries the
1706/// owned-input axis but not the borrowed-input axis forces every
1707/// borrowed-input call site through a `.copied()` /
1708/// `<&'static str>::from(*policy)` / `policy.as_str()` detour whose
1709/// type bounds have no compile-time link to the substrate primitive.
1710/// [`RestartPolicy`] is the second (and second-of-two-in-M2)
1711/// OTP-shape peer to converge onto this campaign — sibling of the
1712/// paired per-supervisor [`RestartStrategy`] borrowed-input axis, so
1713/// with this lift both closed-set typed enums on the M2 `:supervisor`
1714/// slot now carry the full sibling quintet ([`std::fmt::Display`],
1715/// [`AsRef<str>`], [`Self::as_str`], `From<Self> for &'static str`,
1716/// `From<&Self> for &'static str`) plus the paired trait-idiomatic
1717/// reverse projection [`TryFrom<&str>`], closing the borrowed-input
1718/// forward-projection axis on the M2 OTP-shape slot as a unit.
1719///
1720/// Same three-path convergence discipline as the paired owned-input
1721/// impl (this borrowed-input axis, the paired owned-input
1722/// [`From<RestartPolicy> for &'static str`], and
1723/// [`RestartPolicy::as_str`] all route through the same lifted
1724/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const), so a future
1725/// variant rename or per-arm serde-attribute drift reaches every one
1726/// of the six sibling forward-projection paths
1727/// ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
1728/// [`From<Self> for &'static str`], this [`From<&Self> for &'static
1729/// str`], and the un-`rename`d [`serde::Serialize`] derive that also
1730/// emits [`Self::as_str`]'s bytes) through exactly one caixa-core
1731/// edit.
1732///
1733/// The [`RestartPolicy::as_str`] emit and [`RestartPolicy::from_wire`]
1734/// parse share the same `PascalCase` vocabulary by construction, so
1735/// the borrowed-input forward axis and the reverse axis compose
1736/// directly — the round-trip witness pin below locks this direct
1737/// composition without the intermediate wire-vocab hop the peer
1738/// [`crate::CaixaKind`] axis pair requires.
1739///
1740/// Pinned load-bearing by
1741/// [`tests::restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
1742/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1743/// three-arm emit-set via a borrowed input, plus a `const`-context
1744/// materialization witness for the `&'static str` lifetime promise,
1745/// plus a blanket `.into()` shape) and
1746/// [`tests::restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
1747/// (cross-axis partition pin against the paired owned-input
1748/// [`From<RestartPolicy> for &'static str`] impl, plus a
1749/// `.iter().map(Into::into)` pipe witness over
1750/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
1751/// [`TryFrom<&str>`] that closes the two-way `&Self → &'static str →
1752/// Self` round-trip without the wire-vocab intermediate the peer
1753/// [`crate::CaixaKind`] axis pair requires).
1754impl From<&RestartPolicy> for &'static str {
1755 fn from(policy: &RestartPolicy) -> &'static str {
1756 policy.as_str()
1757 }
1758}
1759
1760/// Trait-idiomatic *owned-`String`* forward projection on the second
1761/// M2 OTP-shape closed-set typed enum ([`RestartPolicy`]) — the
1762/// owned-heap-string companion to the paired `&'static str`-returning
1763/// [`From<RestartPolicy> for &'static str`] / [`From<&RestartPolicy>
1764/// for &'static str`] impls immediately above. Routes byte-for-byte
1765/// through the substrate-primitive [`RestartPolicy::as_str`] `pub
1766/// const fn` accessor (via [`str::to_owned`]) so every consumer that
1767/// binds a [`RestartPolicy`] through the standard-library `.into()` /
1768/// [`From<Self> for String`] (equivalently [`Into<String>`]) axis — a
1769/// future `serde_json::Value::String(policy.into())` structured-payload
1770/// composer where the `Value::String` arm typing demands an owned
1771/// [`String`] and the sibling [`&'static str`]-returning axis forces
1772/// an explicit `.to_owned()` / `String::from` restatement at every
1773/// call site, a future `HashMap::<String, RestartPolicy>::from_iter(
1774/// RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))` per-policy
1775/// lookup where the map's key type is owned [`String`] rather than
1776/// [`&'static str`], a future `Cow::<'static, str>::Owned(policy.into())`
1777/// composer on the future M4 admission-webhook rejection body's
1778/// owned-arm, the future wasm-operator's per-child post-exit
1779/// diagnostic emit `serde_json::json!({ "restart": policy })` where the
1780/// JSON serializer's `Serialize` impl on [`String`] owns the emit-path
1781/// — reaches the same three-arm lifted
1782/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1783/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1784/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1785/// paired [`std::fmt::Display`], [`AsRef<str>`],
1786/// [`RestartPolicy::as_str`], and the two `&'static str`-returning
1787/// forward-projection impls already return.
1788///
1789/// Extends the trait-idiomatic *owned-`String`* forward-projection
1790/// axis onto the second-of-two M2 OTP-shape closed-set typed enums on
1791/// the caixa surface — mirror of the first-mover
1792/// [`From<RestartStrategy> for String`] (7baa18a) that opened this
1793/// axis on the sibling supervisor-level strategy enum. Rust's standard
1794/// library does not carry a blanket `impl<T: AsRef<str>> From<T> for
1795/// String` (nor an `impl<T: fmt::Display> From<T> for String`), so
1796/// every closed-set typed enum that carries the paired `AsRef<str>` /
1797/// `Display` / `From<Self> for &'static str` triple but not the
1798/// owned-[`String`] axis forces every owned-string call site through a
1799/// `.to_string()` / `.as_str().to_owned()` / `String::from(policy.as_str())`
1800/// detour whose type bounds have no compile-time link to the
1801/// substrate primitive.
1802///
1803/// Deliberately routes through the human-readable
1804/// [`RestartPolicy::as_str`] axis — for this enum the wire format
1805/// (`PascalCase`, tatara-lisp author surface `:restart Permanent`) and
1806/// the diagnostic byte-string share the same vocabulary by
1807/// construction (unlike the sibling [`crate::CaixaKind`] enum whose
1808/// two axes diverge), so the owned-[`String`] projection lands
1809/// byte-identically on both the wire vocabulary the paired
1810/// [`serde::Serialize`] derive emits and the diagnostic vocabulary the
1811/// [`RestartPolicy::as_str`] helper returns, and — because the paired
1812/// [`TryFrom<&str>`] / [`RestartPolicy::from_wire`] reverse-projection
1813/// axis parses the same `PascalCase` vocabulary — the direct two-way
1814/// `Self → String → Self` round-trip composes without the wire-vocab
1815/// intermediate hop the peer [`crate::CaixaKind`] owned-[`String`]
1816/// axis pair requires.
1817///
1818/// Pinned load-bearing by
1819/// [`tests::restart_policy_from_into_owned_string_routes_through_as_str_accessor`]
1820/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1821/// three-arm emit-set, plus a blanket `.into::<String>()` shape
1822/// witness) and
1823/// [`tests::restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm`]
1824/// (cross-axis partition pin against the paired owned-input
1825/// [`From<RestartPolicy> for &'static str`] impl and the sibling
1826/// [`ToString::to_string`] surface routed through [`std::fmt::Display`],
1827/// plus a `.iter().copied().map(String::from)` pipe witness over
1828/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
1829/// [`TryFrom<&str>`] on the owned-[`String`]'s [`String::as_str`]
1830/// borrow that closes the two-way `Self → String → Self` round-trip
1831/// on the trait-idiomatic owned-[`String`] forward + reverse axis
1832/// pair).
1833impl From<RestartPolicy> for String {
1834 fn from(policy: RestartPolicy) -> String {
1835 policy.as_str().to_owned()
1836 }
1837}
1838
1839/// Trait-idiomatic *borrowed-input, owned-`String` output* forward
1840/// projection on the second-of-two M2 OTP-shape closed-set typed enum
1841/// ([`RestartPolicy`]) — the fourth (and closing) corner of the
1842/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
1843/// projection family on this enum, mirror of the first-mover
1844/// [`From<&RestartStrategy> for String`] (579385f) that opened the
1845/// 2×2-completion corner on the sibling supervisor-level strategy
1846/// enum. Routes byte-for-byte through the substrate-primitive
1847/// [`RestartPolicy::as_str`] `pub const fn` accessor (via
1848/// [`str::to_owned`]) so every consumer that holds a borrowed
1849/// [`&RestartPolicy`] and needs an owned [`String`] — a future
1850/// `serde_json::Value::String(String::from(&policy))` structured-payload
1851/// composer over a borrowed field, a future `Iterator::map` over
1852/// `&[RestartPolicy]` that projects to owned keys through
1853/// `.iter().map(String::from)`, a future `HashMap::<String,
1854/// RestartPolicy>::from_iter` that keys off a borrowed-iteration axis
1855/// where dereferencing the policy would force an unnecessary `Copy` at
1856/// every step, the future wasm-operator's per-supervisor
1857/// `child_policies.iter().map(String::from).collect()` per-child post-
1858/// exit restart-decision diagnostic emit whose iteration axis is
1859/// borrowed by construction — reaches the same three-arm lifted
1860/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1861/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1862/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1863/// paired [`std::fmt::Display`], [`AsRef<str>`],
1864/// [`RestartPolicy::as_str`], and the three other trait-idiomatic
1865/// forward-projection impls
1866/// ([`From<RestartPolicy> for &'static str`],
1867/// [`From<&RestartPolicy> for &'static str`],
1868/// [`From<RestartPolicy> for String`]) already return.
1869///
1870/// Second peer on the substrate-wide trait-idiomatic *borrowed-input,
1871/// owned-`String` output* forward-projection family opened on
1872/// [`crate::supervisor::RestartStrategy`] (579385f) — closes the
1873/// `{Self, &Self} × {&'static str, String}` 2×2 projection corner on
1874/// both M2 OTP-shape sibling peers (the paired supervisor-level
1875/// sibling-restart-strategy axis and the per-child restart-decision-
1876/// policy axis), so the whole M2 OTP-shape axis pair now carries the
1877/// full four-corner family by construction. Rust's standard library
1878/// does not carry a blanket `impl<T: AsRef<str>> From<&T> for String`
1879/// (nor an `impl<T: fmt::Display> From<&T> for String`), so every
1880/// closed-set typed enum that carries the paired `AsRef<str>` /
1881/// `Display` / `From<Self> for &'static str` / `From<&Self> for
1882/// &'static str` / `From<Self> for String` quintuple but not the
1883/// borrowed-input owned-[`String`] axis forces every borrowed-input
1884/// owned-string call site through a `policy.as_str().to_owned()` /
1885/// `String::from(*policy)` (with a spurious `Copy`) /
1886/// `policy.to_string()` (through `Display`) detour whose type bounds
1887/// have no compile-time link to the substrate primitive.
1888///
1889/// Deliberately routes through the human-readable
1890/// [`RestartPolicy::as_str`] axis — for this enum the wire format
1891/// (`PascalCase`, tatara-lisp author surface `:restart Permanent`) and
1892/// the diagnostic byte-string share the same vocabulary by
1893/// construction (unlike the sibling [`crate::CaixaKind`] enum whose
1894/// two axes diverge), so the borrowed-input owned-[`String`]
1895/// projection lands byte-identically on both the wire vocabulary the
1896/// paired [`serde::Serialize`] derive emits and the diagnostic
1897/// vocabulary the [`RestartPolicy::as_str`] helper returns, and —
1898/// because the paired [`TryFrom<&str>`] / [`RestartPolicy::from_wire`]
1899/// reverse-projection axis parses the same `PascalCase` vocabulary —
1900/// the direct two-way `&Self → String → Self` round-trip composes
1901/// without the wire-vocab intermediate hop the peer
1902/// [`crate::CaixaKind`] axis pair requires.
1903///
1904/// The remaining thirteen closed-set typed enums on the caixa
1905/// substrate surface (`CaixaKind`, `CaixaDialeto`, `DepList`,
1906/// `PlacementStrategy`, `WitShape`, `RateLimitUnit`,
1907/// `PathShapeViolation`, `InvariantKind`, `ArchVerdict`, `Severity`,
1908/// `FixSafety`, `Semantic`, `FerriteRuntime`) are the future targets
1909/// of this 2×2-completion campaign — each carries the same paired
1910/// quintuple that this borrowed-input owned-[`String`] axis extends
1911/// onto.
1912///
1913/// Pinned load-bearing by
1914/// [`tests::restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
1915/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1916/// three-arm emit-set through the borrowed-input surface) and
1917/// [`tests::restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
1918/// (cross-axis partition pin against the paired owned-input owned-
1919/// [`String`] [`From<RestartPolicy> for String`] impl, the paired
1920/// borrowed-input owned-[`&'static str`] [`From<&RestartPolicy> for
1921/// &'static str`] impl, and the sibling [`ToString::to_string`]
1922/// surface routed through [`std::fmt::Display`], plus a direct round-
1923/// trip witness through [`TryFrom<&str>`] on the owned-[`String`]'s
1924/// [`String::as_str`] borrow that closes the two-way
1925/// `&Self → String → Self` round-trip on the trait-idiomatic
1926/// borrowed-input owned-[`String`] forward + reverse axis pair).
1927impl From<&RestartPolicy> for String {
1928 fn from(policy: &RestartPolicy) -> String {
1929 policy.as_str().to_owned()
1930 }
1931}
1932
1933/// Trait-idiomatic *owned-input, [`std::borrow::Cow<'static, str>`]
1934/// output* forward projection on the M2 OTP-shape per-child-restart
1935/// [`RestartPolicy`] closed-set typed enum — extends the substrate-
1936/// wide [`std::borrow::Cow<'static, str>`] forward-projection family
1937/// opened on [`crate::CaixaKind`] (99c1735 owned-input, d45c409
1938/// borrowed-input) and first extended off it onto the sibling M2
1939/// OTP-shape sibling-restart [`RestartStrategy`] (7dd28b3 owned-input,
1940/// 9b3e4b3 borrowed-input) onto the second (and second-of-two-in-M2)
1941/// M2 OTP-shape closed-set fieldless typed enum peer on the caixa
1942/// surface (`:children :restart`). Routes byte-for-byte through the
1943/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
1944/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
1945/// that binds a [`RestartPolicy`] through the trait-idiomatic
1946/// [`std::borrow::Cow<'static, str>`] axis — a future
1947/// `axum::response::IntoResponse` composer whose per-policy
1948/// diagnostic-body typing rules out the sibling [`AsRef<str>`]
1949/// borrowed return, a future M4 admission-webhook rejection body
1950/// that composes the accepted-policy enumeration through the same
1951/// `RestartPolicy::ALL.iter().map(Cow::from)` shape [`crate::CaixaKind`]
1952/// and [`RestartStrategy`] already route through, a generic `<T: for<'a>
1953/// Into<std::borrow::Cow<'static, str>>>`-bound structured-log
1954/// emitter on a per-child-policy diagnostic column — reaches the same
1955/// three-arm lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`]
1956/// / [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1957/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1958/// paired [`std::fmt::Display`], [`AsRef<str>`],
1959/// [`RestartPolicy::as_str`], and the four
1960/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
1961/// forward-projection corners already return.
1962///
1963/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
1964/// [`std::borrow::Cow::Owned`] — the substrate-primitive
1965/// [`RestartPolicy::as_str`] accessor's return carries the `&'static
1966/// str` lifetime by construction (each `match` arm resolves to a
1967/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const &str`
1968/// with static lifetime), so the zero-alloc borrowed arm is the
1969/// type-correct projection with no runtime allocation.
1970///
1971/// Rust's standard library carries no blanket `impl<T: AsRef<str>>
1972/// From<T> for Cow<'static, str>` (nor an `impl<T: fmt::Display>
1973/// From<T> for Cow<'static, str>`), so the paired sibling
1974/// [`From<RestartPolicy> for &'static str`] (9fb37d0),
1975/// [`From<RestartPolicy> for String`] (7851725), [`AsRef<str>`], and
1976/// [`std::fmt::Display`] surfaces do not implicitly extend to a
1977/// [`Cow<'static, str>`]-bound call site — every such site is forced
1978/// through a `Cow::Borrowed(policy.as_str())` /
1979/// `Cow::Owned(policy.to_string())` open-code whose type bounds have
1980/// no compile-time link back to the substrate primitive until this
1981/// lift.
1982///
1983/// Second peer to extend the substrate-wide trait-idiomatic
1984/// [`std::borrow::Cow<'static, str>`] forward-projection axis off the
1985/// top-level [`crate::CaixaKind`] enum (99c1735 owned-input, d45c409
1986/// borrowed-input) onto the wider substrate — closes the M2 OTP-shape
1987/// tier of the campaign (both sibling peers, `RestartStrategy` and
1988/// `RestartPolicy`, now carry the owned-input Cow<'static, str>
1989/// forward projection) so the remaining eleven peers
1990/// (`PlacementStrategy`, `RateLimitUnit`, `DepList`, `CaixaDialeto`,
1991/// and the outside-`caixa-core` peers `WitShape`, `PathShapeViolation`,
1992/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
1993/// `FerriteRuntime`) are the future targets. Every future arm addition
1994/// (an OTP-`intrinsic` fourth restart policy the ABSORPTION-ROADMAP
1995/// might reach for once the three canonical OTP restart policies stop
1996/// covering the substrate's discovered load-shape) grows the
1997/// Cow<'static, str> axis by construction through one caixa-core edit
1998/// on [`RestartPolicy::as_str`] — rather than a coordinated rewrite
1999/// across every future Cow<'static, str>-bound consumer site.
2000///
2001/// Pinned load-bearing by
2002/// [`tests::restart_policy_from_into_static_cow_str_routes_through_as_str_accessor`]
2003/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
2004/// against [`RestartPolicy::as_str`] across the three-arm
2005/// [`RestartPolicy::ALL`]) and
2006/// [`tests::restart_policy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
2007/// (cross-axis partition pin against the paired [`From<RestartPolicy>
2008/// for &'static str`], [`From<RestartPolicy> for String`], and
2009/// [`ToString`]-through-[`std::fmt::Display`] axes, plus a
2010/// `.iter().copied().map(Cow::from)` pipe witness over
2011/// [`RestartPolicy::ALL`] that materializes the three-arm accept-set
2012/// through the [`Cow<'static, str>`] axis alone and pins the
2013/// zero-alloc discipline on every element).
2014impl From<RestartPolicy> for std::borrow::Cow<'static, str> {
2015 fn from(policy: RestartPolicy) -> std::borrow::Cow<'static, str> {
2016 std::borrow::Cow::Borrowed(policy.as_str())
2017 }
2018}
2019
2020/// Trait-idiomatic *borrowed-input, [`std::borrow::Cow<'static, str>`]
2021/// output* forward projection on the M2 OTP-shape per-child-restart
2022/// [`RestartPolicy`] closed-set typed enum — the borrowed-input
2023/// companion to the paired owned-input
2024/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl
2025/// immediately above (0612398). Routes byte-for-byte through the same
2026/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2027/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
2028/// that holds a `&RestartPolicy` and needs a
2029/// [`std::borrow::Cow<'static, str>`] — a
2030/// `RestartPolicy::ALL.iter().map(std::borrow::Cow::from).collect::<Vec<_>>()`
2031/// per-arm accept-set materializer (whose iterator over
2032/// `&'static [RestartPolicy]` yields `&RestartPolicy`, not
2033/// `RestartPolicy`, so the paired owned-input
2034/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] axis
2035/// alone forces every call site through an explicit `.copied()` /
2036/// dereference / [`Copy`]-bound restatement rather than the direct
2037/// trait-idiomatic projection), a future generic
2038/// `<T: for<'a> Into<std::borrow::Cow<'static, str>>>`-bound emitter
2039/// on a per-child-policy diagnostic column that walks the
2040/// `iter().map(Into::into)` shape verbatim, the future M4 admission-
2041/// webhook rejection body that composes the accepted-policy
2042/// enumeration from an iterated
2043/// `RestartPolicy::ALL.iter().map(|p| p.into())` pipe rather than a
2044/// per-arm `match p { … }` cascade — reaches the same three-arm
2045/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2046/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2047/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2048/// paired [`std::fmt::Display`], [`AsRef<str>`],
2049/// [`RestartPolicy::as_str`], the four
2050/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
2051/// forward-projection corners, and the paired owned-input
2052/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl
2053/// already return.
2054///
2055/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
2056/// [`std::borrow::Cow::Owned`] — the substrate-primitive
2057/// [`RestartPolicy::as_str`] accessor's return carries the
2058/// `&'static str` lifetime by construction (each `match` arm resolves
2059/// to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const &str`
2060/// with static lifetime), so the zero-alloc borrowed arm is the
2061/// type-correct projection with no runtime allocation.
2062///
2063/// Closes the `{Self, &Self}` input-shape corner on the M2 OTP-shape
2064/// per-child-restart [`std::borrow::Cow<'static, str>`] axis opened
2065/// one commit prior (0612398) on the paired owned-input
2066/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl —
2067/// second-of-two-in-M2 closed-set fieldless typed enum peer on the
2068/// caixa surface (paired with the sibling-restart [`RestartStrategy`]
2069/// which carries both {Self, &Self} × Cow<'static, str> corners since
2070/// 7dd28b3 owned-input, 9b3e4b3 borrowed-input), exactly as d45c409
2071/// closed it on the top-level [`crate::CaixaKind`] one commit after
2072/// the owning half (99c1735) landed. This lift closes the whole M2
2073/// OTP-shape tier of the substrate-wide [`Cow<'static, str>`]
2074/// forward-projection campaign on both input-shape corners
2075/// ({Self, &Self}) of both M2 OTP-shape sibling peers
2076/// ([`RestartStrategy`] and [`RestartPolicy`]), so the remaining
2077/// eleven substrate-wide peers (`PlacementStrategy`, `RateLimitUnit`,
2078/// `DepList`, `CaixaDialeto`, `WitShape`, `PathShapeViolation`,
2079/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
2080/// `FerriteRuntime`) become the future targets of the campaign. Rust's
2081/// standard library does not carry a blanket
2082/// `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor an
2083/// `impl<T: fmt::Display> From<&T> for Cow<'static, str>`), so every
2084/// closed-set fieldless typed enum peer on the substrate that carries
2085/// the paired owned-input [`Cow<'static, str>`] axis but not the
2086/// borrowed-input axis forces every borrowed-input
2087/// [`Cow<'static, str>`]-parameterized call site through a spurious
2088/// [`Copy`] deref (`std::borrow::Cow::from(*policy)`) or a
2089/// `std::borrow::Cow::Borrowed(policy.as_str())` open-code whose type
2090/// bounds have no compile-time link to the substrate primitive.
2091///
2092/// Pinned load-bearing by
2093/// [`tests::restart_policy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor`]
2094/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
2095/// against [`RestartPolicy::as_str`] across the three-arm
2096/// [`RestartPolicy::ALL`] through the borrowed-input surface) and
2097/// [`tests::restart_policy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
2098/// (cross-axis partition pin against the paired owned-input
2099/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`], the
2100/// paired borrowed-input owned-`&'static str`
2101/// [`From<&RestartPolicy> for &'static str`], and the paired
2102/// borrowed-input owned-`String` [`From<&RestartPolicy> for String`]
2103/// impls, plus a `.iter().map(std::borrow::Cow::from)` pipe witness
2104/// over [`RestartPolicy::ALL`] — whose iterator yields
2105/// `&RestartPolicy` by construction, so the borrowed-input
2106/// [`Cow<'static, str>`] axis is what routes the pipe through the
2107/// substrate-primitive [`RestartPolicy::as_str`] accessor with the
2108/// zero-alloc [`Cow::Borrowed`] arm by construction and without a
2109/// spurious [`Copy`] deref).
2110impl From<&RestartPolicy> for std::borrow::Cow<'static, str> {
2111 fn from(policy: &RestartPolicy) -> std::borrow::Cow<'static, str> {
2112 std::borrow::Cow::Borrowed(policy.as_str())
2113 }
2114}
2115
2116/// Trait-idiomatic *owned-input, [`Box<str>`] output* forward
2117/// projection on the M2 OTP-shape per-child-restart [`RestartPolicy`]
2118/// closed-set fieldless typed enum — extends the substrate-wide
2119/// `Box<str>` forward-projection campaign tier opened one commit prior
2120/// (69ef45c) on the paired sibling-restart [`RestartStrategy`] onto
2121/// the second (and third-and-final) M2 OTP-shape closed-set fieldless
2122/// typed enum peer on the caixa surface (`:children :restart`),
2123/// immediately after the paired `Cow<'static, str>` axis (0612398 /
2124/// b4dc55c) closed the
2125/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}` 2×3
2126/// corner on this enum. Routes byte-for-byte through the
2127/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2128/// accessor via [`Box::<str>::from`] on the returned `&'static str`,
2129/// so every consumer that binds a
2130/// `let key: Box<str> = policy.into();`-shaped call site — a
2131/// per-child metric-key materializer that stashes the policy
2132/// discriminator in a `Box<str>`-typed heap-owned scalar for cheap
2133/// clone (a shared-nothing per-policy accept-set the `caixa-operator`
2134/// hierarchical reconciliation scheduler's per-child restart-decision
2135/// fan-out carries), a future admission-webhook rejection body whose
2136/// per-arm `Box<str>` field composes from an owned `RestartPolicy`
2137/// handle — reaches the same three-arm lifted
2138/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2139/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2140/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2141/// sibling
2142/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
2143/// forward-projection corner already returns. Rust's standard library
2144/// carries `impl From<&str> for Box<str>` and
2145/// `impl From<String> for Box<str>` but no blanket
2146/// `impl<T: AsRef<str>> From<T> for Box<str>` (nor any
2147/// `impl<T: Copy, U: From<T>> From<T> for U` route from the enum), so
2148/// this axis is a distinct trait-idiomatic surface that a downstream
2149/// `RestartPolicy → Box<str>` `.into()` reaches through this impl and
2150/// no other — without a `Box::from(policy.as_str())` open-code whose
2151/// type bounds have no compile-time link back to the substrate
2152/// primitive.
2153///
2154/// Second peer on the substrate-wide trait-idiomatic [`Box<str>`]
2155/// forward-projection family opened on the sibling-restart
2156/// [`RestartStrategy`] (69ef45c / 59ae5dc) — closes the whole M2
2157/// OTP-shape tier of the substrate-wide [`Box<str>`] forward-
2158/// projection campaign's owned-input corner on both M2 OTP-shape
2159/// sibling peers ([`RestartStrategy`] and [`RestartPolicy`]), the
2160/// paired borrowed-input `From<&RestartPolicy> for Box<str>` closer
2161/// and the remaining fieldless-enum peers on the M3 mesh-shape /
2162/// outside-M3 caixa-core / render-side / outside-caixa-core tiers
2163/// are the future targets of the campaign.
2164///
2165/// Pinned load-bearing by
2166/// [`tests::restart_policy_from_into_box_str_routes_through_as_str_accessor`]
2167/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2168/// three-arm [`RestartPolicy::ALL`] emit-set on the owned-input
2169/// surface, plus a blanket-derived [`Into`] shape witness).
2170impl From<RestartPolicy> for Box<str> {
2171 fn from(policy: RestartPolicy) -> Box<str> {
2172 Box::<str>::from(policy.as_str())
2173 }
2174}
2175
2176/// Trait-idiomatic *borrowed-input, [`Box<str>`] output* forward
2177/// projection on the M2 OTP-shape per-child-restart [`RestartPolicy`]
2178/// closed-set fieldless typed enum — the borrowed-input companion to
2179/// the paired owned-input [`From<RestartPolicy> for Box<str>`] impl
2180/// (0a1b313, one commit prior) that closes the `{Self, &Self}`
2181/// input-shape corner of the substrate-wide [`Box<str>`] forward-
2182/// projection axis on the second (and third-and-final) M2 OTP-shape
2183/// closed-set fieldless typed enum peer on the caixa surface
2184/// (`:children :restart`), routing byte-for-byte through the
2185/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2186/// accessor via [`Box::<str>::from`] on the returned `&'static str`.
2187/// Every consumer that holds a `&RestartPolicy` and needs a
2188/// [`Box<str>`] — a
2189/// `RestartPolicy::ALL.iter().map(Box::<str>::from).collect::<Vec<_>>()`
2190/// per-arm accept-set materializer (whose iterator over
2191/// `&'static [RestartPolicy]` yields `&RestartPolicy`, not
2192/// `RestartPolicy`, so the paired owned-input
2193/// [`From<RestartPolicy> for Box<str>`] axis alone forces every
2194/// call site through an explicit [`Copy`] deref or a
2195/// `.copied()` restatement rather than the direct trait-idiomatic
2196/// projection), a per-child metric-key materializer holding
2197/// `&RestartPolicy` through a `caixa-operator` hierarchical
2198/// reconciliation scheduler's borrow lifetime, a future admission-
2199/// webhook rejection body whose per-arm `Box<str>` field composes
2200/// from a borrowed `&RestartPolicy` handle — reaches the
2201/// substrate-primitive [`RestartPolicy::as_str`] accessor through
2202/// this impl and no other, without a
2203/// `Box::<str>::from(policy.as_str())` open-code whose type bounds
2204/// have no compile-time link back to the substrate primitive.
2205///
2206/// Rust's standard library carries `impl From<&str> for Box<str>`
2207/// and `impl From<String> for Box<str>` but no blanket
2208/// `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
2209/// `Copy`-based `impl<T: Copy, U: From<&T> for U`), so every closed-
2210/// set fieldless typed enum peer on the substrate that carries the
2211/// paired owned-input `Box<str>` axis but not the borrowed-input
2212/// axis forces every borrowed-input `Box<str>`-parameterized call
2213/// site through a spurious [`Copy`] deref
2214/// (`Box::<str>::from((*policy).as_str())`) or a
2215/// `Box::<str>::from(policy.as_str())` open-code whose type bounds
2216/// have no compile-time link back to the substrate primitive.
2217///
2218/// Fourth (and closing) peer on the substrate-wide trait-idiomatic
2219/// [`Box<str>`] forward-projection family on the M2 OTP-shape tier
2220/// — closes the whole `{Self, &Self}` input-shape corner of the
2221/// [`Box<str>`] axis on both M2 OTP-shape sibling peers
2222/// ([`RestartStrategy`] and [`RestartPolicy`]), exactly as b4dc55c
2223/// closed the paired [`Cow<'static, str>`] axis one commit after
2224/// its owning half (0612398) landed on this enum. The remaining
2225/// fieldless-enum peers on the M3 mesh-shape / outside-M3 caixa-
2226/// core / render-side / outside-caixa-core tiers are the future
2227/// targets of the [`Box<str>`] campaign.
2228///
2229/// Pinned load-bearing by
2230/// [`tests::restart_policy_from_borrowed_into_box_str_routes_through_as_str_accessor`]
2231/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2232/// three-arm [`RestartPolicy::ALL`] emit-set on the borrowed-input
2233/// surface, plus a blanket-derived [`Into`] shape witness, a
2234/// cross-axis partition pin against the paired owned-input
2235/// [`From<RestartPolicy> for Box<str>`] and the sibling borrowed-
2236/// input `{&'static str, String, Cow<'static, str>}` return-shape
2237/// axes, and a `.iter().map(Box::<str>::from)` pipe witness over
2238/// [`RestartPolicy::ALL`] — whose iterator yields `&RestartPolicy`
2239/// by construction, so the borrowed-input [`Box<str>`] axis is
2240/// what routes the pipe through the substrate-primitive
2241/// [`RestartPolicy::as_str`] accessor without a spurious [`Copy`]
2242/// deref).
2243impl From<&RestartPolicy> for Box<str> {
2244 fn from(policy: &RestartPolicy) -> Box<str> {
2245 Box::<str>::from(policy.as_str())
2246 }
2247}
2248
2249// Fleet-wide dispatcher-catalog registrations for caixa's OTP
2250// supervisor surface — two more typed shadows over Erlang/OTP
2251// primitives the substrate now mechanically tracks (see
2252// theory/UNIFIED-COMPUTING-MODEL.md §VI for the roadmap +
2253// theory/TYPED-ABSORPTION.md for the absorption arc).
2254gen_platform::register_dispatcher!("caixa.restart-strategy", RestartStrategy);
2255gen_platform::register_dispatcher!("caixa.restart-policy", RestartPolicy);
2256
2257/// One child entry in the supervisor's `:children` list.
2258///
2259/// Every child references another caixa by `:caixa <nome>` + version
2260/// constraint. The supervisor materializes one ComputeUnit per entry.
2261#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2262#[serde(rename_all = "camelCase")]
2263pub struct ChildSpec {
2264 /// The child caixa's `:nome`. Must resolve via the same dependency
2265 /// resolution path as `:deps` (caixa-resolver).
2266 pub caixa: String,
2267
2268 /// Semver constraint (`"^0.1"`, `"~0.1.2"`, etc.) — same shape as
2269 /// [`crate::dep::Dep::versao`].
2270 pub versao: String,
2271
2272 /// Restart policy — an author-omitted slot degrades onto the
2273 /// substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`]
2274 /// (`permanent`, the Erlang/OTP worker-child default) through the
2275 /// [`Default for RestartPolicy`] impl this `#[serde(default)]` routes
2276 /// to.
2277 #[serde(default)]
2278 pub restart: RestartPolicy,
2279}
2280
2281impl ChildSpec {
2282 /// Substrate-canonical per-`:children` child-caixa `:nome` scalar
2283 /// accessor every consumer that reads the OTP-shape supervised
2284 /// child's identity keys off — returns the author-declared
2285 /// `:children :caixa` byte-string verbatim as a `&str`, borrowed
2286 /// from the typed slot's own [`String`] storage.
2287 ///
2288 /// The `:children :caixa` slot carries the DNS-1123 label — the
2289 /// child caixa's `:nome` — that every emitted cluster artifact
2290 /// derives its `metadata.name` from verbatim: the rendered
2291 /// `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name` per child, the
2292 /// [`crate::LABEL_PROGRAM`] label value on every child's pod
2293 /// identity, and the per-child K8s Service `metadata.name` the
2294 /// future wasm-operator (M3) provisions for inter-child supervision-
2295 /// tree wiring. Every downstream consumer that fans on the child's
2296 /// caixa-name keys off this scalar (the [`SupervisorSpec::validate`]
2297 /// per-child DNS-1123 gate at
2298 /// `require_valid_dns_1123_label(child.nome(), …)`, the per-child
2299 /// duplicate-detection [`crate::render::insert_first_seen`] key, the
2300 /// [`validate_no_self_supervision`] cross-slot equality check
2301 /// against the parent's `:nome`, every `SupervisorError` variant
2302 /// carrying the offending child caixa verbatim for `feira lint`
2303 /// rendering, the future wasm-operator's hierarchical reconciliation
2304 /// scheduler's per-child ComputeUnit-name projection, the future M4
2305 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2306 /// admission webhook).
2307 ///
2308 /// Prior to this lift the `.caixa` byte-string was accessed inline
2309 /// at seven sites in `supervisor.rs` — the DNS-1123 gate's
2310 /// `&child.caixa`, the four `SupervisorError::{ChildCaixaInvalid,
2311 /// EmptyChildVersion, ChildVersaoInvalid, DuplicateChildCaixa}`
2312 /// carriers' `child.caixa.clone()`, the dedup key's
2313 /// `child.caixa.as_str()`, and the [`validate_no_self_supervision`]
2314 /// `child.caixa == parent_nome` cross-slot check — seven open-coded
2315 /// field-accesses that expressed no compile-time link back to the
2316 /// typed slot. A future extension of the `:children :caixa` axis to
2317 /// a richer author surface (a per-cluster alias table the operator
2318 /// pins through a future `:placement`-scoped slot on the supervisor
2319 /// tree, a namespace-qualified rewrite the M4 CR materializer
2320 /// applies per-CR, a per-child overlay from the future `:children
2321 /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
2322 /// acknowledges) would have had to be threaded through every
2323 /// open-coded copy in lockstep or one consumer would silently
2324 /// disagree with the peers on which caixa a given child resolves to
2325 /// — a child-set lookup that treated the name as `"cart-worker"`
2326 /// while the peer duplicate-detector treated it as
2327 /// `"tenant-a/cart-worker"` would silently split the
2328 /// `DuplicateChildCaixa` membership-lookup diagnostic from the
2329 /// self-supervision detector's parent-equality check, a two-consumer
2330 /// split at the validator far from the source `caixa.lisp` with no
2331 /// field naming the identity-drift root cause. Lifting the resolution
2332 /// rule to a typed method on the substrate primitive means every
2333 /// downstream consumer of the Supervisor's per-`:children` identity
2334 /// surface reaches for exactly one typed dispatch — the resolver's
2335 /// accept-set migrates as a unit on any future axis addition.
2336 ///
2337 /// Sibling of the peer per-`:membros` [`crate::Membro::nome`]
2338 /// (4a32abf) member-caixa `:nome` scalar accessor on the M3
2339 /// mesh-slot surface — same "one typed dispatch on the substrate
2340 /// primitive, thin projections at each consumer" discipline extended
2341 /// onto the M2 supervisor-tree per-`:children` child-identity axis.
2342 /// The two typed axes (`Membro::nome` on the M3 Aplicacao side,
2343 /// `ChildSpec::nome` on the M2 Supervisor side) now share one
2344 /// accessor discipline for the shared substrate concept "another
2345 /// caixa referenced by `:nome`". Peer of the second M2 slot scalar
2346 /// accessor [`crate::UpgradeFromEntry::prior_versao`] (75d27a8) on
2347 /// the sibling per-`:upgrade-from :from` OTP-appup axis — the M2
2348 /// slot family's typed-accessor discipline now spans both the
2349 /// upgrade axis (`:upgrade-from`) and the supervision axis
2350 /// (`:children`), matching the closed M3 mesh-slot accessor family's
2351 /// shape. Named `nome()` to match the tatara-lisp author-surface
2352 /// term the field's docstring already reaches for ("The child
2353 /// caixa's `:nome`") and the peer [`crate::Membro::nome`] /
2354 /// [`crate::Caixa::nome`] / [`crate::dep::Dep::nome`] field-name
2355 /// discipline the substrate already carries — the accessor's name
2356 /// maps directly onto the canonical caixa-identity vocabulary rather
2357 /// than shadowing the field's storage-side `caixa` label.
2358 #[must_use]
2359 pub const fn nome(&self) -> &str {
2360 self.caixa.as_str()
2361 }
2362
2363 /// Substrate-canonical per-`:children` child-caixa `:versao` semver-
2364 /// requirement scalar accessor every consumer that reads the OTP-shape
2365 /// supervised child's version pin keys off — returns the author-declared
2366 /// `:children :versao` byte-string verbatim as a `&str`, borrowed from
2367 /// the typed slot's own [`String`] storage.
2368 ///
2369 /// The `:children :versao` slot carries the Cargo-shaped semver
2370 /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that pins
2371 /// which release of the supervised child caixa the OTP-shape supervisor
2372 /// tree materializes against — the same requirement grammar the peer
2373 /// `:deps :versao` / `:membros :versao` axes carry, resolved through the
2374 /// shared [`crate::render::require_valid_versao_requirement`] cascade
2375 /// and the shared [`crate::version::parse_requirement`] parser. Every
2376 /// downstream consumer that fans on the child's version pin keys off
2377 /// this scalar (the [`SupervisorSpec::validate`] per-child requirement
2378 /// gate at `require_valid_versao_requirement(child.versao_requirement(),
2379 /// …)`, the [`SupervisorError::ChildVersaoInvalid`] variant's carrier
2380 /// for `feira lint` rendering, every future per-cluster version-lock
2381 /// overlay the caixa-operator's hierarchical reconciliation scheduler
2382 /// pins through a future `:placement`-scoped supervisor-tree slot, the
2383 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2384 /// per-child version resolver, the future wasm-operator's per-child
2385 /// lacre BLAKE3-closure lookup at `ComputeUnit` materialization time).
2386 ///
2387 /// Prior to this lift the `.versao` byte-string was accessed inline at
2388 /// two `&str`-shaped sites in `caixa-core/src/supervisor.rs` — the
2389 /// [`SupervisorSpec::validate`] requirement-gate call
2390 /// `require_valid_versao_requirement(&child.versao, …)` and the
2391 /// [`SupervisorError::ChildVersaoInvalid`] carrier at
2392 /// `versao: child.versao.clone()` — two open-coded field-accesses that
2393 /// expressed no compile-time link back to the typed slot. A future
2394 /// extension of the `:children :versao` axis to a richer author surface
2395 /// (a per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
2396 /// flow, a lacre-projected concrete-version rewrite the operator
2397 /// materializes at CR-admission time, a future `:children :versao-lock`
2398 /// per-cluster override slot the wasm-operator's hierarchical
2399 /// reconciliation scheduler authors per-CR) would have had to be
2400 /// threaded through both open-coded copies in lockstep or one consumer
2401 /// would silently disagree with the peer on which release constraint a
2402 /// given child resolves to — the requirement-gate call reading
2403 /// `"^0.1"` while the error-body carrier read `"tenant-a-pin/^0.1"`
2404 /// would silently split the `ChildVersaoInvalid` diagnostic quote from
2405 /// the actual gate rejection input, a two-consumer split at the
2406 /// validator far from the source `caixa.lisp` with no field naming the
2407 /// version-pin drift root cause. Lifting the resolution rule to a typed
2408 /// method on the substrate primitive means every downstream
2409 /// requirement-facing consumer of the Supervisor's per-`:children`
2410 /// version-pin surface reaches for exactly one typed dispatch — the
2411 /// resolver's accept-set migrates as a unit on any future axis addition.
2412 ///
2413 /// Sibling of the peer per-`:membros` [`crate::Membro::versao_requirement`]
2414 /// (a40b0e3) member-caixa `:versao` scalar accessor on the M3 mesh-slot
2415 /// surface — same "one typed dispatch on the substrate primitive, thin
2416 /// projections at each consumer" discipline extended onto the M2
2417 /// supervisor-tree per-`:children` child-version-pin axis. The two typed
2418 /// axes (`Membro::versao_requirement` on the M3 Aplicacao side,
2419 /// `ChildSpec::versao_requirement` on the M2 Supervisor side) now share
2420 /// one accessor discipline for the shared substrate concept "another
2421 /// caixa referenced by a Cargo-shaped semver requirement". Peer of the
2422 /// sibling per-`:children` [`ChildSpec::nome`] (57c61d0) child-caixa
2423 /// `:nome` scalar accessor — the pair
2424 /// `(nome(), versao_requirement())` jointly projects the
2425 /// `(caixa, versao)` field pair every OTP-shape supervisor-tree consumer
2426 /// that fans on per-child identity + version pin keys off, closing the
2427 /// last unlifted per-`:children` `String`-carry axis so every downstream
2428 /// per-`:children` reader now routes through a typed dispatch on the
2429 /// substrate primitive. Named `versao_requirement()` rather than
2430 /// `versao()` because the field's storage-side `.versao` label is
2431 /// already the author-surface term (`:versao`); the accessor's name
2432 /// carries the semantic role — the semver *requirement* string the
2433 /// shared [`crate::version::parse_requirement`] entry-point consumes —
2434 /// so a raw field access and a typed dispatch read differently at every
2435 /// consumer site. Matches the peer [`crate::Membro::versao_requirement`]
2436 /// naming discipline verbatim.
2437 #[must_use]
2438 pub const fn versao_requirement(&self) -> &str {
2439 self.versao.as_str()
2440 }
2441
2442 /// Substrate-canonical per-`:children` `:restart` OTP-shaped
2443 /// per-child post-exit restart-decision policy scalar accessor every
2444 /// consumer that dispatches on the supervised child's post-exit
2445 /// reconcile posture keys off — returns the author-declared
2446 /// `:children :restart` variant verbatim as a [`RestartPolicy`],
2447 /// `Copy`-projected from the typed slot's own [`RestartPolicy`]
2448 /// storage.
2449 ///
2450 /// The `:children :restart` slot carries the closed-set OTP-shaped
2451 /// per-child restart-decision policy discriminator
2452 /// ([`RestartPolicy::Permanent`] — always restart, the OTP `permanent`
2453 /// worker-child default; [`RestartPolicy::Transient`] — restart only
2454 /// on abnormal exit, the OTP `transient` clean-completion-aware
2455 /// default; [`RestartPolicy::Temporary`] — never restart, the OTP
2456 /// `temporary` one-shot default) that every downstream consumer of
2457 /// the Supervisor's per-child post-exit reconcile branch keys off.
2458 /// Every future downstream consumer that fans on the per-child
2459 /// restart-decision keys off this scalar (the future `feira app
2460 /// graph` per-child restart column, the future wasm-operator's
2461 /// per-child post-exit restart-decision branch, the future M4
2462 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2463 /// admission webhook, the `caixa-operator`'s hierarchical
2464 /// reconciliation scheduler's per-child post-exit reconcile branch,
2465 /// the [`RestartPolicy::as_str`] `Serialize`-derive-pinning path the
2466 /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
2467 /// pin threads through).
2468 ///
2469 /// Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
2470 /// (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
2471 /// scalar accessor and the M3 mesh-slot
2472 /// [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
2473 /// [`crate::PlacementStrategy`] distribution-strategy scalar accessor
2474 /// — same "one typed dispatch on the substrate primitive,
2475 /// `Copy`-projected closed-set enum-arm discriminator that partitions
2476 /// the downstream renderer's per-arm fan-out" discipline extended
2477 /// onto the M2 supervisor-slot per-`:children` restart-decision-policy
2478 /// `Copy`-composite-enum scalar axis. Third axis on the per-`:children`
2479 /// [`ChildSpec`] type — companion to the sibling per-`:children`
2480 /// [`ChildSpec::nome`] (57c61d0) child-caixa `:nome` scalar accessor
2481 /// and the per-`:children` [`ChildSpec::versao_requirement`]
2482 /// (2c053c8) child-caixa `:versao` semver-requirement scalar accessor
2483 /// on the sibling `String`-carry axes. The triple
2484 /// `(nome(), versao_requirement(), restart())` jointly projects the
2485 /// `(caixa, versao, restart)` field trio every OTP-shape supervisor-
2486 /// tree consumer that fans on per-child identity + version pin +
2487 /// restart-decision keys off, closing the last unlifted per-`:children`
2488 /// axis so every downstream per-`:children` reader now routes through
2489 /// a typed dispatch on the substrate primitive. Named `restart()` to
2490 /// match the storage field's name and the author-surface
2491 /// `:children :restart` slot term verbatim; the accessor's identity
2492 /// name maps onto the canonical OTP-shape per-child restart-decision-
2493 /// policy vocabulary the [`RestartPolicy`] enum's docstring already
2494 /// carries.
2495 ///
2496 /// Declared `pub const fn` to close the last non-`const`
2497 /// `Copy`-return raw-field-getter posture on the M2
2498 /// per-`:children` [`ChildSpec`] substrate-primitive surface — peer
2499 /// of the sibling M2 per-`:supervisor`
2500 /// [`SupervisorSpec::estrategia`] (converted in this commit)
2501 /// `Copy`-composite-enum accessor, the sibling M2 per-`:supervisor`
2502 /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
2503 /// already lifted, and the peer M3 mesh-slot per-`:entrada`
2504 /// [`crate::Entrada::port`] (bafa004) / per-`:placement`
2505 /// [`crate::Placement::estrategia`] (bafa004) `Copy`-return
2506 /// `pub const fn` scalar accessors on the sibling M3 surface. Every
2507 /// downstream substrate-side `const`-context consumer of the
2508 /// per-`:children` restart-decision-policy scalar (a future
2509 /// module-scope `const _:() = assert!(matches!(child.restart(),
2510 /// RestartPolicy::Permanent))` invariant pin on a typed fixture, a
2511 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
2512 /// admission-webhook `const fn` per-child restart-decision floor
2513 /// over a typed [`ChildSpec`], any future `const fn` supervisor-tree
2514 /// composer over the substrate primitive that fans on the per-child
2515 /// restart-decision policy at compile time) now reaches through the
2516 /// same typed dispatch on the substrate primitive at const-eval
2517 /// time as at runtime. A future non-`Copy`-return promotion of the
2518 /// scalar (an `Option<RestartPolicy>`-shape migration on the
2519 /// per-child restart-decision axis once heterogeneous per-cluster
2520 /// restart-policy overlays land, a per-tenant restart-policy-alias
2521 /// table the M4 CR materializer resolves per-CR) that would drop
2522 /// the `const` qualifier fails the fail-before-pass-after pin
2523 /// [`tests::child_spec_restart_accessor_is_const_fn`] at caixa-core
2524 /// build time rather than surfacing as a downstream consumer
2525 /// regression.
2526 #[must_use]
2527 pub const fn restart(&self) -> RestartPolicy {
2528 self.restart
2529 }
2530}
2531
2532/// Supervisor-typed slots that live alongside the standard Caixa
2533/// fields when `:kind Supervisor`. Held flat in [`crate::Caixa`] so
2534/// the manifest stays a single typed form; this struct exists for
2535/// validation + conversion.
2536#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2537#[serde(rename_all = "camelCase")]
2538pub struct SupervisorSpec {
2539 /// Restart strategy. Defaults to [`RestartStrategy::OneForOne`].
2540 #[serde(default)]
2541 pub estrategia: RestartStrategy,
2542
2543 /// Max restarts within [`Self::restart_window`] before the
2544 /// supervisor itself terminates (and its parent supervisor decides
2545 /// what to do). Default 5.
2546 #[serde(default = "default_max_restarts")]
2547 pub max_restarts: u32,
2548
2549 /// Sliding window for `max_restarts`. Authored as a duration
2550 /// string (`"60s"`, `"5m"`); absent = "never reset". A `Some(0s)`
2551 /// is rejected by [`Self::validate`] — Erlang/OTP's
2552 /// `MaxIntensity / Period` invariant requires a positive window
2553 /// (a zero-period supervisor either trips on the first failure or
2554 /// never trips, depending on operator interpretation, neither of
2555 /// which is the author's intent). Omit the slot to express "no
2556 /// reset"; carry a positive duration to express the sliding window.
2557 #[serde(
2558 default,
2559 skip_serializing_if = "Option::is_none",
2560 with = "duration_codec"
2561 )]
2562 pub restart_window: Option<Duration>,
2563
2564 /// Static children. Empty for `SimpleOneForOne` (children added
2565 /// dynamically); required for the other three strategies.
2566 #[serde(default)]
2567 pub children: Vec<ChildSpec>,
2568}
2569
2570const fn default_max_restarts() -> u32 {
2571 // Route the private serde-`#[serde(default = "…")]` helper through
2572 // the substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] typed
2573 // `pub const` rather than the raw `5` literal — one source of truth
2574 // for the Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
2575 // default across the two production consumers that currently
2576 // dispatch on it (this helper via `#[serde(default = "…")]` on
2577 // `SupervisorSpec::max_restarts` and the [`Default for SupervisorSpec`]
2578 // impl at line 962). Pinned by
2579 // `default_max_restarts_helper_routes_through_lifted_default` +
2580 // `supervisor_spec_default_max_restarts_routes_through_lifted_default`
2581 // in the tests module; peer of the sibling caixa-core
2582 // [`crate::manifest::Caixa::supervisor_view`] `unwrap_or(…)` fold
2583 // that now routes its author-omitted `:max-restarts` arm through
2584 // the same lifted constant.
2585 SUPERVISOR_MAX_RESTARTS_DEFAULT
2586}
2587
2588/// Substrate-canonical Erlang/OTP-shaped `MaxIntensity` restart-budget-
2589/// count default for the `:supervisor :max-restarts` axis — the
2590/// canonical `{intensity, 5, 60}` `MaxIntensity` half of Learn You Some
2591/// Erlang's worker-supervisor default, extracted as a typed `pub const`
2592/// so every substrate-side consumer that resolves "what
2593/// [`SupervisorSpec::max_restarts`] value does an author-omitted
2594/// `:max-restarts` slot degrade onto?" reaches for exactly one
2595/// substrate-primitive `u32`.
2596///
2597/// The `:max-restarts` default axis has two production consumers on the
2598/// substrate side today (both prior to this lift folded onto raw `5`
2599/// literals with no compile-time link back to a shared truth): the
2600/// serde-`#[serde(default = "default_max_restarts")]` helper on
2601/// [`SupervisorSpec::max_restarts`] that every author-omitted
2602/// `:supervisor :max-restarts` slot lands in past the derive-macro's
2603/// wire-format compose, and the [`crate::manifest::Caixa::supervisor_view`]
2604/// `.max_restarts().unwrap_or(5)` fold that every downstream consumer of
2605/// the composed [`SupervisorSpec`] altitude reaches through
2606/// (`feira app graph`, the future wasm-operator's per-supervisor
2607/// restart-intensity counter, the future M4
2608/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2609/// webhook, the caixa-operator's hierarchical reconciliation scheduler).
2610/// A pair of open-coded `5`s across two files that expressed no
2611/// compile-time link back to the shared OTP-canonical default — a
2612/// future rebrand of the default (a tightening to Elixir's
2613/// `Supervisor.max_restarts: 3`, a widening to a per-cluster overlay
2614/// the operator pins through a future
2615/// `:supervisor :max-restarts-overrides` slot the MESH-COMPOSITION
2616/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
2617/// plain `u32` count to a richer `{MaxR, MaxT}` per-child-cohort
2618/// restart-budget-partition once the INSPIRATIONS §II.2 Erlang/OTP
2619/// per-child-cohort roadmap lands) would have had to be threaded
2620/// through both open-coded copies in lockstep or the wire-format
2621/// author-omitted arm and the view-construction author-omitted arm
2622/// would silently disagree on which restart-budget an omitted
2623/// `:max-restarts` resolves to (an author writing `:supervisor
2624/// (:max-restarts ())` would round-trip through serde with the new
2625/// default while `supervisor_view` silently continued to compose the
2626/// stale `5`, or vice versa), a two-consumer split at the composition
2627/// boundary far from the source `caixa.lisp` with no field naming the
2628/// default-drift root cause. Lifting the resolution rule to a typed
2629/// `pub const` on the substrate primitive means every downstream
2630/// consumer of the per-Supervisor default-restart-budget-count surface
2631/// reaches for exactly one substrate-primitive `u32` — the resolver's
2632/// accepted value migrates as a unit on any future axis change.
2633///
2634/// The `5` value pins Learn You Some Erlang's `{intensity, 5, 60}`
2635/// worker-supervisor default (the closest canonical OTP-shape
2636/// production reference the substrate carries, matching the sibling
2637/// `60s` `Period` default the [`Default for SupervisorSpec`] impl pairs
2638/// this constant with on the paired sliding-window axis). Two orders of
2639/// magnitude below the [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` ceiling
2640/// (the upper bracket on the same axis, sibling of this lower default;
2641/// both are typed `u32` const bounds on the `:supervisor :max-restarts`
2642/// axis and now share one accessor discipline on the substrate) and
2643/// above the OTP-`supervisor` callback-module `MaxR = 1` minimum-
2644/// restart floor — the "one restart, then escalate" default is
2645/// deliberately loose enough to absorb a short burst of transient
2646/// child failures without escalating past the supervisor's parent
2647/// while remaining tight enough to trip the `MaxIntensity / Period`
2648/// ratio's escalation on a genuinely-stuck child within the sibling
2649/// `60s` sliding window.
2650///
2651/// Lifted as a typed `pub const` so the bound has exactly one source
2652/// of truth — the serde-side wire-format author-omitted arm at
2653/// [`default_max_restarts`], the [`Default for SupervisorSpec`] impl's
2654/// struct-literal default field, and the caixa-core
2655/// [`crate::manifest::Caixa::supervisor_view`] fold's author-omitted
2656/// arm all read from one place. Same shape every other typed default
2657/// in this crate carries (the sibling
2658/// [`SUPERVISOR_MAX_RESTARTS_MAX`] upper cap on the same axis, the
2659/// paired [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the
2660/// sibling `:restart-window` axis, and the peer
2661/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
2662/// per-renderer defaults on the caixa-flux / caixa-helm rendering
2663/// axes).
2664pub const SUPERVISOR_MAX_RESTARTS_DEFAULT: u32 = 5;
2665
2666/// Upper-bound ceiling on the `:supervisor :max-restarts` axis — every
2667/// validated [`SupervisorSpec::max_restarts`] past
2668/// [`SupervisorSpec::validate`] lies in `1..=SUPERVISOR_MAX_RESTARTS_MAX`.
2669///
2670/// The typed field is `u32` (the zero-floor arm
2671/// [`SupervisorError::ZeroMaxRestarts`] already brackets the bottom edge),
2672/// so a programmatic struct literal
2673/// (`SupervisorSpec { max_restarts: u32::MAX, .. }`) and the equivalent
2674/// author-surface form (`:max-restarts 4294967295` or any
2675/// `:max-restarts 100000`-shape typo landing in the slot) both round-trip
2676/// cleanly through serde — a structurally unbounded `u32` ceiling. The
2677/// runtime substrate consuming the value (Erlang/OTP's
2678/// `MaxIntensity / Period` ratio, the future wasm-operator's
2679/// per-supervisor restart-intensity counter, the M4
2680/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook)
2681/// then turned a typed `:max-restarts` policy into a no-op supervisor: the
2682/// escalation threshold is structurally so high that no realistic
2683/// restarts-per-`:restart-window` traffic shape can reach it, the
2684/// supervisor never escalates to its parent, and a bad child can loop
2685/// inside the window indefinitely with the parent supervisor structurally
2686/// never receiving the "this subtree has exceeded its restart budget"
2687/// signal the typed slot is meant to express — the canonical
2688/// "supervisor intensity declared, no escalation" footgun, exactly the
2689/// peer of the [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap
2690/// on the `:politicas :circuit-breaker :max-failures` axis (both are
2691/// "trip the next-higher protection layer after N events in a rolling
2692/// window" counters with identical degenerate-at-the-high-end shape).
2693///
2694/// The `1000` ceiling matches the sibling
2695/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] (the closest
2696/// peer — same "events-per-window trip threshold" semantics, same `u32`
2697/// type, same no-op-at-the-high-end failure mode) so the M4
2698/// `mesh.pleme.io/v1alpha1/Supervisor` / `.../Aplicacao` CR materializers
2699/// and the future wasm-operator's per-supervisor restart-intensity
2700/// counter reach for either field knowing the value is in `1..=1000`
2701/// without re-validating at the reconciler layer. The cap sits two
2702/// orders of magnitude above every documented Erlang/OTP production
2703/// playbook recommendation (Learn You Some Erlang's
2704/// `{intensity, 5, 60}` worker-supervisor default, Elixir's `Supervisor`
2705/// `max_restarts: 3` default, OTP's `supervisor` callback module
2706/// `MaxR = 1` / `MaxT = 5` "minimal-restart" default, Riak Core's
2707/// typical `MaxR ∈ 5..=100`, RabbitMQ's broker-supervisor `MaxR = 5`
2708/// default) and below the clearly-pathological "effectively no
2709/// escalation" floor (`10_000`, `100_000`, `u32::MAX`): a value the
2710/// author can plausibly want at hyperscale (a long-running supervisor
2711/// over a very-flaky pool tolerating thousands of transient restarts
2712/// before escalating), but a hard wall above which the typed policy is
2713/// structurally a no-op carried verbatim on every emitted child-restart
2714/// reconciliation contract.
2715///
2716/// Lifted as a typed `pub const` so the bound has exactly one source of
2717/// truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
2718/// materializer's admission webhook and the wasm-operator-side
2719/// per-supervisor restart-intensity reconciler read from one place. Same
2720/// shape every other typed upper bound in this crate carries
2721/// ([`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
2722/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
2723/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
2724/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2725/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2726/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2727pub const SUPERVISOR_MAX_RESTARTS_MAX: u32 = 1000;
2728
2729/// Upper-bound ceiling on the `:supervisor :restart-window` axis —
2730/// every validated `Some(`[`SupervisorSpec::restart_window`]`)` past
2731/// [`SupervisorSpec::validate`] lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
2732/// (inclusive on both ends, integer-millisecond magnitudes by the
2733/// canonical-form gate immediately preceding).
2734///
2735/// The typed field is `Option<Duration>` (the zero-floor arm
2736/// [`SupervisorError::RestartWindowZero`] already rejects
2737/// `Some(Duration::ZERO)`, and the canonical-form arm
2738/// [`SupervisorError::RestartWindowNotCanonical`] already rejects
2739/// sub-millisecond residue), so a programmatic struct literal
2740/// (`SupervisorSpec { restart_window: Some(Duration::from_secs(86_400)),
2741/// .. }` — 24h) and the equivalent author-surface form
2742/// (`(:supervisor (:restart-window "24h"))` — the shared duration codec
2743/// emits `"<n>h"` for any integer-hour magnitude) both round-trip
2744/// cleanly through serde — a structurally unbounded `Duration` ceiling.
2745/// A `:restart-window` value far above the documented Erlang/OTP
2746/// `MaxIntensity / Period` production-playbook band (Learn You Some
2747/// Erlang's `{intensity, 5, 60}` worker-supervisor `Period = 60s`
2748/// default, Elixir's `Supervisor` `max_seconds: 5` default, OTP's
2749/// `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's
2750/// `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default)
2751/// degenerates the supervisor's restart-intensity counter into a
2752/// lifetime counter: the rolling failure-counting window is structurally
2753/// so long that transient restarts are never forgotten, so the
2754/// `MaxIntensity / Period` ratio degenerates from "trip the parent
2755/// supervisor when the child has exceeded its restart budget *within
2756/// the recent window*" to "trip the parent when the child has exceeded
2757/// its restart budget *over its lifetime*" — every transient restart
2758/// counts against the budget forever, the supervisor's reset semantic
2759/// never reaches the child, and the typed `:restart-window` slot
2760/// becomes a no-op rolling window carried on every emitted hierarchical
2761/// reconciliation contract. The canonical
2762/// rolling-window-degenerates-to-lifetime-counter footgun the sibling
2763/// [`crate::POLICY_BREAKER_WINDOW_MAX`] cap closes on the peer
2764/// `:politicas :circuit-breaker :window` axis with identical shape (both
2765/// are "rolling failure-counting window with a per-`Period` reset" Duration
2766/// axes whose lifetime-counter degenerate at the high end is the same
2767/// "the reset semantic never fires" CSE invariant violation).
2768///
2769/// The `1h` (3600s = `3_600_000` ms) ceiling matches the largest unit
2770/// the shared duration codec emits (`"<n>h"` for any integer-hour
2771/// magnitude) — every value in the canonical authoring form's
2772/// `<integer><unit>` grammar at or below this cap renders to a clean
2773/// canonical string — and matches the three sibling typed-`Duration`
2774/// caps already lifted to this surface
2775/// ([`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
2776/// [`crate::POLICY_BREAKER_WINDOW_MAX`]). All four typed-`Duration`
2777/// axes — per-process `:limits :wall-clock`, per-edge `:politicas
2778/// :timeout`, per-breaker `:politicas :circuit-breaker :window`, and
2779/// per-supervisor `:supervisor :restart-window` — now share a single
2780/// uniform top edge at the codec's largest emitted unit so the next
2781/// typed-slot wiring (the future wasm-operator's per-supervisor
2782/// `MaxIntensity / Period` reconciler, the M4
2783/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2784/// webhook, the `caixa-operator`'s hierarchical reconciliation
2785/// scheduler) reaches for any of the four knowing the value is in
2786/// `1ms..=1h` without re-validating at the renderer layer. The cap sits
2787/// two orders of magnitude above every documented Erlang/OTP / Elixir /
2788/// Riak Core / RabbitMQ production-playbook recommendation band
2789/// (`5s..=300s`) and below the clearly-pathological "rolling window
2790/// degenerates to lifetime counter" floor (`24h`, `7d`, `Duration::MAX`):
2791/// a value the author can plausibly want for a very-low-traffic
2792/// long-tail failure-restart window over a hyperscale-flaky child pool,
2793/// but a hard wall above which the rolling-window contract is
2794/// structurally a lifetime-counter contract.
2795///
2796/// Lifted as a typed `pub const` so the bound has exactly one source
2797/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
2798/// materializer's admission webhook, the wasm-operator-side
2799/// per-supervisor `MaxIntensity / Period` reconciler, and the
2800/// `caixa-operator`'s hierarchical reconciliation scheduler all read
2801/// from one place. Same shape every other typed upper bound in this
2802/// crate carries ([`SUPERVISOR_MAX_RESTARTS_MAX`],
2803/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
2804/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
2805/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
2806/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
2807/// [`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
2808/// [`crate::POLICY_BREAKER_WINDOW_MAX`],
2809/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
2810/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
2811pub const SUPERVISOR_RESTART_WINDOW_MAX: Duration = Duration::from_secs(3600);
2812
2813/// Substrate-canonical Erlang/OTP-shaped `Period` sliding-window-duration
2814/// default for the `:supervisor :restart-window` axis — the canonical
2815/// `{intensity, 5, 60}` `Period` half of Learn You Some Erlang's
2816/// worker-supervisor default, extracted as a typed `pub const` so every
2817/// substrate-side consumer that resolves "what
2818/// [`SupervisorSpec::restart_window`] value does an author-omitted
2819/// `:restart-window` slot degrade onto?" reaches for exactly one
2820/// substrate-primitive [`Duration`].
2821///
2822/// The `:restart-window` default axis has one production consumer on the
2823/// substrate side today: the [`Default for SupervisorSpec`] impl's
2824/// struct-literal `restart_window` field, which prior to this lift folded
2825/// onto a raw `Duration::from_secs(60)` literal with no compile-time link
2826/// back to the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity`
2827/// half of the same `{intensity, 5, 60}` OTP-canonical default. The
2828/// [`crate::manifest::Caixa::supervisor_view`] fold deliberately does
2829/// *not* fall back to this default on the sibling `:restart-window` axis
2830/// — an author-omitted `:supervisor :restart-window` composes to
2831/// `restart_window: None` (the shared codec's soft-swallow shape),
2832/// keeping author-declared intent ("no reset — never escalate on rolling
2833/// window") distinct from the [`Default for SupervisorSpec`] "canonical
2834/// 60s Period" arm every programmatic `SupervisorSpec::default()` caller
2835/// resolves to. Prior to this lift the paired `{intensity, 5, 60}` OTP
2836/// default was split across two files with no compile-time link between
2837/// the halves: [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] pinned the
2838/// `MaxIntensity` half at the substrate primitive while the `Period`
2839/// half rode as an open-coded literal at the composition site, so a
2840/// future coherent rebrand of the paired canonical (a tightening to
2841/// Elixir's `{max_restarts: 3, max_seconds: 5}`, a widening to a
2842/// per-cluster overlay the operator pins through a future
2843/// `:supervisor :restart-window-overrides` slot the MESH-COMPOSITION
2844/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
2845/// paired constants to a per-child-cohort `{MaxR, MaxT}` restart-budget-
2846/// partition once the INSPIRATIONS §II.2 Erlang/OTP per-child-cohort
2847/// roadmap lands) would have had to migrate the `MaxIntensity` half
2848/// through the lifted constant and the `Period` half through a raw
2849/// literal in lockstep or the two halves of the same OTP-canonical
2850/// default would silently drift out of pairing. Lifting the resolution
2851/// rule to a typed `pub const` on the substrate primitive means the
2852/// paired OTP-canonical default migrates as one unit on any future
2853/// axis change.
2854///
2855/// The `60s` value pins Learn You Some Erlang's `{intensity, 5, 60}`
2856/// worker-supervisor default (the closest canonical OTP-shape
2857/// production reference the substrate carries, matching the paired
2858/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5` `MaxIntensity` half this
2859/// constant is the `Period` denominator of on the same
2860/// `MaxIntensity / Period` restart-intensity ratio). Two orders of
2861/// magnitude below the [`SUPERVISOR_RESTART_WINDOW_MAX`] `3600s`
2862/// (`1h`) ceiling (the upper bracket on the same axis, sibling of
2863/// this lower default; both are typed [`Duration`] const bounds on the
2864/// `:supervisor :restart-window` axis and now share one accessor
2865/// discipline on the substrate) and above the OTP-`supervisor`
2866/// callback-module `MaxT = 5` seconds "minimal-window" floor — the "60s
2867/// rolling window" default is deliberately loose enough to absorb a
2868/// short burst of transient child failures without escalating past the
2869/// supervisor's parent while remaining tight enough for the paired
2870/// `MaxIntensity / Period` ratio's escalation to trip on a genuinely-
2871/// stuck child within a human-scale observation window.
2872///
2873/// Lifted as a typed `pub const` so the paired OTP-canonical default has
2874/// exactly one source of truth on each half — the sibling
2875/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half and this
2876/// `Period` `60s` half now share the same substrate-primitive lift
2877/// discipline. Same shape every other typed default in this crate
2878/// carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] paired
2879/// `MaxIntensity` half on the same OTP-canonical `{intensity, 5, 60}`,
2880/// the sibling [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the same
2881/// axis, and the peer [`crate::render::DEFAULT_NAMESPACE`] /
2882/// [`crate::render::DEFAULT_LIBRARY_NAME`] per-renderer defaults on the
2883/// caixa-flux / caixa-helm rendering axes).
2884pub const SUPERVISOR_RESTART_WINDOW_DEFAULT: Duration = Duration::from_secs(60);
2885
2886/// Substrate-canonical Erlang/OTP-shaped sibling-restart-strategy default
2887/// for the `:supervisor :estrategia` axis — the canonical `one_for_one`
2888/// half of Learn You Some Erlang's `{one_for_one, intensity, 5, 60}`
2889/// worker-supervisor default, extracted as a typed `pub const` so every
2890/// substrate-side consumer that resolves "what
2891/// [`SupervisorSpec::estrategia`] variant does an author-omitted
2892/// `:estrategia` slot degrade onto?" reaches for exactly one substrate-
2893/// primitive [`RestartStrategy`].
2894///
2895/// The `:estrategia` default axis has three production consumers on the
2896/// substrate side today: the [`Default for RestartStrategy`] impl's
2897/// return arm, the [`Default for SupervisorSpec`] impl's struct-literal
2898/// `estrategia` field, and the
2899/// [`crate::manifest::Caixa::supervisor_view`] fold's
2900/// `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)` `Option<RestartStrategy>`
2901/// collapse arm — three entry points onto the same OTP-canonical
2902/// `one_for_one` value that prior to this lift folded onto a raw
2903/// `Self::OneForOne` arm at the [`Default for RestartStrategy`] impl and
2904/// implicit `RestartStrategy::default()` routes at the sibling consumers,
2905/// with no compile-time link back to the paired
2906/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` half + the paired
2907/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` half of the same
2908/// `{one_for_one, intensity, 5, 60}` OTP-canonical default. The paired
2909/// triple was split across three altitudes with no compile-time link
2910/// between the halves: the `MaxIntensity` half rode through the lifted
2911/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant (b698ec0) and the `Period`
2912/// half rode through the lifted [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2913/// constant (f7dcd0e) while the `one_for_one` half rode as an open-coded
2914/// discriminator at the [`Default for RestartStrategy`] impl, so a future
2915/// coherent rebrand of the triple (Elixir's `{:one_for_one,
2916/// max_restarts: 3, max_seconds: 5}` — same strategy, different
2917/// intensity/period; an OTP `rest_for_one` widening once the substrate
2918/// discovers startup-order-coupled child cohorts as the more common
2919/// worker-supervisor default; a per-cluster overlay the operator pins
2920/// through a future `:estrategia-overrides` slot the MESH-COMPOSITION
2921/// §III.2 supervision-canary roadmap acknowledges) would have had to
2922/// migrate the `MaxIntensity` + `Period` halves through the lifted
2923/// constants and the `one_for_one` half through an open-coded arm in
2924/// lockstep or the three halves of the same OTP-canonical default would
2925/// silently drift out of pairing. Lifting the resolution rule to a typed
2926/// `pub const` on the substrate primitive means the paired OTP-canonical
2927/// worker-supervisor default migrates as one unit on any future axis
2928/// change.
2929///
2930/// The [`RestartStrategy::OneForOne`] value pins Learn You Some Erlang's
2931/// `{one_for_one, intensity, 5, 60}` worker-supervisor default (the
2932/// closest canonical OTP-shape production reference the substrate
2933/// carries, matching the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5`
2934/// `MaxIntensity` half and the paired [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2935/// `60s` `Period` half). The `one_for_one` strategy — restart only the
2936/// failed child, leaving siblings untouched — is the default for tree-of-
2937/// independent-workers use cases the substrate's [`RestartStrategy`]
2938/// discriminator's own docstring already carries as the default arm; it
2939/// composes with the `{5, 60}` restart-intensity ratio to name the same
2940/// substrate-canonical "canonical worker-supervisor" shape the paired
2941/// halves close on their respective axes.
2942///
2943/// Lifted as a typed `pub const` so the paired OTP-canonical default has
2944/// exactly one source of truth on each of its three halves — the sibling
2945/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half, the
2946/// sibling [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` `60s` half, and
2947/// this `one_for_one` strategy half now share the same substrate-
2948/// primitive lift discipline. Same shape every other typed default in
2949/// this crate carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] +
2950/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] paired halves on the same OTP-
2951/// canonical `{one_for_one, intensity, 5, 60}`, the sibling
2952/// [`SUPERVISOR_MAX_RESTARTS_MAX`] + [`SUPERVISOR_RESTART_WINDOW_MAX`]
2953/// upper caps on the paired sibling axes, and the peer
2954/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
2955/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes).
2956pub const SUPERVISOR_ESTRATEGIA_DEFAULT: RestartStrategy = RestartStrategy::OneForOne;
2957
2958/// Substrate-canonical Erlang/OTP-shaped per-child restart-decision-policy
2959/// default for the `:children :restart` axis — the OTP `permanent`
2960/// worker-child default (`{ChildId, StartFunc, permanent, …}` in a
2961/// `supervisor`'s `init/1` child-spec tuple), extracted as a typed
2962/// `pub const` so every substrate-side consumer that resolves "what
2963/// [`ChildSpec::restart`] variant does an author-omitted `:children
2964/// :restart` slot degrade onto?" reaches for exactly one substrate-
2965/// primitive [`RestartPolicy`].
2966///
2967/// Completes the OTP-shape supervisor-tree default set at the substrate
2968/// primitive. The per-`:supervisor` axis already carries all three of its
2969/// halves as lifted typed constants — [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
2970/// (`one_for_one`, 95ffacc), [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
2971/// (`MaxIntensity` `5`, b698ec0), [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2972/// (`Period` `60s`, f7dcd0e) — while the per-`:children` axis's own
2973/// OTP-canonical default rode as an open-coded `Self::Permanent` arm in
2974/// the [`Default for RestartPolicy`] impl, the last un-lifted default on
2975/// the M2 `:supervisor` slot family. The split mattered because the two
2976/// axes resolve *together* on every author-omitted supervisor: a
2977/// `(defcaixa :kind Supervisor :children ((:caixa "worker" :versao
2978/// "^0.1")))` with no `:estrategia` and no per-child `:restart` degrades
2979/// onto `{one_for_one, 5, 60}` through three lifted constants and onto
2980/// `permanent` through an open-coded enum arm, so a future coherent
2981/// rebrand of the OTP-shape default set (an Elixir-shaped
2982/// `{:one_for_one, max_restarts: 3, max_seconds: 5}` tightening, a
2983/// per-cluster overlay the operator pins through the MESH-COMPOSITION
2984/// §III.2 supervision-canary roadmap slots, an OTP-`transient` widening
2985/// once the substrate discovers clean-completion-aware children as the
2986/// more common child shape) would have had to migrate three halves
2987/// through typed constants and the fourth through a raw enum arm in
2988/// lockstep or the supervisor-level and child-level defaults would
2989/// silently drift apart.
2990///
2991/// The `:children :restart` default axis has two production consumers on
2992/// the substrate side today: the [`Default for RestartPolicy`] impl's
2993/// return arm, and the serde-side `#[serde(default)]` on
2994/// [`ChildSpec::restart`] that resolves an author-omitted `:children
2995/// :restart` slot through that same impl. Both now key off this one
2996/// substrate primitive, so the future wasm-operator's per-child post-exit
2997/// restart-decision branch, the future M4
2998/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2999/// admission webhook, and the `caixa-operator`'s hierarchical
3000/// reconciliation scheduler's per-child fan-out all reach for one typed
3001/// identifier when they resolve an omitted per-child restart posture.
3002///
3003/// The [`RestartPolicy::Permanent`] value pins Erlang/OTP's `permanent`
3004/// worker-child restart type — always restart the child regardless of how
3005/// it died, the canonical posture for long-running services that must
3006/// always be up, matching the sibling [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
3007/// `one_for_one` tree-of-independent-workers strategy this constant pairs
3008/// with under the same `{one_for_one, intensity, 5, 60}` worker-supervisor
3009/// shape. The two alternatives the closed [`RestartPolicy::ALL`] accept-set
3010/// carries ([`RestartPolicy::Transient`] — restart only on abnormal exit;
3011/// [`RestartPolicy::Temporary`] — never restart) express deliberate
3012/// one-shot / clean-completion-aware postures an author declares
3013/// explicitly, never a posture an omitted slot should silently assume.
3014pub const SUPERVISOR_CHILD_RESTART_DEFAULT: RestartPolicy = RestartPolicy::Permanent;
3015
3016/// Route the manually-authored [`Default`] impl on [`SupervisorSpec`]
3017/// through the substrate-canonical [`SupervisorSpec::otp_canonical`]
3018/// `pub const fn` constructor rather than a struct-literal cascade over
3019/// the paired [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
3020/// [`default_max_restarts`] / [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3021/// lifted consts — one source of truth for the Erlang/OTP-canonical
3022/// `{one_for_one, 5, 60}` worker-supervisor baseline across the two
3023/// paths every downstream consumer already reaches through (the
3024/// hand-authored-until-now [`Default::default`] the
3025/// `..SupervisorSpec::default()` struct-update-syntax on every
3026/// one-axis-under-test fixture in this crate's test module rests on,
3027/// and the `pub const fn` [`SupervisorSpec::otp_canonical`] constructor
3028/// every `const`-context consumer reaches through).
3029///
3030/// Extends the [`Default`]-through-const-ctor fold discipline the
3031/// [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
3032/// (abd52c2), [`crate::aplicacao::MeshPolicy`]
3033/// [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`] (91641a4),
3034/// and [`crate::BehaviorSpec`]
3035/// [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c) folds
3036/// closed on the M2 / M3 `Option`-only "canonical unset baseline"
3037/// typed-slot spec family — extended here onto the M2 supervisor-slot
3038/// [`SupervisorSpec`] whose canonical baseline is not "everything
3039/// `None`" but the OTP-canonical `{one_for_one, 5, 60}` worker-
3040/// supervisor triple. The `empty()` peer's naming did not fit
3041/// (`SupervisorSpec` carries a discriminator-shaped `estrategia` field
3042/// and a non-zero `max_restarts`/`restart_window` pair whose canonical
3043/// shape is Erlang/OTP-descended, not the "no axis declared" bottom
3044/// the sibling `Option`-only slots fold to), so this peer is named
3045/// [`SupervisorSpec::otp_canonical`] instead — the same phrasing the
3046/// existing per-arm pin tests
3047/// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`] /
3048/// [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`] /
3049/// [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
3050/// already reach for. Pinned load-bearing by
3051/// [`tests::supervisor_spec_default_routes_through_otp_canonical_ctor`]
3052/// (byte-parity pin against [`SupervisorSpec::otp_canonical`] under
3053/// [`PartialEq`], sharpening the sibling
3054/// `supervisor_spec_default_*_routes_through_lifted_default` per-arm
3055/// pins from a per-field lift into a whole-struct one-source-of-truth
3056/// pin — the derived-until-now [`Default::default`] and the
3057/// [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
3058/// construction, not by coincidence).
3059impl Default for SupervisorSpec {
3060 #[inline]
3061 fn default() -> Self {
3062 Self::otp_canonical()
3063 }
3064}
3065
3066impl SupervisorSpec {
3067 /// `const`-context peer of the [`Default for SupervisorSpec`]
3068 /// impl (which routes through this constructor) — returns the
3069 /// Erlang/OTP-canonical `{one_for_one, 5, 60}` worker-supervisor
3070 /// baseline this crate reaches for in every fixture-builder
3071 /// `..SupervisorSpec::default()` struct-update expression and
3072 /// every downstream `SupervisorSpec::default()` seed.
3073 ///
3074 /// Each field routes through the same substrate-canonical
3075 /// [`SUPERVISOR_ESTRATEGIA_DEFAULT`] / [`default_max_restarts`] /
3076 /// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] lifted consts the
3077 /// per-arm pin tests
3078 /// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`]
3079 /// / [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`]
3080 /// / [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
3081 /// already assert, so a future coherent rebrand of the OTP-canonical
3082 /// triple (Elixir's `{max_restarts: 3, max_seconds: 5}`, a per-
3083 /// cluster overlay via a future `:restart-window-overrides` slot, a
3084 /// per-child-cohort promotion the INSPIRATIONS.md §II.2 Erlang/OTP
3085 /// absorption roadmap acknowledges) migrates through three typed
3086 /// constants in lockstep, and the paired [`Default`] impl inherits
3087 /// every future extension by construction.
3088 ///
3089 /// `pub const fn` rather than the derived-style `Default::default`
3090 /// or a `pub const SUPERVISOR_SPEC_DEFAULT: SupervisorSpec` item —
3091 /// [`Default::default`] is not `const` on stable Rust, and
3092 /// `SupervisorSpec` is non-`Copy` so a `pub const` item would force
3093 /// every consumer through a [`Clone::clone`]. The `pub const fn`
3094 /// discipline lets `const`-context callers construct the OTP-
3095 /// canonical baseline at compile time without runtime dispatch on
3096 /// the derived [`Default::default`], the same posture the sibling
3097 /// [`crate::LimitsSpec::empty`] (9739971) /
3098 /// [`crate::aplicacao::MeshPolicy::empty`] (6df969b) /
3099 /// [`crate::BehaviorSpec::empty`] (f9b18e3) `Option`-only typed-slot
3100 /// spec `pub const fn` constructors carry on the sibling
3101 /// "everything `None`" baseline axis.
3102 ///
3103 /// Fourth peer on the M2 / M3 typed-slot-spec "const-context peer
3104 /// of the derived-style [`Default`]" family — sibling of the
3105 /// [`crate::LimitsSpec::empty`] / [`crate::aplicacao::MeshPolicy::empty`]
3106 /// / [`crate::BehaviorSpec::empty`] `Option`-only "canonical unset
3107 /// baseline" trio, extended here onto the M2 supervisor-slot
3108 /// [`SupervisorSpec`] whose canonical baseline is not "everything
3109 /// `None`" but the Erlang/OTP-canonical `{one_for_one, 5, 60}`
3110 /// worker-supervisor triple. Named [`Self::otp_canonical`] rather
3111 /// than `empty()` to name the actual invariant the return value
3112 /// pins — the same phrasing already used in the per-arm pin tests
3113 /// on this file. Pinned load-bearing by
3114 /// [`tests::supervisor_spec_otp_canonical_byte_equals_default`] and
3115 /// [`tests::supervisor_spec_otp_canonical_is_usable_in_const_context`].
3116 #[must_use]
3117 pub const fn otp_canonical() -> Self {
3118 Self {
3119 estrategia: SUPERVISOR_ESTRATEGIA_DEFAULT,
3120 max_restarts: default_max_restarts(),
3121 restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3122 children: Vec::new(),
3123 }
3124 }
3125
3126 /// Substrate-canonical per-`:supervisor` `:estrategia` OTP-shaped
3127 /// sibling-restart-strategy scalar accessor every consumer that
3128 /// dispatches on the supervisor's per-sibling restart-decision shape
3129 /// keys off — returns the author-declared `:supervisor :estrategia`
3130 /// variant verbatim as a [`RestartStrategy`], `Copy`-projected from
3131 /// the typed slot's own [`RestartStrategy`] storage.
3132 ///
3133 /// The `:supervisor :estrategia` slot carries the closed-set
3134 /// OTP-shaped sibling-restart-strategy discriminator ([`RestartStrategy::OneForOne`]
3135 /// — restart only the failed child, the Erlang/OTP `one_for_one` default;
3136 /// [`RestartStrategy::OneForAll`] — restart every child on any child
3137 /// failure, the Erlang/OTP `one_for_all` shared-state cohort default;
3138 /// [`RestartStrategy::RestForOne`] — restart the failed child and
3139 /// every child started after it, the Erlang/OTP `rest_for_one`
3140 /// startup-order default; [`RestartStrategy::SimpleOneForOne`] —
3141 /// dynamic children of the same shape, the Erlang/OTP
3142 /// `simple_one_for_one` per-session default) that every downstream
3143 /// consumer of the Supervisor's per-sibling restart-decision fan-out
3144 /// shape keys off. Validated by [`SupervisorSpec::validate`] to be
3145 /// paired coherently with the sibling `:children` axis
3146 /// (`SimpleOneForOne ↔ children.is_empty()` — the cross-slot
3147 /// partition the strategy-arm's [`SupervisorError::SimpleOneForOneWithStaticChildren`]
3148 /// / [`SupervisorError::NoChildren`] refusal cascade pins), and every
3149 /// downstream consumer that reads the strategy keys off this scalar
3150 /// (the [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
3151 /// partition-dispatch `match` arm, the non-`SimpleOneForOne`-arm
3152 /// declared-but-empty [`SupervisorError::NoChildren`] error carrier's
3153 /// `estrategia:` field, the future `feira app graph` per-Supervisor
3154 /// strategy print line, the future wasm-operator's per-supervisor
3155 /// sibling-restart-strategy branch, the future M4
3156 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-strategy
3157 /// admission-webhook resolver, the `caixa-operator`'s hierarchical
3158 /// reconciliation scheduler's per-strategy fan-out).
3159 ///
3160 /// Prior to this lift the `.estrategia` field was accessed inline at
3161 /// two production sites in `caixa-core/src/supervisor.rs` — the
3162 /// [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
3163 /// `match self.estrategia { … }` partition dispatch, and the
3164 /// non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
3165 /// carrier at `estrategia: self.estrategia` — two open-coded
3166 /// field-accesses that expressed no compile-time link back to the
3167 /// typed slot. A future extension of the `:supervisor :estrategia`
3168 /// axis to a richer author surface (a per-cluster strategy override
3169 /// the operator pins through a future `:supervisor :estrategia-overrides`
3170 /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
3171 /// acknowledges, a per-tenant strategy-alias table the M4 CR
3172 /// materializer resolves per-CR, a per-Supervisor dynamic strategy
3173 /// derivation the future adaptive-supervision engine computes from
3174 /// child-failure-history topology, a per-child-cohort strategy split
3175 /// the future `RestForCohort` extension acknowledged by the
3176 /// INSPIRATIONS.md §II.2 Erlang/OTP absorption roadmap acknowledges)
3177 /// would have had to be threaded through every open-coded copy in
3178 /// lockstep — one consumer reading the raw variant while a peer read
3179 /// the operator-resolved variant would silently split the
3180 /// [`SupervisorError::NoChildren`] diagnostic's quoted strategy from
3181 /// the actual partition-dispatch input the empty-children refusal
3182 /// arm reached under, a two-consumer split at the validator far from
3183 /// the source `caixa.lisp` with no field naming the strategy-drift
3184 /// root cause. Lifting the resolution rule to a typed method on the
3185 /// substrate primitive means every downstream consumer of the
3186 /// Supervisor's per-`:supervisor` sibling-restart-strategy surface
3187 /// reaches for exactly one typed dispatch — the resolver's accept-set
3188 /// migrates as a unit on any future axis addition.
3189 ///
3190 /// Peer of the sibling M3 mesh-slot [`crate::Placement::estrategia`]
3191 /// (921fe1b) `Copy`-return `PlacementStrategy` scalar accessor on the
3192 /// per-`:placement` distribution-strategy axis — same "one typed
3193 /// dispatch on the substrate primitive, thin projections at each
3194 /// consumer" discipline extended onto the M2 supervisor-slot
3195 /// per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
3196 /// scalar axis. The two typed axes (`Placement::estrategia` on the
3197 /// M3 Aplicacao side, `SupervisorSpec::estrategia` on the M2
3198 /// Supervisor side) now share one accessor discipline for the shared
3199 /// substrate concept "a `Copy`-projected closed-set enum-arm
3200 /// discriminator that partitions the downstream renderer's per-arm
3201 /// fan-out". First `Copy`-return accessor on the M2 supervisor-slot
3202 /// `SupervisorSpec` type — companion to the sibling per-`:children`
3203 /// [`crate::ChildSpec::nome`] (57c61d0) /
3204 /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
3205 /// scalar accessors on the sibling per-`:children` `String`-carry
3206 /// axes. Named `estrategia()` to match the storage field's name and
3207 /// the peer [`crate::Placement::estrategia`] method-name discipline
3208 /// verbatim; the accessor's identity name maps onto the canonical
3209 /// OTP-shape supervision vocabulary the [`RestartStrategy`] enum's
3210 /// docstring already carries.
3211 ///
3212 /// Declared `pub const fn` to close the M2 supervisor-slot
3213 /// `Copy`-return raw-field-getter `const`-eval-surface pass —
3214 /// sibling of the peer M2 per-`:children` [`ChildSpec::restart`]
3215 /// (converted in this commit) `Copy`-composite-enum accessor, peer
3216 /// of the sibling M2 per-`:supervisor`
3217 /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
3218 /// already lifted, and mirror of the peer M3 mesh-slot
3219 /// per-`:placement` [`crate::Placement::estrategia`] (bafa004)
3220 /// `Copy`-return `pub const fn` scalar accessor whose method-name
3221 /// discipline this accessor was authored to match. Every downstream
3222 /// substrate-side `const`-context consumer of the per-`:supervisor`
3223 /// sibling-restart-strategy scalar (a future module-scope `const
3224 /// _:() = assert!(matches!(sup.estrategia(),
3225 /// RestartStrategy::OneForOne))` invariant pin on a typed fixture,
3226 /// a future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
3227 /// admission-webhook `const fn` per-supervisor strategy-arm floor
3228 /// over a typed [`SupervisorSpec`], any future `const fn`
3229 /// supervisor-tree composer over the substrate primitive that fans
3230 /// on the sibling-restart-strategy at compile time) now reaches
3231 /// through the same typed dispatch on the substrate primitive at
3232 /// const-eval time as at runtime. A future non-`Copy`-return
3233 /// promotion of the scalar (an `Option<RestartStrategy>`-shape
3234 /// migration once the substrate grows per-cluster strategy overlays
3235 /// the [`SupervisorSpec`] docstring already anticipates, a
3236 /// per-tenant strategy-alias table the M4 CR materializer resolves
3237 /// per-CR) that would drop the `const` qualifier fails the
3238 /// fail-before-pass-after pin
3239 /// [`tests::supervisor_spec_estrategia_accessor_is_const_fn`] at
3240 /// caixa-core build time rather than surfacing as a downstream
3241 /// consumer regression.
3242 #[must_use]
3243 pub const fn estrategia(&self) -> RestartStrategy {
3244 self.estrategia
3245 }
3246
3247 /// Substrate-canonical per-`:supervisor` `:max-restarts` OTP-shaped
3248 /// `MaxIntensity` restart-budget scalar accessor every consumer that
3249 /// reads the supervisor's per-`:restart-window` restart-budget count
3250 /// keys off — returns the author-declared `:supervisor :max-restarts`
3251 /// typed `u32` verbatim, `Copy`-projected from the typed slot's own
3252 /// `u32` storage (`u32` is `Copy`, so the accessor returns by value; no
3253 /// borrow of `&self` past the call). Non-optional (the `u32` field
3254 /// carries the restart-budget count as a required axis with a
3255 /// [`default_max_restarts`]-supplied default; the zero-floor arm
3256 /// [`SupervisorError::ZeroMaxRestarts`] and the cap arm
3257 /// [`SupervisorError::MaxRestartsExceedsCap`] jointly bracket the
3258 /// accept-set to `1..=SUPERVISOR_MAX_RESTARTS_MAX`).
3259 ///
3260 /// The `:supervisor :max-restarts` slot carries the Erlang/OTP
3261 /// `MaxIntensity` restart-budget count that pairs with the sibling
3262 /// `:restart-window` `Period` to form the `MaxIntensity / Period`
3263 /// restart-intensity ratio the supervisor trips its own escalation on
3264 /// (`theory/RUNTIME-PATTERNS.md` §II.2, Learn You Some Erlang's
3265 /// `{intensity, 5, 60}` worker-supervisor default). Every downstream
3266 /// consumer of the Supervisor's per-`:supervisor` restart-budget count
3267 /// keys off this scalar (the [`SupervisorSpec::validate`] zero-floor +
3268 /// upper-cap bracket at
3269 /// `require_positive_bounded_u32(self.max_restarts(), …)`, the future
3270 /// wasm-operator's per-supervisor restart-intensity counter's
3271 /// budget-vs-count comparator, the future M4
3272 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3273 /// webhook, the `caixa-operator`'s hierarchical reconciliation
3274 /// scheduler's per-supervisor escalation-decision branch, every
3275 /// `SupervisorError::MaxRestartsExceedsCap` variant carrying the
3276 /// offending count verbatim for `feira lint` rendering).
3277 ///
3278 /// Prior to this lift the `.max_restarts` field was accessed inline at
3279 /// one production site in `caixa-core/src/supervisor.rs` — the
3280 /// [`SupervisorSpec::validate`] `require_positive_bounded_u32(self
3281 /// .max_restarts, …)` bracket-gate call — one open-coded field-access
3282 /// that expressed no compile-time link back to the typed slot. A
3283 /// future extension of the `:max-restarts` axis to a richer author
3284 /// surface (a per-cluster restart-budget override the operator pins
3285 /// through a future `:supervisor :max-restarts-overrides` slot the
3286 /// MESH-COMPOSITION §III.2 supervision-canary roadmap acknowledges,
3287 /// a per-tenant restart-budget-alias table the M4 CR materializer
3288 /// resolves per-CR, a per-supervisor dynamic restart-budget derivation
3289 /// the future adaptive-supervision engine computes from child-failure-
3290 /// history topology, a promotion of the plain `u32` count to a richer
3291 /// `{MaxR, MaxT}` tuple once Erlang/OTP's per-child-cohort restart-
3292 /// budget-partition slot comes into scope) would have had to be
3293 /// threaded through every open-coded copy in lockstep or the validate
3294 /// gate and the future M4 emit path would silently disagree on which
3295 /// restart-budget count a given supervisor resolves to — an author's
3296 /// `:max-restarts 5` would satisfy validate while the emit path
3297 /// silently read a drifted other value (a `:max-restarts 10000`
3298 /// no-op supervisor at the emit boundary would carry the author's
3299 /// declared `5` verbatim in `feira lint` output while the future
3300 /// wasm-operator's restart-intensity counter operated under the
3301 /// drifted count), a two-consumer split at the validator far from the
3302 /// source `caixa.lisp` with no field naming the restart-budget-drift
3303 /// root cause. Lifting the resolution rule to a typed method on the
3304 /// substrate primitive means every downstream consumer of the
3305 /// Supervisor's per-`:supervisor` restart-budget-count surface reaches
3306 /// for exactly one typed dispatch — the resolver's accept-set migrates
3307 /// as a unit on any future axis addition.
3308 ///
3309 /// Peer of the sibling M3 mesh-slot [`crate::CircuitBreaker::max_failures`]
3310 /// (3a74062) `Copy`-return `u32` sub-struct required-scalar accessor
3311 /// on the per-`:politicas :circuit-breaker :max-failures` Envoy-
3312 /// outlier-detection trip-threshold axis — same "one typed dispatch on
3313 /// the substrate primitive, thin projections at each consumer"
3314 /// discipline extended onto the M2 supervisor-slot per-`:supervisor`
3315 /// restart-budget-count `Copy`-`u32` scalar axis. The two typed axes
3316 /// (`CircuitBreaker::max_failures` on the M3 Aplicacao side,
3317 /// `SupervisorSpec::max_restarts` on the M2 Supervisor side) now share
3318 /// one accessor discipline for the shared substrate concept "a
3319 /// `Copy`-projected required `u32` count that trips the next-higher
3320 /// protection layer after N events in a rolling window" — both are
3321 /// counters with identical degenerate-at-the-high-end shape and share
3322 /// the paired [`crate::POLICY_BREAKER_MAX_FAILURES_MAX`] /
3323 /// [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` cap. Second `Copy`-return
3324 /// accessor on the M2 supervisor-slot `SupervisorSpec` type, sibling
3325 /// to the [`SupervisorSpec::estrategia`] (eafb619) `Copy`-composite-
3326 /// enum `RestartStrategy` accessor. Named `max_restarts()` to match
3327 /// the storage field's name verbatim and the peer
3328 /// [`crate::CircuitBreaker::max_failures`] method-name discipline; the
3329 /// accessor's identity maps onto the canonical OTP-shape supervision
3330 /// vocabulary the [`SupervisorSpec::max_restarts`] field's docstring
3331 /// already carries.
3332 #[must_use]
3333 pub const fn max_restarts(&self) -> u32 {
3334 self.max_restarts
3335 }
3336
3337 /// Substrate-canonical per-`:supervisor` `:restart-window` OTP-shaped
3338 /// `Period` sliding-window scalar accessor every consumer of the
3339 /// supervisor's `MaxIntensity / Period` restart-intensity denominator
3340 /// keys off — returns the author-declared `:supervisor :restart-window`
3341 /// typed [`Duration`] verbatim as an `Option<Duration>`, copied out of
3342 /// the typed slot's own `Option<Duration>` storage (`Duration` is
3343 /// `Copy`, so `Option<Duration>` is `Copy` and the accessor returns by
3344 /// value; no borrow of `&self` past the call). `None` when the slot is
3345 /// absent (the canonical "never reset — every restart across the
3346 /// supervisor's lifetime counts against the sibling `:max-restarts`
3347 /// budget" sentinel the field's own docstring names and the peer
3348 /// `validate_accepts_none_restart_window` pin locks in on the
3349 /// [`SupervisorSpec::validate`] entry-side).
3350 ///
3351 /// The `:supervisor :restart-window` slot carries the Erlang/OTP
3352 /// `Period` sliding-observation-interval that pairs with the sibling
3353 /// `:max-restarts` `MaxIntensity` restart-budget count to form the
3354 /// `MaxIntensity / Period` restart-intensity ratio the supervisor
3355 /// trips its own escalation on (`theory/RUNTIME-PATTERNS.md` §II.2,
3356 /// Learn You Some Erlang's `{intensity, 5, 60}` worker-supervisor
3357 /// default). The typed slot's `Option<Duration>` accept-set —
3358 /// zero-floor rejected through [`SupervisorError::RestartWindowZero`]
3359 /// (Erlang/OTP's `MaxIntensity / Period` invariant requires
3360 /// `Period > 0`; a zero period either trips on the first failure or
3361 /// never trips depending on operator interpretation, neither of which
3362 /// is the author's intent — omit the slot to express "no reset";
3363 /// carry a positive duration to express the sliding window),
3364 /// integer-millisecond canonical form enforced through
3365 /// [`SupervisorError::RestartWindowNotCanonical`] (the duration
3366 /// codec's canonical form emits `"1500ms"` not `"1.5s"` and the
3367 /// future wasm-operator's per-supervisor restart-intensity counter
3368 /// quantizes at milliseconds), upper-bounded by
3369 /// [`SUPERVISOR_RESTART_WINDOW_MAX`] (1h — the coarsest per-
3370 /// supervisor rolling window any operationally-reachable supervisor
3371 /// can honor without spanning multiple scheduler epochs the
3372 /// hierarchical-reconciliation scheduler treats as independent) —
3373 /// maps onto the future wasm-operator (M3) per-supervisor
3374 /// restart-intensity counter's rolling-observation-interval, the
3375 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
3376 /// per-`spec.restartWindow` admission webhook, and the sibling
3377 /// `duration_codec`-serialized wire scalar every downstream consumer
3378 /// of the supervisor's per-`:supervisor` restart-intensity denominator
3379 /// keys off.
3380 ///
3381 /// Prior to this lift the `.restart_window` field was accessed inline
3382 /// at one production site in `caixa-core/src/supervisor.rs` — the
3383 /// [`SupervisorSpec::validate`] `if let Some(w) = self.restart_window {
3384 /// … }` zero-floor + canonical-form + upper-cap bracket arm — one
3385 /// open-coded field-access that expressed no compile-time link back to
3386 /// the typed slot. A future extension of the `:restart-window` axis to
3387 /// a richer author surface (a per-cluster restart-window override the
3388 /// operator pins through a future `:supervisor :restart-window-overrides`
3389 /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
3390 /// acknowledges, a per-tenant restart-window-alias table the M4 CR
3391 /// materializer resolves per-CR, a per-supervisor dynamic
3392 /// restart-window derivation the future adaptive-supervision engine
3393 /// computes from child-failure-history topology, a promotion of the
3394 /// plain `Option<Duration>` window to a richer `{observation, cooldown}`
3395 /// pair once Erlang/OTP's per-child-cohort observation-interval-
3396 /// partition slot comes into scope) would have had to be threaded
3397 /// through every open-coded copy in lockstep or the validate gate and
3398 /// the future M4 emit path would silently disagree on which
3399 /// restart-window a given supervisor resolves to — an author's
3400 /// `:restart-window "60s"` would satisfy validate while the emit path
3401 /// silently read a drifted other value (a `Some(Duration::from_secs(60))`
3402 /// authored slot at the emit boundary would carry the author's
3403 /// declared window verbatim in `feira lint` output while the future
3404 /// wasm-operator's restart-intensity counter operated under a
3405 /// drifted window, or vice versa: an author's `:restart-window ()`
3406 /// would carry the "never reset" sentinel through validate while the
3407 /// emit path silently substituted a default sliding window), a
3408 /// two-consumer split at the validator far from the source
3409 /// `caixa.lisp` with no field naming the restart-window-drift root
3410 /// cause. Lifting the resolution rule to a typed method on the
3411 /// substrate primitive means every downstream consumer of the
3412 /// Supervisor's per-`:supervisor` restart-intensity-denominator
3413 /// surface reaches for exactly one typed dispatch — the resolver's
3414 /// accept-set migrates as a unit on any future axis addition.
3415 ///
3416 /// Third `Copy`-return accessor on the M2 supervisor-slot
3417 /// `SupervisorSpec` type, closing the last unlifted per-`:supervisor`
3418 /// scalar-value axis (`children: Vec<ChildSpec>` carries a `Vec`
3419 /// payload rather than a `Copy`-scalar, and the per-`:children`
3420 /// [`crate::ChildSpec::nome`] (57c61d0) /
3421 /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
3422 /// scalar accessors already close the per-element `String`-carry
3423 /// axes). Sibling to the peer M2 [`crate::LimitsSpec::wall_clock`]
3424 /// (8cb717b) `Option<Duration>` accessor on the `:limits` slot's
3425 /// per-outermost-call wall-clock-deadline axis and the peer M3
3426 /// [`crate::MeshPolicy::timeout`] (7073d0f) `Option<Duration>`
3427 /// accessor on the `:politicas` slot's per-call-deadline axis — all
3428 /// three share the shared substrate concept "a `Copy`-projected
3429 /// optional `Duration` that carries a positive integer-millisecond
3430 /// canonical value with a `1ms..=<axis-specific>_MAX` accept-set and
3431 /// the paired zero-floor / non-canonical / above-cap refusal cascade"
3432 /// through the same [`crate::render::require_positive_canonical_bounded_duration`]
3433 /// bracket-helper the three axes each route through. Named
3434 /// `restart_window()` to match the storage field's name verbatim and
3435 /// the peer [`crate::LimitsSpec::wall_clock`] /
3436 /// [`crate::MeshPolicy::timeout`] method-name discipline; the
3437 /// accessor's identity maps onto the canonical OTP-shape supervision
3438 /// vocabulary the [`SupervisorSpec::restart_window`] field's docstring
3439 /// already carries.
3440 #[must_use]
3441 pub const fn restart_window(&self) -> Option<Duration> {
3442 self.restart_window
3443 }
3444
3445 /// Substrate-canonical per-`:supervisor` `:children` OTP-shaped
3446 /// static-child-list slice accessor every consumer that walks the
3447 /// supervisor's declared child set keys off — returns the author-
3448 /// declared `:supervisor :children` `Vec<ChildSpec>` verbatim as a
3449 /// `&[ChildSpec]` slice-view, borrowed from the typed slot's own
3450 /// `Vec<ChildSpec>` storage (a zero-copy slice-view over the same
3451 /// backing buffer the `Serialize`/`Deserialize` derives round-trip
3452 /// through). Non-optional: an empty slice is the load-bearing
3453 /// "author declared `:children ()`" sentinel every consumer of the
3454 /// cross-slot `SimpleOneForOne ↔ children.is_empty()` partition
3455 /// keys off (`SimpleOneForOne` requires the empty slice; the peer
3456 /// three strategies require a non-empty slice — the paired
3457 /// [`SupervisorError::SimpleOneForOneWithStaticChildren`] /
3458 /// [`SupervisorError::NoChildren`] refusal cascade pins the
3459 /// partition on both arms).
3460 ///
3461 /// The `:supervisor :children` slot carries the OTP-shaped static
3462 /// child list the supervisor materializes one ComputeUnit per
3463 /// entry from — the Erlang/OTP `supervisor:init/1`'s
3464 /// `{ok, {SupFlags, ChildSpecs}}` `ChildSpecs` list, projected
3465 /// through the tatara-lisp `:children` author surface onto a typed
3466 /// `Vec<ChildSpec>` whose per-element `(nome(),
3467 /// versao_requirement(), restart)` triple the per-child
3468 /// [`SupervisorSpec::validate`] loop already gates through the
3469 /// lifted [`ChildSpec::nome`] (57c61d0) /
3470 /// [`ChildSpec::versao_requirement`] (2c053c8) scalar accessors.
3471 /// Every downstream consumer that fans on the static child list
3472 /// keys off this slice (the [`SupervisorSpec::validate`]
3473 /// `SimpleOneForOne ↔ non-SimpleOneForOne` partition dispatch's
3474 /// `.is_empty()` probe on both arms, the [`SupervisorSpec::validate`]
3475 /// per-child DNS-1123 / semver-requirement / duplicate-detection
3476 /// fan-out loop, every future wasm-operator (M3) per-supervisor
3477 /// hierarchical-reconciliation scheduler's per-child ComputeUnit
3478 /// materialization loop, the future M4
3479 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
3480 /// admission-webhook fan-out, the future `feira app graph`
3481 /// per-supervisor tree-print traversal).
3482 ///
3483 /// Prior to this lift the `.children` `Vec<ChildSpec>` was accessed
3484 /// inline at three production sites in `caixa-core/src/supervisor.rs`
3485 /// — the [`SupervisorSpec::validate`] `SimpleOneForOne`-arm
3486 /// `!self.children.is_empty()` cross-slot refusal probe, the peer
3487 /// non-`SimpleOneForOne`-arm `self.children.is_empty()`
3488 /// [`SupervisorError::NoChildren`] refusal probe, and the per-child
3489 /// validate loop's `for child in &self.children` traversal head —
3490 /// three open-coded field-accesses that expressed no compile-time
3491 /// link back to the typed slot. A future extension of the
3492 /// `:supervisor :children` axis to a richer author surface (a
3493 /// per-cluster child-set overlay the operator pins through a future
3494 /// `:supervisor :children-overrides` slot the MESH-COMPOSITION §III.2
3495 /// supervision-canary roadmap acknowledges, a per-tenant
3496 /// child-set-alias table the M4 CR materializer resolves per-CR,
3497 /// a per-supervisor dynamic-child derivation the future adaptive-
3498 /// supervision engine computes from child-failure-history topology,
3499 /// a promotion of the plain `Vec<ChildSpec>` to a richer
3500 /// `{static, dynamic}` partition once Erlang/OTP's
3501 /// `simple_one_for_one` dynamic-child slot comes into typed scope)
3502 /// would have had to be threaded through all three open-coded copies
3503 /// in lockstep or one consumer would silently disagree with the
3504 /// peers on which child-set a given supervisor resolves to — the
3505 /// `SimpleOneForOne`-arm probe reading the raw slot while the peer
3506 /// non-`SimpleOneForOne`-arm probe read an operator-resolved slot
3507 /// would silently split the partition-dispatch's two-arm coherence
3508 /// (a supervisor that satisfies neither arm's precondition, or that
3509 /// satisfies both, at the cost of the paired
3510 /// `SimpleOneForOneWithStaticChildren`/`NoChildren` refusal cascade
3511 /// silently drifting from the per-child validate loop's actual
3512 /// traversal input), a three-consumer split at the validator far
3513 /// from the source `caixa.lisp` with no field naming the
3514 /// child-set-drift root cause. Lifting the resolution rule to a
3515 /// typed method on the substrate primitive means every downstream
3516 /// consumer of the Supervisor's per-`:supervisor` static-child-list
3517 /// surface reaches for exactly one typed dispatch — the resolver's
3518 /// accept-set migrates as a unit on any future axis addition.
3519 ///
3520 /// First slice-return (`&[T]`) accessor on any M2 or M3 typed slot
3521 /// — the seed for the same "one typed dispatch on the substrate
3522 /// primitive, thin projections at each consumer" discipline the
3523 /// closed [`crate::LimitsSpec`] / [`BehaviorSpec`] /
3524 /// [`crate::UpgradeFromEntry`] scalar-accessor families each carry
3525 /// on their `Copy` / `Option<Copy>` / `Option<&str>` axes, extended
3526 /// onto the first `Vec`-carry axis on the substrate. The four peer
3527 /// `Vec`-carry axes still unlifted at the time of this seed —
3528 /// [`crate::Placement::clusters`] (`Vec<String>` per-cluster
3529 /// distribution-target list), [`crate::AplicacaoSpec::membros`]
3530 /// (`Vec<Membro>` per-Aplicacao member list),
3531 /// [`crate::AplicacaoSpec::contratos`] (`Vec<WitContract>`
3532 /// per-Aplicacao WIT-typed edge list),
3533 /// [`crate::UpgradeFromEntry::instructions`]
3534 /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
3535 /// — inherit this accessor's discipline as future compounding runs
3536 /// migrate their consumers onto the shared slice-return shape.
3537 /// Fourth (and final) accessor on the M2 supervisor-slot
3538 /// `SupervisorSpec` type, sibling to the three `Copy`-return
3539 /// [`SupervisorSpec::estrategia`] (eafb619) /
3540 /// [`SupervisorSpec::max_restarts`] (7844f4e) /
3541 /// [`SupervisorSpec::restart_window`] (7e7b32f) accessors — closes
3542 /// the last unlifted per-`:supervisor` field axis (the
3543 /// `Vec<ChildSpec>` static-child-list carrier) so every downstream
3544 /// per-`:supervisor` reader now routes through a typed dispatch on
3545 /// the substrate primitive. Named `children()` to match the storage
3546 /// field's name verbatim and the tatara-lisp author-surface term
3547 /// (`:children`) the field's own docstring already carries; the
3548 /// accessor's identity maps onto the canonical OTP-shape
3549 /// supervision vocabulary the [`SupervisorSpec::children`] field's
3550 /// docstring already reaches for ("Static children ..."). Returns
3551 /// `&[ChildSpec]` (not `&Vec<ChildSpec>`) because every downstream
3552 /// consumer of the child list treats it as a read-only sequence —
3553 /// the slice-view is the narrowest borrow that supports every
3554 /// present + roadmapped consumer (`.is_empty()`, `.iter()`,
3555 /// index, `.len()`) without leaking the backing `Vec`'s
3556 /// grow/push/reserve surface that no consumer of the typed view
3557 /// reaches for (the storage-side `Vec` remains reachable through
3558 /// the `pub children` field for the mutation-carrying
3559 /// `Caixa::supervisor_view` fold-in path in
3560 /// `manifest.rs:supervisor_view`).
3561 #[must_use]
3562 pub const fn children(&self) -> &[ChildSpec] {
3563 self.children.as_slice()
3564 }
3565
3566 /// Validate the supervisor's typed shape — strategy ↔ children
3567 /// invariants, max_restarts > 0, restart_window > 0 when set,
3568 /// per-child non-empty + duplicate-free names.
3569 ///
3570 /// Mirrors the value-shape discipline applied to every other
3571 /// typed slot:
3572 ///
3573 /// - `Some(Duration::ZERO)` on a Duration-bearing axis is the
3574 /// same "0 means the opposite of what you think" footgun
3575 /// closed for `:politicas :timeout` (Envoy interprets a zero
3576 /// timeout as `infinite`), `:politicas :circuit-breaker
3577 /// :window`, and `:limits :wall-clock`. The
3578 /// `MaxIntensity / Period` ratio in Erlang/OTP's
3579 /// `supervisor` requires `Period > 0`; a zero period either
3580 /// trips on the first failure or never trips depending on
3581 /// operator interpretation, neither of which is the
3582 /// author's intent. Omit `:restart-window` to express "no
3583 /// reset"; carry a positive duration to express the window.
3584 /// - duplicate `:children` `:caixa` names are the same
3585 /// graph-node-set / multiset distinction closed for
3586 /// `:membros` (4bb3f3d), `:placement :clusters` (c7c7799),
3587 /// and `:entrada :paths` (eb3456d). Two children with the
3588 /// same `:caixa` materialize as two ComputeUnits with the
3589 /// same name in the cluster's HelmRelease values, one
3590 /// silently overwriting the other. Erlang/OTP's
3591 /// `child_spec.id` is required-unique per supervisor;
3592 /// pleme-io enforces the same set-not-multiset shape on
3593 /// `:caixa` (the load-bearing identity in our renderer).
3594 pub fn validate(&self) -> Result<(), SupervisorError> {
3595 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition
3596 // dispatch and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
3597 // error carrier's `estrategia:` field through the lifted
3598 // [`SupervisorSpec::estrategia`] accessor rather than the raw
3599 // `self.estrategia` field access — the two production consumers
3600 // of the per-`:supervisor` sibling-restart-strategy scalar now
3601 // key off exactly one typed dispatch on the substrate primitive,
3602 // so any future rebrand on the axis (a per-cluster strategy
3603 // override the operator pins through a future `:supervisor
3604 // :estrategia-overrides` slot, a per-tenant strategy-alias table
3605 // the M4 CR materializer resolves per-CR) migrates as a single
3606 // caixa-core edit rather than a coordinated rewrite of the two
3607 // call sites — sibling of the peer M3 [`crate::Placement::estrategia`]
3608 // (921fe1b) four-consumer migration on the per-`:placement`
3609 // distribution-strategy axis.
3610 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition-
3611 // dispatch's paired `.is_empty()` cross-slot refusal probes
3612 // (the `SimpleOneForOne`-arm
3613 // [`SupervisorError::SimpleOneForOneWithStaticChildren`] refusal
3614 // and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
3615 // refusal) through the lifted [`SupervisorSpec::children`]
3616 // slice-return accessor rather than the raw `self.children`
3617 // field access — the two paired production consumers of the
3618 // per-`:supervisor` static-child-list scalar-shape now key off
3619 // exactly one typed dispatch on the substrate primitive, so any
3620 // future rebrand on the axis (a per-cluster child-set overlay
3621 // the operator pins through a future `:supervisor
3622 // :children-overrides` slot, a per-tenant child-set-alias table
3623 // the M4 CR materializer resolves per-CR) migrates as a single
3624 // caixa-core edit rather than a coordinated rewrite of the
3625 // paired arms — first slice-return migration on any typed slot,
3626 // seed for the peer per-`:placement :clusters`,
3627 // per-`:membros`, per-`:contratos`, and per-`:upgrade-from
3628 // :instructions` `Vec`-carry axes.
3629 match self.estrategia() {
3630 RestartStrategy::SimpleOneForOne => {
3631 // SimpleOneForOne: children added at runtime. Static
3632 // list must be empty (one shape declared elsewhere).
3633 if !self.children().is_empty() {
3634 return Err(SupervisorError::SimpleOneForOneWithStaticChildren);
3635 }
3636 }
3637 _ => {
3638 if self.children().is_empty() {
3639 return Err(SupervisorError::no_children(self.estrategia()));
3640 }
3641 }
3642 }
3643 // Zero-floor + upper-cap bracket on the typed `:max-restarts`
3644 // axis. See [`crate::render::require_positive_bounded_u32`] for
3645 // the ordering discipline (zero-floor arm strictly precedes cap
3646 // arm so `0` surfaces the self-locating `ZeroMaxRestarts`
3647 // diagnostic with its counter-axis remediation directly named,
3648 // not the misleading `0 > SUPERVISOR_MAX_RESTARTS_MAX == false`
3649 // cap-arm miss). Until this bracket landed the top edge ran all
3650 // the way to `u32::MAX` and a struct-literal
3651 // `SupervisorSpec { max_restarts: 100_000, .. }` (or the
3652 // equivalent author-surface `:max-restarts 100000` /
3653 // `:max-restarts 4294967295` typo landing in the slot) silently
3654 // passed validate. The runtime substrate consuming the value
3655 // (Erlang/OTP's `MaxIntensity / Period` ratio, the future
3656 // wasm-operator's per-supervisor restart-intensity counter, the
3657 // M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
3658 // admission webhook) then turned a typed `:max-restarts`
3659 // policy into a no-op supervisor: the escalation threshold is
3660 // structurally so high that no realistic
3661 // restarts-per-`:restart-window` traffic shape can reach it,
3662 // the supervisor never escalates to its parent, and a bad
3663 // child can loop inside the window indefinitely with the
3664 // parent supervisor structurally never receiving the "this
3665 // subtree has exceeded its restart budget" signal the typed
3666 // slot is meant to express. The bracket set is
3667 // `1..=SUPERVISOR_MAX_RESTARTS_MAX`, peer with the
3668 // [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap on
3669 // the sibling `:politicas :circuit-breaker :max-failures` axis:
3670 // both are "trip the next-higher protection layer after N
3671 // events in a rolling window" counters with identical
3672 // degenerate-at-the-high-end shape and now share one canonical
3673 // bracket helper. The bracket precedes the sibling
3674 // `:restart-window` zero-floor / canonical-millisecond arms so
3675 // an over-cap `max_restarts` paired with a structurally invalid
3676 // window surfaces the bracket diagnostic first, mirroring the
3677 // `PolicyBreakerMaxFailuresExceedsCap` / window-axis cross-arm
3678 // ordering on the peer `:politicas :circuit-breaker` slot.
3679 // Route the [`SupervisorSpec::validate`] `:max-restarts` zero-floor +
3680 // upper-cap bracket-gate through the lifted [`SupervisorSpec::max_restarts`]
3681 // accessor rather than the raw `self.max_restarts` field access —
3682 // the one production consumer of the per-`:supervisor`
3683 // restart-budget-count scalar now keys off exactly one typed
3684 // dispatch on the substrate primitive, so any future rebrand on
3685 // the axis (a per-cluster restart-budget override the operator
3686 // pins through a future `:supervisor :max-restarts-overrides`
3687 // slot, a per-tenant restart-budget-alias table the M4 CR
3688 // materializer resolves per-CR) migrates as a single caixa-core
3689 // edit rather than a coordinated rewrite — sibling of the peer M3
3690 // [`crate::CircuitBreaker::max_failures`] (3a74062) migration on
3691 // the per-`:politicas :circuit-breaker :max-failures` axis.
3692 crate::render::require_positive_bounded_u32(
3693 self.max_restarts(),
3694 SUPERVISOR_MAX_RESTARTS_MAX,
3695 || SupervisorError::ZeroMaxRestarts,
3696 SupervisorError::max_restarts_exceeds_cap,
3697 )?;
3698 // Route the [`SupervisorSpec::validate`] `:restart-window`
3699 // zero-floor + integer-millisecond canonical-form + upper-cap
3700 // bracket-gate through the lifted [`SupervisorSpec::restart_window`]
3701 // accessor rather than the raw `self.restart_window` field access —
3702 // the one production consumer of the per-`:supervisor`
3703 // restart-intensity-denominator scalar now keys off exactly one
3704 // typed dispatch on the substrate primitive, so any future rebrand
3705 // on the axis (a per-cluster restart-window override the operator
3706 // pins through a future `:supervisor :restart-window-overrides`
3707 // slot, a per-tenant restart-window-alias table the M4 CR
3708 // materializer resolves per-CR) migrates as a single caixa-core
3709 // edit rather than a coordinated rewrite — sibling of the peer M2
3710 // [`crate::LimitsSpec::wall_clock`] (8cb717b) validate-arm-route
3711 // on the per-`:limits :wall-clock` axis and the peer M3
3712 // [`crate::MeshPolicy::timeout`] (7073d0f) accessor-route on the
3713 // per-`:politicas :timeout` axis.
3714 if let Some(w) = self.restart_window() {
3715 // Zero-floor + integer-millisecond canonical-form +
3716 // upper-cap bracket on the typed `:restart-window` axis.
3717 // See
3718 // [`crate::render::require_positive_canonical_bounded_duration`]
3719 // for the full three-arm ordering discipline (zero-floor
3720 // strictly precedes canonical-form so `Duration::ZERO`
3721 // surfaces the self-locating `RestartWindowZero`
3722 // diagnostic; canonical-form strictly precedes the cap arm
3723 // so a sub-millisecond above-cap value surfaces the more
3724 // fundamental round-trip-shape diagnostic first) and the
3725 // three peer typed-`Duration` sites that share this
3726 // canonical bracket ([`crate::MeshPolicy::timeout`],
3727 // [`crate::CircuitBreaker::window`],
3728 // [`crate::LimitsSpec::wall_clock`]). Every validated
3729 // value lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
3730 // (1ms..=1h), integer-millisecond granularity.
3731 crate::render::require_positive_canonical_bounded_duration(
3732 w,
3733 SUPERVISOR_RESTART_WINDOW_MAX,
3734 || SupervisorError::RestartWindowZero,
3735 SupervisorError::restart_window_not_canonical,
3736 SupervisorError::restart_window_exceeds_cap,
3737 )?;
3738 }
3739 // Route the per-child DNS-1123 / semver-requirement / duplicate-
3740 // detection fan-out loop through the lifted named per-slot gate
3741 // [`SupervisorSpec::validate_children`] rather than an inline
3742 // three-per-child cascade — every future consumer that wants to
3743 // re-check only the `:children` slot's per-entry axes (the M4
3744 // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
3745 // admission webhook re-validating one added/renamed child, the
3746 // future wasm-operator's per-child dynamic-add re-validator on
3747 // the `SimpleOneForOne` runtime-add path once dynamic-children
3748 // graduate to a typed slot, a future partial re-validator on a
3749 // per-`:children`-entry patch) reaches every per-entry axis
3750 // through one dispatch rather than re-inlining the three-arm
3751 // cascade in lockstep with `validate` or paying the peer
3752 // `:estrategia`/`:max-restarts`/`:restart-window` gates to
3753 // reach one entry check. Sibling of the peer M3 mesh-slot
3754 // per-slot gate family (`validate_membros` — the exact peer on
3755 // the M3 side, [`crate::AplicacaoSpec::validate_membros`];
3756 // `validate_contratos` — 906a5c6; `validate_entrada` — 20cd523;
3757 // `validate_placement`; `validate_politicas` routing through
3758 // `MeshPolicy::validate` — f03a154) — the M2 supervisor-slot
3759 // per-slot gate discipline now spans both the M3 mesh-slot
3760 // family and the M2 `:children` per-child-cascade axis on one
3761 // shape: one named per-slot gate per typed per-entry loop.
3762 self.validate_children()?;
3763 Ok(())
3764 }
3765
3766 /// Named per-slot gate on the M2 `:supervisor :children` per-entry
3767 /// axis — folds the per-child DNS-1123 name gate, semver-requirement
3768 /// gate, and duplicate-`:caixa` dedup arm into one call every
3769 /// consumer that wants to re-validate one `:children` entry (or the
3770 /// whole list) against the same accept-set [`SupervisorSpec::validate`]
3771 /// admits reaches through.
3772 ///
3773 /// Peer of the M3 mesh-slot [`crate::AplicacaoSpec::validate_membros`]
3774 /// per-slot gate on the analogous per-entry axis (`:membros`) — same
3775 /// three-per-entry shape (DNS-1123 name + semver-requirement +
3776 /// duplicate-`:caixa` dedup), lifted to one named substrate
3777 /// primitive per slot. The M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
3778 /// materializer's admission webhook re-checking one added or renamed
3779 /// child, the future wasm-operator's per-child dynamic-add
3780 /// re-validator on the `SimpleOneForOne` runtime-add path once
3781 /// dynamic-children graduate to a typed slot, a future partial
3782 /// re-validator on a per-`:children`-entry patch — each reaches the
3783 /// three per-entry axes through this one dispatch rather than
3784 /// re-inlining the three-arm cascade in lockstep with `validate`
3785 /// (the duplication the PRIME DIRECTIVE names as a bug) or paying
3786 /// the peer `:estrategia`/`:max-restarts`/`:restart-window` gates to
3787 /// reach one entry check.
3788 ///
3789 /// Self-contained on `&self` — resolves its own dedup `HashSet`
3790 /// through [`SupervisorSpec::children`] rather than borrowing one
3791 /// threaded down from `validate`, the same posture the peer M3
3792 /// mesh-slot per-slot gates ([`crate::AplicacaoSpec::validate_membros`],
3793 /// [`crate::AplicacaoSpec::validate_contratos`],
3794 /// [`crate::AplicacaoSpec::validate_entrada`],
3795 /// [`crate::AplicacaoSpec::validate_placement`]) each carry, so a
3796 /// consumer that reaches this gate directly (without first calling
3797 /// `validate`) still runs the full per-child cascade — pinned by
3798 /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
3799 /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
3800 /// + `validate_children_is_self_contained_on_children_slot`.
3801 ///
3802 /// The three per-entry arms run in the same canonical order the
3803 /// pre-lift inline cascade encoded (DNS-1123 → semver → dedup), so
3804 /// the diagnostic every author-declared per-`:children` entry surfaces
3805 /// through `validate` is byte-equal to the diagnostic this gate
3806 /// surfaces when called directly — the equivalence-pin pair
3807 /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
3808 /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
3809 /// asserts the two altitudes discriminate the same set on every
3810 /// per-entry-covered input.
3811 pub fn validate_children(&self) -> Result<(), SupervisorError> {
3812 let mut seen = std::collections::HashSet::new();
3813 for child in self.children() {
3814 // Every emitted cluster artifact's `metadata.name` for a
3815 // supervised child derives from this `:children :caixa` value
3816 // verbatim — the rendered `wasm.pleme.io/v1alpha1/ComputeUnit
3817 // .metadata.name` per child, the [`crate::LABEL_PROGRAM`]
3818 // label value on every child's pod identity, and the per-
3819 // child K8s [`Service`][svc] `metadata.name` the future
3820 // wasm-operator (M3) provisions for inter-child supervision
3821 // tree wiring. Each apiserver-side schema on each landing
3822 // site enforces the DNS-1123 label rule on admission; a
3823 // structurally invalid child name (`"Worker"`, `"my_worker"`,
3824 // `"team.worker"`, `"-worker"`, `"worker-"`, the >63-byte
3825 // UUID-shaped mistaken-identity slug) silently passes the
3826 // prior empty-/duplicate-only gate and the failure surfaces
3827 // at `kubectl apply` time as a `metadata.name: Invalid value`
3828 // rejection, far from the source caixa.lisp, with no field
3829 // naming the offending `:children` entry. Lifting the gate
3830 // to caixa-build time mirrors the `:membros :caixa` value-
3831 // shape trajectory (3f9d7a0) and the `:placement :clusters`
3832 // trajectory (6cbb900) onto the third DNS-1123-label-shaped
3833 // identifier axis — the supervisor tree's child names —
3834 // through the lifted
3835 // [`crate::render::require_valid_dns_1123_label`] gate the
3836 // seven peer name axes (`:membros :caixa`, `:placement
3837 // :clusters`, `:placement :affinity`, `:contratos :de`/`:para`,
3838 // `:entrada :para`, `:nome`, `:upgrade-from :module`) each
3839 // route through, so drift between the eight axes' accepted
3840 // DNS-1123-label sets is structurally impossible.
3841 //
3842 // [svc]: https://kubernetes.io/docs/concepts/services-networking/service/
3843 crate::render::require_valid_dns_1123_label(
3844 child.nome(),
3845 || SupervisorError::EmptyChildName,
3846 |reason| SupervisorError::child_caixa_invalid(child.nome(), reason),
3847 )?;
3848 // The author surface for `:children :versao` is the same
3849 // Cargo-shaped semver requirement string `:deps :versao` and
3850 // `:membros :versao` carry — and the lacre pipeline resolves
3851 // all three axes through the same
3852 // [`crate::version::parse_requirement`] entry-point. The
3853 // shared [`crate::render::require_valid_versao_requirement`]
3854 // helper brackets the empty-first + parse cascade both peer
3855 // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
3856 // [`crate::AplicacaoSpec::validate_membros`] on `:membros
3857 // :versao`) route through, so drift between the three axes'
3858 // accepted requirement sets is structurally impossible and
3859 // the parse-side no-op the empty-first arm closes (semver's
3860 // empty parse yields an implicit `*`) lives in exactly one
3861 // predicate. Every `ChildSpec::versao` past validate is
3862 // round-trippable through [`crate::parse_requirement`]
3863 // without re-checking at the resolver layer, and the three
3864 // `:versao` typed surfaces (`:deps`, `:membros`, `:children`)
3865 // are now structurally equivalent by construction.
3866 crate::render::require_valid_versao_requirement(
3867 child.versao_requirement(),
3868 || SupervisorError::empty_child_version(child.nome()),
3869 |reason| {
3870 SupervisorError::child_versao_invalid(
3871 child.nome(),
3872 child.versao_requirement(),
3873 reason,
3874 )
3875 },
3876 )?;
3877 crate::render::insert_first_seen(&mut seen, child.nome(), || {
3878 SupervisorError::duplicate_child_caixa(child.nome())
3879 })?;
3880 }
3881 Ok(())
3882 }
3883}
3884
3885/// Cross-slot coherence gate on the supervision tree: no
3886/// `:children :caixa` entry may name the supervisor's own `:nome`.
3887///
3888/// A supervisor that lists itself as a child is a degenerate self-parent
3889/// — the supervision tree is a DAG rooted at the supervisor (OTP child
3890/// specs reference *distinct* child processes; a supervisor is never its
3891/// own child), and the wasm-operator's hierarchical reconciliation would
3892/// otherwise be handed a node that is its own parent: a one-node cycle it
3893/// either rejects far from the source `caixa.lisp` or recurses on. Because
3894/// every `:nome` is a globally-unique substrate identity (DNS-1123 label +
3895/// lacre closure root), a child whose `:caixa` equals the supervisor's
3896/// `:nome` *is* the supervisor itself, not a coincidentally-named peer.
3897///
3898/// Lives outside [`SupervisorSpec::validate`] because the typed view
3899/// carries the children but not the parent `:nome`; mirrors the
3900/// cross-slot precedence gate `validate_upgrade_from_against_versao`
3901/// (which likewise reads one slot against another at the
3902/// [`crate::layout`] wire-up site) and the mesh self-edge gate
3903/// `AplicacaoSpec`'s `ContratoSelfLoop` — the same "an edge from a graph
3904/// node to itself is structurally not a tree/mesh edge" discipline, here
3905/// on the supervision-tree axis.
3906pub fn validate_no_self_supervision(
3907 children: &[ChildSpec],
3908 parent_nome: &str,
3909) -> Result<(), SupervisorError> {
3910 for child in children {
3911 if child.nome() == parent_nome {
3912 return Err(SupervisorError::child_supervises_self(parent_nome));
3913 }
3914 }
3915 Ok(())
3916}
3917
3918#[derive(Debug, Error, PartialEq, Eq)]
3919pub enum SupervisorError {
3920 #[error("supervisor :estrategia {estrategia:?} requires at least one :children entry")]
3921 NoChildren { estrategia: RestartStrategy },
3922 #[error(
3923 "SimpleOneForOne supervisors must declare zero static children (children spawn dynamically)"
3924 )]
3925 SimpleOneForOneWithStaticChildren,
3926 #[error(":max-restarts must be > 0")]
3927 ZeroMaxRestarts,
3928 #[error(
3929 ":supervisor :max-restarts ({max_restarts}) exceeds the supervisor-policy ceiling \
3930 (SUPERVISOR_MAX_RESTARTS_MAX = 1000) — a value above this cap turns the typed \
3931 restart-intensity policy into a no-op supervisor: the escalation threshold is \
3932 structurally so high that no realistic restarts-per-:restart-window traffic shape \
3933 can reach it, so the supervisor never escalates to its parent and a bad child can \
3934 loop inside the window indefinitely. Every typed-slot consumer (Erlang/OTP's \
3935 MaxIntensity/Period ratio, the future wasm-operator's per-supervisor \
3936 restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
3937 materializer's admission webhook) emits a `:max-restarts` declaration that is \
3938 structurally never reached. Pin a value in 1..=1000 (Erlang/OTP / Elixir / Riak \
3939 Core / RabbitMQ production playbooks recommend 3..=100; the OTP `supervisor` \
3940 callback module's `MaxR = 1` minimal-restart default sits at the bottom of the \
3941 band) or restructure the supervision tree (split the flaky child into its own \
3942 sub-supervisor with a tighter budget) if you need a higher restart tolerance."
3943 )]
3944 MaxRestartsExceedsCap { max_restarts: u32 },
3945 #[error(
3946 ":restart-window must be > 0 when set — Erlang/OTP's MaxIntensity/Period \
3947 requires Period > 0; a zero window either trips on the first failure or \
3948 never trips depending on operator interpretation. Omit :restart-window to \
3949 express `never reset`; carry a positive duration to express the window."
3950 )]
3951 RestartWindowZero,
3952 #[error(
3953 ":supervisor :restart-window ({window:?}) carries a sub-millisecond residue the shared `duration_codec` cannot round-trip — \
3954 the codec truncates to `as_millis()` before picking the canonical unit, so a value with `subsec_nanos() % 1_000_000 != 0` either \
3955 truncates on first serialize (e.g. `Duration::from_micros(1500)` → \"1ms\" → `Duration::from_millis(1)` ≠ original) or renders \
3956 as \"0s\" the `RestartWindowZero` arm then rejects on re-validate. Pin an integer-millisecond magnitude in the canonical authoring form \
3957 (`<integer><unit>` for unit ∈ {{ms, s, m, h}}, e.g. `\"500ms\"`, `\"30s\"`, `\"2m\"`, `\"1h\"`) or omit the field for `never reset`"
3958 )]
3959 RestartWindowNotCanonical { window: Duration },
3960 #[error(
3961 ":supervisor :restart-window ({window:?}) exceeds the supervisor-policy ceiling \
3962 (SUPERVISOR_RESTART_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
3963 per-supervisor rolling-window restart-intensity counter into a lifetime counter: the \
3964 failure-counting window is structurally so long that transient restarts are never \
3965 forgotten, the MaxIntensity/Period ratio degenerates from `trip the parent supervisor \
3966 when the child has exceeded its restart budget within the recent window` to `trip the \
3967 parent when the child has exceeded its restart budget over its lifetime`, and the \
3968 supervisor's reset semantic never reaches the child — every typed-slot consumer \
3969 (Erlang/OTP's MaxIntensity/Period reconciler, the future wasm-operator's \
3970 per-supervisor restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
3971 materializer's admission webhook, the caixa-operator's hierarchical reconciliation \
3972 scheduler) emits a `:restart-window` declaration that is structurally a no-op rolling \
3973 window. Pin a value in 1ms..=1h (Learn You Some Erlang's `{{intensity, 5, 60}}` \
3974 worker-supervisor `Period = 60s` default, Elixir's `Supervisor` `max_seconds: 5` \
3975 default, OTP's `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's \
3976 `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default — every Erlang/OTP \
3977 / Elixir production playbook sits in the 5s..=300s band; the longest documented \
3978 per-supervisor restart-window any pleme-io substrate playbook recommends maxes at \
3979 ~30m) or omit :restart-window to express `never reset` (the supervisor's restart \
3980 budget then becomes a strict lifetime counter by design, not a degenerate one — the \
3981 author surfaces the lifetime-counter semantic explicitly at the slot, rather than \
3982 hiding it behind a rolling-window declaration the cap arm rejects)"
3983 )]
3984 RestartWindowExceedsCap { window: Duration },
3985 #[error("child entry has empty :caixa name")]
3986 EmptyChildName,
3987 #[error(
3988 "child :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
3989 (the K8s apiserver enforces this rule on every `metadata.name` / Service \
3990 name / label value the child name lands in — the per-child \
3991 `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name`, the `LABEL_PROGRAM` \
3992 label value, and the future wasm-operator per-child Service `metadata.name` \
3993 — each apiserver-side schema rejects names that don't match; use a \
3994 lowercase alphanumeric + hyphen identifier like `\"worker\"` or `\"cache-v2\"`)"
3995 )]
3996 ChildCaixaInvalid { caixa: String, reason: String },
3997 #[error("child {caixa:?} has empty :versao constraint")]
3998 EmptyChildVersion { caixa: String },
3999 #[error(
4000 "child {caixa:?} :versao {versao:?} is not a valid semver requirement: \
4001 {reason} (use Cargo-shaped forms like `\"^0.1\"`, `\"~0.1.2\"`, \
4002 `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` and \
4003 `:membros :versao` carry; the lacre pipeline resolves all three \
4004 through the same parser)"
4005 )]
4006 ChildVersaoInvalid {
4007 caixa: String,
4008 versao: String,
4009 reason: String,
4010 },
4011 #[error(
4012 "child {caixa:?} appears more than once (Erlang/OTP requires unique \
4013 child_spec.id per supervisor; duplicate children materialize as duplicate \
4014 ComputeUnits in the rendered chart, one silently overwriting the other)"
4015 )]
4016 DuplicateChildCaixa { caixa: String },
4017 #[error(
4018 "supervisor {caixa:?} lists itself as a :children entry — a supervisor is \
4019 never its own child (the supervision tree is a DAG rooted at the supervisor; \
4020 OTP child specs reference distinct child processes). Since every :nome is a \
4021 globally-unique substrate identity, a child naming the supervisor's own :nome \
4022 is a one-node reconciliation cycle, not a coincidentally-named peer; drop the \
4023 self-referential :children entry or rename it to the actual child caixa."
4024 )]
4025 ChildSupervisesSelf { caixa: String },
4026}
4027
4028// Fold the three `SupervisorError::<Variant> { caixa: <&str>.to_string() }`
4029// caixa-only struct-variant wire-up sites at [`SupervisorSpec::validate_children`]
4030// and [`validate_no_self_supervision`] onto one substrate primitive per
4031// typed variant — the sibling on `SupervisorError` of the four uniform-shape
4032// `LayoutError`-envelope constructor families the peer
4033// [`crate::layout::layout_violation_ctors!`] macro closed (131ca0d, 16
4034// variants on `{ caixa, issue }`), the [`crate::layout::layout_slot_kind_ctors!`]
4035// macro closed (0419438, 4 variants on `{ caixa, kind, slots }`), the
4036// [`crate::LayoutError::missing_entry`] one-variant ctor closed (1b09f9d,
4037// on `{ kind, path }`), and the [`crate::layout::layout_nome_only_ctors!`]
4038// macro closed (3fe3dd7, 6 variants on `<Variant>(String)`), plus the
4039// [`crate::AplicacaoError::entrada_host_invalid`] one-variant ctor
4040// (17dd504, `{ host, reason }`), the [`crate::aplicacao::contrato_target_ctors!`]
4041// macro (14b81d5, 2 variants on `{ de, para, wit, expected }`), and the
4042// [`crate::aplicacao::contrato_empty_pair_ctors!`] macro (8580068, 4
4043// variants on `{ de, para }`) already at that discipline on the peer
4044// `AplicacaoError` envelopes.
4045//
4046// Each of the three wire-up sites on this shape (`EmptyChildVersion` at
4047// the per-`:children` semver-requirement empty-first arm, `DuplicateChildCaixa`
4048// at the per-`:children` dedup arm, `ChildSupervisesSelf` at the cross-slot
4049// self-supervision arm) opened the identical
4050// `SupervisorError::<Variant> { caixa: <&str>.to_string() }` struct-literal —
4051// the exact "same block re-inlined at every consumer" shape the PRIME
4052// DIRECTIVE names as a bug, on the same altitude the peer `LayoutError` /
4053// `AplicacaoError` families each closed on their sibling envelopes. The
4054// three variants share one `{ caixa: String }` shape, so the fold routes
4055// each wire-up site through one dispatch per typed variant.
4056//
4057// The macro below generates one static constructor per variant of shape
4058// `fn <slot>(caixa: &str) -> SupervisorError`, so every wire-up site
4059// collapses onto one dispatch:
4060// `SupervisorError::<slot>(<&str>)`, byte-equal to the pre-lift
4061// struct-literal on the same `&str` fixture. The uniform one-field
4062// construction (`caixa: caixa.to_string()`) is spelled once — inside the
4063// macro — rather than at every wire-up site. Every constructor is
4064// `#[must_use]` so a caller who mistakenly discards the constructed error
4065// trips a compile warning at the wire-up site.
4066//
4067// Every future consumer that wants to construct one of these three
4068// variants outside `SupervisorSpec::validate_children` /
4069// `validate_no_self_supervision` — a deferred
4070// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
4071// webhook re-checking one added/renamed child, a future
4072// `feira validate --supervisor` per-caixa admission verb, a per-child
4073// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path
4074// once dynamic-children graduate to a typed slot, a per-Supervisor
4075// overlay resolver rejecting a duplicate/self-supervising child against
4076// a cluster-local snapshot — now reaches each variant through one call
4077// rather than re-inlining the three-line struct-literal in lockstep
4078// with the three in-crate wire-up sites.
4079macro_rules! supervisor_caixa_only_ctors {
4080 ($($ctor:ident => $variant:ident),* $(,)?) => {
4081 impl SupervisorError {
4082 $(
4083 #[doc = concat!(
4084 "Construct a [`SupervisorError::",
4085 stringify!($variant),
4086 "`] naming the offending `:children :caixa` (or ",
4087 "supervisor `:nome`, on the self-supervision arm). ",
4088 "Folds the uniform `Self::",
4089 stringify!($variant),
4090 " { caixa: caixa.to_string() }` one-field ",
4091 "struct-literal onto one substrate primitive so ",
4092 "every [`SupervisorSpec::validate_children`] / ",
4093 "[`validate_no_self_supervision`] wire-up on this ",
4094 "variant reads through one dispatch rather than the ",
4095 "pre-lift open-coded struct-literal block."
4096 )]
4097 #[must_use]
4098 pub fn $ctor(caixa: &str) -> Self {
4099 Self::$variant { caixa: caixa.to_string() }
4100 }
4101 )*
4102 }
4103 };
4104}
4105
4106supervisor_caixa_only_ctors! {
4107 empty_child_version => EmptyChildVersion,
4108 duplicate_child_caixa => DuplicateChildCaixa,
4109 child_supervises_self => ChildSupervisesSelf,
4110}
4111
4112// Fold the two `SupervisorError::{ChildCaixaInvalid, ChildVersaoInvalid}`
4113// struct-variant wire-up sites at [`SupervisorSpec::validate_children`] onto
4114// one substrate primitive per typed variant — the M2 supervisor-side siblings
4115// of the peer [`crate::AplicacaoError::membro_caixa_invalid`] two-slot ctor
4116// already lifted through the sibling
4117// [`crate::aplicacao::aplicacao_field_reason_ctors!`] macro (981060b) on the
4118// peer `AplicacaoError { caixa: String, reason: String }` envelope. The
4119// `ChildCaixaInvalid` variant carries the same `{ <name>: String, reason:
4120// String }` two-slot shape the peer seven-variant
4121// [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold closed on the
4122// `AplicacaoError` envelope (`MembroCaixaInvalid`, `EntradaParaInvalid`,
4123// `EntradaHostInvalid`, `EntradaPathInvalid`, `PlacementClusterInvalid`,
4124// `PlacementAffinityInvalid`, `ShardKeyInvalid`); the `ChildVersaoInvalid`
4125// variant carries the `{ caixa: String, versao: String, reason: String }`
4126// three-slot shape the sibling `AplicacaoError::MembroVersaoInvalid` axis
4127// carries on the same `:versao` value-shape.
4128//
4129// Each of the two wire-up sites opened the same closure-shaped
4130// `|reason| SupervisorError::<Variant> { caixa: child.nome().to_string(),
4131// [versao: child.versao_requirement().to_string(),] reason }` block inside
4132// the paired [`crate::render::require_valid_dns_1123_label`] and
4133// [`crate::render::require_valid_versao_requirement`] callbacks — the exact
4134// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE names
4135// as a bug, on the same altitude the peer `AplicacaoError` /
4136// `SupervisorError` / `LayoutError` / `DepError` / `LimitsError` ctor
4137// families already closed on their sibling envelopes.
4138//
4139// The two `#[must_use]` inherent constructors below fold each wire-up onto
4140// one dispatch: `SupervisorError::child_caixa_invalid(<name>, <reason>)`
4141// and `SupervisorError::child_versao_invalid(<name>, <versao>, <reason>)`,
4142// byte-equal to the pre-lift struct-literal on the same scalar fixtures.
4143// The uniform per-field `.to_string()` / `.into()` construction is spelled
4144// once — inside each ctor body — rather than at every wire-up site. The
4145// `reason: impl Into<String>` bound accepts both `&str` literals and
4146// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
4147// diagnostic shape at the lift, matching the peer
4148// [`aplicacao_field_reason_ctors!`] and
4149// [`crate::aplicacao::contrato_pair_value_reason_ctors!`] bounds on the
4150// sibling envelopes.
4151//
4152// Every future consumer that wants to construct one of these two variants
4153// outside `SupervisorSpec::validate_children` — a deferred
4154// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook
4155// re-checking one added/renamed child's `:caixa` or `:versao`, a future
4156// `feira validate --supervisor` per-caixa admission verb, a per-child
4157// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path once
4158// dynamic-children graduate to a typed slot, a per-Supervisor overlay
4159// resolver rejecting a shape-invalid child `:caixa`/`:versao` against a
4160// cluster-local snapshot — now reaches each variant through one call rather
4161// than re-inlining the per-shape struct-literal block in lockstep with the
4162// two in-crate wire-up sites.
4163impl SupervisorError {
4164 /// Construct a [`SupervisorError::ChildCaixaInvalid`] naming the
4165 /// offending `:children :caixa` value under the given `reason`. Folds
4166 /// the uniform `Self::ChildCaixaInvalid { caixa: caixa.to_string(),
4167 /// reason: reason.into() }` two-slot struct-literal onto one substrate
4168 /// primitive so every wire-up on this variant reads through one
4169 /// dispatch, matching the peer
4170 /// [`crate::AplicacaoError::membro_caixa_invalid`] ctor's shape on the
4171 /// sibling `AplicacaoError { caixa: String, reason: String }`
4172 /// envelope. `reason` accepts both `&str` literals and `format!(…)`
4173 /// outputs through the `impl Into<String>` bound.
4174 #[must_use]
4175 pub fn child_caixa_invalid(caixa: &str, reason: impl Into<String>) -> Self {
4176 Self::ChildCaixaInvalid {
4177 caixa: caixa.to_string(),
4178 reason: reason.into(),
4179 }
4180 }
4181
4182 /// Construct a [`SupervisorError::ChildVersaoInvalid`] naming the
4183 /// offending `:children :caixa` and its `:versao` requirement under
4184 /// the given `reason`. Folds the uniform `Self::ChildVersaoInvalid {
4185 /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
4186 /// reason.into() }` three-slot struct-literal onto one substrate
4187 /// primitive so every wire-up on this variant reads through one
4188 /// dispatch, matching the sibling `AplicacaoError::MembroVersaoInvalid
4189 /// { caixa, versao, reason }` three-slot axis on the peer
4190 /// `AplicacaoError` envelope. `reason` accepts both `&str` literals
4191 /// and `format!(…)` outputs through the `impl Into<String>` bound.
4192 #[must_use]
4193 pub fn child_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
4194 Self::ChildVersaoInvalid {
4195 caixa: caixa.to_string(),
4196 versao: versao.to_string(),
4197 reason: reason.into(),
4198 }
4199 }
4200}
4201
4202// Fold the four `SupervisorError::<Variant> { <field>: <Copy> }` one-field
4203// Copy-scalar struct-variant wire-up sites at [`SupervisorSpec::validate`]'s
4204// three bracket-arms — one struct-literal at the `:children`-empty
4205// non-`SimpleOneForOne` refusal cascade (`NoChildren { estrategia }`) plus
4206// three `impl FnOnce(<ty>) -> SupervisorError` bracket-closures at the
4207// [`crate::render::require_positive_bounded_u32`] `:max-restarts` cap arm
4208// (`MaxRestartsExceedsCap { max_restarts }`) and the paired
4209// [`crate::render::require_positive_canonical_bounded_duration`]
4210// `:restart-window` canonical-form + cap arms (`RestartWindowNotCanonical
4211// { window }`, `RestartWindowExceedsCap { window }`) — onto one substrate
4212// primitive per typed variant, matching the sibling
4213// [`crate::aplicacao::aplicacao_policy_scalar_ctors!`] macro (7ef425e, 8
4214// variants on the same `{ <field>: Duration | u32 }` shape) at that
4215// discipline on the peer `AplicacaoError` envelope's per-`:politicas`
4216// scalar axis. Every variant is a one-field `Copy`-pass-through struct-
4217// literal — `RestartStrategy | u32 | Duration` — so the fold routes each
4218// wire-up site through one dispatch per typed variant without a runtime-
4219// work delta.
4220//
4221// Each of the four wire-up sites opened the identical
4222// `SupervisorError::<Variant> { <field>: <val> }` struct-literal — the
4223// exact "same block re-inlined at every consumer" shape the PRIME
4224// DIRECTIVE names as a bug, on the same altitude the peer
4225// `aplicacao_policy_scalar_ctors!` fold closed on the sibling
4226// `AplicacaoError` envelope's per-`:politicas` per-axis cap / canonical-
4227// form arms. The four variants share one `{ <field>: <Copy> }` shape, so
4228// the fold routes each wire-up site through one dispatch per typed
4229// variant.
4230//
4231// The macro below generates one static constructor per variant of shape
4232// `const fn <ctor>(<field>: <ty>) -> SupervisorError`, so every wire-up
4233// site collapses onto one dispatch: `SupervisorError::<ctor>(<val>)`,
4234// byte-equal to the pre-lift struct-literal on the same `Copy`-`<ty>`
4235// fixture — as a direct call at the [`SupervisorSpec::validate`]
4236// `:children`-empty refusal, or as a bare function pointer in the
4237// `impl FnOnce(<ty>) -> SupervisorError` bracket-closure slot every
4238// [`crate::render::require_positive_bounded_u32`] /
4239// [`crate::render::require_positive_canonical_bounded_duration`] gate
4240// carries — rather than the pre-lift open-coded one-line closure over
4241// the same one-field struct-literal. `const fn` preserves the `Copy`-
4242// pass-through's zero-runtime-work property verbatim. Every constructor
4243// is `#[must_use]` so a caller who mistakenly discards the constructed
4244// error trips a compile warning at the wire-up site.
4245//
4246// Every future consumer that wants to construct one of these four
4247// variants outside `SupervisorSpec::validate` — a deferred
4248// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
4249// webhook re-checking one edited `:estrategia` / `:max-restarts` /
4250// `:restart-window` slot against the cap + canonical-form cascade, a
4251// future `feira validate --supervisor` per-caixa admission verb re-
4252// running the shape gates on demand, a per-Supervisor overlay resolver
4253// rejecting an author-supplied slot against a cluster-local snapshot —
4254// now reaches each variant through one call rather than re-inlining the
4255// per-shape struct-literal block in lockstep with the four in-crate
4256// wire-up sites.
4257macro_rules! supervisor_scalar_ctors {
4258 ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
4259 impl SupervisorError {
4260 $(
4261 #[doc = concat!(
4262 "Construct a [`SupervisorError::",
4263 stringify!($variant),
4264 "`] naming the offending per-`:supervisor` `",
4265 stringify!($field),
4266 "` scalar. Folds the uniform `Self::",
4267 stringify!($variant),
4268 " { ",
4269 stringify!($field),
4270 " }` one-field `Copy`-pass-through struct-literal onto ",
4271 "one substrate primitive so every per-axis wire-up on ",
4272 "this variant reads through one dispatch — as a direct ",
4273 "call (`SupervisorError::",
4274 stringify!($ctor),
4275 "(<val>)`, byte-equal to the pre-lift struct-literal on ",
4276 "the same `Copy`-`",
4277 stringify!($ty),
4278 "` fixture) or as a bare function pointer in the ",
4279 "`impl FnOnce(",
4280 stringify!($ty),
4281 ") -> SupervisorError` bracket-closure slot every ",
4282 "`crate::render::require_positive_bounded_*` / ",
4283 "`crate::render::require_positive_canonical_bounded_*` ",
4284 "gate carries — rather than the pre-lift open-coded ",
4285 "one-line closure over the same one-field struct-",
4286 "literal. `const fn` preserves the `Copy`-pass-through's ",
4287 "zero-runtime-work property verbatim."
4288 )]
4289 #[must_use]
4290 pub const fn $ctor($field: $ty) -> Self {
4291 Self::$variant { $field }
4292 }
4293 )*
4294 }
4295 };
4296}
4297
4298supervisor_scalar_ctors! {
4299 no_children => NoChildren { estrategia: RestartStrategy },
4300 max_restarts_exceeds_cap => MaxRestartsExceedsCap { max_restarts: u32 },
4301 restart_window_not_canonical => RestartWindowNotCanonical { window: Duration },
4302 restart_window_exceeds_cap => RestartWindowExceedsCap { window: Duration },
4303}
4304
4305/// Shared duration string codec for the typed slots that take a
4306/// duration (`restart_window`, `MeshPolicy::timeout`,
4307/// `CircuitBreaker::window`, …). Public so [`crate::aplicacao`] can
4308/// reuse it without duplicating the parser.
4309pub mod duration_codec {
4310 use super::Duration;
4311 use serde::{Deserializer, Serializer};
4312
4313 pub fn serialize<S: Serializer>(v: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
4314 // Route through the canonical [`crate::render::serialize_option_via_str`]
4315 // — the substrate-side single-owner primitive for the forward
4316 // arm of the typed-magnitude codec family. See its docstring
4317 // for the full sibling roster.
4318 crate::render::serialize_option_via_str(v, s, render)
4319 }
4320
4321 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
4322 // Route through the canonical [`crate::render::deserialize_option_via_str`]
4323 // — the substrate-side single-owner primitive for the reverse
4324 // arm of the typed-magnitude codec family. See its docstring
4325 // for the full sibling roster.
4326 crate::render::deserialize_option_via_str(d, parse)
4327 }
4328
4329 pub(crate) fn parse(s: &str) -> Result<Duration, String> {
4330 // Paired whitespace-rejection arm — same canonical-form
4331 // render-determinism discipline as the peer
4332 // `limits::parse_byte_size` / `limits::parse_duration` /
4333 // `limits::parse_millicores` /
4334 // `aplicacao::rate_limit_codec::parse` sites: the ASCII
4335 // byte-scan closes the WhatWG-conformant whitespace bytes
4336 // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
4337 // `char::is_whitespace` scan closes the strictly-complementary
4338 // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
4339 // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
4340 // codepoints) that `str::trim` at parse entry silently strips.
4341 // Either drift class would round-trip through `render` to a
4342 // *different* canonical form on next emit — breaking the
4343 // THEORY.md Part V render-determinism contract on three typed-
4344 // duration slots at once (`:supervisor :restart-window`,
4345 // `:politicas :timeout`, `:politicas :circuit-breaker :window`)
4346 // via the shared codec.
4347 //
4348 // Routed through the lifted [`crate::render::reject_whitespace`]
4349 // primitive — the substrate-side single-owner paired-arm gate
4350 // every typed-magnitude codec in caixa-core shares.
4351 crate::render::reject_whitespace::<String, _, _>(
4352 s,
4353 |b| {
4354 format!(
4355 "duration: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
4356 authoring form for the typed duration slots routed through this shared codec \
4357 (`:supervisor :restart-window`, `:politicas :timeout`, \
4358 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
4359 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no whitespace bytes \
4360 anywhere. A whitespace-carrying shape (`\" 30s\"`, `\"30s \"`, `\"30 s\"`, \
4361 `\"\\t30s\"`, `\"30s\\n\"`) round-trips through `render` to a *different* \
4362 canonical form (`\"30s\"`) on first serialize — breaking the THEORY.md \
4363 Part V render-determinism contract every typed slot carries. Strip every \
4364 whitespace byte (write `\"30s\"` verbatim)"
4365 )
4366 },
4367 |ch| {
4368 format!(
4369 "duration: value {s:?} contains non-ASCII Unicode whitespace character \
4370 {ch:?} (U+{cp:04X}) — the canonical authoring form for the typed \
4371 duration slots routed through this shared codec (`:supervisor \
4372 :restart-window`, `:politicas :timeout`, `:politicas :circuit-breaker \
4373 :window`) is `<integer><unit>` (e.g. `\"30s\"`, `\"500ms\"`, `\"2m\"`, \
4374 `\"1h\"`) with no whitespace characters anywhere (ASCII or Unicode). A \
4375 non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}30s\"`, \
4376 `\"30s\\u{{2028}}\"`, `\"30\\u{{2003}}s\"`) survives the ASCII byte-scan \
4377 but `str::trim` (which uses `char::is_whitespace` — the Unicode \
4378 `White_Space` property, strictly wider than the ASCII byte set) silently \
4379 strips it at parse entry, and the value round-trips through `render` to \
4380 a *different* canonical form (`\"30s\"`) on first serialize — breaking \
4381 the THEORY.md Part V render-determinism contract every typed slot \
4382 carries. Strip every non-ASCII whitespace character (write `\"30s\"` \
4383 verbatim with only ASCII bytes)",
4384 cp = ch as u32
4385 )
4386 },
4387 )?;
4388 let s = s.trim();
4389 // Routed through the lifted
4390 // [`crate::render::split_magnitude_and_alpha_unit`] primitive —
4391 // the single-owner split every ASCII-alphabetic-unit typed-
4392 // magnitude codec in caixa-core (`limits::parse_byte_size` /
4393 // `limits::parse_duration` / this shared duration codec) shares.
4394 // See its docstring for the full sibling roster on the same
4395 // primitive altitude.
4396 let (num_part, unit) = crate::render::split_magnitude_and_alpha_unit(s);
4397 let num_trim = num_part.trim();
4398 // The canonical authoring form for every typed slot routed
4399 // through this shared codec — `:supervisor :restart-window`,
4400 // `:politicas :timeout`, `:politicas :circuit-breaker :window`
4401 // — is `<integer><unit>`. Every magnitude [`render`] emits is a
4402 // non-negative integer with no decimal point and no leading
4403 // sign, so the parser's accepted set must match for
4404 // serialize/deserialize to round-trip without canonical-form
4405 // drift. Until this gate landed the parser accepted any
4406 // `f64`-shaped magnitude (`"1.5s"` → 1500ms, `"1.0s"` → 1s,
4407 // `"0.5m"` → 30s, `"+30s"` → 30s) and serde silently round-
4408 // tripped the value to a *different* canonical string on the
4409 // next emit (`"1.5s"` → 1500ms → `"1500ms"`, `"1.0s"` → 1s →
4410 // `"1s"`, `"0.5m"` → 30s → `"30s"`, `"+30s"` → 30s → `"30s"`)
4411 // — breaking the THEORY.md Part V render-determinism contract
4412 // on three typed slots at once. Same canonical-form discipline
4413 // `crate::limits::parse_duration` (818dd38, the immediate
4414 // predecessor on the peer `:limits :wall-clock` codec) applies;
4415 // this gate lifts the discipline onto the shared codec that
4416 // backs the remaining three typed-duration slots in caixa-core.
4417 //
4418 // Strict canonical form: every byte of the magnitude is an
4419 // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
4420 // inputs the gate distinguishes "non-canonical-but-numeric"
4421 // (parses as f64 or i64 — surfaced with a self-locating
4422 // diagnostic naming the canonical authoring form, the
4423 // round-trip drift each rejected shape would produce on first
4424 // serialize, and the canonical-form remediation) from
4425 // "garbage" (parses as neither — surfaced with the existing
4426 // narrower "bad duration magnitude" wording so its diagnostic
4427 // shape remains stable for the parser-shape footgun case).
4428 // The pre-existing `num < 0.0` arm is now unreachable — the
4429 // digit-only gate strictly precedes magnitude parsing, and a
4430 // leading `-` is not an ASCII digit, so `"-30s"` lands on the
4431 // non-canonical-but-numeric branch with the `-30` named
4432 // verbatim in the diagnostic rather than the prior
4433 // value-laundered "negative duration in \"-30s\"" wording.
4434 //
4435 // Routed through the lifted
4436 // [`crate::render::is_digit_only_magnitude`] predicate — the
4437 // same source of truth the four peer typed-magnitude codec
4438 // sites share.
4439 let digit_only = crate::render::is_digit_only_magnitude(num_trim);
4440 if !digit_only {
4441 let numeric = num_trim.parse::<f64>().is_ok() || num_trim.parse::<i64>().is_ok();
4442 if numeric {
4443 return Err(format!(
4444 "duration: magnitude {num_trim:?} is not a non-negative integer — the \
4445 canonical authoring form for the typed duration slots routed through \
4446 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
4447 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
4448 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no decimal point and \
4449 no leading `+` / `-` sign. A fractional / decimal-shaped magnitude \
4450 (`\"1.5s\"`, `\"1.0s\"`, `\"0.5m\"`, `\"+30s\"`, `\"-30s\"`) round-trips \
4451 through `render` to a *different* canonical form (`\"1500ms\"`, `\"1s\"`, \
4452 `\"30s\"`, `\"30s\"`, `\"30s\"`) on first serialize — breaking the \
4453 THEORY.md Part V render-determinism contract every typed slot carries. \
4454 Pick an integer magnitude in the unit that divides cleanly (write \
4455 `\"1500ms\"` instead of `\"1.5s\"`; `\"30s\"` instead of `\"0.5m\"`)"
4456 ));
4457 }
4458 return Err(format!("bad duration magnitude in {s:?}"));
4459 }
4460 // Leading-zero arm — peer with the `rate_limit_codec` leading-
4461 // zero arm (4f46830) on the same canonical-form render-
4462 // determinism axis. The digit-only gate accepts `"030s"`,
4463 // `"00s"`, `"01h"`, `"0500ms"` as `u64::from_str` parses them
4464 // losslessly (= 30, 0, 1, 500), but `render` emits the leading-
4465 // zero-stripped form (`"30s"`, `"0s"`, `"1h"`, `"500ms"`) — a
4466 // *different* canonical string on the next emit, breaking the
4467 // THEORY.md Part V render-determinism contract the same way
4468 // `"+30s"` did before the leading-`+` arm landed. The single-
4469 // byte magnitude `"0"` (or `"0s"` / `"0ms"`) round-trips
4470 // losslessly through `render` (`render(Duration::ZERO)` emits
4471 // `"0s"`) — the downstream semantic-zero gates (e.g.
4472 // `SupervisorError::ZeroRestartWindow` on
4473 // `:supervisor :restart-window`,
4474 // `AplicacaoError::PolicyTimeoutZero` /
4475 // `PolicyCircuitBreakerWindowZero` on the typed `:politicas`
4476 // duration slots) refuse zero-magnitude authoring at the typed-
4477 // validate layer above, so the single-byte `"0"` stays in the
4478 // accepted set at this codec layer and the diagnostic
4479 // partitioning between canonical-form drift (this arm) and
4480 // semantic-zero (the downstream gates) remains stable.
4481 // Peer with the future leading-zero arms on the two remaining
4482 // typed-magnitude codecs the trajectory acknowledges:
4483 // `limits::parse_duration` backing `:limits :wall-clock`,
4484 // `limits::parse_byte_size` backing `:limits :memory` — each
4485 // carries the same canonical-form-drift class today; this
4486 // gate lands the discipline on the shared duration codec
4487 // first because the `rate_limit_codec` predecessor on the
4488 // same canonical-form-drift axis is the closest peer on the
4489 // trajectory.
4490 //
4491 // Routed through the lifted
4492 // [`crate::render::is_leading_zero_padded_magnitude`]
4493 // predicate — the same source of truth the four peer
4494 // typed-magnitude codec sites share.
4495 if crate::render::is_leading_zero_padded_magnitude(num_trim) {
4496 return Err(format!(
4497 "duration: magnitude {num_trim:?} has a non-canonical leading zero — the \
4498 canonical authoring form for the typed duration slots routed through \
4499 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
4500 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
4501 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no leading-zero padding \
4502 on the magnitude. A leading-zero magnitude (`\"030s\"`, `\"00s\"`, \
4503 `\"01h\"`, `\"0500ms\"`) round-trips through `render` to a *different* \
4504 canonical form (`\"30s\"`, `\"0s\"`, `\"1h\"`, `\"500ms\"`) on first \
4505 serialize — breaking the THEORY.md Part V render-determinism contract \
4506 every typed slot carries. Strip the leading zeros (write \
4507 `\"30s\"` instead of `\"030s\"`)"
4508 ));
4509 }
4510 // The digit-only gate guarantees every byte is `[0-9]`, and
4511 // the leading-zero arm above guarantees the magnitude is
4512 // either the single byte `"0"` or starts with `[1-9]`, so
4513 // the only way `u64::from_str` can fail here is overflow (the
4514 // magnitude exceeds `u64::MAX`). Surface that with an
4515 // overflow-shaped wording so the diagnostic names the offending
4516 // magnitude verbatim rather than collapsing onto the
4517 // non-canonical arm. The codec now operates on `u64` end-to-end
4518 // — every accepted magnitude is integer-exact; no f64 mantissa
4519 // drift between author-supplied magnitude and the consumer's
4520 // `Duration` value. Same shape `crate::limits::parse_duration`
4521 // (818dd38) carries on the peer `:limits :wall-clock` axis.
4522 let num: u64 = num_trim.parse::<u64>().map_err(|_| {
4523 format!("bad duration magnitude in {s:?} (digit-only magnitude overflows u64)")
4524 })?;
4525 // Route the `{"ms" | "s" | "" | "m" | "h"} → Duration`
4526 // unit-arm dispatch through the canonical
4527 // [`crate::render::duration_from_integer_magnitude_and_unit`]
4528 // primitive — the substrate-side single-owner unit-dispatch
4529 // table every typed-duration codec in caixa-core routes
4530 // through (peer: `crate::limits::parse_duration` backing
4531 // `:limits :wall-clock`). Every unit conversion is integer-
4532 // exact for an integer magnitude; overflow surfaces via the
4533 // typed `DurationUnitError::Overflow { multiplier }`
4534 // discriminant so this arm reconstructs the pre-lift
4535 // `"duration <num><unit> overflows u64 (magnitude × 60 …)"`
4536 // wording verbatim from `num` / `unit_trim` / the returned
4537 // `multiplier`, and the unknown-unit arm reconstructs the
4538 // pre-lift `"unknown duration unit \"<other>\""` wording from
4539 // the caller-scoped `unit_trim`. Load-bearing pinned by
4540 // `crate::render::tests::duration_from_integer_magnitude_and_unit_matches_pre_lift_unit_dispatch_table`.
4541 let unit_trim = unit.trim();
4542 let dur = crate::render::duration_from_integer_magnitude_and_unit(num, unit_trim).map_err(
4543 |e| match e {
4544 crate::render::DurationUnitError::Overflow { multiplier } => format!(
4545 "duration {num}{unit_trim} overflows u64 (magnitude × {multiplier} > 2^64-1)"
4546 ),
4547 crate::render::DurationUnitError::UnknownUnit => {
4548 format!("unknown duration unit {unit_trim:?}")
4549 }
4550 },
4551 )?;
4552 Ok(dur)
4553 }
4554
4555 /// Render a [`Duration`] in the canonical pleme-io duration string
4556 /// form (`"30s"`, `"1m"`, `"1h"`, `"500ms"`). The same form every
4557 /// caixa typed-duration slot serializes to and the same form K8s
4558 /// Gateway API HTTPRoute `timeouts` / `backendRequest` and Cilium
4559 /// EnvoyConfig per-route timeouts both expect (an integer
4560 /// followed by `s`/`m`/`h`/`ms`, no fractional values, no leading
4561 /// `+`). Lifted to `pub` so caixa-side renderers
4562 /// (`caixa-mesh::gateway_routes`'s :politicas :timeout overlay,
4563 /// the future per-:politicas `CiliumClusterwideEnvoyConfig`
4564 /// emitter, the future caixa-otel collector pipeline emitter) can
4565 /// consume the same canonical formatter without re-inlining the
4566 /// magnitude/unit decision tree (and inheriting the same drift
4567 /// footguns: a subtly different `300ms` vs `0.3s` rendering breaks
4568 /// downstream apply-time parsing in non-obvious ways).
4569 pub fn render(d: Duration) -> String {
4570 let total_ms = d.as_millis();
4571 if total_ms == 0 {
4572 return "0s".into();
4573 }
4574 if total_ms.is_multiple_of(3600 * 1000) {
4575 return format!("{}h", total_ms / (3600 * 1000));
4576 }
4577 if total_ms.is_multiple_of(60 * 1000) {
4578 return format!("{}m", total_ms / (60 * 1000));
4579 }
4580 if total_ms.is_multiple_of(1000) {
4581 return format!("{}s", total_ms / 1000);
4582 }
4583 format!("{total_ms}ms")
4584 }
4585
4586 /// True iff `d` round-trips losslessly through [`render`] + [`parse`].
4587 ///
4588 /// [`render`] truncates a `Duration` to `as_millis()` before picking the
4589 /// largest divisor unit, so any sub-millisecond residue
4590 /// (`d.subsec_nanos() % 1_000_000 != 0`) silently breaks the THEORY.md
4591 /// §V.2.7 render-determinism contract:
4592 ///
4593 /// - `Duration::from_micros(1500)` (= `1_500_000` ns) → `as_millis() == 1`
4594 /// → renders `"1ms"` → parses back to `Duration::from_millis(1)` =
4595 /// `1_000_000` ns ≠ original `1_500_000` ns;
4596 /// - `Duration::from_nanos(1)` (= 1 ns) → `as_millis() == 0` →
4597 /// renders the literal `"0s"`, which the per-axis zero-floor gate
4598 /// on every typed-`Duration` slot then rejects on re-validate.
4599 ///
4600 /// Lifted to a `pub` predicate next to the [`render`] / [`parse`] pair so
4601 /// the codec's round-trippable accepted set lives in exactly one place —
4602 /// every typed-`Duration` slot that routes through this shared codec
4603 /// (`SupervisorSpec::restart_window` via [`super::duration_codec`],
4604 /// [`crate::MeshPolicy::timeout`] / [`crate::CircuitBreaker::window`] via
4605 /// `supervisor::duration_codec` + [`super::duration_codec_required`]) and
4606 /// every typed-`Duration` slot whose own codec shares the same
4607 /// `as_millis()`-truncation shape ([`crate::LimitsSpec::wall_clock`] via
4608 /// [`crate::limits`]'s in-module `parse_duration` / `render_duration`
4609 /// pair) calls this predicate from its `validate()` to bracket the
4610 /// accepted set against the codec's accepted set, structurally. Drift
4611 /// between the codec's granularity and any typed slot's accepted set is
4612 /// then a single-source-of-truth edit at this predicate rather than a
4613 /// silent round-trip break the next consumer discovers at apply time.
4614 ///
4615 /// Peer of [`crate::aplicacao::POLICY_RETRIES_MAX`] /
4616 /// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] and the
4617 /// `is_dns_1123_label` / `is_canonical_rate_limit_window` predicate
4618 /// family — same "typed-slot's valid set matches its codec's accepted
4619 /// set, structurally" discipline carried at the codec layer.
4620 #[must_use]
4621 pub fn is_integer_millisecond_duration(d: Duration) -> bool {
4622 d.subsec_nanos().is_multiple_of(1_000_000)
4623 }
4624}
4625
4626/// Required-Duration variant for fields that aren't Option<Duration>.
4627pub mod duration_codec_required {
4628 use super::Duration;
4629 use serde::{Deserialize, Deserializer, Serializer};
4630
4631 pub fn serialize<S: Serializer>(v: &Duration, s: S) -> Result<S::Ok, S::Error> {
4632 s.serialize_str(&super::duration_codec::render(*v))
4633 }
4634
4635 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
4636 let s = String::deserialize(d)?;
4637 super::duration_codec::parse(&s).map_err(serde::de::Error::custom)
4638 }
4639}
4640
4641#[cfg(test)]
4642mod tests {
4643 use super::*;
4644
4645 fn child(name: &str, ver: &str, restart: RestartPolicy) -> ChildSpec {
4646 ChildSpec {
4647 caixa: name.into(),
4648 versao: ver.into(),
4649 restart,
4650 }
4651 }
4652
4653 #[test]
4654 fn child_spec_string_scalar_accessor_pair_is_const_fn() {
4655 // Fail-before-pass-after pin on [`ChildSpec::nome`] +
4656 // [`ChildSpec::versao_requirement`]'s `const`-eval-surface
4657 // posture. Each accessor projects the per-`:children :caixa`
4658 // / per-`:children :versao` [`String`] storage through the
4659 // `pub const fn` [`String::as_str`] (const-stable since Rust
4660 // 1.87, well within the workspace MSRV) — any future
4661 // accidental downgrade to non-`const` fails the corresponding
4662 // `<name>_via_const_fn` wrapper at caixa-core build time with
4663 // E0015 (`cannot call non-const method`), strictly stronger
4664 // than a runtime `assert!`. Sibling of the peer
4665 // per-M2/M3/universal-axis `String → &str` scalar-accessor
4666 // family pins on the sibling `const`-eval-surface passes
4667 // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
4668 // top-level manifest, [`crate::CaixaVersion::as_str`] at the
4669 // typed-newtype wrapper, [`crate::aplicacao::Membro::nome`] /
4670 // [`crate::aplicacao::Membro::versao_requirement`] at the M3
4671 // membership axis, [`crate::aplicacao::Entrada::hostname`] /
4672 // [`crate::aplicacao::Entrada::destination`] at the M3
4673 // ingress axis,
4674 // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
4675 // M2 upgrade axis, [`crate::dep::Dep::nome`] /
4676 // [`crate::dep::Dep::versao_requirement`] at the dep-graph
4677 // axis, and the per-`:contratos`
4678 // [`crate::aplicacao::WitContract::source`] /
4679 // [`crate::aplicacao::WitContract::destination`] /
4680 // [`crate::aplicacao::WitContract::world_ref`] trio the
4681 // sibling pin at 279823b already anchors).
4682 const fn nome_via_const_fn(c: &ChildSpec) -> &str {
4683 c.nome()
4684 }
4685 const fn versao_via_const_fn(c: &ChildSpec) -> &str {
4686 c.versao_requirement()
4687 }
4688 for (caixa, versao) in [
4689 ("worker-a", "^0.1"),
4690 ("worker-b", "~0.2.3"),
4691 ("collector", "*"),
4692 ] {
4693 let c = child(caixa, versao, RestartPolicy::Permanent);
4694 assert_eq!(nome_via_const_fn(&c), c.nome());
4695 assert_eq!(versao_via_const_fn(&c), c.versao_requirement());
4696 assert_eq!(c.nome(), caixa);
4697 assert_eq!(c.versao_requirement(), versao);
4698 }
4699 }
4700
4701 #[test]
4702 fn supervisor_children_slice_return_accessor_is_const_fn() {
4703 // Fail-before-pass-after pin on [`SupervisorSpec::children`]'s
4704 // `const`-eval-surface posture. The accessor destructures the
4705 // per-`:children` `Vec<ChildSpec>` storage through the
4706 // `pub const fn` [`Vec::as_slice`] (const-stable since Rust
4707 // 1.66, well within the workspace MSRV) — any future
4708 // accidental downgrade to non-`const` fails
4709 // `children_via_const_fn` at caixa-core build time with E0015
4710 // (`cannot call non-const method`), strictly stronger than a
4711 // runtime `assert!`. Sibling of the peer per-M3-mesh-slot
4712 // `Vec → &[T]` slice-return accessor family pin
4713 // [`crate::aplicacao::tests::m3_reference_return_accessor_family_is_const_fn`]
4714 // on the M3 mesh-slot per-`:clusters` / per-`:paths` /
4715 // per-`:membros` / per-`:contratos` slice-return axes, and of
4716 // the peer M2 upgrade-appup axis pin
4717 // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
4718 // on the per-`:upgrade-from :instructions` slice-return axis.
4719 const fn children_via_const_fn(s: &SupervisorSpec) -> &[ChildSpec] {
4720 s.children()
4721 }
4722 // Sweep both the empty-children (leaf-supervisor with no
4723 // static children — the `SimpleOneForOne` dynamic-child
4724 // arm's canonical shape) and the populated-children
4725 // (`OneForOne` / `OneForAll` / `RestForOne` static-child
4726 // arm's canonical shape) axes so the accessor carries a
4727 // const-dispatch pin on both arms.
4728 let s_empty = SupervisorSpec {
4729 estrategia: RestartStrategy::SimpleOneForOne,
4730 max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
4731 restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4732 children: vec![],
4733 };
4734 assert!(children_via_const_fn(&s_empty).is_empty());
4735 assert_eq!(children_via_const_fn(&s_empty), s_empty.children());
4736 let s_full = SupervisorSpec {
4737 estrategia: RestartStrategy::OneForOne,
4738 max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
4739 restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4740 children: vec![
4741 child("worker-a", "^0.1", RestartPolicy::Permanent),
4742 child("worker-b", "~0.2.3", RestartPolicy::Transient),
4743 child("collector", "*", RestartPolicy::Temporary),
4744 ],
4745 };
4746 assert_eq!(children_via_const_fn(&s_full).len(), 3);
4747 assert_eq!(children_via_const_fn(&s_full), s_full.children());
4748 }
4749
4750 #[test]
4751 fn default_has_one_for_one_and_5_restarts_in_60s() {
4752 let s = SupervisorSpec::default();
4753 assert_eq!(s.estrategia, RestartStrategy::OneForOne);
4754 assert_eq!(s.max_restarts, 5);
4755 assert_eq!(s.restart_window, Some(Duration::from_secs(60)));
4756 assert!(s.children.is_empty());
4757 }
4758
4759 #[test]
4760 fn validate_one_for_one_requires_children() {
4761 let mut s = SupervisorSpec::default();
4762 s.children = vec![];
4763 assert!(matches!(
4764 s.validate().unwrap_err(),
4765 SupervisorError::NoChildren { .. }
4766 ));
4767 s.children = vec![child("worker", "^0.1", RestartPolicy::Permanent)];
4768 s.validate().unwrap();
4769 }
4770
4771 #[test]
4772 fn validate_simple_one_for_one_forbids_static_children() {
4773 let mut s = SupervisorSpec {
4774 estrategia: RestartStrategy::SimpleOneForOne,
4775 ..SupervisorSpec::default()
4776 };
4777 s.children
4778 .push(child("w", "^0.1", RestartPolicy::Permanent));
4779 assert_eq!(
4780 s.validate().unwrap_err(),
4781 SupervisorError::SimpleOneForOneWithStaticChildren
4782 );
4783 s.children.clear();
4784 s.validate().unwrap();
4785 }
4786
4787 #[test]
4788 fn validate_rejects_zero_max_restarts() {
4789 let s = SupervisorSpec {
4790 max_restarts: 0,
4791 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4792 ..SupervisorSpec::default()
4793 };
4794 assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
4795 }
4796
4797 // ── upper-cap: SUPERVISOR_MAX_RESTARTS_MAX brackets the typed slot ─────
4798 //
4799 // The cap arm lifts the `:politicas :circuit-breaker :max-failures` /
4800 // `POLICY_BREAKER_MAX_FAILURES_MAX` (2b51ace) discipline onto the peer
4801 // `:supervisor :max-restarts` axis — both fields are "trip the
4802 // next-higher protection layer after N events in a rolling window"
4803 // counters with identical degenerate-at-the-high-end shape, so the
4804 // typed-slot's accepted set lies in `1..=1000` on the supervisor side
4805 // exactly as it lies in `1..=1000` on the breaker side.
4806
4807 #[test]
4808 fn validate_rejects_max_restarts_above_cap() {
4809 // The fail-before-pass-after pin: `SUPERVISOR_MAX_RESTARTS_MAX +
4810 // 1` is structurally one past the cap and silently passed
4811 // validate on every pre-gate codebase because the typed slot's
4812 // only check was the zero-floor arm. The no-op-supervisor vector
4813 // only surfaced at the runtime substrate (Erlang/OTP
4814 // MaxIntensity/Period ratio, the future wasm-operator's
4815 // per-supervisor restart-intensity counter) far from the source
4816 // caixa.lisp with no field naming the offending supervisor.
4817 let s = SupervisorSpec {
4818 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4819 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4820 ..SupervisorSpec::default()
4821 };
4822 assert_eq!(
4823 s.validate().unwrap_err(),
4824 SupervisorError::MaxRestartsExceedsCap {
4825 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4826 }
4827 );
4828 }
4829
4830 #[test]
4831 fn validate_rejects_max_restarts_far_above_cap() {
4832 // The `u32::MAX` worst case — the four-billion-restart
4833 // threshold a typo (`:max-restarts 4294967295`) or a
4834 // struct-literal copy-paste lands in the slot. Pin the cap
4835 // arm's coverage explicitly across the full `u32` overflow so
4836 // a future relaxation that drops the upper bound surfaces
4837 // here. Same shape every other typed-cap arm on this surface
4838 // carries (POLICY_BREAKER_MAX_FAILURES_MAX,
4839 // POLICY_RETRIES_MAX, POLICY_RATE_LIMIT_MAX).
4840 let s = SupervisorSpec {
4841 max_restarts: u32::MAX,
4842 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4843 ..SupervisorSpec::default()
4844 };
4845 assert_eq!(
4846 s.validate().unwrap_err(),
4847 SupervisorError::MaxRestartsExceedsCap {
4848 max_restarts: u32::MAX,
4849 }
4850 );
4851 }
4852
4853 #[test]
4854 fn validate_accepts_max_restarts_at_cap() {
4855 // The boundary value — exactly SUPERVISOR_MAX_RESTARTS_MAX —
4856 // must validate. The cap is inclusive on the top edge,
4857 // matching the POLICY_BREAKER_MAX_FAILURES_MAX /
4858 // POLICY_RETRIES_MAX / LIMITS_MEMORY_WASM32_MAX_BYTES
4859 // discipline on the sibling capped axes. Pin the boundary
4860 // explicitly so a future off-by-one tightening
4861 // (`>= SUPERVISOR_MAX_RESTARTS_MAX` instead of `>`) surfaces
4862 // here as a test failure rather than a silent contract
4863 // narrowing.
4864 let s = SupervisorSpec {
4865 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX,
4866 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4867 ..SupervisorSpec::default()
4868 };
4869 s.validate()
4870 .expect("max_restarts == SUPERVISOR_MAX_RESTARTS_MAX must validate");
4871 }
4872
4873 #[test]
4874 fn validate_accepts_max_restarts_typical_values() {
4875 // The documented production-playbook band positive-control
4876 // sweep — every value Erlang/OTP / Elixir / Riak Core /
4877 // RabbitMQ recommend (1..=100) must pass, plus a sweep
4878 // through the hyperscale band (200, 500, 1000) the cap
4879 // accepts. Pin the inclusive validated set explicitly so a
4880 // future tightening of the ceiling surfaces here.
4881 for n in [1u32, 3, 5, 10, 20, 50, 100, 200, 500, 1000] {
4882 let s = SupervisorSpec {
4883 max_restarts: n,
4884 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4885 ..SupervisorSpec::default()
4886 };
4887 s.validate()
4888 .unwrap_or_else(|e| panic!("max_restarts={n} must validate; got {e:?}"));
4889 }
4890 }
4891
4892 #[test]
4893 fn zero_max_restarts_takes_precedence_over_cap() {
4894 // The cross-arm ordering pin: `0` is structurally outside
4895 // both `1..` (zero-floor) and `..=SUPERVISOR_MAX_RESTARTS_MAX`
4896 // (cap), but the zero-floor diagnostic is the more
4897 // self-locating one (it directly names the counter-axis
4898 // remediation), so the validate gate must fire on zero first.
4899 // Same shape every other zero-then-shape ordering on this
4900 // surface uses (PolicyRetriesZero then
4901 // PolicyRetriesExceedsCap; PolicyBreakerZeroFailures then
4902 // PolicyBreakerMaxFailuresExceedsCap).
4903 let s = SupervisorSpec {
4904 max_restarts: 0,
4905 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4906 ..SupervisorSpec::default()
4907 };
4908 assert_eq!(
4909 s.validate().unwrap_err(),
4910 SupervisorError::ZeroMaxRestarts,
4911 "max_restarts == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
4912 );
4913 }
4914
4915 #[test]
4916 fn max_restarts_cap_takes_precedence_over_restart_window_gates() {
4917 // The cross-arm ordering pin between the cap and the sibling
4918 // `:restart-window` gates (zero-window, canonical-window). A
4919 // supervisor carrying both an over-cap `max_restarts` AND a
4920 // structurally invalid window (zero, sub-ms) must surface the
4921 // cap diagnostic first — the cap arm is wired immediately
4922 // after the zero-restart arm and strictly before the window
4923 // arms, so the offending value the diagnostic names matches
4924 // the order the author would discover the gates by reading
4925 // top-to-bottom through `SupervisorSpec::validate`. Pin the
4926 // order so a future refactor that reorders the arms surfaces
4927 // here as a test failure rather than a silent diagnostic
4928 // regression. Peer of
4929 // `circuit_breaker_max_failures_cap_takes_precedence_over_window_gates`
4930 // on the sibling `:politicas :circuit-breaker` slot.
4931 let s = SupervisorSpec {
4932 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4933 restart_window: Some(Duration::ZERO),
4934 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4935 ..SupervisorSpec::default()
4936 };
4937 assert_eq!(
4938 s.validate().unwrap_err(),
4939 SupervisorError::MaxRestartsExceedsCap {
4940 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4941 },
4942 "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
4943 );
4944 }
4945
4946 #[test]
4947 fn max_restarts_cap_diagnostic_carries_offending_value() {
4948 // The diagnostic-shape pin: the offending `u32` is carried
4949 // verbatim into the `SupervisorError::MaxRestartsExceedsCap`
4950 // variant so the surfaced error message names the value the
4951 // author wrote (`":supervisor :max-restarts (50000) exceeds the
4952 // supervisor-policy ceiling …"`), not just the cap. Same
4953 // self-locating diagnostic shape every other typed-cap arm on
4954 // this surface carries
4955 // (`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` carries
4956 // the offending failure count verbatim,
4957 // `AplicacaoError::PolicyRetriesExceedsCap` carries the offending
4958 // retries count verbatim).
4959 let s = SupervisorSpec {
4960 max_restarts: 50_000,
4961 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4962 ..SupervisorSpec::default()
4963 };
4964 let err = s.validate().unwrap_err();
4965 assert!(
4966 matches!(
4967 err,
4968 SupervisorError::MaxRestartsExceedsCap {
4969 max_restarts: 50_000
4970 }
4971 ),
4972 "got {err:?}"
4973 );
4974 let msg = err.to_string();
4975 assert!(
4976 msg.contains("50000"),
4977 ":supervisor :max-restarts cap diagnostic must carry the offending value verbatim (got: {msg})"
4978 );
4979 }
4980
4981 #[test]
4982 fn supervisor_max_restarts_default_pins_otp_canonical_value() {
4983 // Pin [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] at `5` — the
4984 // Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
4985 // half of Learn You Some Erlang's worker-supervisor default,
4986 // sibling of the `60s` `Period` half that the paired
4987 // [`Default for SupervisorSpec`] impl already pins on the
4988 // sibling `restart_window` axis. Pinning the literal here
4989 // surfaces a future rebrand (a tightening to Elixir's `3`,
4990 // a widening to a per-cluster overlay the operator pins
4991 // through a future `:max-restarts-overrides` slot) as a
4992 // deliberate test edit, not a silent contract migration.
4993 // Peer of the sibling
4994 // [`supervisor_max_restarts_cap_pins_canonical_value`]
4995 // upper-bracket pin on the same axis.
4996 assert_eq!(SUPERVISOR_MAX_RESTARTS_DEFAULT, 5);
4997 }
4998
4999 #[test]
5000 fn default_max_restarts_helper_routes_through_lifted_default() {
5001 // Composition pin: the private `default_max_restarts()`
5002 // serde-`#[serde(default = "…")]` helper on
5003 // [`SupervisorSpec::max_restarts`] must route through the
5004 // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
5005 // typed `pub const` rather than a raw `5` literal. Prior to
5006 // the lift the helper carried an inline `5` with no compile-
5007 // time link back to the shared default, so the wire-format
5008 // author-omitted arm and the caixa-core
5009 // [`crate::manifest::Caixa::supervisor_view`] fold's `unwrap_or(5)`
5010 // arm could silently split on any future default rebrand.
5011 // Byte-parity against the lifted constant closes the split.
5012 assert_eq!(default_max_restarts(), SUPERVISOR_MAX_RESTARTS_DEFAULT);
5013 }
5014
5015 #[test]
5016 fn supervisor_spec_default_max_restarts_routes_through_lifted_default() {
5017 // Composition pin: the [`Default for SupervisorSpec`] impl's
5018 // struct-literal `max_restarts` field must route through the
5019 // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
5020 // typed `pub const` (via the private helper this test's
5021 // sibling `default_max_restarts_helper_routes_through_lifted_default`
5022 // already pins onto the constant). Structurally: every
5023 // `SupervisorSpec::default()` call must yield a
5024 // `max_restarts` field byte-equal to the lifted constant
5025 // (the two paired defaults — the serde-side wire-format arm
5026 // and the struct-literal default arm — cannot silently split
5027 // on any future default rebrand). Peer of the sibling
5028 // `default_has_one_for_one_and_5_restarts_in_60s` shape pin
5029 // — this pin closes the byte-parity arm on the two paired
5030 // altitude entry points onto the shared substrate constant.
5031 assert_eq!(
5032 SupervisorSpec::default().max_restarts(),
5033 SUPERVISOR_MAX_RESTARTS_DEFAULT,
5034 );
5035 }
5036
5037 #[test]
5038 fn supervisor_restart_window_default_pins_otp_canonical_value() {
5039 // Pin [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] at `60s` — the
5040 // Erlang/OTP-canonical `{intensity, 5, 60}` `Period` half of
5041 // Learn You Some Erlang's worker-supervisor default, paired
5042 // with the sibling `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5`
5043 // `MaxIntensity` half this constant is the sliding-window
5044 // denominator of on the same `MaxIntensity / Period`
5045 // restart-intensity ratio. Pinning the literal here surfaces a
5046 // future coherent rebrand of the paired default (Elixir's
5047 // `{max_restarts: 3, max_seconds: 5}`, a per-cluster overlay
5048 // the operator pins through a future
5049 // `:restart-window-overrides` slot) as a deliberate test edit,
5050 // not a silent contract migration. Peer of the sibling
5051 // [`supervisor_max_restarts_default_pins_otp_canonical_value`]
5052 // paired-half pin on the same OTP-canonical default and the
5053 // [`supervisor_restart_window_cap_pins_canonical_value`]
5054 // upper-bracket pin on the same axis.
5055 assert_eq!(SUPERVISOR_RESTART_WINDOW_DEFAULT, Duration::from_secs(60),);
5056 }
5057
5058 #[test]
5059 fn supervisor_spec_default_restart_window_routes_through_lifted_default() {
5060 // Composition pin: the [`Default for SupervisorSpec`] impl's
5061 // struct-literal `restart_window` field must route through the
5062 // substrate-canonical [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
5063 // typed `pub const` rather than a raw
5064 // `Duration::from_secs(60)` literal. Prior to this lift the
5065 // paired `{intensity, 5, 60}` OTP-canonical default was split
5066 // across two altitudes with no compile-time link between the
5067 // halves — the `MaxIntensity` half rode through the lifted
5068 // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant while the
5069 // `Period` half rode as an open-coded literal at the
5070 // composition site, so a future coherent rebrand of the paired
5071 // canonical would have had to migrate one half through the
5072 // constant and the other through a raw literal in lockstep.
5073 // Byte-parity against the lifted constant on the `Period` half
5074 // closes the split — the paired OTP-canonical default now
5075 // migrates as one unit on any future axis change. Peer of the
5076 // sibling
5077 // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
5078 // byte-parity pin on the paired `MaxIntensity` half.
5079 assert_eq!(
5080 SupervisorSpec::default().restart_window(),
5081 Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
5082 );
5083 }
5084
5085 #[test]
5086 fn supervisor_estrategia_default_pins_otp_canonical_value() {
5087 // Pin [`SUPERVISOR_ESTRATEGIA_DEFAULT`] at [`RestartStrategy::OneForOne`]
5088 // — the Erlang/OTP-canonical `one_for_one` half of Learn You Some
5089 // Erlang's `{one_for_one, intensity, 5, 60}` worker-supervisor
5090 // canonical default, paired with the sibling
5091 // `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5` `MaxIntensity` half and the
5092 // sibling `SUPERVISOR_RESTART_WINDOW_DEFAULT` `60s` `Period` half
5093 // this constant is the strategy discriminator of on the same
5094 // OTP-canonical worker-supervisor default. Pinning the arm here
5095 // surfaces a future coherent rebrand of the paired triple (Elixir's
5096 // `{:one_for_one, max_restarts: 3, max_seconds: 5}` on the sibling
5097 // intensity/period axes leaving this strategy arm untouched, an OTP
5098 // `rest_for_one` widening once the substrate discovers startup-
5099 // order-coupled child cohorts as the more common worker-supervisor
5100 // shape, a per-cluster overlay the operator pins through a future
5101 // `:estrategia-overrides` slot the MESH-COMPOSITION §III.2
5102 // supervision-canary roadmap acknowledges) as a deliberate test
5103 // edit, not a silent contract migration. Peer of the sibling
5104 // [`supervisor_max_restarts_default_pins_otp_canonical_value`] +
5105 // [`supervisor_restart_window_default_pins_otp_canonical_value`]
5106 // paired-half pins on the same OTP-canonical default.
5107 assert_eq!(SUPERVISOR_ESTRATEGIA_DEFAULT, RestartStrategy::OneForOne);
5108 }
5109
5110 #[test]
5111 fn restart_strategy_default_routes_through_lifted_default() {
5112 // Composition pin: the [`Default for RestartStrategy`] impl's
5113 // return arm must route through the substrate-canonical
5114 // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
5115 // a raw `Self::OneForOne` arm. Prior to the lift the impl carried
5116 // an inline `Self::OneForOne` with no compile-time link back to
5117 // the shared OTP-canonical `one_for_one` strategy the paired
5118 // [`Default for SupervisorSpec`] impl's struct-literal `estrategia`
5119 // field and the [`crate::manifest::Caixa::supervisor_view`] fold's
5120 // `.unwrap_or_default()` (now
5121 // `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)`) arm both key off —
5122 // so a future rebrand of the OTP-canonical strategy default (an
5123 // OTP `rest_for_one` widening once the substrate discovers
5124 // startup-order-coupled child cohorts as the more common worker-
5125 // supervisor shape, a per-cluster overlay the operator pins
5126 // through a future `:estrategia-overrides` slot) would have had to
5127 // be threaded through the `Default` impl and the two peer routes
5128 // in lockstep or the three consumers would silently split. Byte-
5129 // parity against the lifted constant closes the split. Peer of
5130 // the sibling
5131 // [`default_max_restarts_helper_routes_through_lifted_default`] +
5132 // [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
5133 // composition pins on the paired `MaxIntensity` + `Period` halves.
5134 assert_eq!(RestartStrategy::default(), SUPERVISOR_ESTRATEGIA_DEFAULT,);
5135 }
5136
5137 #[test]
5138 fn supervisor_spec_default_estrategia_routes_through_lifted_default() {
5139 // Composition pin: the [`Default for SupervisorSpec`] impl's
5140 // struct-literal `estrategia` field must route through the
5141 // substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed
5142 // `pub const` (either directly, or via the
5143 // [`RestartStrategy::default`] impl that the sibling
5144 // `restart_strategy_default_routes_through_lifted_default` pin
5145 // already routes onto the constant). Structurally: every
5146 // `SupervisorSpec::default()` call must yield an `estrategia`
5147 // field byte-equal to the lifted constant (the three paired
5148 // defaults — the [`Default for RestartStrategy`] impl arm, the
5149 // struct-literal default arm here, and the
5150 // [`crate::manifest::Caixa::supervisor_view`] fold arm — cannot
5151 // silently split on any future default rebrand). Peer of the
5152 // sibling
5153 // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
5154 // + [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
5155 // byte-parity pins on the paired `MaxIntensity` + `Period` halves
5156 // of the same `SupervisorSpec::default()` composed altitude.
5157 assert_eq!(
5158 SupervisorSpec::default().estrategia(),
5159 SUPERVISOR_ESTRATEGIA_DEFAULT,
5160 );
5161 }
5162
5163 #[test]
5164 fn supervisor_spec_default_routes_through_otp_canonical_ctor() {
5165 // Composition pin: the [`Default for SupervisorSpec`] impl must
5166 // route through the substrate-canonical
5167 // [`SupervisorSpec::otp_canonical`] `pub const fn` constructor
5168 // rather than a re-hand-authored struct-literal cascade. Sharpens
5169 // the sibling per-arm
5170 // `supervisor_spec_default_*_routes_through_lifted_default` pins
5171 // from a per-field lift into a whole-struct one-source-of-truth
5172 // pin — the derived-until-now [`Default::default`] and the
5173 // [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
5174 // construction, not by coincidence.
5175 //
5176 // A future extension of the OTP-canonical baseline (a fifth
5177 // `restart_intensity` field the Erlang/OTP `#supervisor` record
5178 // grows, a per-child-cohort split of the `restart_window` /
5179 // `max_restarts` pair, an M4 `mesh.pleme.io/v1alpha1/Supervisor`
5180 // CR materializer's admission-time overlay pass) reaches both
5181 // paths through exactly one edit on
5182 // [`SupervisorSpec::otp_canonical`] — the derived path could
5183 // silently disagree with the constructor's shape on any new
5184 // field whose [`Default::default`] resolves to a different arm
5185 // than the OTP-canonical baseline the constructor names, while
5186 // this delegated impl reaches the constructor directly and
5187 // picks up every future extension by construction.
5188 //
5189 // Fourth peer on the M2 / M3 typed-slot-spec
5190 // [`Default`]-through-const-ctor fold family — sibling of the
5191 // [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
5192 // (abd52c2), [`crate::aplicacao::MeshPolicy`]
5193 // [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`]
5194 // (91641a4), and [`crate::BehaviorSpec`]
5195 // [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c)
5196 // per-`Option`-only-typed-slot folds — extended here onto the
5197 // M2 supervisor-slot [`SupervisorSpec`] whose canonical baseline
5198 // is not "everything `None`" but the Erlang/OTP-canonical
5199 // `{one_for_one, 5, 60}` worker-supervisor triple.
5200 assert_eq!(SupervisorSpec::default(), SupervisorSpec::otp_canonical());
5201 }
5202
5203 #[test]
5204 fn supervisor_spec_otp_canonical_byte_equals_default() {
5205 // Value pin: [`SupervisorSpec::otp_canonical`] must byte-equal
5206 // the hand-authored `{one_for_one, 5, 60, []}` OTP-canonical
5207 // baseline the sibling `default_has_one_for_one_and_5_restarts_in_60s`
5208 // pin already asserts against the [`Default::default`] path.
5209 // Sharpens the pair-invariant into a per-constructor pin so a
5210 // future extension of [`SupervisorSpec`] with a fifth field
5211 // whose OTP-canonical shape is non-`Default::default`-equivalent
5212 // trips at caixa-core test time rather than at a downstream
5213 // consumer that composed [`SupervisorSpec::otp_canonical`] with
5214 // [`SupervisorSpec::validate`] as its "canonical baseline
5215 // seed".
5216 let canonical = SupervisorSpec::otp_canonical();
5217 assert_eq!(canonical.estrategia, RestartStrategy::OneForOne);
5218 assert_eq!(canonical.max_restarts, 5);
5219 assert_eq!(canonical.restart_window, Some(Duration::from_secs(60)));
5220 assert!(canonical.children.is_empty());
5221 }
5222
5223 #[test]
5224 fn supervisor_spec_otp_canonical_is_usable_in_const_context() {
5225 // Const-context pin: [`SupervisorSpec::otp_canonical`] must
5226 // remain callable from a `const`-bound position so downstream
5227 // `const`-context callers wanting a canonical OTP-baseline seed
5228 // can construct one at compile time without runtime dispatch on
5229 // the derived [`Default::default`]. Peer of the sibling
5230 // `pub const fn` [`crate::LimitsSpec::empty`] /
5231 // [`crate::aplicacao::MeshPolicy::empty`] /
5232 // [`crate::BehaviorSpec::empty`] constructors on the sibling
5233 // typed-slot-spec `pub const fn` axis. If a future edit breaks
5234 // the `const`-eligibility of [`SupervisorSpec::otp_canonical`]
5235 // (a non-`const` field-default helper, a non-`const`-stable
5236 // container type promotion), this evaluation fails at
5237 // build time on this file rather than at a downstream
5238 // `const`-context call site.
5239 const CANONICAL: SupervisorSpec = SupervisorSpec::otp_canonical();
5240 assert_eq!(CANONICAL.estrategia, SUPERVISOR_ESTRATEGIA_DEFAULT);
5241 assert_eq!(CANONICAL.max_restarts, SUPERVISOR_MAX_RESTARTS_DEFAULT);
5242 assert_eq!(
5243 CANONICAL.restart_window,
5244 Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
5245 );
5246 assert!(CANONICAL.children.is_empty());
5247 }
5248
5249 #[test]
5250 fn supervisor_child_restart_default_pins_otp_canonical_value() {
5251 // Pin [`SUPERVISOR_CHILD_RESTART_DEFAULT`] at
5252 // [`RestartPolicy::Permanent`] — Erlang/OTP's `permanent`
5253 // worker-child restart type (`{ChildId, StartFunc, permanent, …}`
5254 // in a `supervisor`'s `init/1` child-spec tuple), the per-child
5255 // half of the same OTP-shape supervisor-tree default set whose
5256 // per-`:supervisor` halves the sibling
5257 // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
5258 // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] /
5259 // [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] constants pin. Pinning the
5260 // arm here surfaces a future rebrand of the per-child default (an
5261 // OTP-`transient` widening once the substrate discovers clean-
5262 // completion-aware children as the more common child shape, a
5263 // per-cluster overlay the operator pins through a future
5264 // `:restart-overrides` slot the MESH-COMPOSITION §III.2
5265 // supervision-canary roadmap acknowledges) as a deliberate test
5266 // edit, not a silent contract migration. Peer of the sibling
5267 // [`supervisor_estrategia_default_pins_otp_canonical_value`] /
5268 // [`supervisor_max_restarts_default_pins_otp_canonical_value`] /
5269 // [`supervisor_restart_window_default_pins_otp_canonical_value`]
5270 // value pins on the per-`:supervisor` halves.
5271 assert_eq!(SUPERVISOR_CHILD_RESTART_DEFAULT, RestartPolicy::Permanent);
5272 }
5273
5274 #[test]
5275 fn restart_policy_default_routes_through_lifted_default() {
5276 // Composition pin: the [`Default for RestartPolicy`] impl's return
5277 // arm must route through the substrate-canonical
5278 // [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const` rather
5279 // than a raw `Self::Permanent` arm. Prior to the lift the impl
5280 // carried an inline `Self::Permanent` with no compile-time link
5281 // back to the OTP-shape supervisor-tree default set whose three
5282 // per-`:supervisor` halves already rode through lifted constants
5283 // — so a future coherent rebrand of the set would have had to
5284 // migrate three halves through typed constants and this fourth
5285 // through a raw enum arm in lockstep or the supervisor-level and
5286 // child-level defaults would silently drift apart. Byte-parity
5287 // against the lifted constant closes the split. Peer of the
5288 // sibling
5289 // [`restart_strategy_default_routes_through_lifted_default`]
5290 // composition pin on the per-`:supervisor` `:estrategia` axis.
5291 assert_eq!(RestartPolicy::default(), SUPERVISOR_CHILD_RESTART_DEFAULT);
5292 }
5293
5294 #[test]
5295 fn child_spec_serde_default_restart_routes_through_lifted_default() {
5296 // Composition pin: the serde-side `#[serde(default)]` on
5297 // [`ChildSpec::restart`] — the wire-format author-omitted
5298 // `:children :restart` arm — must resolve onto the substrate-
5299 // canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const`
5300 // (via the [`Default for RestartPolicy`] impl the sibling
5301 // `restart_policy_default_routes_through_lifted_default` pin
5302 // already routes onto the constant). Structurally: a `ChildSpec`
5303 // deserialized from a payload that omits the `restart` key must
5304 // yield a `restart` field byte-equal to the lifted constant, so
5305 // the wire-format author-omitted arm and the
5306 // [`RestartPolicy::default`] impl arm cannot silently split on any
5307 // future default rebrand. Peer of the sibling
5308 // [`supervisor_spec_default_estrategia_routes_through_lifted_default`]
5309 // / [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
5310 // / [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
5311 // byte-parity pins on the per-`:supervisor` halves of the same
5312 // author-omitted-slot resolution surface.
5313 let omitted: ChildSpec = serde_json::from_str(r#"{"caixa":"worker","versao":"^0.1"}"#)
5314 .expect("ChildSpec must deserialize with the restart key omitted");
5315 assert_eq!(
5316 omitted.restart(),
5317 SUPERVISOR_CHILD_RESTART_DEFAULT,
5318 "an author-omitted :children :restart slot must degrade onto \
5319 the SUPERVISOR_CHILD_RESTART_DEFAULT typed pub const (got \
5320 {:?}, expected {:?})",
5321 omitted.restart(),
5322 SUPERVISOR_CHILD_RESTART_DEFAULT,
5323 );
5324 }
5325
5326 #[test]
5327 fn supervisor_max_restarts_cap_pins_canonical_value() {
5328 // The SUPERVISOR_MAX_RESTARTS_MAX constant pins the value at
5329 // 1000 — the same ceiling the peer
5330 // POLICY_BREAKER_MAX_FAILURES_MAX cap carries on the
5331 // `:politicas :circuit-breaker :max-failures` axis (both are
5332 // "trip the next-higher protection layer after N events in a
5333 // rolling window" counters with identical
5334 // degenerate-at-the-high-end shape; uniform top edge so the
5335 // M4 CR materializers and the wasm-operator reconciler reach
5336 // for either field knowing the value is in `1..=1000`). Two
5337 // orders of magnitude above every documented Erlang/OTP /
5338 // Elixir / Riak Core / RabbitMQ production-playbook
5339 // recommendation band and below the clearly-pathological
5340 // "effectively no escalation" floor (10_000, 100_000,
5341 // u32::MAX). Pinning the literal value here surfaces a future
5342 // drift (a relaxation to 10_000, a tightening to 100) as a
5343 // deliberate test edit, not a silent contract narrowing.
5344 assert_eq!(SUPERVISOR_MAX_RESTARTS_MAX, 1000);
5345 }
5346
5347 #[test]
5348 fn validate_rejects_empty_child_name() {
5349 let s = SupervisorSpec {
5350 children: vec![child("", "^0.1", RestartPolicy::Permanent)],
5351 ..SupervisorSpec::default()
5352 };
5353 assert_eq!(s.validate().unwrap_err(), SupervisorError::EmptyChildName);
5354 }
5355
5356 #[test]
5357 fn validate_rejects_empty_child_version() {
5358 let s = SupervisorSpec {
5359 children: vec![child("w", "", RestartPolicy::Permanent)],
5360 ..SupervisorSpec::default()
5361 };
5362 assert!(matches!(
5363 s.validate().unwrap_err(),
5364 SupervisorError::EmptyChildVersion { .. }
5365 ));
5366 }
5367
5368 // ── value-shape: parse-as-VersionReq on :children :versao ─────────────
5369
5370 #[test]
5371 fn validate_rejects_invalid_child_versao_requirement() {
5372 // The fail-before-pass-after pin: a non-empty but malformed
5373 // semver requirement (`"^bad-version"`) silently passed
5374 // `validate()` on every pre-gate codebase because the prior
5375 // shape only refused the empty string. The parse failure
5376 // surfaced far downstream at lacre-resolve time with a
5377 // `semver::Error` that didn't name which `:children` entry
5378 // carried the typo. The new gate moves the check to caixa-build
5379 // time at the source caixa.lisp — the third `:versao` typed
5380 // axis (`:children`) joins `:deps` and `:membros` (9888b13) at
5381 // structural parity.
5382 let s = SupervisorSpec {
5383 children: vec![
5384 child("worker", "^0.1", RestartPolicy::Permanent),
5385 child("cache", "^bad-version", RestartPolicy::Transient),
5386 ],
5387 ..SupervisorSpec::default()
5388 };
5389 let err = s.validate().unwrap_err();
5390 assert!(
5391 matches!(
5392 err,
5393 SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
5394 if caixa == "cache" && versao == "^bad-version"
5395 ),
5396 "got {err:?}"
5397 );
5398 }
5399
5400 #[test]
5401 fn validate_rejects_child_versao_with_double_caret_typo() {
5402 // `"^^0.1"` is the canonical doubled-caret typo — looks
5403 // Cargo-shaped on first glance but fails the parser because
5404 // semver doesn't accept stacked operators. Pin this
5405 // adjacent-shape footgun explicitly so a future relaxation that
5406 // accepts "looks-canonical-but-isn't" forms surfaces here.
5407 let s = SupervisorSpec {
5408 children: vec![child("worker", "^^0.1", RestartPolicy::Permanent)],
5409 ..SupervisorSpec::default()
5410 };
5411 let err = s.validate().unwrap_err();
5412 assert!(
5413 matches!(
5414 err,
5415 SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
5416 if caixa == "worker" && versao == "^^0.1"
5417 ),
5418 "got {err:?}"
5419 );
5420 }
5421
5422 #[test]
5423 fn validate_rejects_child_versao_with_v_prefixed_tag() {
5424 // `"v0.1"` is the canonical "git-tag-shape leaking into the
5425 // semver requirement slot" typo — an author copies the
5426 // publish-side git-tag string verbatim into `:versao`, but
5427 // Cargo's semver parser rejects the leading `v`. Same
5428 // adjacent-shape footgun pinned for `:membros :versao`
5429 // (9888b13).
5430 let s = SupervisorSpec {
5431 children: vec![child("worker", "v0.1", RestartPolicy::Permanent)],
5432 ..SupervisorSpec::default()
5433 };
5434 let err = s.validate().unwrap_err();
5435 assert!(
5436 matches!(
5437 err,
5438 SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
5439 if caixa == "worker" && versao == "v0.1"
5440 ),
5441 "got {err:?}"
5442 );
5443 }
5444
5445 #[test]
5446 fn validate_accepts_canonical_child_versao_forms() {
5447 // The Cargo-shaped requirement forms `:deps :versao` and
5448 // `:membros :versao` already accept via
5449 // `crate::parse_requirement` must pass the children gate
5450 // without re-validating at the resolver layer. Pin every leg so
5451 // a future tightening of the canonical set surfaces here as a
5452 // test failure.
5453 for form in [
5454 "^0.1", // caret — minor-range pin (the most common shape)
5455 "~0.1.2", // tilde — patch-range pin
5456 "0.1.0", // exact — single-version pin
5457 "*", // wildcard — any version (semver::VersionReq::STAR)
5458 ">=0.1, <2", // multi-range — comma-separated comparators
5459 ] {
5460 let s = SupervisorSpec {
5461 children: vec![child("worker", form, RestartPolicy::Permanent)],
5462 ..SupervisorSpec::default()
5463 };
5464 s.validate()
5465 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
5466 }
5467 }
5468
5469 #[test]
5470 fn child_versao_empty_takes_precedence_over_invalid() {
5471 // Order pin: the existing `EmptyChildVersion` diagnostic (which
5472 // doesn't try to parse) fires before the new
5473 // `ChildVersaoInvalid` parse-side diagnostic, so an empty
5474 // `:versao` keeps its narrower error message —
5475 // `parse_requirement` would also reject `""`, but the
5476 // empty-string arm is the more self-locating diagnostic for the
5477 // author. Same ordering discipline as
5478 // `membro_versao_empty_takes_precedence_over_invalid` in
5479 // aplicacao.rs.
5480 let s = SupervisorSpec {
5481 children: vec![child("worker", "", RestartPolicy::Permanent)],
5482 ..SupervisorSpec::default()
5483 };
5484 let err = s.validate().unwrap_err();
5485 assert!(
5486 matches!(err, SupervisorError::EmptyChildVersion { ref caixa } if caixa == "worker"),
5487 "got {err:?}"
5488 );
5489 }
5490
5491 #[test]
5492 fn child_versao_invalid_fires_before_duplicate_check() {
5493 // Order pin: a malformed requirement on a non-duplicate entry
5494 // surfaces *its own* diagnostic (which names the offending
5495 // `:versao` string), even when a later entry would otherwise
5496 // collapse onto an earlier name. The per-entry shape gate runs
5497 // inline before the duplicate-key insert — parallel to
5498 // `membro_versao_invalid_fires_before_duplicate_check` in
5499 // aplicacao.rs and the b0c8389 / c4213a4 ordering discipline.
5500 let s = SupervisorSpec {
5501 children: vec![
5502 child("worker", "^bad", RestartPolicy::Permanent),
5503 child("cache", "^0.1", RestartPolicy::Transient),
5504 child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
5505 ],
5506 ..SupervisorSpec::default()
5507 };
5508 let err = s.validate().unwrap_err();
5509 assert!(
5510 matches!(
5511 err,
5512 SupervisorError::ChildVersaoInvalid { ref caixa, .. } if caixa == "worker"
5513 ),
5514 "got {err:?}"
5515 );
5516 }
5517
5518 #[test]
5519 fn child_versao_invalid_diagnostic_carries_offending_versao() {
5520 // The diagnostic-shape pin: the error names the offending
5521 // `:versao` value verbatim so the author can grep their
5522 // caixa.lisp without re-running the build, and carries a
5523 // non-empty `reason` from `semver::VersionReq::parse` so the
5524 // parser's own wording flows through to the diagnostic.
5525 let s = SupervisorSpec {
5526 children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
5527 ..SupervisorSpec::default()
5528 };
5529 let err = s.validate().unwrap_err();
5530 let SupervisorError::ChildVersaoInvalid {
5531 caixa,
5532 versao,
5533 reason,
5534 } = err
5535 else {
5536 panic!("expected ChildVersaoInvalid, got other variant");
5537 };
5538 assert_eq!(caixa, "worker");
5539 assert_eq!(versao, "not-a-req");
5540 assert!(
5541 !reason.is_empty(),
5542 "ChildVersaoInvalid `reason` must carry the parser's wording verbatim"
5543 );
5544 }
5545
5546 // ── value-shape: DNS-1123 label rule on :children :caixa ──────────────
5547
5548 #[test]
5549 fn validate_rejects_child_caixa_with_uppercase() {
5550 // The canonical "I copied the Servico's display name verbatim"
5551 // typo — child caixa names are lowercase per K8s DNS-1123 label
5552 // rule. The diagnostic names the offending name and suggests the
5553 // lower-cased fix in one edit, mirroring the
5554 // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0).
5555 let s = SupervisorSpec {
5556 children: vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
5557 ..SupervisorSpec::default()
5558 };
5559 let err = s.validate().unwrap_err();
5560 let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
5561 panic!("expected ChildCaixaInvalid, got other variant");
5562 };
5563 assert_eq!(caixa, "Worker");
5564 assert!(
5565 reason.contains("uppercase"),
5566 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
5567 );
5568 assert!(
5569 reason.contains("\"worker\""),
5570 "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
5571 );
5572 }
5573
5574 #[test]
5575 fn validate_rejects_child_caixa_with_underscore() {
5576 // The canonical "I'm thinking of a Python module / Postgres
5577 // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
5578 // label schema. K8s rejects `metadata.name: my_worker` at
5579 // admission time with an opaque `field is invalid` (no source-
5580 // citing diagnostic). The gate moves it to caixa-build time.
5581 let s = SupervisorSpec {
5582 children: vec![child("my_worker", "^0.1", RestartPolicy::Permanent)],
5583 ..SupervisorSpec::default()
5584 };
5585 let err = s.validate().unwrap_err();
5586 assert!(
5587 matches!(
5588 err,
5589 SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
5590 if caixa == "my_worker" && reason.contains('_')
5591 ),
5592 "got {err:?}"
5593 );
5594 }
5595
5596 #[test]
5597 fn validate_rejects_child_caixa_with_dot() {
5598 // A `:children :caixa` entry is a single DNS-1123 label, not a
5599 // subdomain. The K8s Service / ComputeUnit `metadata.name` rules
5600 // forbid dots. Same shape as `rejects_membro_caixa_with_dot`
5601 // (3f9d7a0) on the peer name axis.
5602 let s = SupervisorSpec {
5603 children: vec![child("team.worker", "^0.1", RestartPolicy::Permanent)],
5604 ..SupervisorSpec::default()
5605 };
5606 let err = s.validate().unwrap_err();
5607 assert!(
5608 matches!(
5609 err,
5610 SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
5611 if caixa == "team.worker" && reason.contains('.')
5612 ),
5613 "got {err:?}"
5614 );
5615 }
5616
5617 #[test]
5618 fn validate_rejects_child_caixa_with_leading_hyphen() {
5619 // DNS-1123 / DNS-1035 boundary rule: labels must start and end
5620 // with an alphanumeric. The K8s apiserver rejects `-worker`
5621 // outright; the renderer would emit a `metadata.name: "-worker"`
5622 // that fails admission far from the source caixa.lisp.
5623 let s = SupervisorSpec {
5624 children: vec![child("-worker", "^0.1", RestartPolicy::Permanent)],
5625 ..SupervisorSpec::default()
5626 };
5627 let err = s.validate().unwrap_err();
5628 assert!(
5629 matches!(
5630 err,
5631 SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
5632 if caixa == "-worker" && reason.contains("start and end")
5633 ),
5634 "got {err:?}"
5635 );
5636 }
5637
5638 #[test]
5639 fn validate_rejects_child_caixa_with_trailing_hyphen() {
5640 // The symmetric arm of the boundary rule. Pin separately so
5641 // both ends of the label are covered against a future relaxation
5642 // that only checks one boundary.
5643 let s = SupervisorSpec {
5644 children: vec![child("worker-", "^0.1", RestartPolicy::Permanent)],
5645 ..SupervisorSpec::default()
5646 };
5647 let err = s.validate().unwrap_err();
5648 assert!(
5649 matches!(
5650 err,
5651 SupervisorError::ChildCaixaInvalid { ref caixa, .. }
5652 if caixa == "worker-"
5653 ),
5654 "got {err:?}"
5655 );
5656 }
5657
5658 #[test]
5659 fn validate_rejects_child_caixa_with_unicode() {
5660 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
5661 // (`xn--…`) by the author before it reaches K8s. The byte-by-
5662 // byte ASCII validity check rejects multi-byte UTF-8 sequences
5663 // by the first byte that fails the `[a-z0-9-]` predicate.
5664 let s = SupervisorSpec {
5665 children: vec![child("café", "^0.1", RestartPolicy::Permanent)],
5666 ..SupervisorSpec::default()
5667 };
5668 let err = s.validate().unwrap_err();
5669 assert!(
5670 matches!(
5671 err,
5672 SupervisorError::ChildCaixaInvalid { ref caixa, .. }
5673 if caixa == "café"
5674 ),
5675 "got {err:?}"
5676 );
5677 }
5678
5679 #[test]
5680 fn validate_rejects_child_caixa_with_whitespace() {
5681 // Whitespace is the canonical "I pasted from a sketch / doc"
5682 // footgun. The apiserver rejects every `metadata.name` value
5683 // carrying whitespace; pin the gate fires at the right boundary.
5684 let s = SupervisorSpec {
5685 children: vec![child("my worker", "^0.1", RestartPolicy::Permanent)],
5686 ..SupervisorSpec::default()
5687 };
5688 let err = s.validate().unwrap_err();
5689 assert!(
5690 matches!(
5691 err,
5692 SupervisorError::ChildCaixaInvalid { ref caixa, .. }
5693 if caixa == "my worker"
5694 ),
5695 "got {err:?}"
5696 );
5697 }
5698
5699 #[test]
5700 fn validate_rejects_child_caixa_too_long() {
5701 // The 64-byte boundary pin. DNS-1123 / DNS-1035 cap labels at
5702 // 63 bytes; the K8s apiserver rejects every `metadata.name`
5703 // axis over the limit at admission time. The diagnostic names
5704 // both the cap and the actual length so the author can shorten
5705 // in one edit, mirroring `rejects_membro_caixa_too_long`
5706 // (3f9d7a0) and `rejects_placement_cluster_too_long` (6cbb900).
5707 let too_long = "a".repeat(64);
5708 let s = SupervisorSpec {
5709 children: vec![child(&too_long, "^0.1", RestartPolicy::Permanent)],
5710 ..SupervisorSpec::default()
5711 };
5712 let err = s.validate().unwrap_err();
5713 let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
5714 panic!("expected ChildCaixaInvalid, got other variant");
5715 };
5716 assert_eq!(caixa, too_long);
5717 assert!(
5718 reason.contains("63"),
5719 "diagnostic must name the 63-byte cap (got: {reason:?})"
5720 );
5721 assert!(
5722 reason.contains("64"),
5723 "diagnostic must name the actual length (got: {reason:?})"
5724 );
5725 }
5726
5727 #[test]
5728 fn child_caixa_max_length_validates() {
5729 // The 63-byte boundary control pin — exactly-at-the-cap is
5730 // accepted, mirroring `membro_caixa_max_length_validates`
5731 // (3f9d7a0) and `placement_cluster_max_length_validates`
5732 // (6cbb900). Pinned separately so a future off-by-one tightening
5733 // surfaces here.
5734 let max_label = "a".repeat(63);
5735 let s = SupervisorSpec {
5736 children: vec![child(&max_label, "^0.1", RestartPolicy::Permanent)],
5737 ..SupervisorSpec::default()
5738 };
5739 s.validate().unwrap();
5740 }
5741
5742 #[test]
5743 fn validate_accepts_canonical_child_caixa_forms() {
5744 // The realistic shapes a supervised child's `:caixa` carries —
5745 // single-word `worker`, version-suffixed `cache-v2`, single-char
5746 // `a`, two-char `db`, digit-start `2-pool`, longer hyphen-joined
5747 // `payment-retry`, all-digit `0`. Pin every leg so a future
5748 // tightening (e.g. requiring a leading lowercase letter) surfaces
5749 // here as a test failure. Mirrors `accepts_canonical_membro_caixa_forms`
5750 // (3f9d7a0) and `accepts_canonical_placement_cluster_forms`
5751 // (6cbb900).
5752 for form in [
5753 "worker",
5754 "cache-v2",
5755 "a",
5756 "db",
5757 "2-pool",
5758 "payment-retry",
5759 "0",
5760 ] {
5761 let s = SupervisorSpec {
5762 children: vec![child(form, "^0.1", RestartPolicy::Permanent)],
5763 ..SupervisorSpec::default()
5764 };
5765 s.validate()
5766 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
5767 }
5768 }
5769
5770 #[test]
5771 fn child_caixa_empty_takes_precedence_over_invalid() {
5772 // Order pin: the existing `EmptyChildName` diagnostic (which
5773 // doesn't try to parse the DNS-1123 shape) fires before the new
5774 // `ChildCaixaInvalid` per-axis gate, so an empty `:caixa` keeps
5775 // its narrower error message — `is_dns_1123_label` would reject
5776 // the empty string too (boundary check on the first byte), but
5777 // the empty-string arm is the more self-locating diagnostic for
5778 // the author. Same ordering discipline as
5779 // `membro_caixa_empty_takes_precedence_over_invalid` in
5780 // aplicacao.rs.
5781 let s = SupervisorSpec {
5782 children: vec![child("", "^0.1", RestartPolicy::Permanent)],
5783 ..SupervisorSpec::default()
5784 };
5785 let err = s.validate().unwrap_err();
5786 assert_eq!(err, SupervisorError::EmptyChildName);
5787 }
5788
5789 #[test]
5790 fn child_caixa_invalid_fires_before_versao_check() {
5791 // Order pin: the per-axis shape gate runs inline before the
5792 // per-entry versao check, so a malformed `:caixa` on an entry
5793 // whose `:versao` would also fail surfaces the more self-
5794 // locating name-axis diagnostic first. Parallel to
5795 // `membro_versao_invalid_fires_before_duplicate_check` (9888b13)
5796 // and `placement_cluster_invalid_fires_before_duplicate_check`
5797 // (6cbb900).
5798 let s = SupervisorSpec {
5799 children: vec![child("My_Worker", "", RestartPolicy::Permanent)],
5800 ..SupervisorSpec::default()
5801 };
5802 let err = s.validate().unwrap_err();
5803 assert!(
5804 matches!(
5805 err,
5806 SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "My_Worker"
5807 ),
5808 "got {err:?}"
5809 );
5810 }
5811
5812 #[test]
5813 fn child_caixa_invalid_fires_before_duplicate_check() {
5814 // Order pin: a malformed name on a non-duplicate entry surfaces
5815 // its own diagnostic, even when a later entry would otherwise
5816 // collapse onto an earlier name. The per-entry shape gate runs
5817 // inline before the duplicate-key HashSet insert, mirroring
5818 // `placement_cluster_invalid_fires_before_duplicate_check`
5819 // (6cbb900).
5820 let s = SupervisorSpec {
5821 children: vec![
5822 child("Worker", "^0.1", RestartPolicy::Permanent),
5823 child("cache", "^0.1", RestartPolicy::Transient),
5824 child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
5825 ],
5826 ..SupervisorSpec::default()
5827 };
5828 let err = s.validate().unwrap_err();
5829 assert!(
5830 matches!(
5831 err,
5832 SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "Worker"
5833 ),
5834 "got {err:?}"
5835 );
5836 }
5837
5838 #[test]
5839 fn child_caixa_invalid_diagnostic_carries_offending_caixa() {
5840 // The diagnostic-shape pin: the error names the offending
5841 // `:caixa` verbatim plus a non-empty parser-shaped `reason` so
5842 // the author can grep their caixa.lisp without re-running the
5843 // build. Mirrors the diagnostic-shape sweep on every prior
5844 // value-shape gate (3f9d7a0, 6cbb900, c7d05ec).
5845 let s = SupervisorSpec {
5846 children: vec![child("My_Worker", "^0.1", RestartPolicy::Permanent)],
5847 ..SupervisorSpec::default()
5848 };
5849 let err = s.validate().unwrap_err();
5850 let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
5851 panic!("expected ChildCaixaInvalid, got other variant");
5852 };
5853 assert_eq!(caixa, "My_Worker");
5854 assert!(
5855 !reason.is_empty(),
5856 "ChildCaixaInvalid `reason` must carry the parser's wording verbatim"
5857 );
5858 }
5859
5860 // ── value-shape: zero restart_window + duplicate child names ──────────
5861
5862 #[test]
5863 fn validate_accepts_none_restart_window() {
5864 // Omitted `:restart-window` is the "never reset" sentinel —
5865 // valid by design. Mirrors :limits axes where None = unbounded.
5866 let s = SupervisorSpec {
5867 restart_window: None,
5868 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5869 ..SupervisorSpec::default()
5870 };
5871 s.validate().unwrap();
5872 }
5873
5874 #[test]
5875 fn validate_rejects_zero_restart_window() {
5876 // Same "0 means the opposite of what you think" footgun closed
5877 // for :politicas :timeout (Envoy treats 0s as infinite) and
5878 // :limits :wall-clock (wasmtime traps before the call starts).
5879 // Erlang/OTP's MaxIntensity/Period requires Period > 0.
5880 let s = SupervisorSpec {
5881 restart_window: Some(Duration::ZERO),
5882 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5883 ..SupervisorSpec::default()
5884 };
5885 assert_eq!(
5886 s.validate().unwrap_err(),
5887 SupervisorError::RestartWindowZero
5888 );
5889 }
5890
5891 // ── value-shape: integer-ms canonical-form on :restart-window ─────────
5892 //
5893 // The fourth (and last) typed-`Duration` axis in caixa-core to get
5894 // the integer-millisecond canonical-form gate — peer with
5895 // `:limits :wall-clock` (82fc3ef), `:politicas :timeout` (a4ae535),
5896 // and `:politicas :circuit-breaker :window` (a4ae535). The serde
5897 // path is already gated at the shared codec layer (see
5898 // `restart_window_serde_rejects_fractional_seconds`); this arm
5899 // closes the programmatic-struct-literal path the codec gate can't
5900 // see.
5901
5902 #[test]
5903 fn validate_rejects_sub_millisecond_restart_window() {
5904 // The fail-before-pass-after pin: a programmatic
5905 // `Duration::from_micros(1500)` (= 1_500_000 ns) silently passed
5906 // `validate` on every pre-gate codebase, then truncated to
5907 // `as_millis() == 1` on first serialize — the shared codec
5908 // emits `"1ms"`, parses it back to `Duration::from_millis(1)` =
5909 // 1_000_000 ns, the typed `restart_window` no longer matches
5910 // its rendered form.
5911 let s = SupervisorSpec {
5912 restart_window: Some(Duration::from_micros(1500)),
5913 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5914 ..SupervisorSpec::default()
5915 };
5916 match s.validate().unwrap_err() {
5917 SupervisorError::RestartWindowNotCanonical { window } => {
5918 assert_eq!(window, Duration::from_micros(1500));
5919 }
5920 other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
5921 }
5922 }
5923
5924 #[test]
5925 fn validate_rejects_one_nanosecond_restart_window() {
5926 // The far-sub-ms case: `Duration::from_nanos(1)` is non-zero
5927 // (so `RestartWindowZero` doesn't fire) but `as_millis() == 0`,
5928 // so the shared codec emits the literal `"0s"` — the next
5929 // serde round-trip would parse back to `Duration::ZERO`, which
5930 // the `RestartWindowZero` arm then rejects on re-validate. The
5931 // canonical-form gate at this layer surfaces a self-locating
5932 // diagnostic naming the offending Duration verbatim rather
5933 // than a downstream `RestartWindowZero` whose remediation
5934 // points at omitting the slot.
5935 let s = SupervisorSpec {
5936 restart_window: Some(Duration::from_nanos(1)),
5937 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5938 ..SupervisorSpec::default()
5939 };
5940 match s.validate().unwrap_err() {
5941 SupervisorError::RestartWindowNotCanonical { window } => {
5942 assert_eq!(window, Duration::from_nanos(1));
5943 }
5944 other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
5945 }
5946 }
5947
5948 #[test]
5949 fn validate_rejects_nanosecond_past_canonical_boundary_restart_window() {
5950 // The 1-ns-past-1ms boundary case: a `Duration` carrying
5951 // 1_000_001 ns is structurally past the integer-ms granularity
5952 // floor — `subsec_nanos() % 1_000_000 == 1`. The codec round-
5953 // trip would truncate to `1ms` and the consumer would observe
5954 // a 1-ns drift on every emit. Same boundary the peer
5955 // `validate_rejects_nanosecond_past_canonical_boundary` test
5956 // in limits.rs pins for the `:limits :wall-clock` axis.
5957 let w = Duration::from_nanos(1_000_001);
5958 let s = SupervisorSpec {
5959 restart_window: Some(w),
5960 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5961 ..SupervisorSpec::default()
5962 };
5963 assert_eq!(
5964 s.validate().unwrap_err(),
5965 SupervisorError::RestartWindowNotCanonical { window: w }
5966 );
5967 }
5968
5969 #[test]
5970 fn validate_accepts_integer_millisecond_restart_window_values() {
5971 // The positive-control sweep: every `Duration` the shared
5972 // codec can round-trip losslessly — the canonical
5973 // `<integer>{ms,s,m,h}` set the codec's `render` / `parse`
5974 // pair emits and accepts — passes `validate` without
5975 // surfacing the new canonical-form arm. Mirrors
5976 // `validate_accepts_integer_millisecond_wall_clock_values` on
5977 // the sibling `:limits :wall-clock` axis.
5978 for w in [
5979 Duration::from_millis(1),
5980 Duration::from_millis(500),
5981 Duration::from_millis(1500),
5982 Duration::from_secs(1),
5983 Duration::from_secs(30),
5984 Duration::from_secs(60),
5985 Duration::from_secs(120),
5986 Duration::from_secs(3600),
5987 ] {
5988 let s = SupervisorSpec {
5989 restart_window: Some(w),
5990 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5991 ..SupervisorSpec::default()
5992 };
5993 s.validate()
5994 .unwrap_or_else(|e| panic!("integer-ms {w:?} must validate, got {e:?}"));
5995 }
5996 }
5997
5998 #[test]
5999 fn validate_restart_window_zero_takes_precedence_over_canonical_gate() {
6000 // Cross-arm ordering pin: `Duration::ZERO` has
6001 // `subsec_nanos() == 0` and would otherwise pass the
6002 // canonical-form arm — the zero-floor arm must fire first so
6003 // the more self-locating `RestartWindowZero` diagnostic (with
6004 // its omit-axis remediation directly named) leads. Same
6005 // posture every peer zero-then-shape gate uses
6006 // (`WallClockZero` → `WallClockNotCanonical`,
6007 // `PolicyTimeoutZero` → `PolicyTimeoutNotCanonical`,
6008 // `PolicyBreakerZeroWindow` → `PolicyBreakerWindowNotCanonical`).
6009 let s = SupervisorSpec {
6010 restart_window: Some(Duration::ZERO),
6011 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6012 ..SupervisorSpec::default()
6013 };
6014 assert_eq!(
6015 s.validate().unwrap_err(),
6016 SupervisorError::RestartWindowZero
6017 );
6018 }
6019
6020 #[test]
6021 fn restart_window_canonical_diagnostic_carries_offending_duration() {
6022 // Diagnostic-shape pin: the canonical-form arm names the
6023 // offending `Duration` verbatim so the author's grep lands on
6024 // the field's value, not a generic "duration not canonical"
6025 // message. Same shape every other typed-canonical-form arm
6026 // on this surface carries (`WallClockNotCanonical` carries
6027 // the offending `Duration` verbatim,
6028 // `PolicyTimeoutNotCanonical` carries the offending
6029 // `Duration` verbatim).
6030 let w = Duration::from_micros(500);
6031 let s = SupervisorSpec {
6032 restart_window: Some(w),
6033 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6034 ..SupervisorSpec::default()
6035 };
6036 let err = s.validate().unwrap_err();
6037 let msg = err.to_string();
6038 assert!(
6039 msg.contains("500"),
6040 "diagnostic must carry the offending magnitude verbatim (got {msg:?})"
6041 );
6042 assert!(
6043 msg.contains("sub-millisecond"),
6044 "diagnostic must name the sub-millisecond residue class (got {msg:?})"
6045 );
6046 }
6047
6048 #[test]
6049 fn restart_window_validated_value_round_trips_through_codec() {
6050 // The structural property the canonical-ms gate enforces:
6051 // every `SupervisorSpec::restart_window` past
6052 // `SupervisorSpec::validate` round-trips losslessly through
6053 // the shared duration codec (serialize → string →
6054 // deserialize → equal value). Pin this end-to-end so a future
6055 // change to either side (the validate gate's accepted
6056 // granularity, the codec's parse/render unit set) that breaks
6057 // the alignment surfaces here. Peer of
6058 // `wall_clock_validated_value_round_trips_through_codec` on
6059 // the sibling `:limits :wall-clock` axis.
6060 for w in [
6061 Duration::from_millis(1),
6062 Duration::from_millis(1500),
6063 Duration::from_secs(30),
6064 Duration::from_secs(3600),
6065 ] {
6066 let s = SupervisorSpec {
6067 restart_window: Some(w),
6068 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6069 ..SupervisorSpec::default()
6070 };
6071 s.validate().unwrap();
6072 let json = serde_json::to_string(&s).unwrap();
6073 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6074 assert_eq!(back.restart_window, Some(w));
6075 }
6076 }
6077
6078 // ── value-shape: upper cap on :restart-window ─────────────────────────
6079 //
6080 // The fourth (and last) typed-`Duration` axis in caixa-core to get
6081 // the 1h upper cap — peer with `:limits :wall-clock` (51e0dbd),
6082 // `:politicas :timeout` (2e8ee7e), and `:politicas
6083 // :circuit-breaker :window` (379a814). Brackets the typed
6084 // `:restart-window` axis structurally: every validated value lies
6085 // in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`, integer-millisecond
6086 // granularity, closing the
6087 // rolling-window-degenerates-to-lifetime-counter footgun the prior
6088 // zero-floor-and-canonical-form-only checks left open.
6089
6090 #[test]
6091 fn validate_rejects_restart_window_above_cap() {
6092 // The fail-before-pass-after pin: 3601s = 1h + 1s is
6093 // structurally one canonical-tick past the
6094 // [`SUPERVISOR_RESTART_WINDOW_MAX`] ceiling (1h = 3600s) — an
6095 // integer-millisecond magnitude the canonical-form arm above
6096 // accepts cleanly, that the shared duration codec round-trips
6097 // losslessly as `"3601s"`, and that silently passed validate on
6098 // every pre-gate codebase because the typed slot's only checks
6099 // were the zero-floor and canonical-form arms. The runtime
6100 // substrate consuming the value (Erlang/OTP's MaxIntensity/
6101 // Period reconciler, the future wasm-operator's per-supervisor
6102 // restart-intensity counter) reaches for a `Duration` so long
6103 // no realistic restart-recovery pattern resets the counter,
6104 // far from the source caixa.lisp.
6105 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
6106 let s = SupervisorSpec {
6107 restart_window: Some(w),
6108 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6109 ..SupervisorSpec::default()
6110 };
6111 assert_eq!(
6112 s.validate().unwrap_err(),
6113 SupervisorError::RestartWindowExceedsCap { window: w }
6114 );
6115 }
6116
6117 #[test]
6118 fn validate_rejects_restart_window_one_millisecond_above_cap() {
6119 // Boundary case: exactly 1ms past the cap (the granularity the
6120 // canonical-form gate enforces). Catches a future "strictly
6121 // less than" half-measure and pins the diagnostic to name the
6122 // offending `Duration` verbatim. Peer of
6123 // `validate_rejects_wall_clock_one_millisecond_above_cap` /
6124 // `rejects_policy_timeout_one_millisecond_above_cap` /
6125 // `rejects_circuit_breaker_window_one_millisecond_above_cap`
6126 // on the sibling typed-`Duration` axes' top edges.
6127 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
6128 let s = SupervisorSpec {
6129 restart_window: Some(w),
6130 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6131 ..SupervisorSpec::default()
6132 };
6133 assert_eq!(
6134 s.validate().unwrap_err(),
6135 SupervisorError::RestartWindowExceedsCap { window: w }
6136 );
6137 }
6138
6139 #[test]
6140 fn validate_rejects_restart_window_far_above_cap() {
6141 // The "obvious authoring footgun" case: a `(:restart-window "24h")`,
6142 // `(:restart-window "7d")`, or any "I want a lifetime counter
6143 // but wrote a `<integer>h` magnitude anyway" typo — values the
6144 // canonical-form arm accepts as integer-millisecond magnitudes,
6145 // the codec round-trips losslessly through serde, but the
6146 // operator's `MaxIntensity / Period` reconciler cannot honor
6147 // as a meaningful rolling window. Until this gate landed
6148 // validate accepted them. Pin the common above-cap values (24h,
6149 // 7d, ~11.5d) so a future relaxation that drops the upper bound
6150 // surfaces here.
6151 for w in [
6152 Duration::from_secs(86_400), // 24h
6153 Duration::from_secs(604_800), // 7d
6154 Duration::from_secs(1_000_000), // ~11.5 days
6155 ] {
6156 let s = SupervisorSpec {
6157 restart_window: Some(w),
6158 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6159 ..SupervisorSpec::default()
6160 };
6161 assert_eq!(
6162 s.validate().unwrap_err(),
6163 SupervisorError::RestartWindowExceedsCap { window: w }
6164 );
6165 }
6166 }
6167
6168 #[test]
6169 fn validate_accepts_restart_window_at_cap() {
6170 // The boundary value — exactly [`SUPERVISOR_RESTART_WINDOW_MAX`]
6171 // (1h) — must validate. The cap is inclusive on the top edge,
6172 // matching the [`crate::LIMITS_WALL_CLOCK_MAX`] /
6173 // [`crate::POLICY_TIMEOUT_MAX`] /
6174 // [`crate::POLICY_BREAKER_WINDOW_MAX`] discipline on the sibling
6175 // capped axes. Pin the boundary explicitly so a future
6176 // off-by-one tightening (`>= SUPERVISOR_RESTART_WINDOW_MAX`
6177 // instead of `>`) surfaces here as a test failure rather than a
6178 // silent contract narrowing.
6179 let s = SupervisorSpec {
6180 restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
6181 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6182 ..SupervisorSpec::default()
6183 };
6184 s.validate()
6185 .expect("restart_window == SUPERVISOR_RESTART_WINDOW_MAX must validate");
6186 }
6187
6188 #[test]
6189 fn validate_accepts_restart_window_typical_values() {
6190 // The documented Erlang/OTP / Elixir / Riak Core / RabbitMQ
6191 // per-supervisor production-playbook band positive-control
6192 // sweep — every value Learn You Some Erlang's `{intensity, 5,
6193 // 60}` worker-supervisor `Period = 60s` default, Elixir's
6194 // `Supervisor` `max_seconds: 5` default, OTP's `supervisor`
6195 // callback module `MaxT = 5..=60` typical, Riak Core's `MaxT ∈
6196 // 10s..=300s`, and RabbitMQ broker-supervisor `MaxT = 5s`
6197 // default recommend (5s..=300s) must pass, plus a sweep
6198 // through the long-tail-flaky-pool band (5m, 15m, 30m, 1h) the
6199 // cap accepts. Mirrors `validate_accepts_wall_clock_typical_values`
6200 // on the sibling `:limits :wall-clock` axis.
6201 for w in [
6202 Duration::from_millis(1),
6203 Duration::from_millis(500),
6204 Duration::from_secs(1),
6205 Duration::from_secs(5), // RabbitMQ broker-supervisor default
6206 Duration::from_secs(10), // Riak Core lower
6207 Duration::from_secs(30),
6208 Duration::from_secs(60), // Learn You Some Erlang default
6209 Duration::from_secs(120), // OTP supervisor MaxT typical
6210 Duration::from_secs(300), // Riak Core upper
6211 Duration::from_secs(900), // 15m
6212 Duration::from_secs(1800),
6213 Duration::from_secs(3600), // exactly 1h, the cap
6214 ] {
6215 let s = SupervisorSpec {
6216 restart_window: Some(w),
6217 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6218 ..SupervisorSpec::default()
6219 };
6220 s.validate()
6221 .unwrap_or_else(|e| panic!("restart_window={w:?} must validate; got {e:?}"));
6222 }
6223 }
6224
6225 #[test]
6226 fn restart_window_zero_takes_precedence_over_cap() {
6227 // The cross-arm ordering pin: `Duration::ZERO` is structurally
6228 // outside both `>= 1ms` (zero-floor) and `<=
6229 // SUPERVISOR_RESTART_WINDOW_MAX` (cap), but the zero-floor
6230 // diagnostic is the more self-locating one (it directly names
6231 // the omit-axis remediation), so the validate gate must fire
6232 // on zero first. Same shape every other zero-then-cap ordering
6233 // on this surface uses (`WallClockZero` then
6234 // `WallClockExceedsCap`, `PolicyTimeoutZero` then
6235 // `PolicyTimeoutExceedsCap`, `PolicyBreakerZeroWindow` then
6236 // `PolicyBreakerWindowExceedsCap`).
6237 let s = SupervisorSpec {
6238 restart_window: Some(Duration::ZERO),
6239 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6240 ..SupervisorSpec::default()
6241 };
6242 assert_eq!(
6243 s.validate().unwrap_err(),
6244 SupervisorError::RestartWindowZero,
6245 "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
6246 );
6247 }
6248
6249 #[test]
6250 fn restart_window_canonical_takes_precedence_over_cap() {
6251 // The cross-arm ordering pin: a `Duration` that is *both*
6252 // sub-millisecond (non-canonical-form) and structurally above
6253 // the cap surfaces the canonical-form diagnostic first,
6254 // because the round-trip-shape break is the more fundamental
6255 // issue (the value can't even round-trip through the codec,
6256 // so the cap diagnostic naming `1ms..=1h` would be misleading
6257 // — there's no integer-ms form of the offending value). Pin
6258 // the order so a future refactor that reorders the arms
6259 // surfaces here as a test failure rather than a silent
6260 // diagnostic regression. Peer of
6261 // `wall_clock_canonical_takes_precedence_over_cap` /
6262 // `policy_timeout_canonical_takes_precedence_over_cap`.
6263 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_nanos(1);
6264 let s = SupervisorSpec {
6265 restart_window: Some(w),
6266 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6267 ..SupervisorSpec::default()
6268 };
6269 assert_eq!(
6270 s.validate().unwrap_err(),
6271 SupervisorError::RestartWindowNotCanonical { window: w },
6272 "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
6273 );
6274 }
6275
6276 #[test]
6277 fn max_restarts_cap_takes_precedence_over_restart_window_cap() {
6278 // The cross-arm ordering pin between the `:max-restarts` cap
6279 // and the sibling `:restart-window` cap. A supervisor carrying
6280 // both an over-cap `max_restarts` AND an over-cap window must
6281 // surface the `MaxRestartsExceedsCap` diagnostic first — the
6282 // cap arm is wired immediately after the zero-restart arm and
6283 // strictly before every window-axis arm (zero / canonical /
6284 // cap), so the offending value the diagnostic names matches
6285 // the order the author would discover the gates by reading
6286 // top-to-bottom through `SupervisorSpec::validate`. Pin the
6287 // order so a future refactor that reorders the arms surfaces
6288 // here as a test failure rather than a silent diagnostic
6289 // regression. Peer of
6290 // `max_restarts_cap_takes_precedence_over_restart_window_gates`
6291 // on the sibling zero / canonical window arms.
6292 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
6293 let s = SupervisorSpec {
6294 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
6295 restart_window: Some(w),
6296 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6297 ..SupervisorSpec::default()
6298 };
6299 assert_eq!(
6300 s.validate().unwrap_err(),
6301 SupervisorError::MaxRestartsExceedsCap {
6302 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
6303 },
6304 "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
6305 );
6306 }
6307
6308 #[test]
6309 fn restart_window_cap_diagnostic_carries_offending_value() {
6310 // The diagnostic-shape pin: the offending `Duration` is
6311 // carried verbatim into the
6312 // [`SupervisorError::RestartWindowExceedsCap`] variant so the
6313 // surfaced error message names the value the author wrote,
6314 // not just the cap. Same self-locating diagnostic shape every
6315 // other typed-cap arm on this surface carries
6316 // (`WallClockExceedsCap` carries the offending `Duration`
6317 // verbatim, `PolicyTimeoutExceedsCap` carries the offending
6318 // `Duration` verbatim, `PolicyBreakerWindowExceedsCap` carries
6319 // the offending `Duration` verbatim).
6320 let w = Duration::from_secs(7200); // 2h
6321 let s = SupervisorSpec {
6322 restart_window: Some(w),
6323 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6324 ..SupervisorSpec::default()
6325 };
6326 let err = s.validate().unwrap_err();
6327 assert!(
6328 matches!(err, SupervisorError::RestartWindowExceedsCap { window } if window == w),
6329 "got {err:?}"
6330 );
6331 let msg = err.to_string();
6332 assert!(
6333 msg.contains("7200"),
6334 ":supervisor :restart-window cap diagnostic must carry the offending value verbatim (got: {msg})"
6335 );
6336 }
6337
6338 #[test]
6339 fn supervisor_restart_window_cap_pins_canonical_value() {
6340 // The SUPERVISOR_RESTART_WINDOW_MAX constant pins the value at
6341 // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
6342 // shared duration codec emits as a clean canonical string
6343 // (`"<n>h"`). Pinning the literal value here surfaces a future
6344 // drift (a relaxation to 24h, a tightening to 5m) as a
6345 // deliberate test edit, not a silent contract narrowing.
6346 //
6347 // The four typed-`Duration` caps on the validation surface
6348 // (`LIMITS_WALL_CLOCK_MAX` per-process, `POLICY_TIMEOUT_MAX`
6349 // per-edge, `POLICY_BREAKER_WINDOW_MAX` per-breaker,
6350 // `SUPERVISOR_RESTART_WINDOW_MAX` per-supervisor) share a
6351 // single uniform top edge at the codec's largest emitted unit
6352 // — a structural-property invariant the equality assertions
6353 // here enshrine, so a future drift on any of the four
6354 // surfaces as a deliberate test edit. Same shape every other
6355 // typed-cap value pin uses
6356 // (`wall_clock_cap_pins_canonical_value`,
6357 // `policy_timeout_cap_pins_canonical_value`,
6358 // `circuit_breaker_window_cap_pins_canonical_value`).
6359 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, Duration::from_secs(3600));
6360 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX.as_millis(), 3_600_000);
6361 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::LIMITS_WALL_CLOCK_MAX);
6362 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::POLICY_TIMEOUT_MAX);
6363 assert_eq!(
6364 SUPERVISOR_RESTART_WINDOW_MAX,
6365 crate::POLICY_BREAKER_WINDOW_MAX
6366 );
6367 }
6368
6369 #[test]
6370 fn restart_window_cap_value_round_trips_through_codec() {
6371 // The codec round-trip property the cap arm preserves: the
6372 // [`SUPERVISOR_RESTART_WINDOW_MAX`] constant itself round-trips
6373 // through the shared duration codec — every value at the cap
6374 // serializes to the canonical `"1h"` form and parses back
6375 // identically. Pin the round-trip so a future change to the
6376 // codec's unit set or to the cap's magnitude that breaks the
6377 // round-trip property surfaces here. Peer of
6378 // `wall_clock_cap_value_round_trips_through_codec` on the
6379 // sibling `:limits :wall-clock` axis.
6380 let s = SupervisorSpec {
6381 restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
6382 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6383 ..SupervisorSpec::default()
6384 };
6385 s.validate().unwrap();
6386 let json = serde_json::to_string(&s).unwrap();
6387 assert!(
6388 json.contains("\"1h\""),
6389 "SUPERVISOR_RESTART_WINDOW_MAX must serialize to the canonical `\"1h\"` form (got {json})"
6390 );
6391 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6392 assert_eq!(back.restart_window, Some(SUPERVISOR_RESTART_WINDOW_MAX));
6393 }
6394
6395 #[test]
6396 fn validate_rejects_duplicate_child_caixa() {
6397 // Two children with the same :caixa render to two ComputeUnits
6398 // with the same name in the cluster's HelmRelease values —
6399 // one silently overwrites the other. Erlang/OTP's child_spec.id
6400 // is required-unique per supervisor; same set-not-multiset
6401 // discipline applied here as for :membros / :placement
6402 // :clusters / :entrada :paths.
6403 let s = SupervisorSpec {
6404 children: vec![
6405 child("worker", "^0.1", RestartPolicy::Permanent),
6406 child("cache", "^0.1", RestartPolicy::Transient),
6407 child("worker", "^0.2", RestartPolicy::Permanent),
6408 ],
6409 ..SupervisorSpec::default()
6410 };
6411 let err = s.validate().unwrap_err();
6412 assert!(
6413 matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "worker"),
6414 "got {err:?}"
6415 );
6416 }
6417
6418 #[test]
6419 fn validate_duplicate_child_diagnostic_names_first_collision() {
6420 // Iteration walks the :children list in declaration order —
6421 // the diagnostic names the first repeat, deterministically,
6422 // even when multiple names duplicate.
6423 let s = SupervisorSpec {
6424 children: vec![
6425 child("a", "^0.1", RestartPolicy::Permanent),
6426 child("b", "^0.1", RestartPolicy::Permanent),
6427 child("a", "^0.1", RestartPolicy::Permanent),
6428 child("b", "^0.1", RestartPolicy::Permanent),
6429 ],
6430 ..SupervisorSpec::default()
6431 };
6432 let err = s.validate().unwrap_err();
6433 assert!(
6434 matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "a"),
6435 "got {err:?}"
6436 );
6437 }
6438
6439 // ── self-supervision cross-slot gate ──────────────────────────
6440
6441 #[test]
6442 fn validate_no_self_supervision_rejects_self_referential_child() {
6443 // A supervisor whose `:children` lists its own `:nome` is a
6444 // one-node reconciliation cycle — rejected, naming the parent.
6445 let children = vec![
6446 child("worker", "^0.1", RestartPolicy::Permanent),
6447 child("orquestra", "^0.1", RestartPolicy::Permanent),
6448 ];
6449 let err = validate_no_self_supervision(&children, "orquestra").unwrap_err();
6450 assert!(
6451 matches!(err, SupervisorError::ChildSupervisesSelf { ref caixa } if caixa == "orquestra"),
6452 "got {err:?}"
6453 );
6454 }
6455
6456 #[test]
6457 fn validate_no_self_supervision_accepts_distinct_children() {
6458 // Positive control: distinct child names (including a child that
6459 // is itself a supervisor — nested trees are valid OTP) pass.
6460 let children = vec![
6461 child("worker", "^0.1", RestartPolicy::Permanent),
6462 child("sub-tree", "^0.1", RestartPolicy::Permanent),
6463 ];
6464 validate_no_self_supervision(&children, "orquestra").unwrap();
6465 }
6466
6467 #[test]
6468 fn validate_no_self_supervision_empty_children_is_ok() {
6469 // SimpleOneForOne / no-static-children supervisors have nothing
6470 // to self-reference — the gate is vacuously satisfied.
6471 validate_no_self_supervision(&[], "orquestra").unwrap();
6472 }
6473
6474 #[test]
6475 fn validate_simple_one_for_one_skips_uniqueness_check() {
6476 // SimpleOneForOne supervisors carry no static children — the
6477 // duplicate-child loop never runs. A zero-window declaration
6478 // on a SimpleOneForOne supervisor still trips the window check
6479 // (window applies to dynamic children too).
6480 let s = SupervisorSpec {
6481 estrategia: RestartStrategy::SimpleOneForOne,
6482 restart_window: None,
6483 children: vec![],
6484 ..SupervisorSpec::default()
6485 };
6486 s.validate().unwrap();
6487 let s_zero = SupervisorSpec {
6488 estrategia: RestartStrategy::SimpleOneForOne,
6489 restart_window: Some(Duration::ZERO),
6490 children: vec![],
6491 ..SupervisorSpec::default()
6492 };
6493 assert_eq!(
6494 s_zero.validate().unwrap_err(),
6495 SupervisorError::RestartWindowZero
6496 );
6497 }
6498
6499 #[test]
6500 fn validate_zero_window_runs_after_max_restarts_check() {
6501 // Pin the order: max_restarts == 0 fires before
6502 // restart_window == 0s, so an author with both wrong sees the
6503 // counter-axis diagnostic first (matches the order in the
6504 // struct and in the doc comment).
6505 let s = SupervisorSpec {
6506 max_restarts: 0,
6507 restart_window: Some(Duration::ZERO),
6508 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6509 ..SupervisorSpec::default()
6510 };
6511 assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
6512 }
6513
6514 #[test]
6515 fn round_trip_all_strategies() {
6516 for &strat in RestartStrategy::ALL {
6517 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
6518 // shape partition through the [`gen_platform::IsVariant`]
6519 // derive-generated [`RestartStrategy::is_simple_one_for_one`]
6520 // predicate rather than the raw
6521 // `matches!(strat, RestartStrategy::SimpleOneForOne)`
6522 // open-coded pattern-match — same closed-set-typed-enum
6523 // arm-discriminator dispatch discipline the sibling
6524 // [`crate::upgrade::UpgradeInstruction::is_restart`] convergence
6525 // (915a934) extended onto its two paired positive / negated
6526 // `matches!` filter sites, and the sibling
6527 // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
6528 // predicate convergence (766ec63) extended onto the M3 mesh-
6529 // slot per-`:placement` distribution-strategy `matches!`
6530 // discriminator axis. See the sibling
6531 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
6532 // fixture and the peer `manifest::tests::
6533 // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
6534 // fixture — all three sites (the last unlifted
6535 // `matches!`-based arm-discriminator axis on the OTP-shape
6536 // supervisor sibling-restart-strategy closed-set typed enum,
6537 // acknowledged in 915a934's Prior-commits footnote as the
6538 // outstanding follow-up) now consult one typed dispatch on
6539 // the substrate primitive.
6540 let s = SupervisorSpec {
6541 estrategia: strat,
6542 children: if strat.is_simple_one_for_one() {
6543 vec![]
6544 } else {
6545 vec![child("w", "^0.1", RestartPolicy::Permanent)]
6546 },
6547 ..SupervisorSpec::default()
6548 };
6549 let json = serde_json::to_string(&s).unwrap();
6550 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6551 assert_eq!(s, back);
6552 }
6553 }
6554
6555 #[test]
6556 fn round_trip_all_restart_policies() {
6557 for policy in [
6558 RestartPolicy::Permanent,
6559 RestartPolicy::Temporary,
6560 RestartPolicy::Transient,
6561 ] {
6562 let c = child("w", "^0.1", policy);
6563 let json = serde_json::to_string(&c).unwrap();
6564 let back: ChildSpec = serde_json::from_str(&json).unwrap();
6565 assert_eq!(c, back);
6566 }
6567 }
6568
6569 #[test]
6570 fn restart_strategy_is_simple_one_for_one_predicate_partitions_the_arm_set() {
6571 // The fail-before-pass-after pin on the `gen_platform::IsVariant`
6572 // derive's [`RestartStrategy::is_simple_one_for_one`] arm-
6573 // discriminator predicate: [`RestartStrategy::SimpleOneForOne`]
6574 // is the only variant that satisfies `.is_simple_one_for_one()`;
6575 // every static-children-bearing arm (`OneForOne` / `OneForAll`
6576 // / `RestForOne`) returns `false`. This pin makes the partition
6577 // invariant load-bearing at caixa-core test time so a future
6578 // derive regression (a hole that returns `false` for
6579 // `SimpleOneForOne` too, or a byte-collision that flips a second
6580 // variant to `true`) trips here rather than laundering the arm
6581 // at the three test-fixture builder sites (a hole flips the
6582 // `SimpleOneForOne` fixture to carry a non-empty children list
6583 // and the subsequent `SupervisorSpec::validate` would refuse the
6584 // fixture with [`SupervisorError::SimpleOneForOneWithStaticChildren`];
6585 // a collision flips a peer strategy's fixture to carry an empty
6586 // children list and the subsequent `validate` would refuse with
6587 // [`SupervisorError::NoChildren`] — either way, the pin fires
6588 // here, at the derive site, rather than at the fixture-refusal
6589 // site far away). Peer of the sibling
6590 // [`crate::upgrade::tests::upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
6591 // (915a934) pin on the M2 OTP-appup axis and the sibling
6592 // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
6593 // pin on the M0 `:kind` axis.
6594 let cases: &[(RestartStrategy, bool)] = &[
6595 (RestartStrategy::OneForOne, false),
6596 (RestartStrategy::OneForAll, false),
6597 (RestartStrategy::RestForOne, false),
6598 (RestartStrategy::SimpleOneForOne, true),
6599 ];
6600 for (variant, expected) in cases {
6601 assert_eq!(
6602 variant.is_simple_one_for_one(),
6603 *expected,
6604 "RestartStrategy::{variant:?}.is_simple_one_for_one() must \
6605 return {expected} (partition invariant on the \
6606 IsVariant-derived arm-discriminator predicate — every \
6607 test-fixture site that partitions the `:children` slot \
6608 shape on `SimpleOneForOne ↔ non-SimpleOneForOne` keys \
6609 off this typed dispatch, so a derive regression must \
6610 surface here rather than at the fixture-refusal site)"
6611 );
6612 }
6613 }
6614
6615 #[test]
6616 fn restart_strategy_fixture_partition_routes_through_is_simple_one_for_one_predicate() {
6617 // Byte-identity pin on the `SimpleOneForOne ↔ non-SimpleOneForOne`
6618 // fixture-shape partition against the pre-lift
6619 // `matches!(strat, RestartStrategy::SimpleOneForOne)` open-coded
6620 // pattern-match every test-fixture builder site previously
6621 // coupled to inline. Asserts the two projections agree byte-for-
6622 // byte on every arm of the enum, so a future derive regression
6623 // that flipped either predicate's arm-set would surface here at
6624 // caixa-core test time rather than at the three fixture-builder
6625 // sites (`supervisor::tests::round_trip_all_strategies`,
6626 // `supervisor::tests::supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`,
6627 // `manifest::tests::caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`)
6628 // far from the derive site. Same peer-shape byte-identity pin
6629 // every sibling `IsVariant`-derive-routed convergence carries on
6630 // the substrate's closed-set typed-enum surface (peer of
6631 // [`crate::upgrade::tests::validate_restart_exclusive_routes_through_is_restart_predicate`]
6632 // on the M2 OTP-appup axis).
6633 for &strat in RestartStrategy::ALL {
6634 let via_predicate = strat.is_simple_one_for_one();
6635 let via_matches = matches!(strat, RestartStrategy::SimpleOneForOne);
6636 assert_eq!(
6637 via_predicate, via_matches,
6638 "RestartStrategy::{strat:?}: is_simple_one_for_one() must \
6639 byte-equal matches!(_, RestartStrategy::SimpleOneForOne) — \
6640 the pre-lift open-coded pattern and the \
6641 IsVariant-derived predicate are the same axis, \
6642 one typed dispatch"
6643 );
6644 }
6645 }
6646
6647 #[test]
6648 fn duration_codec_round_trip_canonical_units() {
6649 // Note the canonical-form rule: durations serialize to the
6650 // *largest* unit that divides cleanly, so 60s ↔ "1m" and not
6651 // "60s" — but the round-trip preserves the underlying Duration.
6652 let cases = [
6653 ("30s", Duration::from_secs(30)),
6654 ("5m", Duration::from_secs(300)),
6655 ("1h", Duration::from_secs(3600)),
6656 ("500ms", Duration::from_millis(500)),
6657 ];
6658 for (lit, dur) in cases {
6659 let s = SupervisorSpec {
6660 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6661 restart_window: Some(dur),
6662 ..SupervisorSpec::default()
6663 };
6664 let json = serde_json::to_string(&s).unwrap();
6665 assert!(
6666 json.contains(&format!("\"{lit}\"")),
6667 "expected \"{lit}\" in {json}"
6668 );
6669 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6670 assert_eq!(back.restart_window, Some(dur));
6671 }
6672 }
6673
6674 #[test]
6675 fn duration_canonicalizes_to_largest_unit() {
6676 // 60 seconds → "1m" (largest cleanly-divisible unit), but the
6677 // typed Duration still equals 60s on the way back.
6678 let s = SupervisorSpec {
6679 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6680 restart_window: Some(Duration::from_secs(60)),
6681 ..SupervisorSpec::default()
6682 };
6683 let json = serde_json::to_string(&s).unwrap();
6684 assert!(json.contains("\"1m\""), "{json}");
6685 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6686 assert_eq!(back.restart_window, Some(Duration::from_secs(60)));
6687 }
6688
6689 #[test]
6690 fn three_child_one_for_one_validates() {
6691 let s = SupervisorSpec {
6692 estrategia: RestartStrategy::OneForOne,
6693 max_restarts: 5,
6694 restart_window: Some(Duration::from_secs(60)),
6695 children: vec![
6696 child("worker", "^0.1", RestartPolicy::Permanent),
6697 child("cache", "^0.1", RestartPolicy::Transient),
6698 child("scratch", "^0.1", RestartPolicy::Temporary),
6699 ],
6700 };
6701 s.validate().unwrap();
6702 }
6703
6704 #[test]
6705 fn json_uses_pascal_case_for_strategy_and_policy() {
6706 // Variant names are PascalCase by default in serde, matching
6707 // tatara-lisp's enum convention (`:estrategia OneForOne`).
6708 let c = child("w", "^0.1", RestartPolicy::Permanent);
6709 let json = serde_json::to_string(&c).unwrap();
6710 assert!(json.contains("\"Permanent\""));
6711 assert!(!json.contains("\"permanent\""));
6712
6713 let s = SupervisorSpec {
6714 estrategia: RestartStrategy::OneForOne,
6715 children: vec![c],
6716 ..SupervisorSpec::default()
6717 };
6718 let json = serde_json::to_string(&s).unwrap();
6719 assert!(json.contains("\"estrategia\":\"OneForOne\""));
6720 }
6721
6722 // ── shared duration codec: integer-magnitude canonical-form gate ──
6723 //
6724 // The gate lifts the discipline `crate::limits::parse_duration`
6725 // (818dd38) carries on the peer `:limits :wall-clock` codec onto
6726 // the shared codec backing the remaining three typed-duration
6727 // slots: `:supervisor :restart-window`, `:politicas :timeout`, and
6728 // `:politicas :circuit-breaker :window`. Every magnitude `render`
6729 // emits is a non-negative integer with no decimal point and no
6730 // leading sign, so the codec's accepted set must match for
6731 // serialize/deserialize to round-trip without canonical-form
6732 // drift.
6733
6734 #[test]
6735 fn parse_accepts_integer_canonical_units() {
6736 // Pin the happy-path: every canonical author shape `render`
6737 // ever emits parses to the same `Duration` value, so the
6738 // codec's accepted set is at least a superset of its emitted
6739 // set on the canonical-unit axis.
6740 for (lit, dur) in [
6741 ("30s", Duration::from_secs(30)),
6742 ("500ms", Duration::from_millis(500)),
6743 ("2m", Duration::from_secs(120)),
6744 ("1h", Duration::from_secs(3600)),
6745 ("0s", Duration::ZERO),
6746 ] {
6747 assert_eq!(
6748 duration_codec::parse(lit).unwrap(),
6749 dur,
6750 "parse({lit:?}) should be {dur:?}"
6751 );
6752 }
6753 }
6754
6755 #[test]
6756 fn parse_accepts_bare_integer_as_seconds() {
6757 // The `"s" | ""` arm: a bare integer with no unit is read as
6758 // seconds. Pin this so the unit-empty form keeps parsing (it
6759 // renders to `"<n>s"` on serialize — that's a unit-choice
6760 // drift the integer-magnitude gate does NOT close, matching
6761 // the `parse_byte_size` `"1024"` → `"1KiB"` scope decision in
6762 // the peer `:limits :memory` codec).
6763 assert_eq!(
6764 duration_codec::parse("30").unwrap(),
6765 Duration::from_secs(30)
6766 );
6767 }
6768
6769 #[test]
6770 fn parse_rejects_fractional_seconds_with_canonical_form_diagnostic() {
6771 // `"1.5s"` parses as f64 to 1.5 → renders back as `"1500ms"`
6772 // on first serialize — DRIFT. The integer-magnitude gate names
6773 // the offending `"1.5"` verbatim and points at the canonical
6774 // remediation `"1500ms"`.
6775 let err = duration_codec::parse("1.5s").unwrap_err();
6776 assert!(err.contains("\"1.5\""), "missing magnitude in {err:?}");
6777 assert!(
6778 err.contains("not a non-negative integer"),
6779 "missing canonical-form reason in {err:?}"
6780 );
6781 assert!(
6782 err.contains("\"1500ms\""),
6783 "missing canonical-form remediation in {err:?}"
6784 );
6785 }
6786
6787 #[test]
6788 fn parse_rejects_decimal_shaped_integer_seconds() {
6789 // `"1.0s"` is the trickiest drift class: numerically `1.0s` is
6790 // `1s` exactly, so the round-trip looks correct — but the
6791 // emitted canonical form is `"1s"`, not `"1.0s"`. Gate the
6792 // decimal-shape-with-integer-value form so author intent is
6793 // never silently rewritten.
6794 let err = duration_codec::parse("1.0s").unwrap_err();
6795 assert!(err.contains("\"1.0\""), "missing magnitude in {err:?}");
6796 assert!(
6797 err.contains("not a non-negative integer"),
6798 "missing canonical-form reason in {err:?}"
6799 );
6800 }
6801
6802 #[test]
6803 fn parse_rejects_half_unit_minute() {
6804 // `"0.5m"` is the unit-fraction footgun — author writes a
6805 // human-readable half-minute, serde silently rewrites to
6806 // `"30s"` on next emit. The gate names the offending
6807 // magnitude `"0.5"` and points at the integer-in-smaller-unit
6808 // form.
6809 let err = duration_codec::parse("0.5m").unwrap_err();
6810 assert!(err.contains("\"0.5\""), "missing magnitude in {err:?}");
6811 assert!(
6812 err.contains("\"30s\""),
6813 "missing canonical-form remediation in {err:?}"
6814 );
6815 }
6816
6817 #[test]
6818 fn parse_rejects_leading_plus_sign() {
6819 // `u64::from_str` rejects `"+30"` but `f64::from_str` accepts
6820 // it as `30.0` — the prior parser used f64 so `"+30s"` parsed
6821 // cleanly to 30s and round-tripped to `"30s"` on next emit
6822 // (DRIFT). The digit-only gate closes the leading-sign class
6823 // first; the diagnostic names `"+30"` verbatim.
6824 let err = duration_codec::parse("+30s").unwrap_err();
6825 assert!(err.contains("\"+30\""), "missing magnitude in {err:?}");
6826 assert!(
6827 err.contains("not a non-negative integer"),
6828 "missing canonical-form reason in {err:?}"
6829 );
6830 }
6831
6832 #[test]
6833 fn parse_rejects_leading_minus_sign() {
6834 // The former `num < 0.0` arm: `"-30s"` parsed as f64 to -30,
6835 // rejected with `"negative duration in \"-30s\""`. Under the
6836 // integer-magnitude gate the diagnostic is unified — `-30` is
6837 // non-digit-only, f64-numeric, and surfaces with the canonical-
6838 // form reason (no leading `+` / `-` sign) naming the offending
6839 // `"-30"` verbatim. Same diagnostic shape as every other
6840 // rejected non-integer magnitude.
6841 let err = duration_codec::parse("-30s").unwrap_err();
6842 assert!(err.contains("\"-30\""), "missing magnitude in {err:?}");
6843 assert!(
6844 err.contains("not a non-negative integer"),
6845 "missing canonical-form reason in {err:?}"
6846 );
6847 }
6848
6849 #[test]
6850 fn parse_garbage_still_falls_through_to_bad_magnitude() {
6851 // Non-digit-only AND non-numeric (`"--1s"`, `"abc"`) falls
6852 // through to the narrower "bad duration magnitude" arm — the
6853 // canonical-form diagnostic is reserved for the parser-shape
6854 // footgun case, not the "not a number at all" case. Same
6855 // shape `parse_byte_size`'s `BadByteMagnitude` arm carries on
6856 // the peer `:limits :memory` codec.
6857 let err = duration_codec::parse("--1s").unwrap_err();
6858 assert!(
6859 err.contains("bad duration magnitude"),
6860 "expected bad-magnitude wording in {err:?}"
6861 );
6862 }
6863
6864 #[test]
6865 fn parse_digit_only_magnitude_carries_zero_f64_drift() {
6866 // The accepted set is now closed under `u64`-exact integer
6867 // arithmetic: `"500ms"` → `Duration::from_millis(500)` exactly,
6868 // `"3600s"` → `Duration::from_secs(3600)` exactly, `"1h"` →
6869 // `Duration::from_secs(3600)` exactly, no f64 mantissa drift
6870 // possible. Pin the integer-exact arms across the four unit
6871 // suffixes so a future refactor that reaches back for f64
6872 // (`from_secs_f64`, `mul_f64`) surfaces here.
6873 assert_eq!(
6874 duration_codec::parse("3600s").unwrap(),
6875 Duration::from_secs(3600)
6876 );
6877 assert_eq!(
6878 duration_codec::parse("60m").unwrap(),
6879 Duration::from_secs(3600)
6880 );
6881 assert_eq!(
6882 duration_codec::parse("1h").unwrap(),
6883 Duration::from_secs(3600)
6884 );
6885 assert_eq!(
6886 duration_codec::parse("999ms").unwrap(),
6887 Duration::from_millis(999)
6888 );
6889 }
6890
6891 #[test]
6892 fn restart_window_serde_rejects_fractional_seconds() {
6893 // The shared codec backs `SupervisorSpec::restart_window`
6894 // (`with = "duration_codec"`) — so the gate applies on serde
6895 // deserialize for the typed Supervisor slot. A
6896 // `{"restartWindow":"1.5s"}` payload that previously round-
6897 // tripped to a different canonical string on next serialize
6898 // is now refused at deserialize with the integer-magnitude
6899 // diagnostic.
6900 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6901 "restartWindow":"1.5s",
6902 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6903 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6904 let msg = err.to_string();
6905 assert!(
6906 msg.contains("not a non-negative integer"),
6907 "expected integer-magnitude diagnostic in {msg:?}"
6908 );
6909 assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
6910 }
6911
6912 #[test]
6913 fn restart_window_serde_rejects_leading_plus() {
6914 // The `u64::from_str` leading-`+` permissiveness gap that
6915 // motivated the digit-only gate (the `f64`-side accepted
6916 // `"+30"`, the prior parser silently round-tripped to `"30s"`)
6917 // is now closed on the shared codec — surfaces as a structured
6918 // diagnostic at the serde layer for every typed-duration slot.
6919 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6920 "restartWindow":"+30s",
6921 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6922 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6923 let msg = err.to_string();
6924 assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
6925 assert!(
6926 msg.contains("not a non-negative integer"),
6927 "missing canonical-form reason in {msg:?}"
6928 );
6929 }
6930
6931 #[test]
6932 fn parse_rejects_leading_zero_magnitude() {
6933 // `"030s"` is digit-only, so the existing non-digit-only / sign
6934 // / fractional arm doesn't catch it — `u64::from_str("030")`
6935 // returns `Ok(30)`, so before this gate `"030s"` parsed to
6936 // `Duration::from_secs(30)` and round-tripped through `render`
6937 // to `"30s"` — a *different* canonical string on the next emit,
6938 // breaking the THEORY.md Part V render-determinism contract
6939 // exactly the way `"+30s"` did before the leading-`+` arm
6940 // landed. Peer with the `rate_limit_codec` leading-zero arm
6941 // (4f46830) on the same canonical-form-drift axis.
6942 let err = duration_codec::parse("030s").unwrap_err();
6943 assert!(
6944 err.contains("non-canonical leading zero"),
6945 "expected leading-zero diagnostic in {err:?}"
6946 );
6947 assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
6948 assert!(
6949 err.contains("\"30s\""),
6950 "missing canonical-form remediation in {err:?}"
6951 );
6952 assert!(
6953 err.contains("THEORY.md"),
6954 "missing render-determinism citation in {err:?}"
6955 );
6956 }
6957
6958 #[test]
6959 fn parse_rejects_multi_digit_zero_magnitude() {
6960 // `"00s"` and `"00ms"` are the all-zero leading-zero footgun —
6961 // digit-only, parse losslessly to `Duration::ZERO`, but render
6962 // back to `"0s"` (the single-byte canonical form) on the next
6963 // emit. The leading-zero arm refuses the drift class at the
6964 // codec layer; the semantic-zero gate downstream
6965 // (`SupervisorError::ZeroRestartWindow`, etc.) would refuse
6966 // the single-byte canonical form `"0s"` separately on the
6967 // typed-validate layer.
6968 let err = duration_codec::parse("00s").unwrap_err();
6969 assert!(
6970 err.contains("non-canonical leading zero"),
6971 "expected leading-zero diagnostic in {err:?}"
6972 );
6973 assert!(err.contains("\"00\""), "missing magnitude in {err:?}");
6974 }
6975
6976 #[test]
6977 fn parse_rejects_leading_zero_per_hour_window() {
6978 // `"01h"` is the per-hour-window footgun — multi-byte magnitude
6979 // starting with `0`, parses losslessly to `Duration::from_secs(3600)`,
6980 // renders to `"1h"` (DRIFT). The arm is unit-agnostic: every
6981 // canonical unit suffix the codec accepts (`ms` / `s` / `m` /
6982 // `h` / bare-integer-as-seconds) inherits the same gate.
6983 let err = duration_codec::parse("01h").unwrap_err();
6984 assert!(
6985 err.contains("non-canonical leading zero"),
6986 "expected leading-zero diagnostic in {err:?}"
6987 );
6988 assert!(err.contains("\"01\""), "missing magnitude in {err:?}");
6989 }
6990
6991 #[test]
6992 fn parse_rejects_leading_zero_bare_integer_as_seconds() {
6993 // The `parse_accepts_bare_integer_as_seconds` happy-path
6994 // (`"30"` → 30s) inherits the leading-zero arm: `"030"` is
6995 // multi-byte starts-with-`0`, parses losslessly to
6996 // `Duration::from_secs(30)`, renders to `"30s"` (DRIFT). The
6997 // bare-integer surface accepts permissive unit-empty
6998 // shorthand but still must reject leading-zero padding.
6999 let err = duration_codec::parse("030").unwrap_err();
7000 assert!(
7001 err.contains("non-canonical leading zero"),
7002 "expected leading-zero diagnostic in {err:?}"
7003 );
7004 assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
7005 }
7006
7007 #[test]
7008 fn parse_accepts_single_zero_magnitude_at_codec_layer() {
7009 // The codec-layer / typed-validate-layer boundary: `"0s"` /
7010 // `"0ms"` / `"0"` are the single-byte canonical-zero forms —
7011 // each round-trips losslessly through `render`
7012 // (`render(Duration::ZERO)` → `"0s"`), so the codec layer
7013 // accepts them. The downstream semantic-zero gates
7014 // (`SupervisorError::ZeroRestartWindow`,
7015 // `AplicacaoError::PolicyTimeoutZero`,
7016 // `AplicacaoError::PolicyCircuitBreakerWindowZero`) refuse
7017 // zero-magnitude authoring at the typed-validate layer above,
7018 // peer with the `rate_limit_codec` codec-layer / typed-
7019 // validate-layer partition for `"0/s"`.
7020 assert_eq!(duration_codec::parse("0s").unwrap(), Duration::ZERO);
7021 assert_eq!(duration_codec::parse("0ms").unwrap(), Duration::ZERO);
7022 assert_eq!(duration_codec::parse("0").unwrap(), Duration::ZERO);
7023 }
7024
7025 #[test]
7026 fn parse_accepts_canonical_magnitude_with_leading_one() {
7027 // The complementary boundary: a future tightening cannot
7028 // drift into rejecting valid canonical magnitudes that
7029 // happen to start with `1` (or any digit `[1-9]`). Pin
7030 // every canonical-unit suffix so the leading-zero arm
7031 // remains strictly narrower than the digit-only arm.
7032 assert_eq!(
7033 duration_codec::parse("100ms").unwrap(),
7034 Duration::from_millis(100)
7035 );
7036 assert_eq!(
7037 duration_codec::parse("100s").unwrap(),
7038 Duration::from_secs(100)
7039 );
7040 assert_eq!(
7041 duration_codec::parse("10m").unwrap(),
7042 Duration::from_secs(600)
7043 );
7044 assert_eq!(
7045 duration_codec::parse("10h").unwrap(),
7046 Duration::from_secs(36_000)
7047 );
7048 }
7049
7050 #[test]
7051 fn restart_window_serde_rejects_leading_zero() {
7052 // The shared codec backs `SupervisorSpec::restart_window`
7053 // (`with = "duration_codec"`) — so the leading-zero arm
7054 // applies on serde deserialize for the typed Supervisor slot.
7055 // A `{"restartWindow":"030s"}` payload that previously round-
7056 // tripped to a different canonical string on next serialize
7057 // is now refused at deserialize with the leading-zero
7058 // diagnostic. Peer with `restart_window_serde_rejects_leading_plus`
7059 // / `restart_window_serde_rejects_fractional_seconds` on the
7060 // same canonical-form-drift axis.
7061 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
7062 "restartWindow":"030s",
7063 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
7064 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7065 let msg = err.to_string();
7066 assert!(
7067 msg.contains("non-canonical leading zero"),
7068 "expected leading-zero diagnostic in {msg:?}"
7069 );
7070 assert!(msg.contains("\"030\""), "missing magnitude in {msg:?}");
7071 }
7072
7073 #[test]
7074 fn parse_rejects_leading_whitespace() {
7075 // `" 30s"` — the canonical paste-from-aligned-doc /
7076 // paste-from-YAML-quoted-plain-scalar footgun. Before this
7077 // gate the top-level `s.trim()` at parse entry silently ate
7078 // the leading space and parsed the value to
7079 // `Duration::from_secs(30)`, which then round-tripped through
7080 // `render` to `"30s"` (a *different* canonical string on the
7081 // next emit) — the exact canonical-form-drift class the
7082 // leading-`+` / leading-zero arms already close, extended
7083 // to the whitespace-byte class. Peer with the sibling
7084 // `rate_limit_codec` whitespace-rejection arm (1ad7755) on
7085 // the M3 `:politicas` axis.
7086 let err = duration_codec::parse(" 30s").unwrap_err();
7087 assert!(
7088 err.contains("contains whitespace byte"),
7089 "expected whitespace diagnostic in {err:?}"
7090 );
7091 assert!(err.contains("0x20"), "missing offending byte in {err:?}");
7092 assert!(
7093 err.contains("THEORY.md"),
7094 "missing render-determinism contract citation in {err:?}"
7095 );
7096 }
7097
7098 #[test]
7099 fn parse_rejects_trailing_whitespace() {
7100 // `"30s "` — the canonical shell-history / trailing-space
7101 // paste footgun. Before this gate the top-level `s.trim()`
7102 // silently ate the trailing space and parsed to
7103 // `Duration::from_secs(30)`, round-tripping to `"30s"` on the
7104 // next emit — same canonical-form drift as the leading-space
7105 // sibling, closed on the same whitespace-byte arm.
7106 let err = duration_codec::parse("30s ").unwrap_err();
7107 assert!(
7108 err.contains("contains whitespace byte"),
7109 "expected whitespace diagnostic in {err:?}"
7110 );
7111 assert!(err.contains("0x20"), "missing offending byte in {err:?}");
7112 }
7113
7114 #[test]
7115 fn parse_rejects_internal_whitespace_between_magnitude_and_unit() {
7116 // `"30 s"` — the canonical typographically-spaced author
7117 // shape (the same idiom every prose reference to a duration
7118 // renders as, mistakenly retained when the value is pasted
7119 // into a codec-shaped slot). Before this gate the per-part
7120 // `num_part.trim()` / `unit.trim()` calls silently ate the
7121 // whitespace between the magnitude and the unit and parsed
7122 // the value to `Duration::from_secs(30)`, round-tripping to
7123 // `"30s"` — the codec's *internal* whitespace-tolerance
7124 // vector, orthogonal to the leading / trailing surface but
7125 // the same canonical-form-drift class. Pins the arm as
7126 // strictly stronger than the pre-existing top-level
7127 // `s.trim()` behavior: it fires on whitespace anywhere in
7128 // the value, not just at the string boundary.
7129 let err = duration_codec::parse("30 s").unwrap_err();
7130 assert!(
7131 err.contains("contains whitespace byte"),
7132 "expected whitespace diagnostic in {err:?}"
7133 );
7134 assert!(err.contains("0x20"), "missing offending byte in {err:?}");
7135 }
7136
7137 #[test]
7138 fn parse_rejects_tab_byte() {
7139 // `"\t30s"` — the canonical paste-from-indented-doc /
7140 // paste-from-YAML-block-scalar footgun where a tab byte leads
7141 // the magnitude. Pins that the gate covers tab (`0x09`) as
7142 // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
7143 // members and both would be silently swallowed by `s.trim()`
7144 // pre-gate. The `is_ascii_whitespace` coverage extends beyond
7145 // space alone to the full ASCII-whitespace set (space `0x20`,
7146 // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
7147 // the tab arm as a representative of the non-space members.
7148 let err = duration_codec::parse("\t30s").unwrap_err();
7149 assert!(
7150 err.contains("contains whitespace byte"),
7151 "expected whitespace diagnostic in {err:?}"
7152 );
7153 assert!(
7154 err.contains("0x09"),
7155 "missing offending tab byte in {err:?}"
7156 );
7157 }
7158
7159 #[test]
7160 fn restart_window_serde_rejects_whitespace() {
7161 // The shared codec backs `SupervisorSpec::restart_window`
7162 // (`with = "duration_codec"`) — so the whitespace arm
7163 // applies on serde deserialize for the typed Supervisor slot.
7164 // A `{"restartWindow":" 30s"}` payload that previously round-
7165 // tripped to a different canonical string on next serialize
7166 // is now refused at deserialize with the whitespace-byte
7167 // diagnostic. Peer with `restart_window_serde_rejects_leading_zero`
7168 // / `restart_window_serde_rejects_leading_plus` /
7169 // `restart_window_serde_rejects_fractional_seconds` on the
7170 // same canonical-form-drift axis.
7171 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
7172 "restartWindow":" 30s",
7173 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
7174 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7175 let msg = err.to_string();
7176 assert!(
7177 msg.contains("contains whitespace byte"),
7178 "expected whitespace diagnostic in {msg:?}"
7179 );
7180 assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
7181 }
7182
7183 // ── canonical-form: non-ASCII Unicode `White_Space` duration gate ─────
7184 //
7185 // Successor to the ASCII-whitespace arm (a7ae622) on the shared
7186 // duration codec — closes the strictly-complementary class the
7187 // byte-scan cannot see, through the lifted
7188 // [`crate::render::find_non_ascii_whitespace_char`] predicate.
7189 // Applies to `:supervisor :restart-window`, `:politicas :timeout`,
7190 // and `:politicas :circuit-breaker :window` simultaneously via
7191 // this shared codec.
7192
7193 #[test]
7194 fn duration_codec_parse_rejects_leading_nbsp() {
7195 // NBSP prefix — the strictly-complementary drift class the
7196 // ASCII byte-scan cannot see. `str::trim` strips it silently
7197 // and the value drifts to `"30s"` on next serialize.
7198 let err = duration_codec::parse("\u{00A0}30s").unwrap_err();
7199 assert!(
7200 err.contains("non-ASCII Unicode whitespace character"),
7201 "expected non-ASCII whitespace diagnostic in {err:?}"
7202 );
7203 assert!(err.contains("U+00A0"), "missing codepoint in {err:?}");
7204 }
7205
7206 #[test]
7207 fn duration_codec_parse_rejects_trailing_line_separator() {
7208 // LINE SEPARATOR (`\u{2028}`) trailing — paste-from-web-doc
7209 // footgun.
7210 let err = duration_codec::parse("30s\u{2028}").unwrap_err();
7211 assert!(
7212 err.contains("non-ASCII Unicode whitespace character"),
7213 "expected non-ASCII whitespace diagnostic in {err:?}"
7214 );
7215 assert!(err.contains("U+2028"), "missing codepoint in {err:?}");
7216 }
7217
7218 #[test]
7219 fn duration_codec_parse_accepts_ascii_only_forms_after_unicode_arm() {
7220 // Positive-control pin: every ASCII-only canonical form the
7221 // renderer emits stays accepted through the new arm.
7222 assert_eq!(
7223 duration_codec::parse("30s").unwrap(),
7224 Duration::from_secs(30)
7225 );
7226 assert_eq!(
7227 duration_codec::parse("500ms").unwrap(),
7228 Duration::from_millis(500)
7229 );
7230 assert_eq!(
7231 duration_codec::parse("1h").unwrap(),
7232 Duration::from_secs(3600)
7233 );
7234 }
7235
7236 #[test]
7237 fn restart_window_serde_rejects_non_ascii_whitespace() {
7238 // The shared codec backs `SupervisorSpec::restart_window` — so
7239 // the new non-ASCII Unicode whitespace arm applies on serde
7240 // deserialize for the typed Supervisor slot. A
7241 // `{"restartWindow":" 30s"}` payload that previously
7242 // survived the ASCII byte-scan (only ASCII whitespace was
7243 // refused) is now refused at deserialize with the
7244 // non-ASCII-whitespace-and-codepoint diagnostic.
7245 let payload = "{\"estrategia\":\"OneForOne\",\"maxRestarts\":5,\
7246 \"restartWindow\":\"\u{00A0}30s\",\
7247 \"children\":[{\"caixa\":\"w\",\"versao\":\"^0.1\",\"restart\":\"Permanent\"}]}";
7248 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7249 let msg = err.to_string();
7250 assert!(
7251 msg.contains("non-ASCII Unicode whitespace character"),
7252 "expected non-ASCII whitespace diagnostic in {msg:?}"
7253 );
7254 assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
7255 }
7256
7257 // ── drift-detection: serde-derive-to-SUPERVISOR_KEY_* identity ────────
7258
7259 #[test]
7260 fn supervisor_spec_serde_keys_match_lifted_supervisor_key_consts() {
7261 // Load-bearing invariant: the four `SUPERVISOR_KEY_*` consts
7262 // (`SUPERVISOR_KEY_ESTRATEGIA` / `SUPERVISOR_KEY_MAX_RESTARTS` /
7263 // `SUPERVISOR_KEY_RESTART_WINDOW` / `SUPERVISOR_KEY_CHILDREN`)
7264 // name the exact camelCase JSON keys the
7265 // `#[serde(rename_all = "camelCase")]` attribute on
7266 // `SupervisorSpec` emits. Serialize a fully-populated spec (each
7267 // field carries `Some(_)` / non-empty) and pin that each canonical
7268 // byte-sequence appears verbatim in the JSON — a future accidental
7269 // `rename_all = "snake_case"` / `"kebab-case"` / verbatim-field-
7270 // name flip at the derive attribute (any of which would silently
7271 // break every downstream JSON consumer that reaches for one of the
7272 // four consts via `Value::get(...)`) surfaces here as a build-time
7273 // test failure at `supervisor.rs`, not as an apply-time
7274 // `.get(<stale-canonical-const>)` returning `None` far from the
7275 // derive-attr drift's commit. Peer with the sibling
7276 // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
7277 // (d8b8b4f) pin on the M2 `:limits` axis — same discipline the
7278 // M2 typed-slot family established, extended here to close the
7279 // top-level Supervisor axis.
7280 let spec = SupervisorSpec {
7281 estrategia: RestartStrategy::OneForOne,
7282 max_restarts: 5,
7283 restart_window: Some(Duration::from_secs(60)),
7284 children: vec![ChildSpec {
7285 caixa: "w".into(),
7286 versao: "^0.1".into(),
7287 restart: RestartPolicy::Permanent,
7288 }],
7289 };
7290 let json = serde_json::to_string(&spec).unwrap();
7291 for key in [
7292 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7293 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7294 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7295 crate::render::SUPERVISOR_KEY_CHILDREN,
7296 ] {
7297 let quoted = format!("\"{key}\"");
7298 assert!(
7299 json.contains("ed),
7300 "serialized SupervisorSpec must carry the lifted \
7301 SUPERVISOR_KEY_* byte-sequence {quoted} verbatim in \
7302 the JSON emission (got: {json})",
7303 );
7304 }
7305 }
7306
7307 #[test]
7308 fn supervisor_key_consts_are_pairwise_distinct() {
7309 // Cross-axis drift-detection pin: a future collapse of two
7310 // canonical top-level byte-strings onto the same value (e.g. an
7311 // accidental copy-paste flip of `SUPERVISOR_KEY_CHILDREN` to
7312 // also read `"estrategia"`) would silently reroute every
7313 // downstream probe on one axis onto the sibling axis's overlay
7314 // entry and pass every propagation-probe test that expected only
7315 // the stale axis's value. Peer of the sibling four-way distinct
7316 // pin on the `M2_LIMITS_KEY_*` tetrad (d8b8b4f).
7317 let all = [
7318 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7319 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7320 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7321 crate::render::SUPERVISOR_KEY_CHILDREN,
7322 ];
7323 for (i, a) in all.iter().enumerate() {
7324 for b in all.iter().skip(i + 1) {
7325 assert_ne!(
7326 a, b,
7327 "SUPERVISOR_KEY_* consts must be pairwise-distinct \
7328 canonical byte-sequences — got `{a}` == `{b}`",
7329 );
7330 }
7331 }
7332 }
7333
7334 #[test]
7335 fn supervisor_key_consts_are_lower_camel_case_shape() {
7336 // Shape-pin: every `SUPERVISOR_KEY_*` const must be a
7337 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
7338 // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
7339 // capital, no whitespace / dots) — the canonical shape the
7340 // `#[serde(rename_all = "camelCase")]` derive produces on
7341 // `SupervisorSpec`. A future flip to a non-camelCase attribute
7342 // at the derive surfaces both here (this test fails on the
7343 // stale-constant shape) and at
7344 // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
7345 // (that test fails on the mismatch between const and derive).
7346 // Peer with `m2_limits_key_consts_are_lower_camel_case_shape`
7347 // (d8b8b4f) on the sibling M2 `:limits` axis.
7348 for key in [
7349 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7350 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7351 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7352 crate::render::SUPERVISOR_KEY_CHILDREN,
7353 ] {
7354 assert!(
7355 !key.is_empty(),
7356 "SUPERVISOR_KEY_* must be non-empty (got {key:?})"
7357 );
7358 let first = key.chars().next().unwrap();
7359 assert!(
7360 first.is_ascii_lowercase(),
7361 "SUPERVISOR_KEY_* must lead with an ASCII-lowercase byte \
7362 (got {key:?}, leads with {first:?})",
7363 );
7364 assert!(
7365 key.chars().all(|c| c.is_ascii_alphanumeric()),
7366 "SUPERVISOR_KEY_* must be ASCII-alphanumeric only \
7367 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
7368 );
7369 }
7370 }
7371
7372 #[test]
7373 fn supervisor_key_consts_are_byte_distinct_from_supervisor_author_key_peers() {
7374 // Cross-axis drift pin: the four `SUPERVISOR_KEY_*` consts
7375 // (camelCase JSON keys, no leading colon) must never collide
7376 // byte-for-byte with the four peer `SUPERVISOR_AUTHOR_KEY_*`
7377 // consts (kebab-case author-facing labels with leading colon)
7378 // that sit next to them at `caixa_core::render`. Both families
7379 // cover the same four typed Supervisor slots on two distinct
7380 // axes (author-side kebab vs renderer-side camelCase);
7381 // collapsing either family onto the other's byte-shape would
7382 // silently reroute the render-side probe onto the author-facing
7383 // surface, or vice versa. Peer of the byte-distinctness
7384 // discipline the `M3_PLACEMENT_KEY_ESTRATEGIA` docstring names
7385 // against the peer `M3_AUTHOR_KEY_PLACEMENT`.
7386 let pairs = [
7387 (
7388 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7389 crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA,
7390 ),
7391 (
7392 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7393 crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS,
7394 ),
7395 (
7396 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7397 crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW,
7398 ),
7399 (
7400 crate::render::SUPERVISOR_KEY_CHILDREN,
7401 crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN,
7402 ),
7403 ];
7404 for (json_key, author_key) in pairs {
7405 assert_ne!(
7406 json_key, author_key,
7407 "SUPERVISOR_KEY_* (JSON side) must differ byte-for-byte \
7408 from the peer SUPERVISOR_AUTHOR_KEY_* (author side); \
7409 got JSON `{json_key}` == author `{author_key}`",
7410 );
7411 }
7412 }
7413
7414 // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_KEY_* identity ──
7415
7416 #[test]
7417 fn child_spec_serde_keys_match_lifted_supervisor_child_key_consts() {
7418 // Load-bearing invariant: the three `SUPERVISOR_CHILD_KEY_*` consts
7419 // (`SUPERVISOR_CHILD_KEY_CAIXA` / `SUPERVISOR_CHILD_KEY_VERSAO` /
7420 // `SUPERVISOR_CHILD_KEY_RESTART`) name the exact camelCase JSON
7421 // keys the `#[serde(rename_all = "camelCase")]` attribute on
7422 // `ChildSpec` emits. Serialize a fully-populated `ChildSpec` and
7423 // pin that each canonical byte-sequence appears verbatim in the
7424 // JSON — a future accidental `rename_all = "snake_case"` /
7425 // `"kebab-case"` / verbatim-field-name flip at the derive
7426 // attribute (any of which would silently break every downstream
7427 // JSON consumer that reaches for one of the three consts via
7428 // `Value::get(...)`) surfaces here as a build-time test failure at
7429 // `supervisor.rs`, not as an apply-time
7430 // `.get(<stale-canonical-const>)` returning `None` far from the
7431 // derive-attr drift's commit. Peer with the enclosing
7432 // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
7433 // (40cc4e5) pin on the M2 supervision-tree top-level axis — same
7434 // discipline the SupervisorSpec top-level lift established,
7435 // extended here to the sibling per-`:children` entry `ChildSpec`
7436 // derive so the last M2 typed-struct sub-block
7437 // `#[serde(rename_all = "camelCase")]` axis on the Supervisor
7438 // surface without a lifted serde-key peer joins the substrate's
7439 // "one canonical byte-string per typed serialized-key axis"
7440 // discipline.
7441 let c = ChildSpec {
7442 caixa: "worker".into(),
7443 versao: "^0.1".into(),
7444 restart: RestartPolicy::Permanent,
7445 };
7446 let json = serde_json::to_string(&c).unwrap();
7447 for key in [
7448 crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
7449 crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
7450 crate::render::SUPERVISOR_CHILD_KEY_RESTART,
7451 ] {
7452 let quoted = format!("\"{key}\"");
7453 assert!(
7454 json.contains("ed),
7455 "serialized ChildSpec must carry the lifted \
7456 SUPERVISOR_CHILD_KEY_* byte-sequence {quoted} verbatim \
7457 in the JSON emission (got: {json})",
7458 );
7459 }
7460 }
7461
7462 #[test]
7463 fn supervisor_child_key_consts_are_pairwise_distinct() {
7464 // Cross-axis drift-detection pin: a future collapse of two
7465 // canonical `ChildSpec` per-entry byte-strings onto the same
7466 // value (e.g. an accidental copy-paste flip of
7467 // `SUPERVISOR_CHILD_KEY_RESTART` to also read `"caixa"`) would
7468 // silently reroute every downstream probe on one axis onto the
7469 // sibling axis's overlay entry and pass every propagation-probe
7470 // test that expected only the stale axis's value. Peer of the
7471 // sibling three-way distinct pin on the `CONTRATO_KEY_*` triad
7472 // (ca463a4) and the two-way distinct pin on the `MEMBRO_KEY_*`
7473 // pair (ce80ca0).
7474 let all = [
7475 crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
7476 crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
7477 crate::render::SUPERVISOR_CHILD_KEY_RESTART,
7478 ];
7479 for (i, a) in all.iter().enumerate() {
7480 for b in all.iter().skip(i + 1) {
7481 assert_ne!(
7482 a, b,
7483 "SUPERVISOR_CHILD_KEY_* consts must be pairwise-\
7484 distinct canonical byte-sequences — got `{a}` == `{b}`",
7485 );
7486 }
7487 }
7488 }
7489
7490 #[test]
7491 fn supervisor_child_key_consts_are_lower_camel_case_shape() {
7492 // Shape-pin: every `SUPERVISOR_CHILD_KEY_*` const must be a
7493 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
7494 // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
7495 // capital, no whitespace / dots) — the canonical shape the
7496 // `#[serde(rename_all = "camelCase")]` derive produces on
7497 // `ChildSpec`. A future flip to a non-camelCase attribute at the
7498 // derive surfaces both here (this test fails on the
7499 // stale-constant shape) and at
7500 // `child_spec_serde_keys_match_lifted_supervisor_child_key_consts`
7501 // (that test fails on the mismatch between const and derive).
7502 // Peer with `supervisor_key_consts_are_lower_camel_case_shape`
7503 // (40cc4e5) on the sibling `SupervisorSpec` top-level axis.
7504 for key in [
7505 crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
7506 crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
7507 crate::render::SUPERVISOR_CHILD_KEY_RESTART,
7508 ] {
7509 assert!(
7510 !key.is_empty(),
7511 "SUPERVISOR_CHILD_KEY_* must be non-empty (got {key:?})"
7512 );
7513 let first = key.chars().next().unwrap();
7514 assert!(
7515 first.is_ascii_lowercase(),
7516 "SUPERVISOR_CHILD_KEY_* must lead with an ASCII-lowercase \
7517 byte (got {key:?}, leads with {first:?})",
7518 );
7519 assert!(
7520 key.chars().all(|c| c.is_ascii_alphanumeric()),
7521 "SUPERVISOR_CHILD_KEY_* must be ASCII-alphanumeric only \
7522 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
7523 );
7524 }
7525 }
7526
7527 // ── drift-detection: serde-derive-to-SUPERVISOR_ESTRATEGIA_* identity ────
7528
7529 #[test]
7530 fn restart_strategy_variants_serialize_to_lifted_scalar_values() {
7531 // The fail-before-pass-after pin: pre-lift there was no
7532 // single-source binding between the [`RestartStrategy`] variant
7533 // name the un-`rename`d `Serialize` derive emits under
7534 // [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the byte-string
7535 // every downstream cluster-side dispatcher (the future
7536 // wasm-operator's per-supervisor sibling-restart branch, the
7537 // future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
7538 // admission-time enum-arm bind, the `caixa-operator`'s
7539 // hierarchical reconciliation scheduler's per-strategy fan-out)
7540 // probes verbatim. A future `#[serde(rename_all = "kebab-case")]`
7541 // attribute on the enum — or a per-variant `#[serde(rename = "…")]`
7542 // override, or a variant rename in the source — would silently
7543 // rebrand the emitted scalar under one spelling while every
7544 // downstream dispatcher still probed the other, with the failure
7545 // surfacing at the operator's reconcile posture (subtrees coming
7546 // up under the `default()` `OneForOne` arm rather than the typed
7547 // slot's declared strategy — a bad child would then only take
7548 // itself down instead of the sibling set the author intended, so
7549 // shared-state children fall out of sync) far from the source
7550 // rebrand commit and with no field naming the drift. Pinning the
7551 // two paths (the `Serialize` derive's serialized string AND the
7552 // [`RestartStrategy::as_str`] helper) to the same four lifted
7553 // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
7554 // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
7555 // [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
7556 // [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
7557 // byte-strings makes any future drift on either endpoint fail
7558 // here at caixa-core build time. Peer of the M3
7559 // `placement_strategy_variants_serialize_to_lifted_scalar_values`
7560 // (3f0e21c) on the sibling `PlacementStrategy` axis — same
7561 // three-path-convergence discipline, extended to close the
7562 // OTP-shaped per-supervisor sibling-restart axis.
7563 for (variant, expected) in [
7564 (
7565 RestartStrategy::OneForOne,
7566 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7567 ),
7568 (
7569 RestartStrategy::OneForAll,
7570 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7571 ),
7572 (
7573 RestartStrategy::RestForOne,
7574 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7575 ),
7576 (
7577 RestartStrategy::SimpleOneForOne,
7578 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7579 ),
7580 ] {
7581 let json = serde_json::to_string(&variant).unwrap();
7582 assert_eq!(
7583 json,
7584 format!("\"{expected}\""),
7585 "RestartStrategy::{variant:?} must serialize to {expected:?}"
7586 );
7587 assert_eq!(
7588 variant.as_str(),
7589 expected,
7590 "RestartStrategy::{variant:?}.as_str() must return the lifted \
7591 SUPERVISOR_ESTRATEGIA_* constant"
7592 );
7593 }
7594 }
7595
7596 #[test]
7597 fn supervisor_estrategia_consts_are_pairwise_distinct() {
7598 // Cross-arm drift-detection pin: a future collapse of two
7599 // canonical variant byte-strings onto the same value (e.g. an
7600 // accidental copy-paste flip of `SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`
7601 // to also read `"OneForOne"`) would silently reroute every
7602 // downstream operator's per-strategy dispatch onto the sibling
7603 // arm's reconcile branch and pass every propagation-probe test
7604 // that expected only the stale arm's value — the mis-strategied
7605 // subtree would come up with the wrong sibling-restart posture
7606 // on every subsequent failure. Peer of the sibling four-way
7607 // distinct pin `supervisor_key_consts_are_pairwise_distinct`
7608 // (40cc4e5) on the top-level `SUPERVISOR_KEY_*` axis.
7609 let all = [
7610 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7611 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7612 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7613 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7614 ];
7615 for (i, a) in all.iter().enumerate() {
7616 for (j, b) in all.iter().enumerate() {
7617 if i != j {
7618 assert_ne!(
7619 a, b,
7620 "SUPERVISOR_ESTRATEGIA_* consts must be pairwise distinct \
7621 — got duplicate {a:?} at indices {i} and {j}",
7622 );
7623 }
7624 }
7625 }
7626 }
7627
7628 #[test]
7629 fn restart_strategy_display_routes_through_as_str_helper() {
7630 // The fail-before-pass-after pin on the first half of the
7631 // three-path convergence: pre-convergence the sibling
7632 // OTP-shape typed enum [`RestartStrategy`] carried a
7633 // [`std::fmt::Display`] surface via its
7634 // `#[discriminant(also_display)]` gen-platform derive route,
7635 // which arrived kebab-case as `"one-for-one"` /
7636 // `"one-for-all"` / `"rest-for-one"` /
7637 // `"simple-one-for-one"` while the wire format ran as
7638 // PascalCase `"OneForOne"` / `"OneForAll"` / `"RestForOne"` /
7639 // `"SimpleOneForOne"` through the un-`rename`d serde derive.
7640 // Every consumer reaching for a strategy byte-string past the
7641 // wire format had to pick between three paths
7642 // ([`RestartStrategy::as_str`], the `Serialize` derive's
7643 // serialized string, or `format!("{v}")` on the
7644 // discriminant-Display route), any two of which a future
7645 // variant rename or `#[serde(rename_all = "kebab-case")]`
7646 // attribute would silently desynchronize. Wiring
7647 // [`std::fmt::Display`] through [`RestartStrategy::as_str`]
7648 // closes the third path: every `format!("{v}")` call reaches
7649 // the same lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
7650 // const the wire format and the [`RestartStrategy::as_str`]
7651 // helper already route through, so a future variant rename
7652 // lands at exactly one place. Pin the routing here so a future
7653 // `impl std::fmt::Display for RestartStrategy`
7654 // reimplementation that hand-rolls the arms instead of
7655 // delegating to [`RestartStrategy::as_str`] fails at
7656 // caixa-core build time. Peer of the M3
7657 // `placement_strategy_display_routes_through_as_str_helper`
7658 // (cc8f749) which the M3 axis converged first.
7659 for &variant in RestartStrategy::ALL {
7660 assert_eq!(
7661 variant.to_string(),
7662 variant.as_str(),
7663 "RestartStrategy::{variant:?} Display must route through \
7664 RestartStrategy::as_str (single source of truth: the lifted \
7665 SUPERVISOR_ESTRATEGIA_* const the wire format also emits)"
7666 );
7667 }
7668 }
7669
7670 #[test]
7671 fn restart_strategy_display_matches_serialized_wire_byte_string() {
7672 // The fail-before-pass-after pin on the second half of the
7673 // three-path convergence: `Display` (user-facing text) agrees
7674 // byte-for-byte with the `Serialize` derive's wire format
7675 // (canonical camelCase-schema `SUPERVISOR_KEY_ESTRATEGIA`
7676 // scalar) on every variant. Pre-convergence the two paths
7677 // were structurally independent — a future
7678 // `#[serde(rename_all = "kebab-case")]` attribute on the
7679 // enum would silently rebrand the emitted wire scalar
7680 // (`one-for-one`, `one-for-all`, `rest-for-one`,
7681 // `simple-one-for-one`) while every consumer that
7682 // pretty-prints the strategy (the future wasm-operator's
7683 // per-supervisor sibling-restart-strategy diagnostic line,
7684 // the future `feira app graph` per-supervisor strategy line,
7685 // the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
7686 // materializer's admission-webhook rejection body) would
7687 // still emit the PascalCase form the `as_str` / `Display`
7688 // route returns, with the mismatch surfacing at consumer
7689 // parse time / operator dispatch time far from the source
7690 // rebrand commit. Pin the two paths byte-for-byte here so any
7691 // future serde-attribute or variant-rename drift is a
7692 // caixa-core-build-time test failure at this call, not a
7693 // silent per-consumer dispatch miss. Peer of the M3
7694 // `placement_strategy_display_matches_serialized_wire_byte_string`
7695 // (cc8f749) which the M3 axis converged first.
7696 for &variant in RestartStrategy::ALL {
7697 let wire = serde_json::to_string(&variant).unwrap();
7698 let unquoted = wire
7699 .strip_prefix('"')
7700 .and_then(|s| s.strip_suffix('"'))
7701 .expect("serialized RestartStrategy is a JSON string");
7702 assert_eq!(
7703 variant.to_string(),
7704 unquoted,
7705 "RestartStrategy::{variant:?} Display byte-string must match the \
7706 Serialize derive's wire byte-string (three-path convergence: \
7707 Display + as_str + Serialize all resolve to the same \
7708 SUPERVISOR_ESTRATEGIA_* const)"
7709 );
7710 }
7711 }
7712
7713 #[test]
7714 fn restart_strategy_as_ref_str_routes_through_as_str_accessor() {
7715 // Fail-before-pass-after byte-parity pin on the lifted
7716 // `impl AsRef<str> for RestartStrategy` — asserts the
7717 // standard-library trait impl and the substrate-primitive
7718 // [`RestartStrategy::as_str`] `pub const fn` accessor resolve
7719 // to the same `&str` per instance across the four-arm
7720 // closed set, so any future silent detour that routes the
7721 // impl through a divergent projection (a per-arm inline
7722 // `match self { RestartStrategy::OneForOne => "OneForOne", … }`
7723 // re-inlining that opens a compile-time link to the un-lifted
7724 // arm-literal, a swap onto the kebab-case
7725 // [`gen_platform::Discriminant`] catalog identity that would
7726 // collide the wire axis with the dispatcher-catalog axis) trips
7727 // at caixa-core test time under `PartialEq` rather than at a
7728 // downstream `impl AsRef<str>`-bound consumer's silent split.
7729 // Sweeps every one of the four arms
7730 // [`RestartStrategy::ALL`] carries so no arm's projection is
7731 // covered only by the sibling wire-format `Serialize` derive
7732 // path. Peer of the sibling
7733 // [`crate::version::tests::caixa_version_as_ref_str_routes_through_as_str_accessor`]
7734 // (16d5c7e) `AsRef<str>`-byte-parity pin on the paired
7735 // top-level `:versao` typed newtype — the two pins together
7736 // cover the substrate primitive's `AsRef<str>` projection axis
7737 // on the paired newtype + closed-set-typed-enum surface.
7738 for &variant in RestartStrategy::ALL {
7739 assert_eq!(
7740 <RestartStrategy as AsRef<str>>::as_ref(&variant),
7741 variant.as_str(),
7742 "AsRef<str> impl on RestartStrategy::{variant:?} must \
7743 byte-equal RestartStrategy::as_str on the same instance \
7744 — divergence signals a silent detour off the substrate-\
7745 primitive accessor"
7746 );
7747 }
7748 }
7749
7750 #[test]
7751 fn restart_strategy_as_ref_str_routes_through_display_via_shared_accessor() {
7752 // Fail-before-pass-after byte-parity pin on the three-path
7753 // convergence discipline the M2 sibling-restart primitive now
7754 // carries on the `&str`-projection axis:
7755 // `<RestartStrategy as AsRef<str>>::as_ref(&s)` (the newly
7756 // lifted impl), `format!("{s}")` (the pre-existing
7757 // [`fmt::Display`] impl), and `s.as_str()` (the substrate-
7758 // primitive `pub const fn` accessor both trait impls delegate
7759 // through) must resolve to the same byte-string on every
7760 // instance across the four-arm closed set. Refuses any future
7761 // divergence between the two trait impls (a stray
7762 // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
7763 // rather than delegating through the shared accessor; a
7764 // hypothetical `AsRef<str>` rewrite that inlines a per-arm
7765 // literal cascade) that would silently split the two
7766 // projection paths of the same closed-set typed enum. Mirrors
7767 // the sibling three-path-convergence discipline the peer
7768 // [`crate::CaixaVersion`] typed newtype carries on its
7769 // `AsRef<str>` / `Display` / `as_str` triple
7770 // (version.rs pin
7771 // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
7772 // 16d5c7e).
7773 for &variant in RestartStrategy::ALL {
7774 let via_as_ref: &str = <RestartStrategy as AsRef<str>>::as_ref(&variant);
7775 let via_display: String = format!("{variant}");
7776 let via_accessor: &str = variant.as_str();
7777 assert_eq!(via_as_ref, via_accessor);
7778 assert_eq!(via_display, via_accessor);
7779 assert_eq!(via_as_ref, via_display.as_str());
7780 }
7781 }
7782
7783 #[test]
7784 fn restart_strategy_all_enumerates_every_variant_exactly_once() {
7785 // Fail-before-pass-after pin on the [`RestartStrategy::ALL`]
7786 // exhaustive-iteration surface: every variant appears exactly
7787 // once, and the slice length matches the arm count of the
7788 // closed set. Every consumer that walks the accepted-strategy
7789 // set (a future `feira supervisor --estrategia …` CLI-side
7790 // arg-parse's "did you mean" hint, a future M4 admission-
7791 // webhook's rejection body naming the accepted-`:estrategia`
7792 // list, the [`RestartStrategy::from_wire`] reverse-projection
7793 // consumers that iterate the accept-set for diagnostic
7794 // rendering) reads through this slice, so a future arm addition
7795 // that grows the enum but forgets to grow [`Self::ALL`]
7796 // silently truncates every downstream consumer's accept-set at
7797 // the same pre-addition boundary — this pin fails at caixa-core
7798 // build time on the pairwise-distinct + arm-count invariants.
7799 //
7800 // Peer of the sibling [`crate::CaixaKind::ALL`] (6b1f4fb) /
7801 // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
7802 // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
7803 // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
7804 // pins on the peer closed-set typed-enum axes.
7805 let all: &[RestartStrategy] = RestartStrategy::ALL;
7806 assert_eq!(
7807 all.len(),
7808 4,
7809 "RestartStrategy::ALL must enumerate every variant of the \
7810 four-arm closed set (OneForOne, OneForAll, RestForOne, \
7811 SimpleOneForOne); got {all:?}"
7812 );
7813 for (i, a) in all.iter().enumerate() {
7814 for (j, b) in all.iter().enumerate() {
7815 if i != j {
7816 assert_ne!(
7817 a, b,
7818 "RestartStrategy::ALL must carry every variant exactly \
7819 once — got duplicate {a:?} at indices {i} and {j}"
7820 );
7821 }
7822 }
7823 }
7824 for variant in [
7825 RestartStrategy::OneForOne,
7826 RestartStrategy::OneForAll,
7827 RestartStrategy::RestForOne,
7828 RestartStrategy::SimpleOneForOne,
7829 ] {
7830 assert!(
7831 all.contains(&variant),
7832 "RestartStrategy::ALL must contain {variant:?} — a future arm \
7833 addition that grows the enum but forgets to grow the ALL slice \
7834 silently truncates every downstream consumer's accept-set at \
7835 the pre-addition boundary"
7836 );
7837 }
7838 }
7839
7840 #[test]
7841 fn restart_strategy_from_wire_accepts_every_lifted_constant() {
7842 // Fail-before-pass-after pin on the forward accept-set of the
7843 // [`RestartStrategy::from_wire`] reverse projection: every
7844 // canonical [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
7845 // constant the [`RestartStrategy::as_str`] emitter walks parses
7846 // back to its paired variant. Any future arm addition that
7847 // grows the emitter's `as_str` match but forgets to grow the
7848 // parser's `from_wire` match silently splits the two halves of
7849 // the round-trip — the wire byte-string one non-serde consumer
7850 // parses from the one the emitter wrote — with the failure
7851 // surfacing at parse time far from the rebrand commit. Pinning
7852 // the four-arm accept-set here catches the drift at caixa-core
7853 // build time.
7854 //
7855 // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
7856 // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
7857 // accept-set pins on the peer closed-set typed-enum `str → Self`
7858 // axes.
7859 for (wire, expected) in [
7860 (
7861 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7862 RestartStrategy::OneForOne,
7863 ),
7864 (
7865 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7866 RestartStrategy::OneForAll,
7867 ),
7868 (
7869 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7870 RestartStrategy::RestForOne,
7871 ),
7872 (
7873 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7874 RestartStrategy::SimpleOneForOne,
7875 ),
7876 ] {
7877 let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
7878 panic!(
7879 "RestartStrategy::from_wire({wire:?}) must accept every \
7880 SUPERVISOR_ESTRATEGIA_* constant — got None for the \
7881 lifted canonical byte-string that RestartStrategy::{expected:?} \
7882 serializes as under SUPERVISOR_KEY_ESTRATEGIA"
7883 )
7884 });
7885 assert_eq!(
7886 parsed, expected,
7887 "RestartStrategy::from_wire({wire:?}) must return \
7888 RestartStrategy::{expected:?}; got RestartStrategy::{parsed:?}"
7889 );
7890 }
7891 }
7892
7893 #[test]
7894 fn restart_strategy_from_wire_round_trips_through_as_str() {
7895 // Fail-before-pass-after pin on the closed round-trip between
7896 // the forward [`RestartStrategy::as_str`] emitter and the
7897 // reverse [`RestartStrategy::from_wire`] parser: for every
7898 // variant in [`RestartStrategy::ALL`], parsing the emitter's
7899 // output must return exactly the same variant. Any per-arm
7900 // divergence — a future arm added to `as_str` but not
7901 // `from_wire`, an accidental copy-paste flip in one but not
7902 // the other — silently splits the emit and parse halves and
7903 // the failure surfaces at consumer parse time far from the
7904 // drift site. The `ALL`-iterating shape means a future arm
7905 // addition picks up the coverage by construction.
7906 //
7907 // Peer of the sibling
7908 // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
7909 // (18c7342) round-trip pin on
7910 // [`crate::aplicacao::PlacementStrategy::from_wire`] and
7911 // [`crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`]
7912 // (6b1f4fb) round-trip pin on [`crate::CaixaKind::from_wire`].
7913 for &variant in RestartStrategy::ALL {
7914 let wire = variant.as_str();
7915 let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
7916 panic!(
7917 "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
7918 must be Some({variant:?}) — the two halves of the round-trip \
7919 dispatch on the same lifted SUPERVISOR_ESTRATEGIA_* consts; \
7920 got None on wire byte-string {wire:?}"
7921 )
7922 });
7923 assert_eq!(
7924 parsed, variant,
7925 "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
7926 must round-trip to the same variant; got {parsed:?}"
7927 );
7928 }
7929 }
7930
7931 #[test]
7932 fn restart_strategy_from_wire_rejects_unknown_byte_strings() {
7933 // Fail-before-pass-after pin on the closed-set refusal
7934 // discipline of [`RestartStrategy::from_wire`]: every
7935 // byte-string outside the four-arm accept-set returns `None`
7936 // rather than silently collapsing onto the [`Default`]
7937 // (`OneForOne`) arm or an arbitrary neighbor. The refusal set
7938 // exercised here sweeps the load-bearing drift shapes: the
7939 // empty string (a stripped serde-attribute drift), all-
7940 // whitespace strings (the canonical text-editor accidental
7941 // padding shape), the kebab-case dispatcher-catalog identities
7942 // (`"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
7943 // `"simple-one-for-one"` — the [`gen_platform::FromStrKind`]-
7944 // derived [`std::str::FromStr`] accept-set, which parses the
7945 // *other* axis of this enum's two-axis split and must not leak
7946 // into the `from_wire` PascalCase-wire accept-set), the
7947 // lowercased single-word forms (`"oneforone"`), the padded
7948 // canonical scalar (`" OneForOne "`), the trailing-newline
7949 // shapes (`"OneForOne\n"`), and neighboring-but-unknown arms
7950 // (`"AllForOne"` — the canonical typo direction).
7951 //
7952 // Peer of the sibling
7953 // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
7954 // (2aa6d23) +
7955 // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
7956 // (18c7342) refusal pins on the peer closed-set typed-enum
7957 // axes.
7958 for bad in [
7959 "",
7960 " ",
7961 "\n",
7962 "\t",
7963 "one-for-one",
7964 "one-for-all",
7965 "rest-for-one",
7966 "simple-one-for-one",
7967 "oneforone",
7968 "OneForOnes",
7969 "one_for_one",
7970 "one for one",
7971 "ONEFORONE",
7972 "OneForOne ",
7973 " OneForOne",
7974 " SimpleOneForOne ",
7975 "OneForOne\n",
7976 "restforone",
7977 "REST_FOR_ONE",
7978 "AllForOne",
7979 "Simple",
7980 "?",
7981 ] {
7982 assert!(
7983 RestartStrategy::from_wire(bad).is_none(),
7984 "RestartStrategy::from_wire({bad:?}) must return None — the \
7985 parser's accept-set is exactly the four RestartStrategy::as_str \
7986 outputs (OneForOne, OneForAll, RestForOne, SimpleOneForOne), \
7987 and this byte-string is outside that closed set"
7988 );
7989 }
7990 }
7991
7992 #[test]
7993 fn restart_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
7994 // Fail-before-pass-after pin on the fourth path of the four-path
7995 // convergence: `from_wire` (the reverse projection) inverts the
7996 // `Serialize` derive's wire byte-string on every variant.
7997 // Together with the pre-existing three-path convergence
7998 // (`Display` + `as_str` + `Serialize` all resolve to the same
7999 // lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const,
8000 // pinned by
8001 // [`restart_strategy_display_matches_serialized_wire_byte_string`])
8002 // this closes the round-trip: the wire byte-string the
8003 // `Serialize` derive emits parses back to the same variant
8004 // through `from_wire`, so any future serde-attribute or variant-
8005 // rename drift on the emit half now surfaces as a matched drift
8006 // on the parse half at caixa-core build time — the two halves
8007 // migrate as a unit through the lifted consts on any future
8008 // rename, and the round-trip cannot silently split.
8009 //
8010 // Peer of the sibling
8011 // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
8012 // (18c7342) wire-format pin on
8013 // [`crate::aplicacao::PlacementStrategy::from_wire`].
8014 for &variant in RestartStrategy::ALL {
8015 let wire = serde_json::to_string(&variant).unwrap();
8016 let unquoted = wire
8017 .strip_prefix('"')
8018 .and_then(|s| s.strip_suffix('"'))
8019 .expect("serialized RestartStrategy is a JSON string");
8020 let parsed = RestartStrategy::from_wire(unquoted).unwrap_or_else(|| {
8021 panic!(
8022 "RestartStrategy::from_wire({unquoted:?}) must accept the \
8023 Serialize derive's wire byte-string for \
8024 RestartStrategy::{variant:?} — the four-path convergence \
8025 (Display + as_str + Serialize + from_wire) resolves through \
8026 the same lifted SUPERVISOR_ESTRATEGIA_* const; got None"
8027 )
8028 });
8029 assert_eq!(
8030 parsed, variant,
8031 "RestartStrategy::from_wire of the Serialize derive's wire \
8032 byte-string for RestartStrategy::{variant:?} must round-trip \
8033 to the same variant; got {parsed:?}"
8034 );
8035 }
8036 }
8037
8038 #[test]
8039 fn restart_strategy_try_from_str_routes_through_from_wire_accessor() {
8040 // Fail-before-pass-after byte-parity pin on the newly lifted
8041 // `impl TryFrom<&str> for RestartStrategy` — asserts the standard-
8042 // library trait impl and the substrate-primitive
8043 // [`RestartStrategy::from_wire`] `Option<Self>` accessor resolve to
8044 // the same four-arm accept-set across every arm the exhaustive
8045 // [`RestartStrategy::ALL`] slice enumerates. Any future silent
8046 // detour that routes the trait impl through a divergent projection
8047 // (a per-arm inline `match s { "OneForOne" => Ok(Self::OneForOne),
8048 // … }` re-inlining that opens a compile-time link to the un-
8049 // lifted arm-literal, a hypothetical `#[serde(rename_all = "…")]`
8050 // attribute drift that silently splits the wire byte-string from
8051 // every consumer that reaches for this typed dispatch, an
8052 // accidental swap onto the kebab-case dispatcher-catalog axis the
8053 // pre-existing [`std::str::FromStr`] impl parses through and which
8054 // would collide the two-axis wire/catalog split the sibling
8055 // [`RestartStrategy::from_wire`] doc block makes load-bearing)
8056 // trips at caixa-core test time under `assert_eq!` rather than at
8057 // a downstream `impl TryFrom<&str>`-bound consumer's silent split.
8058 // Sweeps every one of the four arms [`RestartStrategy::ALL`]
8059 // carries so no arm's projection is covered only by the sibling
8060 // method-named `from_wire` path. Peer of the sibling
8061 // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
8062 // (3c83606),
8063 // [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
8064 // (bf33136), and the M3
8065 // [`crate::aplicacao::tests::placement_strategy_try_from_str_routes_through_from_wire_accessor`]
8066 // (6fd00cd) — extends the trait-idiomatic reverse-projection axis
8067 // onto the first M2-OTP-shape closed-set typed enum on the caixa
8068 // surface.
8069 for &variant in RestartStrategy::ALL {
8070 let wire = variant.as_str();
8071 assert_eq!(
8072 <RestartStrategy as TryFrom<&str>>::try_from(wire),
8073 Ok(variant),
8074 "TryFrom<&str> impl on RestartStrategy must round-trip \
8075 RestartStrategy::{variant:?}.as_str() = {wire:?} back to \
8076 Ok(RestartStrategy::{variant:?}) — divergence from \
8077 RestartStrategy::from_wire signals a silent detour off \
8078 the substrate-primitive accessor"
8079 );
8080 assert_eq!(
8081 <RestartStrategy as TryFrom<&str>>::try_from(wire).ok(),
8082 RestartStrategy::from_wire(wire),
8083 "TryFrom<&str> ok()-projection on {wire:?} must byte-equal \
8084 RestartStrategy::from_wire on the same input"
8085 );
8086 }
8087 }
8088
8089 #[test]
8090 fn restart_strategy_try_from_str_rejects_unknown_byte_strings() {
8091 // Rejection witness on the `impl TryFrom<&str> for
8092 // RestartStrategy` — sweeps a candidate set of byte-strings
8093 // outside the four-arm PascalCase wire accept-set the sibling
8094 // [`RestartStrategy::as_str`] emits and asserts every one lands on
8095 // `Err(())`, so a future accidental widening of the trait impl's
8096 // accept-set (a stray additional
8097 // `_ if s.eq_ignore_ascii_case("OneForOne") => Ok(…)` case-fold
8098 // path, a silent inclusion of the kebab-case dispatcher-catalog
8099 // byte-string the pre-existing [`std::str::FromStr`] impl the
8100 // [`gen_platform::FromStrKind`] derive installs parses onto the
8101 // wire axis — which would collide the two-axis
8102 // wire/dispatcher-catalog split the sibling
8103 // [`RestartStrategy::from_wire`] doc block makes load-bearing —
8104 // an English-rebrand or plural-arm silent alias that would
8105 // widen the wire accept-set past the OTP-canonical four) trips at
8106 // caixa-core test time. The candidate set includes the empty
8107 // string, whitespace-only padding, the kebab-case dispatcher-
8108 // catalog byte-strings on the sibling axis (a caller who confuses
8109 // the two axes trips here rather than at a downstream consumer's
8110 // silent reject), a lowercase / uppercase / mixed-case fold of
8111 // each PascalCase arm (a caller who assumes case-fold acceptance
8112 // trips here), leading/trailing whitespace padding, the trailing-
8113 // newline shape, quote-wrapped candidates, and a residual set of
8114 // plausible-but-wrong English rebrand candidates. Peer of the
8115 // sibling
8116 // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
8117 // (3c83606) and
8118 // [`crate::aplicacao::tests::placement_strategy_try_from_str_rejects_unknown_byte_strings`]
8119 // (6fd00cd) rejection witnesses.
8120 let rejected: &[&str] = &[
8121 "",
8122 " ",
8123 "\n",
8124 "\t",
8125 "one-for-one",
8126 "one-for-all",
8127 "rest-for-one",
8128 "simple-one-for-one",
8129 "oneforone",
8130 "one_for_one",
8131 "OneForOnes",
8132 "ONEFORONE",
8133 "oneforall",
8134 "restforone",
8135 "simpleoneforone",
8136 "OneForOne ",
8137 " OneForOne",
8138 " OneForAll ",
8139 "OneForOne\n",
8140 "RestForOne\t",
8141 "OneForEach",
8142 "AllForOne",
8143 "one for one",
8144 "\"OneForOne\"",
8145 "?",
8146 ];
8147 for &input in rejected {
8148 assert_eq!(
8149 <RestartStrategy as TryFrom<&str>>::try_from(input),
8150 Err(()),
8151 "TryFrom<&str> impl on RestartStrategy must reject the \
8152 non-wire byte-string {input:?} — silent acceptance signals \
8153 an accept-set widening off the paired \
8154 RestartStrategy::from_wire resolver"
8155 );
8156 }
8157 }
8158
8159 #[test]
8160 fn restart_strategy_try_from_str_and_from_wire_partition_the_accept_set() {
8161 // Cross-axis partition pin: the paired `TryFrom<&str>` and
8162 // `from_wire` reverse projections must resolve identically on
8163 // *every* input, not just the ones [`RestartStrategy::ALL`]
8164 // enumerates. Sweeps a mixed candidate set spanning accepted
8165 // (four-arm PascalCase wire byte-strings) and rejected (kebab-case
8166 // dispatcher-catalog byte-strings, empty, whitespace-padded,
8167 // quoted, English-rebrand candidates) inputs and asserts the
8168 // trait's `Result::ok()` projection byte-equals the method-named
8169 // resolver's `Option<Self>` return-shape on each, locking the two
8170 // paths together by construction so any future detour (a stray
8171 // `try_from` special-case that widens or narrows the accept-set
8172 // outside the paired `from_wire` resolver, an accidental swap
8173 // onto the kebab-case [`std::str::FromStr`] impl the
8174 // [`gen_platform::FromStrKind`] derive installs on the sibling
8175 // dispatcher-catalog axis) trips at caixa-core test time. Peer of
8176 // the sibling
8177 // [`crate::kind::tests::caixa_kind_try_from_str_and_from_wire_partition_the_accept_set`]
8178 // pin — extends the round-trip discipline onto the M2-OTP-shape
8179 // sibling-restart axis.
8180 let candidates: &[&str] = &[
8181 "OneForOne",
8182 "OneForAll",
8183 "RestForOne",
8184 "SimpleOneForOne",
8185 "",
8186 "one-for-one",
8187 "one-for-all",
8188 "rest-for-one",
8189 "simple-one-for-one",
8190 "oneforone",
8191 "unknown",
8192 "OneForOne ",
8193 " OneForOne",
8194 "\"OneForOne\"",
8195 "OneForEach",
8196 "?",
8197 ];
8198 for &input in candidates {
8199 let via_trait: Option<RestartStrategy> =
8200 <RestartStrategy as TryFrom<&str>>::try_from(input).ok();
8201 let via_method: Option<RestartStrategy> = RestartStrategy::from_wire(input);
8202 assert_eq!(
8203 via_trait, via_method,
8204 "TryFrom<&str> and from_wire must resolve identically on \
8205 input {input:?} — divergence signals the two reverse-\
8206 projection paths have drifted onto different accept-sets"
8207 );
8208 }
8209 }
8210
8211 #[test]
8212 fn restart_strategy_from_into_static_str_routes_through_as_str_accessor() {
8213 // Fail-before-pass-after byte-parity pin on the newly lifted
8214 // `impl From<RestartStrategy> for &'static str` — asserts the
8215 // standard-library trait impl and the substrate-primitive
8216 // [`RestartStrategy::as_str`] `pub const fn` accessor resolve to
8217 // the same four-arm emit-set across every arm the exhaustive
8218 // [`RestartStrategy::ALL`] slice enumerates. Any future silent
8219 // detour that routes the trait impl through a divergent
8220 // projection (a per-arm inline `match strategy { OneForOne =>
8221 // "OneForOne", … }` re-inlining that opens a compile-time link to
8222 // the un-lifted arm-literal, an accidental swap onto the sibling
8223 // kebab-case [`Self::discriminant`] dispatcher-catalog axis that
8224 // would collide the two-axis wire/catalog split the sibling
8225 // [`RestartStrategy::from_wire`] doc block makes load-bearing) trips
8226 // at caixa-core test time under `assert_eq!` rather than at a
8227 // downstream `impl Into<&'static str>`-bound consumer's silent
8228 // split. Sweeps every one of the four arms
8229 // [`RestartStrategy::ALL`] carries so no arm's projection is
8230 // covered only by the sibling method-named `as_str` /
8231 // [`std::fmt::Display`] / [`AsRef<str>`] paths. Materializes the
8232 // `<&'static str as From<RestartStrategy>>::from` output in a
8233 // `const`-shape binding to make the `'static` lifetime promise a
8234 // build-time invariant — a future accidental downgrade of any of
8235 // the four arms' [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
8236 // constants to a non-`&'static str` (a `String::leak()`-produced
8237 // return, a `Box::leak`-cast) trips at caixa-core build time
8238 // rather than at a downstream `'static`-bound consumer.
8239 const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
8240 const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
8241 const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
8242 const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
8243 for &variant in RestartStrategy::ALL {
8244 let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8245 let via_method: &'static str = variant.as_str();
8246 assert_eq!(
8247 via_trait, via_method,
8248 "From<RestartStrategy> for &'static str impl must round-trip \
8249 RestartStrategy::{variant:?} to the same lifted \
8250 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str returns — \
8251 divergence signals a silent detour off the substrate-primitive \
8252 accessor"
8253 );
8254 let via_into: &'static str = variant.into();
8255 assert_eq!(
8256 via_into, via_method,
8257 "Into<&'static str>::into on RestartStrategy::{variant:?} must \
8258 byte-equal RestartStrategy::as_str on the same input — the \
8259 blanket-derived Into shape must resolve to the same as_str \
8260 dispatch as the explicit From impl"
8261 );
8262 }
8263 assert_eq!(
8264 [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
8265 [
8266 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8267 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8268 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8269 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8270 ],
8271 "const-context RestartStrategy::as_str must resolve to the four \
8272 lifted SUPERVISOR_ESTRATEGIA_* consts — a future accidental \
8273 downgrade of any arm to a non-const or non-static byte-string \
8274 breaks the `&'static str`-lifetime promise the paired \
8275 From<RestartStrategy> for &'static str impl carries by \
8276 construction"
8277 );
8278 }
8279
8280 #[test]
8281 fn restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set() {
8282 // Cross-axis partition pin: the paired trait-idiomatic
8283 // `From<RestartStrategy> for &'static str` forward projection and
8284 // the method-named [`RestartStrategy::as_str`] forward projection
8285 // must resolve identically on *every* arm, not just the ones
8286 // named in the primary byte-parity pin above. Sweeps every
8287 // [`RestartStrategy::ALL`] arm and asserts the trait's `From::from`
8288 // output byte-equals the method-named accessor's return-value on
8289 // each, locking the two forward-projection paths together by
8290 // construction so any future detour (a stray `From` special-case
8291 // that lands on a divergent per-arm literal outside the paired
8292 // `as_str` dispatch, a hypothetical rebrand touching one axis
8293 // without the other) trips at caixa-core test time. Peer of the
8294 // sibling reverse-projection partition pin
8295 // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
8296 // — extends the round-trip discipline onto the trait-idiomatic
8297 // *forward* axis, closing the two-way `Self ↔ &'static str`
8298 // round-trip on the trait-idiomatic pair
8299 // (`From<Self> for &'static str` + `TryFrom<&str> for Self`) as
8300 // well as the pre-existing method-named pair
8301 // (`as_str` + `from_wire`).
8302 for &variant in RestartStrategy::ALL {
8303 let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8304 let via_method: &'static str = variant.as_str();
8305 assert_eq!(
8306 via_trait, via_method,
8307 "From<RestartStrategy> for &'static str and \
8308 RestartStrategy::as_str must resolve identically on \
8309 RestartStrategy::{variant:?} — divergence signals the \
8310 two forward-projection paths have drifted onto different \
8311 emit-sets"
8312 );
8313 }
8314 // Round-trip witness: every arm's forward `From` output re-parses
8315 // through the paired trait-idiomatic reverse `TryFrom<&str>` back
8316 // to the original variant. Closes the two-way `RestartStrategy ↔
8317 // &'static str` round-trip on the trait-idiomatic axis pair,
8318 // mirroring the pre-existing method-named `as_str` + `from_wire`
8319 // round-trip on the substrate-primitive axis pair.
8320 for &variant in RestartStrategy::ALL {
8321 let emitted: &'static str = variant.into();
8322 let re_parsed: Result<RestartStrategy, ()> =
8323 <RestartStrategy as TryFrom<&str>>::try_from(emitted);
8324 assert_eq!(
8325 re_parsed,
8326 Ok(variant),
8327 "trait-idiomatic axis pair must round-trip \
8328 RestartStrategy::{variant:?} through `.into::<&'static \
8329 str>()` and back through `TryFrom<&str>` — a break signals \
8330 the forward-emit and reverse-parse axes have drifted onto \
8331 different vocabularies"
8332 );
8333 }
8334 }
8335
8336 #[test]
8337 fn restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
8338 // Fail-before-pass-after byte-parity pin on the newly lifted
8339 // `impl From<&RestartStrategy> for &'static str` — asserts the
8340 // borrowed-input standard-library trait impl and the substrate-
8341 // primitive [`RestartStrategy::as_str`] `pub const fn` accessor
8342 // resolve to the same four-arm emit-set across every arm the
8343 // exhaustive [`RestartStrategy::ALL`] slice enumerates. Rust's
8344 // `From` trait does not auto-derive the borrowed-input sibling
8345 // from a paired owned-input impl (no `impl<T, U> From<&T> for U
8346 // where T: Copy, U: From<T>` blanket in `core`), so the
8347 // borrowed-input axis is a distinct trait-idiomatic surface
8348 // that a `.iter().map(Into::into)` shape over
8349 // [`RestartStrategy::ALL`] (whose iterator yields
8350 // `&RestartStrategy`, not `RestartStrategy`) reaches through
8351 // this impl and no other — the paired owned-input
8352 // [`From<RestartStrategy>`] impl requires an explicit
8353 // `.copied()` / dereference before the trait fires.
8354 // Materializes the `<&'static str as
8355 // From<&RestartStrategy>>::from` output in a `const`-shape
8356 // binding to make the `'static` lifetime promise a build-time
8357 // invariant.
8358 const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
8359 const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
8360 const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
8361 const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
8362 for variant in RestartStrategy::ALL {
8363 let via_trait: &'static str = <&'static str as From<&RestartStrategy>>::from(variant);
8364 let via_method: &'static str = variant.as_str();
8365 assert_eq!(
8366 via_trait, via_method,
8367 "From<&RestartStrategy> for &'static str impl must \
8368 round-trip &RestartStrategy::{variant:?} to the same \
8369 lifted SUPERVISOR_ESTRATEGIA_* const \
8370 RestartStrategy::as_str returns — divergence signals a \
8371 silent detour off the substrate-primitive accessor"
8372 );
8373 let via_into: &'static str = variant.into();
8374 assert_eq!(
8375 via_into, via_method,
8376 "Into<&'static str>::into on &RestartStrategy::{variant:?} \
8377 must byte-equal RestartStrategy::as_str on the same input — \
8378 the blanket-derived Into shape must resolve to the same \
8379 as_str dispatch as the explicit From impl"
8380 );
8381 }
8382 assert_eq!(
8383 [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
8384 [
8385 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8386 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8387 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8388 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8389 ],
8390 "const-context RestartStrategy::as_str must resolve to the \
8391 four lifted SUPERVISOR_ESTRATEGIA_* consts — the borrowed-\
8392 input From<&RestartStrategy> for &'static str impl inherits \
8393 its `'static` lifetime promise from the same accessor the \
8394 owned-input sibling routes through"
8395 );
8396 }
8397
8398 #[test]
8399 fn restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
8400 // Cross-axis partition pin: the paired trait-idiomatic
8401 // owned-input `From<RestartStrategy> for &'static str` (523157d
8402 // campaign-shape) and borrowed-input `From<&RestartStrategy> for
8403 // &'static str` (this lift) forward projections must resolve
8404 // identically on every arm, locking the two input-shape paths
8405 // together so any future detour trips at caixa-core test time.
8406 // Then a witness that a `.iter().map(Into::into)` pipe over
8407 // [`RestartStrategy::ALL`] (whose iterator yields
8408 // `&RestartStrategy`) materializes the four-arm accept-set
8409 // through the borrowed-input axis alone — the exact shape a
8410 // future wasm-operator per-supervisor sibling-restart-strategy
8411 // diagnostic line, a future substrate-wide per-arm diagnostic
8412 // column, or a
8413 // `HashMap::<&'static str, RestartStrategy>::from_iter(
8414 // RestartStrategy::ALL.iter().map(|s| (s.into(), *s)))`-style
8415 // per-strategy lookup reaches through — closing the two-way
8416 // owned/borrowed input-shape symmetry on the forward-projection
8417 // trait-idiomatic axis. Peer of the sibling
8418 // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8419 // (64aa742) /
8420 // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8421 // (5ab993a) /
8422 // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8423 // (807b0b5) partition pins on the sibling closed-set typed-enum
8424 // discriminator axes — extends the borrowed-input axis
8425 // discipline onto the first M2 OTP-shape sibling-restart
8426 // closed-set typed enum on the caixa surface. Also closes the
8427 // direct two-way `&Self → &'static str → Self` round-trip via
8428 // the paired [`TryFrom<&str>`] axis — unlike the peer
8429 // [`crate::CaixaKind`] axis pair (whose forward `From` emits
8430 // lowercase Portuguese diagnostic bytes while the reverse
8431 // `TryFrom` parses `PascalCase` wire bytes, forcing the round-
8432 // trip through an intermediate wire-vocab hop), the
8433 // [`RestartStrategy::as_str`] emit and
8434 // [`RestartStrategy::from_wire`] parse share the same
8435 // `PascalCase` vocabulary by construction, so the borrowed-
8436 // input forward axis and the reverse axis compose directly.
8437 for &variant in RestartStrategy::ALL {
8438 let owned: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8439 let borrowed: &'static str = <&'static str as From<&RestartStrategy>>::from(&variant);
8440 assert_eq!(
8441 owned, borrowed,
8442 "From<RestartStrategy> and From<&RestartStrategy> for \
8443 &'static str must resolve identically on \
8444 RestartStrategy::{variant:?} — divergence signals the \
8445 owned-input and borrowed-input forward-projection paths \
8446 have drifted onto different emit-sets"
8447 );
8448 }
8449 let via_iter: Vec<&'static str> = RestartStrategy::ALL.iter().map(Into::into).collect();
8450 let via_method: Vec<&'static str> =
8451 RestartStrategy::ALL.iter().map(|s| s.as_str()).collect();
8452 assert_eq!(
8453 via_iter, via_method,
8454 "`.iter().map(Into::into)` over RestartStrategy::ALL must \
8455 byte-equal `.iter().map(|s| s.as_str())` on every arm — the \
8456 borrowed-input `From<&RestartStrategy> for &'static str` \
8457 axis is what makes the `.iter().map(Into::into)` shape route \
8458 through the substrate-primitive `RestartStrategy::as_str` \
8459 accessor rather than through a per-call-site `.copied()` / \
8460 dereference detour"
8461 );
8462 for variant in RestartStrategy::ALL {
8463 let emitted: &'static str = variant.into();
8464 let re_parsed: Result<RestartStrategy, ()> =
8465 <RestartStrategy as TryFrom<&str>>::try_from(emitted);
8466 assert_eq!(
8467 re_parsed,
8468 Ok(*variant),
8469 "trait-idiomatic borrowed-input forward-projection + \
8470 reverse-projection axis pair must round-trip \
8471 &RestartStrategy::{variant:?} through `.into::<&'static \
8472 str>()` (via the borrowed-input axis) and back through \
8473 `TryFrom<&str>` — a break signals the borrowed-input \
8474 forward-emit and reverse-parse axes have drifted onto \
8475 different vocabularies"
8476 );
8477 }
8478 }
8479
8480 #[test]
8481 fn restart_strategy_from_into_owned_string_routes_through_as_str_accessor() {
8482 // Fail-before-pass-after byte-parity pin on the newly lifted
8483 // `impl From<RestartStrategy> for String` — asserts the
8484 // owned-`String`-returning standard-library trait impl and the
8485 // substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
8486 // accessor resolve to the same four-arm emit-set across every
8487 // arm the exhaustive [`RestartStrategy::ALL`] slice enumerates.
8488 // Rust's standard library does not carry a blanket
8489 // `impl<T: AsRef<str>> From<T> for String` (nor an
8490 // `impl<T: fmt::Display> From<T> for String`), so the
8491 // owned-`String` forward-projection axis is a distinct
8492 // trait-idiomatic surface that a
8493 // `let key: String = strategy.into();`-shaped call site
8494 // reaches through this impl and no other — the paired sibling
8495 // `From<RestartStrategy> for &'static str` impl forces every
8496 // owned-`String` call site through an explicit
8497 // `.to_owned()` / `String::from` restatement.
8498 for &variant in RestartStrategy::ALL {
8499 let via_trait: String = <String as From<RestartStrategy>>::from(variant);
8500 let via_method: &'static str = variant.as_str();
8501 assert_eq!(
8502 via_trait.as_str(),
8503 via_method,
8504 "From<RestartStrategy> for String impl must round-trip \
8505 RestartStrategy::{variant:?} to the same lifted \
8506 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
8507 returns — divergence signals a silent detour off the \
8508 substrate-primitive accessor"
8509 );
8510 let via_into: String = variant.into();
8511 assert_eq!(
8512 via_into.as_str(),
8513 via_method,
8514 "Into<String>::into on RestartStrategy::{variant:?} must \
8515 byte-equal RestartStrategy::as_str on the same input — the \
8516 blanket-derived Into shape must resolve to the same as_str \
8517 dispatch as the explicit From impl"
8518 );
8519 }
8520 }
8521
8522 #[test]
8523 fn restart_strategy_from_into_owned_string_and_static_str_agree_on_every_arm() {
8524 // Cross-axis partition pin: the paired trait-idiomatic
8525 // owned-`String` `From<RestartStrategy> for String` (this lift)
8526 // and owned-`&'static str` `From<RestartStrategy> for &'static
8527 // str` (523157d) forward projections must resolve identically
8528 // on every arm, locking the two return-type-shape paths
8529 // together so any future detour trips at caixa-core test time.
8530 // Also byte-parity witness against the sibling
8531 // [`ToString::to_string`] surface routed through
8532 // [`std::fmt::Display`] — the three owned-heap-string paths
8533 // (`.into::<String>()`, `String::from`, `.to_string()`) must
8534 // resolve identically on every arm so a future consumer that
8535 // picks any of the three lands on the same lifted
8536 // SUPERVISOR_ESTRATEGIA_* const. Then a direct round-trip
8537 // witness through the paired trait-idiomatic reverse
8538 // [`TryFrom<&str>`] axis on the owned-`String`'s
8539 // [`String::as_str`] borrow that closes the two-way
8540 // `Self → String → Self` round-trip on the trait-idiomatic
8541 // owned-`String` forward + reverse axis pair.
8542 for &variant in RestartStrategy::ALL {
8543 let owned_string: String = <String as From<RestartStrategy>>::from(variant);
8544 let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8545 assert_eq!(
8546 owned_string.as_str(),
8547 owned_static,
8548 "From<RestartStrategy> for String and From<RestartStrategy> \
8549 for &'static str must resolve identically on \
8550 RestartStrategy::{variant:?} — divergence signals the \
8551 owned-`String` and owned-`&'static str` forward-projection \
8552 return-type-shape paths have drifted onto different \
8553 emit-sets"
8554 );
8555 let via_to_string: String = variant.to_string();
8556 assert_eq!(
8557 owned_string, via_to_string,
8558 "From<RestartStrategy> for String must byte-equal \
8559 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
8560 divergence signals the trait-idiomatic owned-`String` \
8561 forward-projection axis and the ToString-through-Display \
8562 axis have drifted onto different emit-sets"
8563 );
8564 }
8565 let via_iter: Vec<String> = RestartStrategy::ALL
8566 .iter()
8567 .copied()
8568 .map(String::from)
8569 .collect();
8570 let via_method: Vec<String> = RestartStrategy::ALL
8571 .iter()
8572 .map(|s| s.as_str().to_owned())
8573 .collect();
8574 assert_eq!(
8575 via_iter, via_method,
8576 "`.iter().copied().map(String::from)` over RestartStrategy::ALL \
8577 must byte-equal `.iter().map(|s| s.as_str().to_owned())` on \
8578 every arm — the owned-`String` `From<RestartStrategy> for \
8579 String` axis is what makes the `String::from` composition \
8580 route through the substrate-primitive `RestartStrategy::as_str` \
8581 accessor rather than through a per-call-site `.to_owned()` / \
8582 `String::from(strategy.as_str())` detour"
8583 );
8584 for &variant in RestartStrategy::ALL {
8585 let emitted: String = variant.into();
8586 let re_parsed: Result<RestartStrategy, ()> =
8587 <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
8588 assert_eq!(
8589 re_parsed,
8590 Ok(variant),
8591 "trait-idiomatic owned-`String` forward-projection + \
8592 reverse-projection axis pair must round-trip \
8593 RestartStrategy::{variant:?} through `.into::<String>()` \
8594 and back through `TryFrom<&str>` on the owned-`String`'s \
8595 String::as_str borrow — a break signals the owned-`String` \
8596 forward-emit and reverse-parse axes have drifted onto \
8597 different vocabularies"
8598 );
8599 }
8600 }
8601
8602 #[test]
8603 fn restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
8604 // Fail-before-pass-after byte-parity pin on the newly lifted
8605 // `impl From<&RestartStrategy> for String` — asserts the
8606 // borrowed-input owned-`String`-returning standard-library trait
8607 // impl and the substrate-primitive [`RestartStrategy::as_str`]
8608 // `pub const fn` accessor resolve to the same four-arm emit-set
8609 // across every arm the exhaustive [`RestartStrategy::ALL`] slice
8610 // enumerates. Rust's standard library does not carry a blanket
8611 // `impl<T: AsRef<str>> From<&T> for String` (nor an
8612 // `impl<T: fmt::Display> From<&T> for String`), so the
8613 // borrowed-input owned-`String` forward-projection axis is a
8614 // distinct trait-idiomatic surface that a
8615 // `let key: String = (&strategy).into();`-shaped call site
8616 // reaches through this impl and no other — the paired sibling
8617 // `From<RestartStrategy> for String` impl forces every
8618 // borrowed-input call site through an explicit `Copy` deref
8619 // (`String::from(*strategy)`) or an `.as_str().to_owned()` /
8620 // `.to_string()` detour.
8621 for &variant in RestartStrategy::ALL {
8622 let via_trait: String = <String as From<&RestartStrategy>>::from(&variant);
8623 let via_method: &'static str = variant.as_str();
8624 assert_eq!(
8625 via_trait.as_str(),
8626 via_method,
8627 "From<&RestartStrategy> for String impl must round-trip \
8628 &RestartStrategy::{variant:?} to the same lifted \
8629 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
8630 returns — divergence signals a silent detour off the \
8631 substrate-primitive accessor"
8632 );
8633 let via_into: String = (&variant).into();
8634 assert_eq!(
8635 via_into.as_str(),
8636 via_method,
8637 "Into<String>::into on &RestartStrategy::{variant:?} must \
8638 byte-equal RestartStrategy::as_str on the same input — the \
8639 blanket-derived Into shape must resolve to the same as_str \
8640 dispatch as the explicit From impl"
8641 );
8642 }
8643 }
8644
8645 #[test]
8646 fn restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
8647 // Cross-axis partition pin: the newly lifted trait-idiomatic
8648 // borrowed-input owned-`String` `From<&RestartStrategy> for
8649 // String` (this lift), the paired owned-input owned-`String`
8650 // `From<RestartStrategy> for String` (7baa18a), the paired
8651 // borrowed-input owned-`&'static str` `From<&RestartStrategy>
8652 // for &'static str` (e941836), and the paired owned-input
8653 // owned-`&'static str` `From<RestartStrategy> for &'static str`
8654 // (523157d) — every corner of the `{Self, &Self} × {&'static
8655 // str, String}` 2×2 trait-idiomatic projection family — must
8656 // resolve identically on every arm, locking the four
8657 // return-shape × input-shape paths together so any future
8658 // detour trips at caixa-core test time. Also byte-parity
8659 // witness against the sibling [`ToString::to_string`] surface
8660 // routed through [`std::fmt::Display`] and a direct round-trip
8661 // witness through the paired trait-idiomatic reverse
8662 // [`TryFrom<&str>`] axis on the owned-`String`'s
8663 // [`String::as_str`] borrow that closes the two-way
8664 // `&Self → String → Self` round-trip on the trait-idiomatic
8665 // borrowed-input owned-`String` forward + reverse axis pair.
8666 for &variant in RestartStrategy::ALL {
8667 let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
8668 let owned_string: String = <String as From<RestartStrategy>>::from(variant);
8669 let borrowed_static: &'static str =
8670 <&'static str as From<&RestartStrategy>>::from(&variant);
8671 let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8672 assert_eq!(
8673 borrowed_string, owned_string,
8674 "From<&RestartStrategy> for String and From<RestartStrategy> \
8675 for String must resolve identically on \
8676 RestartStrategy::{variant:?} — divergence signals the \
8677 borrowed-input and owned-input owned-`String` \
8678 forward-projection input-shape paths have drifted onto \
8679 different emit-sets"
8680 );
8681 assert_eq!(
8682 borrowed_string.as_str(),
8683 borrowed_static,
8684 "From<&RestartStrategy> for String and From<&RestartStrategy> \
8685 for &'static str must resolve identically on \
8686 RestartStrategy::{variant:?} — divergence signals the \
8687 borrowed-input `&'static str` and owned-`String` \
8688 return-shape paths have drifted onto different emit-sets"
8689 );
8690 assert_eq!(
8691 borrowed_string.as_str(),
8692 owned_static,
8693 "From<&RestartStrategy> for String and From<RestartStrategy> \
8694 for &'static str must resolve identically on \
8695 RestartStrategy::{variant:?} — divergence signals a break \
8696 in the diagonal corner of the {{Self, &Self}} × \
8697 {{&'static str, String}} 2×2 trait-idiomatic \
8698 projection family"
8699 );
8700 let via_to_string: String = variant.to_string();
8701 assert_eq!(
8702 borrowed_string, via_to_string,
8703 "From<&RestartStrategy> for String must byte-equal \
8704 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
8705 divergence signals the trait-idiomatic borrowed-input \
8706 owned-`String` forward-projection axis and the \
8707 ToString-through-Display axis have drifted onto different \
8708 emit-sets"
8709 );
8710 }
8711 let via_iter: Vec<String> = RestartStrategy::ALL.iter().map(String::from).collect();
8712 let via_method: Vec<String> = RestartStrategy::ALL
8713 .iter()
8714 .map(|s| s.as_str().to_owned())
8715 .collect();
8716 assert_eq!(
8717 via_iter, via_method,
8718 "`.iter().map(String::from)` over RestartStrategy::ALL — a \
8719 call site whose iteration axis holds `&RestartStrategy` by \
8720 construction — must byte-equal `.iter().map(|s| \
8721 s.as_str().to_owned())` on every arm — the borrowed-input \
8722 owned-`String` `From<&RestartStrategy> for String` axis is \
8723 what makes the `String::from` composition route through the \
8724 substrate-primitive `RestartStrategy::as_str` accessor \
8725 without a spurious `Copy` deref (which would only be \
8726 reachable through the owned-input `From<RestartStrategy> for \
8727 String` axis by first calling `.copied()` on the iterator)"
8728 );
8729 for &variant in RestartStrategy::ALL {
8730 let emitted: String = (&variant).into();
8731 let re_parsed: Result<RestartStrategy, ()> =
8732 <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
8733 assert_eq!(
8734 re_parsed,
8735 Ok(variant),
8736 "trait-idiomatic borrowed-input owned-`String` \
8737 forward-projection + reverse-projection axis pair must \
8738 round-trip &RestartStrategy::{variant:?} through \
8739 `.into::<String>()` on the borrowed-input surface and \
8740 back through `TryFrom<&str>` on the owned-`String`'s \
8741 String::as_str borrow — a break signals the \
8742 borrowed-input owned-`String` forward-emit and \
8743 reverse-parse axes have drifted onto different \
8744 vocabularies"
8745 );
8746 }
8747 }
8748
8749 #[test]
8750 fn restart_strategy_from_into_static_cow_str_routes_through_as_str_accessor() {
8751 // Fail-before-pass-after byte-parity pin on the newly lifted
8752 // `impl From<RestartStrategy> for std::borrow::Cow<'static, str>` —
8753 // asserts the standard-library trait impl and the substrate-
8754 // primitive [`super::RestartStrategy::as_str`] `pub const fn`
8755 // accessor resolve to the same four-arm emit-set across every
8756 // arm the exhaustive [`super::RestartStrategy::ALL`] slice
8757 // enumerates. Rust's standard library does not carry a blanket
8758 // `impl<T: AsRef<str>> From<T> for Cow<'static, str>` (nor an
8759 // `impl<T: fmt::Display> From<T> for Cow<'static, str>`), so
8760 // the `Cow<'static, str>` forward-projection axis is a
8761 // distinct trait-idiomatic surface that a
8762 // `let key: Cow<'static, str> = strategy.into();`-shaped call
8763 // site reaches through this impl and no other — the paired
8764 // sibling `From<RestartStrategy> for &'static str` and
8765 // `From<RestartStrategy> for String` impls force every
8766 // `Cow<'static, str>`-parameterized call site through a
8767 // `Cow::Borrowed(strategy.as_str())` /
8768 // `Cow::Owned(strategy.to_string())` composition whose type
8769 // bounds have no compile-time link back to the substrate
8770 // primitive.
8771 //
8772 // Also asserts the projection lands on the zero-alloc
8773 // [`std::borrow::Cow::Borrowed`] arm (not the
8774 // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
8775 // [`super::RestartStrategy::as_str`] accessor's `&'static str`
8776 // return lifetime by construction makes the borrowed arm the
8777 // type-correct projection with no runtime allocation. Any
8778 // future silent detour that routes the impl through the owned
8779 // arm (an accidental `Cow::Owned(strategy.to_string())` rewrite
8780 // that would allocate on every call site where the
8781 // `&'static str` return of [`super::RestartStrategy::as_str`]
8782 // makes the zero-alloc borrowed projection type-correct) trips
8783 // at caixa-core test time under the
8784 // [`std::borrow::Cow::Borrowed`] discriminator witness rather
8785 // than at a downstream `Cow<'static, str>`-bound consumer's
8786 // silent allocation.
8787 //
8788 // First peer on the substrate-wide trait-idiomatic
8789 // [`std::borrow::Cow<'static, str>`] forward-projection family
8790 // to extend the axis off the top-level [`super::CaixaKind`]
8791 // enum (99c1735 owned-input, d45c409 borrowed-input) onto the
8792 // first M2 OTP-shape closed-set fieldless typed enum on the
8793 // caixa surface.
8794 for &variant in RestartStrategy::ALL {
8795 let via_trait: std::borrow::Cow<'static, str> =
8796 <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
8797 let via_method: &'static str = variant.as_str();
8798 assert_eq!(
8799 via_trait.as_ref(),
8800 via_method,
8801 "From<RestartStrategy> for Cow<'static, str> impl must \
8802 round-trip RestartStrategy::{variant:?} to the same \
8803 lifted SUPERVISOR_ESTRATEGIA_* const \
8804 RestartStrategy::as_str returns — divergence signals a \
8805 silent detour off the substrate-primitive accessor"
8806 );
8807 assert!(
8808 matches!(via_trait, std::borrow::Cow::Borrowed(_)),
8809 "From<RestartStrategy> for Cow<'static, str> impl must \
8810 land on the zero-alloc Cow::Borrowed arm on \
8811 RestartStrategy::{variant:?} — a Cow::Owned outcome \
8812 signals the projection has silently allocated where \
8813 the substrate-primitive RestartStrategy::as_str \
8814 `&'static str` return makes the borrowed arm the \
8815 type-correct projection"
8816 );
8817 let via_into: std::borrow::Cow<'static, str> = variant.into();
8818 assert_eq!(
8819 via_into.as_ref(),
8820 via_method,
8821 "Into<Cow<'static, str>>::into on \
8822 RestartStrategy::{variant:?} must byte-equal \
8823 RestartStrategy::as_str on the same input — the \
8824 blanket-derived Into shape must resolve to the same \
8825 as_str dispatch as the explicit From impl"
8826 );
8827 assert!(
8828 matches!(via_into, std::borrow::Cow::Borrowed(_)),
8829 "Into<Cow<'static, str>>::into on \
8830 RestartStrategy::{variant:?} must land on the \
8831 zero-alloc Cow::Borrowed arm — the blanket-derived \
8832 Into shape must resolve to the same Cow::Borrowed \
8833 dispatch as the explicit From impl"
8834 );
8835 }
8836 }
8837
8838 #[test]
8839 fn restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
8840 // Cross-axis partition pin: the newly lifted trait-idiomatic
8841 // `From<RestartStrategy> for std::borrow::Cow<'static, str>`
8842 // (this lift), the paired owned-input `From<RestartStrategy>
8843 // for &'static str` (523157d), and the paired owned-input
8844 // `From<RestartStrategy> for String` (7baa18a) forward
8845 // projections must resolve identically on every arm, locking
8846 // the three return-shape paths together by construction so any
8847 // future detour trips at caixa-core test time. Also byte-parity
8848 // witness against the sibling [`ToString::to_string`] surface
8849 // routed through [`std::fmt::Display`] — every owned-heap-
8850 // string path (the `Cow::Owned` promotion of this axis's
8851 // `.into_owned()`, `From<RestartStrategy> for String`, and
8852 // `.to_string()`) resolves to the same lifted
8853 // [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const per arm.
8854 //
8855 // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
8856 // witness over [`super::RestartStrategy::ALL`] that
8857 // materializes the four-arm accept-set through the
8858 // [`std::borrow::Cow<'static, str>`] axis alone — the exact
8859 // shape a future `axum::response::IntoResponse` per-strategy
8860 // rejection-body composer, a future M4 admission-webhook
8861 // per-strategy rejection-reason emitter whose typing rules out
8862 // the sibling [`AsRef<str>`] borrowed return, or a future
8863 // substrate-wide per-strategy diagnostic surface that binds
8864 // through a [`Cow<'static, str>`] boundary reaches through.
8865 // The pipe witness also pins the zero-alloc discipline: every
8866 // element in the collected vector satisfies the
8867 // [`std::borrow::Cow::Borrowed`] arm predicate, so a future
8868 // accidental silent-allocation regression on the pipe's
8869 // iteration axis is a caixa-core-test-time failure.
8870 for &variant in RestartStrategy::ALL {
8871 let via_cow: std::borrow::Cow<'static, str> =
8872 <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
8873 let via_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8874 let via_string: String = <String as From<RestartStrategy>>::from(variant);
8875 assert_eq!(
8876 via_cow.as_ref(),
8877 via_static,
8878 "From<RestartStrategy> for Cow<'static, str> and \
8879 From<RestartStrategy> for &'static str must resolve \
8880 identically on RestartStrategy::{variant:?} — \
8881 divergence signals the Cow<'static, str> and \
8882 &'static str return-shape paths have drifted onto \
8883 different emit-sets"
8884 );
8885 assert_eq!(
8886 via_cow.as_ref(),
8887 via_string.as_str(),
8888 "From<RestartStrategy> for Cow<'static, str> and \
8889 From<RestartStrategy> for String must resolve \
8890 identically on RestartStrategy::{variant:?} — \
8891 divergence signals the Cow<'static, str> and String \
8892 return-shape paths have drifted onto different \
8893 emit-sets"
8894 );
8895 let via_to_string: String = variant.to_string();
8896 assert_eq!(
8897 via_cow.as_ref(),
8898 via_to_string.as_str(),
8899 "From<RestartStrategy> for Cow<'static, str> must \
8900 byte-equal RestartStrategy::to_string on \
8901 RestartStrategy::{variant:?} — divergence signals the \
8902 trait-idiomatic Cow<'static, str> forward-projection \
8903 axis and the ToString-through-Display axis have \
8904 drifted onto different emit-sets"
8905 );
8906 }
8907 let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
8908 .iter()
8909 .copied()
8910 .map(std::borrow::Cow::from)
8911 .collect();
8912 let via_method: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
8913 .iter()
8914 .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
8915 .collect();
8916 assert_eq!(
8917 via_iter, via_method,
8918 "`.iter().copied().map(Cow::from)` over \
8919 RestartStrategy::ALL must byte-equal `.iter().map(|s| \
8920 Cow::Borrowed(s.as_str()))` on every arm — the \
8921 trait-idiomatic `From<RestartStrategy> for Cow<'static, \
8922 str>` axis is what makes the `Cow::from` composition \
8923 route through the substrate-primitive \
8924 `RestartStrategy::as_str` accessor with the zero-alloc \
8925 Cow::Borrowed arm by construction, rather than a \
8926 per-call-site `Cow::Owned(strategy.to_string())` \
8927 allocation"
8928 );
8929 for cow in &via_iter {
8930 assert!(
8931 matches!(cow, std::borrow::Cow::Borrowed(_)),
8932 "every element of the \
8933 .iter().copied().map(Cow::from) pipe over \
8934 RestartStrategy::ALL must land on the zero-alloc \
8935 Cow::Borrowed arm — a Cow::Owned outcome on any arm \
8936 signals the pipe's iteration axis has silently \
8937 allocated where the substrate-primitive \
8938 RestartStrategy::as_str `&'static str` return makes \
8939 the borrowed arm the type-correct projection"
8940 );
8941 }
8942 }
8943
8944 #[test]
8945 fn restart_strategy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
8946 // Fail-before-pass-after byte-parity pin on the newly lifted
8947 // `impl From<&RestartStrategy> for std::borrow::Cow<'static, str>` —
8948 // asserts the borrowed-input standard-library trait impl and
8949 // the substrate-primitive [`super::RestartStrategy::as_str`]
8950 // `pub const fn` accessor resolve to the same four-arm emit-
8951 // set across every arm the exhaustive
8952 // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
8953 // standard library does not carry a blanket
8954 // `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor a
8955 // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
8956 // the borrowed-input `Cow<'static, str>` forward-projection
8957 // axis is a distinct trait-idiomatic surface that a
8958 // `let key: Cow<'static, str> = (&strategy).into();`-shaped
8959 // call site or a
8960 // `RestartStrategy::ALL.iter().map(Cow::from)`-shaped pipe
8961 // reaches through this impl and no other — the paired owned-
8962 // input `From<RestartStrategy> for Cow<'static, str>` impl
8963 // (7dd28b3) forces every borrowed-input call site through an
8964 // explicit `Copy` deref (`Cow::from(*strategy)`) or a
8965 // `Cow::Borrowed(strategy.as_str())` open-code whose type
8966 // bounds have no compile-time link back to the substrate
8967 // primitive.
8968 //
8969 // Also asserts the projection lands on the zero-alloc
8970 // [`std::borrow::Cow::Borrowed`] arm (not the
8971 // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
8972 // [`super::RestartStrategy::as_str`] accessor's `&'static str`
8973 // return lifetime by construction makes the borrowed arm the
8974 // type-correct projection with no runtime allocation on the
8975 // borrowed-input surface just as on the paired owned-input
8976 // surface.
8977 //
8978 // Second peer on the substrate-wide trait-idiomatic
8979 // [`std::borrow::Cow<'static, str>`] forward-projection family
8980 // on this enum — closes the `{Self, &Self}` input-shape
8981 // corner of the [`Cow<'static, str>`] axis on the first M2
8982 // OTP-shape closed-set fieldless typed enum peer on the caixa
8983 // surface (`:supervisor :estrategia`), exactly as d45c409
8984 // closed it on the top-level [`super::CaixaKind`] one commit
8985 // after the owning half (99c1735) landed. Every future
8986 // closed-set fieldless typed enum peer on the substrate is a
8987 // future target of the campaign.
8988 for &variant in RestartStrategy::ALL {
8989 let via_trait: std::borrow::Cow<'static, str> =
8990 <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
8991 let via_method: &'static str = variant.as_str();
8992 assert_eq!(
8993 via_trait.as_ref(),
8994 via_method,
8995 "From<&RestartStrategy> for Cow<'static, str> impl must \
8996 round-trip &RestartStrategy::{variant:?} to the same \
8997 lifted SUPERVISOR_ESTRATEGIA_* const \
8998 RestartStrategy::as_str returns — divergence signals a \
8999 silent detour off the substrate-primitive accessor"
9000 );
9001 assert!(
9002 matches!(via_trait, std::borrow::Cow::Borrowed(_)),
9003 "From<&RestartStrategy> for Cow<'static, str> impl must \
9004 land on the zero-alloc Cow::Borrowed arm on \
9005 &RestartStrategy::{variant:?} — a Cow::Owned outcome \
9006 signals the projection has silently allocated where \
9007 the substrate-primitive RestartStrategy::as_str \
9008 `&'static str` return makes the borrowed arm the \
9009 type-correct projection"
9010 );
9011 let via_into: std::borrow::Cow<'static, str> = (&variant).into();
9012 assert_eq!(
9013 via_into.as_ref(),
9014 via_method,
9015 "Into<Cow<'static, str>>::into on \
9016 &RestartStrategy::{variant:?} must byte-equal \
9017 RestartStrategy::as_str on the same input — the \
9018 blanket-derived Into shape must resolve to the same \
9019 as_str dispatch as the explicit From impl"
9020 );
9021 assert!(
9022 matches!(via_into, std::borrow::Cow::Borrowed(_)),
9023 "Into<Cow<'static, str>>::into on \
9024 &RestartStrategy::{variant:?} must land on the \
9025 zero-alloc Cow::Borrowed arm — the blanket-derived \
9026 Into shape must resolve to the same Cow::Borrowed \
9027 dispatch as the explicit From impl"
9028 );
9029 }
9030 }
9031
9032 #[test]
9033 fn restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
9034 // Cross-axis partition pin: the newly lifted trait-idiomatic
9035 // borrowed-input `From<&RestartStrategy> for
9036 // std::borrow::Cow<'static, str>` (this lift), the paired
9037 // owned-input `From<RestartStrategy> for
9038 // std::borrow::Cow<'static, str>` (7dd28b3), the paired
9039 // borrowed-input owned-`&'static str` `From<&RestartStrategy>
9040 // for &'static str`, and the paired borrowed-input owned-
9041 // `String` `From<&RestartStrategy> for String` must resolve
9042 // identically on every arm, locking the four
9043 // return-shape × input-shape paths together by construction so
9044 // any future detour trips at caixa-core test time. Also byte-
9045 // parity witness against the sibling [`ToString::to_string`]
9046 // surface routed through [`std::fmt::Display`] — every owned-
9047 // heap-string path (this axis's `.into_owned()` promotion, the
9048 // paired [`From<&RestartStrategy> for String`], and
9049 // `.to_string()`) resolves to the same lifted
9050 // [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const per arm.
9051 //
9052 // Then a `.iter().map(std::borrow::Cow::from)` pipe witness
9053 // over [`super::RestartStrategy::ALL`] — whose iterator yields
9054 // `&RestartStrategy` by construction, so the borrowed-input
9055 // [`Cow<'static, str>`] axis is what routes the pipe through
9056 // the substrate-primitive [`super::RestartStrategy::as_str`]
9057 // accessor without a spurious [`Copy`] deref (which would only
9058 // be reachable through the owned-input
9059 // [`From<RestartStrategy> for Cow<'static, str>`] axis by
9060 // first calling `.copied()` on the iterator). The pipe witness
9061 // also pins the zero-alloc discipline: every element in the
9062 // collected vector satisfies the [`std::borrow::Cow::Borrowed`]
9063 // arm predicate, so a future accidental silent-allocation
9064 // regression on the pipe's iteration axis is a caixa-core-
9065 // test-time failure.
9066 for &strategy in RestartStrategy::ALL {
9067 let borrowed_cow: std::borrow::Cow<'static, str> =
9068 <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&strategy);
9069 let owned_cow: std::borrow::Cow<'static, str> =
9070 <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(strategy);
9071 let borrowed_static: &'static str =
9072 <&'static str as From<&RestartStrategy>>::from(&strategy);
9073 let borrowed_string: String = <String as From<&RestartStrategy>>::from(&strategy);
9074 assert_eq!(
9075 borrowed_cow, owned_cow,
9076 "From<&RestartStrategy> for Cow<'static, str> and \
9077 From<RestartStrategy> for Cow<'static, str> must \
9078 resolve identically on RestartStrategy::{strategy:?} — \
9079 divergence signals the borrowed-input and owned-input \
9080 Cow<'static, str> forward-projection input-shape \
9081 paths have drifted onto different emit-sets"
9082 );
9083 assert_eq!(
9084 borrowed_cow.as_ref(),
9085 borrowed_static,
9086 "From<&RestartStrategy> for Cow<'static, str> and \
9087 From<&RestartStrategy> for &'static str must resolve \
9088 identically on RestartStrategy::{strategy:?} — \
9089 divergence signals the borrowed-input Cow<'static, \
9090 str> and &'static str return-shape paths have drifted \
9091 onto different emit-sets"
9092 );
9093 assert_eq!(
9094 borrowed_cow.as_ref(),
9095 borrowed_string.as_str(),
9096 "From<&RestartStrategy> for Cow<'static, str> and \
9097 From<&RestartStrategy> for String must resolve \
9098 identically on RestartStrategy::{strategy:?} — \
9099 divergence signals the borrowed-input Cow<'static, \
9100 str> and owned-`String` return-shape paths have \
9101 drifted onto different emit-sets"
9102 );
9103 let via_to_string: String = strategy.to_string();
9104 assert_eq!(
9105 borrowed_cow.as_ref(),
9106 via_to_string.as_str(),
9107 "From<&RestartStrategy> for Cow<'static, str> must \
9108 byte-equal RestartStrategy::to_string on \
9109 RestartStrategy::{strategy:?} — divergence signals \
9110 the trait-idiomatic borrowed-input Cow<'static, str> \
9111 forward-projection axis and the ToString-through-\
9112 Display axis have drifted onto different emit-sets"
9113 );
9114 }
9115 let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
9116 .iter()
9117 .map(std::borrow::Cow::from)
9118 .collect();
9119 let via_method: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
9120 .iter()
9121 .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
9122 .collect();
9123 assert_eq!(
9124 via_iter, via_method,
9125 "`.iter().map(Cow::from)` over RestartStrategy::ALL — a \
9126 call site whose iteration axis holds `&RestartStrategy` \
9127 by construction — must byte-equal `.iter().map(|s| \
9128 Cow::Borrowed(s.as_str()))` on every arm — the borrowed-\
9129 input Cow<'static, str> `From<&RestartStrategy> for \
9130 Cow<'static, str>` axis is what makes the `Cow::from` \
9131 composition route through the substrate-primitive \
9132 `RestartStrategy::as_str` accessor with the zero-alloc \
9133 Cow::Borrowed arm by construction and without a spurious \
9134 `Copy` deref (which would only be reachable through the \
9135 owned-input `From<RestartStrategy> for Cow<'static, str>` \
9136 axis by first calling `.copied()` on the iterator)"
9137 );
9138 for cow in &via_iter {
9139 assert!(
9140 matches!(cow, std::borrow::Cow::Borrowed(_)),
9141 "every element of the .iter().map(Cow::from) pipe \
9142 over RestartStrategy::ALL must land on the zero-\
9143 alloc Cow::Borrowed arm — a Cow::Owned outcome on \
9144 any arm signals the pipe's iteration axis has \
9145 silently allocated where the substrate-primitive \
9146 RestartStrategy::as_str `&'static str` return makes \
9147 the borrowed arm the type-correct projection"
9148 );
9149 }
9150 }
9151
9152 #[test]
9153 fn restart_strategy_from_into_box_str_routes_through_as_str_accessor() {
9154 // Fail-before-pass-after byte-parity pin on the newly lifted
9155 // `impl From<RestartStrategy> for Box<str>` — asserts the
9156 // owned-input standard-library trait impl and the
9157 // substrate-primitive [`super::RestartStrategy::as_str`]
9158 // `pub const fn` accessor resolve to the same four-arm emit-
9159 // set across every arm the exhaustive
9160 // [`super::RestartStrategy::ALL`] slice enumerates. Opens the
9161 // substrate-wide `Box<str>` forward-projection campaign tier
9162 // on the first M2 OTP-shape closed-set fieldless typed enum
9163 // peer on the caixa surface (`:supervisor :estrategia`),
9164 // immediately after the paired `Cow<'static, str>` axis
9165 // (7dd28b3 / ee577fd) closed the
9166 // `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
9167 // 2×3 corner on this enum. Rust's standard library carries
9168 // `impl From<&str> for Box<str>` and
9169 // `impl From<String> for Box<str>` but no blanket
9170 // `impl<T: AsRef<str>> From<T> for Box<str>`, so this axis is
9171 // a distinct trait-idiomatic surface that a
9172 // `let key: Box<str> = strategy.into();`-shaped call site
9173 // reaches through this impl and no other — a paired
9174 // `Box::from(strategy.as_str())` open-code has no compile-
9175 // time link back to the substrate primitive.
9176 for &variant in RestartStrategy::ALL {
9177 let via_trait: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
9178 let via_method: &'static str = variant.as_str();
9179 assert_eq!(
9180 via_trait.as_ref(),
9181 via_method,
9182 "From<RestartStrategy> for Box<str> impl must round-\
9183 trip RestartStrategy::{variant:?} to the same lifted \
9184 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
9185 returns — divergence signals a silent detour off the \
9186 substrate-primitive accessor"
9187 );
9188 let via_into: Box<str> = variant.into();
9189 assert_eq!(
9190 via_into.as_ref(),
9191 via_method,
9192 "Into<Box<str>>::into on RestartStrategy::{variant:?} \
9193 must byte-equal RestartStrategy::as_str on the same \
9194 input — the blanket-derived Into shape must resolve \
9195 to the same as_str dispatch as the explicit From impl"
9196 );
9197 }
9198 }
9199
9200 #[test]
9201 fn restart_strategy_from_borrowed_into_box_str_routes_through_as_str_accessor() {
9202 // Fail-before-pass-after byte-parity pin on the newly lifted
9203 // `impl From<&RestartStrategy> for Box<str>` — asserts the
9204 // borrowed-input standard-library trait impl and the
9205 // substrate-primitive [`super::RestartStrategy::as_str`]
9206 // `pub const fn` accessor resolve to the same four-arm emit-
9207 // set across every arm the exhaustive
9208 // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
9209 // standard library does not carry a blanket
9210 // `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
9211 // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
9212 // so the borrowed-input `Box<str>` forward-projection axis
9213 // is a distinct trait-idiomatic surface that a
9214 // `let key: Box<str> = (&strategy).into();`-shaped call site
9215 // or a `RestartStrategy::ALL.iter().map(Box::<str>::from)`-
9216 // shaped pipe reaches through this impl and no other — the
9217 // paired owned-input `From<RestartStrategy> for Box<str>`
9218 // impl (69ef45c) forces every borrowed-input call site
9219 // through an explicit `Copy` deref
9220 // (`Box::<str>::from((*strategy).as_str())`) or a
9221 // `Box::<str>::from(strategy.as_str())` open-code whose
9222 // type bounds have no compile-time link back to the
9223 // substrate primitive.
9224 //
9225 // Second peer on the substrate-wide trait-idiomatic
9226 // [`Box<str>`] forward-projection family on this enum —
9227 // closes the `{Self, &Self}` input-shape corner of the
9228 // [`Box<str>`] axis on the first M2 OTP-shape closed-set
9229 // fieldless typed enum peer on the caixa surface
9230 // (`:supervisor :estrategia`), exactly as ee577fd closed
9231 // the paired [`Cow<'static, str>`] axis one commit after
9232 // its owning half (7dd28b3) landed. Every future closed-
9233 // set fieldless typed enum peer on the substrate is a
9234 // future target of the campaign.
9235 //
9236 // Also byte-parity witness against the paired owned-input
9237 // [`From<RestartStrategy> for Box<str>`] and the sibling
9238 // borrowed-input [`From<&RestartStrategy> for &'static str`],
9239 // [`From<&RestartStrategy> for String`], and
9240 // [`From<&RestartStrategy> for Cow<'static, str>`]
9241 // return-shape axes — locking the four
9242 // return-shape × input-shape paths together by construction
9243 // so any future detour trips at caixa-core test time. Then a
9244 // `.iter().map(Box::<str>::from)` pipe witness over
9245 // [`super::RestartStrategy::ALL`] — whose iterator yields
9246 // `&RestartStrategy` by construction, so the borrowed-input
9247 // [`Box<str>`] axis is what routes the pipe through the
9248 // substrate-primitive [`super::RestartStrategy::as_str`]
9249 // accessor without a spurious [`Copy`] deref (which would
9250 // only be reachable through the owned-input
9251 // [`From<RestartStrategy> for Box<str>`] axis by first
9252 // calling `.copied()` on the iterator).
9253 for &variant in RestartStrategy::ALL {
9254 let via_trait: Box<str> = <Box<str> as From<&RestartStrategy>>::from(&variant);
9255 let via_method: &'static str = variant.as_str();
9256 assert_eq!(
9257 via_trait.as_ref(),
9258 via_method,
9259 "From<&RestartStrategy> for Box<str> impl must \
9260 round-trip &RestartStrategy::{variant:?} to the same \
9261 lifted SUPERVISOR_ESTRATEGIA_* const \
9262 RestartStrategy::as_str returns — divergence signals \
9263 a silent detour off the substrate-primitive accessor"
9264 );
9265 let via_into: Box<str> = (&variant).into();
9266 assert_eq!(
9267 via_into.as_ref(),
9268 via_method,
9269 "Into<Box<str>>::into on &RestartStrategy::{variant:?} \
9270 must byte-equal RestartStrategy::as_str on the same \
9271 input — the blanket-derived Into shape must resolve \
9272 to the same as_str dispatch as the explicit From impl"
9273 );
9274 let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
9275 assert_eq!(
9276 via_trait, owned_box,
9277 "From<&RestartStrategy> for Box<str> and \
9278 From<RestartStrategy> for Box<str> must resolve \
9279 identically on RestartStrategy::{variant:?} — \
9280 divergence signals the borrowed-input and owned-input \
9281 Box<str> forward-projection input-shape paths have \
9282 drifted onto different emit-sets"
9283 );
9284 let borrowed_static: &'static str =
9285 <&'static str as From<&RestartStrategy>>::from(&variant);
9286 assert_eq!(
9287 via_trait.as_ref(),
9288 borrowed_static,
9289 "From<&RestartStrategy> for Box<str> and \
9290 From<&RestartStrategy> for &'static str must resolve \
9291 identically on RestartStrategy::{variant:?} — \
9292 divergence signals the borrowed-input Box<str> and \
9293 &'static str return-shape paths have drifted onto \
9294 different emit-sets"
9295 );
9296 let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
9297 assert_eq!(
9298 via_trait.as_ref(),
9299 borrowed_string.as_str(),
9300 "From<&RestartStrategy> for Box<str> and \
9301 From<&RestartStrategy> for String must resolve \
9302 identically on RestartStrategy::{variant:?} — \
9303 divergence signals the borrowed-input Box<str> and \
9304 owned-`String` return-shape paths have drifted onto \
9305 different emit-sets"
9306 );
9307 let borrowed_cow: std::borrow::Cow<'static, str> =
9308 <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
9309 assert_eq!(
9310 via_trait.as_ref(),
9311 borrowed_cow.as_ref(),
9312 "From<&RestartStrategy> for Box<str> and \
9313 From<&RestartStrategy> for Cow<'static, str> must \
9314 resolve identically on RestartStrategy::{variant:?} — \
9315 divergence signals the borrowed-input Box<str> and \
9316 Cow<'static, str> return-shape paths have drifted \
9317 onto different emit-sets"
9318 );
9319 }
9320 let via_iter: Vec<Box<str>> = RestartStrategy::ALL.iter().map(Box::<str>::from).collect();
9321 let via_method: Vec<Box<str>> = RestartStrategy::ALL
9322 .iter()
9323 .map(|s| Box::<str>::from(s.as_str()))
9324 .collect();
9325 assert_eq!(
9326 via_iter, via_method,
9327 "`.iter().map(Box::<str>::from)` over \
9328 RestartStrategy::ALL — a call site whose iteration axis \
9329 holds `&RestartStrategy` by construction — must byte-\
9330 equal `.iter().map(|s| Box::<str>::from(s.as_str()))` \
9331 on every arm — the borrowed-input Box<str> \
9332 `From<&RestartStrategy> for Box<str>` axis is what \
9333 makes the `Box::<str>::from` composition route through \
9334 the substrate-primitive `RestartStrategy::as_str` \
9335 accessor without a spurious `Copy` deref (which would \
9336 only be reachable through the owned-input \
9337 `From<RestartStrategy> for Box<str>` axis by first \
9338 calling `.copied()` on the iterator)"
9339 );
9340 }
9341
9342 #[test]
9343 fn restart_strategy_from_into_arc_str_routes_through_as_str_accessor() {
9344 // Fail-before-pass-after byte-parity pin on the newly lifted
9345 // `impl From<RestartStrategy> for std::sync::Arc<str>` — asserts
9346 // the owned-input standard-library trait impl and the
9347 // substrate-primitive [`super::RestartStrategy::as_str`]
9348 // `pub const fn` accessor resolve to the same four-arm emit-
9349 // set across every arm the exhaustive
9350 // [`super::RestartStrategy::ALL`] slice enumerates. Opens the
9351 // substrate-wide [`std::sync::Arc<str>`] forward-projection
9352 // campaign tier on the first M2 OTP-shape closed-set fieldless
9353 // typed enum peer on the caixa surface
9354 // (`:supervisor :estrategia`), immediately after the paired
9355 // [`Box<str>`] axis (69ef45c / 59ae5dc) closed the
9356 // `{Self, &Self} × {&'static str, String, Cow<'static, str>,
9357 // Box<str>}` 2×4 corner on this enum. Rust's standard library
9358 // carries `impl From<&str> for std::sync::Arc<str>` and
9359 // `impl From<String> for std::sync::Arc<str>` but no blanket
9360 // `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor
9361 // an `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`),
9362 // so this axis is a distinct trait-idiomatic surface that a
9363 // `let key: std::sync::Arc<str> = strategy.into();`-shaped call
9364 // site reaches through this impl and no other — a paired
9365 // `std::sync::Arc::<str>::from(strategy.as_str())` open-code
9366 // has no compile-time link back to the substrate primitive,
9367 // and a two-step `std::sync::Arc::<str>::from(String::from(
9368 // strategy))` composition through the owned-`String` axis
9369 // allocates twice (once into the intermediate `String`, once
9370 // into the [`Arc<str>`] on the `From<String>` conversion)
9371 // where the single-step trait impl allocates once.
9372 //
9373 // Cross-axis byte-parity witness against the sibling owned-
9374 // input `{&'static str, String, Cow<'static, str>, Box<str>}`
9375 // return-shape axes — locking the five return-shape paths on
9376 // the owned-input surface together by construction so any
9377 // future detour off the substrate-primitive
9378 // [`super::RestartStrategy::as_str`] accessor trips at caixa-
9379 // core test time.
9380 for &variant in RestartStrategy::ALL {
9381 let via_trait: std::sync::Arc<str> =
9382 <std::sync::Arc<str> as From<RestartStrategy>>::from(variant);
9383 let via_method: &'static str = variant.as_str();
9384 assert_eq!(
9385 via_trait.as_ref(),
9386 via_method,
9387 "From<RestartStrategy> for std::sync::Arc<str> impl \
9388 must round-trip RestartStrategy::{variant:?} to the \
9389 same lifted SUPERVISOR_ESTRATEGIA_* const \
9390 RestartStrategy::as_str returns — divergence signals \
9391 a silent detour off the substrate-primitive accessor"
9392 );
9393 let via_into: std::sync::Arc<str> = variant.into();
9394 assert_eq!(
9395 via_into.as_ref(),
9396 via_method,
9397 "Into<std::sync::Arc<str>>::into on \
9398 RestartStrategy::{variant:?} must byte-equal \
9399 RestartStrategy::as_str on the same input — the \
9400 blanket-derived Into shape must resolve to the same \
9401 as_str dispatch as the explicit From impl"
9402 );
9403 let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
9404 assert_eq!(
9405 via_trait.as_ref(),
9406 owned_static,
9407 "From<RestartStrategy> for std::sync::Arc<str> and \
9408 From<RestartStrategy> for &'static str must resolve \
9409 identically on RestartStrategy::{variant:?} — \
9410 divergence signals the owned-input std::sync::Arc<str> \
9411 and &'static str return-shape paths have drifted onto \
9412 different emit-sets"
9413 );
9414 let owned_string: String = <String as From<RestartStrategy>>::from(variant);
9415 assert_eq!(
9416 via_trait.as_ref(),
9417 owned_string.as_str(),
9418 "From<RestartStrategy> for std::sync::Arc<str> and \
9419 From<RestartStrategy> for String must resolve \
9420 identically on RestartStrategy::{variant:?} — \
9421 divergence signals the owned-input std::sync::Arc<str> \
9422 and owned-`String` return-shape paths have drifted \
9423 onto different emit-sets"
9424 );
9425 let owned_cow: std::borrow::Cow<'static, str> =
9426 <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
9427 assert_eq!(
9428 via_trait.as_ref(),
9429 owned_cow.as_ref(),
9430 "From<RestartStrategy> for std::sync::Arc<str> and \
9431 From<RestartStrategy> for Cow<'static, str> must \
9432 resolve identically on RestartStrategy::{variant:?} — \
9433 divergence signals the owned-input std::sync::Arc<str> \
9434 and Cow<'static, str> return-shape paths have drifted \
9435 onto different emit-sets"
9436 );
9437 let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
9438 assert_eq!(
9439 via_trait.as_ref(),
9440 owned_box.as_ref(),
9441 "From<RestartStrategy> for std::sync::Arc<str> and \
9442 From<RestartStrategy> for Box<str> must resolve \
9443 identically on RestartStrategy::{variant:?} — \
9444 divergence signals the owned-input std::sync::Arc<str> \
9445 and Box<str> return-shape paths have drifted onto \
9446 different emit-sets"
9447 );
9448 }
9449 }
9450
9451 #[test]
9452 fn restart_policy_try_from_str_routes_through_from_wire_accessor() {
9453 // Fail-before-pass-after byte-parity pin on the newly lifted
9454 // `impl TryFrom<&str> for RestartPolicy` — asserts the standard-
9455 // library trait impl and the substrate-primitive
9456 // [`RestartPolicy::from_wire`] `Option<Self>` accessor resolve to
9457 // the same three-arm accept-set across every arm the exhaustive
9458 // [`RestartPolicy::ALL`] slice enumerates. Any future silent
9459 // detour that routes the trait impl through a divergent
9460 // projection (a per-arm inline `match s { "Permanent" =>
9461 // Ok(Self::Permanent), … }` re-inlining that opens a compile-time
9462 // link to the un-lifted arm-literal, a hypothetical
9463 // `#[serde(rename_all = "…")]` attribute drift that silently
9464 // splits the wire byte-string from every consumer that reaches
9465 // for this typed dispatch, an accidental swap onto the kebab-case
9466 // dispatcher-catalog axis the pre-existing [`std::str::FromStr`]
9467 // impl parses through and which would collide the two-axis
9468 // wire/catalog split the sibling [`RestartPolicy::from_wire`]
9469 // doc block makes load-bearing) trips at caixa-core test time
9470 // under `assert_eq!` rather than at a downstream
9471 // `impl TryFrom<&str>`-bound consumer's silent split. Sweeps
9472 // every one of the three arms [`RestartPolicy::ALL`] carries so
9473 // no arm's projection is covered only by the sibling method-
9474 // named `from_wire` path. Peer of the sibling
9475 // [`restart_strategy_try_from_str_routes_through_from_wire_accessor`]
9476 // (5b828ed) — extends the trait-idiomatic reverse-projection
9477 // axis onto the third and final M2-OTP-shape closed-set typed
9478 // enum on the caixa surface (the paired per-child restart-
9479 // decision-policy sibling on the same M2 `:supervisor` slot).
9480 for &variant in RestartPolicy::ALL {
9481 let wire = variant.as_str();
9482 assert_eq!(
9483 <RestartPolicy as TryFrom<&str>>::try_from(wire),
9484 Ok(variant),
9485 "TryFrom<&str> impl on RestartPolicy must round-trip \
9486 RestartPolicy::{variant:?}.as_str() = {wire:?} back to \
9487 Ok(RestartPolicy::{variant:?}) — divergence from \
9488 RestartPolicy::from_wire signals a silent detour off \
9489 the substrate-primitive accessor"
9490 );
9491 assert_eq!(
9492 <RestartPolicy as TryFrom<&str>>::try_from(wire).ok(),
9493 RestartPolicy::from_wire(wire),
9494 "TryFrom<&str> ok()-projection on {wire:?} must byte-\
9495 equal RestartPolicy::from_wire on the same input"
9496 );
9497 }
9498 }
9499
9500 #[test]
9501 fn restart_policy_try_from_str_rejects_unknown_byte_strings() {
9502 // Rejection witness on the `impl TryFrom<&str> for
9503 // RestartPolicy` — sweeps a candidate set of byte-strings
9504 // outside the three-arm PascalCase wire accept-set the sibling
9505 // [`RestartPolicy::as_str`] emits and asserts every one lands on
9506 // `Err(())`, so a future accidental widening of the trait impl's
9507 // accept-set (a stray additional
9508 // `_ if s.eq_ignore_ascii_case("Permanent") => Ok(…)` case-fold
9509 // path, a silent inclusion of the kebab-case dispatcher-catalog
9510 // byte-string the pre-existing [`std::str::FromStr`] impl the
9511 // [`gen_platform::FromStrKind`] derive installs parses onto the
9512 // wire axis — which would collide the two-axis
9513 // wire/dispatcher-catalog split the sibling
9514 // [`RestartPolicy::from_wire`] doc block makes load-bearing —
9515 // an English-rebrand or plural-arm silent alias that would widen
9516 // the wire accept-set past the OTP-canonical three) trips at
9517 // caixa-core test time. The candidate set includes the empty
9518 // string, whitespace-only padding, the kebab-case dispatcher-
9519 // catalog byte-strings on the sibling axis (a caller who
9520 // confuses the two axes trips here rather than at a downstream
9521 // consumer's silent reject), a lowercase / uppercase / mixed-case
9522 // fold of each PascalCase arm (a caller who assumes case-fold
9523 // acceptance trips here), leading/trailing whitespace padding,
9524 // the trailing-newline shape, quote-wrapped candidates, and a
9525 // residual set of plausible-but-wrong English rebrand
9526 // candidates. Peer of the sibling
9527 // [`restart_strategy_try_from_str_rejects_unknown_byte_strings`]
9528 // (5b828ed) rejection witness.
9529 let rejected: &[&str] = &[
9530 "",
9531 " ",
9532 "\n",
9533 "\t",
9534 "permanent",
9535 "temporary",
9536 "transient",
9537 "PERMANENT",
9538 "TEMPORARY",
9539 "TRANSIENT",
9540 "Permanents",
9541 "Permanent ",
9542 " Permanent",
9543 " Temporary ",
9544 "Permanent\n",
9545 "Transient\t",
9546 "\"Permanent\"",
9547 "Ephemeral",
9548 "Always",
9549 "Never",
9550 "OnAbnormalExit",
9551 "intrinsic",
9552 "?",
9553 ];
9554 for &input in rejected {
9555 assert_eq!(
9556 <RestartPolicy as TryFrom<&str>>::try_from(input),
9557 Err(()),
9558 "TryFrom<&str> impl on RestartPolicy must reject the \
9559 non-wire byte-string {input:?} — silent acceptance \
9560 signals an accept-set widening off the paired \
9561 RestartPolicy::from_wire resolver"
9562 );
9563 }
9564 }
9565
9566 #[test]
9567 fn restart_policy_try_from_str_and_from_wire_partition_the_accept_set() {
9568 // Cross-axis partition pin: the paired `TryFrom<&str>` and
9569 // `from_wire` reverse projections must resolve identically on
9570 // *every* input, not just the ones [`RestartPolicy::ALL`]
9571 // enumerates. Sweeps a mixed candidate set spanning accepted
9572 // (three-arm PascalCase wire byte-strings) and rejected (kebab-
9573 // case dispatcher-catalog byte-strings, empty, whitespace-
9574 // padded, quoted, English-rebrand candidates) inputs and asserts
9575 // the trait's `Result::ok()` projection byte-equals the method-
9576 // named resolver's `Option<Self>` return-shape on each, locking
9577 // the two paths together by construction so any future detour
9578 // (a stray `try_from` special-case that widens or narrows the
9579 // accept-set outside the paired `from_wire` resolver, an
9580 // accidental swap onto the kebab-case [`std::str::FromStr`]
9581 // impl the [`gen_platform::FromStrKind`] derive installs on the
9582 // sibling dispatcher-catalog axis) trips at caixa-core test
9583 // time. Peer of the sibling
9584 // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
9585 // pin — extends the round-trip discipline onto the M2-OTP-shape
9586 // per-child restart-policy axis.
9587 let candidates: &[&str] = &[
9588 "Permanent",
9589 "Temporary",
9590 "Transient",
9591 "",
9592 "permanent",
9593 "temporary",
9594 "transient",
9595 "PERMANENT",
9596 "unknown",
9597 "Permanent ",
9598 " Permanent",
9599 "\"Permanent\"",
9600 "Ephemeral",
9601 "OnAbnormalExit",
9602 "?",
9603 ];
9604 for &input in candidates {
9605 let via_trait: Option<RestartPolicy> =
9606 <RestartPolicy as TryFrom<&str>>::try_from(input).ok();
9607 let via_method: Option<RestartPolicy> = RestartPolicy::from_wire(input);
9608 assert_eq!(
9609 via_trait, via_method,
9610 "TryFrom<&str> and from_wire must resolve identically on \
9611 input {input:?} — divergence signals the two reverse-\
9612 projection paths have drifted onto different accept-sets"
9613 );
9614 }
9615 }
9616
9617 #[test]
9618 fn restart_policy_from_into_static_str_routes_through_as_str_accessor() {
9619 // Fail-before-pass-after byte-parity pin on the newly lifted
9620 // `impl From<RestartPolicy> for &'static str` — asserts the
9621 // standard-library trait impl and the substrate-primitive
9622 // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
9623 // the same three-arm emit-set across every arm the exhaustive
9624 // [`RestartPolicy::ALL`] slice enumerates. Any future silent
9625 // detour that routes the trait impl through a divergent
9626 // projection (a per-arm inline `match policy { Permanent =>
9627 // "Permanent", … }` re-inlining that opens a compile-time link
9628 // to the un-lifted arm-literal, an accidental swap onto the
9629 // sibling kebab-case [`Self::discriminant`] dispatcher-catalog
9630 // axis that would collide the two-axis wire/catalog split the
9631 // sibling [`RestartPolicy::from_wire`] doc block makes
9632 // load-bearing) trips at caixa-core test time under
9633 // `assert_eq!` rather than at a downstream
9634 // `impl Into<&'static str>`-bound consumer's silent split.
9635 // Sweeps every one of the three arms [`RestartPolicy::ALL`]
9636 // carries so no arm's projection is covered only by the sibling
9637 // method-named `as_str` / [`std::fmt::Display`] / [`AsRef<str>`]
9638 // paths. Materializes the `<&'static str as
9639 // From<RestartPolicy>>::from` output in a `const`-shape binding
9640 // to make the `'static` lifetime promise a build-time invariant
9641 // — a future accidental downgrade of any of the three arms'
9642 // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] constants to a
9643 // non-`&'static str` (a `String::leak()`-produced return, a
9644 // `Box::leak`-cast) trips at caixa-core build time rather than
9645 // at a downstream `'static`-bound consumer. Peer of the sibling
9646 // [`restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
9647 // (523157d) — extends the trait-idiomatic forward-projection
9648 // axis onto the second (and second-of-two-in-M2) closed-set
9649 // typed enum on the caixa surface (the paired per-child
9650 // restart-decision-policy sibling on the same M2 `:supervisor`
9651 // slot).
9652 const PERMANENT: &str = RestartPolicy::Permanent.as_str();
9653 const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
9654 const TRANSIENT: &str = RestartPolicy::Transient.as_str();
9655 for &variant in RestartPolicy::ALL {
9656 let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
9657 let via_method: &'static str = variant.as_str();
9658 assert_eq!(
9659 via_trait, via_method,
9660 "From<RestartPolicy> for &'static str impl must round-trip \
9661 RestartPolicy::{variant:?} to the same lifted \
9662 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str returns — \
9663 divergence signals a silent detour off the substrate-primitive \
9664 accessor"
9665 );
9666 let via_into: &'static str = variant.into();
9667 assert_eq!(
9668 via_into, via_method,
9669 "Into<&'static str>::into on RestartPolicy::{variant:?} must \
9670 byte-equal RestartPolicy::as_str on the same input — the \
9671 blanket-derived Into shape must resolve to the same as_str \
9672 dispatch as the explicit From impl"
9673 );
9674 }
9675 assert_eq!(
9676 [PERMANENT, TEMPORARY, TRANSIENT],
9677 [
9678 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
9679 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
9680 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
9681 ],
9682 "const-context RestartPolicy::as_str must resolve to the three \
9683 lifted SUPERVISOR_CHILD_RESTART_* consts — a future accidental \
9684 downgrade of any arm to a non-const or non-static byte-string \
9685 breaks the `&'static str`-lifetime promise the paired \
9686 From<RestartPolicy> for &'static str impl carries by \
9687 construction"
9688 );
9689 }
9690
9691 #[test]
9692 fn restart_policy_from_into_static_str_and_as_str_partition_the_emit_set() {
9693 // Cross-axis partition pin: the paired trait-idiomatic
9694 // `From<RestartPolicy> for &'static str` forward projection and
9695 // the method-named [`RestartPolicy::as_str`] forward projection
9696 // must resolve identically on *every* arm, not just the ones
9697 // named in the primary byte-parity pin above. Sweeps every
9698 // [`RestartPolicy::ALL`] arm and asserts the trait's `From::from`
9699 // output byte-equals the method-named accessor's return-value on
9700 // each, locking the two forward-projection paths together by
9701 // construction so any future detour (a stray `From` special-case
9702 // that lands on a divergent per-arm literal outside the paired
9703 // `as_str` dispatch, a hypothetical rebrand touching one axis
9704 // without the other) trips at caixa-core test time. Peer of the
9705 // sibling forward-projection partition pin
9706 // [`restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
9707 // (523157d) — extends the round-trip discipline onto the
9708 // second-of-two M2-OTP-shape closed-set typed enum on the caixa
9709 // surface, closing the two-way `Self ↔ &'static str` round-trip
9710 // on the trait-idiomatic pair (`From<Self> for &'static str` +
9711 // `TryFrom<&str> for Self`) as well as the pre-existing method-
9712 // named pair (`as_str` + `from_wire`).
9713 for &variant in RestartPolicy::ALL {
9714 let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
9715 let via_method: &'static str = variant.as_str();
9716 assert_eq!(
9717 via_trait, via_method,
9718 "From<RestartPolicy> for &'static str and \
9719 RestartPolicy::as_str must resolve identically on \
9720 RestartPolicy::{variant:?} — divergence signals the \
9721 two forward-projection paths have drifted onto different \
9722 emit-sets"
9723 );
9724 }
9725 // Round-trip witness: every arm's forward `From` output re-parses
9726 // through the paired trait-idiomatic reverse `TryFrom<&str>` back
9727 // to the original variant. Closes the two-way `RestartPolicy ↔
9728 // &'static str` round-trip on the trait-idiomatic axis pair,
9729 // mirroring the pre-existing method-named `as_str` + `from_wire`
9730 // round-trip on the substrate-primitive axis pair.
9731 for &variant in RestartPolicy::ALL {
9732 let emitted: &'static str = variant.into();
9733 let re_parsed: Result<RestartPolicy, ()> =
9734 <RestartPolicy as TryFrom<&str>>::try_from(emitted);
9735 assert_eq!(
9736 re_parsed,
9737 Ok(variant),
9738 "trait-idiomatic axis pair must round-trip \
9739 RestartPolicy::{variant:?} through `.into::<&'static \
9740 str>()` and back through `TryFrom<&str>` — a break signals \
9741 the forward-emit and reverse-parse axes have drifted onto \
9742 different vocabularies"
9743 );
9744 }
9745 }
9746
9747 #[test]
9748 fn restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
9749 // Fail-before-pass-after byte-parity pin on the newly lifted
9750 // `impl From<&RestartPolicy> for &'static str` — asserts the
9751 // borrowed-input standard-library trait impl and the substrate-
9752 // primitive [`RestartPolicy::as_str`] `pub const fn` accessor
9753 // resolve to the same three-arm emit-set across every arm the
9754 // exhaustive [`RestartPolicy::ALL`] slice enumerates. Rust's
9755 // `From` trait does not auto-derive the borrowed-input sibling
9756 // from a paired owned-input impl (no `impl<T, U> From<&T> for U
9757 // where T: Copy, U: From<T>` blanket in `core`), so the
9758 // borrowed-input axis is a distinct trait-idiomatic surface
9759 // that a `.iter().map(Into::into)` shape over
9760 // [`RestartPolicy::ALL`] (whose iterator yields
9761 // `&RestartPolicy`, not `RestartPolicy`) reaches through this
9762 // impl and no other — the paired owned-input
9763 // [`From<RestartPolicy>`] impl requires an explicit `.copied()`
9764 // / dereference before the trait fires. Materializes the
9765 // `<&'static str as From<&RestartPolicy>>::from` output in a
9766 // `const`-shape binding to make the `'static` lifetime promise
9767 // a build-time invariant.
9768 const PERMANENT: &str = RestartPolicy::Permanent.as_str();
9769 const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
9770 const TRANSIENT: &str = RestartPolicy::Transient.as_str();
9771 for variant in RestartPolicy::ALL {
9772 let via_trait: &'static str = <&'static str as From<&RestartPolicy>>::from(variant);
9773 let via_method: &'static str = variant.as_str();
9774 assert_eq!(
9775 via_trait, via_method,
9776 "From<&RestartPolicy> for &'static str impl must round-trip \
9777 &RestartPolicy::{variant:?} to the same lifted \
9778 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
9779 returns — divergence signals a silent detour off the \
9780 substrate-primitive accessor"
9781 );
9782 let via_into: &'static str = variant.into();
9783 assert_eq!(
9784 via_into, via_method,
9785 "Into<&'static str>::into on &RestartPolicy::{variant:?} \
9786 must byte-equal RestartPolicy::as_str on the same input — \
9787 the blanket-derived Into shape must resolve to the same \
9788 as_str dispatch as the explicit From impl"
9789 );
9790 }
9791 assert_eq!(
9792 [PERMANENT, TEMPORARY, TRANSIENT],
9793 [
9794 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
9795 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
9796 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
9797 ],
9798 "const-context RestartPolicy::as_str must resolve to the three \
9799 lifted SUPERVISOR_CHILD_RESTART_* consts — the borrowed-input \
9800 From<&RestartPolicy> for &'static str impl inherits its \
9801 `'static` lifetime promise from the same accessor the \
9802 owned-input sibling routes through"
9803 );
9804 }
9805
9806 #[test]
9807 fn restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
9808 // Cross-axis partition pin: the paired trait-idiomatic
9809 // owned-input `From<RestartPolicy> for &'static str` (9fb37d0
9810 // campaign-shape) and borrowed-input `From<&RestartPolicy> for
9811 // &'static str` (this lift) forward projections must resolve
9812 // identically on every arm, locking the two input-shape paths
9813 // together so any future detour trips at caixa-core test time.
9814 // Then a witness that a `.iter().map(Into::into)` pipe over
9815 // [`RestartPolicy::ALL`] (whose iterator yields
9816 // `&RestartPolicy`) materializes the three-arm accept-set
9817 // through the borrowed-input axis alone — the exact shape a
9818 // future wasm-operator per-child post-exit restart-decision
9819 // diagnostic line, a future substrate-wide per-arm diagnostic
9820 // column, or a
9821 // `HashMap::<&'static str, RestartPolicy>::from_iter(
9822 // RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
9823 // per-policy lookup reaches through — closing the two-way
9824 // owned/borrowed input-shape symmetry on the forward-projection
9825 // trait-idiomatic axis. Peer of the sibling
9826 // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9827 // (64aa742) /
9828 // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9829 // (5ab993a) /
9830 // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9831 // (807b0b5) /
9832 // [`restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9833 // (e941836) partition pins on the sibling closed-set typed-enum
9834 // discriminator axes — extends the borrowed-input axis
9835 // discipline onto the second-of-two M2 OTP-shape closed-set
9836 // typed enum on the caixa surface (per-child restart-decision
9837 // policy). Also closes the direct two-way `&Self → &'static
9838 // str → Self` round-trip via the paired [`TryFrom<&str>`] axis
9839 // — unlike the peer [`crate::CaixaKind`] axis pair (whose
9840 // forward `From` emits lowercase Portuguese diagnostic bytes
9841 // while the reverse `TryFrom` parses `PascalCase` wire bytes,
9842 // forcing the round-trip through an intermediate wire-vocab
9843 // hop), the [`RestartPolicy::as_str`] emit and
9844 // [`RestartPolicy::from_wire`] parse share the same
9845 // `PascalCase` vocabulary by construction, so the borrowed-
9846 // input forward axis and the reverse axis compose directly.
9847 for &variant in RestartPolicy::ALL {
9848 let owned: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
9849 let borrowed: &'static str = <&'static str as From<&RestartPolicy>>::from(&variant);
9850 assert_eq!(
9851 owned, borrowed,
9852 "From<RestartPolicy> and From<&RestartPolicy> for \
9853 &'static str must resolve identically on \
9854 RestartPolicy::{variant:?} — divergence signals the \
9855 owned-input and borrowed-input forward-projection paths \
9856 have drifted onto different emit-sets"
9857 );
9858 }
9859 let via_iter: Vec<&'static str> = RestartPolicy::ALL.iter().map(Into::into).collect();
9860 let via_method: Vec<&'static str> = RestartPolicy::ALL.iter().map(|p| p.as_str()).collect();
9861 assert_eq!(
9862 via_iter, via_method,
9863 "`.iter().map(Into::into)` over RestartPolicy::ALL must \
9864 byte-equal `.iter().map(|p| p.as_str())` on every arm — the \
9865 borrowed-input `From<&RestartPolicy> for &'static str` axis \
9866 is what makes the `.iter().map(Into::into)` shape route \
9867 through the substrate-primitive `RestartPolicy::as_str` \
9868 accessor rather than through a per-call-site `.copied()` / \
9869 dereference detour"
9870 );
9871 for variant in RestartPolicy::ALL {
9872 let emitted: &'static str = variant.into();
9873 let re_parsed: Result<RestartPolicy, ()> =
9874 <RestartPolicy as TryFrom<&str>>::try_from(emitted);
9875 assert_eq!(
9876 re_parsed,
9877 Ok(*variant),
9878 "trait-idiomatic borrowed-input forward-projection + \
9879 reverse-projection axis pair must round-trip \
9880 &RestartPolicy::{variant:?} through `.into::<&'static \
9881 str>()` (via the borrowed-input axis) and back through \
9882 `TryFrom<&str>` — a break signals the borrowed-input \
9883 forward-emit and reverse-parse axes have drifted onto \
9884 different vocabularies"
9885 );
9886 }
9887 }
9888
9889 #[test]
9890 fn restart_policy_from_into_owned_string_routes_through_as_str_accessor() {
9891 // Fail-before-pass-after byte-parity pin on the newly lifted
9892 // `impl From<RestartPolicy> for String` — asserts the
9893 // owned-`String`-returning standard-library trait impl and the
9894 // substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
9895 // accessor resolve to the same three-arm emit-set across every
9896 // arm the exhaustive [`RestartPolicy::ALL`] slice enumerates.
9897 // Rust's standard library does not carry a blanket
9898 // `impl<T: AsRef<str>> From<T> for String` (nor an
9899 // `impl<T: fmt::Display> From<T> for String`), so the
9900 // owned-`String` forward-projection axis is a distinct
9901 // trait-idiomatic surface that a `let key: String =
9902 // policy.into();`-shaped call site reaches through this impl
9903 // and no other — the paired sibling `From<RestartPolicy> for
9904 // &'static str` impl forces every owned-`String` call site
9905 // through an explicit `.to_owned()` / `String::from`
9906 // restatement. Peer of the first-mover
9907 // [`restart_strategy_from_into_owned_string_routes_through_as_str_accessor`]
9908 // (7baa18a) — extends the trait-idiomatic owned-`String`
9909 // forward-projection axis onto the second-of-two M2 OTP-shape
9910 // closed-set typed enums on the caixa surface (per-child
9911 // restart-decision-policy sibling on the same M2 `:supervisor`
9912 // slot).
9913 for &variant in RestartPolicy::ALL {
9914 let via_trait: String = <String as From<RestartPolicy>>::from(variant);
9915 let via_method: &'static str = variant.as_str();
9916 assert_eq!(
9917 via_trait.as_str(),
9918 via_method,
9919 "From<RestartPolicy> for String impl must round-trip \
9920 RestartPolicy::{variant:?} to the same lifted \
9921 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
9922 returns — divergence signals a silent detour off the \
9923 substrate-primitive accessor"
9924 );
9925 let via_into: String = variant.into();
9926 assert_eq!(
9927 via_into.as_str(),
9928 via_method,
9929 "Into<String>::into on RestartPolicy::{variant:?} must \
9930 byte-equal RestartPolicy::as_str on the same input — the \
9931 blanket-derived Into shape must resolve to the same as_str \
9932 dispatch as the explicit From impl"
9933 );
9934 }
9935 }
9936
9937 #[test]
9938 fn restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm() {
9939 // Cross-axis partition pin: the paired trait-idiomatic
9940 // owned-`String` `From<RestartPolicy> for String` (this lift)
9941 // and owned-`&'static str` `From<RestartPolicy> for &'static
9942 // str` (9fb37d0) forward projections must resolve identically
9943 // on every arm, locking the two return-type-shape paths
9944 // together so any future detour trips at caixa-core test time.
9945 // Also byte-parity witness against the sibling
9946 // [`ToString::to_string`] surface routed through
9947 // [`std::fmt::Display`] — the three owned-heap-string paths
9948 // (`.into::<String>()`, `String::from`, `.to_string()`) must
9949 // resolve identically on every arm so a future consumer that
9950 // picks any of the three lands on the same lifted
9951 // SUPERVISOR_CHILD_RESTART_* const. Then a `.iter().copied()
9952 // .map(String::from)` pipe witness over [`RestartPolicy::ALL`]
9953 // that materializes the three-arm accept-set through the
9954 // owned-`String` axis alone — the exact shape a future
9955 // wasm-operator per-child post-exit restart-decision
9956 // diagnostic line composer or a
9957 // `HashMap::<String, RestartPolicy>::from_iter(
9958 // RestartPolicy::ALL.iter().copied().map(|p| (p.into(), p)))`-style
9959 // owned-key per-policy lookup reaches through — closing the
9960 // owned-`String` forward-projection axis's iterator-pipe
9961 // shape. Then a direct round-trip witness through the paired
9962 // trait-idiomatic reverse [`TryFrom<&str>`] axis on the
9963 // owned-`String`'s [`String::as_str`] borrow that closes the
9964 // two-way `Self → String → Self` round-trip on the trait-
9965 // idiomatic owned-`String` forward + reverse axis pair —
9966 // unlike the peer [`crate::CaixaKind`] axis pair (whose
9967 // forward `From` emits lowercase Portuguese diagnostic bytes
9968 // while the reverse `TryFrom` parses `PascalCase` wire bytes,
9969 // forcing the round-trip through an intermediate wire-vocab
9970 // hop), the [`RestartPolicy::as_str`] emit and
9971 // [`RestartPolicy::from_wire`] parse share the same
9972 // `PascalCase` vocabulary by construction, so the owned-
9973 // `String` forward axis and the reverse axis compose directly.
9974 for &variant in RestartPolicy::ALL {
9975 let owned_string: String = <String as From<RestartPolicy>>::from(variant);
9976 let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
9977 assert_eq!(
9978 owned_string.as_str(),
9979 owned_static,
9980 "From<RestartPolicy> for String and From<RestartPolicy> \
9981 for &'static str must resolve identically on \
9982 RestartPolicy::{variant:?} — divergence signals the \
9983 owned-`String` and owned-`&'static str` forward-projection \
9984 return-type-shape paths have drifted onto different \
9985 emit-sets"
9986 );
9987 let via_to_string: String = variant.to_string();
9988 assert_eq!(
9989 owned_string, via_to_string,
9990 "From<RestartPolicy> for String must byte-equal \
9991 RestartPolicy::to_string on RestartPolicy::{variant:?} — \
9992 divergence signals the trait-idiomatic owned-`String` \
9993 forward-projection axis and the ToString-through-Display \
9994 axis have drifted onto different emit-sets"
9995 );
9996 }
9997 let via_iter: Vec<String> = RestartPolicy::ALL
9998 .iter()
9999 .copied()
10000 .map(String::from)
10001 .collect();
10002 let via_method: Vec<String> = RestartPolicy::ALL
10003 .iter()
10004 .map(|p| p.as_str().to_owned())
10005 .collect();
10006 assert_eq!(
10007 via_iter, via_method,
10008 "`.iter().copied().map(String::from)` over RestartPolicy::ALL \
10009 must byte-equal `.iter().map(|p| p.as_str().to_owned())` on \
10010 every arm — the owned-`String` `From<RestartPolicy> for \
10011 String` axis is what makes the `String::from` composition \
10012 route through the substrate-primitive `RestartPolicy::as_str` \
10013 accessor rather than through a per-call-site `.to_owned()` / \
10014 `String::from(policy.as_str())` detour"
10015 );
10016 for &variant in RestartPolicy::ALL {
10017 let emitted: String = variant.into();
10018 let re_parsed: Result<RestartPolicy, ()> =
10019 <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
10020 assert_eq!(
10021 re_parsed,
10022 Ok(variant),
10023 "trait-idiomatic owned-`String` forward-projection + \
10024 reverse-projection axis pair must round-trip \
10025 RestartPolicy::{variant:?} through `.into::<String>()` \
10026 and back through `TryFrom<&str>` on the owned-`String`'s \
10027 String::as_str borrow — a break signals the owned-`String` \
10028 forward-emit and reverse-parse axes have drifted onto \
10029 different vocabularies"
10030 );
10031 }
10032 }
10033
10034 #[test]
10035 fn restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
10036 // Fail-before-pass-after byte-parity pin on the newly lifted
10037 // `impl From<&RestartPolicy> for String` — asserts the
10038 // borrowed-input owned-`String`-returning standard-library
10039 // trait impl and the substrate-primitive
10040 // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
10041 // the same three-arm emit-set across every arm the exhaustive
10042 // [`RestartPolicy::ALL`] slice enumerates. Rust's standard
10043 // library does not carry a blanket `impl<T: AsRef<str>>
10044 // From<&T> for String` (nor an `impl<T: fmt::Display> From<&T>
10045 // for String`), so the borrowed-input owned-`String` forward-
10046 // projection axis is a distinct trait-idiomatic surface that a
10047 // `let key: String = (&policy).into();`-shaped call site
10048 // reaches through this impl and no other — the paired sibling
10049 // `From<RestartPolicy> for String` impl forces every borrowed-
10050 // input call site through an explicit `Copy` deref
10051 // (`String::from(*policy)`) or an `.as_str().to_owned()` /
10052 // `.to_string()` detour. Peer of the first-mover
10053 // [`restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
10054 // (579385f) — extends the trait-idiomatic borrowed-input
10055 // owned-`String` forward-projection axis onto the second-of-
10056 // two M2 OTP-shape closed-set typed enums on the caixa surface
10057 // (per-child restart-decision-policy sibling on the same M2
10058 // `:supervisor` slot).
10059 for &variant in RestartPolicy::ALL {
10060 let via_trait: String = <String as From<&RestartPolicy>>::from(&variant);
10061 let via_method: &'static str = variant.as_str();
10062 assert_eq!(
10063 via_trait.as_str(),
10064 via_method,
10065 "From<&RestartPolicy> for String impl must round-trip \
10066 &RestartPolicy::{variant:?} to the same lifted \
10067 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
10068 returns — divergence signals a silent detour off the \
10069 substrate-primitive accessor"
10070 );
10071 let via_into: String = (&variant).into();
10072 assert_eq!(
10073 via_into.as_str(),
10074 via_method,
10075 "Into<String>::into on &RestartPolicy::{variant:?} must \
10076 byte-equal RestartPolicy::as_str on the same input — \
10077 the blanket-derived Into shape must resolve to the \
10078 same as_str dispatch as the explicit From impl"
10079 );
10080 }
10081 }
10082
10083 #[test]
10084 fn restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
10085 // Cross-axis partition pin: the newly lifted trait-idiomatic
10086 // borrowed-input owned-`String` `From<&RestartPolicy> for
10087 // String` (this lift), the paired owned-input owned-`String`
10088 // `From<RestartPolicy> for String` (7851725), the paired
10089 // borrowed-input owned-`&'static str` `From<&RestartPolicy>
10090 // for &'static str` (842c7f3), and the paired owned-input
10091 // owned-`&'static str` `From<RestartPolicy> for &'static str`
10092 // (9fb37d0) — every corner of the `{Self, &Self} × {&'static
10093 // str, String}` 2×2 trait-idiomatic projection family — must
10094 // resolve identically on every arm, locking the four
10095 // return-shape × input-shape paths together so any future
10096 // detour trips at caixa-core test time. Also byte-parity
10097 // witness against the sibling [`ToString::to_string`] surface
10098 // routed through [`std::fmt::Display`] and a direct round-trip
10099 // witness through the paired trait-idiomatic reverse
10100 // [`TryFrom<&str>`] axis on the owned-`String`'s
10101 // [`String::as_str`] borrow that closes the two-way
10102 // `&Self → String → Self` round-trip on the trait-idiomatic
10103 // borrowed-input owned-`String` forward + reverse axis pair.
10104 // Peer of the first-mover
10105 // [`restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
10106 // (579385f) — closes the whole `{Self, &Self} × {&'static str,
10107 // String}` 2×2 projection corner on both M2 OTP-shape sibling
10108 // peers.
10109 for &variant in RestartPolicy::ALL {
10110 let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
10111 let owned_string: String = <String as From<RestartPolicy>>::from(variant);
10112 let borrowed_static: &'static str =
10113 <&'static str as From<&RestartPolicy>>::from(&variant);
10114 let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
10115 assert_eq!(
10116 borrowed_string, owned_string,
10117 "From<&RestartPolicy> for String and From<RestartPolicy> \
10118 for String must resolve identically on \
10119 RestartPolicy::{variant:?} — divergence signals the \
10120 borrowed-input and owned-input owned-`String` \
10121 forward-projection input-shape paths have drifted onto \
10122 different emit-sets"
10123 );
10124 assert_eq!(
10125 borrowed_string.as_str(),
10126 borrowed_static,
10127 "From<&RestartPolicy> for String and From<&RestartPolicy> \
10128 for &'static str must resolve identically on \
10129 RestartPolicy::{variant:?} — divergence signals the \
10130 borrowed-input `&'static str` and owned-`String` \
10131 return-shape paths have drifted onto different \
10132 emit-sets"
10133 );
10134 assert_eq!(
10135 borrowed_string.as_str(),
10136 owned_static,
10137 "From<&RestartPolicy> for String and From<RestartPolicy> \
10138 for &'static str must resolve identically on \
10139 RestartPolicy::{variant:?} — divergence signals a \
10140 break in the diagonal corner of the {{Self, &Self}} × \
10141 {{&'static str, String}} 2×2 trait-idiomatic \
10142 projection family"
10143 );
10144 let via_to_string: String = variant.to_string();
10145 assert_eq!(
10146 borrowed_string, via_to_string,
10147 "From<&RestartPolicy> for String must byte-equal \
10148 RestartPolicy::to_string on RestartPolicy::{variant:?} \
10149 — divergence signals the trait-idiomatic borrowed-input \
10150 owned-`String` forward-projection axis and the \
10151 ToString-through-Display axis have drifted onto \
10152 different emit-sets"
10153 );
10154 }
10155 let via_iter: Vec<String> = RestartPolicy::ALL.iter().map(String::from).collect();
10156 let via_method: Vec<String> = RestartPolicy::ALL
10157 .iter()
10158 .map(|p| p.as_str().to_owned())
10159 .collect();
10160 assert_eq!(
10161 via_iter, via_method,
10162 "`.iter().map(String::from)` over RestartPolicy::ALL — a \
10163 call site whose iteration axis holds `&RestartPolicy` by \
10164 construction — must byte-equal `.iter().map(|p| \
10165 p.as_str().to_owned())` on every arm — the borrowed-input \
10166 owned-`String` `From<&RestartPolicy> for String` axis is \
10167 what makes the `String::from` composition route through \
10168 the substrate-primitive `RestartPolicy::as_str` accessor \
10169 without a spurious `Copy` deref (which would only be \
10170 reachable through the owned-input `From<RestartPolicy> \
10171 for String` axis by first calling `.copied()` on the \
10172 iterator)"
10173 );
10174 for &variant in RestartPolicy::ALL {
10175 let emitted: String = (&variant).into();
10176 let re_parsed: Result<RestartPolicy, ()> =
10177 <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
10178 assert_eq!(
10179 re_parsed,
10180 Ok(variant),
10181 "trait-idiomatic borrowed-input owned-`String` \
10182 forward-projection + reverse-projection axis pair must \
10183 round-trip &RestartPolicy::{variant:?} through \
10184 `.into::<String>()` on the borrowed-input surface and \
10185 back through `TryFrom<&str>` on the owned-`String`'s \
10186 String::as_str borrow — a break signals the \
10187 borrowed-input owned-`String` forward-emit and \
10188 reverse-parse axes have drifted onto different \
10189 vocabularies"
10190 );
10191 }
10192 }
10193
10194 #[test]
10195 fn restart_policy_from_into_static_cow_str_routes_through_as_str_accessor() {
10196 // Fail-before-pass-after byte-parity pin on the newly lifted
10197 // `impl From<RestartPolicy> for std::borrow::Cow<'static, str>` —
10198 // asserts the standard-library trait impl and the substrate-
10199 // primitive [`super::RestartPolicy::as_str`] `pub const fn`
10200 // accessor resolve to the same three-arm emit-set across every
10201 // arm the exhaustive [`super::RestartPolicy::ALL`] slice
10202 // enumerates. Rust's standard library does not carry a blanket
10203 // `impl<T: AsRef<str>> From<T> for Cow<'static, str>` (nor an
10204 // `impl<T: fmt::Display> From<T> for Cow<'static, str>`), so
10205 // the `Cow<'static, str>` forward-projection axis is a
10206 // distinct trait-idiomatic surface that a
10207 // `let key: Cow<'static, str> = policy.into();`-shaped call
10208 // site reaches through this impl and no other — the paired
10209 // sibling `From<RestartPolicy> for &'static str` and
10210 // `From<RestartPolicy> for String` impls force every
10211 // `Cow<'static, str>`-parameterized call site through a
10212 // `Cow::Borrowed(policy.as_str())` /
10213 // `Cow::Owned(policy.to_string())` composition whose type
10214 // bounds have no compile-time link back to the substrate
10215 // primitive.
10216 //
10217 // Also asserts the projection lands on the zero-alloc
10218 // [`std::borrow::Cow::Borrowed`] arm (not the
10219 // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
10220 // [`super::RestartPolicy::as_str`] accessor's `&'static str`
10221 // return lifetime by construction makes the borrowed arm the
10222 // type-correct projection with no runtime allocation. Any
10223 // future silent detour that routes the impl through the owned
10224 // arm (an accidental `Cow::Owned(policy.to_string())` rewrite
10225 // that would allocate on every call site where the
10226 // `&'static str` return of [`super::RestartPolicy::as_str`]
10227 // makes the zero-alloc borrowed projection type-correct) trips
10228 // at caixa-core test time under the
10229 // [`std::borrow::Cow::Borrowed`] discriminator witness rather
10230 // than at a downstream `Cow<'static, str>`-bound consumer's
10231 // silent allocation.
10232 //
10233 // Second peer on the substrate-wide trait-idiomatic
10234 // [`std::borrow::Cow<'static, str>`] forward-projection family
10235 // to extend the axis off the top-level [`super::CaixaKind`]
10236 // enum (99c1735 owned-input, d45c409 borrowed-input) onto the
10237 // second (and second-of-two-in-M2) M2 OTP-shape closed-set
10238 // fieldless typed enum peer on the caixa surface — closes the
10239 // M2 OTP-shape tier of the campaign on the owned-input axis
10240 // (both sibling peers, `RestartStrategy` and `RestartPolicy`,
10241 // now carry the owned-input Cow<'static, str> forward
10242 // projection).
10243 for &variant in RestartPolicy::ALL {
10244 let via_trait: std::borrow::Cow<'static, str> =
10245 <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
10246 let via_method: &'static str = variant.as_str();
10247 assert_eq!(
10248 via_trait.as_ref(),
10249 via_method,
10250 "From<RestartPolicy> for Cow<'static, str> impl must \
10251 round-trip RestartPolicy::{variant:?} to the same \
10252 lifted SUPERVISOR_CHILD_RESTART_* const \
10253 RestartPolicy::as_str returns — divergence signals a \
10254 silent detour off the substrate-primitive accessor"
10255 );
10256 assert!(
10257 matches!(via_trait, std::borrow::Cow::Borrowed(_)),
10258 "From<RestartPolicy> for Cow<'static, str> impl must \
10259 land on the zero-alloc Cow::Borrowed arm on \
10260 RestartPolicy::{variant:?} — a Cow::Owned outcome \
10261 signals the projection has silently allocated where \
10262 the substrate-primitive RestartPolicy::as_str \
10263 `&'static str` return makes the borrowed arm the \
10264 type-correct projection"
10265 );
10266 let via_into: std::borrow::Cow<'static, str> = variant.into();
10267 assert_eq!(
10268 via_into.as_ref(),
10269 via_method,
10270 "Into<Cow<'static, str>>::into on \
10271 RestartPolicy::{variant:?} must byte-equal \
10272 RestartPolicy::as_str on the same input — the \
10273 blanket-derived Into shape must resolve to the same \
10274 as_str dispatch as the explicit From impl"
10275 );
10276 assert!(
10277 matches!(via_into, std::borrow::Cow::Borrowed(_)),
10278 "Into<Cow<'static, str>>::into on \
10279 RestartPolicy::{variant:?} must land on the \
10280 zero-alloc Cow::Borrowed arm — the blanket-derived \
10281 Into shape must resolve to the same Cow::Borrowed \
10282 dispatch as the explicit From impl"
10283 );
10284 }
10285 }
10286
10287 #[test]
10288 fn restart_policy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
10289 // Cross-axis partition pin: the newly lifted trait-idiomatic
10290 // `From<RestartPolicy> for std::borrow::Cow<'static, str>`
10291 // (this lift), the paired owned-input `From<RestartPolicy>
10292 // for &'static str` (9fb37d0), and the paired owned-input
10293 // `From<RestartPolicy> for String` (7851725) forward
10294 // projections must resolve identically on every arm, locking
10295 // the three return-shape paths together by construction so any
10296 // future detour trips at caixa-core test time. Also byte-parity
10297 // witness against the sibling [`ToString::to_string`] surface
10298 // routed through [`std::fmt::Display`] — every owned-heap-
10299 // string path (the `Cow::Owned` promotion of this axis's
10300 // `.into_owned()`, `From<RestartPolicy> for String`, and
10301 // `.to_string()`) resolves to the same lifted
10302 // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const per arm.
10303 //
10304 // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
10305 // witness over [`super::RestartPolicy::ALL`] that
10306 // materializes the three-arm accept-set through the
10307 // [`std::borrow::Cow<'static, str>`] axis alone — the exact
10308 // shape a future `axum::response::IntoResponse` per-policy
10309 // rejection-body composer, a future M4 admission-webhook
10310 // per-policy rejection-reason emitter whose typing rules out
10311 // the sibling [`AsRef<str>`] borrowed return, or a future
10312 // substrate-wide per-policy diagnostic surface that binds
10313 // through a [`Cow<'static, str>`] boundary reaches through.
10314 // The pipe witness also pins the zero-alloc discipline: every
10315 // element in the collected vector satisfies the
10316 // [`std::borrow::Cow::Borrowed`] arm predicate, so a future
10317 // accidental silent-allocation regression on the pipe's
10318 // iteration axis is a caixa-core-test-time failure. Peer of
10319 // the first-mover
10320 // [`restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
10321 // (7dd28b3) on the sibling M2 OTP-shape sibling-restart axis
10322 // — closes the whole owned-input `Cow<'static, str>` +
10323 // paired `{&'static str, String}` cross-axis-parity corner on
10324 // both M2 OTP-shape sibling peers.
10325 for &variant in RestartPolicy::ALL {
10326 let via_cow: std::borrow::Cow<'static, str> =
10327 <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
10328 let via_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
10329 let via_string: String = <String as From<RestartPolicy>>::from(variant);
10330 assert_eq!(
10331 via_cow.as_ref(),
10332 via_static,
10333 "From<RestartPolicy> for Cow<'static, str> and \
10334 From<RestartPolicy> for &'static str must resolve \
10335 identically on RestartPolicy::{variant:?} — \
10336 divergence signals the Cow<'static, str> and \
10337 &'static str return-shape paths have drifted onto \
10338 different emit-sets"
10339 );
10340 assert_eq!(
10341 via_cow.as_ref(),
10342 via_string.as_str(),
10343 "From<RestartPolicy> for Cow<'static, str> and \
10344 From<RestartPolicy> for String must resolve \
10345 identically on RestartPolicy::{variant:?} — \
10346 divergence signals the Cow<'static, str> and String \
10347 return-shape paths have drifted onto different \
10348 emit-sets"
10349 );
10350 let via_to_string: String = variant.to_string();
10351 assert_eq!(
10352 via_cow.as_ref(),
10353 via_to_string.as_str(),
10354 "From<RestartPolicy> for Cow<'static, str> must \
10355 byte-equal RestartPolicy::to_string on \
10356 RestartPolicy::{variant:?} — divergence signals the \
10357 trait-idiomatic Cow<'static, str> forward-projection \
10358 axis and the ToString-through-Display axis have \
10359 drifted onto different emit-sets"
10360 );
10361 }
10362 let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
10363 .iter()
10364 .copied()
10365 .map(std::borrow::Cow::from)
10366 .collect();
10367 let via_method: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
10368 .iter()
10369 .map(|p| std::borrow::Cow::Borrowed(p.as_str()))
10370 .collect();
10371 assert_eq!(
10372 via_iter, via_method,
10373 "`.iter().copied().map(Cow::from)` over \
10374 RestartPolicy::ALL must byte-equal `.iter().map(|p| \
10375 Cow::Borrowed(p.as_str()))` on every arm — the \
10376 trait-idiomatic `From<RestartPolicy> for Cow<'static, \
10377 str>` axis is what makes the `Cow::from` composition \
10378 route through the substrate-primitive \
10379 `RestartPolicy::as_str` accessor with the zero-alloc \
10380 Cow::Borrowed arm by construction, rather than a \
10381 per-call-site `Cow::Owned(policy.to_string())` \
10382 allocation"
10383 );
10384 for cow in &via_iter {
10385 assert!(
10386 matches!(cow, std::borrow::Cow::Borrowed(_)),
10387 "every element of the \
10388 .iter().copied().map(Cow::from) pipe over \
10389 RestartPolicy::ALL must land on the zero-alloc \
10390 Cow::Borrowed arm — a Cow::Owned outcome on any arm \
10391 signals the pipe's iteration axis has silently \
10392 allocated where the substrate-primitive \
10393 RestartPolicy::as_str `&'static str` return makes \
10394 the borrowed arm the type-correct projection"
10395 );
10396 }
10397 }
10398
10399 #[test]
10400 fn restart_policy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
10401 // Fail-before-pass-after byte-parity pin on the newly lifted
10402 // `impl From<&RestartPolicy> for std::borrow::Cow<'static, str>` —
10403 // asserts the borrowed-input standard-library trait impl and
10404 // the substrate-primitive [`super::RestartPolicy::as_str`]
10405 // `pub const fn` accessor resolve to the same three-arm emit-
10406 // set across every arm the exhaustive
10407 // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
10408 // standard library does not carry a blanket
10409 // `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor a
10410 // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
10411 // the borrowed-input `Cow<'static, str>` forward-projection
10412 // axis is a distinct trait-idiomatic surface that a
10413 // `let key: Cow<'static, str> = (&policy).into();`-shaped
10414 // call site or a
10415 // `RestartPolicy::ALL.iter().map(Cow::from)`-shaped pipe
10416 // reaches through this impl and no other — the paired owned-
10417 // input `From<RestartPolicy> for Cow<'static, str>` impl
10418 // (0612398) forces every borrowed-input call site through an
10419 // explicit `Copy` deref (`Cow::from(*policy)`) or a
10420 // `Cow::Borrowed(policy.as_str())` open-code whose type
10421 // bounds have no compile-time link back to the substrate
10422 // primitive.
10423 //
10424 // Also asserts the projection lands on the zero-alloc
10425 // [`std::borrow::Cow::Borrowed`] arm (not the
10426 // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
10427 // [`super::RestartPolicy::as_str`] accessor's `&'static str`
10428 // return lifetime by construction makes the borrowed arm the
10429 // type-correct projection with no runtime allocation on the
10430 // borrowed-input surface just as on the paired owned-input
10431 // surface.
10432 //
10433 // Closes the `{Self, &Self}` input-shape corner on the M2
10434 // OTP-shape per-child-restart [`Cow<'static, str>`] axis on
10435 // the second-of-two-in-M2 closed-set fieldless typed enum peer
10436 // on the caixa surface (`:supervisor :children :restart`),
10437 // exactly as d45c409 closed it on the top-level
10438 // [`super::CaixaKind`] one commit after the owning half
10439 // (99c1735) landed and as 9b3e4b3 closed it on the sibling
10440 // M2 OTP-shape [`super::RestartStrategy`] one commit after
10441 // (7dd28b3) landed. This lift closes the whole M2 OTP-shape
10442 // tier of the substrate-wide Cow<'static, str> forward-
10443 // projection campaign on both input-shape corners
10444 // ({Self, &Self}) of both M2 OTP-shape sibling peers.
10445 for &variant in RestartPolicy::ALL {
10446 let via_trait: std::borrow::Cow<'static, str> =
10447 <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
10448 let via_method: &'static str = variant.as_str();
10449 assert_eq!(
10450 via_trait.as_ref(),
10451 via_method,
10452 "From<&RestartPolicy> for Cow<'static, str> impl must \
10453 round-trip &RestartPolicy::{variant:?} to the same \
10454 lifted SUPERVISOR_CHILD_RESTART_* const \
10455 RestartPolicy::as_str returns — divergence signals a \
10456 silent detour off the substrate-primitive accessor"
10457 );
10458 assert!(
10459 matches!(via_trait, std::borrow::Cow::Borrowed(_)),
10460 "From<&RestartPolicy> for Cow<'static, str> impl must \
10461 land on the zero-alloc Cow::Borrowed arm on \
10462 &RestartPolicy::{variant:?} — a Cow::Owned outcome \
10463 signals the projection has silently allocated where \
10464 the substrate-primitive RestartPolicy::as_str \
10465 `&'static str` return makes the borrowed arm the \
10466 type-correct projection"
10467 );
10468 let via_into: std::borrow::Cow<'static, str> = (&variant).into();
10469 assert_eq!(
10470 via_into.as_ref(),
10471 via_method,
10472 "Into<Cow<'static, str>>::into on \
10473 &RestartPolicy::{variant:?} must byte-equal \
10474 RestartPolicy::as_str on the same input — the \
10475 blanket-derived Into shape must resolve to the same \
10476 as_str dispatch as the explicit From impl"
10477 );
10478 assert!(
10479 matches!(via_into, std::borrow::Cow::Borrowed(_)),
10480 "Into<Cow<'static, str>>::into on \
10481 &RestartPolicy::{variant:?} must land on the \
10482 zero-alloc Cow::Borrowed arm — the blanket-derived \
10483 Into shape must resolve to the same Cow::Borrowed \
10484 dispatch as the explicit From impl"
10485 );
10486 }
10487 }
10488
10489 #[test]
10490 fn restart_policy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
10491 // Cross-axis partition pin: the newly lifted trait-idiomatic
10492 // borrowed-input `From<&RestartPolicy> for
10493 // std::borrow::Cow<'static, str>` (this lift), the paired
10494 // owned-input `From<RestartPolicy> for
10495 // std::borrow::Cow<'static, str>` (0612398), the paired
10496 // borrowed-input owned-`&'static str` `From<&RestartPolicy>
10497 // for &'static str`, and the paired borrowed-input owned-
10498 // `String` `From<&RestartPolicy> for String` must resolve
10499 // identically on every arm, locking the four
10500 // return-shape × input-shape paths together by construction so
10501 // any future detour trips at caixa-core test time. Also byte-
10502 // parity witness against the sibling [`ToString::to_string`]
10503 // surface routed through [`std::fmt::Display`] — every owned-
10504 // heap-string path (this axis's `.into_owned()` promotion, the
10505 // paired [`From<&RestartPolicy> for String`], and
10506 // `.to_string()`) resolves to the same lifted
10507 // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const per arm.
10508 //
10509 // Then a `.iter().map(std::borrow::Cow::from)` pipe witness
10510 // over [`super::RestartPolicy::ALL`] — whose iterator yields
10511 // `&RestartPolicy` by construction, so the borrowed-input
10512 // [`Cow<'static, str>`] axis is what routes the pipe through
10513 // the substrate-primitive [`super::RestartPolicy::as_str`]
10514 // accessor without a spurious [`Copy`] deref (which would only
10515 // be reachable through the owned-input
10516 // [`From<RestartPolicy> for Cow<'static, str>`] axis by first
10517 // calling `.copied()` on the iterator). The pipe witness also
10518 // pins the zero-alloc discipline: every element in the
10519 // collected vector satisfies the [`std::borrow::Cow::Borrowed`]
10520 // arm predicate, so a future accidental silent-allocation
10521 // regression on the pipe's iteration axis is a caixa-core-
10522 // test-time failure. Peer of the sibling
10523 // [`restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
10524 // (9b3e4b3) on the M2 OTP-shape sibling-restart axis — closes
10525 // the whole borrowed-input `Cow<'static, str>` +
10526 // paired `{&'static str, String}` cross-axis-parity corner on
10527 // both M2 OTP-shape sibling peers.
10528 for &policy in RestartPolicy::ALL {
10529 let borrowed_cow: std::borrow::Cow<'static, str> =
10530 <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&policy);
10531 let owned_cow: std::borrow::Cow<'static, str> =
10532 <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(policy);
10533 let borrowed_static: &'static str =
10534 <&'static str as From<&RestartPolicy>>::from(&policy);
10535 let borrowed_string: String = <String as From<&RestartPolicy>>::from(&policy);
10536 assert_eq!(
10537 borrowed_cow, owned_cow,
10538 "From<&RestartPolicy> for Cow<'static, str> and \
10539 From<RestartPolicy> for Cow<'static, str> must \
10540 resolve identically on RestartPolicy::{policy:?} — \
10541 divergence signals the borrowed-input and owned-input \
10542 Cow<'static, str> forward-projection input-shape \
10543 paths have drifted onto different emit-sets"
10544 );
10545 assert_eq!(
10546 borrowed_cow.as_ref(),
10547 borrowed_static,
10548 "From<&RestartPolicy> for Cow<'static, str> and \
10549 From<&RestartPolicy> for &'static str must resolve \
10550 identically on RestartPolicy::{policy:?} — \
10551 divergence signals the borrowed-input Cow<'static, \
10552 str> and &'static str return-shape paths have drifted \
10553 onto different emit-sets"
10554 );
10555 assert_eq!(
10556 borrowed_cow.as_ref(),
10557 borrowed_string.as_str(),
10558 "From<&RestartPolicy> for Cow<'static, str> and \
10559 From<&RestartPolicy> for String must resolve \
10560 identically on RestartPolicy::{policy:?} — \
10561 divergence signals the borrowed-input Cow<'static, \
10562 str> and owned-`String` return-shape paths have \
10563 drifted onto different emit-sets"
10564 );
10565 let via_to_string: String = policy.to_string();
10566 assert_eq!(
10567 borrowed_cow.as_ref(),
10568 via_to_string.as_str(),
10569 "From<&RestartPolicy> for Cow<'static, str> must \
10570 byte-equal RestartPolicy::to_string on \
10571 RestartPolicy::{policy:?} — divergence signals \
10572 the trait-idiomatic borrowed-input Cow<'static, str> \
10573 forward-projection axis and the ToString-through-\
10574 Display axis have drifted onto different emit-sets"
10575 );
10576 }
10577 let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
10578 .iter()
10579 .map(std::borrow::Cow::from)
10580 .collect();
10581 let via_method: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
10582 .iter()
10583 .map(|p| std::borrow::Cow::Borrowed(p.as_str()))
10584 .collect();
10585 assert_eq!(
10586 via_iter, via_method,
10587 "`.iter().map(Cow::from)` over RestartPolicy::ALL — a \
10588 call site whose iteration axis holds `&RestartPolicy` \
10589 by construction — must byte-equal `.iter().map(|p| \
10590 Cow::Borrowed(p.as_str()))` on every arm — the borrowed-\
10591 input Cow<'static, str> `From<&RestartPolicy> for \
10592 Cow<'static, str>` axis is what makes the `Cow::from` \
10593 composition route through the substrate-primitive \
10594 `RestartPolicy::as_str` accessor with the zero-alloc \
10595 Cow::Borrowed arm by construction and without a spurious \
10596 `Copy` deref (which would only be reachable through the \
10597 owned-input `From<RestartPolicy> for Cow<'static, str>` \
10598 axis by first calling `.copied()` on the iterator)"
10599 );
10600 for cow in &via_iter {
10601 assert!(
10602 matches!(cow, std::borrow::Cow::Borrowed(_)),
10603 "every element of the .iter().map(Cow::from) pipe \
10604 over RestartPolicy::ALL must land on the zero-\
10605 alloc Cow::Borrowed arm — a Cow::Owned outcome on \
10606 any arm signals the pipe's iteration axis has \
10607 silently allocated where the substrate-primitive \
10608 RestartPolicy::as_str `&'static str` return makes \
10609 the borrowed arm the type-correct projection"
10610 );
10611 }
10612 }
10613
10614 #[test]
10615 fn restart_policy_from_into_box_str_routes_through_as_str_accessor() {
10616 // Fail-before-pass-after byte-parity pin on the newly lifted
10617 // `impl From<RestartPolicy> for Box<str>` — asserts the
10618 // owned-input standard-library trait impl and the
10619 // substrate-primitive [`super::RestartPolicy::as_str`]
10620 // `pub const fn` accessor resolve to the same three-arm emit-
10621 // set across every arm the exhaustive
10622 // [`super::RestartPolicy::ALL`] slice enumerates. Extends the
10623 // substrate-wide `Box<str>` forward-projection campaign tier
10624 // opened one commit prior (69ef45c) on the paired sibling-
10625 // restart [`RestartStrategy`] onto the second (and third-and-
10626 // final) M2 OTP-shape closed-set fieldless typed enum peer on
10627 // the caixa surface (`:children :restart`), immediately after
10628 // the paired `Cow<'static, str>` axis (0612398 / b4dc55c)
10629 // closed the
10630 // `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
10631 // 2×3 corner on this enum. Rust's standard library carries
10632 // `impl From<&str> for Box<str>` and
10633 // `impl From<String> for Box<str>` but no blanket
10634 // `impl<T: AsRef<str>> From<T> for Box<str>`, so this axis is
10635 // a distinct trait-idiomatic surface that a
10636 // `let key: Box<str> = policy.into();`-shaped call site
10637 // reaches through this impl and no other — a paired
10638 // `Box::from(policy.as_str())` open-code has no compile-time
10639 // link back to the substrate primitive. Peer of the sibling
10640 // [`restart_strategy_from_into_box_str_routes_through_as_str_accessor`]
10641 // (69ef45c) — extends the trait-idiomatic owned-input
10642 // [`Box<str>`] forward-projection axis onto the third and
10643 // final M2-OTP-shape closed-set typed enum on the caixa
10644 // surface.
10645 for &variant in RestartPolicy::ALL {
10646 let via_trait: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
10647 let via_method: &'static str = variant.as_str();
10648 assert_eq!(
10649 via_trait.as_ref(),
10650 via_method,
10651 "From<RestartPolicy> for Box<str> impl must round-\
10652 trip RestartPolicy::{variant:?} to the same lifted \
10653 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
10654 returns — divergence signals a silent detour off the \
10655 substrate-primitive accessor"
10656 );
10657 let via_into: Box<str> = variant.into();
10658 assert_eq!(
10659 via_into.as_ref(),
10660 via_method,
10661 "Into<Box<str>>::into on RestartPolicy::{variant:?} \
10662 must byte-equal RestartPolicy::as_str on the same \
10663 input — the blanket-derived Into shape must resolve \
10664 to the same as_str dispatch as the explicit From impl"
10665 );
10666 }
10667 }
10668
10669 #[test]
10670 fn restart_policy_from_borrowed_into_box_str_routes_through_as_str_accessor() {
10671 // Fail-before-pass-after byte-parity pin on the newly lifted
10672 // `impl From<&RestartPolicy> for Box<str>` — asserts the
10673 // borrowed-input standard-library trait impl and the
10674 // substrate-primitive [`super::RestartPolicy::as_str`]
10675 // `pub const fn` accessor resolve to the same three-arm emit-
10676 // set across every arm the exhaustive
10677 // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
10678 // standard library does not carry a blanket
10679 // `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
10680 // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
10681 // so the borrowed-input `Box<str>` forward-projection axis
10682 // is a distinct trait-idiomatic surface that a
10683 // `let key: Box<str> = (&policy).into();`-shaped call site
10684 // or a `RestartPolicy::ALL.iter().map(Box::<str>::from)`-
10685 // shaped pipe reaches through this impl and no other — the
10686 // paired owned-input `From<RestartPolicy> for Box<str>`
10687 // impl (0a1b313) forces every borrowed-input call site
10688 // through an explicit `Copy` deref
10689 // (`Box::<str>::from((*policy).as_str())`) or a
10690 // `Box::<str>::from(policy.as_str())` open-code whose
10691 // type bounds have no compile-time link back to the
10692 // substrate primitive.
10693 //
10694 // Fourth (and closing) peer on the substrate-wide trait-
10695 // idiomatic [`Box<str>`] forward-projection family on the
10696 // M2 OTP-shape tier — closes the `{Self, &Self}` input-
10697 // shape corner of the [`Box<str>`] axis on the second (and
10698 // third-and-final) M2 OTP-shape closed-set fieldless typed
10699 // enum peer on the caixa surface (`:children :restart`),
10700 // exactly as b4dc55c closed the paired [`Cow<'static, str>`]
10701 // axis one commit after its owning half (0612398) landed
10702 // on this enum. Every remaining closed-set fieldless typed
10703 // enum peer on the M3 mesh-shape / outside-M3 caixa-core /
10704 // render-side / outside-caixa-core tiers is a future
10705 // target of the campaign.
10706 //
10707 // Also byte-parity witness against the paired owned-input
10708 // [`From<RestartPolicy> for Box<str>`] and the sibling
10709 // borrowed-input [`From<&RestartPolicy> for &'static str`],
10710 // [`From<&RestartPolicy> for String`], and
10711 // [`From<&RestartPolicy> for Cow<'static, str>`]
10712 // return-shape axes — locking the four
10713 // return-shape × input-shape paths together by construction
10714 // so any future detour trips at caixa-core test time. Then a
10715 // `.iter().map(Box::<str>::from)` pipe witness over
10716 // [`super::RestartPolicy::ALL`] — whose iterator yields
10717 // `&RestartPolicy` by construction, so the borrowed-input
10718 // [`Box<str>`] axis is what routes the pipe through the
10719 // substrate-primitive [`super::RestartPolicy::as_str`]
10720 // accessor without a spurious [`Copy`] deref (which would
10721 // only be reachable through the owned-input
10722 // [`From<RestartPolicy> for Box<str>`] axis by first
10723 // calling `.copied()` on the iterator).
10724 for &variant in RestartPolicy::ALL {
10725 let via_trait: Box<str> = <Box<str> as From<&RestartPolicy>>::from(&variant);
10726 let via_method: &'static str = variant.as_str();
10727 assert_eq!(
10728 via_trait.as_ref(),
10729 via_method,
10730 "From<&RestartPolicy> for Box<str> impl must round-\
10731 trip &RestartPolicy::{variant:?} to the same lifted \
10732 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
10733 returns — divergence signals a silent detour off the \
10734 substrate-primitive accessor"
10735 );
10736 let via_into: Box<str> = (&variant).into();
10737 assert_eq!(
10738 via_into.as_ref(),
10739 via_method,
10740 "Into<Box<str>>::into on &RestartPolicy::{variant:?} \
10741 must byte-equal RestartPolicy::as_str on the same \
10742 input — the blanket-derived Into shape must resolve \
10743 to the same as_str dispatch as the explicit From impl"
10744 );
10745 let owned_box: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
10746 assert_eq!(
10747 via_trait, owned_box,
10748 "From<&RestartPolicy> for Box<str> and \
10749 From<RestartPolicy> for Box<str> must resolve \
10750 identically on RestartPolicy::{variant:?} — \
10751 divergence signals the borrowed-input and owned-input \
10752 Box<str> forward-projection input-shape paths have \
10753 drifted onto different emit-sets"
10754 );
10755 let borrowed_static: &'static str =
10756 <&'static str as From<&RestartPolicy>>::from(&variant);
10757 assert_eq!(
10758 via_trait.as_ref(),
10759 borrowed_static,
10760 "From<&RestartPolicy> for Box<str> and \
10761 From<&RestartPolicy> for &'static str must resolve \
10762 identically on RestartPolicy::{variant:?} — \
10763 divergence signals the borrowed-input Box<str> and \
10764 &'static str return-shape paths have drifted onto \
10765 different emit-sets"
10766 );
10767 let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
10768 assert_eq!(
10769 via_trait.as_ref(),
10770 borrowed_string.as_str(),
10771 "From<&RestartPolicy> for Box<str> and \
10772 From<&RestartPolicy> for String must resolve \
10773 identically on RestartPolicy::{variant:?} — \
10774 divergence signals the borrowed-input Box<str> and \
10775 owned-`String` return-shape paths have drifted onto \
10776 different emit-sets"
10777 );
10778 let borrowed_cow: std::borrow::Cow<'static, str> =
10779 <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
10780 assert_eq!(
10781 via_trait.as_ref(),
10782 borrowed_cow.as_ref(),
10783 "From<&RestartPolicy> for Box<str> and \
10784 From<&RestartPolicy> for Cow<'static, str> must \
10785 resolve identically on RestartPolicy::{variant:?} — \
10786 divergence signals the borrowed-input Box<str> and \
10787 Cow<'static, str> return-shape paths have drifted \
10788 onto different emit-sets"
10789 );
10790 }
10791 let via_iter: Vec<Box<str>> = RestartPolicy::ALL.iter().map(Box::<str>::from).collect();
10792 let via_method: Vec<Box<str>> = RestartPolicy::ALL
10793 .iter()
10794 .map(|p| Box::<str>::from(p.as_str()))
10795 .collect();
10796 assert_eq!(
10797 via_iter, via_method,
10798 "`.iter().map(Box::<str>::from)` over \
10799 RestartPolicy::ALL — a call site whose iteration axis \
10800 holds `&RestartPolicy` by construction — must byte-\
10801 equal `.iter().map(|p| Box::<str>::from(p.as_str()))` \
10802 on every arm — the borrowed-input Box<str> \
10803 `From<&RestartPolicy> for Box<str>` axis is what \
10804 makes the `Box::<str>::from` composition route through \
10805 the substrate-primitive `RestartPolicy::as_str` \
10806 accessor without a spurious `Copy` deref (which would \
10807 only be reachable through the owned-input \
10808 `From<RestartPolicy> for Box<str>` axis by first \
10809 calling `.copied()` on the iterator)"
10810 );
10811 }
10812
10813 // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_RESTART_* identity ─
10814
10815 #[test]
10816 fn restart_policy_variants_serialize_to_lifted_scalar_values() {
10817 // The fail-before-pass-after pin: pre-lift there was no
10818 // single-source binding between the [`RestartPolicy`] variant
10819 // name the un-`rename`d `Serialize` derive emits under
10820 // [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
10821 // byte-string every downstream cluster-side dispatcher (the
10822 // future wasm-operator's per-child post-exit restart-decision
10823 // branch, the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
10824 // materializer's admission-time enum-arm bind, the
10825 // `caixa-operator`'s hierarchical reconciliation scheduler's
10826 // per-child-policy fan-out) probes verbatim. A future
10827 // `#[serde(rename_all = "kebab-case")]` attribute on the enum —
10828 // or a per-variant `#[serde(rename = "…")]` override, or a
10829 // variant rename in the source — would silently rebrand the
10830 // emitted scalar under one spelling while every downstream
10831 // dispatcher still probed the other, with the failure surfacing
10832 // at the operator's reconcile posture (children coming up under
10833 // the `default()` `Permanent` arm rather than the typed slot's
10834 // declared policy — a `:temporary` `oneShot` child would be
10835 // restarted on clean exit, treating the successful-completion
10836 // signal as failure and re-running the completion-terminal
10837 // one-shot indefinitely; a `:transient` child that clean-exited
10838 // would be restarted, masking the clean-completion contract)
10839 // far from the source rebrand commit and with no field naming
10840 // the drift. Pinning the two paths (the `Serialize` derive's
10841 // serialized string AND the [`RestartPolicy::as_str`] helper)
10842 // to the same three lifted
10843 // [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
10844 // [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
10845 // [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
10846 // byte-strings makes any future drift on either endpoint fail
10847 // here at caixa-core build time. Peer of the sibling
10848 // [`restart_strategy_variants_serialize_to_lifted_scalar_values`]
10849 // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
10850 // and the M3
10851 // `placement_strategy_variants_serialize_to_lifted_scalar_values`
10852 // (3f0e21c) on the per-Aplicacao distribution-strategy axis —
10853 // same three-path-convergence discipline, extended to close the
10854 // third OTP-shaped closed-enum discriminator axis on the caixa
10855 // typed surface (per-child restart-decision policy).
10856 for (variant, expected) in [
10857 (
10858 RestartPolicy::Permanent,
10859 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
10860 ),
10861 (
10862 RestartPolicy::Temporary,
10863 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
10864 ),
10865 (
10866 RestartPolicy::Transient,
10867 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
10868 ),
10869 ] {
10870 let json = serde_json::to_string(&variant).unwrap();
10871 assert_eq!(
10872 json,
10873 format!("\"{expected}\""),
10874 "RestartPolicy::{variant:?} must serialize to {expected:?}"
10875 );
10876 assert_eq!(
10877 variant.as_str(),
10878 expected,
10879 "RestartPolicy::{variant:?}.as_str() must return the lifted \
10880 SUPERVISOR_CHILD_RESTART_* constant"
10881 );
10882 }
10883 }
10884
10885 #[test]
10886 fn supervisor_child_restart_consts_are_pairwise_distinct() {
10887 // Cross-arm drift-detection pin: a future collapse of two
10888 // canonical variant byte-strings onto the same value (e.g. an
10889 // accidental copy-paste flip of `SUPERVISOR_CHILD_RESTART_TRANSIENT`
10890 // to also read `"Permanent"`) would silently reroute every
10891 // downstream operator's per-child-policy dispatch onto the
10892 // sibling arm's reconcile branch and pass every propagation-probe
10893 // test that expected only the stale arm's value — a `:transient`
10894 // child would come up under the `:permanent` restart-decision
10895 // posture on every subsequent clean exit, so a completion-terminal
10896 // child would be restarted indefinitely against its declared
10897 // policy. Peer of the sibling
10898 // [`supervisor_estrategia_consts_are_pairwise_distinct`]
10899 // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
10900 // and the four-way distinct pin
10901 // `supervisor_key_consts_are_pairwise_distinct` (40cc4e5) on the
10902 // top-level `SUPERVISOR_KEY_*` axis.
10903 let all = [
10904 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
10905 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
10906 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
10907 ];
10908 for (i, a) in all.iter().enumerate() {
10909 for (j, b) in all.iter().enumerate() {
10910 if i != j {
10911 assert_ne!(
10912 a, b,
10913 "SUPERVISOR_CHILD_RESTART_* consts must be pairwise distinct \
10914 — got duplicate {a:?} at indices {i} and {j}",
10915 );
10916 }
10917 }
10918 }
10919 }
10920
10921 #[test]
10922 fn restart_policy_display_routes_through_as_str_helper() {
10923 // The fail-before-pass-after pin on the first half of the
10924 // three-path convergence: pre-convergence [`RestartPolicy`]
10925 // carried a [`std::fmt::Display`] surface via its
10926 // `#[discriminant(also_display)]` gen-platform derive route,
10927 // which arrived kebab-case as `"permanent"` / `"temporary"`
10928 // / `"transient"` on this three-arm enum (whose variant
10929 // names each collapse to their own lowercase form under the
10930 // kebab-case transform) while the wire format ran as
10931 // PascalCase `"Permanent"` / `"Temporary"` / `"Transient"`
10932 // through the un-`rename`d serde derive. Every consumer
10933 // reaching for a policy byte-string past the wire format had
10934 // to pick between three paths ([`RestartPolicy::as_str`],
10935 // the `Serialize` derive's serialized string, or
10936 // `format!("{v}")` on the discriminant-Display route), any
10937 // two of which a future variant rename or
10938 // `#[serde(rename_all = "kebab-case")]` attribute would
10939 // silently desynchronize. Wiring [`std::fmt::Display`]
10940 // through [`RestartPolicy::as_str`] closes the third path:
10941 // every `format!("{v}")` call reaches the same lifted
10942 // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the
10943 // wire format and the [`RestartPolicy::as_str`] helper
10944 // already route through, so a future variant rename lands at
10945 // exactly one place. Pin the routing here so a future
10946 // `impl std::fmt::Display for RestartPolicy`
10947 // reimplementation that hand-rolls the arms instead of
10948 // delegating to [`RestartPolicy::as_str`] fails at
10949 // caixa-core build time. Peer of the sibling
10950 // [`restart_strategy_display_routes_through_as_str_helper`]
10951 // on the per-supervisor sibling-restart-strategy axis and
10952 // the M3
10953 // `placement_strategy_display_routes_through_as_str_helper`
10954 // (cc8f749) — the third of three OTP-shape closed-enum
10955 // discriminator axes on the caixa typed surface now
10956 // converged onto the same three-path
10957 // (Display → as_str → lifted const) discipline.
10958 for variant in [
10959 RestartPolicy::Permanent,
10960 RestartPolicy::Temporary,
10961 RestartPolicy::Transient,
10962 ] {
10963 assert_eq!(
10964 variant.to_string(),
10965 variant.as_str(),
10966 "RestartPolicy::{variant:?} Display must route through \
10967 RestartPolicy::as_str (single source of truth: the lifted \
10968 SUPERVISOR_CHILD_RESTART_* const the wire format also emits)"
10969 );
10970 }
10971 }
10972
10973 #[test]
10974 fn restart_policy_display_matches_serialized_wire_byte_string() {
10975 // The fail-before-pass-after pin on the second half of the
10976 // three-path convergence: `Display` (user-facing text) agrees
10977 // byte-for-byte with the `Serialize` derive's wire format
10978 // (canonical camelCase-schema `SUPERVISOR_CHILD_KEY_RESTART`
10979 // scalar) on every variant. Pre-convergence the two paths
10980 // were structurally independent — a future
10981 // `#[serde(rename_all = "kebab-case")]` attribute on the
10982 // enum would silently rebrand the emitted wire scalar
10983 // (`permanent`, `temporary`, `transient`) while every
10984 // consumer that pretty-prints the policy (the future
10985 // wasm-operator's per-child post-exit restart-decision
10986 // diagnostic line, the future `feira app graph` per-child
10987 // restart column, the future M4
10988 // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
10989 // per-child admission-webhook rejection body) would still
10990 // emit the PascalCase form the `as_str` / `Display` route
10991 // returns, with the mismatch surfacing at consumer parse
10992 // time / operator dispatch time far from the source rebrand
10993 // commit. Pin the two paths byte-for-byte here so any future
10994 // serde-attribute or variant-rename drift is a
10995 // caixa-core-build-time test failure at this call, not a
10996 // silent per-consumer dispatch miss. Peer of the sibling
10997 // [`restart_strategy_display_matches_serialized_wire_byte_string`]
10998 // on the per-supervisor sibling-restart-strategy axis and
10999 // the M3
11000 // `placement_strategy_display_matches_serialized_wire_byte_string`
11001 // (cc8f749).
11002 for variant in [
11003 RestartPolicy::Permanent,
11004 RestartPolicy::Temporary,
11005 RestartPolicy::Transient,
11006 ] {
11007 let wire = serde_json::to_string(&variant).unwrap();
11008 let unquoted = wire
11009 .strip_prefix('"')
11010 .and_then(|s| s.strip_suffix('"'))
11011 .expect("serialized RestartPolicy is a JSON string");
11012 assert_eq!(
11013 variant.to_string(),
11014 unquoted,
11015 "RestartPolicy::{variant:?} Display byte-string must match the \
11016 Serialize derive's wire byte-string (three-path convergence: \
11017 Display + as_str + Serialize all resolve to the same \
11018 SUPERVISOR_CHILD_RESTART_* const)"
11019 );
11020 }
11021 }
11022
11023 #[test]
11024 fn restart_policy_as_ref_str_routes_through_as_str_accessor() {
11025 // Fail-before-pass-after byte-parity pin on the lifted
11026 // `impl AsRef<str> for RestartPolicy` — asserts the
11027 // standard-library trait impl and the substrate-primitive
11028 // [`RestartPolicy::as_str`] `pub const fn` accessor resolve
11029 // to the same `&str` per instance across the three-arm
11030 // closed set, so any future silent detour that routes the
11031 // impl through a divergent projection (a per-arm inline
11032 // `match self { RestartPolicy::Permanent => "Permanent", … }`
11033 // re-inlining that opens a compile-time link to the un-lifted
11034 // arm-literal, a swap onto the kebab-case
11035 // [`gen_platform::Discriminant`] catalog identity that would
11036 // collide the wire axis with the dispatcher-catalog axis) trips
11037 // at caixa-core test time under `PartialEq` rather than at a
11038 // downstream `impl AsRef<str>`-bound consumer's silent split.
11039 // Sweeps every one of the three arms
11040 // [`RestartPolicy::ALL`] carries so no arm's projection is
11041 // covered only by the sibling wire-format `Serialize` derive
11042 // path. Peer of the sibling
11043 // [`restart_strategy_as_ref_str_routes_through_as_str_accessor`]
11044 // (63eb1a4) on the paired per-supervisor sibling-restart-
11045 // strategy axis and the [`crate::CaixaVersion`]
11046 // `AsRef<str>`-byte-parity pin (16d5c7e) on the paired
11047 // top-level `:versao` typed newtype — the three pins together
11048 // cover the substrate primitive's `AsRef<str>` projection axis
11049 // on the paired newtype + M2 closed-set-typed-enum surface.
11050 for &variant in RestartPolicy::ALL {
11051 assert_eq!(
11052 <RestartPolicy as AsRef<str>>::as_ref(&variant),
11053 variant.as_str(),
11054 "AsRef<str> impl on RestartPolicy::{variant:?} must \
11055 byte-equal RestartPolicy::as_str on the same instance \
11056 — divergence signals a silent detour off the substrate-\
11057 primitive accessor"
11058 );
11059 }
11060 }
11061
11062 #[test]
11063 fn restart_policy_as_ref_str_routes_through_display_via_shared_accessor() {
11064 // Fail-before-pass-after byte-parity pin on the three-path
11065 // convergence discipline the M2 per-child-restart-policy
11066 // primitive now carries on the `&str`-projection axis:
11067 // `<RestartPolicy as AsRef<str>>::as_ref(&v)` (the newly
11068 // lifted impl), `format!("{v}")` (the pre-existing
11069 // [`fmt::Display`] impl), and `v.as_str()` (the substrate-
11070 // primitive `pub const fn` accessor both trait impls delegate
11071 // through) must resolve to the same byte-string on every
11072 // instance across the three-arm closed set. Refuses any future
11073 // divergence between the two trait impls (a stray
11074 // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
11075 // rather than delegating through the shared accessor; a
11076 // hypothetical `AsRef<str>` rewrite that inlines a per-arm
11077 // literal cascade) that would silently split the two
11078 // projection paths of the same closed-set typed enum. Mirrors
11079 // the sibling three-path-convergence discipline the peer
11080 // [`RestartStrategy`] typed enum carries on its
11081 // `AsRef<str>` / `Display` / `as_str` triple
11082 // (supervisor.rs pin
11083 // `restart_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
11084 // 63eb1a4) and the [`crate::CaixaVersion`] typed newtype
11085 // carries on the same triple (version.rs pin
11086 // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
11087 // 16d5c7e).
11088 for &variant in RestartPolicy::ALL {
11089 let via_as_ref: &str = <RestartPolicy as AsRef<str>>::as_ref(&variant);
11090 let via_display: String = format!("{variant}");
11091 let via_accessor: &str = variant.as_str();
11092 assert_eq!(via_as_ref, via_accessor);
11093 assert_eq!(via_display, via_accessor);
11094 assert_eq!(via_as_ref, via_display.as_str());
11095 }
11096 }
11097
11098 #[test]
11099 fn restart_policy_all_enumerates_every_variant_exactly_once() {
11100 // Fail-before-pass-after pin on the [`RestartPolicy::ALL`]
11101 // exhaustive-iteration surface: every variant appears exactly
11102 // once, and the slice length matches the arm count of the
11103 // closed set. Every consumer that walks the accepted-policy
11104 // set (a future `feira supervisor --restart …` CLI-side
11105 // arg-parse's "did you mean" hint, a future M4 admission-
11106 // webhook's per-child rejection body naming the accepted-
11107 // `:restart` list, the [`RestartPolicy::from_wire`] reverse-
11108 // projection consumers that iterate the accept-set for
11109 // diagnostic rendering) reads through this slice, so a future
11110 // arm addition that grows the enum but forgets to grow
11111 // [`Self::ALL`] silently truncates every downstream consumer's
11112 // accept-set at the same pre-addition boundary — this pin
11113 // fails at caixa-core build time on the pairwise-distinct +
11114 // arm-count invariants.
11115 //
11116 // Peer of the sibling [`RestartStrategy::ALL`] (4eec29c) /
11117 // [`crate::CaixaKind::ALL`] (6b1f4fb) /
11118 // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
11119 // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
11120 // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
11121 // pins on the peer closed-set typed-enum axes.
11122 let all: &[RestartPolicy] = RestartPolicy::ALL;
11123 assert_eq!(
11124 all.len(),
11125 3,
11126 "RestartPolicy::ALL must enumerate every variant of the \
11127 three-arm closed set (Permanent, Temporary, Transient); \
11128 got {all:?}"
11129 );
11130 for (i, a) in all.iter().enumerate() {
11131 for (j, b) in all.iter().enumerate() {
11132 if i != j {
11133 assert_ne!(
11134 a, b,
11135 "RestartPolicy::ALL must carry every variant exactly \
11136 once — got duplicate {a:?} at indices {i} and {j}"
11137 );
11138 }
11139 }
11140 }
11141 for variant in [
11142 RestartPolicy::Permanent,
11143 RestartPolicy::Temporary,
11144 RestartPolicy::Transient,
11145 ] {
11146 assert!(
11147 all.contains(&variant),
11148 "RestartPolicy::ALL must contain {variant:?} — a future arm \
11149 addition that grows the enum but forgets to grow the ALL slice \
11150 silently truncates every downstream consumer's accept-set at \
11151 the pre-addition boundary"
11152 );
11153 }
11154 }
11155
11156 #[test]
11157 fn restart_policy_from_wire_accepts_every_lifted_constant() {
11158 // Fail-before-pass-after pin on the forward accept-set of the
11159 // [`RestartPolicy::from_wire`] reverse projection: every
11160 // canonical [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
11161 // constant the [`RestartPolicy::as_str`] emitter walks parses
11162 // back to its paired variant. Any future arm addition that
11163 // grows the emitter's `as_str` match but forgets to grow the
11164 // parser's `from_wire` match silently splits the two halves of
11165 // the round-trip — the wire byte-string one non-serde consumer
11166 // parses from the one the emitter wrote — with the failure
11167 // surfacing at the operator's reconcile posture (a `:temporary`
11168 // `oneShot` child restarted on clean exit, a `:transient` child
11169 // restarted after clean completion) far from the rebrand
11170 // commit. Pinning the three-arm accept-set here catches the
11171 // drift at caixa-core build time.
11172 //
11173 // Peer of the sibling [`RestartStrategy::from_wire`] (4eec29c)
11174 // + [`crate::CaixaKind::from_wire`] (2aa6d23)
11175 // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
11176 // accept-set pins on the peer closed-set typed-enum `str → Self`
11177 // axes.
11178 for (wire, expected) in [
11179 (
11180 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
11181 RestartPolicy::Permanent,
11182 ),
11183 (
11184 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
11185 RestartPolicy::Temporary,
11186 ),
11187 (
11188 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
11189 RestartPolicy::Transient,
11190 ),
11191 ] {
11192 let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
11193 panic!(
11194 "RestartPolicy::from_wire({wire:?}) must accept every \
11195 SUPERVISOR_CHILD_RESTART_* constant — got None for the \
11196 lifted canonical byte-string that RestartPolicy::{expected:?} \
11197 serializes as under SUPERVISOR_CHILD_KEY_RESTART"
11198 )
11199 });
11200 assert_eq!(
11201 parsed, expected,
11202 "RestartPolicy::from_wire({wire:?}) must return \
11203 RestartPolicy::{expected:?}; got RestartPolicy::{parsed:?}"
11204 );
11205 }
11206 }
11207
11208 #[test]
11209 fn restart_policy_from_wire_round_trips_through_as_str() {
11210 // Fail-before-pass-after pin on the closed round-trip between
11211 // the forward [`RestartPolicy::as_str`] emitter and the
11212 // reverse [`RestartPolicy::from_wire`] parser: for every
11213 // variant in [`RestartPolicy::ALL`], parsing the emitter's
11214 // output must return exactly the same variant. Any per-arm
11215 // divergence — a future arm added to `as_str` but not
11216 // `from_wire`, an accidental copy-paste flip in one but not
11217 // the other — silently splits the emit and parse halves and
11218 // the failure surfaces at consumer parse time far from the
11219 // drift site. The `ALL`-iterating shape means a future arm
11220 // addition picks up the coverage by construction.
11221 //
11222 // Peer of the sibling
11223 // [`restart_strategy_from_wire_round_trips_through_as_str`]
11224 // (4eec29c) round-trip pin on
11225 // [`RestartStrategy::from_wire`] and the M3
11226 // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
11227 // (18c7342) round-trip pin on
11228 // [`crate::aplicacao::PlacementStrategy::from_wire`].
11229 for &variant in RestartPolicy::ALL {
11230 let wire = variant.as_str();
11231 let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
11232 panic!(
11233 "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
11234 must be Some({variant:?}) — the two halves of the round-trip \
11235 dispatch on the same lifted SUPERVISOR_CHILD_RESTART_* consts; \
11236 got None on wire byte-string {wire:?}"
11237 )
11238 });
11239 assert_eq!(
11240 parsed, variant,
11241 "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
11242 must round-trip to the same variant; got {parsed:?}"
11243 );
11244 }
11245 }
11246
11247 #[test]
11248 fn restart_policy_from_wire_rejects_unknown_byte_strings() {
11249 // Fail-before-pass-after pin on the closed-set refusal
11250 // discipline of [`RestartPolicy::from_wire`]: every
11251 // byte-string outside the three-arm accept-set returns `None`
11252 // rather than silently collapsing onto the [`Default`]
11253 // (`Permanent`) arm or an arbitrary neighbor. The refusal set
11254 // exercised here sweeps the load-bearing drift shapes: the
11255 // empty string (a stripped serde-attribute drift), all-
11256 // whitespace strings (the canonical text-editor accidental
11257 // padding shape), the kebab-case dispatcher-catalog identities
11258 // (`"permanent"` / `"temporary"` / `"transient"` — the
11259 // [`gen_platform::FromStrKind`]-derived [`std::str::FromStr`]
11260 // accept-set, which parses the *other* axis of this enum's
11261 // two-axis split and must not leak into the `from_wire`
11262 // PascalCase-wire accept-set — a lowercase leak here would
11263 // silently accept the operator's kebab-case
11264 // dispatcher-catalog probe under the wire-axis parser and mis-
11265 // route a `:permanent` intent), the padded canonical scalar
11266 // (`" Permanent "`), the trailing-newline shapes
11267 // (`"Permanent\n"`), the uppercase-single-word forms
11268 // (`"PERMANENT"`), and neighboring-but-unknown arms
11269 // (`"Restart"` — the canonical typo direction toward the
11270 // sibling [`RestartStrategy`] enum's own wire-arm namespace).
11271 //
11272 // Peer of the sibling
11273 // [`restart_strategy_from_wire_rejects_unknown_byte_strings`]
11274 // (4eec29c) +
11275 // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
11276 // (2aa6d23) +
11277 // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
11278 // (18c7342) refusal pins on the peer closed-set typed-enum
11279 // axes.
11280 for bad in [
11281 "",
11282 " ",
11283 "\n",
11284 "\t",
11285 "permanent",
11286 "temporary",
11287 "transient",
11288 "PERMANENT",
11289 "TEMPORARY",
11290 "TRANSIENT",
11291 "Permanents",
11292 "Permanent ",
11293 " Permanent",
11294 " Transient ",
11295 "Permanent\n",
11296 "perma",
11297 "Trans",
11298 "OneForOne",
11299 "Restart",
11300 "?",
11301 ] {
11302 assert!(
11303 RestartPolicy::from_wire(bad).is_none(),
11304 "RestartPolicy::from_wire({bad:?}) must return None — the \
11305 parser's accept-set is exactly the three RestartPolicy::as_str \
11306 outputs (Permanent, Temporary, Transient), and this \
11307 byte-string is outside that closed set"
11308 );
11309 }
11310 }
11311
11312 #[test]
11313 fn restart_policy_from_wire_matches_serialize_derive_wire_byte_string() {
11314 // Fail-before-pass-after pin on the fourth path of the four-path
11315 // convergence: `from_wire` (the reverse projection) inverts the
11316 // `Serialize` derive's wire byte-string on every variant.
11317 // Together with the pre-existing three-path convergence
11318 // (`Display` + `as_str` + `Serialize` all resolve to the same
11319 // lifted [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const,
11320 // pinned by
11321 // [`restart_policy_display_matches_serialized_wire_byte_string`])
11322 // this closes the round-trip: the wire byte-string the
11323 // `Serialize` derive emits parses back to the same variant
11324 // through `from_wire`, so any future serde-attribute or variant-
11325 // rename drift on the emit half now surfaces as a matched drift
11326 // on the parse half at caixa-core build time — the two halves
11327 // migrate as a unit through the lifted consts on any future
11328 // rename, and the round-trip cannot silently split.
11329 //
11330 // Peer of the sibling
11331 // [`restart_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
11332 // (4eec29c) wire-format pin on
11333 // [`RestartStrategy::from_wire`] and the M3
11334 // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
11335 // (18c7342) wire-format pin on
11336 // [`crate::aplicacao::PlacementStrategy::from_wire`].
11337 for &variant in RestartPolicy::ALL {
11338 let wire = serde_json::to_string(&variant).unwrap();
11339 let unquoted = wire
11340 .strip_prefix('"')
11341 .and_then(|s| s.strip_suffix('"'))
11342 .expect("serialized RestartPolicy is a JSON string");
11343 let parsed = RestartPolicy::from_wire(unquoted).unwrap_or_else(|| {
11344 panic!(
11345 "RestartPolicy::from_wire({unquoted:?}) must accept the \
11346 Serialize derive's wire byte-string for \
11347 RestartPolicy::{variant:?} — the four-path convergence \
11348 (Display + as_str + Serialize + from_wire) resolves through \
11349 the same lifted SUPERVISOR_CHILD_RESTART_* const; got None"
11350 )
11351 });
11352 assert_eq!(
11353 parsed, variant,
11354 "RestartPolicy::from_wire of the Serialize derive's wire \
11355 byte-string for RestartPolicy::{variant:?} must round-trip \
11356 to the same variant; got {parsed:?}"
11357 );
11358 }
11359 }
11360
11361 // ── drift-detection: ChildSpec::nome accessor pins ────────────────────
11362 //
11363 // The M2 supervisor-tree sibling of the M3 `Membro::nome` (4a32abf) pin
11364 // pair (`membro_nome_returns_caixa_byte_equal_across_permutations` +
11365 // `membro_nome_borrows_from_caixa_storage`) — extended here to the M2
11366 // per-`:children` child-caixa `:nome` axis, sibling to the first M2
11367 // slot scalar accessor `UpgradeFromEntry::prior_versao` (75d27a8) on
11368 // the peer per-`:upgrade-from :from` axis. The three pins jointly
11369 // brace the accessor against every future silent detour that would
11370 // desynchronize it from the raw `.caixa` field access every consumer
11371 // previously open-coded.
11372
11373 #[test]
11374 fn child_spec_nome_returns_caixa_byte_equal_across_permutations() {
11375 // The canonical per-`:children` child-caixa `:nome`-scalar pin:
11376 // [`ChildSpec::nome`] must return the `:children :caixa` field
11377 // byte-for-byte across every DNS-1123-label value the upstream
11378 // [`crate::render::require_valid_dns_1123_label`] gate at
11379 // `SupervisorSpec::validate` admits. Peer of the sibling
11380 // `membro_nome_returns_caixa_byte_equal_across_permutations`
11381 // (4a32abf) pin on the M3 per-`:membros` axis — same "the
11382 // substrate-primitive accessor must byte-equal the raw field
11383 // access verbatim across every author-declared value" discipline
11384 // extended to the M2 supervisor-tree per-`:children` arm. Pins
11385 // against a future silent detour that re-normalized the child
11386 // identity (an accidental `.to_lowercase()` — every `:children
11387 // :caixa` is validated as a DNS-1123 label upstream, so any
11388 // re-normalization is redundant + a drift surface between the
11389 // validator and the accessor), a namespace-prefix rewrite (an
11390 // accidental `format!("{namespace}/{caixa}")` per-CR
11391 // fully-qualified rewrite that didn't land on the peer axes), or
11392 // a per-cluster alias stamp the future wasm-operator's
11393 // hierarchical reconciliation scheduler authors on one consumer
11394 // without the others. Five values sweep the accept-set the
11395 // DNS-1123 gate upstream admits (short single-word / dashed /
11396 // v-suffixed / mixed-digit child names).
11397 for name in [
11398 "worker",
11399 "cache-server",
11400 "scratch-job",
11401 "orders-v2",
11402 "session-8080",
11403 ] {
11404 let c = ChildSpec {
11405 caixa: name.into(),
11406 versao: "^0.1".into(),
11407 restart: RestartPolicy::Permanent,
11408 };
11409 assert_eq!(
11410 c.nome(),
11411 name,
11412 "ChildSpec::nome must return :children :caixa verbatim \
11413 (got {:?}, expected {name:?})",
11414 c.nome(),
11415 );
11416 assert_eq!(
11417 c.nome(),
11418 c.caixa.as_str(),
11419 "ChildSpec::nome must byte-equal the .caixa field access",
11420 );
11421 }
11422 }
11423
11424 #[test]
11425 fn child_spec_nome_borrows_from_caixa_storage() {
11426 // The borrow-not-copy pin: [`ChildSpec::nome`] must return a
11427 // `&str` slice that borrows from the typed slot's own [`String`]
11428 // storage — same-address invariant with `c.caixa.as_str()`. Pins
11429 // against a future silent detour that allocated a fresh `String`
11430 // (`self.caixa.clone()` in the body would type-check but silently
11431 // drop the borrow, and every downstream consumer that assumed
11432 // the returned slice outlives `&self` would break on a stale-
11433 // reference use-after-free — the [`crate::render::insert_first_seen`]
11434 // dedup key at [`SupervisorSpec::validate`], the
11435 // [`validate_no_self_supervision`] equality check against the
11436 // parent's `:nome` string slice, the DNS-1123 gate's `&str`
11437 // borrow — each would silently misbehave if this accessor
11438 // produced a detached copy). Peer of the sibling
11439 // `membro_nome_borrows_from_caixa_storage` (4a32abf) pin on the
11440 // M3 per-`:membros` axis and the
11441 // `prior_versao_borrows_from_from_storage` (75d27a8) pin on the
11442 // first M2 slot scalar accessor.
11443 let c = ChildSpec {
11444 caixa: "worker".into(),
11445 versao: "^0.1".into(),
11446 restart: RestartPolicy::Permanent,
11447 };
11448 let name = c.nome();
11449 let caixa_slice = c.caixa.as_str();
11450 assert_eq!(
11451 name.as_ptr(),
11452 caixa_slice.as_ptr(),
11453 "ChildSpec::nome must borrow from the .caixa String's backing \
11454 storage — a fresh allocation here means the accessor no \
11455 longer names the substrate-primitive typed dispatch and \
11456 every downstream consumer would silently carry a detached \
11457 copy",
11458 );
11459 assert_eq!(
11460 name.len(),
11461 caixa_slice.len(),
11462 "ChildSpec::nome and .caixa.as_str() must byte-equal in length \
11463 as well as in address",
11464 );
11465 }
11466
11467 #[test]
11468 fn validate_gates_child_nome_through_lifted_accessor() {
11469 // Bilateral coherence pin: every `:children :caixa` that
11470 // [`SupervisorSpec::validate`] accepts is one
11471 // [`crate::render::require_valid_dns_1123_label`] accepts on the
11472 // accessor-projected value, and vice versa on the reject side.
11473 // This closes the "the validator reads through the accessor"
11474 // contract structurally — a future silent detour that made the
11475 // accessor return a different byte-string than the validator
11476 // gates against would surface here as a coverage mismatch, not
11477 // as an apply-time DNS-1123 rejection at
11478 // `metadata.name: Invalid value` far from the caixa.lisp source.
11479 // Peer of the M2 sibling
11480 // `validate_parses_prior_versao_through_lifted_accessor`
11481 // (75d27a8) on the per-`:upgrade-from :from` axis and the M3
11482 // `validate_membros` peer discipline.
11483 //
11484 // Accept-set sweep: five DNS-1123-label values the upstream gate
11485 // admits.
11486 for ok_name in ["a", "worker", "cache-server", "orders-v2", "svc-8080"] {
11487 let s = SupervisorSpec {
11488 children: vec![ChildSpec {
11489 caixa: ok_name.into(),
11490 versao: "^0.1".into(),
11491 restart: RestartPolicy::Permanent,
11492 }],
11493 ..SupervisorSpec::default()
11494 };
11495 s.validate().unwrap_or_else(|e| {
11496 panic!(
11497 "SupervisorSpec::validate must accept :children :caixa {ok_name:?} \
11498 (upstream DNS-1123 gate accepts it): got {e:?}",
11499 );
11500 });
11501 let c = ChildSpec {
11502 caixa: ok_name.into(),
11503 versao: "^0.1".into(),
11504 restart: RestartPolicy::Permanent,
11505 };
11506 crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| ())
11507 .unwrap_or_else(|()| {
11508 panic!(
11509 "require_valid_dns_1123_label must accept the accessor-projected \
11510 :children :caixa {ok_name:?}",
11511 );
11512 });
11513 }
11514 // Reject-set sweep: five DNS-1123-label-violating shapes the
11515 // upstream gate refuses (empty / uppercase / underscore / dot /
11516 // leading-hyphen). Every rejection at the validator must
11517 // correspond to a rejection when the accessor's projected value
11518 // is fed back through the shared gate.
11519 for bad_name in ["", "Worker", "my_worker", "team.worker", "-worker"] {
11520 let s = SupervisorSpec {
11521 children: vec![ChildSpec {
11522 caixa: bad_name.into(),
11523 versao: "^0.1".into(),
11524 restart: RestartPolicy::Permanent,
11525 }],
11526 ..SupervisorSpec::default()
11527 };
11528 let err = s.validate().unwrap_err();
11529 assert!(
11530 matches!(
11531 err,
11532 SupervisorError::EmptyChildName | SupervisorError::ChildCaixaInvalid { .. }
11533 ),
11534 "SupervisorSpec::validate must reject :children :caixa {bad_name:?} \
11535 via the DNS-1123 gate: got {err:?}",
11536 );
11537 let c = ChildSpec {
11538 caixa: bad_name.into(),
11539 versao: "^0.1".into(),
11540 restart: RestartPolicy::Permanent,
11541 };
11542 assert!(
11543 crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| (),)
11544 .is_err(),
11545 "require_valid_dns_1123_label must reject the accessor-projected \
11546 :children :caixa {bad_name:?}",
11547 );
11548 }
11549 }
11550
11551 // ── drift-detection: ChildSpec::versao_requirement accessor pins ──────
11552 //
11553 // Sibling of the peer per-`:membros` `membro_versao_requirement_*`
11554 // (a40b0e3) pin pair on the M3 mesh-slot surface — extended here to the
11555 // M2 supervisor-tree per-`:children` child-`:versao` axis, sibling to
11556 // the just-landed [`ChildSpec::nome`] (57c61d0) child-`:nome` pin
11557 // trio on the peer per-`:children` `String`-carry axis. The three pins
11558 // jointly brace the accessor against every future silent detour that
11559 // would desynchronize it from the raw `.versao` field access the
11560 // requirement gate + error carrier previously open-coded.
11561 //
11562 // Closes the last unlifted per-`:children` `String`-carry axis: the
11563 // pair (`nome`, `versao_requirement`) now jointly projects the
11564 // (`.caixa`, `.versao`) field pair every OTP-shape supervisor-tree
11565 // consumer that fans on per-child identity + version pin reads,
11566 // matching the peer M3 (`Membro::nome`, `Membro::versao_requirement`)
11567 // pair discipline verbatim.
11568 #[test]
11569 fn child_spec_versao_requirement_returns_versao_byte_equal_across_permutations() {
11570 // The canonical per-`:children` child-`:versao`-scalar pin:
11571 // [`ChildSpec::versao_requirement`] must return the `:children
11572 // :versao` field byte-for-byte across every Cargo-shaped semver
11573 // requirement value the upstream
11574 // [`crate::render::require_valid_versao_requirement`] gate admits.
11575 // Peer of the sibling
11576 // `membro_versao_requirement_returns_versao_byte_equal_across_permutations`
11577 // (a40b0e3) pin on the M3 per-`:membros` axis — same "the
11578 // substrate-primitive accessor must byte-equal the raw field
11579 // access verbatim across every author-declared value" discipline
11580 // extended to the M2 supervisor-tree per-`:children` arm. Pins
11581 // against a future silent detour that re-canonicalized the
11582 // requirement (an accidental `.to_string()` via
11583 // [`crate::version::parse_requirement`] → [`std::fmt::Display`]
11584 // round-trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and
11585 // silently drifted the error carrier's quoted requirement away
11586 // from the source `caixa.lisp`, an accidental whitespace trim on
11587 // `"^ 0.1"` that no consumer ever produced from the field-access
11588 // side, an accidental per-cluster lacre-projected concrete-version
11589 // rewrite that didn't land on the peer requirement-gate call).
11590 // Five values sweep the accept-set the shared
11591 // [`crate::render::require_valid_versao_requirement`] gate admits
11592 // (caret / tilde / exact / wildcard / bare-major).
11593 for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
11594 let c = ChildSpec {
11595 caixa: "worker".into(),
11596 versao: req.into(),
11597 restart: RestartPolicy::Permanent,
11598 };
11599 assert_eq!(
11600 c.versao_requirement(),
11601 req,
11602 "ChildSpec::versao_requirement must return :children :versao \
11603 verbatim (got {:?}, expected {req:?})",
11604 c.versao_requirement(),
11605 );
11606 assert_eq!(
11607 c.versao_requirement(),
11608 c.versao.as_str(),
11609 "ChildSpec::versao_requirement must byte-equal the .versao \
11610 field access",
11611 );
11612 }
11613 }
11614
11615 #[test]
11616 fn child_spec_versao_requirement_borrows_from_versao_storage() {
11617 // The borrow-not-copy pin: [`ChildSpec::versao_requirement`] must
11618 // return a `&str` slice that borrows from the typed slot's own
11619 // [`String`] storage — same-address invariant with
11620 // `c.versao.as_str()`. Pins against a future silent detour that
11621 // allocated a fresh `String` (`self.versao.clone()` in the body
11622 // would type-check but silently drop the borrow, and every
11623 // downstream consumer that assumed the returned slice outlives
11624 // `&self` — the [`crate::render::require_valid_versao_requirement`]
11625 // gate's `&str` borrow, the [`SupervisorError::ChildVersaoInvalid`]
11626 // `.to_string()` carrier's byte-length assumption — would silently
11627 // misbehave if this accessor produced a detached copy). Peer of
11628 // the sibling `child_spec_nome_borrows_from_caixa_storage`
11629 // (57c61d0) pin on the per-`:children` `:nome` axis and the M3
11630 // `membro_versao_requirement_borrows_from_versao_storage` (a40b0e3)
11631 // pin on the peer per-`:membros` `:versao` axis.
11632 let c = ChildSpec {
11633 caixa: "worker".into(),
11634 versao: "^0.1".into(),
11635 restart: RestartPolicy::Permanent,
11636 };
11637 let req = c.versao_requirement();
11638 let versao_slice = c.versao.as_str();
11639 assert_eq!(
11640 req.as_ptr(),
11641 versao_slice.as_ptr(),
11642 "ChildSpec::versao_requirement must borrow from the .versao \
11643 String's backing storage — a fresh allocation here means the \
11644 accessor no longer names the substrate-primitive typed \
11645 dispatch and every downstream consumer would silently carry \
11646 a detached copy",
11647 );
11648 assert_eq!(
11649 req.len(),
11650 versao_slice.len(),
11651 "ChildSpec::versao_requirement and .versao.as_str() must \
11652 byte-equal in length as well as in address",
11653 );
11654 }
11655
11656 #[test]
11657 fn validate_gates_child_versao_through_lifted_accessor() {
11658 // Bilateral coherence pin: every `:children :versao` that
11659 // [`SupervisorSpec::validate`] accepts is one
11660 // [`crate::render::require_valid_versao_requirement`] accepts on
11661 // the accessor-projected value, and vice versa on the reject side.
11662 // This closes the "the validator reads through the accessor"
11663 // contract structurally — a future silent detour that made the
11664 // accessor return a different byte-string than the validator gates
11665 // against would surface here as a coverage mismatch, not as a
11666 // resolver-time semver-parse rejection at lacre-closure time far
11667 // from the caixa.lisp source. Peer of the sibling
11668 // `validate_gates_child_nome_through_lifted_accessor` (57c61d0) on
11669 // the per-`:children :caixa` axis and the M2
11670 // `validate_parses_prior_versao_through_lifted_accessor` (75d27a8)
11671 // on the peer per-`:upgrade-from :from` axis.
11672 //
11673 // Accept-set sweep: five Cargo-shaped semver requirement values
11674 // the upstream gate admits (caret / tilde / exact / wildcard /
11675 // bare-major).
11676 for ok_req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
11677 let s = SupervisorSpec {
11678 children: vec![ChildSpec {
11679 caixa: "worker".into(),
11680 versao: ok_req.into(),
11681 restart: RestartPolicy::Permanent,
11682 }],
11683 ..SupervisorSpec::default()
11684 };
11685 s.validate().unwrap_or_else(|e| {
11686 panic!(
11687 "SupervisorSpec::validate must accept :children :versao {ok_req:?} \
11688 (upstream versao-requirement gate accepts it): got {e:?}",
11689 );
11690 });
11691 let c = ChildSpec {
11692 caixa: "worker".into(),
11693 versao: ok_req.into(),
11694 restart: RestartPolicy::Permanent,
11695 };
11696 crate::render::require_valid_versao_requirement(
11697 c.versao_requirement(),
11698 || (),
11699 |_reason| (),
11700 )
11701 .unwrap_or_else(|()| {
11702 panic!(
11703 "require_valid_versao_requirement must accept the accessor-projected \
11704 :children :versao {ok_req:?}",
11705 );
11706 });
11707 }
11708 // Reject-set sweep: five requirement-violating shapes the upstream
11709 // gate refuses. The empty string closes the empty-first arm of the
11710 // shared [`crate::render::require_valid_versao_requirement`]
11711 // cascade; the four non-empty arms exercise distinct semver-parse
11712 // failure modes the M3 peer per-`:membros` reject-set already pins
11713 // (`rejects_invalid_membro_versao_requirement` on `^bad-version`,
11714 // `rejects_membro_versao_with_double_caret_typo` on `^^0.1`,
11715 // `rejects_membro_versao_with_v_prefixed_tag` on `v0.1`) — the
11716 // shared parser routing means the same reject-set must fail
11717 // identically at the M2 supervisor-tree per-`:children` accessor
11718 // arm here. Every rejection at the validator must correspond to a
11719 // rejection when the accessor's projected value is fed back
11720 // through the shared gate.
11721 //
11722 // (Bare partial magnitudes like `"0.1"` and bare identifiers like
11723 // `"not-a-semver"` are intentionally *not* in the reject-set: the
11724 // semver crate accepts `"0.1"` as an implicit `^0.1` requirement,
11725 // and the identifier-tail arm's grammar admits some non-canonical
11726 // shapes — matching what the M3 peer test suite already documents
11727 // as the shared parser's accept-set edges.)
11728 for bad_req in ["", "v0.1.0", "^bad-version", "^^0.1", "v0.1"] {
11729 let s = SupervisorSpec {
11730 children: vec![ChildSpec {
11731 caixa: "worker".into(),
11732 versao: bad_req.into(),
11733 restart: RestartPolicy::Permanent,
11734 }],
11735 ..SupervisorSpec::default()
11736 };
11737 let err = s.validate().unwrap_err();
11738 assert!(
11739 matches!(
11740 err,
11741 SupervisorError::EmptyChildVersion { .. }
11742 | SupervisorError::ChildVersaoInvalid { .. }
11743 ),
11744 "SupervisorSpec::validate must reject :children :versao {bad_req:?} \
11745 via the versao-requirement gate: got {err:?}",
11746 );
11747 let c = ChildSpec {
11748 caixa: "worker".into(),
11749 versao: bad_req.into(),
11750 restart: RestartPolicy::Permanent,
11751 };
11752 assert!(
11753 crate::render::require_valid_versao_requirement(
11754 c.versao_requirement(),
11755 || (),
11756 |_reason| (),
11757 )
11758 .is_err(),
11759 "require_valid_versao_requirement must reject the accessor-projected \
11760 :children :versao {bad_req:?}",
11761 );
11762 }
11763 }
11764
11765 // ── per-`:children` `:restart` typed-accessor coherence pins ──────────
11766 //
11767 // The [`ChildSpec::restart`] accessor lift closes the last unlifted
11768 // per-`:children` axis (the pair `nome()` + `versao_requirement()`
11769 // already project the `String`-carry `(caixa, versao)` fields; the
11770 // `Copy`-composite-enum `restart` field is the third and final axis).
11771 // Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
11772 // (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
11773 // scalar accessor and the M3 mesh-slot [`crate::Placement::estrategia`]
11774 // (921fe1b) `Copy`-return [`crate::PlacementStrategy`] distribution-
11775 // strategy scalar accessor — same "one typed dispatch on the substrate
11776 // primitive, `Copy`-projected closed-set enum-arm discriminator" shape
11777 // extended onto the M2 supervisor-slot per-`:children` restart-decision
11778 // axis. The pin below covers the accessor's byte-equal projection
11779 // against the raw field access across every variant in the closed
11780 // accept-set (`Permanent`, `Transient`, `Temporary`).
11781
11782 #[test]
11783 fn child_spec_restart_returns_restart_verbatim_across_permutations() {
11784 // The canonical per-`:children` restart-decision-policy-scalar
11785 // pin: [`ChildSpec::restart`] must return the `:children :restart`
11786 // field verbatim as a [`RestartPolicy`], `Copy`-projected from the
11787 // typed slot's own [`RestartPolicy`] storage across every variant
11788 // in the closed accept-set (`Permanent`, `Transient`, `Temporary`).
11789 // Pins against a future silent detour that re-derived the policy
11790 // from a peer axis (an accidental fallback to
11791 // `if is_supervisor_child { Permanent } else { Temporary }` that
11792 // collapsed the child's kind axis into the restart discriminator),
11793 // a variant remap the operator authors on one consumer without the
11794 // other, or a stale-derive detour that substituted
11795 // [`RestartPolicy::default`] when the field held any explicit
11796 // variant (which would silently collapse the distinction between
11797 // "author explicitly declared `:restart Permanent`" and "author
11798 // omitted the slot and inherited the default" the future
11799 // per-cluster restart-decision override slot depends on).
11800 //
11801 // Peer of the sibling per-`:supervisor`
11802 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
11803 // (eafb619) pin on the M2 supervisor-slot sibling-restart-strategy
11804 // axis and the M3
11805 // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
11806 // (921fe1b) pin on the per-`:placement` distribution-strategy axis
11807 // — same "the substrate-primitive accessor must byte-equal the raw
11808 // field access verbatim across every author-declared value"
11809 // discipline extended onto the M2 supervisor-slot per-`:children`
11810 // restart-decision-policy axis, closing the last unlifted axis on
11811 // the per-`:children` [`ChildSpec`] type.
11812 for restart in [
11813 RestartPolicy::Permanent,
11814 RestartPolicy::Transient,
11815 RestartPolicy::Temporary,
11816 ] {
11817 let c = ChildSpec {
11818 caixa: "worker".into(),
11819 versao: "^0.1".into(),
11820 restart,
11821 };
11822 assert_eq!(
11823 c.restart(),
11824 restart,
11825 "ChildSpec::restart must return :children :restart \
11826 verbatim (got {:?}, expected {restart:?})",
11827 c.restart(),
11828 );
11829 assert_eq!(
11830 c.restart(),
11831 c.restart,
11832 "ChildSpec::restart accessor and .restart field access \
11833 must byte-equal — the accessor is the substrate-primitive \
11834 typed dispatch every downstream per-child restart-\
11835 decision consumer must route through",
11836 );
11837 }
11838 }
11839
11840 // ── per-`:supervisor` `:estrategia` typed-accessor coherence pins ─────
11841 //
11842 // The [`SupervisorSpec::estrategia`] accessor lift extends the peer M3
11843 // [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
11844 // distribution-strategy accessor discipline onto the M2 supervisor-slot
11845 // per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
11846 // scalar axis. The two pins below cover (1) the accessor's byte-equal
11847 // projection against the raw field access across every variant in the
11848 // closed accept-set, and (2) the two-consumer coherence between the
11849 // [`SupervisorSpec::validate`] partition-dispatch `match` arm and the
11850 // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
11851 // carrier's `estrategia:` field — peer of the sibling M3
11852 // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
11853 // / `validate_placement_reads_through_lifted_estrategia_accessor` pin
11854 // pair on the per-`:placement` distribution-strategy axis.
11855
11856 #[test]
11857 fn supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations() {
11858 // The canonical per-`:supervisor` sibling-restart-strategy-scalar
11859 // pin: [`SupervisorSpec::estrategia`] must return the
11860 // `:supervisor :estrategia` field verbatim as a
11861 // [`RestartStrategy`], `Copy`-projected from the typed slot's own
11862 // [`RestartStrategy`] storage across every variant in the closed
11863 // accept-set (`OneForOne`, `OneForAll`, `RestForOne`,
11864 // `SimpleOneForOne`). Pins against a future silent detour that
11865 // re-derived the strategy from a peer axis (an accidental
11866 // fallback to `if children.is_empty() { SimpleOneForOne } else {
11867 // OneForOne }` collapse that read the children-count axis into
11868 // the strategy discriminator), a variant remap the operator
11869 // authors on one consumer without the other, or a stale-derive
11870 // detour that substituted [`RestartStrategy::default`] when the
11871 // field held any explicit variant (which would silently collapse
11872 // the distinction between "author explicitly declared
11873 // `:estrategia OneForOne`" and "author omitted the slot and
11874 // inherited the default" the future per-cluster strategy override
11875 // slot depends on). Peer of the sibling M3
11876 // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
11877 // (921fe1b) pin on the M3 mesh-slot `Copy`-composite-enum scalar
11878 // axis — same "the substrate-primitive accessor must byte-equal
11879 // the raw field access verbatim across every author-declared
11880 // value" discipline extended onto the M2 supervisor-slot
11881 // per-`:supervisor` sibling-restart-strategy axis.
11882 for &estrategia in RestartStrategy::ALL {
11883 // `SimpleOneForOne` requires `children.is_empty()`; the peer
11884 // three strategies require a non-empty static children list.
11885 // Build each shape coherently so the pin's fixture would
11886 // itself pass [`SupervisorSpec::validate`] once fed through
11887 // the sibling coherence pin below — the byte-equal projection
11888 // asserted here is a strictly weaker property (a `Copy` field
11889 // read) that does not depend on `validate` running, but
11890 // keeping the fixture validate-clean means a future extension
11891 // of the pin to exercise `validate` end-to-end does not have
11892 // to re-author the children shape.
11893 //
11894 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
11895 // shape partition through the [`gen_platform::IsVariant`]
11896 // derive-generated
11897 // [`RestartStrategy::is_simple_one_for_one`] predicate rather
11898 // than the raw `matches!(estrategia, RestartStrategy::
11899 // SimpleOneForOne)` open-coded pattern-match — same closed-
11900 // set-typed-enum arm-discriminator dispatch discipline the
11901 // sibling [`crate::upgrade::UpgradeInstruction::is_restart`]
11902 // convergence (915a934) extended onto its two paired positive
11903 // / negated `matches!` sites and the peer
11904 // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
11905 // predicate convergence (766ec63) extended onto the M3 mesh-
11906 // slot per-`:placement` distribution-strategy discriminator
11907 // axis. See the sibling `round_trip_all_strategies` and the
11908 // peer `manifest::tests::
11909 // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
11910 // fixture for the two peer sites the same lift closes on.
11911 let children = if estrategia.is_simple_one_for_one() {
11912 Vec::new()
11913 } else {
11914 vec![ChildSpec {
11915 caixa: "worker".into(),
11916 versao: "^0.1".into(),
11917 restart: RestartPolicy::Permanent,
11918 }]
11919 };
11920 let s = SupervisorSpec {
11921 estrategia,
11922 children,
11923 ..SupervisorSpec::default()
11924 };
11925 assert_eq!(
11926 s.estrategia(),
11927 estrategia,
11928 "SupervisorSpec::estrategia must return :supervisor :estrategia \
11929 verbatim (got {:?}, expected {estrategia:?})",
11930 s.estrategia(),
11931 );
11932 assert_eq!(
11933 s.estrategia(),
11934 s.estrategia,
11935 "SupervisorSpec::estrategia accessor and .estrategia field \
11936 access must byte-equal — the accessor is the substrate-\
11937 primitive typed dispatch every downstream sibling-restart-\
11938 strategy consumer must route through",
11939 );
11940 }
11941 }
11942
11943 #[test]
11944 fn validate_reads_through_lifted_estrategia_accessor() {
11945 // Two-consumer coherence pin: the [`SupervisorSpec::validate`]
11946 // `SimpleOneForOne ↔ non-SimpleOneForOne` `match` partition
11947 // dispatch (which reads through [`SupervisorSpec::estrategia`]
11948 // to fan across the strategy-arm shape-gate cascades) and the
11949 // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
11950 // error carrier's `estrategia:` field (which reads through
11951 // [`SupervisorSpec::estrategia`] to name the strategy the empty
11952 // `:children` list was declared against) must both key off the
11953 // lifted accessor, so any future rebrand on the typed slot's
11954 // reader shape lands at exactly one place. Pins the two-site
11955 // coherence by exercising the `NoChildren` error surface end-to-
11956 // end across every non-`SimpleOneForOne` variant and asserting
11957 // the surfaced `estrategia:` field byte-equals the accessor's
11958 // return. Peer of the sibling M3
11959 // `validate_placement_reads_through_lifted_estrategia_accessor`
11960 // (921fe1b) three-consumer coherence pin on the per-`:placement`
11961 // distribution-strategy axis.
11962 for estrategia in [
11963 RestartStrategy::OneForOne,
11964 RestartStrategy::OneForAll,
11965 RestartStrategy::RestForOne,
11966 ] {
11967 let s = SupervisorSpec {
11968 estrategia,
11969 children: Vec::new(),
11970 ..SupervisorSpec::default()
11971 };
11972 let err = s.validate().unwrap_err();
11973 match err {
11974 SupervisorError::NoChildren { estrategia: e } => {
11975 assert_eq!(
11976 e,
11977 s.estrategia(),
11978 "NoChildren.estrategia must byte-equal \
11979 SupervisorSpec::estrategia() — the empty-`:children` \
11980 refusal reads through the lifted accessor",
11981 );
11982 assert_eq!(
11983 e, estrategia,
11984 "NoChildren.estrategia must carry the author-declared \
11985 :supervisor :estrategia variant verbatim (got {e:?}, \
11986 expected {estrategia:?})",
11987 );
11988 }
11989 other => panic!("expected NoChildren, got {other:?} for estrategia={estrategia:?}"),
11990 }
11991 }
11992 }
11993
11994 // ── per-`:supervisor` `:max-restarts` typed-accessor coherence pins ────
11995 //
11996 // The [`SupervisorSpec::max_restarts`] accessor lift extends the peer M3
11997 // [`crate::CircuitBreaker::max_failures`] (3a74062) `Copy`-return
11998 // required-`u32` scalar accessor discipline onto the M2 supervisor-slot
11999 // per-`:supervisor` restart-budget-count `Copy`-`u32` scalar axis.
12000 // The two pins below cover (1) the accessor's byte-equal projection
12001 // against the raw field access across every representative value in
12002 // the `u32` accept-set (`1` lower boundary, `SUPERVISOR_MAX_RESTARTS_MAX`
12003 // upper boundary, `0` past-the-guard zero sentinel, `u32::MAX`
12004 // past-the-guard cap sentinel), and (2) the [`SupervisorSpec::validate`]
12005 // zero-floor / cap composition — the validate gate and the accessor
12006 // must route through the same substrate-primitive typed dispatch, so
12007 // any future silent detour that had the accessor perform a
12008 // bounds-collapsing clamp would fail here at caixa-core build time.
12009 // Peer of the sibling M3
12010 // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
12011 // (3a74062) pin on the per-`CircuitBreaker :max-failures` axis.
12012
12013 #[test]
12014 fn supervisor_spec_max_restarts_returns_max_restarts_u32_byte_equal_across_permutations() {
12015 // The canonical per-`:supervisor` restart-budget-count scalar pin:
12016 // [`SupervisorSpec::max_restarts`] must return the `:supervisor
12017 // :max-restarts` typed `u32` verbatim, `Copy`-projected from the
12018 // typed slot's own `u32` storage, byte-equal to the raw field
12019 // access across every representative value in the accept-set —
12020 // `1` (the lower boundary of the `1..=SUPERVISOR_MAX_RESTARTS_MAX`
12021 // accept-set the surrounding [`SupervisorSpec::validate`] gate
12022 // carves out on the sibling `ZeroMaxRestarts` refusal),
12023 // `SUPERVISOR_MAX_RESTARTS_MAX` (the upper boundary the same gate
12024 // carves out on the sibling `MaxRestartsExceedsCap` refusal), `0`
12025 // (a past-the-guard sentinel that pins the accessor doesn't
12026 // perform a silent bounds-collapse into `1` on the zero arm —
12027 // validate rejects zero but the accessor must ship the raw slot
12028 // verbatim so a validate-time gate regression surfaces at the
12029 // emit boundary rather than being silently absorbed), `u32::MAX`
12030 // (a past-the-guard sentinel that pins the accessor doesn't
12031 // perform a silent bounds-collapse through
12032 // `SUPERVISOR_MAX_RESTARTS_MAX` at the return path).
12033 //
12034 // Peer of the sibling M3
12035 // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
12036 // (3a74062) pin on the M3 mesh-slot `Copy`-`u32` sub-struct
12037 // required-scalar axis — same "the substrate-primitive accessor
12038 // must byte-equal the raw field access verbatim across every
12039 // value in the `u32` accept-set" discipline extended onto the M2
12040 // supervisor-slot per-`:supervisor` restart-budget-count axis.
12041 for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX, 0, u32::MAX] {
12042 let s = SupervisorSpec {
12043 max_restarts,
12044 ..SupervisorSpec::default()
12045 };
12046 assert_eq!(
12047 s.max_restarts(),
12048 max_restarts,
12049 "SupervisorSpec::max_restarts must return :supervisor \
12050 :max-restarts verbatim (got {}, expected {max_restarts})",
12051 s.max_restarts(),
12052 );
12053 assert_eq!(
12054 s.max_restarts(),
12055 s.max_restarts,
12056 "SupervisorSpec::max_restarts accessor and .max_restarts \
12057 field access must byte-equal — the accessor is the \
12058 substrate-primitive typed dispatch every downstream \
12059 restart-budget-count consumer must route through",
12060 );
12061 }
12062 }
12063
12064 #[test]
12065 fn validate_max_restarts_zero_floor_and_cap_arms_route_through_accessor() {
12066 // Composition pin: [`SupervisorSpec::validate`]'s `:max-restarts`
12067 // zero-floor + upper-cap bracket must key off
12068 // [`SupervisorSpec::max_restarts`], not the raw `.max_restarts`
12069 // field access. Structurally: a `SupervisorSpec { max_restarts:
12070 // 0, .. }` must surface the `ZeroMaxRestarts` refusal exactly, a
12071 // `SupervisorSpec { max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
12072 // .. }` must surface the `MaxRestartsExceedsCap` refusal exactly
12073 // (with the offending count carried verbatim from the accessor
12074 // return), and a `SupervisorSpec { max_restarts: 1, .. }` (the
12075 // lower boundary of the accept-set) plus a `SupervisorSpec {
12076 // max_restarts: SUPERVISOR_MAX_RESTARTS_MAX, .. }` (the upper
12077 // boundary) must pass validate. The four together jointly pin the
12078 // accessor + validate-gate composition: any future silent detour
12079 // that had the accessor return a fresh `1` on the zero arm (a
12080 // `.max_restarts().max(1)` collapse) would silently absorb the
12081 // `ZeroMaxRestarts` refusal at the accessor boundary and the
12082 // validate gate would accept a struct-literal `SupervisorSpec {
12083 // max_restarts: 0, .. }` — the composition pin catches that at
12084 // caixa-core build time.
12085 //
12086 // Peer of the sibling M3
12087 // `validate_politicas_max_failures_zero_floor_arm_routes_through_accessor`
12088 // (3a74062) pin on the sibling per-`CircuitBreaker :max-failures`
12089 // composition axis — same "the validate / shape-gate predicate
12090 // must route through the substrate-primitive typed dispatch"
12091 // discipline extended onto the peer M2 supervisor-slot
12092 // required-`u32` composition axis.
12093 let child = ChildSpec {
12094 caixa: "worker".into(),
12095 versao: "^0.1".into(),
12096 restart: RestartPolicy::Permanent,
12097 };
12098 // Zero-floor arm.
12099 let s = SupervisorSpec {
12100 max_restarts: 0,
12101 children: vec![child.clone()],
12102 ..SupervisorSpec::default()
12103 };
12104 assert_eq!(
12105 s.validate().unwrap_err(),
12106 SupervisorError::ZeroMaxRestarts,
12107 "validate must reject max_restarts == 0 with ZeroMaxRestarts \
12108 — the accessor and the validate gate must route through the \
12109 same substrate-primitive typed dispatch on the zero-floor arm",
12110 );
12111 // Cap arm — the surfaced `max_restarts:` field must byte-equal
12112 // the accessor's return so a future rebrand on the accessor
12113 // lands in the diagnostic without a coordinated rewrite.
12114 let over_cap = SUPERVISOR_MAX_RESTARTS_MAX + 1;
12115 let s = SupervisorSpec {
12116 max_restarts: over_cap,
12117 children: vec![child.clone()],
12118 ..SupervisorSpec::default()
12119 };
12120 match s.validate().unwrap_err() {
12121 SupervisorError::MaxRestartsExceedsCap { max_restarts } => {
12122 assert_eq!(
12123 max_restarts,
12124 s.max_restarts(),
12125 "MaxRestartsExceedsCap.max_restarts must byte-equal \
12126 SupervisorSpec::max_restarts() — the cap-arm refusal \
12127 reads through the lifted accessor",
12128 );
12129 assert_eq!(
12130 max_restarts, over_cap,
12131 "MaxRestartsExceedsCap.max_restarts must carry the \
12132 author-declared :supervisor :max-restarts value \
12133 verbatim (got {max_restarts}, expected {over_cap})",
12134 );
12135 }
12136 other => panic!("expected MaxRestartsExceedsCap, got {other:?}"),
12137 }
12138 // Lower + upper accept-set boundaries.
12139 for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX] {
12140 let s = SupervisorSpec {
12141 max_restarts,
12142 children: vec![child.clone()],
12143 ..SupervisorSpec::default()
12144 };
12145 assert!(
12146 s.validate().is_ok(),
12147 "validate must accept max_restarts == {max_restarts} \
12148 (an accept-set boundary of \
12149 1..=SUPERVISOR_MAX_RESTARTS_MAX)",
12150 );
12151 }
12152 }
12153
12154 // ── per-`:supervisor` `:restart-window` typed-accessor coherence pins ─
12155 //
12156 // The [`SupervisorSpec::restart_window`] accessor lift extends the peer
12157 // M2 [`crate::LimitsSpec::wall_clock`] (8cb717b) `Option<Duration>`
12158 // accessor discipline and the peer M3 [`crate::MeshPolicy::timeout`]
12159 // (7073d0f) `Option<Duration>` accessor discipline onto the M2
12160 // supervisor-slot per-`:supervisor` restart-intensity-denominator
12161 // `Option<Duration>` scalar axis — third `Copy`-return accessor on the
12162 // M2 supervisor-slot `SupervisorSpec` type, closing the last unlifted
12163 // per-`:supervisor` scalar-value axis. The three pins below cover
12164 // (1) the accessor's byte-equal projection against the raw field
12165 // access across every representative value in the `Option<Duration>`
12166 // accept-set (`None` never-reset sentinel, `Some(Duration::from_millis(1))`
12167 // lower boundary, `Some(SUPERVISOR_RESTART_WINDOW_MAX)` upper boundary,
12168 // `Some(Duration::ZERO)` past-the-guard zero sentinel, `Some(Duration::MAX)`
12169 // past-the-guard above-cap sentinel), (2) the [`SupervisorSpec::validate`]
12170 // `if let Some(w) = self.restart_window() { … }` bracket-arm
12171 // composition — the validate gate and the accessor must route through
12172 // the same substrate-primitive typed dispatch, so any future silent
12173 // detour that had the accessor perform a bounds-collapsing clamp
12174 // would fail here at caixa-core build time, and (3) the accessor's
12175 // by-copy idempotence pin — the returned `Option<Duration>` must
12176 // outlive `&self` and two successive calls must return byte-equal
12177 // values. Peer of the sibling M2
12178 // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
12179 // (8cb717b) pin on the per-`:limits :wall-clock` axis and the sibling
12180 // M3 `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
12181 // (7073d0f) pin on the per-`:politicas :timeout` axis.
12182
12183 #[test]
12184 fn supervisor_spec_restart_window_returns_option_duration_byte_equal_across_permutations() {
12185 // The canonical per-`:supervisor` restart-intensity-denominator
12186 // scalar pin: [`SupervisorSpec::restart_window`] must return the
12187 // `:supervisor :restart-window` typed [`Duration`] verbatim as an
12188 // `Option<Duration>`, `Copy`-projected from the typed slot's own
12189 // `Option<Duration>` storage, byte-equal to the raw field access
12190 // across every representative value in the accept-set — `None`
12191 // (the "never reset — every restart across the supervisor's
12192 // lifetime counts against the sibling `:max-restarts` budget"
12193 // sentinel the field's own docstring names and the peer
12194 // `validate_accepts_none_restart_window` pin locks in on the
12195 // [`SupervisorSpec::validate`] entry-side),
12196 // `Some(Duration::from_millis(1))` (the structural minimum a
12197 // validated `:restart-window` may carry, the integer-millisecond
12198 // floor [`SupervisorError::RestartWindowNotCanonical`] rejects
12199 // everything sub-ms; `Duration::ZERO` is separately rejected by
12200 // [`SupervisorError::RestartWindowZero`]),
12201 // `Some(SUPERVISOR_RESTART_WINDOW_MAX)` (the upper boundary the
12202 // surrounding [`SupervisorSpec::validate`] gate carves out on the
12203 // sibling [`SupervisorError::RestartWindowExceedsCap`] refusal),
12204 // `Some(Duration::ZERO)` (a past-the-guard sentinel that pins the
12205 // accessor doesn't perform a silent bounds-collapse into `None` on
12206 // the zero-Duration arm — validate rejects zero but the accessor
12207 // must ship the raw slot verbatim so a validate-time gate
12208 // regression surfaces at the emit boundary rather than being
12209 // silently absorbed), and `Some(Duration::MAX)` (a past-the-guard
12210 // sentinel that pins the accessor doesn't perform a silent
12211 // bounds-collapse through [`SUPERVISOR_RESTART_WINDOW_MAX`] at the
12212 // return path).
12213 //
12214 // Peer of the sibling M2
12215 // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
12216 // (8cb717b) pin on the per-`:limits :wall-clock` axis and the
12217 // sibling M3
12218 // `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
12219 // (7073d0f) pin on the per-`:politicas :timeout` axis — same "the
12220 // substrate-primitive accessor must byte-equal the raw field
12221 // access verbatim across every value in the `Option<Duration>`
12222 // accept-set" discipline extended onto the M2 supervisor-slot
12223 // per-`:supervisor` `Option<Duration>` axis. Pins against a future
12224 // silent detour that re-derived the restart-window from a peer
12225 // axis (an accidental `.max_restarts.into()` collapse that read
12226 // the restart-budget-count as a duration — the two axes serve
12227 // different halves of the `MaxIntensity / Period` restart-
12228 // intensity ratio, and confusing them silently inverts the
12229 // ratio's numerator and denominator), a `None → Some(Duration::ZERO)`
12230 // "zero means never reset" collapse (the canonical
12231 // `Option<Duration>` → `Duration` collapse footgun the
12232 // [`SupervisorError::RestartWindowZero`] validate arm guards on
12233 // the peer zero-floor axis; a zero period either trips on the
12234 // first failure or never trips depending on operator
12235 // interpretation, neither of which is the author's "never reset"
12236 // intent that `None` expresses structurally), or a per-arm
12237 // variant swap that landed on one consumer without the other.
12238 for restart_window in [
12239 None,
12240 Some(Duration::from_millis(1)),
12241 Some(SUPERVISOR_RESTART_WINDOW_MAX),
12242 Some(Duration::ZERO),
12243 Some(Duration::MAX),
12244 ] {
12245 let s = SupervisorSpec {
12246 restart_window,
12247 ..SupervisorSpec::default()
12248 };
12249 assert_eq!(
12250 s.restart_window(),
12251 restart_window,
12252 "SupervisorSpec::restart_window must return :supervisor \
12253 :restart-window verbatim (got {:?}, expected {restart_window:?})",
12254 s.restart_window(),
12255 );
12256 assert_eq!(
12257 s.restart_window(),
12258 s.restart_window,
12259 "SupervisorSpec::restart_window accessor and \
12260 .restart_window field access must byte-equal — the \
12261 accessor is the substrate-primitive typed dispatch every \
12262 downstream restart-intensity-denominator consumer must \
12263 route through",
12264 );
12265 }
12266 }
12267
12268 #[test]
12269 fn validate_restart_window_bracket_arm_routes_through_accessor() {
12270 // Composition pin: [`SupervisorSpec::validate`]'s
12271 // `:restart-window` `if let Some(w) = self.restart_window() { … }`
12272 // zero-floor + integer-millisecond canonical-form + upper-cap
12273 // bracket-arm must key off [`SupervisorSpec::restart_window`], not
12274 // the raw `.restart_window` field access. Structurally: a
12275 // `SupervisorSpec { restart_window: None, .. }` must pass the
12276 // arm gate structurally (the `if let Some(_)` shape returns
12277 // early on the `None` arm — the accessor and the validate gate
12278 // must agree on `None → skip the bracket cascade` so an authored
12279 // `:restart-window ()` structurally routes through the "never
12280 // reset" sentinel path), a `SupervisorSpec { restart_window:
12281 // Some(Duration::ZERO), .. }` must surface the `RestartWindowZero`
12282 // refusal exactly, a `SupervisorSpec { restart_window:
12283 // Some(Duration::from_micros(1500)), .. }` must surface the
12284 // `RestartWindowNotCanonical` refusal exactly (with the offending
12285 // duration carried verbatim from the accessor return), a
12286 // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX
12287 // + Duration::from_millis(1)), .. }` must surface the
12288 // `RestartWindowExceedsCap` refusal exactly (with the offending
12289 // duration carried verbatim from the accessor return), and a
12290 // `SupervisorSpec { restart_window: Some(Duration::from_millis(1)),
12291 // .. }` (the lower boundary of the accept-set) plus a
12292 // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
12293 // .. }` (the upper boundary) must pass validate. The six together
12294 // jointly pin the accessor + validate-gate composition: any future
12295 // silent detour that had the accessor return a fresh `None` on any
12296 // `Some` arm (a `.restart_window().filter(|w| !w.is_zero())`
12297 // collapse) would silently absorb the `RestartWindowZero` refusal
12298 // at the accessor boundary and the validate gate would accept a
12299 // struct-literal `SupervisorSpec { restart_window:
12300 // Some(Duration::ZERO), .. }` — the composition pin catches that
12301 // at caixa-core build time.
12302 //
12303 // Peer of the sibling M2 [`crate::LimitsSpec::wall_clock`]
12304 // (8cb717b) validate-arm-route pin on the per-`:limits :wall-clock`
12305 // axis and the peer M3 [`crate::MeshPolicy::timeout`] (7073d0f)
12306 // accessor-composition pin on the per-`:politicas :timeout` axis —
12307 // same "the validate / shape-gate predicate must route through
12308 // the substrate-primitive typed dispatch" discipline extended
12309 // onto the peer M2 supervisor-slot optional-`Duration` axis.
12310 let child = ChildSpec {
12311 caixa: "worker".into(),
12312 versao: "^0.1".into(),
12313 restart: RestartPolicy::Permanent,
12314 };
12315 // None arm — must not surface any :restart-window-shaped refusal;
12316 // the `if let Some(_)` bracket returns early on `None` structurally.
12317 let s = SupervisorSpec {
12318 restart_window: None,
12319 children: vec![child.clone()],
12320 ..SupervisorSpec::default()
12321 };
12322 assert!(
12323 s.validate().is_ok(),
12324 "validate must accept restart_window: None (the never-reset \
12325 sentinel) — the `if let Some(_)` bracket returns early on \
12326 the None arm and the accessor must agree",
12327 );
12328 // Zero-floor arm.
12329 let s = SupervisorSpec {
12330 restart_window: Some(Duration::ZERO),
12331 children: vec![child.clone()],
12332 ..SupervisorSpec::default()
12333 };
12334 assert_eq!(
12335 s.validate().unwrap_err(),
12336 SupervisorError::RestartWindowZero,
12337 "validate must reject restart_window == Some(Duration::ZERO) \
12338 with RestartWindowZero — the accessor and the validate gate \
12339 must route through the same substrate-primitive typed \
12340 dispatch on the zero-floor arm",
12341 );
12342 // Non-canonical (sub-ms) arm — the surfaced `window:` field must
12343 // byte-equal the accessor's return so a future rebrand on the
12344 // accessor lands in the diagnostic without a coordinated rewrite.
12345 let sub_ms = Duration::from_micros(1500);
12346 let s = SupervisorSpec {
12347 restart_window: Some(sub_ms),
12348 children: vec![child.clone()],
12349 ..SupervisorSpec::default()
12350 };
12351 match s.validate().unwrap_err() {
12352 SupervisorError::RestartWindowNotCanonical { window } => {
12353 assert_eq!(
12354 Some(window),
12355 s.restart_window(),
12356 "RestartWindowNotCanonical.window must byte-equal \
12357 SupervisorSpec::restart_window().unwrap() — the \
12358 non-canonical-arm refusal reads through the lifted \
12359 accessor",
12360 );
12361 assert_eq!(
12362 window, sub_ms,
12363 "RestartWindowNotCanonical.window must carry the \
12364 author-declared :supervisor :restart-window value \
12365 verbatim (got {window:?}, expected {sub_ms:?})",
12366 );
12367 }
12368 other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
12369 }
12370 // Cap arm — the surfaced `window:` field must byte-equal the
12371 // accessor's return.
12372 let over_cap = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
12373 let s = SupervisorSpec {
12374 restart_window: Some(over_cap),
12375 children: vec![child.clone()],
12376 ..SupervisorSpec::default()
12377 };
12378 match s.validate().unwrap_err() {
12379 SupervisorError::RestartWindowExceedsCap { window } => {
12380 assert_eq!(
12381 Some(window),
12382 s.restart_window(),
12383 "RestartWindowExceedsCap.window must byte-equal \
12384 SupervisorSpec::restart_window().unwrap() — the \
12385 cap-arm refusal reads through the lifted accessor",
12386 );
12387 assert_eq!(
12388 window, over_cap,
12389 "RestartWindowExceedsCap.window must carry the \
12390 author-declared :supervisor :restart-window value \
12391 verbatim (got {window:?}, expected {over_cap:?})",
12392 );
12393 }
12394 other => panic!("expected RestartWindowExceedsCap, got {other:?}"),
12395 }
12396 // Lower + upper accept-set boundaries.
12397 for restart_window in [Duration::from_millis(1), SUPERVISOR_RESTART_WINDOW_MAX] {
12398 let s = SupervisorSpec {
12399 restart_window: Some(restart_window),
12400 children: vec![child.clone()],
12401 ..SupervisorSpec::default()
12402 };
12403 assert!(
12404 s.validate().is_ok(),
12405 "validate must accept restart_window == Some({restart_window:?}) \
12406 (an accept-set boundary of \
12407 1ms..=SUPERVISOR_RESTART_WINDOW_MAX)",
12408 );
12409 }
12410 }
12411
12412 #[test]
12413 fn supervisor_spec_restart_window_projects_option_duration_by_copy() {
12414 // The by-copy pin: [`SupervisorSpec::restart_window`] returns
12415 // `Option<Duration>` by copy — `Duration` is `Copy` (so
12416 // `Option<Duration>` is `Copy`) and the accessor must return by
12417 // value, not by reference. Peer of the sibling M2
12418 // [`crate::LimitsSpec::wall_clock`] (8cb717b) by-copy pin on the
12419 // per-`:limits :wall-clock` axis and the sibling M3
12420 // [`crate::MeshPolicy::timeout`] (7073d0f) by-copy pin on the
12421 // per-`:politicas :timeout` axis, extended onto the peer M2
12422 // supervisor-slot `Option<Duration>` copy-invariant shape — the
12423 // accessor's returned `Option<Duration>` must outlive `&self`
12424 // (multiple calls must return equal values from a dropped-`&self`
12425 // copy, since the returned Option carries no borrow), and calling
12426 // the accessor twice on the same SupervisorSpec must yield the
12427 // same `Option<Duration>` verbatim (idempotent, no side effects
12428 // on `&self`).
12429 //
12430 // Pins against a future silent detour that returned
12431 // `Option<&Duration>` (which would type-check but silently break
12432 // every downstream caller — the future wasm-operator's
12433 // per-supervisor restart-intensity counter consumes `Duration` by
12434 // value and `&Duration` would fold to a detached copy at the call
12435 // site), an accidental `Option::as_ref()` projection
12436 // (`self.restart_window.as_ref()` would also type-check but
12437 // return `Option<&Duration>`), or a one-arm-only accessor that
12438 // reads `Some(*w)` in the Some arm but reads a fresh
12439 // `Default::default()` (which would collapse to `Duration::ZERO`,
12440 // not `None`) in the None arm — a footgun the
12441 // [`SupervisorError::RestartWindowZero`] validate arm explicitly
12442 // closes since Erlang/OTP's `MaxIntensity / Period` invariant
12443 // requires `Period > 0` and `None` structurally expresses "never
12444 // reset" instead.
12445 for restart_window in [
12446 None,
12447 Some(Duration::from_millis(1)),
12448 Some(Duration::from_secs(60)),
12449 Some(SUPERVISOR_RESTART_WINDOW_MAX),
12450 ] {
12451 let s = SupervisorSpec {
12452 restart_window,
12453 ..SupervisorSpec::default()
12454 };
12455 let first = s.restart_window();
12456 let second = s.restart_window();
12457 assert_eq!(
12458 first, second,
12459 "SupervisorSpec::restart_window must be idempotent — two \
12460 successive calls on the same &self must return the \
12461 same Option<Duration>",
12462 );
12463 assert_eq!(
12464 first, restart_window,
12465 "SupervisorSpec::restart_window must return :supervisor \
12466 :restart-window verbatim by copy — got {first:?}, \
12467 expected {restart_window:?}",
12468 );
12469 }
12470 }
12471
12472 // ── per-`:supervisor` `:children` typed-accessor coherence pins ─────────
12473 //
12474 // The [`SupervisorSpec::children`] accessor lift is the seed of the
12475 // slice-return (`&[T]`) accessor discipline on the substrate — the four
12476 // peer `Vec`-carry axes ([`crate::Placement::clusters`],
12477 // [`crate::AplicacaoSpec::membros`], [`crate::AplicacaoSpec::contratos`],
12478 // [`crate::UpgradeFromEntry::instructions`]) still key off the raw field
12479 // access at the time of this seed, and inherit this pin family's
12480 // discipline as future compounding runs migrate their consumers. The
12481 // three pins below cover (1) the accessor's byte-equal projection
12482 // against the raw field access across the empty / singleton / cohort
12483 // fixtures the [`SupervisorSpec::validate`] partition-dispatch fans
12484 // between, (2) the [`SupervisorSpec::validate`] `SimpleOneForOne ↔
12485 // non-SimpleOneForOne` partition dispatch's paired `.is_empty()`
12486 // consumer routing through the accessor on both arms, and (3) the
12487 // per-child validate loop's traversal reading the same slice-view the
12488 // accessor projects. Peer of the sibling M2
12489 // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
12490 // two-consumer coherence pin on the per-`:supervisor`
12491 // sibling-restart-strategy `Copy`-composite-enum scalar axis, extended
12492 // onto the per-`:supervisor` static-child-list `Vec`-carry axis.
12493
12494 #[test]
12495 fn supervisor_spec_children_returns_children_slice_byte_equal_across_permutations() {
12496 // The canonical per-`:supervisor` static-child-list scalar-shape
12497 // pin: [`SupervisorSpec::children`] must return the `:supervisor
12498 // :children` typed `Vec<ChildSpec>` verbatim as a `&[ChildSpec]`
12499 // slice-view over the same backing buffer the raw
12500 // `self.children.as_slice()` field access borrows from, byte-
12501 // equal across every representative fixture in the accept-set —
12502 // the empty slice (the `SimpleOneForOne`-arm sentinel),
12503 // the singleton slice (the minimal non-`SimpleOneForOne` shape),
12504 // and a two-child cohort (a peer non-`SimpleOneForOne` shape
12505 // with the peer three restart-policy variants in play).
12506 //
12507 // Pins against a future silent detour that returned
12508 // `&Vec<ChildSpec>` (which would type-check but leak the
12509 // storage-side `Vec`'s grow/push/reserve surface no consumer of
12510 // the typed view reaches for), a fresh-allocated
12511 // `Vec<ChildSpec>` copy (which would type-check via a coercion
12512 // but silently break every downstream caller that relied on the
12513 // slice sharing the backing buffer's identity), or an
12514 // out-of-order or length-drifted projection (which would silently
12515 // split the per-child validate loop's traversal input from the
12516 // paired partition-dispatch `.is_empty()` probe's input).
12517 //
12518 // Peer of the sibling
12519 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
12520 // (eafb619) `Copy`-composite-enum byte-equal pin on the
12521 // per-`:supervisor` sibling-restart-strategy axis, extended onto
12522 // the per-`:supervisor` static-child-list `Vec`-carry axis.
12523 let fixtures: Vec<Vec<ChildSpec>> = vec![
12524 Vec::new(),
12525 vec![child("worker", "^0.1", RestartPolicy::Permanent)],
12526 vec![
12527 child("worker", "^0.1", RestartPolicy::Permanent),
12528 child("cache-server", "^0.1", RestartPolicy::Transient),
12529 ],
12530 vec![
12531 child("worker", "^0.1", RestartPolicy::Permanent),
12532 child("cache-server", "^0.1", RestartPolicy::Transient),
12533 child("scratch-job", "^0.1", RestartPolicy::Temporary),
12534 ],
12535 ];
12536 for children in fixtures {
12537 let s = SupervisorSpec {
12538 children: children.clone(),
12539 ..SupervisorSpec::default()
12540 };
12541 assert_eq!(
12542 s.children(),
12543 children.as_slice(),
12544 "SupervisorSpec::children must return :supervisor \
12545 :children verbatim (got {:?}, expected {:?})",
12546 s.children(),
12547 children.as_slice(),
12548 );
12549 assert_eq!(
12550 s.children(),
12551 s.children.as_slice(),
12552 "SupervisorSpec::children accessor and \
12553 .children.as_slice() field access must byte-equal — \
12554 the accessor is the substrate-primitive typed \
12555 dispatch every downstream static-child-list consumer \
12556 must route through",
12557 );
12558 assert_eq!(
12559 s.children().len(),
12560 s.children.len(),
12561 "SupervisorSpec::children().len() must byte-equal \
12562 self.children.len() — a length-drift would silently \
12563 split the paired partition-dispatch `.is_empty()` \
12564 probe input from the per-child validate loop's \
12565 traversal input",
12566 );
12567 }
12568 }
12569
12570 #[test]
12571 fn validate_reads_through_lifted_children_accessor() {
12572 // Three-consumer coherence pin: the [`SupervisorSpec::validate`]
12573 // `SimpleOneForOne`-arm `!self.children().is_empty()` refusal
12574 // probe (which must trip [`SupervisorError::SimpleOneForOneWithStaticChildren`]
12575 // when the accessor projects a non-empty slice under a
12576 // `SimpleOneForOne` estrategia), the peer non-`SimpleOneForOne`-arm
12577 // `self.children().is_empty()` refusal probe (which must trip
12578 // [`SupervisorError::NoChildren`] when the accessor projects the
12579 // empty slice under any peer estrategia), and the per-child
12580 // validate loop's `for child in self.children()` traversal
12581 // (which must reach every entry in the same order the accessor
12582 // projects) must all key off the lifted accessor, so any future
12583 // rebrand on the typed slot's reader shape lands at exactly one
12584 // place. Pins the three-site coherence by exercising each
12585 // production consumer end-to-end: (1) the
12586 // `SimpleOneForOneWithStaticChildren` refusal under a non-empty
12587 // slice + `SimpleOneForOne` estrategia, (2) the `NoChildren`
12588 // refusal under the empty slice + non-`SimpleOneForOne`
12589 // estrategia across every peer variant, and (3) the per-child
12590 // duplicate-detection surface fires on the second entry of a
12591 // two-child cohort that shares a `:caixa` name (which requires
12592 // the loop to reach both entries — a first-entry-only projection
12593 // would silently pass since the dedup HashSet has room for the
12594 // first insert).
12595 //
12596 // Peer of the sibling M2
12597 // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
12598 // two-consumer coherence pin on the per-`:supervisor`
12599 // sibling-restart-strategy axis, extended onto the
12600 // per-`:supervisor` static-child-list `Vec`-carry axis.
12601
12602 // (1) `SimpleOneForOne`-arm probe: a non-empty slice under a
12603 // `SimpleOneForOne` estrategia must trip
12604 // `SimpleOneForOneWithStaticChildren`.
12605 let s = SupervisorSpec {
12606 estrategia: RestartStrategy::SimpleOneForOne,
12607 children: vec![child("worker", "^0.1", RestartPolicy::Permanent)],
12608 ..SupervisorSpec::default()
12609 };
12610 assert_eq!(
12611 s.validate().unwrap_err(),
12612 SupervisorError::SimpleOneForOneWithStaticChildren,
12613 "SimpleOneForOne + non-empty children must trip \
12614 SimpleOneForOneWithStaticChildren — the accessor projects \
12615 a non-empty slice, and the SimpleOneForOne-arm refusal \
12616 probe reads through the lifted accessor",
12617 );
12618 assert!(
12619 !s.children().is_empty(),
12620 "the SimpleOneForOne-arm refusal input must be a non-empty \
12621 slice per the accessor's projection",
12622 );
12623
12624 // (2) Peer non-`SimpleOneForOne`-arm probe: the empty slice
12625 // under any peer estrategia must trip `NoChildren`.
12626 for estrategia in [
12627 RestartStrategy::OneForOne,
12628 RestartStrategy::OneForAll,
12629 RestartStrategy::RestForOne,
12630 ] {
12631 let s = SupervisorSpec {
12632 estrategia,
12633 children: Vec::new(),
12634 ..SupervisorSpec::default()
12635 };
12636 match s.validate().unwrap_err() {
12637 SupervisorError::NoChildren { estrategia: e } => {
12638 assert_eq!(
12639 e, estrategia,
12640 "NoChildren.estrategia must carry the author-\
12641 declared :supervisor :estrategia variant \
12642 verbatim (got {e:?}, expected {estrategia:?})",
12643 );
12644 }
12645 other => panic!(
12646 "expected NoChildren, got {other:?} for \
12647 estrategia={estrategia:?}"
12648 ),
12649 }
12650 assert!(
12651 s.children().is_empty(),
12652 "the non-SimpleOneForOne-arm refusal input must be the \
12653 empty slice per the accessor's projection",
12654 );
12655 }
12656
12657 // (3) Per-child validate loop: a two-child cohort that shares a
12658 // `:caixa` name must trip `DuplicateChildCaixa` — the loop must
12659 // reach both entries through the accessor.
12660 let s = SupervisorSpec {
12661 estrategia: RestartStrategy::OneForOne,
12662 children: vec![
12663 child("worker", "^0.1", RestartPolicy::Permanent),
12664 child("worker", "^0.2", RestartPolicy::Transient),
12665 ],
12666 ..SupervisorSpec::default()
12667 };
12668 match s.validate().unwrap_err() {
12669 SupervisorError::DuplicateChildCaixa { caixa } => {
12670 assert_eq!(
12671 caixa, "worker",
12672 "DuplicateChildCaixa.caixa must carry the shared \
12673 child `:caixa` name verbatim",
12674 );
12675 }
12676 other => panic!("expected DuplicateChildCaixa, got {other:?}"),
12677 }
12678 assert_eq!(
12679 s.children().len(),
12680 2,
12681 "the per-child validate loop's traversal input must be a \
12682 two-element slice per the accessor's projection",
12683 );
12684 }
12685
12686 // Shared helper for the M2 per-`:children` per-slot-gate ≡
12687 // `validate` equivalence pins: builds an `OneForOne`-estrategia
12688 // one-cohort spec whose peer `:estrategia`↔`:children.is_empty()`
12689 // partition, `:max-restarts` zero-floor/cap, and `:restart-window`
12690 // bracket all pass cleanly so the sole failing surface is the
12691 // per-child cascade [`SupervisorSpec::validate_children`] owns, and
12692 // pins the two-altitude equivalence on the paired probe.
12693 fn assert_validate_children_matches_gate(children: Vec<ChildSpec>, expected: &SupervisorError) {
12694 let s = SupervisorSpec {
12695 estrategia: RestartStrategy::OneForOne,
12696 children,
12697 ..SupervisorSpec::default()
12698 };
12699 let via_gate = s.validate_children().unwrap_err();
12700 let via_validate = s.validate().unwrap_err();
12701 assert_eq!(&via_gate, expected, "validate_children direct dispatch",);
12702 assert_eq!(&via_validate, expected, "validate() end-to-end dispatch",);
12703 assert_eq!(
12704 via_gate, via_validate,
12705 "per-slot gate ≡ validate() must discriminate the same \
12706 refusal shape",
12707 );
12708 }
12709
12710 #[test]
12711 fn validate_children_matches_gate_on_per_axis_refusal_shapes() {
12712 // Fail-before-pass-after equivalence pin on the M2
12713 // per-`:children` per-slot gate ≡ [`SupervisorSpec::validate`]
12714 // convergence — sibling of the M3 mesh-slot
12715 // `validate_membros_*` / `validate_contratos_*` /
12716 // `validate_entrada_*` per-slot-gate ≡ `validate` pins on the
12717 // peer per-entry axes. Sweeps four of the five refusal shapes
12718 // the per-slot gate owns: (1) `EmptyChildName` on an empty-
12719 // `:caixa` child, (2) `ChildCaixaInvalid` on a structurally
12720 // invalid `:caixa` DNS-1123 label, (3) `EmptyChildVersion` on
12721 // an empty-`:versao` child, (4) `DuplicateChildCaixa` on a
12722 // duplicate-`:caixa` fan-out. Companion pin
12723 // `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
12724 // covers `ChildVersaoInvalid` (whose parser-owned reason string
12725 // needs pattern-matching, not equality) and the clean-pass
12726 // canonical fixture; together the two pins guarantee the
12727 // per-slot gate and `validate` discriminate the same set on
12728 // every per-child-covered input.
12729 assert_validate_children_matches_gate(
12730 vec![child("", "^0.1", RestartPolicy::Permanent)],
12731 &SupervisorError::EmptyChildName,
12732 );
12733 assert_validate_children_matches_gate(
12734 vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
12735 &SupervisorError::ChildCaixaInvalid {
12736 caixa: "Worker".into(),
12737 reason: "contains uppercase character 'W' (K8s DNS-1123 label names are lowercase-only; use \"worker\")".into(),
12738 },
12739 );
12740 assert_validate_children_matches_gate(
12741 vec![child("worker", "", RestartPolicy::Permanent)],
12742 &SupervisorError::EmptyChildVersion {
12743 caixa: "worker".into(),
12744 },
12745 );
12746 assert_validate_children_matches_gate(
12747 vec![
12748 child("worker", "^0.1", RestartPolicy::Permanent),
12749 child("worker", "^0.2", RestartPolicy::Transient),
12750 ],
12751 &SupervisorError::DuplicateChildCaixa {
12752 caixa: "worker".into(),
12753 },
12754 );
12755 }
12756
12757 #[test]
12758 fn validate_children_matches_gate_on_versao_invalid_and_clean_pass() {
12759 // Second half of the two-altitude equivalence pin — covers the
12760 // one refusal shape whose reason string is parser-owned
12761 // (`ChildVersaoInvalid`, whose reason comes from the shared
12762 // [`crate::version::parse_requirement`] impl and may drift) and
12763 // the clean-pass canonical fixture. Sibling pin
12764 // `validate_children_matches_gate_on_per_axis_refusal_shapes`
12765 // covers the four equality-comparable refusal shapes.
12766 let s_bad_versao = SupervisorSpec {
12767 estrategia: RestartStrategy::OneForOne,
12768 children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
12769 ..SupervisorSpec::default()
12770 };
12771 let via_gate = s_bad_versao.validate_children().unwrap_err();
12772 let via_validate = s_bad_versao.validate().unwrap_err();
12773 match (&via_gate, &via_validate) {
12774 (
12775 SupervisorError::ChildVersaoInvalid {
12776 caixa: cg,
12777 versao: vg,
12778 ..
12779 },
12780 SupervisorError::ChildVersaoInvalid {
12781 caixa: cv,
12782 versao: vv,
12783 ..
12784 },
12785 ) => {
12786 assert_eq!(cg, "worker", "per-slot gate :caixa carrier");
12787 assert_eq!(vg, "not-a-req", "per-slot gate :versao carrier");
12788 assert_eq!(cv, "worker", "validate() :caixa carrier");
12789 assert_eq!(vv, "not-a-req", "validate() :versao carrier");
12790 }
12791 other => panic!("expected ChildVersaoInvalid on both altitudes, got {other:?}"),
12792 }
12793 assert_eq!(
12794 via_gate, via_validate,
12795 "per-slot gate ≡ validate() on ChildVersaoInvalid full envelope",
12796 );
12797
12798 let s_ok = SupervisorSpec {
12799 estrategia: RestartStrategy::OneForOne,
12800 children: vec![
12801 child("worker-a", "^0.1", RestartPolicy::Permanent),
12802 child("worker-b", "~0.2.3", RestartPolicy::Transient),
12803 child("collector", "*", RestartPolicy::Temporary),
12804 ],
12805 ..SupervisorSpec::default()
12806 };
12807 s_ok.validate_children()
12808 .expect("per-slot gate must accept the clean-pass fixture");
12809 s_ok.validate()
12810 .expect("validate() must accept the clean-pass fixture");
12811 }
12812
12813 #[test]
12814 fn validate_children_is_self_contained_on_children_slot() {
12815 // Self-containment pin: [`SupervisorSpec::validate_children`]
12816 // resolves the per-child cascade against `&self` alone, without
12817 // depending on the peer `:estrategia`/`:max-restarts`/
12818 // `:restart-window` gates having run first — same posture the M3
12819 // peer per-slot gates carry (`validate_membros`,
12820 // `validate_contratos`, `validate_entrada`, `validate_placement`,
12821 // routing through their own oracles rather than borrowing state
12822 // threaded down from `validate`). A future consumer that reaches
12823 // the per-slot gate directly on a spec whose peer slots would
12824 // fail `validate` still surfaces the per-child refusal, not the
12825 // peer refusal.
12826 //
12827 // Construct a spec whose `:max-restarts` is `0` (which would
12828 // trip [`SupervisorError::ZeroMaxRestarts`] at `validate` after
12829 // the partition-dispatch) and whose `:children` carries a
12830 // `DuplicateChildCaixa` shape: the per-slot gate called directly
12831 // must surface `DuplicateChildCaixa`, proving it does not depend
12832 // on the peer `:max-restarts` gate running first.
12833 let s = SupervisorSpec {
12834 estrategia: RestartStrategy::OneForOne,
12835 max_restarts: 0,
12836 restart_window: Some(Duration::from_secs(60)),
12837 children: vec![
12838 child("worker", "^0.1", RestartPolicy::Permanent),
12839 child("worker", "^0.2", RestartPolicy::Transient),
12840 ],
12841 };
12842 assert_eq!(
12843 s.validate_children().unwrap_err(),
12844 SupervisorError::DuplicateChildCaixa {
12845 caixa: "worker".into(),
12846 },
12847 "per-slot gate must resolve per-child refusal directly against \
12848 `&self` — a dependency on the peer `:max-restarts` gate \
12849 running first would surface ZeroMaxRestarts here instead",
12850 );
12851 // The peer gate is still the surface `validate` reaches — pin
12852 // the ordering to establish that `validate_children` truly runs
12853 // last in `validate`'s dispatch, so a direct call bypasses the
12854 // peer gates on any spec whose per-child cascade would fail.
12855 assert_eq!(
12856 s.validate().unwrap_err(),
12857 SupervisorError::ZeroMaxRestarts,
12858 "validate() must surface the peer `:max-restarts` gate before \
12859 reaching the per-child cascade — this pins the dispatch \
12860 ordering the per-slot gate's self-containment complements",
12861 );
12862 }
12863
12864 #[test]
12865 fn child_spec_restart_accessor_is_const_fn() {
12866 // The [`ChildSpec::restart`] per-`:children` restart-decision-
12867 // policy `Copy`-return scalar accessor is declared
12868 // `#[must_use] pub const fn` — matching the sibling M2
12869 // per-`:supervisor` [`SupervisorSpec::estrategia`] (pinned by
12870 // [`supervisor_spec_estrategia_accessor_is_const_fn`] below,
12871 // both converted in this commit), the sibling M2
12872 // per-`:supervisor` [`SupervisorSpec::max_restarts`] (b698ec0)
12873 // `Copy`-`u32` accessor already `pub const fn`, and the peer M3
12874 // mesh-slot per-`:entrada` [`crate::Entrada::port`] (bafa004) /
12875 // per-`:placement` [`crate::Placement::estrategia`] (bafa004)
12876 // `Copy`-return `pub const fn` scalar accessors on the sibling
12877 // M3 surface. Pin the `const`-eval posture here so a future
12878 // accidental downgrade to non-`const` (an added runtime helper
12879 // reachable only from a non-`const` context, an
12880 // `Option<RestartPolicy>`-shape migration on the per-child
12881 // restart-decision axis once heterogeneous per-cluster
12882 // restart-policy overlays land that would silently drop the
12883 // `const` qualifier, a manual hand-rolled shadow) trips at
12884 // caixa-core build time rather than surfacing as a downstream
12885 // `const`-context regression far from the declaration.
12886 //
12887 // Same shape as the sibling M3
12888 // [`crate::aplicacao::tests::placement_estrategia_accessor_is_const_fn`]
12889 // and [`crate::aplicacao::tests::entrada_port_accessor_is_const_fn`]
12890 // (bafa004) pins on the peer M3 mesh-slot `Copy`-return scalar
12891 // accessor axis — the load-bearing witness lives in the
12892 // module-scope `const fn` wrapper `restart_via_const_fn` below:
12893 // a body that calls [`ChildSpec::restart`] under a `const fn`
12894 // signature is well-formed only when the callee is itself
12895 // `const fn`, so any future accidental downgrade of
12896 // [`ChildSpec::restart`] to non-`const` fails at caixa-core
12897 // build time (const-eval E0015 `cannot call non-const method`),
12898 // strictly stronger than a runtime `assert!(CONST)` and
12899 // side-stepping the destructor-in-const restriction that
12900 // blocks direct `const _: RestartPolicy = FIXTURE.restart()`
12901 // items on `ChildSpec`'s `String` carriers.
12902 //
12903 // The runtime body sweeps every closed-set [`RestartPolicy`]
12904 // arm and asserts the wrapped and direct dispatches agree.
12905 const fn restart_via_const_fn(c: &ChildSpec) -> RestartPolicy {
12906 c.restart()
12907 }
12908 for restart in [
12909 RestartPolicy::Permanent,
12910 RestartPolicy::Transient,
12911 RestartPolicy::Temporary,
12912 ] {
12913 let c = ChildSpec {
12914 caixa: "worker".into(),
12915 versao: "^0.1".into(),
12916 restart,
12917 };
12918 assert_eq!(
12919 restart_via_const_fn(&c),
12920 c.restart(),
12921 "const-fn-wrapped and direct dispatch on \
12922 ChildSpec::restart must agree for {restart:?}",
12923 );
12924 assert_eq!(
12925 c.restart(),
12926 restart,
12927 "ChildSpec::restart must return the storage-side \
12928 RestartPolicy verbatim for {restart:?} (a violation \
12929 means the accessor stopped being a raw field-return \
12930 copy)",
12931 );
12932 }
12933 }
12934
12935 #[test]
12936 fn supervisor_spec_estrategia_accessor_is_const_fn() {
12937 // The [`SupervisorSpec::estrategia`] per-`:supervisor`
12938 // sibling-restart-strategy `Copy`-return scalar accessor is
12939 // declared `#[must_use] pub const fn` — matching the sibling M2
12940 // per-`:children` [`ChildSpec::restart`] (pinned by
12941 // [`child_spec_restart_accessor_is_const_fn`] above, both
12942 // converted in this commit), the sibling M2 per-`:supervisor`
12943 // [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32`
12944 // accessor already `pub const fn`, and mirroring the peer M3
12945 // mesh-slot per-`:placement`
12946 // [`crate::Placement::estrategia`] (bafa004) `Copy`-return
12947 // `pub const fn` scalar accessor whose method-name discipline
12948 // the [`SupervisorSpec::estrategia`] method was authored to
12949 // match. Pin the `const`-eval posture here so a future
12950 // accidental downgrade to non-`const` (an added runtime helper
12951 // reachable only from a non-`const` context, an
12952 // `Option<RestartStrategy>`-shape migration once the substrate
12953 // grows per-cluster strategy overlays that would silently drop
12954 // the `const` qualifier, a manual hand-rolled shadow) trips at
12955 // caixa-core build time rather than surfacing as a downstream
12956 // `const`-context regression far from the declaration.
12957 //
12958 // Same shape as the sibling
12959 // [`child_spec_restart_accessor_is_const_fn`] pin above — the
12960 // load-bearing witness lives in the module-scope `const fn`
12961 // wrapper `estrategia_via_const_fn` below: a body that calls
12962 // [`SupervisorSpec::estrategia`] under a `const fn` signature
12963 // is well-formed only when the callee is itself `const fn`,
12964 // side-stepping the destructor-in-const restriction that would
12965 // otherwise block a direct
12966 // `const _: RestartStrategy = FIXTURE.estrategia()` item on
12967 // `SupervisorSpec`'s `Vec<ChildSpec>` / `Option<Duration>`
12968 // carriers.
12969 //
12970 // The runtime body sweeps every closed-set [`RestartStrategy`]
12971 // arm via [`RestartStrategy::ALL`] and asserts the wrapped and
12972 // direct dispatches agree.
12973 const fn estrategia_via_const_fn(s: &SupervisorSpec) -> RestartStrategy {
12974 s.estrategia()
12975 }
12976 for &estrategia in RestartStrategy::ALL {
12977 let s = SupervisorSpec {
12978 estrategia,
12979 max_restarts: 5,
12980 restart_window: Some(Duration::from_secs(60)),
12981 children: Vec::new(),
12982 };
12983 assert_eq!(
12984 estrategia_via_const_fn(&s),
12985 s.estrategia(),
12986 "const-fn-wrapped and direct dispatch on \
12987 SupervisorSpec::estrategia must agree for {estrategia:?}",
12988 );
12989 assert_eq!(
12990 s.estrategia(),
12991 estrategia,
12992 "SupervisorSpec::estrategia must return the storage-side \
12993 RestartStrategy verbatim for {estrategia:?} (a violation \
12994 means the accessor stopped being a raw field-return \
12995 copy)",
12996 );
12997 }
12998 }
12999
13000 // Per-variant equivalence pins for the [`supervisor_caixa_only_ctors!`]
13001 // macro definition (see the paired doc-block above the macro
13002 // definition) — every generated `<ctor>(caixa: &str) -> Self`
13003 // constructor folds the uniform `Self::<Variant> { caixa:
13004 // caixa.to_string() }` one-field struct-literal onto one substrate
13005 // primitive. The three per-variant equivalence pins below
13006 // (fail-before-pass-after by construction — a byte-mismatched macro
13007 // arm would trip its equivalence pin first) lock each generated
13008 // constructor to its struct-literal peer under `PartialEq`, so
13009 // every wire-up in [`SupervisorSpec::validate_children`] and
13010 // [`validate_no_self_supervision`] on that variant produces a
13011 // byte-equal `SupervisorError` to the pre-lift open-coded
13012 // struct-literal. The cross-axis pin that follows (non-default
13013 // caixa name) routes the sole constructor input axis through
13014 // `.to_string()`, so the fold does not silently collapse onto a
13015 // fixed name.
13016 //
13017 // Peer of the sibling `<slot>_ctor_matches_tuple_literal_wrap` /
13018 // `<slot>_violation_ctor_matches_struct_literal_wrap` /
13019 // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
13020 // `missing_entry_ctor_matches_struct_literal_wrap` /
13021 // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
13022 // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
13023 // `contrato_missing_target_ctor_matches_struct_literal_wrap` /
13024 // `<variant>_ctor_matches_struct_literal_wrap` equivalence pins
13025 // on the six sibling ctor families the recent trajectory closed
13026 // on the peer `LayoutError` / `AplicacaoError` envelopes.
13027
13028 #[test]
13029 fn empty_child_version_ctor_matches_struct_literal_wrap() {
13030 assert_eq!(
13031 SupervisorError::empty_child_version("worker"),
13032 SupervisorError::EmptyChildVersion {
13033 caixa: "worker".to_string(),
13034 },
13035 "generated empty_child_version ctor must produce byte-equal \
13036 SupervisorError to the open-coded struct-literal wrap on the \
13037 same &str fixture",
13038 );
13039 }
13040
13041 #[test]
13042 fn duplicate_child_caixa_ctor_matches_struct_literal_wrap() {
13043 assert_eq!(
13044 SupervisorError::duplicate_child_caixa("worker"),
13045 SupervisorError::DuplicateChildCaixa {
13046 caixa: "worker".to_string(),
13047 },
13048 "generated duplicate_child_caixa ctor must produce byte-equal \
13049 SupervisorError to the open-coded struct-literal wrap on the \
13050 same &str fixture",
13051 );
13052 }
13053
13054 #[test]
13055 fn child_supervises_self_ctor_matches_struct_literal_wrap() {
13056 assert_eq!(
13057 SupervisorError::child_supervises_self("orquestra"),
13058 SupervisorError::ChildSupervisesSelf {
13059 caixa: "orquestra".to_string(),
13060 },
13061 "generated child_supervises_self ctor must produce byte-equal \
13062 SupervisorError to the open-coded struct-literal wrap on the \
13063 same &str fixture",
13064 );
13065 }
13066
13067 // Per-variant equivalence pins for the two lifted
13068 // [`SupervisorError::child_caixa_invalid`] /
13069 // [`SupervisorError::child_versao_invalid`] inherent constructors
13070 // (fail-before-pass-after by construction — a byte-mismatched ctor body
13071 // would trip its equivalence pin first). Each pins the ctor output to
13072 // its pre-lift struct-literal peer under `PartialEq`, so every wire-up
13073 // in [`SupervisorSpec::validate_children`] on the two variants
13074 // produces a byte-equal `SupervisorError` to the pre-lift open-coded
13075 // struct-literal on the same scalar fixtures. Peers of the sibling
13076 // `membro_caixa_invalid_ctor_matches_struct_literal_wrap` /
13077 // `entrada_para_invalid_ctor_matches_struct_literal_wrap` / … pins on
13078 // the peer `AplicacaoError` envelope's
13079 // [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold.
13080
13081 #[test]
13082 fn child_caixa_invalid_ctor_matches_struct_literal_wrap() {
13083 let caixa = "Worker";
13084 let reason = "sample reason text";
13085 assert_eq!(
13086 SupervisorError::child_caixa_invalid(caixa, reason),
13087 SupervisorError::ChildCaixaInvalid {
13088 caixa: caixa.to_string(),
13089 reason: reason.to_string(),
13090 },
13091 "lifted child_caixa_invalid ctor must produce byte-equal \
13092 SupervisorError to the open-coded struct-literal wrap on the \
13093 same (&str, reason) fixture",
13094 );
13095 }
13096
13097 #[test]
13098 fn child_versao_invalid_ctor_matches_struct_literal_wrap() {
13099 let caixa = "worker";
13100 let versao = "not-a-req";
13101 let reason = "sample reason text";
13102 assert_eq!(
13103 SupervisorError::child_versao_invalid(caixa, versao, reason),
13104 SupervisorError::ChildVersaoInvalid {
13105 caixa: caixa.to_string(),
13106 versao: versao.to_string(),
13107 reason: reason.to_string(),
13108 },
13109 "lifted child_versao_invalid ctor must produce byte-equal \
13110 SupervisorError to the open-coded struct-literal wrap on the \
13111 same (&str, &str, reason) fixture",
13112 );
13113 }
13114
13115 #[test]
13116 fn supervisor_child_reason_ctors_route_reason_through_into_uniformly() {
13117 // Cross-axis pin: sweep the two lifted `{ …, reason }` ctors
13118 // against a `&str`-literal vs. `format!(…)` reason input to pin
13119 // both constructors accept the `impl Into<String>` bound
13120 // uniformly, so neither wire-up site drifts under a per-arm
13121 // wrapper transformation on the caller-side `reason` axis. Peer
13122 // of the sibling
13123 // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
13124 // sweep on the peer `AplicacaoError` envelope.
13125 let via_literal = "literal reason text";
13126 let via_format = format!("{} reason text", "literal");
13127 assert_eq!(
13128 SupervisorError::child_caixa_invalid("Worker", via_literal),
13129 SupervisorError::child_caixa_invalid("Worker", via_format.clone()),
13130 );
13131 assert_eq!(
13132 SupervisorError::child_versao_invalid("worker", "not-a-req", via_literal),
13133 SupervisorError::child_versao_invalid("worker", "not-a-req", via_format),
13134 );
13135 }
13136
13137 #[test]
13138 fn supervisor_caixa_only_ctors_route_caixa_through_to_string() {
13139 // Cross-axis pin: sweep the sole constructor input axis (`caixa:
13140 // &str`) through a non-default fixture name against every
13141 // generated arm in the [`supervisor_caixa_only_ctors!`] macro,
13142 // so any wrapper-side lowercase / trim / truncate / re-order on
13143 // the `caixa.to_string()` sole-field construction surfaces
13144 // here rather than at a downstream diagnostic-shape mismatch.
13145 // Peer of the sibling `nome_only_ctor_routes_caixa_through_
13146 // nome_accessor` / `entrada_host_invalid_ctor_routes_host_
13147 // through_to_string` / `contrato_target_ctors_route_edge_
13148 // triple_through_verbatim` / `contrato_empty_pair_ctors_
13149 // route_edge_pair_through_verbatim` cross-axis routing pins on
13150 // the peer `LayoutError` / `AplicacaoError` envelopes; extended
13151 // here onto the `SupervisorError` `{ caixa: String }` envelope
13152 // so every substrate-primitive ctor family in caixa-core
13153 // guarantees the sole-field construction routes the caller's
13154 // `&str` through `.to_string()` verbatim.
13155 let name = "cache-v2";
13156 assert_eq!(
13157 SupervisorError::empty_child_version(name),
13158 SupervisorError::EmptyChildVersion {
13159 caixa: name.to_string(),
13160 },
13161 );
13162 assert_eq!(
13163 SupervisorError::duplicate_child_caixa(name),
13164 SupervisorError::DuplicateChildCaixa {
13165 caixa: name.to_string(),
13166 },
13167 );
13168 assert_eq!(
13169 SupervisorError::child_supervises_self(name),
13170 SupervisorError::ChildSupervisesSelf {
13171 caixa: name.to_string(),
13172 },
13173 );
13174 }
13175
13176 // ── supervisor_scalar_ctors! per-variant + cross-axis pins ──────────────
13177 //
13178 // Per-variant byte-equality pins guaranteeing every generated ctor arm in
13179 // the [`supervisor_scalar_ctors!`] macro produces a `SupervisorError`
13180 // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
13181 // one-line struct-literal on the same `Copy`-`RestartStrategy | u32 |
13182 // Duration` fixture, plus one cross-axis sweep that routes each per-variant
13183 // `<field>: <ty>` scalar through the sole `$field:ident: $ty:ty` axis the
13184 // macro exposes so any wrapper-side truncation / re-order / silent `.into()`
13185 // / silent constant-substitution on any one variant surfaces here rather
13186 // than at a downstream per-`:supervisor` diagnostic-shape drift. Peer of the
13187 // sibling per-variant pins on `aplicacao_policy_scalar_ctors!` (7ef425e,
13188 // the 8-variant `AplicacaoError` `{ <field>: Duration | u32 }` fold on the
13189 // per-`:politicas` per-axis cap / canonical-form arms), plus the sibling
13190 // `supervisor_caixa_only_ctors!` (db09650), `SupervisorError::
13191 // {child_caixa_invalid,child_versao_invalid}` (d2ef2ec), and the peer
13192 // `DepError` / `AplicacaoError` / `LayoutError` / `LimitsError` /
13193 // `BehaviorError` / `UpgradeError` per-envelope ctor-macro pins.
13194 #[test]
13195 fn no_children_ctor_matches_struct_literal_wrap() {
13196 let estrategia = RestartStrategy::OneForAll;
13197 assert_eq!(
13198 SupervisorError::no_children(estrategia),
13199 SupervisorError::NoChildren { estrategia },
13200 "generated no_children ctor must produce byte-equal \
13201 `SupervisorError::NoChildren` to the pre-lift struct-literal wrap \
13202 on the same `Copy`-`RestartStrategy` fixture",
13203 );
13204 }
13205
13206 #[test]
13207 fn max_restarts_exceeds_cap_ctor_matches_struct_literal_wrap() {
13208 let max_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 1;
13209 assert_eq!(
13210 SupervisorError::max_restarts_exceeds_cap(max_restarts),
13211 SupervisorError::MaxRestartsExceedsCap { max_restarts },
13212 "generated max_restarts_exceeds_cap ctor must produce byte-equal \
13213 `SupervisorError::MaxRestartsExceedsCap` to the pre-lift \
13214 struct-literal wrap on the same `Copy`-`u32` fixture",
13215 );
13216 }
13217
13218 #[test]
13219 fn restart_window_not_canonical_ctor_matches_struct_literal_wrap() {
13220 let window = Duration::from_micros(1_500);
13221 assert_eq!(
13222 SupervisorError::restart_window_not_canonical(window),
13223 SupervisorError::RestartWindowNotCanonical { window },
13224 "generated restart_window_not_canonical ctor must produce \
13225 byte-equal `SupervisorError::RestartWindowNotCanonical` to the \
13226 pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
13227 );
13228 }
13229
13230 #[test]
13231 fn restart_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
13232 let window = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
13233 assert_eq!(
13234 SupervisorError::restart_window_exceeds_cap(window),
13235 SupervisorError::RestartWindowExceedsCap { window },
13236 "generated restart_window_exceeds_cap ctor must produce \
13237 byte-equal `SupervisorError::RestartWindowExceedsCap` to the \
13238 pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
13239 );
13240 }
13241
13242 #[test]
13243 fn supervisor_scalar_ctors_route_field_through_copy_uniformly() {
13244 // Cross-axis routing pin: sweep each generated `<field>: <ty>`
13245 // constructor input axis through a non-default `Copy` fixture against
13246 // every arm in the [`supervisor_scalar_ctors!`] macro, so any wrapper-
13247 // side silent `.into()` / silent constant-substitution / silent field
13248 // re-name away from the canonical `estrategia | max_restarts | window`
13249 // axes on any one variant, or a `RestartStrategy | u32 | Duration`
13250 // axis silently rerouted through some other `Copy` coercion, surfaces
13251 // here rather than at a downstream per-`:supervisor` diagnostic-shape
13252 // drift. Peer of the sibling
13253 // `aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly`
13254 // (7ef425e) cross-axis routing pin on the peer `AplicacaoError`
13255 // envelope's per-`:politicas` per-axis ctor family, extended here onto
13256 // the last M2 per-`:supervisor` `Copy`-scalar `SupervisorError`
13257 // variant family folded onto a substrate primitive.
13258 //
13259 // Fixtures picked out of each variant's accept-set boundary rather
13260 // than the default value so a silent constant-substitution to a per-
13261 // variant sentinel surfaces here on the structural-equality assertion.
13262 // The `RestartStrategy` fixture picks `RestForOne` (a non-default arm
13263 // that isn't the `OneForOne` [`SUPERVISOR_ESTRATEGIA_DEFAULT`] and
13264 // isn't the `SimpleOneForOne` arm the sibling
13265 // `SimpleOneForOneWithStaticChildren` unit variant intercepts). The
13266 // `max_restarts` fixture picks an above-cap magnitude the cap arm
13267 // rejects; the two `Duration` fixtures pick the sub-millisecond and
13268 // above-cap ends of the `:restart-window` canonical-form + cap
13269 // bracket respectively.
13270 let estrategia = RestartStrategy::RestForOne;
13271 let above_cap_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 137;
13272 let sub_ms = Duration::from_micros(1_500);
13273 let above_hour = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
13274 assert_eq!(
13275 SupervisorError::no_children(estrategia),
13276 SupervisorError::NoChildren { estrategia },
13277 );
13278 assert_eq!(
13279 SupervisorError::max_restarts_exceeds_cap(above_cap_restarts),
13280 SupervisorError::MaxRestartsExceedsCap {
13281 max_restarts: above_cap_restarts,
13282 },
13283 );
13284 assert_eq!(
13285 SupervisorError::restart_window_not_canonical(sub_ms),
13286 SupervisorError::RestartWindowNotCanonical { window: sub_ms },
13287 );
13288 assert_eq!(
13289 SupervisorError::restart_window_exceeds_cap(above_hour),
13290 SupervisorError::RestartWindowExceedsCap { window: above_hour },
13291 );
13292 }
13293
13294 #[test]
13295 fn supervisor_scalar_ctors_are_const_zero_runtime_work() {
13296 // Const-eval pin: the [`supervisor_scalar_ctors!`] macro spells every
13297 // generated ctor `const fn` so a caller can pin a `SupervisorError`
13298 // at compile time — the same zero-runtime-work property the pre-lift
13299 // `|<slot>| SupervisorError::<Variant> { <slot> }` closure carried on
13300 // its `Copy`-pass-through construction path (no `.to_string()` /
13301 // `.into()` allocation, no branching). If any future edit silently
13302 // drops the `const` qualifier from the macro body the per-arm `const`
13303 // bindings below fail to compile, which surfaces the regression at
13304 // the substrate-primitive definition rather than at some downstream
13305 // consumer that had come to rely on the `const`-constructibility.
13306 // Peer of the sibling
13307 // `aplicacao_policy_scalar_ctors_are_const_zero_runtime_work`
13308 // (7ef425e) const-eval pin on the peer `AplicacaoError` envelope's
13309 // per-`:politicas` per-axis ctor family.
13310 const NO_CHILDREN: SupervisorError =
13311 SupervisorError::no_children(RestartStrategy::OneForAll);
13312 const MAX_RESTARTS_CAP: SupervisorError = SupervisorError::max_restarts_exceeds_cap(1_337);
13313 const WINDOW_NC: SupervisorError =
13314 SupervisorError::restart_window_not_canonical(Duration::from_micros(1));
13315 const WINDOW_CAP: SupervisorError =
13316 SupervisorError::restart_window_exceeds_cap(Duration::from_secs(3_601));
13317 assert!(matches!(NO_CHILDREN, SupervisorError::NoChildren { .. }));
13318 assert!(matches!(
13319 MAX_RESTARTS_CAP,
13320 SupervisorError::MaxRestartsExceedsCap { .. }
13321 ));
13322 assert!(matches!(
13323 WINDOW_NC,
13324 SupervisorError::RestartWindowNotCanonical { .. }
13325 ));
13326 assert!(matches!(
13327 WINDOW_CAP,
13328 SupervisorError::RestartWindowExceedsCap { .. }
13329 ));
13330 }
13331}