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/// Per-child restart policy.
705///
706/// Permanent / Temporary / Transient match Erlang/OTP semantics 1:1.
707#[derive(
708 Serialize,
709 Deserialize,
710 Debug,
711 Clone,
712 Copy,
713 PartialEq,
714 Eq,
715 Hash,
716 gen_platform::TypedDispatcher,
717 gen_platform::Discriminant,
718 gen_platform::IsVariant,
719 gen_platform::FromStrKind,
720)]
721pub enum RestartPolicy {
722 /// Always restart the child, regardless of how it died. Used for
723 /// long-running services that must always be up.
724 Permanent,
725 /// Never restart. Used for one-shot work whose completion is
726 /// itself the success signal (`oneShot` triggers map here).
727 Temporary,
728 /// Restart only when the child died *abnormally* (non-zero exit
729 /// or unhandled exception). A clean exit completes the child.
730 Transient,
731}
732
733impl Default for RestartPolicy {
734 fn default() -> Self {
735 // Route the [`Default for RestartPolicy`] impl's return arm through
736 // the substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed
737 // `pub const` rather than a raw `Self::Permanent` arm — one source
738 // of truth for the Erlang/OTP-canonical `permanent` worker-child
739 // default across the two production consumers that currently
740 // dispatch on it (this impl at the [`RestartPolicy::default`] call
741 // and the serde-side `#[serde(default)]` on
742 // [`ChildSpec::restart`] that resolves an author-omitted
743 // `:children :restart` slot through `RestartPolicy::default()`).
744 // Peer of the sibling per-`:supervisor` axis
745 // [`Default for RestartStrategy`] → [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
746 // route (95ffacc) — the two impls now share one substrate-primitive
747 // lift discipline, so any future coherent rebrand of the OTP-shape
748 // supervisor+child default set migrates through typed constants in
749 // lockstep instead of splitting a lifted supervisor half against
750 // an open-coded child half. Pinned by
751 // `restart_policy_default_routes_through_lifted_default` +
752 // `child_spec_serde_default_restart_routes_through_lifted_default`
753 // in the tests module.
754 SUPERVISOR_CHILD_RESTART_DEFAULT
755 }
756}
757
758impl RestartPolicy {
759 /// Exhaustive iteration surface for every consumer that walks the
760 /// closed three-arm [`RestartPolicy`] discriminator set (the future
761 /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
762 /// per-child admission-webhook rejection body naming the accepted-
763 /// `:restart` list, a future `feira supervisor --restart …` CLI
764 /// arg-parse's "did you mean" hint via a [`Self::from_wire`]-scan
765 /// over the slice, the future `feira app graph` per-child restart
766 /// column, any future round-trip fuzz harness that sweeps every
767 /// arm). A future arm addition (an OTP-`intrinsic` fourth arm the
768 /// theory
769 /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
770 /// might reach for once the three canonical OTP restart policies
771 /// stop covering the substrate's discovered load-shape) extends
772 /// this slice as one edit and every consumer picks up the new entry
773 /// by construction; the compiler-checked exhaustiveness on the
774 /// sibling method `match` arms ([`Self::as_str`] / [`Self::from_wire`])
775 /// is the build-time guarantee that no arm forgets to grow.
776 ///
777 /// Peer of the sibling closed-set typed enums'
778 /// [`RestartStrategy::ALL`] (4eec29c) /
779 /// [`crate::CaixaKind::ALL`] (6b1f4fb) /
780 /// [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
781 /// [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
782 /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
783 /// surfaces — the sixth (and the third and final M2 OTP-shape)
784 /// closed-set typed enum on the caixa surface to converge onto the
785 /// same one-canonical-arm-list-per-enum discipline. Sibling axis to
786 /// the peer [`RestartStrategy::ALL`] on the per-supervisor
787 /// sibling-restart-strategy axis; this closes the per-child
788 /// restart-decision-policy axis on the same M2 `:supervisor` slot.
789 pub const ALL: &'static [Self] = &[Self::Permanent, Self::Temporary, Self::Transient];
790
791 /// Canonical PascalCase discriminator scalar this variant serializes
792 /// as under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`]. The three
793 /// arms return the paired
794 /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
795 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
796 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] lifted
797 /// constants so every substrate consumer that dispatches on the
798 /// per-child restart-decision policy (the future wasm-operator's
799 /// per-child post-exit restart-decision branch, the future M4
800 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
801 /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
802 /// reconciliation scheduler's per-child-policy fan-out) reads the
803 /// same byte-string the `Serialize` derive emits — the pin test in
804 /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
805 /// asserts the two paths agree, peer of the M2
806 /// [`RestartStrategy::as_str`] (09ffb2d) on the sibling per-supervisor
807 /// sibling-restart-strategy axis and the M3
808 /// [`crate::aplicacao::PlacementStrategy::as_str`] (cc8f749) on the
809 /// per-Aplicacao distribution-strategy axis — the third of three
810 /// OTP-shaped closed-enum discriminator axes on the caixa typed
811 /// surface to converge onto the same three-path-convergence
812 /// (`Serialize` derive → `as_str` helper → lifted constant)
813 /// drift-detection posture.
814 #[must_use]
815 pub const fn as_str(self) -> &'static str {
816 match self {
817 Self::Permanent => crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
818 Self::Temporary => crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
819 Self::Transient => crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
820 }
821 }
822
823 /// Substrate-canonical reverse projection on the `:children :restart`
824 /// closed-set axis — parses the `PascalCase` discriminator scalar
825 /// back to the typed variant, or `None` when `s` is outside the
826 /// closed-set arm-string set [`Self::as_str`] emits. Dispatches on
827 /// the same lifted
828 /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
829 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
830 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] constants
831 /// the [`Self::as_str`] emitter walks, so the parse and emit halves
832 /// of the round-trip migrate through one caixa-core edit on any
833 /// future arm addition.
834 ///
835 /// Prior to this lift the substrate carried only the forward
836 /// `Self → &str` projection on the OTP per-child restart-policy
837 /// axis (the [`Self::as_str`] emitter, the [`std::fmt::Display`]
838 /// impl routed through it, the `Serialize` derive that emits the
839 /// same byte-string under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`])
840 /// plus the kebab-case dispatcher-catalog identity via
841 /// [`Self::discriminant`] — every non-serde consumer that wanted to
842 /// parse a wire-form `PascalCase` policy scalar had to re-inline a
843 /// three-arm `match s { "Permanent" => …, "Temporary" => …,
844 /// "Transient" => …, _ => … }` cascade that expressed no
845 /// compile-time link back to the typed variant's canonical lifted
846 /// constant. A future variant rename or per-arm serde-attribute
847 /// drift would silently split the wire byte-string one non-serde
848 /// consumer parsed from the one the emitter wrote, with the failure
849 /// surfacing at the operator's reconcile posture (a `:temporary`
850 /// `oneShot` child being restarted on clean exit, treating the
851 /// successful-completion signal as failure and re-running the
852 /// completion-terminal one-shot indefinitely; a `:transient` child
853 /// that clean-exited being restarted, masking the clean-completion
854 /// contract) far from the rebrand commit and with no field naming
855 /// the drift.
856 ///
857 /// Distinct axis from the [`std::str::FromStr`] impl the
858 /// [`gen_platform::FromStrKind`] derive already installs on this
859 /// enum by design, not by drift: `FromStr` parses the *kebab-case*
860 /// dispatcher-catalog identity (`"permanent"` / `"temporary"` /
861 /// `"transient"` — the inverse of [`Self::discriminant`]), while
862 /// this method inverts the `PascalCase` wire byte-string
863 /// [`Self::as_str`] emits. The two-axis split lets the dispatcher-
864 /// catalog identity live in kebab-case (where every peer catalog
865 /// identifier already lives) without forcing a wire-format rename
866 /// on the tatara-lisp author surface (`:restart Permanent`,
867 /// `PascalCase`) — the same two-axis distinction the sibling
868 /// [`RestartStrategy::from_wire`] (4eec29c) /
869 /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
870 /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
871 /// carry on their peer closed-set typed-enum wire round-trips.
872 ///
873 /// Same closed-set-reverse-projection discipline the sibling
874 /// [`RestartStrategy::from_wire`] (4eec29c) /
875 /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
876 /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
877 /// [`crate::aplicacao::RateLimitUnit::from_suffix`] typed enums
878 /// carry on the peer wire-side `str → Self` axes — extended onto
879 /// the M2 OTP-shape per-child restart-policy closed-set axis, the
880 /// sixth substrate-side closed-set typed enum (and the third and
881 /// final OTP-shape closed-enum discriminator axis) to converge on
882 /// the two-way `str ↔ Self` round-trip. Method-named `from_wire`
883 /// (not `from_str`) to match the peer [`RestartStrategy::from_wire`]
884 /// shape verbatim and side-step the [`std::str::FromStr`] impl the
885 /// derive already installs on the sibling kebab-case axis. Returns
886 /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
887 /// shapes: the caller picks the diagnostic form appropriate for
888 /// its use site.
889 #[must_use]
890 pub fn from_wire(s: &str) -> Option<Self> {
891 match s {
892 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT => Some(Self::Permanent),
893 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY => Some(Self::Temporary),
894 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT => Some(Self::Transient),
895 _ => None,
896 }
897 }
898}
899
900/// [`std::fmt::Display`] routed through [`RestartPolicy::as_str`], so the
901/// pretty-printed byte-string every consumer that formats the policy as
902/// user-facing text lands on (the future wasm-operator's per-child
903/// post-exit restart-decision diagnostic line, the future `feira app
904/// graph` per-child restart column, the future M4
905/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
906/// admission-webhook rejection body) reaches for the same lifted
907/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
908/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
909/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
910/// wire-format `Serialize` derive already emits under
911/// [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
912/// [`RestartPolicy::as_str`] helper already returns.
913///
914/// Pre-convergence the two paths structurally disagreed — the
915/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
916/// route (now retired here) sent [`std::fmt::Display`] through the
917/// gen-platform discriminant catalog string, which arrives kebab-case as
918/// `"permanent"` / `"temporary"` / `"transient"` on this three-arm enum
919/// (whose variant names each collapse to their own lowercase form under
920/// the kebab-case transform), while the wire format ran as `PascalCase`
921/// `"Permanent"` / `"Temporary"` / `"Transient"` through the un-`rename`d
922/// serde derive. Every consumer that formatted the policy for a
923/// diagnostic line, a graph column, or a rejection body under
924/// `format!("{v}")` therefore landed under a different byte-string than
925/// the wire format the operator's per-child-policy dispatch keyed off —
926/// a silent split whose apply-time symptom (a `format!("{v}")`-carrying
927/// diagnostic quoting `"permanent"` while the wire scalar the operator
928/// probed was `"Permanent"`) surfaced as a confused correlate at
929/// operator-log time far from the two-declaration site.
930///
931/// Routing `Display` through [`RestartPolicy::as_str`] closes the third
932/// path: every `format!("{v}")` call reaches the same lifted
933/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the wire format
934/// and the [`RestartPolicy::as_str`] helper route through — `Debug` (the
935/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
936/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
937/// byte-string per variant. A future variant rename or
938/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
939/// exactly one place, structurally.
940///
941/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
942/// (from `#[derive(gen_platform::Discriminant)]`) still returns
943/// `"permanent"` / `"temporary"` / `"transient"`, and the fleet-wide
944/// [`gen_platform::register_dispatcher!("caixa.restart-policy", …)`]
945/// registration keys the catalog off the same kebab identity. The two
946/// naming worlds now live on separate typed methods (`Display` /
947/// `as_str` for the wire byte-string, `discriminant` for the catalog
948/// identity) rather than sharing one `Display` route that structurally
949/// disagrees with the wire format.
950///
951/// Pin tests
952/// [`tests::restart_policy_display_routes_through_as_str_helper`]
953/// and
954/// [`tests::restart_policy_display_matches_serialized_wire_byte_string`]
955/// assert the three paths agree byte-for-byte on every variant, so a
956/// future variant rename or per-arm serde attribute drift is a build
957/// error visible at caixa-core test time, not a silent per-consumer
958/// dispatch miss at apply / reconcile time.
959///
960/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
961/// (aplicacao.rs:2306) on the per-Aplicacao distribution-strategy axis
962/// and the sibling [`RestartStrategy`] `Display` impl on the
963/// per-supervisor sibling-restart-strategy axis — same three-path-
964/// convergence discipline, extended to close the third and final of
965/// three OTP-shaped closed-enum discriminator axes on the caixa typed
966/// surface.
967impl std::fmt::Display for RestartPolicy {
968 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
969 f.write_str(self.as_str())
970 }
971}
972
973/// Substrate-canonical [`AsRef<str>`] projection on the M2
974/// per-child-restart-policy [`RestartPolicy`] closed-set typed enum —
975/// routes through the same [`RestartPolicy::as_str`] `pub const fn`
976/// scalar accessor the paired [`std::fmt::Display`] impl and the
977/// un-`rename`d [`serde::Serialize`] derive already key off, so any
978/// future consumer that binds a [`RestartPolicy`] through the
979/// standard-library `impl AsRef<str>` bound (a future
980/// [`caixa-feira`] `feira supervisor --restart <arm>` verb that
981/// composes the emitted `PascalCase` wire scalar into a
982/// [`std::process::Command::arg`] shell-out of the future
983/// wasm-operator's per-child admission gate, a per-child structured-
984/// log recorder on the future `caixa-operator`'s hierarchical
985/// reconciliation surface that accepts `impl AsRef<str>` at the
986/// `tracing::field::Value` `Str`-arm, a [`std::collections::HashMap`]
987/// lookup keyed on the restart-policy wire byte through
988/// `map.get::<str>(policy.as_ref())` on a future per-policy
989/// dispatch table) reaches the paired
990/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
991/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
992/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
993/// lifted-const through one substrate-primitive dispatch rather
994/// than an open-coded `.as_str()` projection at every wire-up.
995///
996/// Peer of the sibling [`std::fmt::Display`] impl on the same
997/// primitive — both delegate to the shared [`RestartPolicy::as_str`]
998/// `pub const fn` accessor, so [`format!("{v}")`], `v.as_str()`, and
999/// `<RestartPolicy as AsRef<str>>::as_ref(&v)` resolve to the same
1000/// byte-string per instance by construction. A future variant rename
1001/// or `#[serde(rename_all = "kebab-case")]` attribute-drift on the
1002/// enum reaches every one of the three paths (plus the wire-format
1003/// `Serialize` derive that already routes through the same lifted
1004/// const) through exactly one caixa-core edit.
1005///
1006/// Same "route the trait impl through the substrate-primitive
1007/// accessor" discipline the sibling [`crate::CaixaVersion`]
1008/// [`AsRef<str>`] impl (16d5c7e) and the paired M2
1009/// [`RestartStrategy`] [`AsRef<str>`] impl (63eb1a4) carry — extends
1010/// the axis onto the paired per-child-restart-decision-policy
1011/// sibling on the same M2 `:supervisor` slot (the second M2
1012/// OTP-shape closed-set typed enum to converge onto the standard-
1013/// library [`AsRef<str>`] projection). Rust-side newtype/typed-enum
1014/// convention pairs [`AsRef<str>`] and [`fmt::Display`] on the same
1015/// primitive so a caller who has one has both; before this lift,
1016/// [`RestartPolicy`] carried [`fmt::Display`] but not the paired
1017/// [`AsRef<str>`] impl the convention names.
1018///
1019/// Pinned load-bearing by
1020/// [`tests::restart_policy_as_ref_str_routes_through_as_str_accessor`]
1021/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1022/// three-arm closed set) and
1023/// [`tests::restart_policy_as_ref_str_routes_through_display_via_shared_accessor`]
1024/// (three-path convergence: `AsRef<str>` + `Display` + `as_str` all
1025/// resolve to the same lifted `SUPERVISOR_CHILD_RESTART_*` const per
1026/// arm) — any future silent detour that routes the impl through a
1027/// divergent projection (a per-arm inline `match self { … }`
1028/// re-inlining that opens a compile-time link to the un-lifted
1029/// arm-literal, a swap onto the kebab-case
1030/// [`gen_platform::Discriminant`] catalog identity that would
1031/// collide the wire axis with the dispatcher-catalog axis) trips at
1032/// caixa-core test time under `assert_eq!` rather than at a
1033/// downstream `impl AsRef<str>`-bound consumer's silent split.
1034impl AsRef<str> for RestartPolicy {
1035 fn as_ref(&self) -> &str {
1036 self.as_str()
1037 }
1038}
1039
1040/// Trait-idiomatic reverse projection on the M2-OTP-shape per-child
1041/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
1042/// byte-for-byte through the paired substrate-primitive
1043/// [`RestartPolicy::from_wire`] `Option<Self>` accessor so every future
1044/// consumer that binds a `PascalCase` `:children :restart` wire
1045/// byte-string through the standard-library `.try_into()` / [`TryFrom`]
1046/// axis (a future [`caixa-feira`] `feira supervisor --restart
1047/// <Permanent|Temporary|Transient>` CLI arg-parse that composes into
1048/// `let restart: RestartPolicy = s.try_into()?`, a future
1049/// `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook that folds a
1050/// `spec.children[*].restart: String` field through
1051/// `RestartPolicy::try_from(&s)?`, a generic
1052/// `<T: TryFrom<&str>>`-bound loader over any of the substrate's closed-
1053/// set typed enums) reaches the same three-arm accept-set the sibling
1054/// [`RestartPolicy::from_wire`] resolver parses through and the sibling
1055/// [`RestartPolicy::as_str`] emits, rather than an open-coded per-arm
1056/// `match s { "Permanent" => …, "Temporary" => …, "Transient" => …, _ =>
1057/// … }` cascade whose arm-set has no compile-time link back to the
1058/// substrate primitive.
1059///
1060/// Complements the pre-existing forward-projection triple
1061/// ([`std::fmt::Display`], [`AsRef<str>`], [`RestartPolicy::as_str`])
1062/// with the paired trait-idiomatic reverse-projection axis: Rust-side
1063/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
1064/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so a
1065/// caller who can project *out to* a `&str` can also project *in from*
1066/// one. The [`TryFrom<&str>`] axis is deliberately chosen over
1067/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
1068/// lint the sibling method-named [`RestartPolicy::from_wire`] would
1069/// trigger under a `FromStr` impl and to avoid colliding with the
1070/// [`std::str::FromStr`] impl the [`gen_platform::FromStrKind`] derive
1071/// already installs on the paired *kebab-case dispatcher-catalog* axis
1072/// (which parses `"permanent"` / `"temporary"` / `"transient"`, the
1073/// inverse of [`Self::discriminant`]) — this impl closes the trait-
1074/// idiomatic reverse axis on the *`PascalCase` wire* half without
1075/// disturbing either the method-named `from_wire` shape every sibling
1076/// closed-set typed enum on the substrate already carries or the
1077/// pre-existing `FromStr` on the dispatcher-catalog half, keeping the
1078/// two-axis split the sibling [`Self::from_wire`] doc block motivates.
1079///
1080/// `type Error = ()` matches the sibling [`RestartPolicy::from_wire`]'s
1081/// `Option<Self>` return-shape's deliberate deferral of error typing: the
1082/// caller picks the diagnostic form appropriate for its use site (a
1083/// future `feira supervisor --restart` arg-parse composes its own
1084/// per-verb "unknown restart: <arg> — accepted: {…}" message enumerating
1085/// [`RestartPolicy::ALL`], a future M4 admission-webhook rejection body
1086/// wraps the `Err(())` outcome with the accepted-set enumeration for
1087/// operator diagnostics, a `Result::map_err` at the call site lifts the
1088/// unit-error to a per-verb error type). Same shape the peer
1089/// [`RestartStrategy`] (5b828ed) on the sibling per-supervisor axis,
1090/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136), and
1091/// [`crate::aplicacao::PlacementStrategy`] (6fd00cd) blocks motivate on
1092/// their peer closed-set typed enums' reverse projections.
1093///
1094/// The paired [`TryFrom<&str>`] impl reaches the same three-arm accept-
1095/// set the [`RestartPolicy::from_wire`] resolver dispatches through, so
1096/// any future arm addition (an OTP-`intrinsic` fourth arm the theory
1097/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1098/// might reach for once the three canonical OTP restart policies stop
1099/// covering the substrate's discovered load-shape) grows the trait-
1100/// idiomatic axis by construction — one caixa-core edit on
1101/// [`RestartPolicy::from_wire`] extends both the method-named reverse
1102/// projection every existing consumer keys off and the trait-idiomatic
1103/// reverse projection this impl exposes, without a coordinated rewrite
1104/// across every future `TryFrom<&str>`-bound consumer's arm-set.
1105///
1106/// Extends the substrate-wide closed-set-enum reverse-projection family
1107/// ([`crate::CaixaKind`] via 3c83606, [`crate::CaixaDialeto`] via
1108/// bf33136, [`crate::aplicacao::PlacementStrategy`] via 6fd00cd, and
1109/// [`RestartStrategy`] via 5b828ed) onto the third and final OTP-shape
1110/// closed-enum discriminator axis on the caixa surface — the paired
1111/// per-child `:children :restart` closed set the future wasm-operator's
1112/// hierarchical reconciliation scheduler's per-child post-exit
1113/// restart-decision branch keys off end-to-end.
1114///
1115/// Pinned load-bearing by
1116/// [`tests::restart_policy_try_from_str_routes_through_from_wire_accessor`]
1117/// (byte-parity pin against [`RestartPolicy::from_wire`] across the
1118/// three-arm accept-set),
1119/// [`tests::restart_policy_try_from_str_rejects_unknown_byte_strings`]
1120/// (rejection witness against silent accept-set widening), and
1121/// [`tests::restart_policy_try_from_str_and_from_wire_partition_the_accept_set`]
1122/// (cross-axis partition pin locking the trait and method-named
1123/// projections onto one accept-set).
1124impl TryFrom<&str> for RestartPolicy {
1125 type Error = ();
1126
1127 fn try_from(s: &str) -> Result<Self, Self::Error> {
1128 Self::from_wire(s).ok_or(())
1129 }
1130}
1131
1132/// Trait-idiomatic forward projection on the M2-OTP-shape per-child
1133/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
1134/// byte-for-byte through the paired substrate-primitive
1135/// [`RestartPolicy::as_str`] `pub const fn` accessor. Return type is
1136/// `&'static str` by construction — every [`RestartPolicy::as_str`] arm
1137/// resolves to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const
1138/// &str` with `'static` lifetime, so the trait's return-type promise is
1139/// upheld structurally without a [`String::leak`] cast or a per-arm inline
1140/// literal.
1141///
1142/// Every future consumer that specifically needs `&'static str` lifetime
1143/// bytes on the per-child restart-decision axis (a
1144/// [`tracing::field::valuable::Value::Str`] recording where the `Str`
1145/// arm's typing demands `&'static str`, a
1146/// [`std::borrow::Cow::Borrowed`]`::<'static, str>(policy.into())` composer
1147/// on the future M4 admission-webhook rejection body where the
1148/// `Cow<'static, str>` typing rules out the sibling [`AsRef<str>`]
1149/// borrowed return, a generic `<T: Into<&'static str>>`-bound serializer
1150/// or error formatter that requires the `'static` bound) reaches the same
1151/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1152/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1153/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] substrate-
1154/// primitive dispatch rather than an open-coded per-arm literal cascade
1155/// whose arm-set has no compile-time link back to the substrate primitive.
1156///
1157/// Peer of the sibling M2-OTP-shape [`RestartStrategy`] forward-projection
1158/// impl (523157d) on the per-supervisor sibling-restart-strategy axis —
1159/// the second (and second-of-two-in-M2) closed-set typed enum on the
1160/// caixa surface to converge onto the paired trait-idiomatic forward-
1161/// projection axis. With this lift the paired per-child
1162/// `:children :restart` closed-set typed enum carries the full sibling
1163/// quintet ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
1164/// [`TryFrom<&str>`] via 6fdd0d9, `From<Self> for &'static str` via this
1165/// lift) plus the round-trip witness through both the trait-idiomatic
1166/// (`From<Self> for &'static str` + `TryFrom<&str>`) and the method-named
1167/// (`as_str` + `from_wire`) axis pairs — mirrors the sibling
1168/// [`RestartStrategy`] surface arm-for-arm, so every future arm addition
1169/// (an OTP-`intrinsic` fourth arm the theory
1170/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1171/// might reach for once the three canonical OTP restart policies stop
1172/// covering the substrate's discovered load-shape) grows the trait-
1173/// idiomatic forward axis by construction: one caixa-core edit on
1174/// [`RestartPolicy::as_str`] extends every one of the five sibling
1175/// forward-projection paths ([`std::fmt::Display`], [`AsRef<str>`],
1176/// [`Self::as_str`] itself, this `From<Self> for &'static str`, and the
1177/// un-`rename`d [`serde::Serialize`] derive that also emits `as_str`'s
1178/// bytes) without a coordinated rewrite across every future
1179/// `Into<&'static str>`-bound consumer's arm-set.
1180///
1181/// Pinned load-bearing by
1182/// [`tests::restart_policy_from_into_static_str_routes_through_as_str_accessor`]
1183/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1184/// three-arm emit-set, plus a `const`-context materialization witness for
1185/// the `&'static str` lifetime promise) and
1186/// [`tests::restart_policy_from_into_static_str_and_as_str_partition_the_emit_set`]
1187/// (partition pin asserting `<&'static str as From<RestartPolicy>>::from`
1188/// and [`RestartPolicy::as_str`] agree on every arm, plus a two-way
1189/// round-trip witness through the paired trait-idiomatic reverse-
1190/// projection axis [`TryFrom<&str>`] (6fdd0d9): every
1191/// `policy.into::<&'static str>()` output re-parses back through
1192/// [`RestartPolicy::try_from`] to the original variant, closing the two-
1193/// way `Self ↔ &'static str` round-trip on the trait-idiomatic axis pair).
1194impl From<RestartPolicy> for &'static str {
1195 fn from(policy: RestartPolicy) -> &'static str {
1196 policy.as_str()
1197 }
1198}
1199
1200/// Trait-idiomatic *forward* projection on [`RestartPolicy`] from a
1201/// *borrowed* input onto the `&'static str` axis — the borrowed-input
1202/// companion to the paired owned-input [`From<RestartPolicy> for
1203/// &'static str`] impl immediately above. Routes byte-for-byte through
1204/// the same substrate-primitive [`RestartPolicy::as_str`] `pub const
1205/// fn` accessor so every consumer that binds a `&RestartPolicy`
1206/// through the standard-library `.into()` / [`From<&Self> for &'static
1207/// str`] axis (a `RestartPolicy::ALL.iter().map(<&'static
1208/// str>::from).collect::<Vec<_>>()` per-arm accept-set materializer —
1209/// whose iterator over `&'static [RestartPolicy]` yields
1210/// `&RestartPolicy`, not `RestartPolicy`, so the owned-input
1211/// [`From<RestartPolicy>`] axis alone forces every call site through
1212/// an explicit `.copied()` / dereference / [`Copy`]-bound restatement
1213/// rather than the direct trait-idiomatic projection; a future generic
1214/// `<T: Copy + for<'a> Into<&'static str>>`-bound diagnostic column
1215/// that walks the `iter().map(Into::into)` shape verbatim across every
1216/// substrate-wide closed-set typed enum; the future wasm-operator's
1217/// per-child post-exit restart-decision diagnostic line that composes
1218/// the accepted-set enumeration from an iterated
1219/// `RestartPolicy::ALL.iter().map(|p| p.into())` pipe rather than a
1220/// per-arm `match p { … }` cascade; a future
1221/// `HashMap::<&'static str, RestartPolicy>::from_iter(
1222/// RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
1223/// per-policy reverse-lookup table the sibling [`TryFrom<&str>`] impl
1224/// cannot compose without this borrowed-input axis in place) reaches
1225/// the same three-arm lifted
1226/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1227/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1228/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1229/// paired owned-input [`From<RestartPolicy> for &'static str`], the
1230/// sibling [`std::fmt::Display`], [`AsRef<str>`], and
1231/// [`RestartPolicy::as_str`] surfaces already return.
1232///
1233/// Fifth peer on the substrate-wide trait-idiomatic *borrowed-input*
1234/// forward-projection family opened on [`crate::dep::DepList`]
1235/// (64aa742) and extended onto [`crate::CaixaKind`] (5ab993a),
1236/// [`crate::CaixaDialeto`] (807b0b5), and the paired
1237/// per-supervisor sibling-restart-strategy [`RestartStrategy`]
1238/// (e941836). Rust's `From` trait does not auto-derive the
1239/// `From<&Self>` sibling from a `From<Self>` impl (the blanket
1240/// `impl<T, U> From<&T> for U where T: Copy, U: From<T>` does not
1241/// exist in `core`), so every closed-set typed enum that carries the
1242/// owned-input axis but not the borrowed-input axis forces every
1243/// borrowed-input call site through a `.copied()` /
1244/// `<&'static str>::from(*policy)` / `policy.as_str()` detour whose
1245/// type bounds have no compile-time link to the substrate primitive.
1246/// [`RestartPolicy`] is the second (and second-of-two-in-M2)
1247/// OTP-shape peer to converge onto this campaign — sibling of the
1248/// paired per-supervisor [`RestartStrategy`] borrowed-input axis, so
1249/// with this lift both closed-set typed enums on the M2 `:supervisor`
1250/// slot now carry the full sibling quintet ([`std::fmt::Display`],
1251/// [`AsRef<str>`], [`Self::as_str`], `From<Self> for &'static str`,
1252/// `From<&Self> for &'static str`) plus the paired trait-idiomatic
1253/// reverse projection [`TryFrom<&str>`], closing the borrowed-input
1254/// forward-projection axis on the M2 OTP-shape slot as a unit.
1255///
1256/// Same three-path convergence discipline as the paired owned-input
1257/// impl (this borrowed-input axis, the paired owned-input
1258/// [`From<RestartPolicy> for &'static str`], and
1259/// [`RestartPolicy::as_str`] all route through the same lifted
1260/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const), so a future
1261/// variant rename or per-arm serde-attribute drift reaches every one
1262/// of the six sibling forward-projection paths
1263/// ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
1264/// [`From<Self> for &'static str`], this [`From<&Self> for &'static
1265/// str`], and the un-`rename`d [`serde::Serialize`] derive that also
1266/// emits [`Self::as_str`]'s bytes) through exactly one caixa-core
1267/// edit.
1268///
1269/// The [`RestartPolicy::as_str`] emit and [`RestartPolicy::from_wire`]
1270/// parse share the same `PascalCase` vocabulary by construction, so
1271/// the borrowed-input forward axis and the reverse axis compose
1272/// directly — the round-trip witness pin below locks this direct
1273/// composition without the intermediate wire-vocab hop the peer
1274/// [`crate::CaixaKind`] axis pair requires.
1275///
1276/// Pinned load-bearing by
1277/// [`tests::restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
1278/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1279/// three-arm emit-set via a borrowed input, plus a `const`-context
1280/// materialization witness for the `&'static str` lifetime promise,
1281/// plus a blanket `.into()` shape) and
1282/// [`tests::restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
1283/// (cross-axis partition pin against the paired owned-input
1284/// [`From<RestartPolicy> for &'static str`] impl, plus a
1285/// `.iter().map(Into::into)` pipe witness over
1286/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
1287/// [`TryFrom<&str>`] that closes the two-way `&Self → &'static str →
1288/// Self` round-trip without the wire-vocab intermediate the peer
1289/// [`crate::CaixaKind`] axis pair requires).
1290impl From<&RestartPolicy> for &'static str {
1291 fn from(policy: &RestartPolicy) -> &'static str {
1292 policy.as_str()
1293 }
1294}
1295
1296// Fleet-wide dispatcher-catalog registrations for caixa's OTP
1297// supervisor surface — two more typed shadows over Erlang/OTP
1298// primitives the substrate now mechanically tracks (see
1299// theory/UNIFIED-COMPUTING-MODEL.md §VI for the roadmap +
1300// theory/TYPED-ABSORPTION.md for the absorption arc).
1301gen_platform::register_dispatcher!("caixa.restart-strategy", RestartStrategy);
1302gen_platform::register_dispatcher!("caixa.restart-policy", RestartPolicy);
1303
1304/// One child entry in the supervisor's `:children` list.
1305///
1306/// Every child references another caixa by `:caixa <nome>` + version
1307/// constraint. The supervisor materializes one ComputeUnit per entry.
1308#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1309#[serde(rename_all = "camelCase")]
1310pub struct ChildSpec {
1311 /// The child caixa's `:nome`. Must resolve via the same dependency
1312 /// resolution path as `:deps` (caixa-resolver).
1313 pub caixa: String,
1314
1315 /// Semver constraint (`"^0.1"`, `"~0.1.2"`, etc.) — same shape as
1316 /// [`crate::dep::Dep::versao`].
1317 pub versao: String,
1318
1319 /// Restart policy — an author-omitted slot degrades onto the
1320 /// substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`]
1321 /// (`permanent`, the Erlang/OTP worker-child default) through the
1322 /// [`Default for RestartPolicy`] impl this `#[serde(default)]` routes
1323 /// to.
1324 #[serde(default)]
1325 pub restart: RestartPolicy,
1326}
1327
1328impl ChildSpec {
1329 /// Substrate-canonical per-`:children` child-caixa `:nome` scalar
1330 /// accessor every consumer that reads the OTP-shape supervised
1331 /// child's identity keys off — returns the author-declared
1332 /// `:children :caixa` byte-string verbatim as a `&str`, borrowed
1333 /// from the typed slot's own [`String`] storage.
1334 ///
1335 /// The `:children :caixa` slot carries the DNS-1123 label — the
1336 /// child caixa's `:nome` — that every emitted cluster artifact
1337 /// derives its `metadata.name` from verbatim: the rendered
1338 /// `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name` per child, the
1339 /// [`crate::LABEL_PROGRAM`] label value on every child's pod
1340 /// identity, and the per-child K8s Service `metadata.name` the
1341 /// future wasm-operator (M3) provisions for inter-child supervision-
1342 /// tree wiring. Every downstream consumer that fans on the child's
1343 /// caixa-name keys off this scalar (the [`SupervisorSpec::validate`]
1344 /// per-child DNS-1123 gate at
1345 /// `require_valid_dns_1123_label(child.nome(), …)`, the per-child
1346 /// duplicate-detection [`crate::render::insert_first_seen`] key, the
1347 /// [`validate_no_self_supervision`] cross-slot equality check
1348 /// against the parent's `:nome`, every `SupervisorError` variant
1349 /// carrying the offending child caixa verbatim for `feira lint`
1350 /// rendering, the future wasm-operator's hierarchical reconciliation
1351 /// scheduler's per-child ComputeUnit-name projection, the future M4
1352 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1353 /// admission webhook).
1354 ///
1355 /// Prior to this lift the `.caixa` byte-string was accessed inline
1356 /// at seven sites in `supervisor.rs` — the DNS-1123 gate's
1357 /// `&child.caixa`, the four `SupervisorError::{ChildCaixaInvalid,
1358 /// EmptyChildVersion, ChildVersaoInvalid, DuplicateChildCaixa}`
1359 /// carriers' `child.caixa.clone()`, the dedup key's
1360 /// `child.caixa.as_str()`, and the [`validate_no_self_supervision`]
1361 /// `child.caixa == parent_nome` cross-slot check — seven open-coded
1362 /// field-accesses that expressed no compile-time link back to the
1363 /// typed slot. A future extension of the `:children :caixa` axis to
1364 /// a richer author surface (a per-cluster alias table the operator
1365 /// pins through a future `:placement`-scoped slot on the supervisor
1366 /// tree, a namespace-qualified rewrite the M4 CR materializer
1367 /// applies per-CR, a per-child overlay from the future `:children
1368 /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
1369 /// acknowledges) would have had to be threaded through every
1370 /// open-coded copy in lockstep or one consumer would silently
1371 /// disagree with the peers on which caixa a given child resolves to
1372 /// — a child-set lookup that treated the name as `"cart-worker"`
1373 /// while the peer duplicate-detector treated it as
1374 /// `"tenant-a/cart-worker"` would silently split the
1375 /// `DuplicateChildCaixa` membership-lookup diagnostic from the
1376 /// self-supervision detector's parent-equality check, a two-consumer
1377 /// split at the validator far from the source `caixa.lisp` with no
1378 /// field naming the identity-drift root cause. Lifting the resolution
1379 /// rule to a typed method on the substrate primitive means every
1380 /// downstream consumer of the Supervisor's per-`:children` identity
1381 /// surface reaches for exactly one typed dispatch — the resolver's
1382 /// accept-set migrates as a unit on any future axis addition.
1383 ///
1384 /// Sibling of the peer per-`:membros` [`crate::Membro::nome`]
1385 /// (4a32abf) member-caixa `:nome` scalar accessor on the M3
1386 /// mesh-slot surface — same "one typed dispatch on the substrate
1387 /// primitive, thin projections at each consumer" discipline extended
1388 /// onto the M2 supervisor-tree per-`:children` child-identity axis.
1389 /// The two typed axes (`Membro::nome` on the M3 Aplicacao side,
1390 /// `ChildSpec::nome` on the M2 Supervisor side) now share one
1391 /// accessor discipline for the shared substrate concept "another
1392 /// caixa referenced by `:nome`". Peer of the second M2 slot scalar
1393 /// accessor [`crate::UpgradeFromEntry::prior_versao`] (75d27a8) on
1394 /// the sibling per-`:upgrade-from :from` OTP-appup axis — the M2
1395 /// slot family's typed-accessor discipline now spans both the
1396 /// upgrade axis (`:upgrade-from`) and the supervision axis
1397 /// (`:children`), matching the closed M3 mesh-slot accessor family's
1398 /// shape. Named `nome()` to match the tatara-lisp author-surface
1399 /// term the field's docstring already reaches for ("The child
1400 /// caixa's `:nome`") and the peer [`crate::Membro::nome`] /
1401 /// [`crate::Caixa::nome`] / [`crate::dep::Dep::nome`] field-name
1402 /// discipline the substrate already carries — the accessor's name
1403 /// maps directly onto the canonical caixa-identity vocabulary rather
1404 /// than shadowing the field's storage-side `caixa` label.
1405 #[must_use]
1406 pub const fn nome(&self) -> &str {
1407 self.caixa.as_str()
1408 }
1409
1410 /// Substrate-canonical per-`:children` child-caixa `:versao` semver-
1411 /// requirement scalar accessor every consumer that reads the OTP-shape
1412 /// supervised child's version pin keys off — returns the author-declared
1413 /// `:children :versao` byte-string verbatim as a `&str`, borrowed from
1414 /// the typed slot's own [`String`] storage.
1415 ///
1416 /// The `:children :versao` slot carries the Cargo-shaped semver
1417 /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that pins
1418 /// which release of the supervised child caixa the OTP-shape supervisor
1419 /// tree materializes against — the same requirement grammar the peer
1420 /// `:deps :versao` / `:membros :versao` axes carry, resolved through the
1421 /// shared [`crate::render::require_valid_versao_requirement`] cascade
1422 /// and the shared [`crate::version::parse_requirement`] parser. Every
1423 /// downstream consumer that fans on the child's version pin keys off
1424 /// this scalar (the [`SupervisorSpec::validate`] per-child requirement
1425 /// gate at `require_valid_versao_requirement(child.versao_requirement(),
1426 /// …)`, the [`SupervisorError::ChildVersaoInvalid`] variant's carrier
1427 /// for `feira lint` rendering, every future per-cluster version-lock
1428 /// overlay the caixa-operator's hierarchical reconciliation scheduler
1429 /// pins through a future `:placement`-scoped supervisor-tree slot, the
1430 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1431 /// per-child version resolver, the future wasm-operator's per-child
1432 /// lacre BLAKE3-closure lookup at `ComputeUnit` materialization time).
1433 ///
1434 /// Prior to this lift the `.versao` byte-string was accessed inline at
1435 /// two `&str`-shaped sites in `caixa-core/src/supervisor.rs` — the
1436 /// [`SupervisorSpec::validate`] requirement-gate call
1437 /// `require_valid_versao_requirement(&child.versao, …)` and the
1438 /// [`SupervisorError::ChildVersaoInvalid`] carrier at
1439 /// `versao: child.versao.clone()` — two open-coded field-accesses that
1440 /// expressed no compile-time link back to the typed slot. A future
1441 /// extension of the `:children :versao` axis to a richer author surface
1442 /// (a per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
1443 /// flow, a lacre-projected concrete-version rewrite the operator
1444 /// materializes at CR-admission time, a future `:children :versao-lock`
1445 /// per-cluster override slot the wasm-operator's hierarchical
1446 /// reconciliation scheduler authors per-CR) would have had to be
1447 /// threaded through both open-coded copies in lockstep or one consumer
1448 /// would silently disagree with the peer on which release constraint a
1449 /// given child resolves to — the requirement-gate call reading
1450 /// `"^0.1"` while the error-body carrier read `"tenant-a-pin/^0.1"`
1451 /// would silently split the `ChildVersaoInvalid` diagnostic quote from
1452 /// the actual gate rejection input, a two-consumer split at the
1453 /// validator far from the source `caixa.lisp` with no field naming the
1454 /// version-pin drift root cause. Lifting the resolution rule to a typed
1455 /// method on the substrate primitive means every downstream
1456 /// requirement-facing consumer of the Supervisor's per-`:children`
1457 /// version-pin surface reaches for exactly one typed dispatch — the
1458 /// resolver's accept-set migrates as a unit on any future axis addition.
1459 ///
1460 /// Sibling of the peer per-`:membros` [`crate::Membro::versao_requirement`]
1461 /// (a40b0e3) member-caixa `:versao` scalar accessor on the M3 mesh-slot
1462 /// surface — same "one typed dispatch on the substrate primitive, thin
1463 /// projections at each consumer" discipline extended onto the M2
1464 /// supervisor-tree per-`:children` child-version-pin axis. The two typed
1465 /// axes (`Membro::versao_requirement` on the M3 Aplicacao side,
1466 /// `ChildSpec::versao_requirement` on the M2 Supervisor side) now share
1467 /// one accessor discipline for the shared substrate concept "another
1468 /// caixa referenced by a Cargo-shaped semver requirement". Peer of the
1469 /// sibling per-`:children` [`ChildSpec::nome`] (57c61d0) child-caixa
1470 /// `:nome` scalar accessor — the pair
1471 /// `(nome(), versao_requirement())` jointly projects the
1472 /// `(caixa, versao)` field pair every OTP-shape supervisor-tree consumer
1473 /// that fans on per-child identity + version pin keys off, closing the
1474 /// last unlifted per-`:children` `String`-carry axis so every downstream
1475 /// per-`:children` reader now routes through a typed dispatch on the
1476 /// substrate primitive. Named `versao_requirement()` rather than
1477 /// `versao()` because the field's storage-side `.versao` label is
1478 /// already the author-surface term (`:versao`); the accessor's name
1479 /// carries the semantic role — the semver *requirement* string the
1480 /// shared [`crate::version::parse_requirement`] entry-point consumes —
1481 /// so a raw field access and a typed dispatch read differently at every
1482 /// consumer site. Matches the peer [`crate::Membro::versao_requirement`]
1483 /// naming discipline verbatim.
1484 #[must_use]
1485 pub const fn versao_requirement(&self) -> &str {
1486 self.versao.as_str()
1487 }
1488
1489 /// Substrate-canonical per-`:children` `:restart` OTP-shaped
1490 /// per-child post-exit restart-decision policy scalar accessor every
1491 /// consumer that dispatches on the supervised child's post-exit
1492 /// reconcile posture keys off — returns the author-declared
1493 /// `:children :restart` variant verbatim as a [`RestartPolicy`],
1494 /// `Copy`-projected from the typed slot's own [`RestartPolicy`]
1495 /// storage.
1496 ///
1497 /// The `:children :restart` slot carries the closed-set OTP-shaped
1498 /// per-child restart-decision policy discriminator
1499 /// ([`RestartPolicy::Permanent`] — always restart, the OTP `permanent`
1500 /// worker-child default; [`RestartPolicy::Transient`] — restart only
1501 /// on abnormal exit, the OTP `transient` clean-completion-aware
1502 /// default; [`RestartPolicy::Temporary`] — never restart, the OTP
1503 /// `temporary` one-shot default) that every downstream consumer of
1504 /// the Supervisor's per-child post-exit reconcile branch keys off.
1505 /// Every future downstream consumer that fans on the per-child
1506 /// restart-decision keys off this scalar (the future `feira app
1507 /// graph` per-child restart column, the future wasm-operator's
1508 /// per-child post-exit restart-decision branch, the future M4
1509 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1510 /// admission webhook, the `caixa-operator`'s hierarchical
1511 /// reconciliation scheduler's per-child post-exit reconcile branch,
1512 /// the [`RestartPolicy::as_str`] `Serialize`-derive-pinning path the
1513 /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
1514 /// pin threads through).
1515 ///
1516 /// Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
1517 /// (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
1518 /// scalar accessor and the M3 mesh-slot
1519 /// [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
1520 /// [`crate::PlacementStrategy`] distribution-strategy scalar accessor
1521 /// — same "one typed dispatch on the substrate primitive,
1522 /// `Copy`-projected closed-set enum-arm discriminator that partitions
1523 /// the downstream renderer's per-arm fan-out" discipline extended
1524 /// onto the M2 supervisor-slot per-`:children` restart-decision-policy
1525 /// `Copy`-composite-enum scalar axis. Third axis on the per-`:children`
1526 /// [`ChildSpec`] type — companion to the sibling per-`:children`
1527 /// [`ChildSpec::nome`] (57c61d0) child-caixa `:nome` scalar accessor
1528 /// and the per-`:children` [`ChildSpec::versao_requirement`]
1529 /// (2c053c8) child-caixa `:versao` semver-requirement scalar accessor
1530 /// on the sibling `String`-carry axes. The triple
1531 /// `(nome(), versao_requirement(), restart())` jointly projects the
1532 /// `(caixa, versao, restart)` field trio every OTP-shape supervisor-
1533 /// tree consumer that fans on per-child identity + version pin +
1534 /// restart-decision keys off, closing the last unlifted per-`:children`
1535 /// axis so every downstream per-`:children` reader now routes through
1536 /// a typed dispatch on the substrate primitive. Named `restart()` to
1537 /// match the storage field's name and the author-surface
1538 /// `:children :restart` slot term verbatim; the accessor's identity
1539 /// name maps onto the canonical OTP-shape per-child restart-decision-
1540 /// policy vocabulary the [`RestartPolicy`] enum's docstring already
1541 /// carries.
1542 ///
1543 /// Declared `pub const fn` to close the last non-`const`
1544 /// `Copy`-return raw-field-getter posture on the M2
1545 /// per-`:children` [`ChildSpec`] substrate-primitive surface — peer
1546 /// of the sibling M2 per-`:supervisor`
1547 /// [`SupervisorSpec::estrategia`] (converted in this commit)
1548 /// `Copy`-composite-enum accessor, the sibling M2 per-`:supervisor`
1549 /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
1550 /// already lifted, and the peer M3 mesh-slot per-`:entrada`
1551 /// [`crate::Entrada::port`] (bafa004) / per-`:placement`
1552 /// [`crate::Placement::estrategia`] (bafa004) `Copy`-return
1553 /// `pub const fn` scalar accessors on the sibling M3 surface. Every
1554 /// downstream substrate-side `const`-context consumer of the
1555 /// per-`:children` restart-decision-policy scalar (a future
1556 /// module-scope `const _:() = assert!(matches!(child.restart(),
1557 /// RestartPolicy::Permanent))` invariant pin on a typed fixture, a
1558 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
1559 /// admission-webhook `const fn` per-child restart-decision floor
1560 /// over a typed [`ChildSpec`], any future `const fn` supervisor-tree
1561 /// composer over the substrate primitive that fans on the per-child
1562 /// restart-decision policy at compile time) now reaches through the
1563 /// same typed dispatch on the substrate primitive at const-eval
1564 /// time as at runtime. A future non-`Copy`-return promotion of the
1565 /// scalar (an `Option<RestartPolicy>`-shape migration on the
1566 /// per-child restart-decision axis once heterogeneous per-cluster
1567 /// restart-policy overlays land, a per-tenant restart-policy-alias
1568 /// table the M4 CR materializer resolves per-CR) that would drop
1569 /// the `const` qualifier fails the fail-before-pass-after pin
1570 /// [`tests::child_spec_restart_accessor_is_const_fn`] at caixa-core
1571 /// build time rather than surfacing as a downstream consumer
1572 /// regression.
1573 #[must_use]
1574 pub const fn restart(&self) -> RestartPolicy {
1575 self.restart
1576 }
1577}
1578
1579/// Supervisor-typed slots that live alongside the standard Caixa
1580/// fields when `:kind Supervisor`. Held flat in [`crate::Caixa`] so
1581/// the manifest stays a single typed form; this struct exists for
1582/// validation + conversion.
1583#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1584#[serde(rename_all = "camelCase")]
1585pub struct SupervisorSpec {
1586 /// Restart strategy. Defaults to [`RestartStrategy::OneForOne`].
1587 #[serde(default)]
1588 pub estrategia: RestartStrategy,
1589
1590 /// Max restarts within [`Self::restart_window`] before the
1591 /// supervisor itself terminates (and its parent supervisor decides
1592 /// what to do). Default 5.
1593 #[serde(default = "default_max_restarts")]
1594 pub max_restarts: u32,
1595
1596 /// Sliding window for `max_restarts`. Authored as a duration
1597 /// string (`"60s"`, `"5m"`); absent = "never reset". A `Some(0s)`
1598 /// is rejected by [`Self::validate`] — Erlang/OTP's
1599 /// `MaxIntensity / Period` invariant requires a positive window
1600 /// (a zero-period supervisor either trips on the first failure or
1601 /// never trips, depending on operator interpretation, neither of
1602 /// which is the author's intent). Omit the slot to express "no
1603 /// reset"; carry a positive duration to express the sliding window.
1604 #[serde(
1605 default,
1606 skip_serializing_if = "Option::is_none",
1607 with = "duration_codec"
1608 )]
1609 pub restart_window: Option<Duration>,
1610
1611 /// Static children. Empty for `SimpleOneForOne` (children added
1612 /// dynamically); required for the other three strategies.
1613 #[serde(default)]
1614 pub children: Vec<ChildSpec>,
1615}
1616
1617const fn default_max_restarts() -> u32 {
1618 // Route the private serde-`#[serde(default = "…")]` helper through
1619 // the substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] typed
1620 // `pub const` rather than the raw `5` literal — one source of truth
1621 // for the Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
1622 // default across the two production consumers that currently
1623 // dispatch on it (this helper via `#[serde(default = "…")]` on
1624 // `SupervisorSpec::max_restarts` and the [`Default for SupervisorSpec`]
1625 // impl at line 962). Pinned by
1626 // `default_max_restarts_helper_routes_through_lifted_default` +
1627 // `supervisor_spec_default_max_restarts_routes_through_lifted_default`
1628 // in the tests module; peer of the sibling caixa-core
1629 // [`crate::manifest::Caixa::supervisor_view`] `unwrap_or(…)` fold
1630 // that now routes its author-omitted `:max-restarts` arm through
1631 // the same lifted constant.
1632 SUPERVISOR_MAX_RESTARTS_DEFAULT
1633}
1634
1635/// Substrate-canonical Erlang/OTP-shaped `MaxIntensity` restart-budget-
1636/// count default for the `:supervisor :max-restarts` axis — the
1637/// canonical `{intensity, 5, 60}` `MaxIntensity` half of Learn You Some
1638/// Erlang's worker-supervisor default, extracted as a typed `pub const`
1639/// so every substrate-side consumer that resolves "what
1640/// [`SupervisorSpec::max_restarts`] value does an author-omitted
1641/// `:max-restarts` slot degrade onto?" reaches for exactly one
1642/// substrate-primitive `u32`.
1643///
1644/// The `:max-restarts` default axis has two production consumers on the
1645/// substrate side today (both prior to this lift folded onto raw `5`
1646/// literals with no compile-time link back to a shared truth): the
1647/// serde-`#[serde(default = "default_max_restarts")]` helper on
1648/// [`SupervisorSpec::max_restarts`] that every author-omitted
1649/// `:supervisor :max-restarts` slot lands in past the derive-macro's
1650/// wire-format compose, and the [`crate::manifest::Caixa::supervisor_view`]
1651/// `.max_restarts().unwrap_or(5)` fold that every downstream consumer of
1652/// the composed [`SupervisorSpec`] altitude reaches through
1653/// (`feira app graph`, the future wasm-operator's per-supervisor
1654/// restart-intensity counter, the future M4
1655/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
1656/// webhook, the caixa-operator's hierarchical reconciliation scheduler).
1657/// A pair of open-coded `5`s across two files that expressed no
1658/// compile-time link back to the shared OTP-canonical default — a
1659/// future rebrand of the default (a tightening to Elixir's
1660/// `Supervisor.max_restarts: 3`, a widening to a per-cluster overlay
1661/// the operator pins through a future
1662/// `:supervisor :max-restarts-overrides` slot the MESH-COMPOSITION
1663/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
1664/// plain `u32` count to a richer `{MaxR, MaxT}` per-child-cohort
1665/// restart-budget-partition once the INSPIRATIONS §II.2 Erlang/OTP
1666/// per-child-cohort roadmap lands) would have had to be threaded
1667/// through both open-coded copies in lockstep or the wire-format
1668/// author-omitted arm and the view-construction author-omitted arm
1669/// would silently disagree on which restart-budget an omitted
1670/// `:max-restarts` resolves to (an author writing `:supervisor
1671/// (:max-restarts ())` would round-trip through serde with the new
1672/// default while `supervisor_view` silently continued to compose the
1673/// stale `5`, or vice versa), a two-consumer split at the composition
1674/// boundary far from the source `caixa.lisp` with no field naming the
1675/// default-drift root cause. Lifting the resolution rule to a typed
1676/// `pub const` on the substrate primitive means every downstream
1677/// consumer of the per-Supervisor default-restart-budget-count surface
1678/// reaches for exactly one substrate-primitive `u32` — the resolver's
1679/// accepted value migrates as a unit on any future axis change.
1680///
1681/// The `5` value pins Learn You Some Erlang's `{intensity, 5, 60}`
1682/// worker-supervisor default (the closest canonical OTP-shape
1683/// production reference the substrate carries, matching the sibling
1684/// `60s` `Period` default the [`Default for SupervisorSpec`] impl pairs
1685/// this constant with on the paired sliding-window axis). Two orders of
1686/// magnitude below the [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` ceiling
1687/// (the upper bracket on the same axis, sibling of this lower default;
1688/// both are typed `u32` const bounds on the `:supervisor :max-restarts`
1689/// axis and now share one accessor discipline on the substrate) and
1690/// above the OTP-`supervisor` callback-module `MaxR = 1` minimum-
1691/// restart floor — the "one restart, then escalate" default is
1692/// deliberately loose enough to absorb a short burst of transient
1693/// child failures without escalating past the supervisor's parent
1694/// while remaining tight enough to trip the `MaxIntensity / Period`
1695/// ratio's escalation on a genuinely-stuck child within the sibling
1696/// `60s` sliding window.
1697///
1698/// Lifted as a typed `pub const` so the bound has exactly one source
1699/// of truth — the serde-side wire-format author-omitted arm at
1700/// [`default_max_restarts`], the [`Default for SupervisorSpec`] impl's
1701/// struct-literal default field, and the caixa-core
1702/// [`crate::manifest::Caixa::supervisor_view`] fold's author-omitted
1703/// arm all read from one place. Same shape every other typed default
1704/// in this crate carries (the sibling
1705/// [`SUPERVISOR_MAX_RESTARTS_MAX`] upper cap on the same axis, the
1706/// paired [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the
1707/// sibling `:restart-window` axis, and the peer
1708/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
1709/// per-renderer defaults on the caixa-flux / caixa-helm rendering
1710/// axes).
1711pub const SUPERVISOR_MAX_RESTARTS_DEFAULT: u32 = 5;
1712
1713/// Upper-bound ceiling on the `:supervisor :max-restarts` axis — every
1714/// validated [`SupervisorSpec::max_restarts`] past
1715/// [`SupervisorSpec::validate`] lies in `1..=SUPERVISOR_MAX_RESTARTS_MAX`.
1716///
1717/// The typed field is `u32` (the zero-floor arm
1718/// [`SupervisorError::ZeroMaxRestarts`] already brackets the bottom edge),
1719/// so a programmatic struct literal
1720/// (`SupervisorSpec { max_restarts: u32::MAX, .. }`) and the equivalent
1721/// author-surface form (`:max-restarts 4294967295` or any
1722/// `:max-restarts 100000`-shape typo landing in the slot) both round-trip
1723/// cleanly through serde — a structurally unbounded `u32` ceiling. The
1724/// runtime substrate consuming the value (Erlang/OTP's
1725/// `MaxIntensity / Period` ratio, the future wasm-operator's
1726/// per-supervisor restart-intensity counter, the M4
1727/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook)
1728/// then turned a typed `:max-restarts` policy into a no-op supervisor: the
1729/// escalation threshold is structurally so high that no realistic
1730/// restarts-per-`:restart-window` traffic shape can reach it, the
1731/// supervisor never escalates to its parent, and a bad child can loop
1732/// inside the window indefinitely with the parent supervisor structurally
1733/// never receiving the "this subtree has exceeded its restart budget"
1734/// signal the typed slot is meant to express — the canonical
1735/// "supervisor intensity declared, no escalation" footgun, exactly the
1736/// peer of the [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap
1737/// on the `:politicas :circuit-breaker :max-failures` axis (both are
1738/// "trip the next-higher protection layer after N events in a rolling
1739/// window" counters with identical degenerate-at-the-high-end shape).
1740///
1741/// The `1000` ceiling matches the sibling
1742/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] (the closest
1743/// peer — same "events-per-window trip threshold" semantics, same `u32`
1744/// type, same no-op-at-the-high-end failure mode) so the M4
1745/// `mesh.pleme.io/v1alpha1/Supervisor` / `.../Aplicacao` CR materializers
1746/// and the future wasm-operator's per-supervisor restart-intensity
1747/// counter reach for either field knowing the value is in `1..=1000`
1748/// without re-validating at the reconciler layer. The cap sits two
1749/// orders of magnitude above every documented Erlang/OTP production
1750/// playbook recommendation (Learn You Some Erlang's
1751/// `{intensity, 5, 60}` worker-supervisor default, Elixir's `Supervisor`
1752/// `max_restarts: 3` default, OTP's `supervisor` callback module
1753/// `MaxR = 1` / `MaxT = 5` "minimal-restart" default, Riak Core's
1754/// typical `MaxR ∈ 5..=100`, RabbitMQ's broker-supervisor `MaxR = 5`
1755/// default) and below the clearly-pathological "effectively no
1756/// escalation" floor (`10_000`, `100_000`, `u32::MAX`): a value the
1757/// author can plausibly want at hyperscale (a long-running supervisor
1758/// over a very-flaky pool tolerating thousands of transient restarts
1759/// before escalating), but a hard wall above which the typed policy is
1760/// structurally a no-op carried verbatim on every emitted child-restart
1761/// reconciliation contract.
1762///
1763/// Lifted as a typed `pub const` so the bound has exactly one source of
1764/// truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
1765/// materializer's admission webhook and the wasm-operator-side
1766/// per-supervisor restart-intensity reconciler read from one place. Same
1767/// shape every other typed upper bound in this crate carries
1768/// ([`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
1769/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
1770/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
1771/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
1772/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
1773/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
1774pub const SUPERVISOR_MAX_RESTARTS_MAX: u32 = 1000;
1775
1776/// Upper-bound ceiling on the `:supervisor :restart-window` axis —
1777/// every validated `Some(`[`SupervisorSpec::restart_window`]`)` past
1778/// [`SupervisorSpec::validate`] lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
1779/// (inclusive on both ends, integer-millisecond magnitudes by the
1780/// canonical-form gate immediately preceding).
1781///
1782/// The typed field is `Option<Duration>` (the zero-floor arm
1783/// [`SupervisorError::RestartWindowZero`] already rejects
1784/// `Some(Duration::ZERO)`, and the canonical-form arm
1785/// [`SupervisorError::RestartWindowNotCanonical`] already rejects
1786/// sub-millisecond residue), so a programmatic struct literal
1787/// (`SupervisorSpec { restart_window: Some(Duration::from_secs(86_400)),
1788/// .. }` — 24h) and the equivalent author-surface form
1789/// (`(:supervisor (:restart-window "24h"))` — the shared duration codec
1790/// emits `"<n>h"` for any integer-hour magnitude) both round-trip
1791/// cleanly through serde — a structurally unbounded `Duration` ceiling.
1792/// A `:restart-window` value far above the documented Erlang/OTP
1793/// `MaxIntensity / Period` production-playbook band (Learn You Some
1794/// Erlang's `{intensity, 5, 60}` worker-supervisor `Period = 60s`
1795/// default, Elixir's `Supervisor` `max_seconds: 5` default, OTP's
1796/// `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's
1797/// `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default)
1798/// degenerates the supervisor's restart-intensity counter into a
1799/// lifetime counter: the rolling failure-counting window is structurally
1800/// so long that transient restarts are never forgotten, so the
1801/// `MaxIntensity / Period` ratio degenerates from "trip the parent
1802/// supervisor when the child has exceeded its restart budget *within
1803/// the recent window*" to "trip the parent when the child has exceeded
1804/// its restart budget *over its lifetime*" — every transient restart
1805/// counts against the budget forever, the supervisor's reset semantic
1806/// never reaches the child, and the typed `:restart-window` slot
1807/// becomes a no-op rolling window carried on every emitted hierarchical
1808/// reconciliation contract. The canonical
1809/// rolling-window-degenerates-to-lifetime-counter footgun the sibling
1810/// [`crate::POLICY_BREAKER_WINDOW_MAX`] cap closes on the peer
1811/// `:politicas :circuit-breaker :window` axis with identical shape (both
1812/// are "rolling failure-counting window with a per-`Period` reset" Duration
1813/// axes whose lifetime-counter degenerate at the high end is the same
1814/// "the reset semantic never fires" CSE invariant violation).
1815///
1816/// The `1h` (3600s = `3_600_000` ms) ceiling matches the largest unit
1817/// the shared duration codec emits (`"<n>h"` for any integer-hour
1818/// magnitude) — every value in the canonical authoring form's
1819/// `<integer><unit>` grammar at or below this cap renders to a clean
1820/// canonical string — and matches the three sibling typed-`Duration`
1821/// caps already lifted to this surface
1822/// ([`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
1823/// [`crate::POLICY_BREAKER_WINDOW_MAX`]). All four typed-`Duration`
1824/// axes — per-process `:limits :wall-clock`, per-edge `:politicas
1825/// :timeout`, per-breaker `:politicas :circuit-breaker :window`, and
1826/// per-supervisor `:supervisor :restart-window` — now share a single
1827/// uniform top edge at the codec's largest emitted unit so the next
1828/// typed-slot wiring (the future wasm-operator's per-supervisor
1829/// `MaxIntensity / Period` reconciler, the M4
1830/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
1831/// webhook, the `caixa-operator`'s hierarchical reconciliation
1832/// scheduler) reaches for any of the four knowing the value is in
1833/// `1ms..=1h` without re-validating at the renderer layer. The cap sits
1834/// two orders of magnitude above every documented Erlang/OTP / Elixir /
1835/// Riak Core / RabbitMQ production-playbook recommendation band
1836/// (`5s..=300s`) and below the clearly-pathological "rolling window
1837/// degenerates to lifetime counter" floor (`24h`, `7d`, `Duration::MAX`):
1838/// a value the author can plausibly want for a very-low-traffic
1839/// long-tail failure-restart window over a hyperscale-flaky child pool,
1840/// but a hard wall above which the rolling-window contract is
1841/// structurally a lifetime-counter contract.
1842///
1843/// Lifted as a typed `pub const` so the bound has exactly one source
1844/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
1845/// materializer's admission webhook, the wasm-operator-side
1846/// per-supervisor `MaxIntensity / Period` reconciler, and the
1847/// `caixa-operator`'s hierarchical reconciliation scheduler all read
1848/// from one place. Same shape every other typed upper bound in this
1849/// crate carries ([`SUPERVISOR_MAX_RESTARTS_MAX`],
1850/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
1851/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
1852/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
1853/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
1854/// [`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
1855/// [`crate::POLICY_BREAKER_WINDOW_MAX`],
1856/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
1857/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
1858pub const SUPERVISOR_RESTART_WINDOW_MAX: Duration = Duration::from_secs(3600);
1859
1860/// Substrate-canonical Erlang/OTP-shaped `Period` sliding-window-duration
1861/// default for the `:supervisor :restart-window` axis — the canonical
1862/// `{intensity, 5, 60}` `Period` half of Learn You Some Erlang's
1863/// worker-supervisor default, extracted as a typed `pub const` so every
1864/// substrate-side consumer that resolves "what
1865/// [`SupervisorSpec::restart_window`] value does an author-omitted
1866/// `:restart-window` slot degrade onto?" reaches for exactly one
1867/// substrate-primitive [`Duration`].
1868///
1869/// The `:restart-window` default axis has one production consumer on the
1870/// substrate side today: the [`Default for SupervisorSpec`] impl's
1871/// struct-literal `restart_window` field, which prior to this lift folded
1872/// onto a raw `Duration::from_secs(60)` literal with no compile-time link
1873/// back to the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity`
1874/// half of the same `{intensity, 5, 60}` OTP-canonical default. The
1875/// [`crate::manifest::Caixa::supervisor_view`] fold deliberately does
1876/// *not* fall back to this default on the sibling `:restart-window` axis
1877/// — an author-omitted `:supervisor :restart-window` composes to
1878/// `restart_window: None` (the shared codec's soft-swallow shape),
1879/// keeping author-declared intent ("no reset — never escalate on rolling
1880/// window") distinct from the [`Default for SupervisorSpec`] "canonical
1881/// 60s Period" arm every programmatic `SupervisorSpec::default()` caller
1882/// resolves to. Prior to this lift the paired `{intensity, 5, 60}` OTP
1883/// default was split across two files with no compile-time link between
1884/// the halves: [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] pinned the
1885/// `MaxIntensity` half at the substrate primitive while the `Period`
1886/// half rode as an open-coded literal at the composition site, so a
1887/// future coherent rebrand of the paired canonical (a tightening to
1888/// Elixir's `{max_restarts: 3, max_seconds: 5}`, a widening to a
1889/// per-cluster overlay the operator pins through a future
1890/// `:supervisor :restart-window-overrides` slot the MESH-COMPOSITION
1891/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
1892/// paired constants to a per-child-cohort `{MaxR, MaxT}` restart-budget-
1893/// partition once the INSPIRATIONS §II.2 Erlang/OTP per-child-cohort
1894/// roadmap lands) would have had to migrate the `MaxIntensity` half
1895/// through the lifted constant and the `Period` half through a raw
1896/// literal in lockstep or the two halves of the same OTP-canonical
1897/// default would silently drift out of pairing. Lifting the resolution
1898/// rule to a typed `pub const` on the substrate primitive means the
1899/// paired OTP-canonical default migrates as one unit on any future
1900/// axis change.
1901///
1902/// The `60s` value pins Learn You Some Erlang's `{intensity, 5, 60}`
1903/// worker-supervisor default (the closest canonical OTP-shape
1904/// production reference the substrate carries, matching the paired
1905/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5` `MaxIntensity` half this
1906/// constant is the `Period` denominator of on the same
1907/// `MaxIntensity / Period` restart-intensity ratio). Two orders of
1908/// magnitude below the [`SUPERVISOR_RESTART_WINDOW_MAX`] `3600s`
1909/// (`1h`) ceiling (the upper bracket on the same axis, sibling of
1910/// this lower default; both are typed [`Duration`] const bounds on the
1911/// `:supervisor :restart-window` axis and now share one accessor
1912/// discipline on the substrate) and above the OTP-`supervisor`
1913/// callback-module `MaxT = 5` seconds "minimal-window" floor — the "60s
1914/// rolling window" default is deliberately loose enough to absorb a
1915/// short burst of transient child failures without escalating past the
1916/// supervisor's parent while remaining tight enough for the paired
1917/// `MaxIntensity / Period` ratio's escalation to trip on a genuinely-
1918/// stuck child within a human-scale observation window.
1919///
1920/// Lifted as a typed `pub const` so the paired OTP-canonical default has
1921/// exactly one source of truth on each half — the sibling
1922/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half and this
1923/// `Period` `60s` half now share the same substrate-primitive lift
1924/// discipline. Same shape every other typed default in this crate
1925/// carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] paired
1926/// `MaxIntensity` half on the same OTP-canonical `{intensity, 5, 60}`,
1927/// the sibling [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the same
1928/// axis, and the peer [`crate::render::DEFAULT_NAMESPACE`] /
1929/// [`crate::render::DEFAULT_LIBRARY_NAME`] per-renderer defaults on the
1930/// caixa-flux / caixa-helm rendering axes).
1931pub const SUPERVISOR_RESTART_WINDOW_DEFAULT: Duration = Duration::from_secs(60);
1932
1933/// Substrate-canonical Erlang/OTP-shaped sibling-restart-strategy default
1934/// for the `:supervisor :estrategia` axis — the canonical `one_for_one`
1935/// half of Learn You Some Erlang's `{one_for_one, intensity, 5, 60}`
1936/// worker-supervisor default, extracted as a typed `pub const` so every
1937/// substrate-side consumer that resolves "what
1938/// [`SupervisorSpec::estrategia`] variant does an author-omitted
1939/// `:estrategia` slot degrade onto?" reaches for exactly one substrate-
1940/// primitive [`RestartStrategy`].
1941///
1942/// The `:estrategia` default axis has three production consumers on the
1943/// substrate side today: the [`Default for RestartStrategy`] impl's
1944/// return arm, the [`Default for SupervisorSpec`] impl's struct-literal
1945/// `estrategia` field, and the
1946/// [`crate::manifest::Caixa::supervisor_view`] fold's
1947/// `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)` `Option<RestartStrategy>`
1948/// collapse arm — three entry points onto the same OTP-canonical
1949/// `one_for_one` value that prior to this lift folded onto a raw
1950/// `Self::OneForOne` arm at the [`Default for RestartStrategy`] impl and
1951/// implicit `RestartStrategy::default()` routes at the sibling consumers,
1952/// with no compile-time link back to the paired
1953/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` half + the paired
1954/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` half of the same
1955/// `{one_for_one, intensity, 5, 60}` OTP-canonical default. The paired
1956/// triple was split across three altitudes with no compile-time link
1957/// between the halves: the `MaxIntensity` half rode through the lifted
1958/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant (b698ec0) and the `Period`
1959/// half rode through the lifted [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
1960/// constant (f7dcd0e) while the `one_for_one` half rode as an open-coded
1961/// discriminator at the [`Default for RestartStrategy`] impl, so a future
1962/// coherent rebrand of the triple (Elixir's `{:one_for_one,
1963/// max_restarts: 3, max_seconds: 5}` — same strategy, different
1964/// intensity/period; an OTP `rest_for_one` widening once the substrate
1965/// discovers startup-order-coupled child cohorts as the more common
1966/// worker-supervisor default; a per-cluster overlay the operator pins
1967/// through a future `:estrategia-overrides` slot the MESH-COMPOSITION
1968/// §III.2 supervision-canary roadmap acknowledges) would have had to
1969/// migrate the `MaxIntensity` + `Period` halves through the lifted
1970/// constants and the `one_for_one` half through an open-coded arm in
1971/// lockstep or the three halves of the same OTP-canonical default would
1972/// silently drift out of pairing. Lifting the resolution rule to a typed
1973/// `pub const` on the substrate primitive means the paired OTP-canonical
1974/// worker-supervisor default migrates as one unit on any future axis
1975/// change.
1976///
1977/// The [`RestartStrategy::OneForOne`] value pins Learn You Some Erlang's
1978/// `{one_for_one, intensity, 5, 60}` worker-supervisor default (the
1979/// closest canonical OTP-shape production reference the substrate
1980/// carries, matching the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5`
1981/// `MaxIntensity` half and the paired [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
1982/// `60s` `Period` half). The `one_for_one` strategy — restart only the
1983/// failed child, leaving siblings untouched — is the default for tree-of-
1984/// independent-workers use cases the substrate's [`RestartStrategy`]
1985/// discriminator's own docstring already carries as the default arm; it
1986/// composes with the `{5, 60}` restart-intensity ratio to name the same
1987/// substrate-canonical "canonical worker-supervisor" shape the paired
1988/// halves close on their respective axes.
1989///
1990/// Lifted as a typed `pub const` so the paired OTP-canonical default has
1991/// exactly one source of truth on each of its three halves — the sibling
1992/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half, the
1993/// sibling [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` `60s` half, and
1994/// this `one_for_one` strategy half now share the same substrate-
1995/// primitive lift discipline. Same shape every other typed default in
1996/// this crate carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] +
1997/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] paired halves on the same OTP-
1998/// canonical `{one_for_one, intensity, 5, 60}`, the sibling
1999/// [`SUPERVISOR_MAX_RESTARTS_MAX`] + [`SUPERVISOR_RESTART_WINDOW_MAX`]
2000/// upper caps on the paired sibling axes, and the peer
2001/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
2002/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes).
2003pub const SUPERVISOR_ESTRATEGIA_DEFAULT: RestartStrategy = RestartStrategy::OneForOne;
2004
2005/// Substrate-canonical Erlang/OTP-shaped per-child restart-decision-policy
2006/// default for the `:children :restart` axis — the OTP `permanent`
2007/// worker-child default (`{ChildId, StartFunc, permanent, …}` in a
2008/// `supervisor`'s `init/1` child-spec tuple), extracted as a typed
2009/// `pub const` so every substrate-side consumer that resolves "what
2010/// [`ChildSpec::restart`] variant does an author-omitted `:children
2011/// :restart` slot degrade onto?" reaches for exactly one substrate-
2012/// primitive [`RestartPolicy`].
2013///
2014/// Completes the OTP-shape supervisor-tree default set at the substrate
2015/// primitive. The per-`:supervisor` axis already carries all three of its
2016/// halves as lifted typed constants — [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
2017/// (`one_for_one`, 95ffacc), [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
2018/// (`MaxIntensity` `5`, b698ec0), [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2019/// (`Period` `60s`, f7dcd0e) — while the per-`:children` axis's own
2020/// OTP-canonical default rode as an open-coded `Self::Permanent` arm in
2021/// the [`Default for RestartPolicy`] impl, the last un-lifted default on
2022/// the M2 `:supervisor` slot family. The split mattered because the two
2023/// axes resolve *together* on every author-omitted supervisor: a
2024/// `(defcaixa :kind Supervisor :children ((:caixa "worker" :versao
2025/// "^0.1")))` with no `:estrategia` and no per-child `:restart` degrades
2026/// onto `{one_for_one, 5, 60}` through three lifted constants and onto
2027/// `permanent` through an open-coded enum arm, so a future coherent
2028/// rebrand of the OTP-shape default set (an Elixir-shaped
2029/// `{:one_for_one, max_restarts: 3, max_seconds: 5}` tightening, a
2030/// per-cluster overlay the operator pins through the MESH-COMPOSITION
2031/// §III.2 supervision-canary roadmap slots, an OTP-`transient` widening
2032/// once the substrate discovers clean-completion-aware children as the
2033/// more common child shape) would have had to migrate three halves
2034/// through typed constants and the fourth through a raw enum arm in
2035/// lockstep or the supervisor-level and child-level defaults would
2036/// silently drift apart.
2037///
2038/// The `:children :restart` default axis has two production consumers on
2039/// the substrate side today: the [`Default for RestartPolicy`] impl's
2040/// return arm, and the serde-side `#[serde(default)]` on
2041/// [`ChildSpec::restart`] that resolves an author-omitted `:children
2042/// :restart` slot through that same impl. Both now key off this one
2043/// substrate primitive, so the future wasm-operator's per-child post-exit
2044/// restart-decision branch, the future M4
2045/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2046/// admission webhook, and the `caixa-operator`'s hierarchical
2047/// reconciliation scheduler's per-child fan-out all reach for one typed
2048/// identifier when they resolve an omitted per-child restart posture.
2049///
2050/// The [`RestartPolicy::Permanent`] value pins Erlang/OTP's `permanent`
2051/// worker-child restart type — always restart the child regardless of how
2052/// it died, the canonical posture for long-running services that must
2053/// always be up, matching the sibling [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
2054/// `one_for_one` tree-of-independent-workers strategy this constant pairs
2055/// with under the same `{one_for_one, intensity, 5, 60}` worker-supervisor
2056/// shape. The two alternatives the closed [`RestartPolicy::ALL`] accept-set
2057/// carries ([`RestartPolicy::Transient`] — restart only on abnormal exit;
2058/// [`RestartPolicy::Temporary`] — never restart) express deliberate
2059/// one-shot / clean-completion-aware postures an author declares
2060/// explicitly, never a posture an omitted slot should silently assume.
2061pub const SUPERVISOR_CHILD_RESTART_DEFAULT: RestartPolicy = RestartPolicy::Permanent;
2062
2063/// Route the manually-authored [`Default`] impl on [`SupervisorSpec`]
2064/// through the substrate-canonical [`SupervisorSpec::otp_canonical`]
2065/// `pub const fn` constructor rather than a struct-literal cascade over
2066/// the paired [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
2067/// [`default_max_restarts`] / [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
2068/// lifted consts — one source of truth for the Erlang/OTP-canonical
2069/// `{one_for_one, 5, 60}` worker-supervisor baseline across the two
2070/// paths every downstream consumer already reaches through (the
2071/// hand-authored-until-now [`Default::default`] the
2072/// `..SupervisorSpec::default()` struct-update-syntax on every
2073/// one-axis-under-test fixture in this crate's test module rests on,
2074/// and the `pub const fn` [`SupervisorSpec::otp_canonical`] constructor
2075/// every `const`-context consumer reaches through).
2076///
2077/// Extends the [`Default`]-through-const-ctor fold discipline the
2078/// [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
2079/// (abd52c2), [`crate::aplicacao::MeshPolicy`]
2080/// [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`] (91641a4),
2081/// and [`crate::BehaviorSpec`]
2082/// [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c) folds
2083/// closed on the M2 / M3 `Option`-only "canonical unset baseline"
2084/// typed-slot spec family — extended here onto the M2 supervisor-slot
2085/// [`SupervisorSpec`] whose canonical baseline is not "everything
2086/// `None`" but the OTP-canonical `{one_for_one, 5, 60}` worker-
2087/// supervisor triple. The `empty()` peer's naming did not fit
2088/// (`SupervisorSpec` carries a discriminator-shaped `estrategia` field
2089/// and a non-zero `max_restarts`/`restart_window` pair whose canonical
2090/// shape is Erlang/OTP-descended, not the "no axis declared" bottom
2091/// the sibling `Option`-only slots fold to), so this peer is named
2092/// [`SupervisorSpec::otp_canonical`] instead — the same phrasing the
2093/// existing per-arm pin tests
2094/// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`] /
2095/// [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`] /
2096/// [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
2097/// already reach for. Pinned load-bearing by
2098/// [`tests::supervisor_spec_default_routes_through_otp_canonical_ctor`]
2099/// (byte-parity pin against [`SupervisorSpec::otp_canonical`] under
2100/// [`PartialEq`], sharpening the sibling
2101/// `supervisor_spec_default_*_routes_through_lifted_default` per-arm
2102/// pins from a per-field lift into a whole-struct one-source-of-truth
2103/// pin — the derived-until-now [`Default::default`] and the
2104/// [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
2105/// construction, not by coincidence).
2106impl Default for SupervisorSpec {
2107 #[inline]
2108 fn default() -> Self {
2109 Self::otp_canonical()
2110 }
2111}
2112
2113impl SupervisorSpec {
2114 /// `const`-context peer of the [`Default for SupervisorSpec`]
2115 /// impl (which routes through this constructor) — returns the
2116 /// Erlang/OTP-canonical `{one_for_one, 5, 60}` worker-supervisor
2117 /// baseline this crate reaches for in every fixture-builder
2118 /// `..SupervisorSpec::default()` struct-update expression and
2119 /// every downstream `SupervisorSpec::default()` seed.
2120 ///
2121 /// Each field routes through the same substrate-canonical
2122 /// [`SUPERVISOR_ESTRATEGIA_DEFAULT`] / [`default_max_restarts`] /
2123 /// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] lifted consts the
2124 /// per-arm pin tests
2125 /// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`]
2126 /// / [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`]
2127 /// / [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
2128 /// already assert, so a future coherent rebrand of the OTP-canonical
2129 /// triple (Elixir's `{max_restarts: 3, max_seconds: 5}`, a per-
2130 /// cluster overlay via a future `:restart-window-overrides` slot, a
2131 /// per-child-cohort promotion the INSPIRATIONS.md §II.2 Erlang/OTP
2132 /// absorption roadmap acknowledges) migrates through three typed
2133 /// constants in lockstep, and the paired [`Default`] impl inherits
2134 /// every future extension by construction.
2135 ///
2136 /// `pub const fn` rather than the derived-style `Default::default`
2137 /// or a `pub const SUPERVISOR_SPEC_DEFAULT: SupervisorSpec` item —
2138 /// [`Default::default`] is not `const` on stable Rust, and
2139 /// `SupervisorSpec` is non-`Copy` so a `pub const` item would force
2140 /// every consumer through a [`Clone::clone`]. The `pub const fn`
2141 /// discipline lets `const`-context callers construct the OTP-
2142 /// canonical baseline at compile time without runtime dispatch on
2143 /// the derived [`Default::default`], the same posture the sibling
2144 /// [`crate::LimitsSpec::empty`] (9739971) /
2145 /// [`crate::aplicacao::MeshPolicy::empty`] (6df969b) /
2146 /// [`crate::BehaviorSpec::empty`] (f9b18e3) `Option`-only typed-slot
2147 /// spec `pub const fn` constructors carry on the sibling
2148 /// "everything `None`" baseline axis.
2149 ///
2150 /// Fourth peer on the M2 / M3 typed-slot-spec "const-context peer
2151 /// of the derived-style [`Default`]" family — sibling of the
2152 /// [`crate::LimitsSpec::empty`] / [`crate::aplicacao::MeshPolicy::empty`]
2153 /// / [`crate::BehaviorSpec::empty`] `Option`-only "canonical unset
2154 /// baseline" trio, extended here onto the M2 supervisor-slot
2155 /// [`SupervisorSpec`] whose canonical baseline is not "everything
2156 /// `None`" but the Erlang/OTP-canonical `{one_for_one, 5, 60}`
2157 /// worker-supervisor triple. Named [`Self::otp_canonical`] rather
2158 /// than `empty()` to name the actual invariant the return value
2159 /// pins — the same phrasing already used in the per-arm pin tests
2160 /// on this file. Pinned load-bearing by
2161 /// [`tests::supervisor_spec_otp_canonical_byte_equals_default`] and
2162 /// [`tests::supervisor_spec_otp_canonical_is_usable_in_const_context`].
2163 #[must_use]
2164 pub const fn otp_canonical() -> Self {
2165 Self {
2166 estrategia: SUPERVISOR_ESTRATEGIA_DEFAULT,
2167 max_restarts: default_max_restarts(),
2168 restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
2169 children: Vec::new(),
2170 }
2171 }
2172
2173 /// Substrate-canonical per-`:supervisor` `:estrategia` OTP-shaped
2174 /// sibling-restart-strategy scalar accessor every consumer that
2175 /// dispatches on the supervisor's per-sibling restart-decision shape
2176 /// keys off — returns the author-declared `:supervisor :estrategia`
2177 /// variant verbatim as a [`RestartStrategy`], `Copy`-projected from
2178 /// the typed slot's own [`RestartStrategy`] storage.
2179 ///
2180 /// The `:supervisor :estrategia` slot carries the closed-set
2181 /// OTP-shaped sibling-restart-strategy discriminator ([`RestartStrategy::OneForOne`]
2182 /// — restart only the failed child, the Erlang/OTP `one_for_one` default;
2183 /// [`RestartStrategy::OneForAll`] — restart every child on any child
2184 /// failure, the Erlang/OTP `one_for_all` shared-state cohort default;
2185 /// [`RestartStrategy::RestForOne`] — restart the failed child and
2186 /// every child started after it, the Erlang/OTP `rest_for_one`
2187 /// startup-order default; [`RestartStrategy::SimpleOneForOne`] —
2188 /// dynamic children of the same shape, the Erlang/OTP
2189 /// `simple_one_for_one` per-session default) that every downstream
2190 /// consumer of the Supervisor's per-sibling restart-decision fan-out
2191 /// shape keys off. Validated by [`SupervisorSpec::validate`] to be
2192 /// paired coherently with the sibling `:children` axis
2193 /// (`SimpleOneForOne ↔ children.is_empty()` — the cross-slot
2194 /// partition the strategy-arm's [`SupervisorError::SimpleOneForOneWithStaticChildren`]
2195 /// / [`SupervisorError::NoChildren`] refusal cascade pins), and every
2196 /// downstream consumer that reads the strategy keys off this scalar
2197 /// (the [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
2198 /// partition-dispatch `match` arm, the non-`SimpleOneForOne`-arm
2199 /// declared-but-empty [`SupervisorError::NoChildren`] error carrier's
2200 /// `estrategia:` field, the future `feira app graph` per-Supervisor
2201 /// strategy print line, the future wasm-operator's per-supervisor
2202 /// sibling-restart-strategy branch, the future M4
2203 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-strategy
2204 /// admission-webhook resolver, the `caixa-operator`'s hierarchical
2205 /// reconciliation scheduler's per-strategy fan-out).
2206 ///
2207 /// Prior to this lift the `.estrategia` field was accessed inline at
2208 /// two production sites in `caixa-core/src/supervisor.rs` — the
2209 /// [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
2210 /// `match self.estrategia { … }` partition dispatch, and the
2211 /// non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
2212 /// carrier at `estrategia: self.estrategia` — two open-coded
2213 /// field-accesses that expressed no compile-time link back to the
2214 /// typed slot. A future extension of the `:supervisor :estrategia`
2215 /// axis to a richer author surface (a per-cluster strategy override
2216 /// the operator pins through a future `:supervisor :estrategia-overrides`
2217 /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
2218 /// acknowledges, a per-tenant strategy-alias table the M4 CR
2219 /// materializer resolves per-CR, a per-Supervisor dynamic strategy
2220 /// derivation the future adaptive-supervision engine computes from
2221 /// child-failure-history topology, a per-child-cohort strategy split
2222 /// the future `RestForCohort` extension acknowledged by the
2223 /// INSPIRATIONS.md §II.2 Erlang/OTP absorption roadmap acknowledges)
2224 /// would have had to be threaded through every open-coded copy in
2225 /// lockstep — one consumer reading the raw variant while a peer read
2226 /// the operator-resolved variant would silently split the
2227 /// [`SupervisorError::NoChildren`] diagnostic's quoted strategy from
2228 /// the actual partition-dispatch input the empty-children refusal
2229 /// arm reached under, a two-consumer split at the validator far from
2230 /// the source `caixa.lisp` with no field naming the strategy-drift
2231 /// root cause. Lifting the resolution rule to a typed method on the
2232 /// substrate primitive means every downstream consumer of the
2233 /// Supervisor's per-`:supervisor` sibling-restart-strategy surface
2234 /// reaches for exactly one typed dispatch — the resolver's accept-set
2235 /// migrates as a unit on any future axis addition.
2236 ///
2237 /// Peer of the sibling M3 mesh-slot [`crate::Placement::estrategia`]
2238 /// (921fe1b) `Copy`-return `PlacementStrategy` scalar accessor on the
2239 /// per-`:placement` distribution-strategy axis — same "one typed
2240 /// dispatch on the substrate primitive, thin projections at each
2241 /// consumer" discipline extended onto the M2 supervisor-slot
2242 /// per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
2243 /// scalar axis. The two typed axes (`Placement::estrategia` on the
2244 /// M3 Aplicacao side, `SupervisorSpec::estrategia` on the M2
2245 /// Supervisor side) now share one accessor discipline for the shared
2246 /// substrate concept "a `Copy`-projected closed-set enum-arm
2247 /// discriminator that partitions the downstream renderer's per-arm
2248 /// fan-out". First `Copy`-return accessor on the M2 supervisor-slot
2249 /// `SupervisorSpec` type — companion to the sibling per-`:children`
2250 /// [`crate::ChildSpec::nome`] (57c61d0) /
2251 /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
2252 /// scalar accessors on the sibling per-`:children` `String`-carry
2253 /// axes. Named `estrategia()` to match the storage field's name and
2254 /// the peer [`crate::Placement::estrategia`] method-name discipline
2255 /// verbatim; the accessor's identity name maps onto the canonical
2256 /// OTP-shape supervision vocabulary the [`RestartStrategy`] enum's
2257 /// docstring already carries.
2258 ///
2259 /// Declared `pub const fn` to close the M2 supervisor-slot
2260 /// `Copy`-return raw-field-getter `const`-eval-surface pass —
2261 /// sibling of the peer M2 per-`:children` [`ChildSpec::restart`]
2262 /// (converted in this commit) `Copy`-composite-enum accessor, peer
2263 /// of the sibling M2 per-`:supervisor`
2264 /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
2265 /// already lifted, and mirror of the peer M3 mesh-slot
2266 /// per-`:placement` [`crate::Placement::estrategia`] (bafa004)
2267 /// `Copy`-return `pub const fn` scalar accessor whose method-name
2268 /// discipline this accessor was authored to match. Every downstream
2269 /// substrate-side `const`-context consumer of the per-`:supervisor`
2270 /// sibling-restart-strategy scalar (a future module-scope `const
2271 /// _:() = assert!(matches!(sup.estrategia(),
2272 /// RestartStrategy::OneForOne))` invariant pin on a typed fixture,
2273 /// a future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
2274 /// admission-webhook `const fn` per-supervisor strategy-arm floor
2275 /// over a typed [`SupervisorSpec`], any future `const fn`
2276 /// supervisor-tree composer over the substrate primitive that fans
2277 /// on the sibling-restart-strategy at compile time) now reaches
2278 /// through the same typed dispatch on the substrate primitive at
2279 /// const-eval time as at runtime. A future non-`Copy`-return
2280 /// promotion of the scalar (an `Option<RestartStrategy>`-shape
2281 /// migration once the substrate grows per-cluster strategy overlays
2282 /// the [`SupervisorSpec`] docstring already anticipates, a
2283 /// per-tenant strategy-alias table the M4 CR materializer resolves
2284 /// per-CR) that would drop the `const` qualifier fails the
2285 /// fail-before-pass-after pin
2286 /// [`tests::supervisor_spec_estrategia_accessor_is_const_fn`] at
2287 /// caixa-core build time rather than surfacing as a downstream
2288 /// consumer regression.
2289 #[must_use]
2290 pub const fn estrategia(&self) -> RestartStrategy {
2291 self.estrategia
2292 }
2293
2294 /// Substrate-canonical per-`:supervisor` `:max-restarts` OTP-shaped
2295 /// `MaxIntensity` restart-budget scalar accessor every consumer that
2296 /// reads the supervisor's per-`:restart-window` restart-budget count
2297 /// keys off — returns the author-declared `:supervisor :max-restarts`
2298 /// typed `u32` verbatim, `Copy`-projected from the typed slot's own
2299 /// `u32` storage (`u32` is `Copy`, so the accessor returns by value; no
2300 /// borrow of `&self` past the call). Non-optional (the `u32` field
2301 /// carries the restart-budget count as a required axis with a
2302 /// [`default_max_restarts`]-supplied default; the zero-floor arm
2303 /// [`SupervisorError::ZeroMaxRestarts`] and the cap arm
2304 /// [`SupervisorError::MaxRestartsExceedsCap`] jointly bracket the
2305 /// accept-set to `1..=SUPERVISOR_MAX_RESTARTS_MAX`).
2306 ///
2307 /// The `:supervisor :max-restarts` slot carries the Erlang/OTP
2308 /// `MaxIntensity` restart-budget count that pairs with the sibling
2309 /// `:restart-window` `Period` to form the `MaxIntensity / Period`
2310 /// restart-intensity ratio the supervisor trips its own escalation on
2311 /// (`theory/RUNTIME-PATTERNS.md` §II.2, Learn You Some Erlang's
2312 /// `{intensity, 5, 60}` worker-supervisor default). Every downstream
2313 /// consumer of the Supervisor's per-`:supervisor` restart-budget count
2314 /// keys off this scalar (the [`SupervisorSpec::validate`] zero-floor +
2315 /// upper-cap bracket at
2316 /// `require_positive_bounded_u32(self.max_restarts(), …)`, the future
2317 /// wasm-operator's per-supervisor restart-intensity counter's
2318 /// budget-vs-count comparator, the future M4
2319 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2320 /// webhook, the `caixa-operator`'s hierarchical reconciliation
2321 /// scheduler's per-supervisor escalation-decision branch, every
2322 /// `SupervisorError::MaxRestartsExceedsCap` variant carrying the
2323 /// offending count verbatim for `feira lint` rendering).
2324 ///
2325 /// Prior to this lift the `.max_restarts` field was accessed inline at
2326 /// one production site in `caixa-core/src/supervisor.rs` — the
2327 /// [`SupervisorSpec::validate`] `require_positive_bounded_u32(self
2328 /// .max_restarts, …)` bracket-gate call — one open-coded field-access
2329 /// that expressed no compile-time link back to the typed slot. A
2330 /// future extension of the `:max-restarts` axis to a richer author
2331 /// surface (a per-cluster restart-budget override the operator pins
2332 /// through a future `:supervisor :max-restarts-overrides` slot the
2333 /// MESH-COMPOSITION §III.2 supervision-canary roadmap acknowledges,
2334 /// a per-tenant restart-budget-alias table the M4 CR materializer
2335 /// resolves per-CR, a per-supervisor dynamic restart-budget derivation
2336 /// the future adaptive-supervision engine computes from child-failure-
2337 /// history topology, a promotion of the plain `u32` count to a richer
2338 /// `{MaxR, MaxT}` tuple once Erlang/OTP's per-child-cohort restart-
2339 /// budget-partition slot comes into scope) would have had to be
2340 /// threaded through every open-coded copy in lockstep or the validate
2341 /// gate and the future M4 emit path would silently disagree on which
2342 /// restart-budget count a given supervisor resolves to — an author's
2343 /// `:max-restarts 5` would satisfy validate while the emit path
2344 /// silently read a drifted other value (a `:max-restarts 10000`
2345 /// no-op supervisor at the emit boundary would carry the author's
2346 /// declared `5` verbatim in `feira lint` output while the future
2347 /// wasm-operator's restart-intensity counter operated under the
2348 /// drifted count), a two-consumer split at the validator far from the
2349 /// source `caixa.lisp` with no field naming the restart-budget-drift
2350 /// root cause. Lifting the resolution rule to a typed method on the
2351 /// substrate primitive means every downstream consumer of the
2352 /// Supervisor's per-`:supervisor` restart-budget-count surface reaches
2353 /// for exactly one typed dispatch — the resolver's accept-set migrates
2354 /// as a unit on any future axis addition.
2355 ///
2356 /// Peer of the sibling M3 mesh-slot [`crate::CircuitBreaker::max_failures`]
2357 /// (3a74062) `Copy`-return `u32` sub-struct required-scalar accessor
2358 /// on the per-`:politicas :circuit-breaker :max-failures` Envoy-
2359 /// outlier-detection trip-threshold axis — same "one typed dispatch on
2360 /// the substrate primitive, thin projections at each consumer"
2361 /// discipline extended onto the M2 supervisor-slot per-`:supervisor`
2362 /// restart-budget-count `Copy`-`u32` scalar axis. The two typed axes
2363 /// (`CircuitBreaker::max_failures` on the M3 Aplicacao side,
2364 /// `SupervisorSpec::max_restarts` on the M2 Supervisor side) now share
2365 /// one accessor discipline for the shared substrate concept "a
2366 /// `Copy`-projected required `u32` count that trips the next-higher
2367 /// protection layer after N events in a rolling window" — both are
2368 /// counters with identical degenerate-at-the-high-end shape and share
2369 /// the paired [`crate::POLICY_BREAKER_MAX_FAILURES_MAX`] /
2370 /// [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` cap. Second `Copy`-return
2371 /// accessor on the M2 supervisor-slot `SupervisorSpec` type, sibling
2372 /// to the [`SupervisorSpec::estrategia`] (eafb619) `Copy`-composite-
2373 /// enum `RestartStrategy` accessor. Named `max_restarts()` to match
2374 /// the storage field's name verbatim and the peer
2375 /// [`crate::CircuitBreaker::max_failures`] method-name discipline; the
2376 /// accessor's identity maps onto the canonical OTP-shape supervision
2377 /// vocabulary the [`SupervisorSpec::max_restarts`] field's docstring
2378 /// already carries.
2379 #[must_use]
2380 pub const fn max_restarts(&self) -> u32 {
2381 self.max_restarts
2382 }
2383
2384 /// Substrate-canonical per-`:supervisor` `:restart-window` OTP-shaped
2385 /// `Period` sliding-window scalar accessor every consumer of the
2386 /// supervisor's `MaxIntensity / Period` restart-intensity denominator
2387 /// keys off — returns the author-declared `:supervisor :restart-window`
2388 /// typed [`Duration`] verbatim as an `Option<Duration>`, copied out of
2389 /// the typed slot's own `Option<Duration>` storage (`Duration` is
2390 /// `Copy`, so `Option<Duration>` is `Copy` and the accessor returns by
2391 /// value; no borrow of `&self` past the call). `None` when the slot is
2392 /// absent (the canonical "never reset — every restart across the
2393 /// supervisor's lifetime counts against the sibling `:max-restarts`
2394 /// budget" sentinel the field's own docstring names and the peer
2395 /// `validate_accepts_none_restart_window` pin locks in on the
2396 /// [`SupervisorSpec::validate`] entry-side).
2397 ///
2398 /// The `:supervisor :restart-window` slot carries the Erlang/OTP
2399 /// `Period` sliding-observation-interval that pairs with the sibling
2400 /// `:max-restarts` `MaxIntensity` restart-budget count to form the
2401 /// `MaxIntensity / Period` restart-intensity ratio the supervisor
2402 /// trips its own escalation on (`theory/RUNTIME-PATTERNS.md` §II.2,
2403 /// Learn You Some Erlang's `{intensity, 5, 60}` worker-supervisor
2404 /// default). The typed slot's `Option<Duration>` accept-set —
2405 /// zero-floor rejected through [`SupervisorError::RestartWindowZero`]
2406 /// (Erlang/OTP's `MaxIntensity / Period` invariant requires
2407 /// `Period > 0`; a zero period either trips on the first failure or
2408 /// never trips depending on operator interpretation, neither of which
2409 /// is the author's intent — omit the slot to express "no reset";
2410 /// carry a positive duration to express the sliding window),
2411 /// integer-millisecond canonical form enforced through
2412 /// [`SupervisorError::RestartWindowNotCanonical`] (the duration
2413 /// codec's canonical form emits `"1500ms"` not `"1.5s"` and the
2414 /// future wasm-operator's per-supervisor restart-intensity counter
2415 /// quantizes at milliseconds), upper-bounded by
2416 /// [`SUPERVISOR_RESTART_WINDOW_MAX`] (1h — the coarsest per-
2417 /// supervisor rolling window any operationally-reachable supervisor
2418 /// can honor without spanning multiple scheduler epochs the
2419 /// hierarchical-reconciliation scheduler treats as independent) —
2420 /// maps onto the future wasm-operator (M3) per-supervisor
2421 /// restart-intensity counter's rolling-observation-interval, the
2422 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2423 /// per-`spec.restartWindow` admission webhook, and the sibling
2424 /// `duration_codec`-serialized wire scalar every downstream consumer
2425 /// of the supervisor's per-`:supervisor` restart-intensity denominator
2426 /// keys off.
2427 ///
2428 /// Prior to this lift the `.restart_window` field was accessed inline
2429 /// at one production site in `caixa-core/src/supervisor.rs` — the
2430 /// [`SupervisorSpec::validate`] `if let Some(w) = self.restart_window {
2431 /// … }` zero-floor + canonical-form + upper-cap bracket arm — one
2432 /// open-coded field-access that expressed no compile-time link back to
2433 /// the typed slot. A future extension of the `:restart-window` axis to
2434 /// a richer author surface (a per-cluster restart-window override the
2435 /// operator pins through a future `:supervisor :restart-window-overrides`
2436 /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
2437 /// acknowledges, a per-tenant restart-window-alias table the M4 CR
2438 /// materializer resolves per-CR, a per-supervisor dynamic
2439 /// restart-window derivation the future adaptive-supervision engine
2440 /// computes from child-failure-history topology, a promotion of the
2441 /// plain `Option<Duration>` window to a richer `{observation, cooldown}`
2442 /// pair once Erlang/OTP's per-child-cohort observation-interval-
2443 /// partition slot comes into scope) would have had to be threaded
2444 /// through every open-coded copy in lockstep or the validate gate and
2445 /// the future M4 emit path would silently disagree on which
2446 /// restart-window a given supervisor resolves to — an author's
2447 /// `:restart-window "60s"` would satisfy validate while the emit path
2448 /// silently read a drifted other value (a `Some(Duration::from_secs(60))`
2449 /// authored slot at the emit boundary would carry the author's
2450 /// declared window verbatim in `feira lint` output while the future
2451 /// wasm-operator's restart-intensity counter operated under a
2452 /// drifted window, or vice versa: an author's `:restart-window ()`
2453 /// would carry the "never reset" sentinel through validate while the
2454 /// emit path silently substituted a default sliding window), a
2455 /// two-consumer split at the validator far from the source
2456 /// `caixa.lisp` with no field naming the restart-window-drift root
2457 /// cause. Lifting the resolution rule to a typed method on the
2458 /// substrate primitive means every downstream consumer of the
2459 /// Supervisor's per-`:supervisor` restart-intensity-denominator
2460 /// surface reaches for exactly one typed dispatch — the resolver's
2461 /// accept-set migrates as a unit on any future axis addition.
2462 ///
2463 /// Third `Copy`-return accessor on the M2 supervisor-slot
2464 /// `SupervisorSpec` type, closing the last unlifted per-`:supervisor`
2465 /// scalar-value axis (`children: Vec<ChildSpec>` carries a `Vec`
2466 /// payload rather than a `Copy`-scalar, and the per-`:children`
2467 /// [`crate::ChildSpec::nome`] (57c61d0) /
2468 /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
2469 /// scalar accessors already close the per-element `String`-carry
2470 /// axes). Sibling to the peer M2 [`crate::LimitsSpec::wall_clock`]
2471 /// (8cb717b) `Option<Duration>` accessor on the `:limits` slot's
2472 /// per-outermost-call wall-clock-deadline axis and the peer M3
2473 /// [`crate::MeshPolicy::timeout`] (7073d0f) `Option<Duration>`
2474 /// accessor on the `:politicas` slot's per-call-deadline axis — all
2475 /// three share the shared substrate concept "a `Copy`-projected
2476 /// optional `Duration` that carries a positive integer-millisecond
2477 /// canonical value with a `1ms..=<axis-specific>_MAX` accept-set and
2478 /// the paired zero-floor / non-canonical / above-cap refusal cascade"
2479 /// through the same [`crate::render::require_positive_canonical_bounded_duration`]
2480 /// bracket-helper the three axes each route through. Named
2481 /// `restart_window()` to match the storage field's name verbatim and
2482 /// the peer [`crate::LimitsSpec::wall_clock`] /
2483 /// [`crate::MeshPolicy::timeout`] method-name discipline; the
2484 /// accessor's identity maps onto the canonical OTP-shape supervision
2485 /// vocabulary the [`SupervisorSpec::restart_window`] field's docstring
2486 /// already carries.
2487 #[must_use]
2488 pub const fn restart_window(&self) -> Option<Duration> {
2489 self.restart_window
2490 }
2491
2492 /// Substrate-canonical per-`:supervisor` `:children` OTP-shaped
2493 /// static-child-list slice accessor every consumer that walks the
2494 /// supervisor's declared child set keys off — returns the author-
2495 /// declared `:supervisor :children` `Vec<ChildSpec>` verbatim as a
2496 /// `&[ChildSpec]` slice-view, borrowed from the typed slot's own
2497 /// `Vec<ChildSpec>` storage (a zero-copy slice-view over the same
2498 /// backing buffer the `Serialize`/`Deserialize` derives round-trip
2499 /// through). Non-optional: an empty slice is the load-bearing
2500 /// "author declared `:children ()`" sentinel every consumer of the
2501 /// cross-slot `SimpleOneForOne ↔ children.is_empty()` partition
2502 /// keys off (`SimpleOneForOne` requires the empty slice; the peer
2503 /// three strategies require a non-empty slice — the paired
2504 /// [`SupervisorError::SimpleOneForOneWithStaticChildren`] /
2505 /// [`SupervisorError::NoChildren`] refusal cascade pins the
2506 /// partition on both arms).
2507 ///
2508 /// The `:supervisor :children` slot carries the OTP-shaped static
2509 /// child list the supervisor materializes one ComputeUnit per
2510 /// entry from — the Erlang/OTP `supervisor:init/1`'s
2511 /// `{ok, {SupFlags, ChildSpecs}}` `ChildSpecs` list, projected
2512 /// through the tatara-lisp `:children` author surface onto a typed
2513 /// `Vec<ChildSpec>` whose per-element `(nome(),
2514 /// versao_requirement(), restart)` triple the per-child
2515 /// [`SupervisorSpec::validate`] loop already gates through the
2516 /// lifted [`ChildSpec::nome`] (57c61d0) /
2517 /// [`ChildSpec::versao_requirement`] (2c053c8) scalar accessors.
2518 /// Every downstream consumer that fans on the static child list
2519 /// keys off this slice (the [`SupervisorSpec::validate`]
2520 /// `SimpleOneForOne ↔ non-SimpleOneForOne` partition dispatch's
2521 /// `.is_empty()` probe on both arms, the [`SupervisorSpec::validate`]
2522 /// per-child DNS-1123 / semver-requirement / duplicate-detection
2523 /// fan-out loop, every future wasm-operator (M3) per-supervisor
2524 /// hierarchical-reconciliation scheduler's per-child ComputeUnit
2525 /// materialization loop, the future M4
2526 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2527 /// admission-webhook fan-out, the future `feira app graph`
2528 /// per-supervisor tree-print traversal).
2529 ///
2530 /// Prior to this lift the `.children` `Vec<ChildSpec>` was accessed
2531 /// inline at three production sites in `caixa-core/src/supervisor.rs`
2532 /// — the [`SupervisorSpec::validate`] `SimpleOneForOne`-arm
2533 /// `!self.children.is_empty()` cross-slot refusal probe, the peer
2534 /// non-`SimpleOneForOne`-arm `self.children.is_empty()`
2535 /// [`SupervisorError::NoChildren`] refusal probe, and the per-child
2536 /// validate loop's `for child in &self.children` traversal head —
2537 /// three open-coded field-accesses that expressed no compile-time
2538 /// link back to the typed slot. A future extension of the
2539 /// `:supervisor :children` axis to a richer author surface (a
2540 /// per-cluster child-set overlay the operator pins through a future
2541 /// `:supervisor :children-overrides` slot the MESH-COMPOSITION §III.2
2542 /// supervision-canary roadmap acknowledges, a per-tenant
2543 /// child-set-alias table the M4 CR materializer resolves per-CR,
2544 /// a per-supervisor dynamic-child derivation the future adaptive-
2545 /// supervision engine computes from child-failure-history topology,
2546 /// a promotion of the plain `Vec<ChildSpec>` to a richer
2547 /// `{static, dynamic}` partition once Erlang/OTP's
2548 /// `simple_one_for_one` dynamic-child slot comes into typed scope)
2549 /// would have had to be threaded through all three open-coded copies
2550 /// in lockstep or one consumer would silently disagree with the
2551 /// peers on which child-set a given supervisor resolves to — the
2552 /// `SimpleOneForOne`-arm probe reading the raw slot while the peer
2553 /// non-`SimpleOneForOne`-arm probe read an operator-resolved slot
2554 /// would silently split the partition-dispatch's two-arm coherence
2555 /// (a supervisor that satisfies neither arm's precondition, or that
2556 /// satisfies both, at the cost of the paired
2557 /// `SimpleOneForOneWithStaticChildren`/`NoChildren` refusal cascade
2558 /// silently drifting from the per-child validate loop's actual
2559 /// traversal input), a three-consumer split at the validator far
2560 /// from the source `caixa.lisp` with no field naming the
2561 /// child-set-drift root cause. Lifting the resolution rule to a
2562 /// typed method on the substrate primitive means every downstream
2563 /// consumer of the Supervisor's per-`:supervisor` static-child-list
2564 /// surface reaches for exactly one typed dispatch — the resolver's
2565 /// accept-set migrates as a unit on any future axis addition.
2566 ///
2567 /// First slice-return (`&[T]`) accessor on any M2 or M3 typed slot
2568 /// — the seed for the same "one typed dispatch on the substrate
2569 /// primitive, thin projections at each consumer" discipline the
2570 /// closed [`crate::LimitsSpec`] / [`BehaviorSpec`] /
2571 /// [`crate::UpgradeFromEntry`] scalar-accessor families each carry
2572 /// on their `Copy` / `Option<Copy>` / `Option<&str>` axes, extended
2573 /// onto the first `Vec`-carry axis on the substrate. The four peer
2574 /// `Vec`-carry axes still unlifted at the time of this seed —
2575 /// [`crate::Placement::clusters`] (`Vec<String>` per-cluster
2576 /// distribution-target list), [`crate::AplicacaoSpec::membros`]
2577 /// (`Vec<Membro>` per-Aplicacao member list),
2578 /// [`crate::AplicacaoSpec::contratos`] (`Vec<WitContract>`
2579 /// per-Aplicacao WIT-typed edge list),
2580 /// [`crate::UpgradeFromEntry::instructions`]
2581 /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
2582 /// — inherit this accessor's discipline as future compounding runs
2583 /// migrate their consumers onto the shared slice-return shape.
2584 /// Fourth (and final) accessor on the M2 supervisor-slot
2585 /// `SupervisorSpec` type, sibling to the three `Copy`-return
2586 /// [`SupervisorSpec::estrategia`] (eafb619) /
2587 /// [`SupervisorSpec::max_restarts`] (7844f4e) /
2588 /// [`SupervisorSpec::restart_window`] (7e7b32f) accessors — closes
2589 /// the last unlifted per-`:supervisor` field axis (the
2590 /// `Vec<ChildSpec>` static-child-list carrier) so every downstream
2591 /// per-`:supervisor` reader now routes through a typed dispatch on
2592 /// the substrate primitive. Named `children()` to match the storage
2593 /// field's name verbatim and the tatara-lisp author-surface term
2594 /// (`:children`) the field's own docstring already carries; the
2595 /// accessor's identity maps onto the canonical OTP-shape
2596 /// supervision vocabulary the [`SupervisorSpec::children`] field's
2597 /// docstring already reaches for ("Static children ..."). Returns
2598 /// `&[ChildSpec]` (not `&Vec<ChildSpec>`) because every downstream
2599 /// consumer of the child list treats it as a read-only sequence —
2600 /// the slice-view is the narrowest borrow that supports every
2601 /// present + roadmapped consumer (`.is_empty()`, `.iter()`,
2602 /// index, `.len()`) without leaking the backing `Vec`'s
2603 /// grow/push/reserve surface that no consumer of the typed view
2604 /// reaches for (the storage-side `Vec` remains reachable through
2605 /// the `pub children` field for the mutation-carrying
2606 /// `Caixa::supervisor_view` fold-in path in
2607 /// `manifest.rs:supervisor_view`).
2608 #[must_use]
2609 pub const fn children(&self) -> &[ChildSpec] {
2610 self.children.as_slice()
2611 }
2612
2613 /// Validate the supervisor's typed shape — strategy ↔ children
2614 /// invariants, max_restarts > 0, restart_window > 0 when set,
2615 /// per-child non-empty + duplicate-free names.
2616 ///
2617 /// Mirrors the value-shape discipline applied to every other
2618 /// typed slot:
2619 ///
2620 /// - `Some(Duration::ZERO)` on a Duration-bearing axis is the
2621 /// same "0 means the opposite of what you think" footgun
2622 /// closed for `:politicas :timeout` (Envoy interprets a zero
2623 /// timeout as `infinite`), `:politicas :circuit-breaker
2624 /// :window`, and `:limits :wall-clock`. The
2625 /// `MaxIntensity / Period` ratio in Erlang/OTP's
2626 /// `supervisor` requires `Period > 0`; a zero period either
2627 /// trips on the first failure or never trips depending on
2628 /// operator interpretation, neither of which is the
2629 /// author's intent. Omit `:restart-window` to express "no
2630 /// reset"; carry a positive duration to express the window.
2631 /// - duplicate `:children` `:caixa` names are the same
2632 /// graph-node-set / multiset distinction closed for
2633 /// `:membros` (4bb3f3d), `:placement :clusters` (c7c7799),
2634 /// and `:entrada :paths` (eb3456d). Two children with the
2635 /// same `:caixa` materialize as two ComputeUnits with the
2636 /// same name in the cluster's HelmRelease values, one
2637 /// silently overwriting the other. Erlang/OTP's
2638 /// `child_spec.id` is required-unique per supervisor;
2639 /// pleme-io enforces the same set-not-multiset shape on
2640 /// `:caixa` (the load-bearing identity in our renderer).
2641 pub fn validate(&self) -> Result<(), SupervisorError> {
2642 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition
2643 // dispatch and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
2644 // error carrier's `estrategia:` field through the lifted
2645 // [`SupervisorSpec::estrategia`] accessor rather than the raw
2646 // `self.estrategia` field access — the two production consumers
2647 // of the per-`:supervisor` sibling-restart-strategy scalar now
2648 // key off exactly one typed dispatch on the substrate primitive,
2649 // so any future rebrand on the axis (a per-cluster strategy
2650 // override the operator pins through a future `:supervisor
2651 // :estrategia-overrides` slot, a per-tenant strategy-alias table
2652 // the M4 CR materializer resolves per-CR) migrates as a single
2653 // caixa-core edit rather than a coordinated rewrite of the two
2654 // call sites — sibling of the peer M3 [`crate::Placement::estrategia`]
2655 // (921fe1b) four-consumer migration on the per-`:placement`
2656 // distribution-strategy axis.
2657 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition-
2658 // dispatch's paired `.is_empty()` cross-slot refusal probes
2659 // (the `SimpleOneForOne`-arm
2660 // [`SupervisorError::SimpleOneForOneWithStaticChildren`] refusal
2661 // and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
2662 // refusal) through the lifted [`SupervisorSpec::children`]
2663 // slice-return accessor rather than the raw `self.children`
2664 // field access — the two paired production consumers of the
2665 // per-`:supervisor` static-child-list scalar-shape now key off
2666 // exactly one typed dispatch on the substrate primitive, so any
2667 // future rebrand on the axis (a per-cluster child-set overlay
2668 // the operator pins through a future `:supervisor
2669 // :children-overrides` slot, a per-tenant child-set-alias table
2670 // the M4 CR materializer resolves per-CR) migrates as a single
2671 // caixa-core edit rather than a coordinated rewrite of the
2672 // paired arms — first slice-return migration on any typed slot,
2673 // seed for the peer per-`:placement :clusters`,
2674 // per-`:membros`, per-`:contratos`, and per-`:upgrade-from
2675 // :instructions` `Vec`-carry axes.
2676 match self.estrategia() {
2677 RestartStrategy::SimpleOneForOne => {
2678 // SimpleOneForOne: children added at runtime. Static
2679 // list must be empty (one shape declared elsewhere).
2680 if !self.children().is_empty() {
2681 return Err(SupervisorError::SimpleOneForOneWithStaticChildren);
2682 }
2683 }
2684 _ => {
2685 if self.children().is_empty() {
2686 return Err(SupervisorError::no_children(self.estrategia()));
2687 }
2688 }
2689 }
2690 // Zero-floor + upper-cap bracket on the typed `:max-restarts`
2691 // axis. See [`crate::render::require_positive_bounded_u32`] for
2692 // the ordering discipline (zero-floor arm strictly precedes cap
2693 // arm so `0` surfaces the self-locating `ZeroMaxRestarts`
2694 // diagnostic with its counter-axis remediation directly named,
2695 // not the misleading `0 > SUPERVISOR_MAX_RESTARTS_MAX == false`
2696 // cap-arm miss). Until this bracket landed the top edge ran all
2697 // the way to `u32::MAX` and a struct-literal
2698 // `SupervisorSpec { max_restarts: 100_000, .. }` (or the
2699 // equivalent author-surface `:max-restarts 100000` /
2700 // `:max-restarts 4294967295` typo landing in the slot) silently
2701 // passed validate. The runtime substrate consuming the value
2702 // (Erlang/OTP's `MaxIntensity / Period` ratio, the future
2703 // wasm-operator's per-supervisor restart-intensity counter, the
2704 // M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2705 // admission webhook) then turned a typed `:max-restarts`
2706 // policy into a no-op supervisor: the escalation threshold is
2707 // structurally so high that no realistic
2708 // restarts-per-`:restart-window` traffic shape can reach it,
2709 // the supervisor never escalates to its parent, and a bad
2710 // child can loop inside the window indefinitely with the
2711 // parent supervisor structurally never receiving the "this
2712 // subtree has exceeded its restart budget" signal the typed
2713 // slot is meant to express. The bracket set is
2714 // `1..=SUPERVISOR_MAX_RESTARTS_MAX`, peer with the
2715 // [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap on
2716 // the sibling `:politicas :circuit-breaker :max-failures` axis:
2717 // both are "trip the next-higher protection layer after N
2718 // events in a rolling window" counters with identical
2719 // degenerate-at-the-high-end shape and now share one canonical
2720 // bracket helper. The bracket precedes the sibling
2721 // `:restart-window` zero-floor / canonical-millisecond arms so
2722 // an over-cap `max_restarts` paired with a structurally invalid
2723 // window surfaces the bracket diagnostic first, mirroring the
2724 // `PolicyBreakerMaxFailuresExceedsCap` / window-axis cross-arm
2725 // ordering on the peer `:politicas :circuit-breaker` slot.
2726 // Route the [`SupervisorSpec::validate`] `:max-restarts` zero-floor +
2727 // upper-cap bracket-gate through the lifted [`SupervisorSpec::max_restarts`]
2728 // accessor rather than the raw `self.max_restarts` field access —
2729 // the one production consumer of the per-`:supervisor`
2730 // restart-budget-count scalar now keys off exactly one typed
2731 // dispatch on the substrate primitive, so any future rebrand on
2732 // the axis (a per-cluster restart-budget override the operator
2733 // pins through a future `:supervisor :max-restarts-overrides`
2734 // slot, a per-tenant restart-budget-alias table the M4 CR
2735 // materializer resolves per-CR) migrates as a single caixa-core
2736 // edit rather than a coordinated rewrite — sibling of the peer M3
2737 // [`crate::CircuitBreaker::max_failures`] (3a74062) migration on
2738 // the per-`:politicas :circuit-breaker :max-failures` axis.
2739 crate::render::require_positive_bounded_u32(
2740 self.max_restarts(),
2741 SUPERVISOR_MAX_RESTARTS_MAX,
2742 || SupervisorError::ZeroMaxRestarts,
2743 SupervisorError::max_restarts_exceeds_cap,
2744 )?;
2745 // Route the [`SupervisorSpec::validate`] `:restart-window`
2746 // zero-floor + integer-millisecond canonical-form + upper-cap
2747 // bracket-gate through the lifted [`SupervisorSpec::restart_window`]
2748 // accessor rather than the raw `self.restart_window` field access —
2749 // the one production consumer of the per-`:supervisor`
2750 // restart-intensity-denominator scalar now keys off exactly one
2751 // typed dispatch on the substrate primitive, so any future rebrand
2752 // on the axis (a per-cluster restart-window override the operator
2753 // pins through a future `:supervisor :restart-window-overrides`
2754 // slot, a per-tenant restart-window-alias table the M4 CR
2755 // materializer resolves per-CR) migrates as a single caixa-core
2756 // edit rather than a coordinated rewrite — sibling of the peer M2
2757 // [`crate::LimitsSpec::wall_clock`] (8cb717b) validate-arm-route
2758 // on the per-`:limits :wall-clock` axis and the peer M3
2759 // [`crate::MeshPolicy::timeout`] (7073d0f) accessor-route on the
2760 // per-`:politicas :timeout` axis.
2761 if let Some(w) = self.restart_window() {
2762 // Zero-floor + integer-millisecond canonical-form +
2763 // upper-cap bracket on the typed `:restart-window` axis.
2764 // See
2765 // [`crate::render::require_positive_canonical_bounded_duration`]
2766 // for the full three-arm ordering discipline (zero-floor
2767 // strictly precedes canonical-form so `Duration::ZERO`
2768 // surfaces the self-locating `RestartWindowZero`
2769 // diagnostic; canonical-form strictly precedes the cap arm
2770 // so a sub-millisecond above-cap value surfaces the more
2771 // fundamental round-trip-shape diagnostic first) and the
2772 // three peer typed-`Duration` sites that share this
2773 // canonical bracket ([`crate::MeshPolicy::timeout`],
2774 // [`crate::CircuitBreaker::window`],
2775 // [`crate::LimitsSpec::wall_clock`]). Every validated
2776 // value lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
2777 // (1ms..=1h), integer-millisecond granularity.
2778 crate::render::require_positive_canonical_bounded_duration(
2779 w,
2780 SUPERVISOR_RESTART_WINDOW_MAX,
2781 || SupervisorError::RestartWindowZero,
2782 SupervisorError::restart_window_not_canonical,
2783 SupervisorError::restart_window_exceeds_cap,
2784 )?;
2785 }
2786 // Route the per-child DNS-1123 / semver-requirement / duplicate-
2787 // detection fan-out loop through the lifted named per-slot gate
2788 // [`SupervisorSpec::validate_children`] rather than an inline
2789 // three-per-child cascade — every future consumer that wants to
2790 // re-check only the `:children` slot's per-entry axes (the M4
2791 // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2792 // admission webhook re-validating one added/renamed child, the
2793 // future wasm-operator's per-child dynamic-add re-validator on
2794 // the `SimpleOneForOne` runtime-add path once dynamic-children
2795 // graduate to a typed slot, a future partial re-validator on a
2796 // per-`:children`-entry patch) reaches every per-entry axis
2797 // through one dispatch rather than re-inlining the three-arm
2798 // cascade in lockstep with `validate` or paying the peer
2799 // `:estrategia`/`:max-restarts`/`:restart-window` gates to
2800 // reach one entry check. Sibling of the peer M3 mesh-slot
2801 // per-slot gate family (`validate_membros` — the exact peer on
2802 // the M3 side, [`crate::AplicacaoSpec::validate_membros`];
2803 // `validate_contratos` — 906a5c6; `validate_entrada` — 20cd523;
2804 // `validate_placement`; `validate_politicas` routing through
2805 // `MeshPolicy::validate` — f03a154) — the M2 supervisor-slot
2806 // per-slot gate discipline now spans both the M3 mesh-slot
2807 // family and the M2 `:children` per-child-cascade axis on one
2808 // shape: one named per-slot gate per typed per-entry loop.
2809 self.validate_children()?;
2810 Ok(())
2811 }
2812
2813 /// Named per-slot gate on the M2 `:supervisor :children` per-entry
2814 /// axis — folds the per-child DNS-1123 name gate, semver-requirement
2815 /// gate, and duplicate-`:caixa` dedup arm into one call every
2816 /// consumer that wants to re-validate one `:children` entry (or the
2817 /// whole list) against the same accept-set [`SupervisorSpec::validate`]
2818 /// admits reaches through.
2819 ///
2820 /// Peer of the M3 mesh-slot [`crate::AplicacaoSpec::validate_membros`]
2821 /// per-slot gate on the analogous per-entry axis (`:membros`) — same
2822 /// three-per-entry shape (DNS-1123 name + semver-requirement +
2823 /// duplicate-`:caixa` dedup), lifted to one named substrate
2824 /// primitive per slot. The M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
2825 /// materializer's admission webhook re-checking one added or renamed
2826 /// child, the future wasm-operator's per-child dynamic-add
2827 /// re-validator on the `SimpleOneForOne` runtime-add path once
2828 /// dynamic-children graduate to a typed slot, a future partial
2829 /// re-validator on a per-`:children`-entry patch — each reaches the
2830 /// three per-entry axes through this one dispatch rather than
2831 /// re-inlining the three-arm cascade in lockstep with `validate`
2832 /// (the duplication the PRIME DIRECTIVE names as a bug) or paying
2833 /// the peer `:estrategia`/`:max-restarts`/`:restart-window` gates to
2834 /// reach one entry check.
2835 ///
2836 /// Self-contained on `&self` — resolves its own dedup `HashSet`
2837 /// through [`SupervisorSpec::children`] rather than borrowing one
2838 /// threaded down from `validate`, the same posture the peer M3
2839 /// mesh-slot per-slot gates ([`crate::AplicacaoSpec::validate_membros`],
2840 /// [`crate::AplicacaoSpec::validate_contratos`],
2841 /// [`crate::AplicacaoSpec::validate_entrada`],
2842 /// [`crate::AplicacaoSpec::validate_placement`]) each carry, so a
2843 /// consumer that reaches this gate directly (without first calling
2844 /// `validate`) still runs the full per-child cascade — pinned by
2845 /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
2846 /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
2847 /// + `validate_children_is_self_contained_on_children_slot`.
2848 ///
2849 /// The three per-entry arms run in the same canonical order the
2850 /// pre-lift inline cascade encoded (DNS-1123 → semver → dedup), so
2851 /// the diagnostic every author-declared per-`:children` entry surfaces
2852 /// through `validate` is byte-equal to the diagnostic this gate
2853 /// surfaces when called directly — the equivalence-pin pair
2854 /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
2855 /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
2856 /// asserts the two altitudes discriminate the same set on every
2857 /// per-entry-covered input.
2858 pub fn validate_children(&self) -> Result<(), SupervisorError> {
2859 let mut seen = std::collections::HashSet::new();
2860 for child in self.children() {
2861 // Every emitted cluster artifact's `metadata.name` for a
2862 // supervised child derives from this `:children :caixa` value
2863 // verbatim — the rendered `wasm.pleme.io/v1alpha1/ComputeUnit
2864 // .metadata.name` per child, the [`crate::LABEL_PROGRAM`]
2865 // label value on every child's pod identity, and the per-
2866 // child K8s [`Service`][svc] `metadata.name` the future
2867 // wasm-operator (M3) provisions for inter-child supervision
2868 // tree wiring. Each apiserver-side schema on each landing
2869 // site enforces the DNS-1123 label rule on admission; a
2870 // structurally invalid child name (`"Worker"`, `"my_worker"`,
2871 // `"team.worker"`, `"-worker"`, `"worker-"`, the >63-byte
2872 // UUID-shaped mistaken-identity slug) silently passes the
2873 // prior empty-/duplicate-only gate and the failure surfaces
2874 // at `kubectl apply` time as a `metadata.name: Invalid value`
2875 // rejection, far from the source caixa.lisp, with no field
2876 // naming the offending `:children` entry. Lifting the gate
2877 // to caixa-build time mirrors the `:membros :caixa` value-
2878 // shape trajectory (3f9d7a0) and the `:placement :clusters`
2879 // trajectory (6cbb900) onto the third DNS-1123-label-shaped
2880 // identifier axis — the supervisor tree's child names —
2881 // through the lifted
2882 // [`crate::render::require_valid_dns_1123_label`] gate the
2883 // seven peer name axes (`:membros :caixa`, `:placement
2884 // :clusters`, `:placement :affinity`, `:contratos :de`/`:para`,
2885 // `:entrada :para`, `:nome`, `:upgrade-from :module`) each
2886 // route through, so drift between the eight axes' accepted
2887 // DNS-1123-label sets is structurally impossible.
2888 //
2889 // [svc]: https://kubernetes.io/docs/concepts/services-networking/service/
2890 crate::render::require_valid_dns_1123_label(
2891 child.nome(),
2892 || SupervisorError::EmptyChildName,
2893 |reason| SupervisorError::child_caixa_invalid(child.nome(), reason),
2894 )?;
2895 // The author surface for `:children :versao` is the same
2896 // Cargo-shaped semver requirement string `:deps :versao` and
2897 // `:membros :versao` carry — and the lacre pipeline resolves
2898 // all three axes through the same
2899 // [`crate::version::parse_requirement`] entry-point. The
2900 // shared [`crate::render::require_valid_versao_requirement`]
2901 // helper brackets the empty-first + parse cascade both peer
2902 // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
2903 // [`crate::AplicacaoSpec::validate_membros`] on `:membros
2904 // :versao`) route through, so drift between the three axes'
2905 // accepted requirement sets is structurally impossible and
2906 // the parse-side no-op the empty-first arm closes (semver's
2907 // empty parse yields an implicit `*`) lives in exactly one
2908 // predicate. Every `ChildSpec::versao` past validate is
2909 // round-trippable through [`crate::parse_requirement`]
2910 // without re-checking at the resolver layer, and the three
2911 // `:versao` typed surfaces (`:deps`, `:membros`, `:children`)
2912 // are now structurally equivalent by construction.
2913 crate::render::require_valid_versao_requirement(
2914 child.versao_requirement(),
2915 || SupervisorError::empty_child_version(child.nome()),
2916 |reason| {
2917 SupervisorError::child_versao_invalid(
2918 child.nome(),
2919 child.versao_requirement(),
2920 reason,
2921 )
2922 },
2923 )?;
2924 crate::render::insert_first_seen(&mut seen, child.nome(), || {
2925 SupervisorError::duplicate_child_caixa(child.nome())
2926 })?;
2927 }
2928 Ok(())
2929 }
2930}
2931
2932/// Cross-slot coherence gate on the supervision tree: no
2933/// `:children :caixa` entry may name the supervisor's own `:nome`.
2934///
2935/// A supervisor that lists itself as a child is a degenerate self-parent
2936/// — the supervision tree is a DAG rooted at the supervisor (OTP child
2937/// specs reference *distinct* child processes; a supervisor is never its
2938/// own child), and the wasm-operator's hierarchical reconciliation would
2939/// otherwise be handed a node that is its own parent: a one-node cycle it
2940/// either rejects far from the source `caixa.lisp` or recurses on. Because
2941/// every `:nome` is a globally-unique substrate identity (DNS-1123 label +
2942/// lacre closure root), a child whose `:caixa` equals the supervisor's
2943/// `:nome` *is* the supervisor itself, not a coincidentally-named peer.
2944///
2945/// Lives outside [`SupervisorSpec::validate`] because the typed view
2946/// carries the children but not the parent `:nome`; mirrors the
2947/// cross-slot precedence gate `validate_upgrade_from_against_versao`
2948/// (which likewise reads one slot against another at the
2949/// [`crate::layout`] wire-up site) and the mesh self-edge gate
2950/// `AplicacaoSpec`'s `ContratoSelfLoop` — the same "an edge from a graph
2951/// node to itself is structurally not a tree/mesh edge" discipline, here
2952/// on the supervision-tree axis.
2953pub fn validate_no_self_supervision(
2954 children: &[ChildSpec],
2955 parent_nome: &str,
2956) -> Result<(), SupervisorError> {
2957 for child in children {
2958 if child.nome() == parent_nome {
2959 return Err(SupervisorError::child_supervises_self(parent_nome));
2960 }
2961 }
2962 Ok(())
2963}
2964
2965#[derive(Debug, Error, PartialEq, Eq)]
2966pub enum SupervisorError {
2967 #[error("supervisor :estrategia {estrategia:?} requires at least one :children entry")]
2968 NoChildren { estrategia: RestartStrategy },
2969 #[error(
2970 "SimpleOneForOne supervisors must declare zero static children (children spawn dynamically)"
2971 )]
2972 SimpleOneForOneWithStaticChildren,
2973 #[error(":max-restarts must be > 0")]
2974 ZeroMaxRestarts,
2975 #[error(
2976 ":supervisor :max-restarts ({max_restarts}) exceeds the supervisor-policy ceiling \
2977 (SUPERVISOR_MAX_RESTARTS_MAX = 1000) — a value above this cap turns the typed \
2978 restart-intensity policy into a no-op supervisor: the escalation threshold is \
2979 structurally so high that no realistic restarts-per-:restart-window traffic shape \
2980 can reach it, so the supervisor never escalates to its parent and a bad child can \
2981 loop inside the window indefinitely. Every typed-slot consumer (Erlang/OTP's \
2982 MaxIntensity/Period ratio, the future wasm-operator's per-supervisor \
2983 restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
2984 materializer's admission webhook) emits a `:max-restarts` declaration that is \
2985 structurally never reached. Pin a value in 1..=1000 (Erlang/OTP / Elixir / Riak \
2986 Core / RabbitMQ production playbooks recommend 3..=100; the OTP `supervisor` \
2987 callback module's `MaxR = 1` minimal-restart default sits at the bottom of the \
2988 band) or restructure the supervision tree (split the flaky child into its own \
2989 sub-supervisor with a tighter budget) if you need a higher restart tolerance."
2990 )]
2991 MaxRestartsExceedsCap { max_restarts: u32 },
2992 #[error(
2993 ":restart-window must be > 0 when set — Erlang/OTP's MaxIntensity/Period \
2994 requires Period > 0; a zero window either trips on the first failure or \
2995 never trips depending on operator interpretation. Omit :restart-window to \
2996 express `never reset`; carry a positive duration to express the window."
2997 )]
2998 RestartWindowZero,
2999 #[error(
3000 ":supervisor :restart-window ({window:?}) carries a sub-millisecond residue the shared `duration_codec` cannot round-trip — \
3001 the codec truncates to `as_millis()` before picking the canonical unit, so a value with `subsec_nanos() % 1_000_000 != 0` either \
3002 truncates on first serialize (e.g. `Duration::from_micros(1500)` → \"1ms\" → `Duration::from_millis(1)` ≠ original) or renders \
3003 as \"0s\" the `RestartWindowZero` arm then rejects on re-validate. Pin an integer-millisecond magnitude in the canonical authoring form \
3004 (`<integer><unit>` for unit ∈ {{ms, s, m, h}}, e.g. `\"500ms\"`, `\"30s\"`, `\"2m\"`, `\"1h\"`) or omit the field for `never reset`"
3005 )]
3006 RestartWindowNotCanonical { window: Duration },
3007 #[error(
3008 ":supervisor :restart-window ({window:?}) exceeds the supervisor-policy ceiling \
3009 (SUPERVISOR_RESTART_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
3010 per-supervisor rolling-window restart-intensity counter into a lifetime counter: the \
3011 failure-counting window is structurally so long that transient restarts are never \
3012 forgotten, the MaxIntensity/Period ratio degenerates from `trip the parent supervisor \
3013 when the child has exceeded its restart budget within the recent window` to `trip the \
3014 parent when the child has exceeded its restart budget over its lifetime`, and the \
3015 supervisor's reset semantic never reaches the child — every typed-slot consumer \
3016 (Erlang/OTP's MaxIntensity/Period reconciler, the future wasm-operator's \
3017 per-supervisor restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
3018 materializer's admission webhook, the caixa-operator's hierarchical reconciliation \
3019 scheduler) emits a `:restart-window` declaration that is structurally a no-op rolling \
3020 window. Pin a value in 1ms..=1h (Learn You Some Erlang's `{{intensity, 5, 60}}` \
3021 worker-supervisor `Period = 60s` default, Elixir's `Supervisor` `max_seconds: 5` \
3022 default, OTP's `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's \
3023 `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default — every Erlang/OTP \
3024 / Elixir production playbook sits in the 5s..=300s band; the longest documented \
3025 per-supervisor restart-window any pleme-io substrate playbook recommends maxes at \
3026 ~30m) or omit :restart-window to express `never reset` (the supervisor's restart \
3027 budget then becomes a strict lifetime counter by design, not a degenerate one — the \
3028 author surfaces the lifetime-counter semantic explicitly at the slot, rather than \
3029 hiding it behind a rolling-window declaration the cap arm rejects)"
3030 )]
3031 RestartWindowExceedsCap { window: Duration },
3032 #[error("child entry has empty :caixa name")]
3033 EmptyChildName,
3034 #[error(
3035 "child :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
3036 (the K8s apiserver enforces this rule on every `metadata.name` / Service \
3037 name / label value the child name lands in — the per-child \
3038 `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name`, the `LABEL_PROGRAM` \
3039 label value, and the future wasm-operator per-child Service `metadata.name` \
3040 — each apiserver-side schema rejects names that don't match; use a \
3041 lowercase alphanumeric + hyphen identifier like `\"worker\"` or `\"cache-v2\"`)"
3042 )]
3043 ChildCaixaInvalid { caixa: String, reason: String },
3044 #[error("child {caixa:?} has empty :versao constraint")]
3045 EmptyChildVersion { caixa: String },
3046 #[error(
3047 "child {caixa:?} :versao {versao:?} is not a valid semver requirement: \
3048 {reason} (use Cargo-shaped forms like `\"^0.1\"`, `\"~0.1.2\"`, \
3049 `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` and \
3050 `:membros :versao` carry; the lacre pipeline resolves all three \
3051 through the same parser)"
3052 )]
3053 ChildVersaoInvalid {
3054 caixa: String,
3055 versao: String,
3056 reason: String,
3057 },
3058 #[error(
3059 "child {caixa:?} appears more than once (Erlang/OTP requires unique \
3060 child_spec.id per supervisor; duplicate children materialize as duplicate \
3061 ComputeUnits in the rendered chart, one silently overwriting the other)"
3062 )]
3063 DuplicateChildCaixa { caixa: String },
3064 #[error(
3065 "supervisor {caixa:?} lists itself as a :children entry — a supervisor is \
3066 never its own child (the supervision tree is a DAG rooted at the supervisor; \
3067 OTP child specs reference distinct child processes). Since every :nome is a \
3068 globally-unique substrate identity, a child naming the supervisor's own :nome \
3069 is a one-node reconciliation cycle, not a coincidentally-named peer; drop the \
3070 self-referential :children entry or rename it to the actual child caixa."
3071 )]
3072 ChildSupervisesSelf { caixa: String },
3073}
3074
3075// Fold the three `SupervisorError::<Variant> { caixa: <&str>.to_string() }`
3076// caixa-only struct-variant wire-up sites at [`SupervisorSpec::validate_children`]
3077// and [`validate_no_self_supervision`] onto one substrate primitive per
3078// typed variant — the sibling on `SupervisorError` of the four uniform-shape
3079// `LayoutError`-envelope constructor families the peer
3080// [`crate::layout::layout_violation_ctors!`] macro closed (131ca0d, 16
3081// variants on `{ caixa, issue }`), the [`crate::layout::layout_slot_kind_ctors!`]
3082// macro closed (0419438, 4 variants on `{ caixa, kind, slots }`), the
3083// [`crate::LayoutError::missing_entry`] one-variant ctor closed (1b09f9d,
3084// on `{ kind, path }`), and the [`crate::layout::layout_nome_only_ctors!`]
3085// macro closed (3fe3dd7, 6 variants on `<Variant>(String)`), plus the
3086// [`crate::AplicacaoError::entrada_host_invalid`] one-variant ctor
3087// (17dd504, `{ host, reason }`), the [`crate::aplicacao::contrato_target_ctors!`]
3088// macro (14b81d5, 2 variants on `{ de, para, wit, expected }`), and the
3089// [`crate::aplicacao::contrato_empty_pair_ctors!`] macro (8580068, 4
3090// variants on `{ de, para }`) already at that discipline on the peer
3091// `AplicacaoError` envelopes.
3092//
3093// Each of the three wire-up sites on this shape (`EmptyChildVersion` at
3094// the per-`:children` semver-requirement empty-first arm, `DuplicateChildCaixa`
3095// at the per-`:children` dedup arm, `ChildSupervisesSelf` at the cross-slot
3096// self-supervision arm) opened the identical
3097// `SupervisorError::<Variant> { caixa: <&str>.to_string() }` struct-literal —
3098// the exact "same block re-inlined at every consumer" shape the PRIME
3099// DIRECTIVE names as a bug, on the same altitude the peer `LayoutError` /
3100// `AplicacaoError` families each closed on their sibling envelopes. The
3101// three variants share one `{ caixa: String }` shape, so the fold routes
3102// each wire-up site through one dispatch per typed variant.
3103//
3104// The macro below generates one static constructor per variant of shape
3105// `fn <slot>(caixa: &str) -> SupervisorError`, so every wire-up site
3106// collapses onto one dispatch:
3107// `SupervisorError::<slot>(<&str>)`, byte-equal to the pre-lift
3108// struct-literal on the same `&str` fixture. The uniform one-field
3109// construction (`caixa: caixa.to_string()`) is spelled once — inside the
3110// macro — rather than at every wire-up site. Every constructor is
3111// `#[must_use]` so a caller who mistakenly discards the constructed error
3112// trips a compile warning at the wire-up site.
3113//
3114// Every future consumer that wants to construct one of these three
3115// variants outside `SupervisorSpec::validate_children` /
3116// `validate_no_self_supervision` — a deferred
3117// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3118// webhook re-checking one added/renamed child, a future
3119// `feira validate --supervisor` per-caixa admission verb, a per-child
3120// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path
3121// once dynamic-children graduate to a typed slot, a per-Supervisor
3122// overlay resolver rejecting a duplicate/self-supervising child against
3123// a cluster-local snapshot — now reaches each variant through one call
3124// rather than re-inlining the three-line struct-literal in lockstep
3125// with the three in-crate wire-up sites.
3126macro_rules! supervisor_caixa_only_ctors {
3127 ($($ctor:ident => $variant:ident),* $(,)?) => {
3128 impl SupervisorError {
3129 $(
3130 #[doc = concat!(
3131 "Construct a [`SupervisorError::",
3132 stringify!($variant),
3133 "`] naming the offending `:children :caixa` (or ",
3134 "supervisor `:nome`, on the self-supervision arm). ",
3135 "Folds the uniform `Self::",
3136 stringify!($variant),
3137 " { caixa: caixa.to_string() }` one-field ",
3138 "struct-literal onto one substrate primitive so ",
3139 "every [`SupervisorSpec::validate_children`] / ",
3140 "[`validate_no_self_supervision`] wire-up on this ",
3141 "variant reads through one dispatch rather than the ",
3142 "pre-lift open-coded struct-literal block."
3143 )]
3144 #[must_use]
3145 pub fn $ctor(caixa: &str) -> Self {
3146 Self::$variant { caixa: caixa.to_string() }
3147 }
3148 )*
3149 }
3150 };
3151}
3152
3153supervisor_caixa_only_ctors! {
3154 empty_child_version => EmptyChildVersion,
3155 duplicate_child_caixa => DuplicateChildCaixa,
3156 child_supervises_self => ChildSupervisesSelf,
3157}
3158
3159// Fold the two `SupervisorError::{ChildCaixaInvalid, ChildVersaoInvalid}`
3160// struct-variant wire-up sites at [`SupervisorSpec::validate_children`] onto
3161// one substrate primitive per typed variant — the M2 supervisor-side siblings
3162// of the peer [`crate::AplicacaoError::membro_caixa_invalid`] two-slot ctor
3163// already lifted through the sibling
3164// [`crate::aplicacao::aplicacao_field_reason_ctors!`] macro (981060b) on the
3165// peer `AplicacaoError { caixa: String, reason: String }` envelope. The
3166// `ChildCaixaInvalid` variant carries the same `{ <name>: String, reason:
3167// String }` two-slot shape the peer seven-variant
3168// [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold closed on the
3169// `AplicacaoError` envelope (`MembroCaixaInvalid`, `EntradaParaInvalid`,
3170// `EntradaHostInvalid`, `EntradaPathInvalid`, `PlacementClusterInvalid`,
3171// `PlacementAffinityInvalid`, `ShardKeyInvalid`); the `ChildVersaoInvalid`
3172// variant carries the `{ caixa: String, versao: String, reason: String }`
3173// three-slot shape the sibling `AplicacaoError::MembroVersaoInvalid` axis
3174// carries on the same `:versao` value-shape.
3175//
3176// Each of the two wire-up sites opened the same closure-shaped
3177// `|reason| SupervisorError::<Variant> { caixa: child.nome().to_string(),
3178// [versao: child.versao_requirement().to_string(),] reason }` block inside
3179// the paired [`crate::render::require_valid_dns_1123_label`] and
3180// [`crate::render::require_valid_versao_requirement`] callbacks — the exact
3181// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE names
3182// as a bug, on the same altitude the peer `AplicacaoError` /
3183// `SupervisorError` / `LayoutError` / `DepError` / `LimitsError` ctor
3184// families already closed on their sibling envelopes.
3185//
3186// The two `#[must_use]` inherent constructors below fold each wire-up onto
3187// one dispatch: `SupervisorError::child_caixa_invalid(<name>, <reason>)`
3188// and `SupervisorError::child_versao_invalid(<name>, <versao>, <reason>)`,
3189// byte-equal to the pre-lift struct-literal on the same scalar fixtures.
3190// The uniform per-field `.to_string()` / `.into()` construction is spelled
3191// once — inside each ctor body — rather than at every wire-up site. The
3192// `reason: impl Into<String>` bound accepts both `&str` literals and
3193// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
3194// diagnostic shape at the lift, matching the peer
3195// [`aplicacao_field_reason_ctors!`] and
3196// [`crate::aplicacao::contrato_pair_value_reason_ctors!`] bounds on the
3197// sibling envelopes.
3198//
3199// Every future consumer that wants to construct one of these two variants
3200// outside `SupervisorSpec::validate_children` — a deferred
3201// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook
3202// re-checking one added/renamed child's `:caixa` or `:versao`, a future
3203// `feira validate --supervisor` per-caixa admission verb, a per-child
3204// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path once
3205// dynamic-children graduate to a typed slot, a per-Supervisor overlay
3206// resolver rejecting a shape-invalid child `:caixa`/`:versao` against a
3207// cluster-local snapshot — now reaches each variant through one call rather
3208// than re-inlining the per-shape struct-literal block in lockstep with the
3209// two in-crate wire-up sites.
3210impl SupervisorError {
3211 /// Construct a [`SupervisorError::ChildCaixaInvalid`] naming the
3212 /// offending `:children :caixa` value under the given `reason`. Folds
3213 /// the uniform `Self::ChildCaixaInvalid { caixa: caixa.to_string(),
3214 /// reason: reason.into() }` two-slot struct-literal onto one substrate
3215 /// primitive so every wire-up on this variant reads through one
3216 /// dispatch, matching the peer
3217 /// [`crate::AplicacaoError::membro_caixa_invalid`] ctor's shape on the
3218 /// sibling `AplicacaoError { caixa: String, reason: String }`
3219 /// envelope. `reason` accepts both `&str` literals and `format!(…)`
3220 /// outputs through the `impl Into<String>` bound.
3221 #[must_use]
3222 pub fn child_caixa_invalid(caixa: &str, reason: impl Into<String>) -> Self {
3223 Self::ChildCaixaInvalid {
3224 caixa: caixa.to_string(),
3225 reason: reason.into(),
3226 }
3227 }
3228
3229 /// Construct a [`SupervisorError::ChildVersaoInvalid`] naming the
3230 /// offending `:children :caixa` and its `:versao` requirement under
3231 /// the given `reason`. Folds the uniform `Self::ChildVersaoInvalid {
3232 /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
3233 /// reason.into() }` three-slot struct-literal onto one substrate
3234 /// primitive so every wire-up on this variant reads through one
3235 /// dispatch, matching the sibling `AplicacaoError::MembroVersaoInvalid
3236 /// { caixa, versao, reason }` three-slot axis on the peer
3237 /// `AplicacaoError` envelope. `reason` accepts both `&str` literals
3238 /// and `format!(…)` outputs through the `impl Into<String>` bound.
3239 #[must_use]
3240 pub fn child_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
3241 Self::ChildVersaoInvalid {
3242 caixa: caixa.to_string(),
3243 versao: versao.to_string(),
3244 reason: reason.into(),
3245 }
3246 }
3247}
3248
3249// Fold the four `SupervisorError::<Variant> { <field>: <Copy> }` one-field
3250// Copy-scalar struct-variant wire-up sites at [`SupervisorSpec::validate`]'s
3251// three bracket-arms — one struct-literal at the `:children`-empty
3252// non-`SimpleOneForOne` refusal cascade (`NoChildren { estrategia }`) plus
3253// three `impl FnOnce(<ty>) -> SupervisorError` bracket-closures at the
3254// [`crate::render::require_positive_bounded_u32`] `:max-restarts` cap arm
3255// (`MaxRestartsExceedsCap { max_restarts }`) and the paired
3256// [`crate::render::require_positive_canonical_bounded_duration`]
3257// `:restart-window` canonical-form + cap arms (`RestartWindowNotCanonical
3258// { window }`, `RestartWindowExceedsCap { window }`) — onto one substrate
3259// primitive per typed variant, matching the sibling
3260// [`crate::aplicacao::aplicacao_policy_scalar_ctors!`] macro (7ef425e, 8
3261// variants on the same `{ <field>: Duration | u32 }` shape) at that
3262// discipline on the peer `AplicacaoError` envelope's per-`:politicas`
3263// scalar axis. Every variant is a one-field `Copy`-pass-through struct-
3264// literal — `RestartStrategy | u32 | Duration` — so the fold routes each
3265// wire-up site through one dispatch per typed variant without a runtime-
3266// work delta.
3267//
3268// Each of the four wire-up sites opened the identical
3269// `SupervisorError::<Variant> { <field>: <val> }` struct-literal — the
3270// exact "same block re-inlined at every consumer" shape the PRIME
3271// DIRECTIVE names as a bug, on the same altitude the peer
3272// `aplicacao_policy_scalar_ctors!` fold closed on the sibling
3273// `AplicacaoError` envelope's per-`:politicas` per-axis cap / canonical-
3274// form arms. The four variants share one `{ <field>: <Copy> }` shape, so
3275// the fold routes each wire-up site through one dispatch per typed
3276// variant.
3277//
3278// The macro below generates one static constructor per variant of shape
3279// `const fn <ctor>(<field>: <ty>) -> SupervisorError`, so every wire-up
3280// site collapses onto one dispatch: `SupervisorError::<ctor>(<val>)`,
3281// byte-equal to the pre-lift struct-literal on the same `Copy`-`<ty>`
3282// fixture — as a direct call at the [`SupervisorSpec::validate`]
3283// `:children`-empty refusal, or as a bare function pointer in the
3284// `impl FnOnce(<ty>) -> SupervisorError` bracket-closure slot every
3285// [`crate::render::require_positive_bounded_u32`] /
3286// [`crate::render::require_positive_canonical_bounded_duration`] gate
3287// carries — rather than the pre-lift open-coded one-line closure over
3288// the same one-field struct-literal. `const fn` preserves the `Copy`-
3289// pass-through's zero-runtime-work property verbatim. Every constructor
3290// is `#[must_use]` so a caller who mistakenly discards the constructed
3291// error trips a compile warning at the wire-up site.
3292//
3293// Every future consumer that wants to construct one of these four
3294// variants outside `SupervisorSpec::validate` — a deferred
3295// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3296// webhook re-checking one edited `:estrategia` / `:max-restarts` /
3297// `:restart-window` slot against the cap + canonical-form cascade, a
3298// future `feira validate --supervisor` per-caixa admission verb re-
3299// running the shape gates on demand, a per-Supervisor overlay resolver
3300// rejecting an author-supplied slot against a cluster-local snapshot —
3301// now reaches each variant through one call rather than re-inlining the
3302// per-shape struct-literal block in lockstep with the four in-crate
3303// wire-up sites.
3304macro_rules! supervisor_scalar_ctors {
3305 ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
3306 impl SupervisorError {
3307 $(
3308 #[doc = concat!(
3309 "Construct a [`SupervisorError::",
3310 stringify!($variant),
3311 "`] naming the offending per-`:supervisor` `",
3312 stringify!($field),
3313 "` scalar. Folds the uniform `Self::",
3314 stringify!($variant),
3315 " { ",
3316 stringify!($field),
3317 " }` one-field `Copy`-pass-through struct-literal onto ",
3318 "one substrate primitive so every per-axis wire-up on ",
3319 "this variant reads through one dispatch — as a direct ",
3320 "call (`SupervisorError::",
3321 stringify!($ctor),
3322 "(<val>)`, byte-equal to the pre-lift struct-literal on ",
3323 "the same `Copy`-`",
3324 stringify!($ty),
3325 "` fixture) or as a bare function pointer in the ",
3326 "`impl FnOnce(",
3327 stringify!($ty),
3328 ") -> SupervisorError` bracket-closure slot every ",
3329 "`crate::render::require_positive_bounded_*` / ",
3330 "`crate::render::require_positive_canonical_bounded_*` ",
3331 "gate carries — rather than the pre-lift open-coded ",
3332 "one-line closure over the same one-field struct-",
3333 "literal. `const fn` preserves the `Copy`-pass-through's ",
3334 "zero-runtime-work property verbatim."
3335 )]
3336 #[must_use]
3337 pub const fn $ctor($field: $ty) -> Self {
3338 Self::$variant { $field }
3339 }
3340 )*
3341 }
3342 };
3343}
3344
3345supervisor_scalar_ctors! {
3346 no_children => NoChildren { estrategia: RestartStrategy },
3347 max_restarts_exceeds_cap => MaxRestartsExceedsCap { max_restarts: u32 },
3348 restart_window_not_canonical => RestartWindowNotCanonical { window: Duration },
3349 restart_window_exceeds_cap => RestartWindowExceedsCap { window: Duration },
3350}
3351
3352/// Shared duration string codec for the typed slots that take a
3353/// duration (`restart_window`, `MeshPolicy::timeout`,
3354/// `CircuitBreaker::window`, …). Public so [`crate::aplicacao`] can
3355/// reuse it without duplicating the parser.
3356pub mod duration_codec {
3357 use super::Duration;
3358 use serde::{Deserializer, Serializer};
3359
3360 pub fn serialize<S: Serializer>(v: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
3361 // Route through the canonical [`crate::render::serialize_option_via_str`]
3362 // — the substrate-side single-owner primitive for the forward
3363 // arm of the typed-magnitude codec family. See its docstring
3364 // for the full sibling roster.
3365 crate::render::serialize_option_via_str(v, s, render)
3366 }
3367
3368 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
3369 // Route through the canonical [`crate::render::deserialize_option_via_str`]
3370 // — the substrate-side single-owner primitive for the reverse
3371 // arm of the typed-magnitude codec family. See its docstring
3372 // for the full sibling roster.
3373 crate::render::deserialize_option_via_str(d, parse)
3374 }
3375
3376 pub(crate) fn parse(s: &str) -> Result<Duration, String> {
3377 // Paired whitespace-rejection arm — same canonical-form
3378 // render-determinism discipline as the peer
3379 // `limits::parse_byte_size` / `limits::parse_duration` /
3380 // `limits::parse_millicores` /
3381 // `aplicacao::rate_limit_codec::parse` sites: the ASCII
3382 // byte-scan closes the WhatWG-conformant whitespace bytes
3383 // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
3384 // `char::is_whitespace` scan closes the strictly-complementary
3385 // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
3386 // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
3387 // codepoints) that `str::trim` at parse entry silently strips.
3388 // Either drift class would round-trip through `render` to a
3389 // *different* canonical form on next emit — breaking the
3390 // THEORY.md Part V render-determinism contract on three typed-
3391 // duration slots at once (`:supervisor :restart-window`,
3392 // `:politicas :timeout`, `:politicas :circuit-breaker :window`)
3393 // via the shared codec.
3394 //
3395 // Routed through the lifted [`crate::render::reject_whitespace`]
3396 // primitive — the substrate-side single-owner paired-arm gate
3397 // every typed-magnitude codec in caixa-core shares.
3398 crate::render::reject_whitespace::<String, _, _>(
3399 s,
3400 |b| {
3401 format!(
3402 "duration: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
3403 authoring form for the typed duration slots routed through this shared codec \
3404 (`:supervisor :restart-window`, `:politicas :timeout`, \
3405 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
3406 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no whitespace bytes \
3407 anywhere. A whitespace-carrying shape (`\" 30s\"`, `\"30s \"`, `\"30 s\"`, \
3408 `\"\\t30s\"`, `\"30s\\n\"`) round-trips through `render` to a *different* \
3409 canonical form (`\"30s\"`) on first serialize — breaking the THEORY.md \
3410 Part V render-determinism contract every typed slot carries. Strip every \
3411 whitespace byte (write `\"30s\"` verbatim)"
3412 )
3413 },
3414 |ch| {
3415 format!(
3416 "duration: value {s:?} contains non-ASCII Unicode whitespace character \
3417 {ch:?} (U+{cp:04X}) — the canonical authoring form for the typed \
3418 duration slots routed through this shared codec (`:supervisor \
3419 :restart-window`, `:politicas :timeout`, `:politicas :circuit-breaker \
3420 :window`) is `<integer><unit>` (e.g. `\"30s\"`, `\"500ms\"`, `\"2m\"`, \
3421 `\"1h\"`) with no whitespace characters anywhere (ASCII or Unicode). A \
3422 non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}30s\"`, \
3423 `\"30s\\u{{2028}}\"`, `\"30\\u{{2003}}s\"`) survives the ASCII byte-scan \
3424 but `str::trim` (which uses `char::is_whitespace` — the Unicode \
3425 `White_Space` property, strictly wider than the ASCII byte set) silently \
3426 strips it at parse entry, and the value round-trips through `render` to \
3427 a *different* canonical form (`\"30s\"`) on first serialize — breaking \
3428 the THEORY.md Part V render-determinism contract every typed slot \
3429 carries. Strip every non-ASCII whitespace character (write `\"30s\"` \
3430 verbatim with only ASCII bytes)",
3431 cp = ch as u32
3432 )
3433 },
3434 )?;
3435 let s = s.trim();
3436 // Routed through the lifted
3437 // [`crate::render::split_magnitude_and_alpha_unit`] primitive —
3438 // the single-owner split every ASCII-alphabetic-unit typed-
3439 // magnitude codec in caixa-core (`limits::parse_byte_size` /
3440 // `limits::parse_duration` / this shared duration codec) shares.
3441 // See its docstring for the full sibling roster on the same
3442 // primitive altitude.
3443 let (num_part, unit) = crate::render::split_magnitude_and_alpha_unit(s);
3444 let num_trim = num_part.trim();
3445 // The canonical authoring form for every typed slot routed
3446 // through this shared codec — `:supervisor :restart-window`,
3447 // `:politicas :timeout`, `:politicas :circuit-breaker :window`
3448 // — is `<integer><unit>`. Every magnitude [`render`] emits is a
3449 // non-negative integer with no decimal point and no leading
3450 // sign, so the parser's accepted set must match for
3451 // serialize/deserialize to round-trip without canonical-form
3452 // drift. Until this gate landed the parser accepted any
3453 // `f64`-shaped magnitude (`"1.5s"` → 1500ms, `"1.0s"` → 1s,
3454 // `"0.5m"` → 30s, `"+30s"` → 30s) and serde silently round-
3455 // tripped the value to a *different* canonical string on the
3456 // next emit (`"1.5s"` → 1500ms → `"1500ms"`, `"1.0s"` → 1s →
3457 // `"1s"`, `"0.5m"` → 30s → `"30s"`, `"+30s"` → 30s → `"30s"`)
3458 // — breaking the THEORY.md Part V render-determinism contract
3459 // on three typed slots at once. Same canonical-form discipline
3460 // `crate::limits::parse_duration` (818dd38, the immediate
3461 // predecessor on the peer `:limits :wall-clock` codec) applies;
3462 // this gate lifts the discipline onto the shared codec that
3463 // backs the remaining three typed-duration slots in caixa-core.
3464 //
3465 // Strict canonical form: every byte of the magnitude is an
3466 // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
3467 // inputs the gate distinguishes "non-canonical-but-numeric"
3468 // (parses as f64 or i64 — surfaced with a self-locating
3469 // diagnostic naming the canonical authoring form, the
3470 // round-trip drift each rejected shape would produce on first
3471 // serialize, and the canonical-form remediation) from
3472 // "garbage" (parses as neither — surfaced with the existing
3473 // narrower "bad duration magnitude" wording so its diagnostic
3474 // shape remains stable for the parser-shape footgun case).
3475 // The pre-existing `num < 0.0` arm is now unreachable — the
3476 // digit-only gate strictly precedes magnitude parsing, and a
3477 // leading `-` is not an ASCII digit, so `"-30s"` lands on the
3478 // non-canonical-but-numeric branch with the `-30` named
3479 // verbatim in the diagnostic rather than the prior
3480 // value-laundered "negative duration in \"-30s\"" wording.
3481 //
3482 // Routed through the lifted
3483 // [`crate::render::is_digit_only_magnitude`] predicate — the
3484 // same source of truth the four peer typed-magnitude codec
3485 // sites share.
3486 let digit_only = crate::render::is_digit_only_magnitude(num_trim);
3487 if !digit_only {
3488 let numeric = num_trim.parse::<f64>().is_ok() || num_trim.parse::<i64>().is_ok();
3489 if numeric {
3490 return Err(format!(
3491 "duration: magnitude {num_trim:?} is not a non-negative integer — the \
3492 canonical authoring form for the typed duration slots routed through \
3493 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
3494 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
3495 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no decimal point and \
3496 no leading `+` / `-` sign. A fractional / decimal-shaped magnitude \
3497 (`\"1.5s\"`, `\"1.0s\"`, `\"0.5m\"`, `\"+30s\"`, `\"-30s\"`) round-trips \
3498 through `render` to a *different* canonical form (`\"1500ms\"`, `\"1s\"`, \
3499 `\"30s\"`, `\"30s\"`, `\"30s\"`) on first serialize — breaking the \
3500 THEORY.md Part V render-determinism contract every typed slot carries. \
3501 Pick an integer magnitude in the unit that divides cleanly (write \
3502 `\"1500ms\"` instead of `\"1.5s\"`; `\"30s\"` instead of `\"0.5m\"`)"
3503 ));
3504 }
3505 return Err(format!("bad duration magnitude in {s:?}"));
3506 }
3507 // Leading-zero arm — peer with the `rate_limit_codec` leading-
3508 // zero arm (4f46830) on the same canonical-form render-
3509 // determinism axis. The digit-only gate accepts `"030s"`,
3510 // `"00s"`, `"01h"`, `"0500ms"` as `u64::from_str` parses them
3511 // losslessly (= 30, 0, 1, 500), but `render` emits the leading-
3512 // zero-stripped form (`"30s"`, `"0s"`, `"1h"`, `"500ms"`) — a
3513 // *different* canonical string on the next emit, breaking the
3514 // THEORY.md Part V render-determinism contract the same way
3515 // `"+30s"` did before the leading-`+` arm landed. The single-
3516 // byte magnitude `"0"` (or `"0s"` / `"0ms"`) round-trips
3517 // losslessly through `render` (`render(Duration::ZERO)` emits
3518 // `"0s"`) — the downstream semantic-zero gates (e.g.
3519 // `SupervisorError::ZeroRestartWindow` on
3520 // `:supervisor :restart-window`,
3521 // `AplicacaoError::PolicyTimeoutZero` /
3522 // `PolicyCircuitBreakerWindowZero` on the typed `:politicas`
3523 // duration slots) refuse zero-magnitude authoring at the typed-
3524 // validate layer above, so the single-byte `"0"` stays in the
3525 // accepted set at this codec layer and the diagnostic
3526 // partitioning between canonical-form drift (this arm) and
3527 // semantic-zero (the downstream gates) remains stable.
3528 // Peer with the future leading-zero arms on the two remaining
3529 // typed-magnitude codecs the trajectory acknowledges:
3530 // `limits::parse_duration` backing `:limits :wall-clock`,
3531 // `limits::parse_byte_size` backing `:limits :memory` — each
3532 // carries the same canonical-form-drift class today; this
3533 // gate lands the discipline on the shared duration codec
3534 // first because the `rate_limit_codec` predecessor on the
3535 // same canonical-form-drift axis is the closest peer on the
3536 // trajectory.
3537 //
3538 // Routed through the lifted
3539 // [`crate::render::is_leading_zero_padded_magnitude`]
3540 // predicate — the same source of truth the four peer
3541 // typed-magnitude codec sites share.
3542 if crate::render::is_leading_zero_padded_magnitude(num_trim) {
3543 return Err(format!(
3544 "duration: magnitude {num_trim:?} has a non-canonical leading zero — the \
3545 canonical authoring form for the typed duration slots routed through \
3546 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
3547 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
3548 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no leading-zero padding \
3549 on the magnitude. A leading-zero magnitude (`\"030s\"`, `\"00s\"`, \
3550 `\"01h\"`, `\"0500ms\"`) round-trips through `render` to a *different* \
3551 canonical form (`\"30s\"`, `\"0s\"`, `\"1h\"`, `\"500ms\"`) on first \
3552 serialize — breaking the THEORY.md Part V render-determinism contract \
3553 every typed slot carries. Strip the leading zeros (write \
3554 `\"30s\"` instead of `\"030s\"`)"
3555 ));
3556 }
3557 // The digit-only gate guarantees every byte is `[0-9]`, and
3558 // the leading-zero arm above guarantees the magnitude is
3559 // either the single byte `"0"` or starts with `[1-9]`, so
3560 // the only way `u64::from_str` can fail here is overflow (the
3561 // magnitude exceeds `u64::MAX`). Surface that with an
3562 // overflow-shaped wording so the diagnostic names the offending
3563 // magnitude verbatim rather than collapsing onto the
3564 // non-canonical arm. The codec now operates on `u64` end-to-end
3565 // — every accepted magnitude is integer-exact; no f64 mantissa
3566 // drift between author-supplied magnitude and the consumer's
3567 // `Duration` value. Same shape `crate::limits::parse_duration`
3568 // (818dd38) carries on the peer `:limits :wall-clock` axis.
3569 let num: u64 = num_trim.parse::<u64>().map_err(|_| {
3570 format!("bad duration magnitude in {s:?} (digit-only magnitude overflows u64)")
3571 })?;
3572 // Route the `{"ms" | "s" | "" | "m" | "h"} → Duration`
3573 // unit-arm dispatch through the canonical
3574 // [`crate::render::duration_from_integer_magnitude_and_unit`]
3575 // primitive — the substrate-side single-owner unit-dispatch
3576 // table every typed-duration codec in caixa-core routes
3577 // through (peer: `crate::limits::parse_duration` backing
3578 // `:limits :wall-clock`). Every unit conversion is integer-
3579 // exact for an integer magnitude; overflow surfaces via the
3580 // typed `DurationUnitError::Overflow { multiplier }`
3581 // discriminant so this arm reconstructs the pre-lift
3582 // `"duration <num><unit> overflows u64 (magnitude × 60 …)"`
3583 // wording verbatim from `num` / `unit_trim` / the returned
3584 // `multiplier`, and the unknown-unit arm reconstructs the
3585 // pre-lift `"unknown duration unit \"<other>\""` wording from
3586 // the caller-scoped `unit_trim`. Load-bearing pinned by
3587 // `crate::render::tests::duration_from_integer_magnitude_and_unit_matches_pre_lift_unit_dispatch_table`.
3588 let unit_trim = unit.trim();
3589 let dur = crate::render::duration_from_integer_magnitude_and_unit(num, unit_trim).map_err(
3590 |e| match e {
3591 crate::render::DurationUnitError::Overflow { multiplier } => format!(
3592 "duration {num}{unit_trim} overflows u64 (magnitude × {multiplier} > 2^64-1)"
3593 ),
3594 crate::render::DurationUnitError::UnknownUnit => {
3595 format!("unknown duration unit {unit_trim:?}")
3596 }
3597 },
3598 )?;
3599 Ok(dur)
3600 }
3601
3602 /// Render a [`Duration`] in the canonical pleme-io duration string
3603 /// form (`"30s"`, `"1m"`, `"1h"`, `"500ms"`). The same form every
3604 /// caixa typed-duration slot serializes to and the same form K8s
3605 /// Gateway API HTTPRoute `timeouts` / `backendRequest` and Cilium
3606 /// EnvoyConfig per-route timeouts both expect (an integer
3607 /// followed by `s`/`m`/`h`/`ms`, no fractional values, no leading
3608 /// `+`). Lifted to `pub` so caixa-side renderers
3609 /// (`caixa-mesh::gateway_routes`'s :politicas :timeout overlay,
3610 /// the future per-:politicas `CiliumClusterwideEnvoyConfig`
3611 /// emitter, the future caixa-otel collector pipeline emitter) can
3612 /// consume the same canonical formatter without re-inlining the
3613 /// magnitude/unit decision tree (and inheriting the same drift
3614 /// footguns: a subtly different `300ms` vs `0.3s` rendering breaks
3615 /// downstream apply-time parsing in non-obvious ways).
3616 pub fn render(d: Duration) -> String {
3617 let total_ms = d.as_millis();
3618 if total_ms == 0 {
3619 return "0s".into();
3620 }
3621 if total_ms.is_multiple_of(3600 * 1000) {
3622 return format!("{}h", total_ms / (3600 * 1000));
3623 }
3624 if total_ms.is_multiple_of(60 * 1000) {
3625 return format!("{}m", total_ms / (60 * 1000));
3626 }
3627 if total_ms.is_multiple_of(1000) {
3628 return format!("{}s", total_ms / 1000);
3629 }
3630 format!("{total_ms}ms")
3631 }
3632
3633 /// True iff `d` round-trips losslessly through [`render`] + [`parse`].
3634 ///
3635 /// [`render`] truncates a `Duration` to `as_millis()` before picking the
3636 /// largest divisor unit, so any sub-millisecond residue
3637 /// (`d.subsec_nanos() % 1_000_000 != 0`) silently breaks the THEORY.md
3638 /// §V.2.7 render-determinism contract:
3639 ///
3640 /// - `Duration::from_micros(1500)` (= `1_500_000` ns) → `as_millis() == 1`
3641 /// → renders `"1ms"` → parses back to `Duration::from_millis(1)` =
3642 /// `1_000_000` ns ≠ original `1_500_000` ns;
3643 /// - `Duration::from_nanos(1)` (= 1 ns) → `as_millis() == 0` →
3644 /// renders the literal `"0s"`, which the per-axis zero-floor gate
3645 /// on every typed-`Duration` slot then rejects on re-validate.
3646 ///
3647 /// Lifted to a `pub` predicate next to the [`render`] / [`parse`] pair so
3648 /// the codec's round-trippable accepted set lives in exactly one place —
3649 /// every typed-`Duration` slot that routes through this shared codec
3650 /// (`SupervisorSpec::restart_window` via [`super::duration_codec`],
3651 /// [`crate::MeshPolicy::timeout`] / [`crate::CircuitBreaker::window`] via
3652 /// `supervisor::duration_codec` + [`super::duration_codec_required`]) and
3653 /// every typed-`Duration` slot whose own codec shares the same
3654 /// `as_millis()`-truncation shape ([`crate::LimitsSpec::wall_clock`] via
3655 /// [`crate::limits`]'s in-module `parse_duration` / `render_duration`
3656 /// pair) calls this predicate from its `validate()` to bracket the
3657 /// accepted set against the codec's accepted set, structurally. Drift
3658 /// between the codec's granularity and any typed slot's accepted set is
3659 /// then a single-source-of-truth edit at this predicate rather than a
3660 /// silent round-trip break the next consumer discovers at apply time.
3661 ///
3662 /// Peer of [`crate::aplicacao::POLICY_RETRIES_MAX`] /
3663 /// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] and the
3664 /// `is_dns_1123_label` / `is_canonical_rate_limit_window` predicate
3665 /// family — same "typed-slot's valid set matches its codec's accepted
3666 /// set, structurally" discipline carried at the codec layer.
3667 #[must_use]
3668 pub fn is_integer_millisecond_duration(d: Duration) -> bool {
3669 d.subsec_nanos().is_multiple_of(1_000_000)
3670 }
3671}
3672
3673/// Required-Duration variant for fields that aren't Option<Duration>.
3674pub mod duration_codec_required {
3675 use super::Duration;
3676 use serde::{Deserialize, Deserializer, Serializer};
3677
3678 pub fn serialize<S: Serializer>(v: &Duration, s: S) -> Result<S::Ok, S::Error> {
3679 s.serialize_str(&super::duration_codec::render(*v))
3680 }
3681
3682 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
3683 let s = String::deserialize(d)?;
3684 super::duration_codec::parse(&s).map_err(serde::de::Error::custom)
3685 }
3686}
3687
3688#[cfg(test)]
3689mod tests {
3690 use super::*;
3691
3692 fn child(name: &str, ver: &str, restart: RestartPolicy) -> ChildSpec {
3693 ChildSpec {
3694 caixa: name.into(),
3695 versao: ver.into(),
3696 restart,
3697 }
3698 }
3699
3700 #[test]
3701 fn child_spec_string_scalar_accessor_pair_is_const_fn() {
3702 // Fail-before-pass-after pin on [`ChildSpec::nome`] +
3703 // [`ChildSpec::versao_requirement`]'s `const`-eval-surface
3704 // posture. Each accessor projects the per-`:children :caixa`
3705 // / per-`:children :versao` [`String`] storage through the
3706 // `pub const fn` [`String::as_str`] (const-stable since Rust
3707 // 1.87, well within the workspace MSRV) — any future
3708 // accidental downgrade to non-`const` fails the corresponding
3709 // `<name>_via_const_fn` wrapper at caixa-core build time with
3710 // E0015 (`cannot call non-const method`), strictly stronger
3711 // than a runtime `assert!`. Sibling of the peer
3712 // per-M2/M3/universal-axis `String → &str` scalar-accessor
3713 // family pins on the sibling `const`-eval-surface passes
3714 // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
3715 // top-level manifest, [`crate::CaixaVersion::as_str`] at the
3716 // typed-newtype wrapper, [`crate::aplicacao::Membro::nome`] /
3717 // [`crate::aplicacao::Membro::versao_requirement`] at the M3
3718 // membership axis, [`crate::aplicacao::Entrada::hostname`] /
3719 // [`crate::aplicacao::Entrada::destination`] at the M3
3720 // ingress axis,
3721 // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
3722 // M2 upgrade axis, [`crate::dep::Dep::nome`] /
3723 // [`crate::dep::Dep::versao_requirement`] at the dep-graph
3724 // axis, and the per-`:contratos`
3725 // [`crate::aplicacao::WitContract::source`] /
3726 // [`crate::aplicacao::WitContract::destination`] /
3727 // [`crate::aplicacao::WitContract::world_ref`] trio the
3728 // sibling pin at 279823b already anchors).
3729 const fn nome_via_const_fn(c: &ChildSpec) -> &str {
3730 c.nome()
3731 }
3732 const fn versao_via_const_fn(c: &ChildSpec) -> &str {
3733 c.versao_requirement()
3734 }
3735 for (caixa, versao) in [
3736 ("worker-a", "^0.1"),
3737 ("worker-b", "~0.2.3"),
3738 ("collector", "*"),
3739 ] {
3740 let c = child(caixa, versao, RestartPolicy::Permanent);
3741 assert_eq!(nome_via_const_fn(&c), c.nome());
3742 assert_eq!(versao_via_const_fn(&c), c.versao_requirement());
3743 assert_eq!(c.nome(), caixa);
3744 assert_eq!(c.versao_requirement(), versao);
3745 }
3746 }
3747
3748 #[test]
3749 fn supervisor_children_slice_return_accessor_is_const_fn() {
3750 // Fail-before-pass-after pin on [`SupervisorSpec::children`]'s
3751 // `const`-eval-surface posture. The accessor destructures the
3752 // per-`:children` `Vec<ChildSpec>` storage through the
3753 // `pub const fn` [`Vec::as_slice`] (const-stable since Rust
3754 // 1.66, well within the workspace MSRV) — any future
3755 // accidental downgrade to non-`const` fails
3756 // `children_via_const_fn` at caixa-core build time with E0015
3757 // (`cannot call non-const method`), strictly stronger than a
3758 // runtime `assert!`. Sibling of the peer per-M3-mesh-slot
3759 // `Vec → &[T]` slice-return accessor family pin
3760 // [`crate::aplicacao::tests::m3_reference_return_accessor_family_is_const_fn`]
3761 // on the M3 mesh-slot per-`:clusters` / per-`:paths` /
3762 // per-`:membros` / per-`:contratos` slice-return axes, and of
3763 // the peer M2 upgrade-appup axis pin
3764 // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
3765 // on the per-`:upgrade-from :instructions` slice-return axis.
3766 const fn children_via_const_fn(s: &SupervisorSpec) -> &[ChildSpec] {
3767 s.children()
3768 }
3769 // Sweep both the empty-children (leaf-supervisor with no
3770 // static children — the `SimpleOneForOne` dynamic-child
3771 // arm's canonical shape) and the populated-children
3772 // (`OneForOne` / `OneForAll` / `RestForOne` static-child
3773 // arm's canonical shape) axes so the accessor carries a
3774 // const-dispatch pin on both arms.
3775 let s_empty = SupervisorSpec {
3776 estrategia: RestartStrategy::SimpleOneForOne,
3777 max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
3778 restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3779 children: vec![],
3780 };
3781 assert!(children_via_const_fn(&s_empty).is_empty());
3782 assert_eq!(children_via_const_fn(&s_empty), s_empty.children());
3783 let s_full = SupervisorSpec {
3784 estrategia: RestartStrategy::OneForOne,
3785 max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
3786 restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3787 children: vec![
3788 child("worker-a", "^0.1", RestartPolicy::Permanent),
3789 child("worker-b", "~0.2.3", RestartPolicy::Transient),
3790 child("collector", "*", RestartPolicy::Temporary),
3791 ],
3792 };
3793 assert_eq!(children_via_const_fn(&s_full).len(), 3);
3794 assert_eq!(children_via_const_fn(&s_full), s_full.children());
3795 }
3796
3797 #[test]
3798 fn default_has_one_for_one_and_5_restarts_in_60s() {
3799 let s = SupervisorSpec::default();
3800 assert_eq!(s.estrategia, RestartStrategy::OneForOne);
3801 assert_eq!(s.max_restarts, 5);
3802 assert_eq!(s.restart_window, Some(Duration::from_secs(60)));
3803 assert!(s.children.is_empty());
3804 }
3805
3806 #[test]
3807 fn validate_one_for_one_requires_children() {
3808 let mut s = SupervisorSpec::default();
3809 s.children = vec![];
3810 assert!(matches!(
3811 s.validate().unwrap_err(),
3812 SupervisorError::NoChildren { .. }
3813 ));
3814 s.children = vec![child("worker", "^0.1", RestartPolicy::Permanent)];
3815 s.validate().unwrap();
3816 }
3817
3818 #[test]
3819 fn validate_simple_one_for_one_forbids_static_children() {
3820 let mut s = SupervisorSpec {
3821 estrategia: RestartStrategy::SimpleOneForOne,
3822 ..SupervisorSpec::default()
3823 };
3824 s.children
3825 .push(child("w", "^0.1", RestartPolicy::Permanent));
3826 assert_eq!(
3827 s.validate().unwrap_err(),
3828 SupervisorError::SimpleOneForOneWithStaticChildren
3829 );
3830 s.children.clear();
3831 s.validate().unwrap();
3832 }
3833
3834 #[test]
3835 fn validate_rejects_zero_max_restarts() {
3836 let s = SupervisorSpec {
3837 max_restarts: 0,
3838 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3839 ..SupervisorSpec::default()
3840 };
3841 assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
3842 }
3843
3844 // ── upper-cap: SUPERVISOR_MAX_RESTARTS_MAX brackets the typed slot ─────
3845 //
3846 // The cap arm lifts the `:politicas :circuit-breaker :max-failures` /
3847 // `POLICY_BREAKER_MAX_FAILURES_MAX` (2b51ace) discipline onto the peer
3848 // `:supervisor :max-restarts` axis — both fields are "trip the
3849 // next-higher protection layer after N events in a rolling window"
3850 // counters with identical degenerate-at-the-high-end shape, so the
3851 // typed-slot's accepted set lies in `1..=1000` on the supervisor side
3852 // exactly as it lies in `1..=1000` on the breaker side.
3853
3854 #[test]
3855 fn validate_rejects_max_restarts_above_cap() {
3856 // The fail-before-pass-after pin: `SUPERVISOR_MAX_RESTARTS_MAX +
3857 // 1` is structurally one past the cap and silently passed
3858 // validate on every pre-gate codebase because the typed slot's
3859 // only check was the zero-floor arm. The no-op-supervisor vector
3860 // only surfaced at the runtime substrate (Erlang/OTP
3861 // MaxIntensity/Period ratio, the future wasm-operator's
3862 // per-supervisor restart-intensity counter) far from the source
3863 // caixa.lisp with no field naming the offending supervisor.
3864 let s = SupervisorSpec {
3865 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3866 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3867 ..SupervisorSpec::default()
3868 };
3869 assert_eq!(
3870 s.validate().unwrap_err(),
3871 SupervisorError::MaxRestartsExceedsCap {
3872 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3873 }
3874 );
3875 }
3876
3877 #[test]
3878 fn validate_rejects_max_restarts_far_above_cap() {
3879 // The `u32::MAX` worst case — the four-billion-restart
3880 // threshold a typo (`:max-restarts 4294967295`) or a
3881 // struct-literal copy-paste lands in the slot. Pin the cap
3882 // arm's coverage explicitly across the full `u32` overflow so
3883 // a future relaxation that drops the upper bound surfaces
3884 // here. Same shape every other typed-cap arm on this surface
3885 // carries (POLICY_BREAKER_MAX_FAILURES_MAX,
3886 // POLICY_RETRIES_MAX, POLICY_RATE_LIMIT_MAX).
3887 let s = SupervisorSpec {
3888 max_restarts: u32::MAX,
3889 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3890 ..SupervisorSpec::default()
3891 };
3892 assert_eq!(
3893 s.validate().unwrap_err(),
3894 SupervisorError::MaxRestartsExceedsCap {
3895 max_restarts: u32::MAX,
3896 }
3897 );
3898 }
3899
3900 #[test]
3901 fn validate_accepts_max_restarts_at_cap() {
3902 // The boundary value — exactly SUPERVISOR_MAX_RESTARTS_MAX —
3903 // must validate. The cap is inclusive on the top edge,
3904 // matching the POLICY_BREAKER_MAX_FAILURES_MAX /
3905 // POLICY_RETRIES_MAX / LIMITS_MEMORY_WASM32_MAX_BYTES
3906 // discipline on the sibling capped axes. Pin the boundary
3907 // explicitly so a future off-by-one tightening
3908 // (`>= SUPERVISOR_MAX_RESTARTS_MAX` instead of `>`) surfaces
3909 // here as a test failure rather than a silent contract
3910 // narrowing.
3911 let s = SupervisorSpec {
3912 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX,
3913 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3914 ..SupervisorSpec::default()
3915 };
3916 s.validate()
3917 .expect("max_restarts == SUPERVISOR_MAX_RESTARTS_MAX must validate");
3918 }
3919
3920 #[test]
3921 fn validate_accepts_max_restarts_typical_values() {
3922 // The documented production-playbook band positive-control
3923 // sweep — every value Erlang/OTP / Elixir / Riak Core /
3924 // RabbitMQ recommend (1..=100) must pass, plus a sweep
3925 // through the hyperscale band (200, 500, 1000) the cap
3926 // accepts. Pin the inclusive validated set explicitly so a
3927 // future tightening of the ceiling surfaces here.
3928 for n in [1u32, 3, 5, 10, 20, 50, 100, 200, 500, 1000] {
3929 let s = SupervisorSpec {
3930 max_restarts: n,
3931 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3932 ..SupervisorSpec::default()
3933 };
3934 s.validate()
3935 .unwrap_or_else(|e| panic!("max_restarts={n} must validate; got {e:?}"));
3936 }
3937 }
3938
3939 #[test]
3940 fn zero_max_restarts_takes_precedence_over_cap() {
3941 // The cross-arm ordering pin: `0` is structurally outside
3942 // both `1..` (zero-floor) and `..=SUPERVISOR_MAX_RESTARTS_MAX`
3943 // (cap), but the zero-floor diagnostic is the more
3944 // self-locating one (it directly names the counter-axis
3945 // remediation), so the validate gate must fire on zero first.
3946 // Same shape every other zero-then-shape ordering on this
3947 // surface uses (PolicyRetriesZero then
3948 // PolicyRetriesExceedsCap; PolicyBreakerZeroFailures then
3949 // PolicyBreakerMaxFailuresExceedsCap).
3950 let s = SupervisorSpec {
3951 max_restarts: 0,
3952 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3953 ..SupervisorSpec::default()
3954 };
3955 assert_eq!(
3956 s.validate().unwrap_err(),
3957 SupervisorError::ZeroMaxRestarts,
3958 "max_restarts == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
3959 );
3960 }
3961
3962 #[test]
3963 fn max_restarts_cap_takes_precedence_over_restart_window_gates() {
3964 // The cross-arm ordering pin between the cap and the sibling
3965 // `:restart-window` gates (zero-window, canonical-window). A
3966 // supervisor carrying both an over-cap `max_restarts` AND a
3967 // structurally invalid window (zero, sub-ms) must surface the
3968 // cap diagnostic first — the cap arm is wired immediately
3969 // after the zero-restart arm and strictly before the window
3970 // arms, so the offending value the diagnostic names matches
3971 // the order the author would discover the gates by reading
3972 // top-to-bottom through `SupervisorSpec::validate`. Pin the
3973 // order so a future refactor that reorders the arms surfaces
3974 // here as a test failure rather than a silent diagnostic
3975 // regression. Peer of
3976 // `circuit_breaker_max_failures_cap_takes_precedence_over_window_gates`
3977 // on the sibling `:politicas :circuit-breaker` slot.
3978 let s = SupervisorSpec {
3979 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3980 restart_window: Some(Duration::ZERO),
3981 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3982 ..SupervisorSpec::default()
3983 };
3984 assert_eq!(
3985 s.validate().unwrap_err(),
3986 SupervisorError::MaxRestartsExceedsCap {
3987 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3988 },
3989 "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
3990 );
3991 }
3992
3993 #[test]
3994 fn max_restarts_cap_diagnostic_carries_offending_value() {
3995 // The diagnostic-shape pin: the offending `u32` is carried
3996 // verbatim into the `SupervisorError::MaxRestartsExceedsCap`
3997 // variant so the surfaced error message names the value the
3998 // author wrote (`":supervisor :max-restarts (50000) exceeds the
3999 // supervisor-policy ceiling …"`), not just the cap. Same
4000 // self-locating diagnostic shape every other typed-cap arm on
4001 // this surface carries
4002 // (`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` carries
4003 // the offending failure count verbatim,
4004 // `AplicacaoError::PolicyRetriesExceedsCap` carries the offending
4005 // retries count verbatim).
4006 let s = SupervisorSpec {
4007 max_restarts: 50_000,
4008 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4009 ..SupervisorSpec::default()
4010 };
4011 let err = s.validate().unwrap_err();
4012 assert!(
4013 matches!(
4014 err,
4015 SupervisorError::MaxRestartsExceedsCap {
4016 max_restarts: 50_000
4017 }
4018 ),
4019 "got {err:?}"
4020 );
4021 let msg = err.to_string();
4022 assert!(
4023 msg.contains("50000"),
4024 ":supervisor :max-restarts cap diagnostic must carry the offending value verbatim (got: {msg})"
4025 );
4026 }
4027
4028 #[test]
4029 fn supervisor_max_restarts_default_pins_otp_canonical_value() {
4030 // Pin [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] at `5` — the
4031 // Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
4032 // half of Learn You Some Erlang's worker-supervisor default,
4033 // sibling of the `60s` `Period` half that the paired
4034 // [`Default for SupervisorSpec`] impl already pins on the
4035 // sibling `restart_window` axis. Pinning the literal here
4036 // surfaces a future rebrand (a tightening to Elixir's `3`,
4037 // a widening to a per-cluster overlay the operator pins
4038 // through a future `:max-restarts-overrides` slot) as a
4039 // deliberate test edit, not a silent contract migration.
4040 // Peer of the sibling
4041 // [`supervisor_max_restarts_cap_pins_canonical_value`]
4042 // upper-bracket pin on the same axis.
4043 assert_eq!(SUPERVISOR_MAX_RESTARTS_DEFAULT, 5);
4044 }
4045
4046 #[test]
4047 fn default_max_restarts_helper_routes_through_lifted_default() {
4048 // Composition pin: the private `default_max_restarts()`
4049 // serde-`#[serde(default = "…")]` helper on
4050 // [`SupervisorSpec::max_restarts`] must route through the
4051 // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
4052 // typed `pub const` rather than a raw `5` literal. Prior to
4053 // the lift the helper carried an inline `5` with no compile-
4054 // time link back to the shared default, so the wire-format
4055 // author-omitted arm and the caixa-core
4056 // [`crate::manifest::Caixa::supervisor_view`] fold's `unwrap_or(5)`
4057 // arm could silently split on any future default rebrand.
4058 // Byte-parity against the lifted constant closes the split.
4059 assert_eq!(default_max_restarts(), SUPERVISOR_MAX_RESTARTS_DEFAULT);
4060 }
4061
4062 #[test]
4063 fn supervisor_spec_default_max_restarts_routes_through_lifted_default() {
4064 // Composition pin: the [`Default for SupervisorSpec`] impl's
4065 // struct-literal `max_restarts` field must route through the
4066 // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
4067 // typed `pub const` (via the private helper this test's
4068 // sibling `default_max_restarts_helper_routes_through_lifted_default`
4069 // already pins onto the constant). Structurally: every
4070 // `SupervisorSpec::default()` call must yield a
4071 // `max_restarts` field byte-equal to the lifted constant
4072 // (the two paired defaults — the serde-side wire-format arm
4073 // and the struct-literal default arm — cannot silently split
4074 // on any future default rebrand). Peer of the sibling
4075 // `default_has_one_for_one_and_5_restarts_in_60s` shape pin
4076 // — this pin closes the byte-parity arm on the two paired
4077 // altitude entry points onto the shared substrate constant.
4078 assert_eq!(
4079 SupervisorSpec::default().max_restarts(),
4080 SUPERVISOR_MAX_RESTARTS_DEFAULT,
4081 );
4082 }
4083
4084 #[test]
4085 fn supervisor_restart_window_default_pins_otp_canonical_value() {
4086 // Pin [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] at `60s` — the
4087 // Erlang/OTP-canonical `{intensity, 5, 60}` `Period` half of
4088 // Learn You Some Erlang's worker-supervisor default, paired
4089 // with the sibling `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5`
4090 // `MaxIntensity` half this constant is the sliding-window
4091 // denominator of on the same `MaxIntensity / Period`
4092 // restart-intensity ratio. Pinning the literal here surfaces a
4093 // future coherent rebrand of the paired default (Elixir's
4094 // `{max_restarts: 3, max_seconds: 5}`, a per-cluster overlay
4095 // the operator pins through a future
4096 // `:restart-window-overrides` slot) as a deliberate test edit,
4097 // not a silent contract migration. Peer of the sibling
4098 // [`supervisor_max_restarts_default_pins_otp_canonical_value`]
4099 // paired-half pin on the same OTP-canonical default and the
4100 // [`supervisor_restart_window_cap_pins_canonical_value`]
4101 // upper-bracket pin on the same axis.
4102 assert_eq!(SUPERVISOR_RESTART_WINDOW_DEFAULT, Duration::from_secs(60),);
4103 }
4104
4105 #[test]
4106 fn supervisor_spec_default_restart_window_routes_through_lifted_default() {
4107 // Composition pin: the [`Default for SupervisorSpec`] impl's
4108 // struct-literal `restart_window` field must route through the
4109 // substrate-canonical [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
4110 // typed `pub const` rather than a raw
4111 // `Duration::from_secs(60)` literal. Prior to this lift the
4112 // paired `{intensity, 5, 60}` OTP-canonical default was split
4113 // across two altitudes with no compile-time link between the
4114 // halves — the `MaxIntensity` half rode through the lifted
4115 // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant while the
4116 // `Period` half rode as an open-coded literal at the
4117 // composition site, so a future coherent rebrand of the paired
4118 // canonical would have had to migrate one half through the
4119 // constant and the other through a raw literal in lockstep.
4120 // Byte-parity against the lifted constant on the `Period` half
4121 // closes the split — the paired OTP-canonical default now
4122 // migrates as one unit on any future axis change. Peer of the
4123 // sibling
4124 // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
4125 // byte-parity pin on the paired `MaxIntensity` half.
4126 assert_eq!(
4127 SupervisorSpec::default().restart_window(),
4128 Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4129 );
4130 }
4131
4132 #[test]
4133 fn supervisor_estrategia_default_pins_otp_canonical_value() {
4134 // Pin [`SUPERVISOR_ESTRATEGIA_DEFAULT`] at [`RestartStrategy::OneForOne`]
4135 // — the Erlang/OTP-canonical `one_for_one` half of Learn You Some
4136 // Erlang's `{one_for_one, intensity, 5, 60}` worker-supervisor
4137 // canonical default, paired with the sibling
4138 // `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5` `MaxIntensity` half and the
4139 // sibling `SUPERVISOR_RESTART_WINDOW_DEFAULT` `60s` `Period` half
4140 // this constant is the strategy discriminator of on the same
4141 // OTP-canonical worker-supervisor default. Pinning the arm here
4142 // surfaces a future coherent rebrand of the paired triple (Elixir's
4143 // `{:one_for_one, max_restarts: 3, max_seconds: 5}` on the sibling
4144 // intensity/period axes leaving this strategy arm untouched, an OTP
4145 // `rest_for_one` widening once the substrate discovers startup-
4146 // order-coupled child cohorts as the more common worker-supervisor
4147 // shape, a per-cluster overlay the operator pins through a future
4148 // `:estrategia-overrides` slot the MESH-COMPOSITION §III.2
4149 // supervision-canary roadmap acknowledges) as a deliberate test
4150 // edit, not a silent contract migration. Peer of the sibling
4151 // [`supervisor_max_restarts_default_pins_otp_canonical_value`] +
4152 // [`supervisor_restart_window_default_pins_otp_canonical_value`]
4153 // paired-half pins on the same OTP-canonical default.
4154 assert_eq!(SUPERVISOR_ESTRATEGIA_DEFAULT, RestartStrategy::OneForOne);
4155 }
4156
4157 #[test]
4158 fn restart_strategy_default_routes_through_lifted_default() {
4159 // Composition pin: the [`Default for RestartStrategy`] impl's
4160 // return arm must route through the substrate-canonical
4161 // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
4162 // a raw `Self::OneForOne` arm. Prior to the lift the impl carried
4163 // an inline `Self::OneForOne` with no compile-time link back to
4164 // the shared OTP-canonical `one_for_one` strategy the paired
4165 // [`Default for SupervisorSpec`] impl's struct-literal `estrategia`
4166 // field and the [`crate::manifest::Caixa::supervisor_view`] fold's
4167 // `.unwrap_or_default()` (now
4168 // `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)`) arm both key off —
4169 // so a future rebrand of the OTP-canonical strategy default (an
4170 // OTP `rest_for_one` widening once the substrate discovers
4171 // startup-order-coupled child cohorts as the more common worker-
4172 // supervisor shape, a per-cluster overlay the operator pins
4173 // through a future `:estrategia-overrides` slot) would have had to
4174 // be threaded through the `Default` impl and the two peer routes
4175 // in lockstep or the three consumers would silently split. Byte-
4176 // parity against the lifted constant closes the split. Peer of
4177 // the sibling
4178 // [`default_max_restarts_helper_routes_through_lifted_default`] +
4179 // [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
4180 // composition pins on the paired `MaxIntensity` + `Period` halves.
4181 assert_eq!(RestartStrategy::default(), SUPERVISOR_ESTRATEGIA_DEFAULT,);
4182 }
4183
4184 #[test]
4185 fn supervisor_spec_default_estrategia_routes_through_lifted_default() {
4186 // Composition pin: the [`Default for SupervisorSpec`] impl's
4187 // struct-literal `estrategia` field must route through the
4188 // substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed
4189 // `pub const` (either directly, or via the
4190 // [`RestartStrategy::default`] impl that the sibling
4191 // `restart_strategy_default_routes_through_lifted_default` pin
4192 // already routes onto the constant). Structurally: every
4193 // `SupervisorSpec::default()` call must yield an `estrategia`
4194 // field byte-equal to the lifted constant (the three paired
4195 // defaults — the [`Default for RestartStrategy`] impl arm, the
4196 // struct-literal default arm here, and the
4197 // [`crate::manifest::Caixa::supervisor_view`] fold arm — cannot
4198 // silently split on any future default rebrand). Peer of the
4199 // sibling
4200 // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
4201 // + [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
4202 // byte-parity pins on the paired `MaxIntensity` + `Period` halves
4203 // of the same `SupervisorSpec::default()` composed altitude.
4204 assert_eq!(
4205 SupervisorSpec::default().estrategia(),
4206 SUPERVISOR_ESTRATEGIA_DEFAULT,
4207 );
4208 }
4209
4210 #[test]
4211 fn supervisor_spec_default_routes_through_otp_canonical_ctor() {
4212 // Composition pin: the [`Default for SupervisorSpec`] impl must
4213 // route through the substrate-canonical
4214 // [`SupervisorSpec::otp_canonical`] `pub const fn` constructor
4215 // rather than a re-hand-authored struct-literal cascade. Sharpens
4216 // the sibling per-arm
4217 // `supervisor_spec_default_*_routes_through_lifted_default` pins
4218 // from a per-field lift into a whole-struct one-source-of-truth
4219 // pin — the derived-until-now [`Default::default`] and the
4220 // [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
4221 // construction, not by coincidence.
4222 //
4223 // A future extension of the OTP-canonical baseline (a fifth
4224 // `restart_intensity` field the Erlang/OTP `#supervisor` record
4225 // grows, a per-child-cohort split of the `restart_window` /
4226 // `max_restarts` pair, an M4 `mesh.pleme.io/v1alpha1/Supervisor`
4227 // CR materializer's admission-time overlay pass) reaches both
4228 // paths through exactly one edit on
4229 // [`SupervisorSpec::otp_canonical`] — the derived path could
4230 // silently disagree with the constructor's shape on any new
4231 // field whose [`Default::default`] resolves to a different arm
4232 // than the OTP-canonical baseline the constructor names, while
4233 // this delegated impl reaches the constructor directly and
4234 // picks up every future extension by construction.
4235 //
4236 // Fourth peer on the M2 / M3 typed-slot-spec
4237 // [`Default`]-through-const-ctor fold family — sibling of the
4238 // [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
4239 // (abd52c2), [`crate::aplicacao::MeshPolicy`]
4240 // [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`]
4241 // (91641a4), and [`crate::BehaviorSpec`]
4242 // [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c)
4243 // per-`Option`-only-typed-slot folds — extended here onto the
4244 // M2 supervisor-slot [`SupervisorSpec`] whose canonical baseline
4245 // is not "everything `None`" but the Erlang/OTP-canonical
4246 // `{one_for_one, 5, 60}` worker-supervisor triple.
4247 assert_eq!(SupervisorSpec::default(), SupervisorSpec::otp_canonical());
4248 }
4249
4250 #[test]
4251 fn supervisor_spec_otp_canonical_byte_equals_default() {
4252 // Value pin: [`SupervisorSpec::otp_canonical`] must byte-equal
4253 // the hand-authored `{one_for_one, 5, 60, []}` OTP-canonical
4254 // baseline the sibling `default_has_one_for_one_and_5_restarts_in_60s`
4255 // pin already asserts against the [`Default::default`] path.
4256 // Sharpens the pair-invariant into a per-constructor pin so a
4257 // future extension of [`SupervisorSpec`] with a fifth field
4258 // whose OTP-canonical shape is non-`Default::default`-equivalent
4259 // trips at caixa-core test time rather than at a downstream
4260 // consumer that composed [`SupervisorSpec::otp_canonical`] with
4261 // [`SupervisorSpec::validate`] as its "canonical baseline
4262 // seed".
4263 let canonical = SupervisorSpec::otp_canonical();
4264 assert_eq!(canonical.estrategia, RestartStrategy::OneForOne);
4265 assert_eq!(canonical.max_restarts, 5);
4266 assert_eq!(canonical.restart_window, Some(Duration::from_secs(60)));
4267 assert!(canonical.children.is_empty());
4268 }
4269
4270 #[test]
4271 fn supervisor_spec_otp_canonical_is_usable_in_const_context() {
4272 // Const-context pin: [`SupervisorSpec::otp_canonical`] must
4273 // remain callable from a `const`-bound position so downstream
4274 // `const`-context callers wanting a canonical OTP-baseline seed
4275 // can construct one at compile time without runtime dispatch on
4276 // the derived [`Default::default`]. Peer of the sibling
4277 // `pub const fn` [`crate::LimitsSpec::empty`] /
4278 // [`crate::aplicacao::MeshPolicy::empty`] /
4279 // [`crate::BehaviorSpec::empty`] constructors on the sibling
4280 // typed-slot-spec `pub const fn` axis. If a future edit breaks
4281 // the `const`-eligibility of [`SupervisorSpec::otp_canonical`]
4282 // (a non-`const` field-default helper, a non-`const`-stable
4283 // container type promotion), this evaluation fails at
4284 // build time on this file rather than at a downstream
4285 // `const`-context call site.
4286 const CANONICAL: SupervisorSpec = SupervisorSpec::otp_canonical();
4287 assert_eq!(CANONICAL.estrategia, SUPERVISOR_ESTRATEGIA_DEFAULT);
4288 assert_eq!(CANONICAL.max_restarts, SUPERVISOR_MAX_RESTARTS_DEFAULT);
4289 assert_eq!(
4290 CANONICAL.restart_window,
4291 Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4292 );
4293 assert!(CANONICAL.children.is_empty());
4294 }
4295
4296 #[test]
4297 fn supervisor_child_restart_default_pins_otp_canonical_value() {
4298 // Pin [`SUPERVISOR_CHILD_RESTART_DEFAULT`] at
4299 // [`RestartPolicy::Permanent`] — Erlang/OTP's `permanent`
4300 // worker-child restart type (`{ChildId, StartFunc, permanent, …}`
4301 // in a `supervisor`'s `init/1` child-spec tuple), the per-child
4302 // half of the same OTP-shape supervisor-tree default set whose
4303 // per-`:supervisor` halves the sibling
4304 // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
4305 // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] /
4306 // [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] constants pin. Pinning the
4307 // arm here surfaces a future rebrand of the per-child default (an
4308 // OTP-`transient` widening once the substrate discovers clean-
4309 // completion-aware children as the more common child shape, a
4310 // per-cluster overlay the operator pins through a future
4311 // `:restart-overrides` slot the MESH-COMPOSITION §III.2
4312 // supervision-canary roadmap acknowledges) as a deliberate test
4313 // edit, not a silent contract migration. Peer of the sibling
4314 // [`supervisor_estrategia_default_pins_otp_canonical_value`] /
4315 // [`supervisor_max_restarts_default_pins_otp_canonical_value`] /
4316 // [`supervisor_restart_window_default_pins_otp_canonical_value`]
4317 // value pins on the per-`:supervisor` halves.
4318 assert_eq!(SUPERVISOR_CHILD_RESTART_DEFAULT, RestartPolicy::Permanent);
4319 }
4320
4321 #[test]
4322 fn restart_policy_default_routes_through_lifted_default() {
4323 // Composition pin: the [`Default for RestartPolicy`] impl's return
4324 // arm must route through the substrate-canonical
4325 // [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const` rather
4326 // than a raw `Self::Permanent` arm. Prior to the lift the impl
4327 // carried an inline `Self::Permanent` with no compile-time link
4328 // back to the OTP-shape supervisor-tree default set whose three
4329 // per-`:supervisor` halves already rode through lifted constants
4330 // — so a future coherent rebrand of the set would have had to
4331 // migrate three halves through typed constants and this fourth
4332 // through a raw enum arm in lockstep or the supervisor-level and
4333 // child-level defaults would silently drift apart. Byte-parity
4334 // against the lifted constant closes the split. Peer of the
4335 // sibling
4336 // [`restart_strategy_default_routes_through_lifted_default`]
4337 // composition pin on the per-`:supervisor` `:estrategia` axis.
4338 assert_eq!(RestartPolicy::default(), SUPERVISOR_CHILD_RESTART_DEFAULT);
4339 }
4340
4341 #[test]
4342 fn child_spec_serde_default_restart_routes_through_lifted_default() {
4343 // Composition pin: the serde-side `#[serde(default)]` on
4344 // [`ChildSpec::restart`] — the wire-format author-omitted
4345 // `:children :restart` arm — must resolve onto the substrate-
4346 // canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const`
4347 // (via the [`Default for RestartPolicy`] impl the sibling
4348 // `restart_policy_default_routes_through_lifted_default` pin
4349 // already routes onto the constant). Structurally: a `ChildSpec`
4350 // deserialized from a payload that omits the `restart` key must
4351 // yield a `restart` field byte-equal to the lifted constant, so
4352 // the wire-format author-omitted arm and the
4353 // [`RestartPolicy::default`] impl arm cannot silently split on any
4354 // future default rebrand. Peer of the sibling
4355 // [`supervisor_spec_default_estrategia_routes_through_lifted_default`]
4356 // / [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
4357 // / [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
4358 // byte-parity pins on the per-`:supervisor` halves of the same
4359 // author-omitted-slot resolution surface.
4360 let omitted: ChildSpec = serde_json::from_str(r#"{"caixa":"worker","versao":"^0.1"}"#)
4361 .expect("ChildSpec must deserialize with the restart key omitted");
4362 assert_eq!(
4363 omitted.restart(),
4364 SUPERVISOR_CHILD_RESTART_DEFAULT,
4365 "an author-omitted :children :restart slot must degrade onto \
4366 the SUPERVISOR_CHILD_RESTART_DEFAULT typed pub const (got \
4367 {:?}, expected {:?})",
4368 omitted.restart(),
4369 SUPERVISOR_CHILD_RESTART_DEFAULT,
4370 );
4371 }
4372
4373 #[test]
4374 fn supervisor_max_restarts_cap_pins_canonical_value() {
4375 // The SUPERVISOR_MAX_RESTARTS_MAX constant pins the value at
4376 // 1000 — the same ceiling the peer
4377 // POLICY_BREAKER_MAX_FAILURES_MAX cap carries on the
4378 // `:politicas :circuit-breaker :max-failures` axis (both are
4379 // "trip the next-higher protection layer after N events in a
4380 // rolling window" counters with identical
4381 // degenerate-at-the-high-end shape; uniform top edge so the
4382 // M4 CR materializers and the wasm-operator reconciler reach
4383 // for either field knowing the value is in `1..=1000`). Two
4384 // orders of magnitude above every documented Erlang/OTP /
4385 // Elixir / Riak Core / RabbitMQ production-playbook
4386 // recommendation band and below the clearly-pathological
4387 // "effectively no escalation" floor (10_000, 100_000,
4388 // u32::MAX). Pinning the literal value here surfaces a future
4389 // drift (a relaxation to 10_000, a tightening to 100) as a
4390 // deliberate test edit, not a silent contract narrowing.
4391 assert_eq!(SUPERVISOR_MAX_RESTARTS_MAX, 1000);
4392 }
4393
4394 #[test]
4395 fn validate_rejects_empty_child_name() {
4396 let s = SupervisorSpec {
4397 children: vec![child("", "^0.1", RestartPolicy::Permanent)],
4398 ..SupervisorSpec::default()
4399 };
4400 assert_eq!(s.validate().unwrap_err(), SupervisorError::EmptyChildName);
4401 }
4402
4403 #[test]
4404 fn validate_rejects_empty_child_version() {
4405 let s = SupervisorSpec {
4406 children: vec![child("w", "", RestartPolicy::Permanent)],
4407 ..SupervisorSpec::default()
4408 };
4409 assert!(matches!(
4410 s.validate().unwrap_err(),
4411 SupervisorError::EmptyChildVersion { .. }
4412 ));
4413 }
4414
4415 // ── value-shape: parse-as-VersionReq on :children :versao ─────────────
4416
4417 #[test]
4418 fn validate_rejects_invalid_child_versao_requirement() {
4419 // The fail-before-pass-after pin: a non-empty but malformed
4420 // semver requirement (`"^bad-version"`) silently passed
4421 // `validate()` on every pre-gate codebase because the prior
4422 // shape only refused the empty string. The parse failure
4423 // surfaced far downstream at lacre-resolve time with a
4424 // `semver::Error` that didn't name which `:children` entry
4425 // carried the typo. The new gate moves the check to caixa-build
4426 // time at the source caixa.lisp — the third `:versao` typed
4427 // axis (`:children`) joins `:deps` and `:membros` (9888b13) at
4428 // structural parity.
4429 let s = SupervisorSpec {
4430 children: vec![
4431 child("worker", "^0.1", RestartPolicy::Permanent),
4432 child("cache", "^bad-version", RestartPolicy::Transient),
4433 ],
4434 ..SupervisorSpec::default()
4435 };
4436 let err = s.validate().unwrap_err();
4437 assert!(
4438 matches!(
4439 err,
4440 SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
4441 if caixa == "cache" && versao == "^bad-version"
4442 ),
4443 "got {err:?}"
4444 );
4445 }
4446
4447 #[test]
4448 fn validate_rejects_child_versao_with_double_caret_typo() {
4449 // `"^^0.1"` is the canonical doubled-caret typo — looks
4450 // Cargo-shaped on first glance but fails the parser because
4451 // semver doesn't accept stacked operators. Pin this
4452 // adjacent-shape footgun explicitly so a future relaxation that
4453 // accepts "looks-canonical-but-isn't" forms surfaces here.
4454 let s = SupervisorSpec {
4455 children: vec![child("worker", "^^0.1", RestartPolicy::Permanent)],
4456 ..SupervisorSpec::default()
4457 };
4458 let err = s.validate().unwrap_err();
4459 assert!(
4460 matches!(
4461 err,
4462 SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
4463 if caixa == "worker" && versao == "^^0.1"
4464 ),
4465 "got {err:?}"
4466 );
4467 }
4468
4469 #[test]
4470 fn validate_rejects_child_versao_with_v_prefixed_tag() {
4471 // `"v0.1"` is the canonical "git-tag-shape leaking into the
4472 // semver requirement slot" typo — an author copies the
4473 // publish-side git-tag string verbatim into `:versao`, but
4474 // Cargo's semver parser rejects the leading `v`. Same
4475 // adjacent-shape footgun pinned for `:membros :versao`
4476 // (9888b13).
4477 let s = SupervisorSpec {
4478 children: vec![child("worker", "v0.1", RestartPolicy::Permanent)],
4479 ..SupervisorSpec::default()
4480 };
4481 let err = s.validate().unwrap_err();
4482 assert!(
4483 matches!(
4484 err,
4485 SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
4486 if caixa == "worker" && versao == "v0.1"
4487 ),
4488 "got {err:?}"
4489 );
4490 }
4491
4492 #[test]
4493 fn validate_accepts_canonical_child_versao_forms() {
4494 // The Cargo-shaped requirement forms `:deps :versao` and
4495 // `:membros :versao` already accept via
4496 // `crate::parse_requirement` must pass the children gate
4497 // without re-validating at the resolver layer. Pin every leg so
4498 // a future tightening of the canonical set surfaces here as a
4499 // test failure.
4500 for form in [
4501 "^0.1", // caret — minor-range pin (the most common shape)
4502 "~0.1.2", // tilde — patch-range pin
4503 "0.1.0", // exact — single-version pin
4504 "*", // wildcard — any version (semver::VersionReq::STAR)
4505 ">=0.1, <2", // multi-range — comma-separated comparators
4506 ] {
4507 let s = SupervisorSpec {
4508 children: vec![child("worker", form, RestartPolicy::Permanent)],
4509 ..SupervisorSpec::default()
4510 };
4511 s.validate()
4512 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
4513 }
4514 }
4515
4516 #[test]
4517 fn child_versao_empty_takes_precedence_over_invalid() {
4518 // Order pin: the existing `EmptyChildVersion` diagnostic (which
4519 // doesn't try to parse) fires before the new
4520 // `ChildVersaoInvalid` parse-side diagnostic, so an empty
4521 // `:versao` keeps its narrower error message —
4522 // `parse_requirement` would also reject `""`, but the
4523 // empty-string arm is the more self-locating diagnostic for the
4524 // author. Same ordering discipline as
4525 // `membro_versao_empty_takes_precedence_over_invalid` in
4526 // aplicacao.rs.
4527 let s = SupervisorSpec {
4528 children: vec![child("worker", "", RestartPolicy::Permanent)],
4529 ..SupervisorSpec::default()
4530 };
4531 let err = s.validate().unwrap_err();
4532 assert!(
4533 matches!(err, SupervisorError::EmptyChildVersion { ref caixa } if caixa == "worker"),
4534 "got {err:?}"
4535 );
4536 }
4537
4538 #[test]
4539 fn child_versao_invalid_fires_before_duplicate_check() {
4540 // Order pin: a malformed requirement on a non-duplicate entry
4541 // surfaces *its own* diagnostic (which names the offending
4542 // `:versao` string), even when a later entry would otherwise
4543 // collapse onto an earlier name. The per-entry shape gate runs
4544 // inline before the duplicate-key insert — parallel to
4545 // `membro_versao_invalid_fires_before_duplicate_check` in
4546 // aplicacao.rs and the b0c8389 / c4213a4 ordering discipline.
4547 let s = SupervisorSpec {
4548 children: vec![
4549 child("worker", "^bad", RestartPolicy::Permanent),
4550 child("cache", "^0.1", RestartPolicy::Transient),
4551 child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
4552 ],
4553 ..SupervisorSpec::default()
4554 };
4555 let err = s.validate().unwrap_err();
4556 assert!(
4557 matches!(
4558 err,
4559 SupervisorError::ChildVersaoInvalid { ref caixa, .. } if caixa == "worker"
4560 ),
4561 "got {err:?}"
4562 );
4563 }
4564
4565 #[test]
4566 fn child_versao_invalid_diagnostic_carries_offending_versao() {
4567 // The diagnostic-shape pin: the error names the offending
4568 // `:versao` value verbatim so the author can grep their
4569 // caixa.lisp without re-running the build, and carries a
4570 // non-empty `reason` from `semver::VersionReq::parse` so the
4571 // parser's own wording flows through to the diagnostic.
4572 let s = SupervisorSpec {
4573 children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
4574 ..SupervisorSpec::default()
4575 };
4576 let err = s.validate().unwrap_err();
4577 let SupervisorError::ChildVersaoInvalid {
4578 caixa,
4579 versao,
4580 reason,
4581 } = err
4582 else {
4583 panic!("expected ChildVersaoInvalid, got other variant");
4584 };
4585 assert_eq!(caixa, "worker");
4586 assert_eq!(versao, "not-a-req");
4587 assert!(
4588 !reason.is_empty(),
4589 "ChildVersaoInvalid `reason` must carry the parser's wording verbatim"
4590 );
4591 }
4592
4593 // ── value-shape: DNS-1123 label rule on :children :caixa ──────────────
4594
4595 #[test]
4596 fn validate_rejects_child_caixa_with_uppercase() {
4597 // The canonical "I copied the Servico's display name verbatim"
4598 // typo — child caixa names are lowercase per K8s DNS-1123 label
4599 // rule. The diagnostic names the offending name and suggests the
4600 // lower-cased fix in one edit, mirroring the
4601 // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0).
4602 let s = SupervisorSpec {
4603 children: vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
4604 ..SupervisorSpec::default()
4605 };
4606 let err = s.validate().unwrap_err();
4607 let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
4608 panic!("expected ChildCaixaInvalid, got other variant");
4609 };
4610 assert_eq!(caixa, "Worker");
4611 assert!(
4612 reason.contains("uppercase"),
4613 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
4614 );
4615 assert!(
4616 reason.contains("\"worker\""),
4617 "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
4618 );
4619 }
4620
4621 #[test]
4622 fn validate_rejects_child_caixa_with_underscore() {
4623 // The canonical "I'm thinking of a Python module / Postgres
4624 // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
4625 // label schema. K8s rejects `metadata.name: my_worker` at
4626 // admission time with an opaque `field is invalid` (no source-
4627 // citing diagnostic). The gate moves it to caixa-build time.
4628 let s = SupervisorSpec {
4629 children: vec![child("my_worker", "^0.1", RestartPolicy::Permanent)],
4630 ..SupervisorSpec::default()
4631 };
4632 let err = s.validate().unwrap_err();
4633 assert!(
4634 matches!(
4635 err,
4636 SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
4637 if caixa == "my_worker" && reason.contains('_')
4638 ),
4639 "got {err:?}"
4640 );
4641 }
4642
4643 #[test]
4644 fn validate_rejects_child_caixa_with_dot() {
4645 // A `:children :caixa` entry is a single DNS-1123 label, not a
4646 // subdomain. The K8s Service / ComputeUnit `metadata.name` rules
4647 // forbid dots. Same shape as `rejects_membro_caixa_with_dot`
4648 // (3f9d7a0) on the peer name axis.
4649 let s = SupervisorSpec {
4650 children: vec![child("team.worker", "^0.1", RestartPolicy::Permanent)],
4651 ..SupervisorSpec::default()
4652 };
4653 let err = s.validate().unwrap_err();
4654 assert!(
4655 matches!(
4656 err,
4657 SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
4658 if caixa == "team.worker" && reason.contains('.')
4659 ),
4660 "got {err:?}"
4661 );
4662 }
4663
4664 #[test]
4665 fn validate_rejects_child_caixa_with_leading_hyphen() {
4666 // DNS-1123 / DNS-1035 boundary rule: labels must start and end
4667 // with an alphanumeric. The K8s apiserver rejects `-worker`
4668 // outright; the renderer would emit a `metadata.name: "-worker"`
4669 // that fails admission far from the source caixa.lisp.
4670 let s = SupervisorSpec {
4671 children: vec![child("-worker", "^0.1", RestartPolicy::Permanent)],
4672 ..SupervisorSpec::default()
4673 };
4674 let err = s.validate().unwrap_err();
4675 assert!(
4676 matches!(
4677 err,
4678 SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
4679 if caixa == "-worker" && reason.contains("start and end")
4680 ),
4681 "got {err:?}"
4682 );
4683 }
4684
4685 #[test]
4686 fn validate_rejects_child_caixa_with_trailing_hyphen() {
4687 // The symmetric arm of the boundary rule. Pin separately so
4688 // both ends of the label are covered against a future relaxation
4689 // that only checks one boundary.
4690 let s = SupervisorSpec {
4691 children: vec![child("worker-", "^0.1", RestartPolicy::Permanent)],
4692 ..SupervisorSpec::default()
4693 };
4694 let err = s.validate().unwrap_err();
4695 assert!(
4696 matches!(
4697 err,
4698 SupervisorError::ChildCaixaInvalid { ref caixa, .. }
4699 if caixa == "worker-"
4700 ),
4701 "got {err:?}"
4702 );
4703 }
4704
4705 #[test]
4706 fn validate_rejects_child_caixa_with_unicode() {
4707 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
4708 // (`xn--…`) by the author before it reaches K8s. The byte-by-
4709 // byte ASCII validity check rejects multi-byte UTF-8 sequences
4710 // by the first byte that fails the `[a-z0-9-]` predicate.
4711 let s = SupervisorSpec {
4712 children: vec![child("café", "^0.1", RestartPolicy::Permanent)],
4713 ..SupervisorSpec::default()
4714 };
4715 let err = s.validate().unwrap_err();
4716 assert!(
4717 matches!(
4718 err,
4719 SupervisorError::ChildCaixaInvalid { ref caixa, .. }
4720 if caixa == "café"
4721 ),
4722 "got {err:?}"
4723 );
4724 }
4725
4726 #[test]
4727 fn validate_rejects_child_caixa_with_whitespace() {
4728 // Whitespace is the canonical "I pasted from a sketch / doc"
4729 // footgun. The apiserver rejects every `metadata.name` value
4730 // carrying whitespace; pin the gate fires at the right boundary.
4731 let s = SupervisorSpec {
4732 children: vec![child("my worker", "^0.1", RestartPolicy::Permanent)],
4733 ..SupervisorSpec::default()
4734 };
4735 let err = s.validate().unwrap_err();
4736 assert!(
4737 matches!(
4738 err,
4739 SupervisorError::ChildCaixaInvalid { ref caixa, .. }
4740 if caixa == "my worker"
4741 ),
4742 "got {err:?}"
4743 );
4744 }
4745
4746 #[test]
4747 fn validate_rejects_child_caixa_too_long() {
4748 // The 64-byte boundary pin. DNS-1123 / DNS-1035 cap labels at
4749 // 63 bytes; the K8s apiserver rejects every `metadata.name`
4750 // axis over the limit at admission time. The diagnostic names
4751 // both the cap and the actual length so the author can shorten
4752 // in one edit, mirroring `rejects_membro_caixa_too_long`
4753 // (3f9d7a0) and `rejects_placement_cluster_too_long` (6cbb900).
4754 let too_long = "a".repeat(64);
4755 let s = SupervisorSpec {
4756 children: vec![child(&too_long, "^0.1", RestartPolicy::Permanent)],
4757 ..SupervisorSpec::default()
4758 };
4759 let err = s.validate().unwrap_err();
4760 let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
4761 panic!("expected ChildCaixaInvalid, got other variant");
4762 };
4763 assert_eq!(caixa, too_long);
4764 assert!(
4765 reason.contains("63"),
4766 "diagnostic must name the 63-byte cap (got: {reason:?})"
4767 );
4768 assert!(
4769 reason.contains("64"),
4770 "diagnostic must name the actual length (got: {reason:?})"
4771 );
4772 }
4773
4774 #[test]
4775 fn child_caixa_max_length_validates() {
4776 // The 63-byte boundary control pin — exactly-at-the-cap is
4777 // accepted, mirroring `membro_caixa_max_length_validates`
4778 // (3f9d7a0) and `placement_cluster_max_length_validates`
4779 // (6cbb900). Pinned separately so a future off-by-one tightening
4780 // surfaces here.
4781 let max_label = "a".repeat(63);
4782 let s = SupervisorSpec {
4783 children: vec![child(&max_label, "^0.1", RestartPolicy::Permanent)],
4784 ..SupervisorSpec::default()
4785 };
4786 s.validate().unwrap();
4787 }
4788
4789 #[test]
4790 fn validate_accepts_canonical_child_caixa_forms() {
4791 // The realistic shapes a supervised child's `:caixa` carries —
4792 // single-word `worker`, version-suffixed `cache-v2`, single-char
4793 // `a`, two-char `db`, digit-start `2-pool`, longer hyphen-joined
4794 // `payment-retry`, all-digit `0`. Pin every leg so a future
4795 // tightening (e.g. requiring a leading lowercase letter) surfaces
4796 // here as a test failure. Mirrors `accepts_canonical_membro_caixa_forms`
4797 // (3f9d7a0) and `accepts_canonical_placement_cluster_forms`
4798 // (6cbb900).
4799 for form in [
4800 "worker",
4801 "cache-v2",
4802 "a",
4803 "db",
4804 "2-pool",
4805 "payment-retry",
4806 "0",
4807 ] {
4808 let s = SupervisorSpec {
4809 children: vec![child(form, "^0.1", RestartPolicy::Permanent)],
4810 ..SupervisorSpec::default()
4811 };
4812 s.validate()
4813 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
4814 }
4815 }
4816
4817 #[test]
4818 fn child_caixa_empty_takes_precedence_over_invalid() {
4819 // Order pin: the existing `EmptyChildName` diagnostic (which
4820 // doesn't try to parse the DNS-1123 shape) fires before the new
4821 // `ChildCaixaInvalid` per-axis gate, so an empty `:caixa` keeps
4822 // its narrower error message — `is_dns_1123_label` would reject
4823 // the empty string too (boundary check on the first byte), but
4824 // the empty-string arm is the more self-locating diagnostic for
4825 // the author. Same ordering discipline as
4826 // `membro_caixa_empty_takes_precedence_over_invalid` in
4827 // aplicacao.rs.
4828 let s = SupervisorSpec {
4829 children: vec![child("", "^0.1", RestartPolicy::Permanent)],
4830 ..SupervisorSpec::default()
4831 };
4832 let err = s.validate().unwrap_err();
4833 assert_eq!(err, SupervisorError::EmptyChildName);
4834 }
4835
4836 #[test]
4837 fn child_caixa_invalid_fires_before_versao_check() {
4838 // Order pin: the per-axis shape gate runs inline before the
4839 // per-entry versao check, so a malformed `:caixa` on an entry
4840 // whose `:versao` would also fail surfaces the more self-
4841 // locating name-axis diagnostic first. Parallel to
4842 // `membro_versao_invalid_fires_before_duplicate_check` (9888b13)
4843 // and `placement_cluster_invalid_fires_before_duplicate_check`
4844 // (6cbb900).
4845 let s = SupervisorSpec {
4846 children: vec![child("My_Worker", "", RestartPolicy::Permanent)],
4847 ..SupervisorSpec::default()
4848 };
4849 let err = s.validate().unwrap_err();
4850 assert!(
4851 matches!(
4852 err,
4853 SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "My_Worker"
4854 ),
4855 "got {err:?}"
4856 );
4857 }
4858
4859 #[test]
4860 fn child_caixa_invalid_fires_before_duplicate_check() {
4861 // Order pin: a malformed name on a non-duplicate entry surfaces
4862 // its own diagnostic, even when a later entry would otherwise
4863 // collapse onto an earlier name. The per-entry shape gate runs
4864 // inline before the duplicate-key HashSet insert, mirroring
4865 // `placement_cluster_invalid_fires_before_duplicate_check`
4866 // (6cbb900).
4867 let s = SupervisorSpec {
4868 children: vec![
4869 child("Worker", "^0.1", RestartPolicy::Permanent),
4870 child("cache", "^0.1", RestartPolicy::Transient),
4871 child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
4872 ],
4873 ..SupervisorSpec::default()
4874 };
4875 let err = s.validate().unwrap_err();
4876 assert!(
4877 matches!(
4878 err,
4879 SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "Worker"
4880 ),
4881 "got {err:?}"
4882 );
4883 }
4884
4885 #[test]
4886 fn child_caixa_invalid_diagnostic_carries_offending_caixa() {
4887 // The diagnostic-shape pin: the error names the offending
4888 // `:caixa` verbatim plus a non-empty parser-shaped `reason` so
4889 // the author can grep their caixa.lisp without re-running the
4890 // build. Mirrors the diagnostic-shape sweep on every prior
4891 // value-shape gate (3f9d7a0, 6cbb900, c7d05ec).
4892 let s = SupervisorSpec {
4893 children: vec![child("My_Worker", "^0.1", RestartPolicy::Permanent)],
4894 ..SupervisorSpec::default()
4895 };
4896 let err = s.validate().unwrap_err();
4897 let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
4898 panic!("expected ChildCaixaInvalid, got other variant");
4899 };
4900 assert_eq!(caixa, "My_Worker");
4901 assert!(
4902 !reason.is_empty(),
4903 "ChildCaixaInvalid `reason` must carry the parser's wording verbatim"
4904 );
4905 }
4906
4907 // ── value-shape: zero restart_window + duplicate child names ──────────
4908
4909 #[test]
4910 fn validate_accepts_none_restart_window() {
4911 // Omitted `:restart-window` is the "never reset" sentinel —
4912 // valid by design. Mirrors :limits axes where None = unbounded.
4913 let s = SupervisorSpec {
4914 restart_window: None,
4915 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4916 ..SupervisorSpec::default()
4917 };
4918 s.validate().unwrap();
4919 }
4920
4921 #[test]
4922 fn validate_rejects_zero_restart_window() {
4923 // Same "0 means the opposite of what you think" footgun closed
4924 // for :politicas :timeout (Envoy treats 0s as infinite) and
4925 // :limits :wall-clock (wasmtime traps before the call starts).
4926 // Erlang/OTP's MaxIntensity/Period requires Period > 0.
4927 let s = SupervisorSpec {
4928 restart_window: Some(Duration::ZERO),
4929 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4930 ..SupervisorSpec::default()
4931 };
4932 assert_eq!(
4933 s.validate().unwrap_err(),
4934 SupervisorError::RestartWindowZero
4935 );
4936 }
4937
4938 // ── value-shape: integer-ms canonical-form on :restart-window ─────────
4939 //
4940 // The fourth (and last) typed-`Duration` axis in caixa-core to get
4941 // the integer-millisecond canonical-form gate — peer with
4942 // `:limits :wall-clock` (82fc3ef), `:politicas :timeout` (a4ae535),
4943 // and `:politicas :circuit-breaker :window` (a4ae535). The serde
4944 // path is already gated at the shared codec layer (see
4945 // `restart_window_serde_rejects_fractional_seconds`); this arm
4946 // closes the programmatic-struct-literal path the codec gate can't
4947 // see.
4948
4949 #[test]
4950 fn validate_rejects_sub_millisecond_restart_window() {
4951 // The fail-before-pass-after pin: a programmatic
4952 // `Duration::from_micros(1500)` (= 1_500_000 ns) silently passed
4953 // `validate` on every pre-gate codebase, then truncated to
4954 // `as_millis() == 1` on first serialize — the shared codec
4955 // emits `"1ms"`, parses it back to `Duration::from_millis(1)` =
4956 // 1_000_000 ns, the typed `restart_window` no longer matches
4957 // its rendered form.
4958 let s = SupervisorSpec {
4959 restart_window: Some(Duration::from_micros(1500)),
4960 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4961 ..SupervisorSpec::default()
4962 };
4963 match s.validate().unwrap_err() {
4964 SupervisorError::RestartWindowNotCanonical { window } => {
4965 assert_eq!(window, Duration::from_micros(1500));
4966 }
4967 other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
4968 }
4969 }
4970
4971 #[test]
4972 fn validate_rejects_one_nanosecond_restart_window() {
4973 // The far-sub-ms case: `Duration::from_nanos(1)` is non-zero
4974 // (so `RestartWindowZero` doesn't fire) but `as_millis() == 0`,
4975 // so the shared codec emits the literal `"0s"` — the next
4976 // serde round-trip would parse back to `Duration::ZERO`, which
4977 // the `RestartWindowZero` arm then rejects on re-validate. The
4978 // canonical-form gate at this layer surfaces a self-locating
4979 // diagnostic naming the offending Duration verbatim rather
4980 // than a downstream `RestartWindowZero` whose remediation
4981 // points at omitting the slot.
4982 let s = SupervisorSpec {
4983 restart_window: Some(Duration::from_nanos(1)),
4984 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4985 ..SupervisorSpec::default()
4986 };
4987 match s.validate().unwrap_err() {
4988 SupervisorError::RestartWindowNotCanonical { window } => {
4989 assert_eq!(window, Duration::from_nanos(1));
4990 }
4991 other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
4992 }
4993 }
4994
4995 #[test]
4996 fn validate_rejects_nanosecond_past_canonical_boundary_restart_window() {
4997 // The 1-ns-past-1ms boundary case: a `Duration` carrying
4998 // 1_000_001 ns is structurally past the integer-ms granularity
4999 // floor — `subsec_nanos() % 1_000_000 == 1`. The codec round-
5000 // trip would truncate to `1ms` and the consumer would observe
5001 // a 1-ns drift on every emit. Same boundary the peer
5002 // `validate_rejects_nanosecond_past_canonical_boundary` test
5003 // in limits.rs pins for the `:limits :wall-clock` axis.
5004 let w = Duration::from_nanos(1_000_001);
5005 let s = SupervisorSpec {
5006 restart_window: Some(w),
5007 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5008 ..SupervisorSpec::default()
5009 };
5010 assert_eq!(
5011 s.validate().unwrap_err(),
5012 SupervisorError::RestartWindowNotCanonical { window: w }
5013 );
5014 }
5015
5016 #[test]
5017 fn validate_accepts_integer_millisecond_restart_window_values() {
5018 // The positive-control sweep: every `Duration` the shared
5019 // codec can round-trip losslessly — the canonical
5020 // `<integer>{ms,s,m,h}` set the codec's `render` / `parse`
5021 // pair emits and accepts — passes `validate` without
5022 // surfacing the new canonical-form arm. Mirrors
5023 // `validate_accepts_integer_millisecond_wall_clock_values` on
5024 // the sibling `:limits :wall-clock` axis.
5025 for w in [
5026 Duration::from_millis(1),
5027 Duration::from_millis(500),
5028 Duration::from_millis(1500),
5029 Duration::from_secs(1),
5030 Duration::from_secs(30),
5031 Duration::from_secs(60),
5032 Duration::from_secs(120),
5033 Duration::from_secs(3600),
5034 ] {
5035 let s = SupervisorSpec {
5036 restart_window: Some(w),
5037 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5038 ..SupervisorSpec::default()
5039 };
5040 s.validate()
5041 .unwrap_or_else(|e| panic!("integer-ms {w:?} must validate, got {e:?}"));
5042 }
5043 }
5044
5045 #[test]
5046 fn validate_restart_window_zero_takes_precedence_over_canonical_gate() {
5047 // Cross-arm ordering pin: `Duration::ZERO` has
5048 // `subsec_nanos() == 0` and would otherwise pass the
5049 // canonical-form arm — the zero-floor arm must fire first so
5050 // the more self-locating `RestartWindowZero` diagnostic (with
5051 // its omit-axis remediation directly named) leads. Same
5052 // posture every peer zero-then-shape gate uses
5053 // (`WallClockZero` → `WallClockNotCanonical`,
5054 // `PolicyTimeoutZero` → `PolicyTimeoutNotCanonical`,
5055 // `PolicyBreakerZeroWindow` → `PolicyBreakerWindowNotCanonical`).
5056 let s = SupervisorSpec {
5057 restart_window: Some(Duration::ZERO),
5058 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5059 ..SupervisorSpec::default()
5060 };
5061 assert_eq!(
5062 s.validate().unwrap_err(),
5063 SupervisorError::RestartWindowZero
5064 );
5065 }
5066
5067 #[test]
5068 fn restart_window_canonical_diagnostic_carries_offending_duration() {
5069 // Diagnostic-shape pin: the canonical-form arm names the
5070 // offending `Duration` verbatim so the author's grep lands on
5071 // the field's value, not a generic "duration not canonical"
5072 // message. Same shape every other typed-canonical-form arm
5073 // on this surface carries (`WallClockNotCanonical` carries
5074 // the offending `Duration` verbatim,
5075 // `PolicyTimeoutNotCanonical` carries the offending
5076 // `Duration` verbatim).
5077 let w = Duration::from_micros(500);
5078 let s = SupervisorSpec {
5079 restart_window: Some(w),
5080 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5081 ..SupervisorSpec::default()
5082 };
5083 let err = s.validate().unwrap_err();
5084 let msg = err.to_string();
5085 assert!(
5086 msg.contains("500"),
5087 "diagnostic must carry the offending magnitude verbatim (got {msg:?})"
5088 );
5089 assert!(
5090 msg.contains("sub-millisecond"),
5091 "diagnostic must name the sub-millisecond residue class (got {msg:?})"
5092 );
5093 }
5094
5095 #[test]
5096 fn restart_window_validated_value_round_trips_through_codec() {
5097 // The structural property the canonical-ms gate enforces:
5098 // every `SupervisorSpec::restart_window` past
5099 // `SupervisorSpec::validate` round-trips losslessly through
5100 // the shared duration codec (serialize → string →
5101 // deserialize → equal value). Pin this end-to-end so a future
5102 // change to either side (the validate gate's accepted
5103 // granularity, the codec's parse/render unit set) that breaks
5104 // the alignment surfaces here. Peer of
5105 // `wall_clock_validated_value_round_trips_through_codec` on
5106 // the sibling `:limits :wall-clock` axis.
5107 for w in [
5108 Duration::from_millis(1),
5109 Duration::from_millis(1500),
5110 Duration::from_secs(30),
5111 Duration::from_secs(3600),
5112 ] {
5113 let s = SupervisorSpec {
5114 restart_window: Some(w),
5115 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5116 ..SupervisorSpec::default()
5117 };
5118 s.validate().unwrap();
5119 let json = serde_json::to_string(&s).unwrap();
5120 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5121 assert_eq!(back.restart_window, Some(w));
5122 }
5123 }
5124
5125 // ── value-shape: upper cap on :restart-window ─────────────────────────
5126 //
5127 // The fourth (and last) typed-`Duration` axis in caixa-core to get
5128 // the 1h upper cap — peer with `:limits :wall-clock` (51e0dbd),
5129 // `:politicas :timeout` (2e8ee7e), and `:politicas
5130 // :circuit-breaker :window` (379a814). Brackets the typed
5131 // `:restart-window` axis structurally: every validated value lies
5132 // in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`, integer-millisecond
5133 // granularity, closing the
5134 // rolling-window-degenerates-to-lifetime-counter footgun the prior
5135 // zero-floor-and-canonical-form-only checks left open.
5136
5137 #[test]
5138 fn validate_rejects_restart_window_above_cap() {
5139 // The fail-before-pass-after pin: 3601s = 1h + 1s is
5140 // structurally one canonical-tick past the
5141 // [`SUPERVISOR_RESTART_WINDOW_MAX`] ceiling (1h = 3600s) — an
5142 // integer-millisecond magnitude the canonical-form arm above
5143 // accepts cleanly, that the shared duration codec round-trips
5144 // losslessly as `"3601s"`, and that silently passed validate on
5145 // every pre-gate codebase because the typed slot's only checks
5146 // were the zero-floor and canonical-form arms. The runtime
5147 // substrate consuming the value (Erlang/OTP's MaxIntensity/
5148 // Period reconciler, the future wasm-operator's per-supervisor
5149 // restart-intensity counter) reaches for a `Duration` so long
5150 // no realistic restart-recovery pattern resets the counter,
5151 // far from the source caixa.lisp.
5152 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
5153 let s = SupervisorSpec {
5154 restart_window: Some(w),
5155 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5156 ..SupervisorSpec::default()
5157 };
5158 assert_eq!(
5159 s.validate().unwrap_err(),
5160 SupervisorError::RestartWindowExceedsCap { window: w }
5161 );
5162 }
5163
5164 #[test]
5165 fn validate_rejects_restart_window_one_millisecond_above_cap() {
5166 // Boundary case: exactly 1ms past the cap (the granularity the
5167 // canonical-form gate enforces). Catches a future "strictly
5168 // less than" half-measure and pins the diagnostic to name the
5169 // offending `Duration` verbatim. Peer of
5170 // `validate_rejects_wall_clock_one_millisecond_above_cap` /
5171 // `rejects_policy_timeout_one_millisecond_above_cap` /
5172 // `rejects_circuit_breaker_window_one_millisecond_above_cap`
5173 // on the sibling typed-`Duration` axes' top edges.
5174 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
5175 let s = SupervisorSpec {
5176 restart_window: Some(w),
5177 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5178 ..SupervisorSpec::default()
5179 };
5180 assert_eq!(
5181 s.validate().unwrap_err(),
5182 SupervisorError::RestartWindowExceedsCap { window: w }
5183 );
5184 }
5185
5186 #[test]
5187 fn validate_rejects_restart_window_far_above_cap() {
5188 // The "obvious authoring footgun" case: a `(:restart-window "24h")`,
5189 // `(:restart-window "7d")`, or any "I want a lifetime counter
5190 // but wrote a `<integer>h` magnitude anyway" typo — values the
5191 // canonical-form arm accepts as integer-millisecond magnitudes,
5192 // the codec round-trips losslessly through serde, but the
5193 // operator's `MaxIntensity / Period` reconciler cannot honor
5194 // as a meaningful rolling window. Until this gate landed
5195 // validate accepted them. Pin the common above-cap values (24h,
5196 // 7d, ~11.5d) so a future relaxation that drops the upper bound
5197 // surfaces here.
5198 for w in [
5199 Duration::from_secs(86_400), // 24h
5200 Duration::from_secs(604_800), // 7d
5201 Duration::from_secs(1_000_000), // ~11.5 days
5202 ] {
5203 let s = SupervisorSpec {
5204 restart_window: Some(w),
5205 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5206 ..SupervisorSpec::default()
5207 };
5208 assert_eq!(
5209 s.validate().unwrap_err(),
5210 SupervisorError::RestartWindowExceedsCap { window: w }
5211 );
5212 }
5213 }
5214
5215 #[test]
5216 fn validate_accepts_restart_window_at_cap() {
5217 // The boundary value — exactly [`SUPERVISOR_RESTART_WINDOW_MAX`]
5218 // (1h) — must validate. The cap is inclusive on the top edge,
5219 // matching the [`crate::LIMITS_WALL_CLOCK_MAX`] /
5220 // [`crate::POLICY_TIMEOUT_MAX`] /
5221 // [`crate::POLICY_BREAKER_WINDOW_MAX`] discipline on the sibling
5222 // capped axes. Pin the boundary explicitly so a future
5223 // off-by-one tightening (`>= SUPERVISOR_RESTART_WINDOW_MAX`
5224 // instead of `>`) surfaces here as a test failure rather than a
5225 // silent contract narrowing.
5226 let s = SupervisorSpec {
5227 restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
5228 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5229 ..SupervisorSpec::default()
5230 };
5231 s.validate()
5232 .expect("restart_window == SUPERVISOR_RESTART_WINDOW_MAX must validate");
5233 }
5234
5235 #[test]
5236 fn validate_accepts_restart_window_typical_values() {
5237 // The documented Erlang/OTP / Elixir / Riak Core / RabbitMQ
5238 // per-supervisor production-playbook band positive-control
5239 // sweep — every value Learn You Some Erlang's `{intensity, 5,
5240 // 60}` worker-supervisor `Period = 60s` default, Elixir's
5241 // `Supervisor` `max_seconds: 5` default, OTP's `supervisor`
5242 // callback module `MaxT = 5..=60` typical, Riak Core's `MaxT ∈
5243 // 10s..=300s`, and RabbitMQ broker-supervisor `MaxT = 5s`
5244 // default recommend (5s..=300s) must pass, plus a sweep
5245 // through the long-tail-flaky-pool band (5m, 15m, 30m, 1h) the
5246 // cap accepts. Mirrors `validate_accepts_wall_clock_typical_values`
5247 // on the sibling `:limits :wall-clock` axis.
5248 for w in [
5249 Duration::from_millis(1),
5250 Duration::from_millis(500),
5251 Duration::from_secs(1),
5252 Duration::from_secs(5), // RabbitMQ broker-supervisor default
5253 Duration::from_secs(10), // Riak Core lower
5254 Duration::from_secs(30),
5255 Duration::from_secs(60), // Learn You Some Erlang default
5256 Duration::from_secs(120), // OTP supervisor MaxT typical
5257 Duration::from_secs(300), // Riak Core upper
5258 Duration::from_secs(900), // 15m
5259 Duration::from_secs(1800),
5260 Duration::from_secs(3600), // exactly 1h, the cap
5261 ] {
5262 let s = SupervisorSpec {
5263 restart_window: Some(w),
5264 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5265 ..SupervisorSpec::default()
5266 };
5267 s.validate()
5268 .unwrap_or_else(|e| panic!("restart_window={w:?} must validate; got {e:?}"));
5269 }
5270 }
5271
5272 #[test]
5273 fn restart_window_zero_takes_precedence_over_cap() {
5274 // The cross-arm ordering pin: `Duration::ZERO` is structurally
5275 // outside both `>= 1ms` (zero-floor) and `<=
5276 // SUPERVISOR_RESTART_WINDOW_MAX` (cap), but the zero-floor
5277 // diagnostic is the more self-locating one (it directly names
5278 // the omit-axis remediation), so the validate gate must fire
5279 // on zero first. Same shape every other zero-then-cap ordering
5280 // on this surface uses (`WallClockZero` then
5281 // `WallClockExceedsCap`, `PolicyTimeoutZero` then
5282 // `PolicyTimeoutExceedsCap`, `PolicyBreakerZeroWindow` then
5283 // `PolicyBreakerWindowExceedsCap`).
5284 let s = SupervisorSpec {
5285 restart_window: Some(Duration::ZERO),
5286 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5287 ..SupervisorSpec::default()
5288 };
5289 assert_eq!(
5290 s.validate().unwrap_err(),
5291 SupervisorError::RestartWindowZero,
5292 "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
5293 );
5294 }
5295
5296 #[test]
5297 fn restart_window_canonical_takes_precedence_over_cap() {
5298 // The cross-arm ordering pin: a `Duration` that is *both*
5299 // sub-millisecond (non-canonical-form) and structurally above
5300 // the cap surfaces the canonical-form diagnostic first,
5301 // because the round-trip-shape break is the more fundamental
5302 // issue (the value can't even round-trip through the codec,
5303 // so the cap diagnostic naming `1ms..=1h` would be misleading
5304 // — there's no integer-ms form of the offending value). Pin
5305 // the order so a future refactor that reorders the arms
5306 // surfaces here as a test failure rather than a silent
5307 // diagnostic regression. Peer of
5308 // `wall_clock_canonical_takes_precedence_over_cap` /
5309 // `policy_timeout_canonical_takes_precedence_over_cap`.
5310 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_nanos(1);
5311 let s = SupervisorSpec {
5312 restart_window: Some(w),
5313 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5314 ..SupervisorSpec::default()
5315 };
5316 assert_eq!(
5317 s.validate().unwrap_err(),
5318 SupervisorError::RestartWindowNotCanonical { window: w },
5319 "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
5320 );
5321 }
5322
5323 #[test]
5324 fn max_restarts_cap_takes_precedence_over_restart_window_cap() {
5325 // The cross-arm ordering pin between the `:max-restarts` cap
5326 // and the sibling `:restart-window` cap. A supervisor carrying
5327 // both an over-cap `max_restarts` AND an over-cap window must
5328 // surface the `MaxRestartsExceedsCap` diagnostic first — the
5329 // cap arm is wired immediately after the zero-restart arm and
5330 // strictly before every window-axis arm (zero / canonical /
5331 // cap), so the offending value the diagnostic names matches
5332 // the order the author would discover the gates by reading
5333 // top-to-bottom through `SupervisorSpec::validate`. Pin the
5334 // order so a future refactor that reorders the arms surfaces
5335 // here as a test failure rather than a silent diagnostic
5336 // regression. Peer of
5337 // `max_restarts_cap_takes_precedence_over_restart_window_gates`
5338 // on the sibling zero / canonical window arms.
5339 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
5340 let s = SupervisorSpec {
5341 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5342 restart_window: Some(w),
5343 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5344 ..SupervisorSpec::default()
5345 };
5346 assert_eq!(
5347 s.validate().unwrap_err(),
5348 SupervisorError::MaxRestartsExceedsCap {
5349 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5350 },
5351 "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
5352 );
5353 }
5354
5355 #[test]
5356 fn restart_window_cap_diagnostic_carries_offending_value() {
5357 // The diagnostic-shape pin: the offending `Duration` is
5358 // carried verbatim into the
5359 // [`SupervisorError::RestartWindowExceedsCap`] variant so the
5360 // surfaced error message names the value the author wrote,
5361 // not just the cap. Same self-locating diagnostic shape every
5362 // other typed-cap arm on this surface carries
5363 // (`WallClockExceedsCap` carries the offending `Duration`
5364 // verbatim, `PolicyTimeoutExceedsCap` carries the offending
5365 // `Duration` verbatim, `PolicyBreakerWindowExceedsCap` carries
5366 // the offending `Duration` verbatim).
5367 let w = Duration::from_secs(7200); // 2h
5368 let s = SupervisorSpec {
5369 restart_window: Some(w),
5370 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5371 ..SupervisorSpec::default()
5372 };
5373 let err = s.validate().unwrap_err();
5374 assert!(
5375 matches!(err, SupervisorError::RestartWindowExceedsCap { window } if window == w),
5376 "got {err:?}"
5377 );
5378 let msg = err.to_string();
5379 assert!(
5380 msg.contains("7200"),
5381 ":supervisor :restart-window cap diagnostic must carry the offending value verbatim (got: {msg})"
5382 );
5383 }
5384
5385 #[test]
5386 fn supervisor_restart_window_cap_pins_canonical_value() {
5387 // The SUPERVISOR_RESTART_WINDOW_MAX constant pins the value at
5388 // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
5389 // shared duration codec emits as a clean canonical string
5390 // (`"<n>h"`). Pinning the literal value here surfaces a future
5391 // drift (a relaxation to 24h, a tightening to 5m) as a
5392 // deliberate test edit, not a silent contract narrowing.
5393 //
5394 // The four typed-`Duration` caps on the validation surface
5395 // (`LIMITS_WALL_CLOCK_MAX` per-process, `POLICY_TIMEOUT_MAX`
5396 // per-edge, `POLICY_BREAKER_WINDOW_MAX` per-breaker,
5397 // `SUPERVISOR_RESTART_WINDOW_MAX` per-supervisor) share a
5398 // single uniform top edge at the codec's largest emitted unit
5399 // — a structural-property invariant the equality assertions
5400 // here enshrine, so a future drift on any of the four
5401 // surfaces as a deliberate test edit. Same shape every other
5402 // typed-cap value pin uses
5403 // (`wall_clock_cap_pins_canonical_value`,
5404 // `policy_timeout_cap_pins_canonical_value`,
5405 // `circuit_breaker_window_cap_pins_canonical_value`).
5406 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, Duration::from_secs(3600));
5407 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX.as_millis(), 3_600_000);
5408 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::LIMITS_WALL_CLOCK_MAX);
5409 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::POLICY_TIMEOUT_MAX);
5410 assert_eq!(
5411 SUPERVISOR_RESTART_WINDOW_MAX,
5412 crate::POLICY_BREAKER_WINDOW_MAX
5413 );
5414 }
5415
5416 #[test]
5417 fn restart_window_cap_value_round_trips_through_codec() {
5418 // The codec round-trip property the cap arm preserves: the
5419 // [`SUPERVISOR_RESTART_WINDOW_MAX`] constant itself round-trips
5420 // through the shared duration codec — every value at the cap
5421 // serializes to the canonical `"1h"` form and parses back
5422 // identically. Pin the round-trip so a future change to the
5423 // codec's unit set or to the cap's magnitude that breaks the
5424 // round-trip property surfaces here. Peer of
5425 // `wall_clock_cap_value_round_trips_through_codec` on the
5426 // sibling `:limits :wall-clock` axis.
5427 let s = SupervisorSpec {
5428 restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
5429 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5430 ..SupervisorSpec::default()
5431 };
5432 s.validate().unwrap();
5433 let json = serde_json::to_string(&s).unwrap();
5434 assert!(
5435 json.contains("\"1h\""),
5436 "SUPERVISOR_RESTART_WINDOW_MAX must serialize to the canonical `\"1h\"` form (got {json})"
5437 );
5438 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5439 assert_eq!(back.restart_window, Some(SUPERVISOR_RESTART_WINDOW_MAX));
5440 }
5441
5442 #[test]
5443 fn validate_rejects_duplicate_child_caixa() {
5444 // Two children with the same :caixa render to two ComputeUnits
5445 // with the same name in the cluster's HelmRelease values —
5446 // one silently overwrites the other. Erlang/OTP's child_spec.id
5447 // is required-unique per supervisor; same set-not-multiset
5448 // discipline applied here as for :membros / :placement
5449 // :clusters / :entrada :paths.
5450 let s = SupervisorSpec {
5451 children: vec![
5452 child("worker", "^0.1", RestartPolicy::Permanent),
5453 child("cache", "^0.1", RestartPolicy::Transient),
5454 child("worker", "^0.2", RestartPolicy::Permanent),
5455 ],
5456 ..SupervisorSpec::default()
5457 };
5458 let err = s.validate().unwrap_err();
5459 assert!(
5460 matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "worker"),
5461 "got {err:?}"
5462 );
5463 }
5464
5465 #[test]
5466 fn validate_duplicate_child_diagnostic_names_first_collision() {
5467 // Iteration walks the :children list in declaration order —
5468 // the diagnostic names the first repeat, deterministically,
5469 // even when multiple names duplicate.
5470 let s = SupervisorSpec {
5471 children: vec![
5472 child("a", "^0.1", RestartPolicy::Permanent),
5473 child("b", "^0.1", RestartPolicy::Permanent),
5474 child("a", "^0.1", RestartPolicy::Permanent),
5475 child("b", "^0.1", RestartPolicy::Permanent),
5476 ],
5477 ..SupervisorSpec::default()
5478 };
5479 let err = s.validate().unwrap_err();
5480 assert!(
5481 matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "a"),
5482 "got {err:?}"
5483 );
5484 }
5485
5486 // ── self-supervision cross-slot gate ──────────────────────────
5487
5488 #[test]
5489 fn validate_no_self_supervision_rejects_self_referential_child() {
5490 // A supervisor whose `:children` lists its own `:nome` is a
5491 // one-node reconciliation cycle — rejected, naming the parent.
5492 let children = vec![
5493 child("worker", "^0.1", RestartPolicy::Permanent),
5494 child("orquestra", "^0.1", RestartPolicy::Permanent),
5495 ];
5496 let err = validate_no_self_supervision(&children, "orquestra").unwrap_err();
5497 assert!(
5498 matches!(err, SupervisorError::ChildSupervisesSelf { ref caixa } if caixa == "orquestra"),
5499 "got {err:?}"
5500 );
5501 }
5502
5503 #[test]
5504 fn validate_no_self_supervision_accepts_distinct_children() {
5505 // Positive control: distinct child names (including a child that
5506 // is itself a supervisor — nested trees are valid OTP) pass.
5507 let children = vec![
5508 child("worker", "^0.1", RestartPolicy::Permanent),
5509 child("sub-tree", "^0.1", RestartPolicy::Permanent),
5510 ];
5511 validate_no_self_supervision(&children, "orquestra").unwrap();
5512 }
5513
5514 #[test]
5515 fn validate_no_self_supervision_empty_children_is_ok() {
5516 // SimpleOneForOne / no-static-children supervisors have nothing
5517 // to self-reference — the gate is vacuously satisfied.
5518 validate_no_self_supervision(&[], "orquestra").unwrap();
5519 }
5520
5521 #[test]
5522 fn validate_simple_one_for_one_skips_uniqueness_check() {
5523 // SimpleOneForOne supervisors carry no static children — the
5524 // duplicate-child loop never runs. A zero-window declaration
5525 // on a SimpleOneForOne supervisor still trips the window check
5526 // (window applies to dynamic children too).
5527 let s = SupervisorSpec {
5528 estrategia: RestartStrategy::SimpleOneForOne,
5529 restart_window: None,
5530 children: vec![],
5531 ..SupervisorSpec::default()
5532 };
5533 s.validate().unwrap();
5534 let s_zero = SupervisorSpec {
5535 estrategia: RestartStrategy::SimpleOneForOne,
5536 restart_window: Some(Duration::ZERO),
5537 children: vec![],
5538 ..SupervisorSpec::default()
5539 };
5540 assert_eq!(
5541 s_zero.validate().unwrap_err(),
5542 SupervisorError::RestartWindowZero
5543 );
5544 }
5545
5546 #[test]
5547 fn validate_zero_window_runs_after_max_restarts_check() {
5548 // Pin the order: max_restarts == 0 fires before
5549 // restart_window == 0s, so an author with both wrong sees the
5550 // counter-axis diagnostic first (matches the order in the
5551 // struct and in the doc comment).
5552 let s = SupervisorSpec {
5553 max_restarts: 0,
5554 restart_window: Some(Duration::ZERO),
5555 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5556 ..SupervisorSpec::default()
5557 };
5558 assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
5559 }
5560
5561 #[test]
5562 fn round_trip_all_strategies() {
5563 for &strat in RestartStrategy::ALL {
5564 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
5565 // shape partition through the [`gen_platform::IsVariant`]
5566 // derive-generated [`RestartStrategy::is_simple_one_for_one`]
5567 // predicate rather than the raw
5568 // `matches!(strat, RestartStrategy::SimpleOneForOne)`
5569 // open-coded pattern-match — same closed-set-typed-enum
5570 // arm-discriminator dispatch discipline the sibling
5571 // [`crate::upgrade::UpgradeInstruction::is_restart`] convergence
5572 // (915a934) extended onto its two paired positive / negated
5573 // `matches!` filter sites, and the sibling
5574 // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
5575 // predicate convergence (766ec63) extended onto the M3 mesh-
5576 // slot per-`:placement` distribution-strategy `matches!`
5577 // discriminator axis. See the sibling
5578 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
5579 // fixture and the peer `manifest::tests::
5580 // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
5581 // fixture — all three sites (the last unlifted
5582 // `matches!`-based arm-discriminator axis on the OTP-shape
5583 // supervisor sibling-restart-strategy closed-set typed enum,
5584 // acknowledged in 915a934's Prior-commits footnote as the
5585 // outstanding follow-up) now consult one typed dispatch on
5586 // the substrate primitive.
5587 let s = SupervisorSpec {
5588 estrategia: strat,
5589 children: if strat.is_simple_one_for_one() {
5590 vec![]
5591 } else {
5592 vec![child("w", "^0.1", RestartPolicy::Permanent)]
5593 },
5594 ..SupervisorSpec::default()
5595 };
5596 let json = serde_json::to_string(&s).unwrap();
5597 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5598 assert_eq!(s, back);
5599 }
5600 }
5601
5602 #[test]
5603 fn round_trip_all_restart_policies() {
5604 for policy in [
5605 RestartPolicy::Permanent,
5606 RestartPolicy::Temporary,
5607 RestartPolicy::Transient,
5608 ] {
5609 let c = child("w", "^0.1", policy);
5610 let json = serde_json::to_string(&c).unwrap();
5611 let back: ChildSpec = serde_json::from_str(&json).unwrap();
5612 assert_eq!(c, back);
5613 }
5614 }
5615
5616 #[test]
5617 fn restart_strategy_is_simple_one_for_one_predicate_partitions_the_arm_set() {
5618 // The fail-before-pass-after pin on the `gen_platform::IsVariant`
5619 // derive's [`RestartStrategy::is_simple_one_for_one`] arm-
5620 // discriminator predicate: [`RestartStrategy::SimpleOneForOne`]
5621 // is the only variant that satisfies `.is_simple_one_for_one()`;
5622 // every static-children-bearing arm (`OneForOne` / `OneForAll`
5623 // / `RestForOne`) returns `false`. This pin makes the partition
5624 // invariant load-bearing at caixa-core test time so a future
5625 // derive regression (a hole that returns `false` for
5626 // `SimpleOneForOne` too, or a byte-collision that flips a second
5627 // variant to `true`) trips here rather than laundering the arm
5628 // at the three test-fixture builder sites (a hole flips the
5629 // `SimpleOneForOne` fixture to carry a non-empty children list
5630 // and the subsequent `SupervisorSpec::validate` would refuse the
5631 // fixture with [`SupervisorError::SimpleOneForOneWithStaticChildren`];
5632 // a collision flips a peer strategy's fixture to carry an empty
5633 // children list and the subsequent `validate` would refuse with
5634 // [`SupervisorError::NoChildren`] — either way, the pin fires
5635 // here, at the derive site, rather than at the fixture-refusal
5636 // site far away). Peer of the sibling
5637 // [`crate::upgrade::tests::upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
5638 // (915a934) pin on the M2 OTP-appup axis and the sibling
5639 // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
5640 // pin on the M0 `:kind` axis.
5641 let cases: &[(RestartStrategy, bool)] = &[
5642 (RestartStrategy::OneForOne, false),
5643 (RestartStrategy::OneForAll, false),
5644 (RestartStrategy::RestForOne, false),
5645 (RestartStrategy::SimpleOneForOne, true),
5646 ];
5647 for (variant, expected) in cases {
5648 assert_eq!(
5649 variant.is_simple_one_for_one(),
5650 *expected,
5651 "RestartStrategy::{variant:?}.is_simple_one_for_one() must \
5652 return {expected} (partition invariant on the \
5653 IsVariant-derived arm-discriminator predicate — every \
5654 test-fixture site that partitions the `:children` slot \
5655 shape on `SimpleOneForOne ↔ non-SimpleOneForOne` keys \
5656 off this typed dispatch, so a derive regression must \
5657 surface here rather than at the fixture-refusal site)"
5658 );
5659 }
5660 }
5661
5662 #[test]
5663 fn restart_strategy_fixture_partition_routes_through_is_simple_one_for_one_predicate() {
5664 // Byte-identity pin on the `SimpleOneForOne ↔ non-SimpleOneForOne`
5665 // fixture-shape partition against the pre-lift
5666 // `matches!(strat, RestartStrategy::SimpleOneForOne)` open-coded
5667 // pattern-match every test-fixture builder site previously
5668 // coupled to inline. Asserts the two projections agree byte-for-
5669 // byte on every arm of the enum, so a future derive regression
5670 // that flipped either predicate's arm-set would surface here at
5671 // caixa-core test time rather than at the three fixture-builder
5672 // sites (`supervisor::tests::round_trip_all_strategies`,
5673 // `supervisor::tests::supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`,
5674 // `manifest::tests::caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`)
5675 // far from the derive site. Same peer-shape byte-identity pin
5676 // every sibling `IsVariant`-derive-routed convergence carries on
5677 // the substrate's closed-set typed-enum surface (peer of
5678 // [`crate::upgrade::tests::validate_restart_exclusive_routes_through_is_restart_predicate`]
5679 // on the M2 OTP-appup axis).
5680 for &strat in RestartStrategy::ALL {
5681 let via_predicate = strat.is_simple_one_for_one();
5682 let via_matches = matches!(strat, RestartStrategy::SimpleOneForOne);
5683 assert_eq!(
5684 via_predicate, via_matches,
5685 "RestartStrategy::{strat:?}: is_simple_one_for_one() must \
5686 byte-equal matches!(_, RestartStrategy::SimpleOneForOne) — \
5687 the pre-lift open-coded pattern and the \
5688 IsVariant-derived predicate are the same axis, \
5689 one typed dispatch"
5690 );
5691 }
5692 }
5693
5694 #[test]
5695 fn duration_codec_round_trip_canonical_units() {
5696 // Note the canonical-form rule: durations serialize to the
5697 // *largest* unit that divides cleanly, so 60s ↔ "1m" and not
5698 // "60s" — but the round-trip preserves the underlying Duration.
5699 let cases = [
5700 ("30s", Duration::from_secs(30)),
5701 ("5m", Duration::from_secs(300)),
5702 ("1h", Duration::from_secs(3600)),
5703 ("500ms", Duration::from_millis(500)),
5704 ];
5705 for (lit, dur) in cases {
5706 let s = SupervisorSpec {
5707 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5708 restart_window: Some(dur),
5709 ..SupervisorSpec::default()
5710 };
5711 let json = serde_json::to_string(&s).unwrap();
5712 assert!(
5713 json.contains(&format!("\"{lit}\"")),
5714 "expected \"{lit}\" in {json}"
5715 );
5716 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5717 assert_eq!(back.restart_window, Some(dur));
5718 }
5719 }
5720
5721 #[test]
5722 fn duration_canonicalizes_to_largest_unit() {
5723 // 60 seconds → "1m" (largest cleanly-divisible unit), but the
5724 // typed Duration still equals 60s on the way back.
5725 let s = SupervisorSpec {
5726 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5727 restart_window: Some(Duration::from_secs(60)),
5728 ..SupervisorSpec::default()
5729 };
5730 let json = serde_json::to_string(&s).unwrap();
5731 assert!(json.contains("\"1m\""), "{json}");
5732 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5733 assert_eq!(back.restart_window, Some(Duration::from_secs(60)));
5734 }
5735
5736 #[test]
5737 fn three_child_one_for_one_validates() {
5738 let s = SupervisorSpec {
5739 estrategia: RestartStrategy::OneForOne,
5740 max_restarts: 5,
5741 restart_window: Some(Duration::from_secs(60)),
5742 children: vec![
5743 child("worker", "^0.1", RestartPolicy::Permanent),
5744 child("cache", "^0.1", RestartPolicy::Transient),
5745 child("scratch", "^0.1", RestartPolicy::Temporary),
5746 ],
5747 };
5748 s.validate().unwrap();
5749 }
5750
5751 #[test]
5752 fn json_uses_pascal_case_for_strategy_and_policy() {
5753 // Variant names are PascalCase by default in serde, matching
5754 // tatara-lisp's enum convention (`:estrategia OneForOne`).
5755 let c = child("w", "^0.1", RestartPolicy::Permanent);
5756 let json = serde_json::to_string(&c).unwrap();
5757 assert!(json.contains("\"Permanent\""));
5758 assert!(!json.contains("\"permanent\""));
5759
5760 let s = SupervisorSpec {
5761 estrategia: RestartStrategy::OneForOne,
5762 children: vec![c],
5763 ..SupervisorSpec::default()
5764 };
5765 let json = serde_json::to_string(&s).unwrap();
5766 assert!(json.contains("\"estrategia\":\"OneForOne\""));
5767 }
5768
5769 // ── shared duration codec: integer-magnitude canonical-form gate ──
5770 //
5771 // The gate lifts the discipline `crate::limits::parse_duration`
5772 // (818dd38) carries on the peer `:limits :wall-clock` codec onto
5773 // the shared codec backing the remaining three typed-duration
5774 // slots: `:supervisor :restart-window`, `:politicas :timeout`, and
5775 // `:politicas :circuit-breaker :window`. Every magnitude `render`
5776 // emits is a non-negative integer with no decimal point and no
5777 // leading sign, so the codec's accepted set must match for
5778 // serialize/deserialize to round-trip without canonical-form
5779 // drift.
5780
5781 #[test]
5782 fn parse_accepts_integer_canonical_units() {
5783 // Pin the happy-path: every canonical author shape `render`
5784 // ever emits parses to the same `Duration` value, so the
5785 // codec's accepted set is at least a superset of its emitted
5786 // set on the canonical-unit axis.
5787 for (lit, dur) in [
5788 ("30s", Duration::from_secs(30)),
5789 ("500ms", Duration::from_millis(500)),
5790 ("2m", Duration::from_secs(120)),
5791 ("1h", Duration::from_secs(3600)),
5792 ("0s", Duration::ZERO),
5793 ] {
5794 assert_eq!(
5795 duration_codec::parse(lit).unwrap(),
5796 dur,
5797 "parse({lit:?}) should be {dur:?}"
5798 );
5799 }
5800 }
5801
5802 #[test]
5803 fn parse_accepts_bare_integer_as_seconds() {
5804 // The `"s" | ""` arm: a bare integer with no unit is read as
5805 // seconds. Pin this so the unit-empty form keeps parsing (it
5806 // renders to `"<n>s"` on serialize — that's a unit-choice
5807 // drift the integer-magnitude gate does NOT close, matching
5808 // the `parse_byte_size` `"1024"` → `"1KiB"` scope decision in
5809 // the peer `:limits :memory` codec).
5810 assert_eq!(
5811 duration_codec::parse("30").unwrap(),
5812 Duration::from_secs(30)
5813 );
5814 }
5815
5816 #[test]
5817 fn parse_rejects_fractional_seconds_with_canonical_form_diagnostic() {
5818 // `"1.5s"` parses as f64 to 1.5 → renders back as `"1500ms"`
5819 // on first serialize — DRIFT. The integer-magnitude gate names
5820 // the offending `"1.5"` verbatim and points at the canonical
5821 // remediation `"1500ms"`.
5822 let err = duration_codec::parse("1.5s").unwrap_err();
5823 assert!(err.contains("\"1.5\""), "missing magnitude in {err:?}");
5824 assert!(
5825 err.contains("not a non-negative integer"),
5826 "missing canonical-form reason in {err:?}"
5827 );
5828 assert!(
5829 err.contains("\"1500ms\""),
5830 "missing canonical-form remediation in {err:?}"
5831 );
5832 }
5833
5834 #[test]
5835 fn parse_rejects_decimal_shaped_integer_seconds() {
5836 // `"1.0s"` is the trickiest drift class: numerically `1.0s` is
5837 // `1s` exactly, so the round-trip looks correct — but the
5838 // emitted canonical form is `"1s"`, not `"1.0s"`. Gate the
5839 // decimal-shape-with-integer-value form so author intent is
5840 // never silently rewritten.
5841 let err = duration_codec::parse("1.0s").unwrap_err();
5842 assert!(err.contains("\"1.0\""), "missing magnitude in {err:?}");
5843 assert!(
5844 err.contains("not a non-negative integer"),
5845 "missing canonical-form reason in {err:?}"
5846 );
5847 }
5848
5849 #[test]
5850 fn parse_rejects_half_unit_minute() {
5851 // `"0.5m"` is the unit-fraction footgun — author writes a
5852 // human-readable half-minute, serde silently rewrites to
5853 // `"30s"` on next emit. The gate names the offending
5854 // magnitude `"0.5"` and points at the integer-in-smaller-unit
5855 // form.
5856 let err = duration_codec::parse("0.5m").unwrap_err();
5857 assert!(err.contains("\"0.5\""), "missing magnitude in {err:?}");
5858 assert!(
5859 err.contains("\"30s\""),
5860 "missing canonical-form remediation in {err:?}"
5861 );
5862 }
5863
5864 #[test]
5865 fn parse_rejects_leading_plus_sign() {
5866 // `u64::from_str` rejects `"+30"` but `f64::from_str` accepts
5867 // it as `30.0` — the prior parser used f64 so `"+30s"` parsed
5868 // cleanly to 30s and round-tripped to `"30s"` on next emit
5869 // (DRIFT). The digit-only gate closes the leading-sign class
5870 // first; the diagnostic names `"+30"` verbatim.
5871 let err = duration_codec::parse("+30s").unwrap_err();
5872 assert!(err.contains("\"+30\""), "missing magnitude in {err:?}");
5873 assert!(
5874 err.contains("not a non-negative integer"),
5875 "missing canonical-form reason in {err:?}"
5876 );
5877 }
5878
5879 #[test]
5880 fn parse_rejects_leading_minus_sign() {
5881 // The former `num < 0.0` arm: `"-30s"` parsed as f64 to -30,
5882 // rejected with `"negative duration in \"-30s\""`. Under the
5883 // integer-magnitude gate the diagnostic is unified — `-30` is
5884 // non-digit-only, f64-numeric, and surfaces with the canonical-
5885 // form reason (no leading `+` / `-` sign) naming the offending
5886 // `"-30"` verbatim. Same diagnostic shape as every other
5887 // rejected non-integer magnitude.
5888 let err = duration_codec::parse("-30s").unwrap_err();
5889 assert!(err.contains("\"-30\""), "missing magnitude in {err:?}");
5890 assert!(
5891 err.contains("not a non-negative integer"),
5892 "missing canonical-form reason in {err:?}"
5893 );
5894 }
5895
5896 #[test]
5897 fn parse_garbage_still_falls_through_to_bad_magnitude() {
5898 // Non-digit-only AND non-numeric (`"--1s"`, `"abc"`) falls
5899 // through to the narrower "bad duration magnitude" arm — the
5900 // canonical-form diagnostic is reserved for the parser-shape
5901 // footgun case, not the "not a number at all" case. Same
5902 // shape `parse_byte_size`'s `BadByteMagnitude` arm carries on
5903 // the peer `:limits :memory` codec.
5904 let err = duration_codec::parse("--1s").unwrap_err();
5905 assert!(
5906 err.contains("bad duration magnitude"),
5907 "expected bad-magnitude wording in {err:?}"
5908 );
5909 }
5910
5911 #[test]
5912 fn parse_digit_only_magnitude_carries_zero_f64_drift() {
5913 // The accepted set is now closed under `u64`-exact integer
5914 // arithmetic: `"500ms"` → `Duration::from_millis(500)` exactly,
5915 // `"3600s"` → `Duration::from_secs(3600)` exactly, `"1h"` →
5916 // `Duration::from_secs(3600)` exactly, no f64 mantissa drift
5917 // possible. Pin the integer-exact arms across the four unit
5918 // suffixes so a future refactor that reaches back for f64
5919 // (`from_secs_f64`, `mul_f64`) surfaces here.
5920 assert_eq!(
5921 duration_codec::parse("3600s").unwrap(),
5922 Duration::from_secs(3600)
5923 );
5924 assert_eq!(
5925 duration_codec::parse("60m").unwrap(),
5926 Duration::from_secs(3600)
5927 );
5928 assert_eq!(
5929 duration_codec::parse("1h").unwrap(),
5930 Duration::from_secs(3600)
5931 );
5932 assert_eq!(
5933 duration_codec::parse("999ms").unwrap(),
5934 Duration::from_millis(999)
5935 );
5936 }
5937
5938 #[test]
5939 fn restart_window_serde_rejects_fractional_seconds() {
5940 // The shared codec backs `SupervisorSpec::restart_window`
5941 // (`with = "duration_codec"`) — so the gate applies on serde
5942 // deserialize for the typed Supervisor slot. A
5943 // `{"restartWindow":"1.5s"}` payload that previously round-
5944 // tripped to a different canonical string on next serialize
5945 // is now refused at deserialize with the integer-magnitude
5946 // diagnostic.
5947 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
5948 "restartWindow":"1.5s",
5949 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
5950 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5951 let msg = err.to_string();
5952 assert!(
5953 msg.contains("not a non-negative integer"),
5954 "expected integer-magnitude diagnostic in {msg:?}"
5955 );
5956 assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
5957 }
5958
5959 #[test]
5960 fn restart_window_serde_rejects_leading_plus() {
5961 // The `u64::from_str` leading-`+` permissiveness gap that
5962 // motivated the digit-only gate (the `f64`-side accepted
5963 // `"+30"`, the prior parser silently round-tripped to `"30s"`)
5964 // is now closed on the shared codec — surfaces as a structured
5965 // diagnostic at the serde layer for every typed-duration slot.
5966 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
5967 "restartWindow":"+30s",
5968 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
5969 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5970 let msg = err.to_string();
5971 assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
5972 assert!(
5973 msg.contains("not a non-negative integer"),
5974 "missing canonical-form reason in {msg:?}"
5975 );
5976 }
5977
5978 #[test]
5979 fn parse_rejects_leading_zero_magnitude() {
5980 // `"030s"` is digit-only, so the existing non-digit-only / sign
5981 // / fractional arm doesn't catch it — `u64::from_str("030")`
5982 // returns `Ok(30)`, so before this gate `"030s"` parsed to
5983 // `Duration::from_secs(30)` and round-tripped through `render`
5984 // to `"30s"` — a *different* canonical string on the next emit,
5985 // breaking the THEORY.md Part V render-determinism contract
5986 // exactly the way `"+30s"` did before the leading-`+` arm
5987 // landed. Peer with the `rate_limit_codec` leading-zero arm
5988 // (4f46830) on the same canonical-form-drift axis.
5989 let err = duration_codec::parse("030s").unwrap_err();
5990 assert!(
5991 err.contains("non-canonical leading zero"),
5992 "expected leading-zero diagnostic in {err:?}"
5993 );
5994 assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
5995 assert!(
5996 err.contains("\"30s\""),
5997 "missing canonical-form remediation in {err:?}"
5998 );
5999 assert!(
6000 err.contains("THEORY.md"),
6001 "missing render-determinism citation in {err:?}"
6002 );
6003 }
6004
6005 #[test]
6006 fn parse_rejects_multi_digit_zero_magnitude() {
6007 // `"00s"` and `"00ms"` are the all-zero leading-zero footgun —
6008 // digit-only, parse losslessly to `Duration::ZERO`, but render
6009 // back to `"0s"` (the single-byte canonical form) on the next
6010 // emit. The leading-zero arm refuses the drift class at the
6011 // codec layer; the semantic-zero gate downstream
6012 // (`SupervisorError::ZeroRestartWindow`, etc.) would refuse
6013 // the single-byte canonical form `"0s"` separately on the
6014 // typed-validate layer.
6015 let err = duration_codec::parse("00s").unwrap_err();
6016 assert!(
6017 err.contains("non-canonical leading zero"),
6018 "expected leading-zero diagnostic in {err:?}"
6019 );
6020 assert!(err.contains("\"00\""), "missing magnitude in {err:?}");
6021 }
6022
6023 #[test]
6024 fn parse_rejects_leading_zero_per_hour_window() {
6025 // `"01h"` is the per-hour-window footgun — multi-byte magnitude
6026 // starting with `0`, parses losslessly to `Duration::from_secs(3600)`,
6027 // renders to `"1h"` (DRIFT). The arm is unit-agnostic: every
6028 // canonical unit suffix the codec accepts (`ms` / `s` / `m` /
6029 // `h` / bare-integer-as-seconds) inherits the same gate.
6030 let err = duration_codec::parse("01h").unwrap_err();
6031 assert!(
6032 err.contains("non-canonical leading zero"),
6033 "expected leading-zero diagnostic in {err:?}"
6034 );
6035 assert!(err.contains("\"01\""), "missing magnitude in {err:?}");
6036 }
6037
6038 #[test]
6039 fn parse_rejects_leading_zero_bare_integer_as_seconds() {
6040 // The `parse_accepts_bare_integer_as_seconds` happy-path
6041 // (`"30"` → 30s) inherits the leading-zero arm: `"030"` is
6042 // multi-byte starts-with-`0`, parses losslessly to
6043 // `Duration::from_secs(30)`, renders to `"30s"` (DRIFT). The
6044 // bare-integer surface accepts permissive unit-empty
6045 // shorthand but still must reject leading-zero padding.
6046 let err = duration_codec::parse("030").unwrap_err();
6047 assert!(
6048 err.contains("non-canonical leading zero"),
6049 "expected leading-zero diagnostic in {err:?}"
6050 );
6051 assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
6052 }
6053
6054 #[test]
6055 fn parse_accepts_single_zero_magnitude_at_codec_layer() {
6056 // The codec-layer / typed-validate-layer boundary: `"0s"` /
6057 // `"0ms"` / `"0"` are the single-byte canonical-zero forms —
6058 // each round-trips losslessly through `render`
6059 // (`render(Duration::ZERO)` → `"0s"`), so the codec layer
6060 // accepts them. The downstream semantic-zero gates
6061 // (`SupervisorError::ZeroRestartWindow`,
6062 // `AplicacaoError::PolicyTimeoutZero`,
6063 // `AplicacaoError::PolicyCircuitBreakerWindowZero`) refuse
6064 // zero-magnitude authoring at the typed-validate layer above,
6065 // peer with the `rate_limit_codec` codec-layer / typed-
6066 // validate-layer partition for `"0/s"`.
6067 assert_eq!(duration_codec::parse("0s").unwrap(), Duration::ZERO);
6068 assert_eq!(duration_codec::parse("0ms").unwrap(), Duration::ZERO);
6069 assert_eq!(duration_codec::parse("0").unwrap(), Duration::ZERO);
6070 }
6071
6072 #[test]
6073 fn parse_accepts_canonical_magnitude_with_leading_one() {
6074 // The complementary boundary: a future tightening cannot
6075 // drift into rejecting valid canonical magnitudes that
6076 // happen to start with `1` (or any digit `[1-9]`). Pin
6077 // every canonical-unit suffix so the leading-zero arm
6078 // remains strictly narrower than the digit-only arm.
6079 assert_eq!(
6080 duration_codec::parse("100ms").unwrap(),
6081 Duration::from_millis(100)
6082 );
6083 assert_eq!(
6084 duration_codec::parse("100s").unwrap(),
6085 Duration::from_secs(100)
6086 );
6087 assert_eq!(
6088 duration_codec::parse("10m").unwrap(),
6089 Duration::from_secs(600)
6090 );
6091 assert_eq!(
6092 duration_codec::parse("10h").unwrap(),
6093 Duration::from_secs(36_000)
6094 );
6095 }
6096
6097 #[test]
6098 fn restart_window_serde_rejects_leading_zero() {
6099 // The shared codec backs `SupervisorSpec::restart_window`
6100 // (`with = "duration_codec"`) — so the leading-zero arm
6101 // applies on serde deserialize for the typed Supervisor slot.
6102 // A `{"restartWindow":"030s"}` payload that previously round-
6103 // tripped to a different canonical string on next serialize
6104 // is now refused at deserialize with the leading-zero
6105 // diagnostic. Peer with `restart_window_serde_rejects_leading_plus`
6106 // / `restart_window_serde_rejects_fractional_seconds` on the
6107 // same canonical-form-drift axis.
6108 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6109 "restartWindow":"030s",
6110 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6111 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6112 let msg = err.to_string();
6113 assert!(
6114 msg.contains("non-canonical leading zero"),
6115 "expected leading-zero diagnostic in {msg:?}"
6116 );
6117 assert!(msg.contains("\"030\""), "missing magnitude in {msg:?}");
6118 }
6119
6120 #[test]
6121 fn parse_rejects_leading_whitespace() {
6122 // `" 30s"` — the canonical paste-from-aligned-doc /
6123 // paste-from-YAML-quoted-plain-scalar footgun. Before this
6124 // gate the top-level `s.trim()` at parse entry silently ate
6125 // the leading space and parsed the value to
6126 // `Duration::from_secs(30)`, which then round-tripped through
6127 // `render` to `"30s"` (a *different* canonical string on the
6128 // next emit) — the exact canonical-form-drift class the
6129 // leading-`+` / leading-zero arms already close, extended
6130 // to the whitespace-byte class. Peer with the sibling
6131 // `rate_limit_codec` whitespace-rejection arm (1ad7755) on
6132 // the M3 `:politicas` axis.
6133 let err = duration_codec::parse(" 30s").unwrap_err();
6134 assert!(
6135 err.contains("contains whitespace byte"),
6136 "expected whitespace diagnostic in {err:?}"
6137 );
6138 assert!(err.contains("0x20"), "missing offending byte in {err:?}");
6139 assert!(
6140 err.contains("THEORY.md"),
6141 "missing render-determinism contract citation in {err:?}"
6142 );
6143 }
6144
6145 #[test]
6146 fn parse_rejects_trailing_whitespace() {
6147 // `"30s "` — the canonical shell-history / trailing-space
6148 // paste footgun. Before this gate the top-level `s.trim()`
6149 // silently ate the trailing space and parsed to
6150 // `Duration::from_secs(30)`, round-tripping to `"30s"` on the
6151 // next emit — same canonical-form drift as the leading-space
6152 // sibling, closed on the same whitespace-byte arm.
6153 let err = duration_codec::parse("30s ").unwrap_err();
6154 assert!(
6155 err.contains("contains whitespace byte"),
6156 "expected whitespace diagnostic in {err:?}"
6157 );
6158 assert!(err.contains("0x20"), "missing offending byte in {err:?}");
6159 }
6160
6161 #[test]
6162 fn parse_rejects_internal_whitespace_between_magnitude_and_unit() {
6163 // `"30 s"` — the canonical typographically-spaced author
6164 // shape (the same idiom every prose reference to a duration
6165 // renders as, mistakenly retained when the value is pasted
6166 // into a codec-shaped slot). Before this gate the per-part
6167 // `num_part.trim()` / `unit.trim()` calls silently ate the
6168 // whitespace between the magnitude and the unit and parsed
6169 // the value to `Duration::from_secs(30)`, round-tripping to
6170 // `"30s"` — the codec's *internal* whitespace-tolerance
6171 // vector, orthogonal to the leading / trailing surface but
6172 // the same canonical-form-drift class. Pins the arm as
6173 // strictly stronger than the pre-existing top-level
6174 // `s.trim()` behavior: it fires on whitespace anywhere in
6175 // the value, not just at the string boundary.
6176 let err = duration_codec::parse("30 s").unwrap_err();
6177 assert!(
6178 err.contains("contains whitespace byte"),
6179 "expected whitespace diagnostic in {err:?}"
6180 );
6181 assert!(err.contains("0x20"), "missing offending byte in {err:?}");
6182 }
6183
6184 #[test]
6185 fn parse_rejects_tab_byte() {
6186 // `"\t30s"` — the canonical paste-from-indented-doc /
6187 // paste-from-YAML-block-scalar footgun where a tab byte leads
6188 // the magnitude. Pins that the gate covers tab (`0x09`) as
6189 // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
6190 // members and both would be silently swallowed by `s.trim()`
6191 // pre-gate. The `is_ascii_whitespace` coverage extends beyond
6192 // space alone to the full ASCII-whitespace set (space `0x20`,
6193 // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
6194 // the tab arm as a representative of the non-space members.
6195 let err = duration_codec::parse("\t30s").unwrap_err();
6196 assert!(
6197 err.contains("contains whitespace byte"),
6198 "expected whitespace diagnostic in {err:?}"
6199 );
6200 assert!(
6201 err.contains("0x09"),
6202 "missing offending tab byte in {err:?}"
6203 );
6204 }
6205
6206 #[test]
6207 fn restart_window_serde_rejects_whitespace() {
6208 // The shared codec backs `SupervisorSpec::restart_window`
6209 // (`with = "duration_codec"`) — so the whitespace arm
6210 // applies on serde deserialize for the typed Supervisor slot.
6211 // A `{"restartWindow":" 30s"}` payload that previously round-
6212 // tripped to a different canonical string on next serialize
6213 // is now refused at deserialize with the whitespace-byte
6214 // diagnostic. Peer with `restart_window_serde_rejects_leading_zero`
6215 // / `restart_window_serde_rejects_leading_plus` /
6216 // `restart_window_serde_rejects_fractional_seconds` on the
6217 // same canonical-form-drift axis.
6218 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6219 "restartWindow":" 30s",
6220 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6221 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6222 let msg = err.to_string();
6223 assert!(
6224 msg.contains("contains whitespace byte"),
6225 "expected whitespace diagnostic in {msg:?}"
6226 );
6227 assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
6228 }
6229
6230 // ── canonical-form: non-ASCII Unicode `White_Space` duration gate ─────
6231 //
6232 // Successor to the ASCII-whitespace arm (a7ae622) on the shared
6233 // duration codec — closes the strictly-complementary class the
6234 // byte-scan cannot see, through the lifted
6235 // [`crate::render::find_non_ascii_whitespace_char`] predicate.
6236 // Applies to `:supervisor :restart-window`, `:politicas :timeout`,
6237 // and `:politicas :circuit-breaker :window` simultaneously via
6238 // this shared codec.
6239
6240 #[test]
6241 fn duration_codec_parse_rejects_leading_nbsp() {
6242 // NBSP prefix — the strictly-complementary drift class the
6243 // ASCII byte-scan cannot see. `str::trim` strips it silently
6244 // and the value drifts to `"30s"` on next serialize.
6245 let err = duration_codec::parse("\u{00A0}30s").unwrap_err();
6246 assert!(
6247 err.contains("non-ASCII Unicode whitespace character"),
6248 "expected non-ASCII whitespace diagnostic in {err:?}"
6249 );
6250 assert!(err.contains("U+00A0"), "missing codepoint in {err:?}");
6251 }
6252
6253 #[test]
6254 fn duration_codec_parse_rejects_trailing_line_separator() {
6255 // LINE SEPARATOR (`\u{2028}`) trailing — paste-from-web-doc
6256 // footgun.
6257 let err = duration_codec::parse("30s\u{2028}").unwrap_err();
6258 assert!(
6259 err.contains("non-ASCII Unicode whitespace character"),
6260 "expected non-ASCII whitespace diagnostic in {err:?}"
6261 );
6262 assert!(err.contains("U+2028"), "missing codepoint in {err:?}");
6263 }
6264
6265 #[test]
6266 fn duration_codec_parse_accepts_ascii_only_forms_after_unicode_arm() {
6267 // Positive-control pin: every ASCII-only canonical form the
6268 // renderer emits stays accepted through the new arm.
6269 assert_eq!(
6270 duration_codec::parse("30s").unwrap(),
6271 Duration::from_secs(30)
6272 );
6273 assert_eq!(
6274 duration_codec::parse("500ms").unwrap(),
6275 Duration::from_millis(500)
6276 );
6277 assert_eq!(
6278 duration_codec::parse("1h").unwrap(),
6279 Duration::from_secs(3600)
6280 );
6281 }
6282
6283 #[test]
6284 fn restart_window_serde_rejects_non_ascii_whitespace() {
6285 // The shared codec backs `SupervisorSpec::restart_window` — so
6286 // the new non-ASCII Unicode whitespace arm applies on serde
6287 // deserialize for the typed Supervisor slot. A
6288 // `{"restartWindow":" 30s"}` payload that previously
6289 // survived the ASCII byte-scan (only ASCII whitespace was
6290 // refused) is now refused at deserialize with the
6291 // non-ASCII-whitespace-and-codepoint diagnostic.
6292 let payload = "{\"estrategia\":\"OneForOne\",\"maxRestarts\":5,\
6293 \"restartWindow\":\"\u{00A0}30s\",\
6294 \"children\":[{\"caixa\":\"w\",\"versao\":\"^0.1\",\"restart\":\"Permanent\"}]}";
6295 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6296 let msg = err.to_string();
6297 assert!(
6298 msg.contains("non-ASCII Unicode whitespace character"),
6299 "expected non-ASCII whitespace diagnostic in {msg:?}"
6300 );
6301 assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
6302 }
6303
6304 // ── drift-detection: serde-derive-to-SUPERVISOR_KEY_* identity ────────
6305
6306 #[test]
6307 fn supervisor_spec_serde_keys_match_lifted_supervisor_key_consts() {
6308 // Load-bearing invariant: the four `SUPERVISOR_KEY_*` consts
6309 // (`SUPERVISOR_KEY_ESTRATEGIA` / `SUPERVISOR_KEY_MAX_RESTARTS` /
6310 // `SUPERVISOR_KEY_RESTART_WINDOW` / `SUPERVISOR_KEY_CHILDREN`)
6311 // name the exact camelCase JSON keys the
6312 // `#[serde(rename_all = "camelCase")]` attribute on
6313 // `SupervisorSpec` emits. Serialize a fully-populated spec (each
6314 // field carries `Some(_)` / non-empty) and pin that each canonical
6315 // byte-sequence appears verbatim in the JSON — a future accidental
6316 // `rename_all = "snake_case"` / `"kebab-case"` / verbatim-field-
6317 // name flip at the derive attribute (any of which would silently
6318 // break every downstream JSON consumer that reaches for one of the
6319 // four consts via `Value::get(...)`) surfaces here as a build-time
6320 // test failure at `supervisor.rs`, not as an apply-time
6321 // `.get(<stale-canonical-const>)` returning `None` far from the
6322 // derive-attr drift's commit. Peer with the sibling
6323 // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
6324 // (d8b8b4f) pin on the M2 `:limits` axis — same discipline the
6325 // M2 typed-slot family established, extended here to close the
6326 // top-level Supervisor axis.
6327 let spec = SupervisorSpec {
6328 estrategia: RestartStrategy::OneForOne,
6329 max_restarts: 5,
6330 restart_window: Some(Duration::from_secs(60)),
6331 children: vec![ChildSpec {
6332 caixa: "w".into(),
6333 versao: "^0.1".into(),
6334 restart: RestartPolicy::Permanent,
6335 }],
6336 };
6337 let json = serde_json::to_string(&spec).unwrap();
6338 for key in [
6339 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6340 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6341 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6342 crate::render::SUPERVISOR_KEY_CHILDREN,
6343 ] {
6344 let quoted = format!("\"{key}\"");
6345 assert!(
6346 json.contains("ed),
6347 "serialized SupervisorSpec must carry the lifted \
6348 SUPERVISOR_KEY_* byte-sequence {quoted} verbatim in \
6349 the JSON emission (got: {json})",
6350 );
6351 }
6352 }
6353
6354 #[test]
6355 fn supervisor_key_consts_are_pairwise_distinct() {
6356 // Cross-axis drift-detection pin: a future collapse of two
6357 // canonical top-level byte-strings onto the same value (e.g. an
6358 // accidental copy-paste flip of `SUPERVISOR_KEY_CHILDREN` to
6359 // also read `"estrategia"`) would silently reroute every
6360 // downstream probe on one axis onto the sibling axis's overlay
6361 // entry and pass every propagation-probe test that expected only
6362 // the stale axis's value. Peer of the sibling four-way distinct
6363 // pin on the `M2_LIMITS_KEY_*` tetrad (d8b8b4f).
6364 let all = [
6365 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6366 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6367 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6368 crate::render::SUPERVISOR_KEY_CHILDREN,
6369 ];
6370 for (i, a) in all.iter().enumerate() {
6371 for b in all.iter().skip(i + 1) {
6372 assert_ne!(
6373 a, b,
6374 "SUPERVISOR_KEY_* consts must be pairwise-distinct \
6375 canonical byte-sequences — got `{a}` == `{b}`",
6376 );
6377 }
6378 }
6379 }
6380
6381 #[test]
6382 fn supervisor_key_consts_are_lower_camel_case_shape() {
6383 // Shape-pin: every `SUPERVISOR_KEY_*` const must be a
6384 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
6385 // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
6386 // capital, no whitespace / dots) — the canonical shape the
6387 // `#[serde(rename_all = "camelCase")]` derive produces on
6388 // `SupervisorSpec`. A future flip to a non-camelCase attribute
6389 // at the derive surfaces both here (this test fails on the
6390 // stale-constant shape) and at
6391 // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
6392 // (that test fails on the mismatch between const and derive).
6393 // Peer with `m2_limits_key_consts_are_lower_camel_case_shape`
6394 // (d8b8b4f) on the sibling M2 `:limits` axis.
6395 for key in [
6396 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6397 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6398 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6399 crate::render::SUPERVISOR_KEY_CHILDREN,
6400 ] {
6401 assert!(
6402 !key.is_empty(),
6403 "SUPERVISOR_KEY_* must be non-empty (got {key:?})"
6404 );
6405 let first = key.chars().next().unwrap();
6406 assert!(
6407 first.is_ascii_lowercase(),
6408 "SUPERVISOR_KEY_* must lead with an ASCII-lowercase byte \
6409 (got {key:?}, leads with {first:?})",
6410 );
6411 assert!(
6412 key.chars().all(|c| c.is_ascii_alphanumeric()),
6413 "SUPERVISOR_KEY_* must be ASCII-alphanumeric only \
6414 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
6415 );
6416 }
6417 }
6418
6419 #[test]
6420 fn supervisor_key_consts_are_byte_distinct_from_supervisor_author_key_peers() {
6421 // Cross-axis drift pin: the four `SUPERVISOR_KEY_*` consts
6422 // (camelCase JSON keys, no leading colon) must never collide
6423 // byte-for-byte with the four peer `SUPERVISOR_AUTHOR_KEY_*`
6424 // consts (kebab-case author-facing labels with leading colon)
6425 // that sit next to them at `caixa_core::render`. Both families
6426 // cover the same four typed Supervisor slots on two distinct
6427 // axes (author-side kebab vs renderer-side camelCase);
6428 // collapsing either family onto the other's byte-shape would
6429 // silently reroute the render-side probe onto the author-facing
6430 // surface, or vice versa. Peer of the byte-distinctness
6431 // discipline the `M3_PLACEMENT_KEY_ESTRATEGIA` docstring names
6432 // against the peer `M3_AUTHOR_KEY_PLACEMENT`.
6433 let pairs = [
6434 (
6435 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6436 crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA,
6437 ),
6438 (
6439 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6440 crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS,
6441 ),
6442 (
6443 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6444 crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW,
6445 ),
6446 (
6447 crate::render::SUPERVISOR_KEY_CHILDREN,
6448 crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN,
6449 ),
6450 ];
6451 for (json_key, author_key) in pairs {
6452 assert_ne!(
6453 json_key, author_key,
6454 "SUPERVISOR_KEY_* (JSON side) must differ byte-for-byte \
6455 from the peer SUPERVISOR_AUTHOR_KEY_* (author side); \
6456 got JSON `{json_key}` == author `{author_key}`",
6457 );
6458 }
6459 }
6460
6461 // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_KEY_* identity ──
6462
6463 #[test]
6464 fn child_spec_serde_keys_match_lifted_supervisor_child_key_consts() {
6465 // Load-bearing invariant: the three `SUPERVISOR_CHILD_KEY_*` consts
6466 // (`SUPERVISOR_CHILD_KEY_CAIXA` / `SUPERVISOR_CHILD_KEY_VERSAO` /
6467 // `SUPERVISOR_CHILD_KEY_RESTART`) name the exact camelCase JSON
6468 // keys the `#[serde(rename_all = "camelCase")]` attribute on
6469 // `ChildSpec` emits. Serialize a fully-populated `ChildSpec` and
6470 // pin that each canonical byte-sequence appears verbatim in the
6471 // JSON — a future accidental `rename_all = "snake_case"` /
6472 // `"kebab-case"` / verbatim-field-name flip at the derive
6473 // attribute (any of which would silently break every downstream
6474 // JSON consumer that reaches for one of the three consts via
6475 // `Value::get(...)`) surfaces here as a build-time test failure at
6476 // `supervisor.rs`, not as an apply-time
6477 // `.get(<stale-canonical-const>)` returning `None` far from the
6478 // derive-attr drift's commit. Peer with the enclosing
6479 // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
6480 // (40cc4e5) pin on the M2 supervision-tree top-level axis — same
6481 // discipline the SupervisorSpec top-level lift established,
6482 // extended here to the sibling per-`:children` entry `ChildSpec`
6483 // derive so the last M2 typed-struct sub-block
6484 // `#[serde(rename_all = "camelCase")]` axis on the Supervisor
6485 // surface without a lifted serde-key peer joins the substrate's
6486 // "one canonical byte-string per typed serialized-key axis"
6487 // discipline.
6488 let c = ChildSpec {
6489 caixa: "worker".into(),
6490 versao: "^0.1".into(),
6491 restart: RestartPolicy::Permanent,
6492 };
6493 let json = serde_json::to_string(&c).unwrap();
6494 for key in [
6495 crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
6496 crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
6497 crate::render::SUPERVISOR_CHILD_KEY_RESTART,
6498 ] {
6499 let quoted = format!("\"{key}\"");
6500 assert!(
6501 json.contains("ed),
6502 "serialized ChildSpec must carry the lifted \
6503 SUPERVISOR_CHILD_KEY_* byte-sequence {quoted} verbatim \
6504 in the JSON emission (got: {json})",
6505 );
6506 }
6507 }
6508
6509 #[test]
6510 fn supervisor_child_key_consts_are_pairwise_distinct() {
6511 // Cross-axis drift-detection pin: a future collapse of two
6512 // canonical `ChildSpec` per-entry byte-strings onto the same
6513 // value (e.g. an accidental copy-paste flip of
6514 // `SUPERVISOR_CHILD_KEY_RESTART` to also read `"caixa"`) would
6515 // silently reroute every downstream probe on one axis onto the
6516 // sibling axis's overlay entry and pass every propagation-probe
6517 // test that expected only the stale axis's value. Peer of the
6518 // sibling three-way distinct pin on the `CONTRATO_KEY_*` triad
6519 // (ca463a4) and the two-way distinct pin on the `MEMBRO_KEY_*`
6520 // pair (ce80ca0).
6521 let all = [
6522 crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
6523 crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
6524 crate::render::SUPERVISOR_CHILD_KEY_RESTART,
6525 ];
6526 for (i, a) in all.iter().enumerate() {
6527 for b in all.iter().skip(i + 1) {
6528 assert_ne!(
6529 a, b,
6530 "SUPERVISOR_CHILD_KEY_* consts must be pairwise-\
6531 distinct canonical byte-sequences — got `{a}` == `{b}`",
6532 );
6533 }
6534 }
6535 }
6536
6537 #[test]
6538 fn supervisor_child_key_consts_are_lower_camel_case_shape() {
6539 // Shape-pin: every `SUPERVISOR_CHILD_KEY_*` const must be a
6540 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
6541 // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
6542 // capital, no whitespace / dots) — the canonical shape the
6543 // `#[serde(rename_all = "camelCase")]` derive produces on
6544 // `ChildSpec`. A future flip to a non-camelCase attribute at the
6545 // derive surfaces both here (this test fails on the
6546 // stale-constant shape) and at
6547 // `child_spec_serde_keys_match_lifted_supervisor_child_key_consts`
6548 // (that test fails on the mismatch between const and derive).
6549 // Peer with `supervisor_key_consts_are_lower_camel_case_shape`
6550 // (40cc4e5) on the sibling `SupervisorSpec` top-level axis.
6551 for key in [
6552 crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
6553 crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
6554 crate::render::SUPERVISOR_CHILD_KEY_RESTART,
6555 ] {
6556 assert!(
6557 !key.is_empty(),
6558 "SUPERVISOR_CHILD_KEY_* must be non-empty (got {key:?})"
6559 );
6560 let first = key.chars().next().unwrap();
6561 assert!(
6562 first.is_ascii_lowercase(),
6563 "SUPERVISOR_CHILD_KEY_* must lead with an ASCII-lowercase \
6564 byte (got {key:?}, leads with {first:?})",
6565 );
6566 assert!(
6567 key.chars().all(|c| c.is_ascii_alphanumeric()),
6568 "SUPERVISOR_CHILD_KEY_* must be ASCII-alphanumeric only \
6569 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
6570 );
6571 }
6572 }
6573
6574 // ── drift-detection: serde-derive-to-SUPERVISOR_ESTRATEGIA_* identity ────
6575
6576 #[test]
6577 fn restart_strategy_variants_serialize_to_lifted_scalar_values() {
6578 // The fail-before-pass-after pin: pre-lift there was no
6579 // single-source binding between the [`RestartStrategy`] variant
6580 // name the un-`rename`d `Serialize` derive emits under
6581 // [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the byte-string
6582 // every downstream cluster-side dispatcher (the future
6583 // wasm-operator's per-supervisor sibling-restart branch, the
6584 // future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
6585 // admission-time enum-arm bind, the `caixa-operator`'s
6586 // hierarchical reconciliation scheduler's per-strategy fan-out)
6587 // probes verbatim. A future `#[serde(rename_all = "kebab-case")]`
6588 // attribute on the enum — or a per-variant `#[serde(rename = "…")]`
6589 // override, or a variant rename in the source — would silently
6590 // rebrand the emitted scalar under one spelling while every
6591 // downstream dispatcher still probed the other, with the failure
6592 // surfacing at the operator's reconcile posture (subtrees coming
6593 // up under the `default()` `OneForOne` arm rather than the typed
6594 // slot's declared strategy — a bad child would then only take
6595 // itself down instead of the sibling set the author intended, so
6596 // shared-state children fall out of sync) far from the source
6597 // rebrand commit and with no field naming the drift. Pinning the
6598 // two paths (the `Serialize` derive's serialized string AND the
6599 // [`RestartStrategy::as_str`] helper) to the same four lifted
6600 // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
6601 // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
6602 // [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
6603 // [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
6604 // byte-strings makes any future drift on either endpoint fail
6605 // here at caixa-core build time. Peer of the M3
6606 // `placement_strategy_variants_serialize_to_lifted_scalar_values`
6607 // (3f0e21c) on the sibling `PlacementStrategy` axis — same
6608 // three-path-convergence discipline, extended to close the
6609 // OTP-shaped per-supervisor sibling-restart axis.
6610 for (variant, expected) in [
6611 (
6612 RestartStrategy::OneForOne,
6613 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
6614 ),
6615 (
6616 RestartStrategy::OneForAll,
6617 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
6618 ),
6619 (
6620 RestartStrategy::RestForOne,
6621 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
6622 ),
6623 (
6624 RestartStrategy::SimpleOneForOne,
6625 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
6626 ),
6627 ] {
6628 let json = serde_json::to_string(&variant).unwrap();
6629 assert_eq!(
6630 json,
6631 format!("\"{expected}\""),
6632 "RestartStrategy::{variant:?} must serialize to {expected:?}"
6633 );
6634 assert_eq!(
6635 variant.as_str(),
6636 expected,
6637 "RestartStrategy::{variant:?}.as_str() must return the lifted \
6638 SUPERVISOR_ESTRATEGIA_* constant"
6639 );
6640 }
6641 }
6642
6643 #[test]
6644 fn supervisor_estrategia_consts_are_pairwise_distinct() {
6645 // Cross-arm drift-detection pin: a future collapse of two
6646 // canonical variant byte-strings onto the same value (e.g. an
6647 // accidental copy-paste flip of `SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`
6648 // to also read `"OneForOne"`) would silently reroute every
6649 // downstream operator's per-strategy dispatch onto the sibling
6650 // arm's reconcile branch and pass every propagation-probe test
6651 // that expected only the stale arm's value — the mis-strategied
6652 // subtree would come up with the wrong sibling-restart posture
6653 // on every subsequent failure. Peer of the sibling four-way
6654 // distinct pin `supervisor_key_consts_are_pairwise_distinct`
6655 // (40cc4e5) on the top-level `SUPERVISOR_KEY_*` axis.
6656 let all = [
6657 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
6658 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
6659 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
6660 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
6661 ];
6662 for (i, a) in all.iter().enumerate() {
6663 for (j, b) in all.iter().enumerate() {
6664 if i != j {
6665 assert_ne!(
6666 a, b,
6667 "SUPERVISOR_ESTRATEGIA_* consts must be pairwise distinct \
6668 — got duplicate {a:?} at indices {i} and {j}",
6669 );
6670 }
6671 }
6672 }
6673 }
6674
6675 #[test]
6676 fn restart_strategy_display_routes_through_as_str_helper() {
6677 // The fail-before-pass-after pin on the first half of the
6678 // three-path convergence: pre-convergence the sibling
6679 // OTP-shape typed enum [`RestartStrategy`] carried a
6680 // [`std::fmt::Display`] surface via its
6681 // `#[discriminant(also_display)]` gen-platform derive route,
6682 // which arrived kebab-case as `"one-for-one"` /
6683 // `"one-for-all"` / `"rest-for-one"` /
6684 // `"simple-one-for-one"` while the wire format ran as
6685 // PascalCase `"OneForOne"` / `"OneForAll"` / `"RestForOne"` /
6686 // `"SimpleOneForOne"` through the un-`rename`d serde derive.
6687 // Every consumer reaching for a strategy byte-string past the
6688 // wire format had to pick between three paths
6689 // ([`RestartStrategy::as_str`], the `Serialize` derive's
6690 // serialized string, or `format!("{v}")` on the
6691 // discriminant-Display route), any two of which a future
6692 // variant rename or `#[serde(rename_all = "kebab-case")]`
6693 // attribute would silently desynchronize. Wiring
6694 // [`std::fmt::Display`] through [`RestartStrategy::as_str`]
6695 // closes the third path: every `format!("{v}")` call reaches
6696 // the same lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
6697 // const the wire format and the [`RestartStrategy::as_str`]
6698 // helper already route through, so a future variant rename
6699 // lands at exactly one place. Pin the routing here so a future
6700 // `impl std::fmt::Display for RestartStrategy`
6701 // reimplementation that hand-rolls the arms instead of
6702 // delegating to [`RestartStrategy::as_str`] fails at
6703 // caixa-core build time. Peer of the M3
6704 // `placement_strategy_display_routes_through_as_str_helper`
6705 // (cc8f749) which the M3 axis converged first.
6706 for &variant in RestartStrategy::ALL {
6707 assert_eq!(
6708 variant.to_string(),
6709 variant.as_str(),
6710 "RestartStrategy::{variant:?} Display must route through \
6711 RestartStrategy::as_str (single source of truth: the lifted \
6712 SUPERVISOR_ESTRATEGIA_* const the wire format also emits)"
6713 );
6714 }
6715 }
6716
6717 #[test]
6718 fn restart_strategy_display_matches_serialized_wire_byte_string() {
6719 // The fail-before-pass-after pin on the second half of the
6720 // three-path convergence: `Display` (user-facing text) agrees
6721 // byte-for-byte with the `Serialize` derive's wire format
6722 // (canonical camelCase-schema `SUPERVISOR_KEY_ESTRATEGIA`
6723 // scalar) on every variant. Pre-convergence the two paths
6724 // were structurally independent — a future
6725 // `#[serde(rename_all = "kebab-case")]` attribute on the
6726 // enum would silently rebrand the emitted wire scalar
6727 // (`one-for-one`, `one-for-all`, `rest-for-one`,
6728 // `simple-one-for-one`) while every consumer that
6729 // pretty-prints the strategy (the future wasm-operator's
6730 // per-supervisor sibling-restart-strategy diagnostic line,
6731 // the future `feira app graph` per-supervisor strategy line,
6732 // the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
6733 // materializer's admission-webhook rejection body) would
6734 // still emit the PascalCase form the `as_str` / `Display`
6735 // route returns, with the mismatch surfacing at consumer
6736 // parse time / operator dispatch time far from the source
6737 // rebrand commit. Pin the two paths byte-for-byte here so any
6738 // future serde-attribute or variant-rename drift is a
6739 // caixa-core-build-time test failure at this call, not a
6740 // silent per-consumer dispatch miss. Peer of the M3
6741 // `placement_strategy_display_matches_serialized_wire_byte_string`
6742 // (cc8f749) which the M3 axis converged first.
6743 for &variant in RestartStrategy::ALL {
6744 let wire = serde_json::to_string(&variant).unwrap();
6745 let unquoted = wire
6746 .strip_prefix('"')
6747 .and_then(|s| s.strip_suffix('"'))
6748 .expect("serialized RestartStrategy is a JSON string");
6749 assert_eq!(
6750 variant.to_string(),
6751 unquoted,
6752 "RestartStrategy::{variant:?} Display byte-string must match the \
6753 Serialize derive's wire byte-string (three-path convergence: \
6754 Display + as_str + Serialize all resolve to the same \
6755 SUPERVISOR_ESTRATEGIA_* const)"
6756 );
6757 }
6758 }
6759
6760 #[test]
6761 fn restart_strategy_as_ref_str_routes_through_as_str_accessor() {
6762 // Fail-before-pass-after byte-parity pin on the lifted
6763 // `impl AsRef<str> for RestartStrategy` — asserts the
6764 // standard-library trait impl and the substrate-primitive
6765 // [`RestartStrategy::as_str`] `pub const fn` accessor resolve
6766 // to the same `&str` per instance across the four-arm
6767 // closed set, so any future silent detour that routes the
6768 // impl through a divergent projection (a per-arm inline
6769 // `match self { RestartStrategy::OneForOne => "OneForOne", … }`
6770 // re-inlining that opens a compile-time link to the un-lifted
6771 // arm-literal, a swap onto the kebab-case
6772 // [`gen_platform::Discriminant`] catalog identity that would
6773 // collide the wire axis with the dispatcher-catalog axis) trips
6774 // at caixa-core test time under `PartialEq` rather than at a
6775 // downstream `impl AsRef<str>`-bound consumer's silent split.
6776 // Sweeps every one of the four arms
6777 // [`RestartStrategy::ALL`] carries so no arm's projection is
6778 // covered only by the sibling wire-format `Serialize` derive
6779 // path. Peer of the sibling
6780 // [`crate::version::tests::caixa_version_as_ref_str_routes_through_as_str_accessor`]
6781 // (16d5c7e) `AsRef<str>`-byte-parity pin on the paired
6782 // top-level `:versao` typed newtype — the two pins together
6783 // cover the substrate primitive's `AsRef<str>` projection axis
6784 // on the paired newtype + closed-set-typed-enum surface.
6785 for &variant in RestartStrategy::ALL {
6786 assert_eq!(
6787 <RestartStrategy as AsRef<str>>::as_ref(&variant),
6788 variant.as_str(),
6789 "AsRef<str> impl on RestartStrategy::{variant:?} must \
6790 byte-equal RestartStrategy::as_str on the same instance \
6791 — divergence signals a silent detour off the substrate-\
6792 primitive accessor"
6793 );
6794 }
6795 }
6796
6797 #[test]
6798 fn restart_strategy_as_ref_str_routes_through_display_via_shared_accessor() {
6799 // Fail-before-pass-after byte-parity pin on the three-path
6800 // convergence discipline the M2 sibling-restart primitive now
6801 // carries on the `&str`-projection axis:
6802 // `<RestartStrategy as AsRef<str>>::as_ref(&s)` (the newly
6803 // lifted impl), `format!("{s}")` (the pre-existing
6804 // [`fmt::Display`] impl), and `s.as_str()` (the substrate-
6805 // primitive `pub const fn` accessor both trait impls delegate
6806 // through) must resolve to the same byte-string on every
6807 // instance across the four-arm closed set. Refuses any future
6808 // divergence between the two trait impls (a stray
6809 // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
6810 // rather than delegating through the shared accessor; a
6811 // hypothetical `AsRef<str>` rewrite that inlines a per-arm
6812 // literal cascade) that would silently split the two
6813 // projection paths of the same closed-set typed enum. Mirrors
6814 // the sibling three-path-convergence discipline the peer
6815 // [`crate::CaixaVersion`] typed newtype carries on its
6816 // `AsRef<str>` / `Display` / `as_str` triple
6817 // (version.rs pin
6818 // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
6819 // 16d5c7e).
6820 for &variant in RestartStrategy::ALL {
6821 let via_as_ref: &str = <RestartStrategy as AsRef<str>>::as_ref(&variant);
6822 let via_display: String = format!("{variant}");
6823 let via_accessor: &str = variant.as_str();
6824 assert_eq!(via_as_ref, via_accessor);
6825 assert_eq!(via_display, via_accessor);
6826 assert_eq!(via_as_ref, via_display.as_str());
6827 }
6828 }
6829
6830 #[test]
6831 fn restart_strategy_all_enumerates_every_variant_exactly_once() {
6832 // Fail-before-pass-after pin on the [`RestartStrategy::ALL`]
6833 // exhaustive-iteration surface: every variant appears exactly
6834 // once, and the slice length matches the arm count of the
6835 // closed set. Every consumer that walks the accepted-strategy
6836 // set (a future `feira supervisor --estrategia …` CLI-side
6837 // arg-parse's "did you mean" hint, a future M4 admission-
6838 // webhook's rejection body naming the accepted-`:estrategia`
6839 // list, the [`RestartStrategy::from_wire`] reverse-projection
6840 // consumers that iterate the accept-set for diagnostic
6841 // rendering) reads through this slice, so a future arm addition
6842 // that grows the enum but forgets to grow [`Self::ALL`]
6843 // silently truncates every downstream consumer's accept-set at
6844 // the same pre-addition boundary — this pin fails at caixa-core
6845 // build time on the pairwise-distinct + arm-count invariants.
6846 //
6847 // Peer of the sibling [`crate::CaixaKind::ALL`] (6b1f4fb) /
6848 // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
6849 // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
6850 // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
6851 // pins on the peer closed-set typed-enum axes.
6852 let all: &[RestartStrategy] = RestartStrategy::ALL;
6853 assert_eq!(
6854 all.len(),
6855 4,
6856 "RestartStrategy::ALL must enumerate every variant of the \
6857 four-arm closed set (OneForOne, OneForAll, RestForOne, \
6858 SimpleOneForOne); got {all:?}"
6859 );
6860 for (i, a) in all.iter().enumerate() {
6861 for (j, b) in all.iter().enumerate() {
6862 if i != j {
6863 assert_ne!(
6864 a, b,
6865 "RestartStrategy::ALL must carry every variant exactly \
6866 once — got duplicate {a:?} at indices {i} and {j}"
6867 );
6868 }
6869 }
6870 }
6871 for variant in [
6872 RestartStrategy::OneForOne,
6873 RestartStrategy::OneForAll,
6874 RestartStrategy::RestForOne,
6875 RestartStrategy::SimpleOneForOne,
6876 ] {
6877 assert!(
6878 all.contains(&variant),
6879 "RestartStrategy::ALL must contain {variant:?} — a future arm \
6880 addition that grows the enum but forgets to grow the ALL slice \
6881 silently truncates every downstream consumer's accept-set at \
6882 the pre-addition boundary"
6883 );
6884 }
6885 }
6886
6887 #[test]
6888 fn restart_strategy_from_wire_accepts_every_lifted_constant() {
6889 // Fail-before-pass-after pin on the forward accept-set of the
6890 // [`RestartStrategy::from_wire`] reverse projection: every
6891 // canonical [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
6892 // constant the [`RestartStrategy::as_str`] emitter walks parses
6893 // back to its paired variant. Any future arm addition that
6894 // grows the emitter's `as_str` match but forgets to grow the
6895 // parser's `from_wire` match silently splits the two halves of
6896 // the round-trip — the wire byte-string one non-serde consumer
6897 // parses from the one the emitter wrote — with the failure
6898 // surfacing at parse time far from the rebrand commit. Pinning
6899 // the four-arm accept-set here catches the drift at caixa-core
6900 // build time.
6901 //
6902 // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
6903 // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
6904 // accept-set pins on the peer closed-set typed-enum `str → Self`
6905 // axes.
6906 for (wire, expected) in [
6907 (
6908 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
6909 RestartStrategy::OneForOne,
6910 ),
6911 (
6912 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
6913 RestartStrategy::OneForAll,
6914 ),
6915 (
6916 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
6917 RestartStrategy::RestForOne,
6918 ),
6919 (
6920 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
6921 RestartStrategy::SimpleOneForOne,
6922 ),
6923 ] {
6924 let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
6925 panic!(
6926 "RestartStrategy::from_wire({wire:?}) must accept every \
6927 SUPERVISOR_ESTRATEGIA_* constant — got None for the \
6928 lifted canonical byte-string that RestartStrategy::{expected:?} \
6929 serializes as under SUPERVISOR_KEY_ESTRATEGIA"
6930 )
6931 });
6932 assert_eq!(
6933 parsed, expected,
6934 "RestartStrategy::from_wire({wire:?}) must return \
6935 RestartStrategy::{expected:?}; got RestartStrategy::{parsed:?}"
6936 );
6937 }
6938 }
6939
6940 #[test]
6941 fn restart_strategy_from_wire_round_trips_through_as_str() {
6942 // Fail-before-pass-after pin on the closed round-trip between
6943 // the forward [`RestartStrategy::as_str`] emitter and the
6944 // reverse [`RestartStrategy::from_wire`] parser: for every
6945 // variant in [`RestartStrategy::ALL`], parsing the emitter's
6946 // output must return exactly the same variant. Any per-arm
6947 // divergence — a future arm added to `as_str` but not
6948 // `from_wire`, an accidental copy-paste flip in one but not
6949 // the other — silently splits the emit and parse halves and
6950 // the failure surfaces at consumer parse time far from the
6951 // drift site. The `ALL`-iterating shape means a future arm
6952 // addition picks up the coverage by construction.
6953 //
6954 // Peer of the sibling
6955 // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
6956 // (18c7342) round-trip pin on
6957 // [`crate::aplicacao::PlacementStrategy::from_wire`] and
6958 // [`crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`]
6959 // (6b1f4fb) round-trip pin on [`crate::CaixaKind::from_wire`].
6960 for &variant in RestartStrategy::ALL {
6961 let wire = variant.as_str();
6962 let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
6963 panic!(
6964 "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
6965 must be Some({variant:?}) — the two halves of the round-trip \
6966 dispatch on the same lifted SUPERVISOR_ESTRATEGIA_* consts; \
6967 got None on wire byte-string {wire:?}"
6968 )
6969 });
6970 assert_eq!(
6971 parsed, variant,
6972 "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
6973 must round-trip to the same variant; got {parsed:?}"
6974 );
6975 }
6976 }
6977
6978 #[test]
6979 fn restart_strategy_from_wire_rejects_unknown_byte_strings() {
6980 // Fail-before-pass-after pin on the closed-set refusal
6981 // discipline of [`RestartStrategy::from_wire`]: every
6982 // byte-string outside the four-arm accept-set returns `None`
6983 // rather than silently collapsing onto the [`Default`]
6984 // (`OneForOne`) arm or an arbitrary neighbor. The refusal set
6985 // exercised here sweeps the load-bearing drift shapes: the
6986 // empty string (a stripped serde-attribute drift), all-
6987 // whitespace strings (the canonical text-editor accidental
6988 // padding shape), the kebab-case dispatcher-catalog identities
6989 // (`"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
6990 // `"simple-one-for-one"` — the [`gen_platform::FromStrKind`]-
6991 // derived [`std::str::FromStr`] accept-set, which parses the
6992 // *other* axis of this enum's two-axis split and must not leak
6993 // into the `from_wire` PascalCase-wire accept-set), the
6994 // lowercased single-word forms (`"oneforone"`), the padded
6995 // canonical scalar (`" OneForOne "`), the trailing-newline
6996 // shapes (`"OneForOne\n"`), and neighboring-but-unknown arms
6997 // (`"AllForOne"` — the canonical typo direction).
6998 //
6999 // Peer of the sibling
7000 // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
7001 // (2aa6d23) +
7002 // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
7003 // (18c7342) refusal pins on the peer closed-set typed-enum
7004 // axes.
7005 for bad in [
7006 "",
7007 " ",
7008 "\n",
7009 "\t",
7010 "one-for-one",
7011 "one-for-all",
7012 "rest-for-one",
7013 "simple-one-for-one",
7014 "oneforone",
7015 "OneForOnes",
7016 "one_for_one",
7017 "one for one",
7018 "ONEFORONE",
7019 "OneForOne ",
7020 " OneForOne",
7021 " SimpleOneForOne ",
7022 "OneForOne\n",
7023 "restforone",
7024 "REST_FOR_ONE",
7025 "AllForOne",
7026 "Simple",
7027 "?",
7028 ] {
7029 assert!(
7030 RestartStrategy::from_wire(bad).is_none(),
7031 "RestartStrategy::from_wire({bad:?}) must return None — the \
7032 parser's accept-set is exactly the four RestartStrategy::as_str \
7033 outputs (OneForOne, OneForAll, RestForOne, SimpleOneForOne), \
7034 and this byte-string is outside that closed set"
7035 );
7036 }
7037 }
7038
7039 #[test]
7040 fn restart_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
7041 // Fail-before-pass-after pin on the fourth path of the four-path
7042 // convergence: `from_wire` (the reverse projection) inverts the
7043 // `Serialize` derive's wire byte-string on every variant.
7044 // Together with the pre-existing three-path convergence
7045 // (`Display` + `as_str` + `Serialize` all resolve to the same
7046 // lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const,
7047 // pinned by
7048 // [`restart_strategy_display_matches_serialized_wire_byte_string`])
7049 // this closes the round-trip: the wire byte-string the
7050 // `Serialize` derive emits parses back to the same variant
7051 // through `from_wire`, so any future serde-attribute or variant-
7052 // rename drift on the emit half now surfaces as a matched drift
7053 // on the parse half at caixa-core build time — the two halves
7054 // migrate as a unit through the lifted consts on any future
7055 // rename, and the round-trip cannot silently split.
7056 //
7057 // Peer of the sibling
7058 // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
7059 // (18c7342) wire-format pin on
7060 // [`crate::aplicacao::PlacementStrategy::from_wire`].
7061 for &variant in RestartStrategy::ALL {
7062 let wire = serde_json::to_string(&variant).unwrap();
7063 let unquoted = wire
7064 .strip_prefix('"')
7065 .and_then(|s| s.strip_suffix('"'))
7066 .expect("serialized RestartStrategy is a JSON string");
7067 let parsed = RestartStrategy::from_wire(unquoted).unwrap_or_else(|| {
7068 panic!(
7069 "RestartStrategy::from_wire({unquoted:?}) must accept the \
7070 Serialize derive's wire byte-string for \
7071 RestartStrategy::{variant:?} — the four-path convergence \
7072 (Display + as_str + Serialize + from_wire) resolves through \
7073 the same lifted SUPERVISOR_ESTRATEGIA_* const; got None"
7074 )
7075 });
7076 assert_eq!(
7077 parsed, variant,
7078 "RestartStrategy::from_wire of the Serialize derive's wire \
7079 byte-string for RestartStrategy::{variant:?} must round-trip \
7080 to the same variant; got {parsed:?}"
7081 );
7082 }
7083 }
7084
7085 #[test]
7086 fn restart_strategy_try_from_str_routes_through_from_wire_accessor() {
7087 // Fail-before-pass-after byte-parity pin on the newly lifted
7088 // `impl TryFrom<&str> for RestartStrategy` — asserts the standard-
7089 // library trait impl and the substrate-primitive
7090 // [`RestartStrategy::from_wire`] `Option<Self>` accessor resolve to
7091 // the same four-arm accept-set across every arm the exhaustive
7092 // [`RestartStrategy::ALL`] slice enumerates. Any future silent
7093 // detour that routes the trait impl through a divergent projection
7094 // (a per-arm inline `match s { "OneForOne" => Ok(Self::OneForOne),
7095 // … }` re-inlining that opens a compile-time link to the un-
7096 // lifted arm-literal, a hypothetical `#[serde(rename_all = "…")]`
7097 // attribute drift that silently splits the wire byte-string from
7098 // every consumer that reaches for this typed dispatch, an
7099 // accidental swap onto the kebab-case dispatcher-catalog axis the
7100 // pre-existing [`std::str::FromStr`] impl parses through and which
7101 // would collide the two-axis wire/catalog split the sibling
7102 // [`RestartStrategy::from_wire`] doc block makes load-bearing)
7103 // trips at caixa-core test time under `assert_eq!` rather than at
7104 // a downstream `impl TryFrom<&str>`-bound consumer's silent split.
7105 // Sweeps every one of the four arms [`RestartStrategy::ALL`]
7106 // carries so no arm's projection is covered only by the sibling
7107 // method-named `from_wire` path. Peer of the sibling
7108 // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
7109 // (3c83606),
7110 // [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
7111 // (bf33136), and the M3
7112 // [`crate::aplicacao::tests::placement_strategy_try_from_str_routes_through_from_wire_accessor`]
7113 // (6fd00cd) — extends the trait-idiomatic reverse-projection axis
7114 // onto the first M2-OTP-shape closed-set typed enum on the caixa
7115 // surface.
7116 for &variant in RestartStrategy::ALL {
7117 let wire = variant.as_str();
7118 assert_eq!(
7119 <RestartStrategy as TryFrom<&str>>::try_from(wire),
7120 Ok(variant),
7121 "TryFrom<&str> impl on RestartStrategy must round-trip \
7122 RestartStrategy::{variant:?}.as_str() = {wire:?} back to \
7123 Ok(RestartStrategy::{variant:?}) — divergence from \
7124 RestartStrategy::from_wire signals a silent detour off \
7125 the substrate-primitive accessor"
7126 );
7127 assert_eq!(
7128 <RestartStrategy as TryFrom<&str>>::try_from(wire).ok(),
7129 RestartStrategy::from_wire(wire),
7130 "TryFrom<&str> ok()-projection on {wire:?} must byte-equal \
7131 RestartStrategy::from_wire on the same input"
7132 );
7133 }
7134 }
7135
7136 #[test]
7137 fn restart_strategy_try_from_str_rejects_unknown_byte_strings() {
7138 // Rejection witness on the `impl TryFrom<&str> for
7139 // RestartStrategy` — sweeps a candidate set of byte-strings
7140 // outside the four-arm PascalCase wire accept-set the sibling
7141 // [`RestartStrategy::as_str`] emits and asserts every one lands on
7142 // `Err(())`, so a future accidental widening of the trait impl's
7143 // accept-set (a stray additional
7144 // `_ if s.eq_ignore_ascii_case("OneForOne") => Ok(…)` case-fold
7145 // path, a silent inclusion of the kebab-case dispatcher-catalog
7146 // byte-string the pre-existing [`std::str::FromStr`] impl the
7147 // [`gen_platform::FromStrKind`] derive installs parses onto the
7148 // wire axis — which would collide the two-axis
7149 // wire/dispatcher-catalog split the sibling
7150 // [`RestartStrategy::from_wire`] doc block makes load-bearing —
7151 // an English-rebrand or plural-arm silent alias that would
7152 // widen the wire accept-set past the OTP-canonical four) trips at
7153 // caixa-core test time. The candidate set includes the empty
7154 // string, whitespace-only padding, the kebab-case dispatcher-
7155 // catalog byte-strings on the sibling axis (a caller who confuses
7156 // the two axes trips here rather than at a downstream consumer's
7157 // silent reject), a lowercase / uppercase / mixed-case fold of
7158 // each PascalCase arm (a caller who assumes case-fold acceptance
7159 // trips here), leading/trailing whitespace padding, the trailing-
7160 // newline shape, quote-wrapped candidates, and a residual set of
7161 // plausible-but-wrong English rebrand candidates. Peer of the
7162 // sibling
7163 // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
7164 // (3c83606) and
7165 // [`crate::aplicacao::tests::placement_strategy_try_from_str_rejects_unknown_byte_strings`]
7166 // (6fd00cd) rejection witnesses.
7167 let rejected: &[&str] = &[
7168 "",
7169 " ",
7170 "\n",
7171 "\t",
7172 "one-for-one",
7173 "one-for-all",
7174 "rest-for-one",
7175 "simple-one-for-one",
7176 "oneforone",
7177 "one_for_one",
7178 "OneForOnes",
7179 "ONEFORONE",
7180 "oneforall",
7181 "restforone",
7182 "simpleoneforone",
7183 "OneForOne ",
7184 " OneForOne",
7185 " OneForAll ",
7186 "OneForOne\n",
7187 "RestForOne\t",
7188 "OneForEach",
7189 "AllForOne",
7190 "one for one",
7191 "\"OneForOne\"",
7192 "?",
7193 ];
7194 for &input in rejected {
7195 assert_eq!(
7196 <RestartStrategy as TryFrom<&str>>::try_from(input),
7197 Err(()),
7198 "TryFrom<&str> impl on RestartStrategy must reject the \
7199 non-wire byte-string {input:?} — silent acceptance signals \
7200 an accept-set widening off the paired \
7201 RestartStrategy::from_wire resolver"
7202 );
7203 }
7204 }
7205
7206 #[test]
7207 fn restart_strategy_try_from_str_and_from_wire_partition_the_accept_set() {
7208 // Cross-axis partition pin: the paired `TryFrom<&str>` and
7209 // `from_wire` reverse projections must resolve identically on
7210 // *every* input, not just the ones [`RestartStrategy::ALL`]
7211 // enumerates. Sweeps a mixed candidate set spanning accepted
7212 // (four-arm PascalCase wire byte-strings) and rejected (kebab-case
7213 // dispatcher-catalog byte-strings, empty, whitespace-padded,
7214 // quoted, English-rebrand candidates) inputs and asserts the
7215 // trait's `Result::ok()` projection byte-equals the method-named
7216 // resolver's `Option<Self>` return-shape on each, locking the two
7217 // paths together by construction so any future detour (a stray
7218 // `try_from` special-case that widens or narrows the accept-set
7219 // outside the paired `from_wire` resolver, an accidental swap
7220 // onto the kebab-case [`std::str::FromStr`] impl the
7221 // [`gen_platform::FromStrKind`] derive installs on the sibling
7222 // dispatcher-catalog axis) trips at caixa-core test time. Peer of
7223 // the sibling
7224 // [`crate::kind::tests::caixa_kind_try_from_str_and_from_wire_partition_the_accept_set`]
7225 // pin — extends the round-trip discipline onto the M2-OTP-shape
7226 // sibling-restart axis.
7227 let candidates: &[&str] = &[
7228 "OneForOne",
7229 "OneForAll",
7230 "RestForOne",
7231 "SimpleOneForOne",
7232 "",
7233 "one-for-one",
7234 "one-for-all",
7235 "rest-for-one",
7236 "simple-one-for-one",
7237 "oneforone",
7238 "unknown",
7239 "OneForOne ",
7240 " OneForOne",
7241 "\"OneForOne\"",
7242 "OneForEach",
7243 "?",
7244 ];
7245 for &input in candidates {
7246 let via_trait: Option<RestartStrategy> =
7247 <RestartStrategy as TryFrom<&str>>::try_from(input).ok();
7248 let via_method: Option<RestartStrategy> = RestartStrategy::from_wire(input);
7249 assert_eq!(
7250 via_trait, via_method,
7251 "TryFrom<&str> and from_wire must resolve identically on \
7252 input {input:?} — divergence signals the two reverse-\
7253 projection paths have drifted onto different accept-sets"
7254 );
7255 }
7256 }
7257
7258 #[test]
7259 fn restart_strategy_from_into_static_str_routes_through_as_str_accessor() {
7260 // Fail-before-pass-after byte-parity pin on the newly lifted
7261 // `impl From<RestartStrategy> for &'static str` — asserts the
7262 // standard-library trait impl and the substrate-primitive
7263 // [`RestartStrategy::as_str`] `pub const fn` accessor resolve to
7264 // the same four-arm emit-set across every arm the exhaustive
7265 // [`RestartStrategy::ALL`] slice enumerates. Any future silent
7266 // detour that routes the trait impl through a divergent
7267 // projection (a per-arm inline `match strategy { OneForOne =>
7268 // "OneForOne", … }` re-inlining that opens a compile-time link to
7269 // the un-lifted arm-literal, an accidental swap onto the sibling
7270 // kebab-case [`Self::discriminant`] dispatcher-catalog axis that
7271 // would collide the two-axis wire/catalog split the sibling
7272 // [`RestartStrategy::from_wire`] doc block makes load-bearing) trips
7273 // at caixa-core test time under `assert_eq!` rather than at a
7274 // downstream `impl Into<&'static str>`-bound consumer's silent
7275 // split. Sweeps every one of the four arms
7276 // [`RestartStrategy::ALL`] carries so no arm's projection is
7277 // covered only by the sibling method-named `as_str` /
7278 // [`std::fmt::Display`] / [`AsRef<str>`] paths. Materializes the
7279 // `<&'static str as From<RestartStrategy>>::from` output in a
7280 // `const`-shape binding to make the `'static` lifetime promise a
7281 // build-time invariant — a future accidental downgrade of any of
7282 // the four arms' [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
7283 // constants to a non-`&'static str` (a `String::leak()`-produced
7284 // return, a `Box::leak`-cast) trips at caixa-core build time
7285 // rather than at a downstream `'static`-bound consumer.
7286 const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
7287 const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
7288 const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
7289 const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
7290 for &variant in RestartStrategy::ALL {
7291 let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
7292 let via_method: &'static str = variant.as_str();
7293 assert_eq!(
7294 via_trait, via_method,
7295 "From<RestartStrategy> for &'static str impl must round-trip \
7296 RestartStrategy::{variant:?} to the same lifted \
7297 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str returns — \
7298 divergence signals a silent detour off the substrate-primitive \
7299 accessor"
7300 );
7301 let via_into: &'static str = variant.into();
7302 assert_eq!(
7303 via_into, via_method,
7304 "Into<&'static str>::into on RestartStrategy::{variant:?} must \
7305 byte-equal RestartStrategy::as_str on the same input — the \
7306 blanket-derived Into shape must resolve to the same as_str \
7307 dispatch as the explicit From impl"
7308 );
7309 }
7310 assert_eq!(
7311 [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
7312 [
7313 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7314 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7315 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7316 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7317 ],
7318 "const-context RestartStrategy::as_str must resolve to the four \
7319 lifted SUPERVISOR_ESTRATEGIA_* consts — a future accidental \
7320 downgrade of any arm to a non-const or non-static byte-string \
7321 breaks the `&'static str`-lifetime promise the paired \
7322 From<RestartStrategy> for &'static str impl carries by \
7323 construction"
7324 );
7325 }
7326
7327 #[test]
7328 fn restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set() {
7329 // Cross-axis partition pin: the paired trait-idiomatic
7330 // `From<RestartStrategy> for &'static str` forward projection and
7331 // the method-named [`RestartStrategy::as_str`] forward projection
7332 // must resolve identically on *every* arm, not just the ones
7333 // named in the primary byte-parity pin above. Sweeps every
7334 // [`RestartStrategy::ALL`] arm and asserts the trait's `From::from`
7335 // output byte-equals the method-named accessor's return-value on
7336 // each, locking the two forward-projection paths together by
7337 // construction so any future detour (a stray `From` special-case
7338 // that lands on a divergent per-arm literal outside the paired
7339 // `as_str` dispatch, a hypothetical rebrand touching one axis
7340 // without the other) trips at caixa-core test time. Peer of the
7341 // sibling reverse-projection partition pin
7342 // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
7343 // — extends the round-trip discipline onto the trait-idiomatic
7344 // *forward* axis, closing the two-way `Self ↔ &'static str`
7345 // round-trip on the trait-idiomatic pair
7346 // (`From<Self> for &'static str` + `TryFrom<&str> for Self`) as
7347 // well as the pre-existing method-named pair
7348 // (`as_str` + `from_wire`).
7349 for &variant in RestartStrategy::ALL {
7350 let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
7351 let via_method: &'static str = variant.as_str();
7352 assert_eq!(
7353 via_trait, via_method,
7354 "From<RestartStrategy> for &'static str and \
7355 RestartStrategy::as_str must resolve identically on \
7356 RestartStrategy::{variant:?} — divergence signals the \
7357 two forward-projection paths have drifted onto different \
7358 emit-sets"
7359 );
7360 }
7361 // Round-trip witness: every arm's forward `From` output re-parses
7362 // through the paired trait-idiomatic reverse `TryFrom<&str>` back
7363 // to the original variant. Closes the two-way `RestartStrategy ↔
7364 // &'static str` round-trip on the trait-idiomatic axis pair,
7365 // mirroring the pre-existing method-named `as_str` + `from_wire`
7366 // round-trip on the substrate-primitive axis pair.
7367 for &variant in RestartStrategy::ALL {
7368 let emitted: &'static str = variant.into();
7369 let re_parsed: Result<RestartStrategy, ()> =
7370 <RestartStrategy as TryFrom<&str>>::try_from(emitted);
7371 assert_eq!(
7372 re_parsed,
7373 Ok(variant),
7374 "trait-idiomatic axis pair must round-trip \
7375 RestartStrategy::{variant:?} through `.into::<&'static \
7376 str>()` and back through `TryFrom<&str>` — a break signals \
7377 the forward-emit and reverse-parse axes have drifted onto \
7378 different vocabularies"
7379 );
7380 }
7381 }
7382
7383 #[test]
7384 fn restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
7385 // Fail-before-pass-after byte-parity pin on the newly lifted
7386 // `impl From<&RestartStrategy> for &'static str` — asserts the
7387 // borrowed-input standard-library trait impl and the substrate-
7388 // primitive [`RestartStrategy::as_str`] `pub const fn` accessor
7389 // resolve to the same four-arm emit-set across every arm the
7390 // exhaustive [`RestartStrategy::ALL`] slice enumerates. Rust's
7391 // `From` trait does not auto-derive the borrowed-input sibling
7392 // from a paired owned-input impl (no `impl<T, U> From<&T> for U
7393 // where T: Copy, U: From<T>` blanket in `core`), so the
7394 // borrowed-input axis is a distinct trait-idiomatic surface
7395 // that a `.iter().map(Into::into)` shape over
7396 // [`RestartStrategy::ALL`] (whose iterator yields
7397 // `&RestartStrategy`, not `RestartStrategy`) reaches through
7398 // this impl and no other — the paired owned-input
7399 // [`From<RestartStrategy>`] impl requires an explicit
7400 // `.copied()` / dereference before the trait fires.
7401 // Materializes the `<&'static str as
7402 // From<&RestartStrategy>>::from` output in a `const`-shape
7403 // binding to make the `'static` lifetime promise a build-time
7404 // invariant.
7405 const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
7406 const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
7407 const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
7408 const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
7409 for variant in RestartStrategy::ALL {
7410 let via_trait: &'static str = <&'static str as From<&RestartStrategy>>::from(variant);
7411 let via_method: &'static str = variant.as_str();
7412 assert_eq!(
7413 via_trait, via_method,
7414 "From<&RestartStrategy> for &'static str impl must \
7415 round-trip &RestartStrategy::{variant:?} to the same \
7416 lifted SUPERVISOR_ESTRATEGIA_* const \
7417 RestartStrategy::as_str returns — divergence signals a \
7418 silent detour off the substrate-primitive accessor"
7419 );
7420 let via_into: &'static str = variant.into();
7421 assert_eq!(
7422 via_into, via_method,
7423 "Into<&'static str>::into on &RestartStrategy::{variant:?} \
7424 must byte-equal RestartStrategy::as_str on the same input — \
7425 the blanket-derived Into shape must resolve to the same \
7426 as_str dispatch as the explicit From impl"
7427 );
7428 }
7429 assert_eq!(
7430 [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
7431 [
7432 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7433 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7434 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7435 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7436 ],
7437 "const-context RestartStrategy::as_str must resolve to the \
7438 four lifted SUPERVISOR_ESTRATEGIA_* consts — the borrowed-\
7439 input From<&RestartStrategy> for &'static str impl inherits \
7440 its `'static` lifetime promise from the same accessor the \
7441 owned-input sibling routes through"
7442 );
7443 }
7444
7445 #[test]
7446 fn restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
7447 // Cross-axis partition pin: the paired trait-idiomatic
7448 // owned-input `From<RestartStrategy> for &'static str` (523157d
7449 // campaign-shape) and borrowed-input `From<&RestartStrategy> for
7450 // &'static str` (this lift) forward projections must resolve
7451 // identically on every arm, locking the two input-shape paths
7452 // together so any future detour trips at caixa-core test time.
7453 // Then a witness that a `.iter().map(Into::into)` pipe over
7454 // [`RestartStrategy::ALL`] (whose iterator yields
7455 // `&RestartStrategy`) materializes the four-arm accept-set
7456 // through the borrowed-input axis alone — the exact shape a
7457 // future wasm-operator per-supervisor sibling-restart-strategy
7458 // diagnostic line, a future substrate-wide per-arm diagnostic
7459 // column, or a
7460 // `HashMap::<&'static str, RestartStrategy>::from_iter(
7461 // RestartStrategy::ALL.iter().map(|s| (s.into(), *s)))`-style
7462 // per-strategy lookup reaches through — closing the two-way
7463 // owned/borrowed input-shape symmetry on the forward-projection
7464 // trait-idiomatic axis. Peer of the sibling
7465 // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
7466 // (64aa742) /
7467 // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
7468 // (5ab993a) /
7469 // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
7470 // (807b0b5) partition pins on the sibling closed-set typed-enum
7471 // discriminator axes — extends the borrowed-input axis
7472 // discipline onto the first M2 OTP-shape sibling-restart
7473 // closed-set typed enum on the caixa surface. Also closes the
7474 // direct two-way `&Self → &'static str → Self` round-trip via
7475 // the paired [`TryFrom<&str>`] axis — unlike the peer
7476 // [`crate::CaixaKind`] axis pair (whose forward `From` emits
7477 // lowercase Portuguese diagnostic bytes while the reverse
7478 // `TryFrom` parses `PascalCase` wire bytes, forcing the round-
7479 // trip through an intermediate wire-vocab hop), the
7480 // [`RestartStrategy::as_str`] emit and
7481 // [`RestartStrategy::from_wire`] parse share the same
7482 // `PascalCase` vocabulary by construction, so the borrowed-
7483 // input forward axis and the reverse axis compose directly.
7484 for &variant in RestartStrategy::ALL {
7485 let owned: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
7486 let borrowed: &'static str = <&'static str as From<&RestartStrategy>>::from(&variant);
7487 assert_eq!(
7488 owned, borrowed,
7489 "From<RestartStrategy> and From<&RestartStrategy> for \
7490 &'static str must resolve identically on \
7491 RestartStrategy::{variant:?} — divergence signals the \
7492 owned-input and borrowed-input forward-projection paths \
7493 have drifted onto different emit-sets"
7494 );
7495 }
7496 let via_iter: Vec<&'static str> = RestartStrategy::ALL.iter().map(Into::into).collect();
7497 let via_method: Vec<&'static str> =
7498 RestartStrategy::ALL.iter().map(|s| s.as_str()).collect();
7499 assert_eq!(
7500 via_iter, via_method,
7501 "`.iter().map(Into::into)` over RestartStrategy::ALL must \
7502 byte-equal `.iter().map(|s| s.as_str())` on every arm — the \
7503 borrowed-input `From<&RestartStrategy> for &'static str` \
7504 axis is what makes the `.iter().map(Into::into)` shape route \
7505 through the substrate-primitive `RestartStrategy::as_str` \
7506 accessor rather than through a per-call-site `.copied()` / \
7507 dereference detour"
7508 );
7509 for variant in RestartStrategy::ALL {
7510 let emitted: &'static str = variant.into();
7511 let re_parsed: Result<RestartStrategy, ()> =
7512 <RestartStrategy as TryFrom<&str>>::try_from(emitted);
7513 assert_eq!(
7514 re_parsed,
7515 Ok(*variant),
7516 "trait-idiomatic borrowed-input forward-projection + \
7517 reverse-projection axis pair must round-trip \
7518 &RestartStrategy::{variant:?} through `.into::<&'static \
7519 str>()` (via the borrowed-input axis) and back through \
7520 `TryFrom<&str>` — a break signals the borrowed-input \
7521 forward-emit and reverse-parse axes have drifted onto \
7522 different vocabularies"
7523 );
7524 }
7525 }
7526
7527 #[test]
7528 fn restart_strategy_from_into_owned_string_routes_through_as_str_accessor() {
7529 // Fail-before-pass-after byte-parity pin on the newly lifted
7530 // `impl From<RestartStrategy> for String` — asserts the
7531 // owned-`String`-returning standard-library trait impl and the
7532 // substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
7533 // accessor resolve to the same four-arm emit-set across every
7534 // arm the exhaustive [`RestartStrategy::ALL`] slice enumerates.
7535 // Rust's standard library does not carry a blanket
7536 // `impl<T: AsRef<str>> From<T> for String` (nor an
7537 // `impl<T: fmt::Display> From<T> for String`), so the
7538 // owned-`String` forward-projection axis is a distinct
7539 // trait-idiomatic surface that a
7540 // `let key: String = strategy.into();`-shaped call site
7541 // reaches through this impl and no other — the paired sibling
7542 // `From<RestartStrategy> for &'static str` impl forces every
7543 // owned-`String` call site through an explicit
7544 // `.to_owned()` / `String::from` restatement.
7545 for &variant in RestartStrategy::ALL {
7546 let via_trait: String = <String as From<RestartStrategy>>::from(variant);
7547 let via_method: &'static str = variant.as_str();
7548 assert_eq!(
7549 via_trait.as_str(),
7550 via_method,
7551 "From<RestartStrategy> for String impl must round-trip \
7552 RestartStrategy::{variant:?} to the same lifted \
7553 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
7554 returns — divergence signals a silent detour off the \
7555 substrate-primitive accessor"
7556 );
7557 let via_into: String = variant.into();
7558 assert_eq!(
7559 via_into.as_str(),
7560 via_method,
7561 "Into<String>::into on RestartStrategy::{variant:?} must \
7562 byte-equal RestartStrategy::as_str on the same input — the \
7563 blanket-derived Into shape must resolve to the same as_str \
7564 dispatch as the explicit From impl"
7565 );
7566 }
7567 }
7568
7569 #[test]
7570 fn restart_strategy_from_into_owned_string_and_static_str_agree_on_every_arm() {
7571 // Cross-axis partition pin: the paired trait-idiomatic
7572 // owned-`String` `From<RestartStrategy> for String` (this lift)
7573 // and owned-`&'static str` `From<RestartStrategy> for &'static
7574 // str` (523157d) forward projections must resolve identically
7575 // on every arm, locking the two return-type-shape paths
7576 // together so any future detour trips at caixa-core test time.
7577 // Also byte-parity witness against the sibling
7578 // [`ToString::to_string`] surface routed through
7579 // [`std::fmt::Display`] — the three owned-heap-string paths
7580 // (`.into::<String>()`, `String::from`, `.to_string()`) must
7581 // resolve identically on every arm so a future consumer that
7582 // picks any of the three lands on the same lifted
7583 // SUPERVISOR_ESTRATEGIA_* const. Then a direct round-trip
7584 // witness through the paired trait-idiomatic reverse
7585 // [`TryFrom<&str>`] axis on the owned-`String`'s
7586 // [`String::as_str`] borrow that closes the two-way
7587 // `Self → String → Self` round-trip on the trait-idiomatic
7588 // owned-`String` forward + reverse axis pair.
7589 for &variant in RestartStrategy::ALL {
7590 let owned_string: String = <String as From<RestartStrategy>>::from(variant);
7591 let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
7592 assert_eq!(
7593 owned_string.as_str(),
7594 owned_static,
7595 "From<RestartStrategy> for String and From<RestartStrategy> \
7596 for &'static str must resolve identically on \
7597 RestartStrategy::{variant:?} — divergence signals the \
7598 owned-`String` and owned-`&'static str` forward-projection \
7599 return-type-shape paths have drifted onto different \
7600 emit-sets"
7601 );
7602 let via_to_string: String = variant.to_string();
7603 assert_eq!(
7604 owned_string, via_to_string,
7605 "From<RestartStrategy> for String must byte-equal \
7606 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
7607 divergence signals the trait-idiomatic owned-`String` \
7608 forward-projection axis and the ToString-through-Display \
7609 axis have drifted onto different emit-sets"
7610 );
7611 }
7612 let via_iter: Vec<String> = RestartStrategy::ALL
7613 .iter()
7614 .copied()
7615 .map(String::from)
7616 .collect();
7617 let via_method: Vec<String> = RestartStrategy::ALL
7618 .iter()
7619 .map(|s| s.as_str().to_owned())
7620 .collect();
7621 assert_eq!(
7622 via_iter, via_method,
7623 "`.iter().copied().map(String::from)` over RestartStrategy::ALL \
7624 must byte-equal `.iter().map(|s| s.as_str().to_owned())` on \
7625 every arm — the owned-`String` `From<RestartStrategy> for \
7626 String` axis is what makes the `String::from` composition \
7627 route through the substrate-primitive `RestartStrategy::as_str` \
7628 accessor rather than through a per-call-site `.to_owned()` / \
7629 `String::from(strategy.as_str())` detour"
7630 );
7631 for &variant in RestartStrategy::ALL {
7632 let emitted: String = variant.into();
7633 let re_parsed: Result<RestartStrategy, ()> =
7634 <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
7635 assert_eq!(
7636 re_parsed,
7637 Ok(variant),
7638 "trait-idiomatic owned-`String` forward-projection + \
7639 reverse-projection axis pair must round-trip \
7640 RestartStrategy::{variant:?} through `.into::<String>()` \
7641 and back through `TryFrom<&str>` on the owned-`String`'s \
7642 String::as_str borrow — a break signals the owned-`String` \
7643 forward-emit and reverse-parse axes have drifted onto \
7644 different vocabularies"
7645 );
7646 }
7647 }
7648
7649 #[test]
7650 fn restart_policy_try_from_str_routes_through_from_wire_accessor() {
7651 // Fail-before-pass-after byte-parity pin on the newly lifted
7652 // `impl TryFrom<&str> for RestartPolicy` — asserts the standard-
7653 // library trait impl and the substrate-primitive
7654 // [`RestartPolicy::from_wire`] `Option<Self>` accessor resolve to
7655 // the same three-arm accept-set across every arm the exhaustive
7656 // [`RestartPolicy::ALL`] slice enumerates. Any future silent
7657 // detour that routes the trait impl through a divergent
7658 // projection (a per-arm inline `match s { "Permanent" =>
7659 // Ok(Self::Permanent), … }` re-inlining that opens a compile-time
7660 // link to the un-lifted arm-literal, a hypothetical
7661 // `#[serde(rename_all = "…")]` attribute drift that silently
7662 // splits the wire byte-string from every consumer that reaches
7663 // for this typed dispatch, an accidental swap onto the kebab-case
7664 // dispatcher-catalog axis the pre-existing [`std::str::FromStr`]
7665 // impl parses through and which would collide the two-axis
7666 // wire/catalog split the sibling [`RestartPolicy::from_wire`]
7667 // doc block makes load-bearing) trips at caixa-core test time
7668 // under `assert_eq!` rather than at a downstream
7669 // `impl TryFrom<&str>`-bound consumer's silent split. Sweeps
7670 // every one of the three arms [`RestartPolicy::ALL`] carries so
7671 // no arm's projection is covered only by the sibling method-
7672 // named `from_wire` path. Peer of the sibling
7673 // [`restart_strategy_try_from_str_routes_through_from_wire_accessor`]
7674 // (5b828ed) — extends the trait-idiomatic reverse-projection
7675 // axis onto the third and final M2-OTP-shape closed-set typed
7676 // enum on the caixa surface (the paired per-child restart-
7677 // decision-policy sibling on the same M2 `:supervisor` slot).
7678 for &variant in RestartPolicy::ALL {
7679 let wire = variant.as_str();
7680 assert_eq!(
7681 <RestartPolicy as TryFrom<&str>>::try_from(wire),
7682 Ok(variant),
7683 "TryFrom<&str> impl on RestartPolicy must round-trip \
7684 RestartPolicy::{variant:?}.as_str() = {wire:?} back to \
7685 Ok(RestartPolicy::{variant:?}) — divergence from \
7686 RestartPolicy::from_wire signals a silent detour off \
7687 the substrate-primitive accessor"
7688 );
7689 assert_eq!(
7690 <RestartPolicy as TryFrom<&str>>::try_from(wire).ok(),
7691 RestartPolicy::from_wire(wire),
7692 "TryFrom<&str> ok()-projection on {wire:?} must byte-\
7693 equal RestartPolicy::from_wire on the same input"
7694 );
7695 }
7696 }
7697
7698 #[test]
7699 fn restart_policy_try_from_str_rejects_unknown_byte_strings() {
7700 // Rejection witness on the `impl TryFrom<&str> for
7701 // RestartPolicy` — sweeps a candidate set of byte-strings
7702 // outside the three-arm PascalCase wire accept-set the sibling
7703 // [`RestartPolicy::as_str`] emits and asserts every one lands on
7704 // `Err(())`, so a future accidental widening of the trait impl's
7705 // accept-set (a stray additional
7706 // `_ if s.eq_ignore_ascii_case("Permanent") => Ok(…)` case-fold
7707 // path, a silent inclusion of the kebab-case dispatcher-catalog
7708 // byte-string the pre-existing [`std::str::FromStr`] impl the
7709 // [`gen_platform::FromStrKind`] derive installs parses onto the
7710 // wire axis — which would collide the two-axis
7711 // wire/dispatcher-catalog split the sibling
7712 // [`RestartPolicy::from_wire`] doc block makes load-bearing —
7713 // an English-rebrand or plural-arm silent alias that would widen
7714 // the wire accept-set past the OTP-canonical three) trips at
7715 // caixa-core test time. The candidate set includes the empty
7716 // string, whitespace-only padding, the kebab-case dispatcher-
7717 // catalog byte-strings on the sibling axis (a caller who
7718 // confuses the two axes trips here rather than at a downstream
7719 // consumer's silent reject), a lowercase / uppercase / mixed-case
7720 // fold of each PascalCase arm (a caller who assumes case-fold
7721 // acceptance trips here), leading/trailing whitespace padding,
7722 // the trailing-newline shape, quote-wrapped candidates, and a
7723 // residual set of plausible-but-wrong English rebrand
7724 // candidates. Peer of the sibling
7725 // [`restart_strategy_try_from_str_rejects_unknown_byte_strings`]
7726 // (5b828ed) rejection witness.
7727 let rejected: &[&str] = &[
7728 "",
7729 " ",
7730 "\n",
7731 "\t",
7732 "permanent",
7733 "temporary",
7734 "transient",
7735 "PERMANENT",
7736 "TEMPORARY",
7737 "TRANSIENT",
7738 "Permanents",
7739 "Permanent ",
7740 " Permanent",
7741 " Temporary ",
7742 "Permanent\n",
7743 "Transient\t",
7744 "\"Permanent\"",
7745 "Ephemeral",
7746 "Always",
7747 "Never",
7748 "OnAbnormalExit",
7749 "intrinsic",
7750 "?",
7751 ];
7752 for &input in rejected {
7753 assert_eq!(
7754 <RestartPolicy as TryFrom<&str>>::try_from(input),
7755 Err(()),
7756 "TryFrom<&str> impl on RestartPolicy must reject the \
7757 non-wire byte-string {input:?} — silent acceptance \
7758 signals an accept-set widening off the paired \
7759 RestartPolicy::from_wire resolver"
7760 );
7761 }
7762 }
7763
7764 #[test]
7765 fn restart_policy_try_from_str_and_from_wire_partition_the_accept_set() {
7766 // Cross-axis partition pin: the paired `TryFrom<&str>` and
7767 // `from_wire` reverse projections must resolve identically on
7768 // *every* input, not just the ones [`RestartPolicy::ALL`]
7769 // enumerates. Sweeps a mixed candidate set spanning accepted
7770 // (three-arm PascalCase wire byte-strings) and rejected (kebab-
7771 // case dispatcher-catalog byte-strings, empty, whitespace-
7772 // padded, quoted, English-rebrand candidates) inputs and asserts
7773 // the trait's `Result::ok()` projection byte-equals the method-
7774 // named resolver's `Option<Self>` return-shape on each, locking
7775 // the two paths together by construction so any future detour
7776 // (a stray `try_from` special-case that widens or narrows the
7777 // accept-set outside the paired `from_wire` resolver, an
7778 // accidental swap onto the kebab-case [`std::str::FromStr`]
7779 // impl the [`gen_platform::FromStrKind`] derive installs on the
7780 // sibling dispatcher-catalog axis) trips at caixa-core test
7781 // time. Peer of the sibling
7782 // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
7783 // pin — extends the round-trip discipline onto the M2-OTP-shape
7784 // per-child restart-policy axis.
7785 let candidates: &[&str] = &[
7786 "Permanent",
7787 "Temporary",
7788 "Transient",
7789 "",
7790 "permanent",
7791 "temporary",
7792 "transient",
7793 "PERMANENT",
7794 "unknown",
7795 "Permanent ",
7796 " Permanent",
7797 "\"Permanent\"",
7798 "Ephemeral",
7799 "OnAbnormalExit",
7800 "?",
7801 ];
7802 for &input in candidates {
7803 let via_trait: Option<RestartPolicy> =
7804 <RestartPolicy as TryFrom<&str>>::try_from(input).ok();
7805 let via_method: Option<RestartPolicy> = RestartPolicy::from_wire(input);
7806 assert_eq!(
7807 via_trait, via_method,
7808 "TryFrom<&str> and from_wire must resolve identically on \
7809 input {input:?} — divergence signals the two reverse-\
7810 projection paths have drifted onto different accept-sets"
7811 );
7812 }
7813 }
7814
7815 #[test]
7816 fn restart_policy_from_into_static_str_routes_through_as_str_accessor() {
7817 // Fail-before-pass-after byte-parity pin on the newly lifted
7818 // `impl From<RestartPolicy> for &'static str` — asserts the
7819 // standard-library trait impl and the substrate-primitive
7820 // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
7821 // the same three-arm emit-set across every arm the exhaustive
7822 // [`RestartPolicy::ALL`] slice enumerates. Any future silent
7823 // detour that routes the trait impl through a divergent
7824 // projection (a per-arm inline `match policy { Permanent =>
7825 // "Permanent", … }` re-inlining that opens a compile-time link
7826 // to the un-lifted arm-literal, an accidental swap onto the
7827 // sibling kebab-case [`Self::discriminant`] dispatcher-catalog
7828 // axis that would collide the two-axis wire/catalog split the
7829 // sibling [`RestartPolicy::from_wire`] doc block makes
7830 // load-bearing) trips at caixa-core test time under
7831 // `assert_eq!` rather than at a downstream
7832 // `impl Into<&'static str>`-bound consumer's silent split.
7833 // Sweeps every one of the three arms [`RestartPolicy::ALL`]
7834 // carries so no arm's projection is covered only by the sibling
7835 // method-named `as_str` / [`std::fmt::Display`] / [`AsRef<str>`]
7836 // paths. Materializes the `<&'static str as
7837 // From<RestartPolicy>>::from` output in a `const`-shape binding
7838 // to make the `'static` lifetime promise a build-time invariant
7839 // — a future accidental downgrade of any of the three arms'
7840 // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] constants to a
7841 // non-`&'static str` (a `String::leak()`-produced return, a
7842 // `Box::leak`-cast) trips at caixa-core build time rather than
7843 // at a downstream `'static`-bound consumer. Peer of the sibling
7844 // [`restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
7845 // (523157d) — extends the trait-idiomatic forward-projection
7846 // axis onto the second (and second-of-two-in-M2) closed-set
7847 // typed enum on the caixa surface (the paired per-child
7848 // restart-decision-policy sibling on the same M2 `:supervisor`
7849 // slot).
7850 const PERMANENT: &str = RestartPolicy::Permanent.as_str();
7851 const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
7852 const TRANSIENT: &str = RestartPolicy::Transient.as_str();
7853 for &variant in RestartPolicy::ALL {
7854 let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
7855 let via_method: &'static str = variant.as_str();
7856 assert_eq!(
7857 via_trait, via_method,
7858 "From<RestartPolicy> for &'static str impl must round-trip \
7859 RestartPolicy::{variant:?} to the same lifted \
7860 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str returns — \
7861 divergence signals a silent detour off the substrate-primitive \
7862 accessor"
7863 );
7864 let via_into: &'static str = variant.into();
7865 assert_eq!(
7866 via_into, via_method,
7867 "Into<&'static str>::into on RestartPolicy::{variant:?} must \
7868 byte-equal RestartPolicy::as_str on the same input — the \
7869 blanket-derived Into shape must resolve to the same as_str \
7870 dispatch as the explicit From impl"
7871 );
7872 }
7873 assert_eq!(
7874 [PERMANENT, TEMPORARY, TRANSIENT],
7875 [
7876 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
7877 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
7878 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
7879 ],
7880 "const-context RestartPolicy::as_str must resolve to the three \
7881 lifted SUPERVISOR_CHILD_RESTART_* consts — a future accidental \
7882 downgrade of any arm to a non-const or non-static byte-string \
7883 breaks the `&'static str`-lifetime promise the paired \
7884 From<RestartPolicy> for &'static str impl carries by \
7885 construction"
7886 );
7887 }
7888
7889 #[test]
7890 fn restart_policy_from_into_static_str_and_as_str_partition_the_emit_set() {
7891 // Cross-axis partition pin: the paired trait-idiomatic
7892 // `From<RestartPolicy> for &'static str` forward projection and
7893 // the method-named [`RestartPolicy::as_str`] forward projection
7894 // must resolve identically on *every* arm, not just the ones
7895 // named in the primary byte-parity pin above. Sweeps every
7896 // [`RestartPolicy::ALL`] arm and asserts the trait's `From::from`
7897 // output byte-equals the method-named accessor's return-value on
7898 // each, locking the two forward-projection paths together by
7899 // construction so any future detour (a stray `From` special-case
7900 // that lands on a divergent per-arm literal outside the paired
7901 // `as_str` dispatch, a hypothetical rebrand touching one axis
7902 // without the other) trips at caixa-core test time. Peer of the
7903 // sibling forward-projection partition pin
7904 // [`restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
7905 // (523157d) — extends the round-trip discipline onto the
7906 // second-of-two M2-OTP-shape closed-set typed enum on the caixa
7907 // surface, closing the two-way `Self ↔ &'static str` round-trip
7908 // on the trait-idiomatic pair (`From<Self> for &'static str` +
7909 // `TryFrom<&str> for Self`) as well as the pre-existing method-
7910 // named pair (`as_str` + `from_wire`).
7911 for &variant in RestartPolicy::ALL {
7912 let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
7913 let via_method: &'static str = variant.as_str();
7914 assert_eq!(
7915 via_trait, via_method,
7916 "From<RestartPolicy> for &'static str and \
7917 RestartPolicy::as_str must resolve identically on \
7918 RestartPolicy::{variant:?} — divergence signals the \
7919 two forward-projection paths have drifted onto different \
7920 emit-sets"
7921 );
7922 }
7923 // Round-trip witness: every arm's forward `From` output re-parses
7924 // through the paired trait-idiomatic reverse `TryFrom<&str>` back
7925 // to the original variant. Closes the two-way `RestartPolicy ↔
7926 // &'static str` round-trip on the trait-idiomatic axis pair,
7927 // mirroring the pre-existing method-named `as_str` + `from_wire`
7928 // round-trip on the substrate-primitive axis pair.
7929 for &variant in RestartPolicy::ALL {
7930 let emitted: &'static str = variant.into();
7931 let re_parsed: Result<RestartPolicy, ()> =
7932 <RestartPolicy as TryFrom<&str>>::try_from(emitted);
7933 assert_eq!(
7934 re_parsed,
7935 Ok(variant),
7936 "trait-idiomatic axis pair must round-trip \
7937 RestartPolicy::{variant:?} through `.into::<&'static \
7938 str>()` and back through `TryFrom<&str>` — a break signals \
7939 the forward-emit and reverse-parse axes have drifted onto \
7940 different vocabularies"
7941 );
7942 }
7943 }
7944
7945 #[test]
7946 fn restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
7947 // Fail-before-pass-after byte-parity pin on the newly lifted
7948 // `impl From<&RestartPolicy> for &'static str` — asserts the
7949 // borrowed-input standard-library trait impl and the substrate-
7950 // primitive [`RestartPolicy::as_str`] `pub const fn` accessor
7951 // resolve to the same three-arm emit-set across every arm the
7952 // exhaustive [`RestartPolicy::ALL`] slice enumerates. Rust's
7953 // `From` trait does not auto-derive the borrowed-input sibling
7954 // from a paired owned-input impl (no `impl<T, U> From<&T> for U
7955 // where T: Copy, U: From<T>` blanket in `core`), so the
7956 // borrowed-input axis is a distinct trait-idiomatic surface
7957 // that a `.iter().map(Into::into)` shape over
7958 // [`RestartPolicy::ALL`] (whose iterator yields
7959 // `&RestartPolicy`, not `RestartPolicy`) reaches through this
7960 // impl and no other — the paired owned-input
7961 // [`From<RestartPolicy>`] impl requires an explicit `.copied()`
7962 // / dereference before the trait fires. Materializes the
7963 // `<&'static str as From<&RestartPolicy>>::from` output in a
7964 // `const`-shape binding to make the `'static` lifetime promise
7965 // a build-time invariant.
7966 const PERMANENT: &str = RestartPolicy::Permanent.as_str();
7967 const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
7968 const TRANSIENT: &str = RestartPolicy::Transient.as_str();
7969 for variant in RestartPolicy::ALL {
7970 let via_trait: &'static str = <&'static str as From<&RestartPolicy>>::from(variant);
7971 let via_method: &'static str = variant.as_str();
7972 assert_eq!(
7973 via_trait, via_method,
7974 "From<&RestartPolicy> for &'static str impl must round-trip \
7975 &RestartPolicy::{variant:?} to the same lifted \
7976 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
7977 returns — divergence signals a silent detour off the \
7978 substrate-primitive accessor"
7979 );
7980 let via_into: &'static str = variant.into();
7981 assert_eq!(
7982 via_into, via_method,
7983 "Into<&'static str>::into on &RestartPolicy::{variant:?} \
7984 must byte-equal RestartPolicy::as_str on the same input — \
7985 the blanket-derived Into shape must resolve to the same \
7986 as_str dispatch as the explicit From impl"
7987 );
7988 }
7989 assert_eq!(
7990 [PERMANENT, TEMPORARY, TRANSIENT],
7991 [
7992 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
7993 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
7994 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
7995 ],
7996 "const-context RestartPolicy::as_str must resolve to the three \
7997 lifted SUPERVISOR_CHILD_RESTART_* consts — the borrowed-input \
7998 From<&RestartPolicy> for &'static str impl inherits its \
7999 `'static` lifetime promise from the same accessor the \
8000 owned-input sibling routes through"
8001 );
8002 }
8003
8004 #[test]
8005 fn restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
8006 // Cross-axis partition pin: the paired trait-idiomatic
8007 // owned-input `From<RestartPolicy> for &'static str` (9fb37d0
8008 // campaign-shape) and borrowed-input `From<&RestartPolicy> for
8009 // &'static str` (this lift) forward projections must resolve
8010 // identically on every arm, locking the two input-shape paths
8011 // together so any future detour trips at caixa-core test time.
8012 // Then a witness that a `.iter().map(Into::into)` pipe over
8013 // [`RestartPolicy::ALL`] (whose iterator yields
8014 // `&RestartPolicy`) materializes the three-arm accept-set
8015 // through the borrowed-input axis alone — the exact shape a
8016 // future wasm-operator per-child post-exit restart-decision
8017 // diagnostic line, a future substrate-wide per-arm diagnostic
8018 // column, or a
8019 // `HashMap::<&'static str, RestartPolicy>::from_iter(
8020 // RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
8021 // per-policy lookup reaches through — closing the two-way
8022 // owned/borrowed input-shape symmetry on the forward-projection
8023 // trait-idiomatic axis. Peer of the sibling
8024 // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8025 // (64aa742) /
8026 // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8027 // (5ab993a) /
8028 // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8029 // (807b0b5) /
8030 // [`restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8031 // (e941836) partition pins on the sibling closed-set typed-enum
8032 // discriminator axes — extends the borrowed-input axis
8033 // discipline onto the second-of-two M2 OTP-shape closed-set
8034 // typed enum on the caixa surface (per-child restart-decision
8035 // policy). Also closes the direct two-way `&Self → &'static
8036 // str → Self` round-trip via the paired [`TryFrom<&str>`] axis
8037 // — unlike the peer [`crate::CaixaKind`] axis pair (whose
8038 // forward `From` emits lowercase Portuguese diagnostic bytes
8039 // while the reverse `TryFrom` parses `PascalCase` wire bytes,
8040 // forcing the round-trip through an intermediate wire-vocab
8041 // hop), the [`RestartPolicy::as_str`] emit and
8042 // [`RestartPolicy::from_wire`] parse share the same
8043 // `PascalCase` vocabulary by construction, so the borrowed-
8044 // input forward axis and the reverse axis compose directly.
8045 for &variant in RestartPolicy::ALL {
8046 let owned: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
8047 let borrowed: &'static str = <&'static str as From<&RestartPolicy>>::from(&variant);
8048 assert_eq!(
8049 owned, borrowed,
8050 "From<RestartPolicy> and From<&RestartPolicy> for \
8051 &'static str must resolve identically on \
8052 RestartPolicy::{variant:?} — divergence signals the \
8053 owned-input and borrowed-input forward-projection paths \
8054 have drifted onto different emit-sets"
8055 );
8056 }
8057 let via_iter: Vec<&'static str> = RestartPolicy::ALL.iter().map(Into::into).collect();
8058 let via_method: Vec<&'static str> = RestartPolicy::ALL.iter().map(|p| p.as_str()).collect();
8059 assert_eq!(
8060 via_iter, via_method,
8061 "`.iter().map(Into::into)` over RestartPolicy::ALL must \
8062 byte-equal `.iter().map(|p| p.as_str())` on every arm — the \
8063 borrowed-input `From<&RestartPolicy> for &'static str` axis \
8064 is what makes the `.iter().map(Into::into)` shape route \
8065 through the substrate-primitive `RestartPolicy::as_str` \
8066 accessor rather than through a per-call-site `.copied()` / \
8067 dereference detour"
8068 );
8069 for variant in RestartPolicy::ALL {
8070 let emitted: &'static str = variant.into();
8071 let re_parsed: Result<RestartPolicy, ()> =
8072 <RestartPolicy as TryFrom<&str>>::try_from(emitted);
8073 assert_eq!(
8074 re_parsed,
8075 Ok(*variant),
8076 "trait-idiomatic borrowed-input forward-projection + \
8077 reverse-projection axis pair must round-trip \
8078 &RestartPolicy::{variant:?} through `.into::<&'static \
8079 str>()` (via the borrowed-input axis) and back through \
8080 `TryFrom<&str>` — a break signals the borrowed-input \
8081 forward-emit and reverse-parse axes have drifted onto \
8082 different vocabularies"
8083 );
8084 }
8085 }
8086
8087 // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_RESTART_* identity ─
8088
8089 #[test]
8090 fn restart_policy_variants_serialize_to_lifted_scalar_values() {
8091 // The fail-before-pass-after pin: pre-lift there was no
8092 // single-source binding between the [`RestartPolicy`] variant
8093 // name the un-`rename`d `Serialize` derive emits under
8094 // [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
8095 // byte-string every downstream cluster-side dispatcher (the
8096 // future wasm-operator's per-child post-exit restart-decision
8097 // branch, the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
8098 // materializer's admission-time enum-arm bind, the
8099 // `caixa-operator`'s hierarchical reconciliation scheduler's
8100 // per-child-policy fan-out) probes verbatim. A future
8101 // `#[serde(rename_all = "kebab-case")]` attribute on the enum —
8102 // or a per-variant `#[serde(rename = "…")]` override, or a
8103 // variant rename in the source — would silently rebrand the
8104 // emitted scalar under one spelling while every downstream
8105 // dispatcher still probed the other, with the failure surfacing
8106 // at the operator's reconcile posture (children coming up under
8107 // the `default()` `Permanent` arm rather than the typed slot's
8108 // declared policy — a `:temporary` `oneShot` child would be
8109 // restarted on clean exit, treating the successful-completion
8110 // signal as failure and re-running the completion-terminal
8111 // one-shot indefinitely; a `:transient` child that clean-exited
8112 // would be restarted, masking the clean-completion contract)
8113 // far from the source rebrand commit and with no field naming
8114 // the drift. Pinning the two paths (the `Serialize` derive's
8115 // serialized string AND the [`RestartPolicy::as_str`] helper)
8116 // to the same three lifted
8117 // [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
8118 // [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
8119 // [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
8120 // byte-strings makes any future drift on either endpoint fail
8121 // here at caixa-core build time. Peer of the sibling
8122 // [`restart_strategy_variants_serialize_to_lifted_scalar_values`]
8123 // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
8124 // and the M3
8125 // `placement_strategy_variants_serialize_to_lifted_scalar_values`
8126 // (3f0e21c) on the per-Aplicacao distribution-strategy axis —
8127 // same three-path-convergence discipline, extended to close the
8128 // third OTP-shaped closed-enum discriminator axis on the caixa
8129 // typed surface (per-child restart-decision policy).
8130 for (variant, expected) in [
8131 (
8132 RestartPolicy::Permanent,
8133 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
8134 ),
8135 (
8136 RestartPolicy::Temporary,
8137 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
8138 ),
8139 (
8140 RestartPolicy::Transient,
8141 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
8142 ),
8143 ] {
8144 let json = serde_json::to_string(&variant).unwrap();
8145 assert_eq!(
8146 json,
8147 format!("\"{expected}\""),
8148 "RestartPolicy::{variant:?} must serialize to {expected:?}"
8149 );
8150 assert_eq!(
8151 variant.as_str(),
8152 expected,
8153 "RestartPolicy::{variant:?}.as_str() must return the lifted \
8154 SUPERVISOR_CHILD_RESTART_* constant"
8155 );
8156 }
8157 }
8158
8159 #[test]
8160 fn supervisor_child_restart_consts_are_pairwise_distinct() {
8161 // Cross-arm drift-detection pin: a future collapse of two
8162 // canonical variant byte-strings onto the same value (e.g. an
8163 // accidental copy-paste flip of `SUPERVISOR_CHILD_RESTART_TRANSIENT`
8164 // to also read `"Permanent"`) would silently reroute every
8165 // downstream operator's per-child-policy dispatch onto the
8166 // sibling arm's reconcile branch and pass every propagation-probe
8167 // test that expected only the stale arm's value — a `:transient`
8168 // child would come up under the `:permanent` restart-decision
8169 // posture on every subsequent clean exit, so a completion-terminal
8170 // child would be restarted indefinitely against its declared
8171 // policy. Peer of the sibling
8172 // [`supervisor_estrategia_consts_are_pairwise_distinct`]
8173 // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
8174 // and the four-way distinct pin
8175 // `supervisor_key_consts_are_pairwise_distinct` (40cc4e5) on the
8176 // top-level `SUPERVISOR_KEY_*` axis.
8177 let all = [
8178 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
8179 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
8180 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
8181 ];
8182 for (i, a) in all.iter().enumerate() {
8183 for (j, b) in all.iter().enumerate() {
8184 if i != j {
8185 assert_ne!(
8186 a, b,
8187 "SUPERVISOR_CHILD_RESTART_* consts must be pairwise distinct \
8188 — got duplicate {a:?} at indices {i} and {j}",
8189 );
8190 }
8191 }
8192 }
8193 }
8194
8195 #[test]
8196 fn restart_policy_display_routes_through_as_str_helper() {
8197 // The fail-before-pass-after pin on the first half of the
8198 // three-path convergence: pre-convergence [`RestartPolicy`]
8199 // carried a [`std::fmt::Display`] surface via its
8200 // `#[discriminant(also_display)]` gen-platform derive route,
8201 // which arrived kebab-case as `"permanent"` / `"temporary"`
8202 // / `"transient"` on this three-arm enum (whose variant
8203 // names each collapse to their own lowercase form under the
8204 // kebab-case transform) while the wire format ran as
8205 // PascalCase `"Permanent"` / `"Temporary"` / `"Transient"`
8206 // through the un-`rename`d serde derive. Every consumer
8207 // reaching for a policy byte-string past the wire format had
8208 // to pick between three paths ([`RestartPolicy::as_str`],
8209 // the `Serialize` derive's serialized string, or
8210 // `format!("{v}")` on the discriminant-Display route), any
8211 // two of which a future variant rename or
8212 // `#[serde(rename_all = "kebab-case")]` attribute would
8213 // silently desynchronize. Wiring [`std::fmt::Display`]
8214 // through [`RestartPolicy::as_str`] closes the third path:
8215 // every `format!("{v}")` call reaches the same lifted
8216 // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the
8217 // wire format and the [`RestartPolicy::as_str`] helper
8218 // already route through, so a future variant rename lands at
8219 // exactly one place. Pin the routing here so a future
8220 // `impl std::fmt::Display for RestartPolicy`
8221 // reimplementation that hand-rolls the arms instead of
8222 // delegating to [`RestartPolicy::as_str`] fails at
8223 // caixa-core build time. Peer of the sibling
8224 // [`restart_strategy_display_routes_through_as_str_helper`]
8225 // on the per-supervisor sibling-restart-strategy axis and
8226 // the M3
8227 // `placement_strategy_display_routes_through_as_str_helper`
8228 // (cc8f749) — the third of three OTP-shape closed-enum
8229 // discriminator axes on the caixa typed surface now
8230 // converged onto the same three-path
8231 // (Display → as_str → lifted const) discipline.
8232 for variant in [
8233 RestartPolicy::Permanent,
8234 RestartPolicy::Temporary,
8235 RestartPolicy::Transient,
8236 ] {
8237 assert_eq!(
8238 variant.to_string(),
8239 variant.as_str(),
8240 "RestartPolicy::{variant:?} Display must route through \
8241 RestartPolicy::as_str (single source of truth: the lifted \
8242 SUPERVISOR_CHILD_RESTART_* const the wire format also emits)"
8243 );
8244 }
8245 }
8246
8247 #[test]
8248 fn restart_policy_display_matches_serialized_wire_byte_string() {
8249 // The fail-before-pass-after pin on the second half of the
8250 // three-path convergence: `Display` (user-facing text) agrees
8251 // byte-for-byte with the `Serialize` derive's wire format
8252 // (canonical camelCase-schema `SUPERVISOR_CHILD_KEY_RESTART`
8253 // scalar) on every variant. Pre-convergence the two paths
8254 // were structurally independent — a future
8255 // `#[serde(rename_all = "kebab-case")]` attribute on the
8256 // enum would silently rebrand the emitted wire scalar
8257 // (`permanent`, `temporary`, `transient`) while every
8258 // consumer that pretty-prints the policy (the future
8259 // wasm-operator's per-child post-exit restart-decision
8260 // diagnostic line, the future `feira app graph` per-child
8261 // restart column, the future M4
8262 // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
8263 // per-child admission-webhook rejection body) would still
8264 // emit the PascalCase form the `as_str` / `Display` route
8265 // returns, with the mismatch surfacing at consumer parse
8266 // time / operator dispatch time far from the source rebrand
8267 // commit. Pin the two paths byte-for-byte here so any future
8268 // serde-attribute or variant-rename drift is a
8269 // caixa-core-build-time test failure at this call, not a
8270 // silent per-consumer dispatch miss. Peer of the sibling
8271 // [`restart_strategy_display_matches_serialized_wire_byte_string`]
8272 // on the per-supervisor sibling-restart-strategy axis and
8273 // the M3
8274 // `placement_strategy_display_matches_serialized_wire_byte_string`
8275 // (cc8f749).
8276 for variant in [
8277 RestartPolicy::Permanent,
8278 RestartPolicy::Temporary,
8279 RestartPolicy::Transient,
8280 ] {
8281 let wire = serde_json::to_string(&variant).unwrap();
8282 let unquoted = wire
8283 .strip_prefix('"')
8284 .and_then(|s| s.strip_suffix('"'))
8285 .expect("serialized RestartPolicy is a JSON string");
8286 assert_eq!(
8287 variant.to_string(),
8288 unquoted,
8289 "RestartPolicy::{variant:?} Display byte-string must match the \
8290 Serialize derive's wire byte-string (three-path convergence: \
8291 Display + as_str + Serialize all resolve to the same \
8292 SUPERVISOR_CHILD_RESTART_* const)"
8293 );
8294 }
8295 }
8296
8297 #[test]
8298 fn restart_policy_as_ref_str_routes_through_as_str_accessor() {
8299 // Fail-before-pass-after byte-parity pin on the lifted
8300 // `impl AsRef<str> for RestartPolicy` — asserts the
8301 // standard-library trait impl and the substrate-primitive
8302 // [`RestartPolicy::as_str`] `pub const fn` accessor resolve
8303 // to the same `&str` per instance across the three-arm
8304 // closed set, so any future silent detour that routes the
8305 // impl through a divergent projection (a per-arm inline
8306 // `match self { RestartPolicy::Permanent => "Permanent", … }`
8307 // re-inlining that opens a compile-time link to the un-lifted
8308 // arm-literal, a swap onto the kebab-case
8309 // [`gen_platform::Discriminant`] catalog identity that would
8310 // collide the wire axis with the dispatcher-catalog axis) trips
8311 // at caixa-core test time under `PartialEq` rather than at a
8312 // downstream `impl AsRef<str>`-bound consumer's silent split.
8313 // Sweeps every one of the three arms
8314 // [`RestartPolicy::ALL`] carries so no arm's projection is
8315 // covered only by the sibling wire-format `Serialize` derive
8316 // path. Peer of the sibling
8317 // [`restart_strategy_as_ref_str_routes_through_as_str_accessor`]
8318 // (63eb1a4) on the paired per-supervisor sibling-restart-
8319 // strategy axis and the [`crate::CaixaVersion`]
8320 // `AsRef<str>`-byte-parity pin (16d5c7e) on the paired
8321 // top-level `:versao` typed newtype — the three pins together
8322 // cover the substrate primitive's `AsRef<str>` projection axis
8323 // on the paired newtype + M2 closed-set-typed-enum surface.
8324 for &variant in RestartPolicy::ALL {
8325 assert_eq!(
8326 <RestartPolicy as AsRef<str>>::as_ref(&variant),
8327 variant.as_str(),
8328 "AsRef<str> impl on RestartPolicy::{variant:?} must \
8329 byte-equal RestartPolicy::as_str on the same instance \
8330 — divergence signals a silent detour off the substrate-\
8331 primitive accessor"
8332 );
8333 }
8334 }
8335
8336 #[test]
8337 fn restart_policy_as_ref_str_routes_through_display_via_shared_accessor() {
8338 // Fail-before-pass-after byte-parity pin on the three-path
8339 // convergence discipline the M2 per-child-restart-policy
8340 // primitive now carries on the `&str`-projection axis:
8341 // `<RestartPolicy as AsRef<str>>::as_ref(&v)` (the newly
8342 // lifted impl), `format!("{v}")` (the pre-existing
8343 // [`fmt::Display`] impl), and `v.as_str()` (the substrate-
8344 // primitive `pub const fn` accessor both trait impls delegate
8345 // through) must resolve to the same byte-string on every
8346 // instance across the three-arm closed set. Refuses any future
8347 // divergence between the two trait impls (a stray
8348 // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
8349 // rather than delegating through the shared accessor; a
8350 // hypothetical `AsRef<str>` rewrite that inlines a per-arm
8351 // literal cascade) that would silently split the two
8352 // projection paths of the same closed-set typed enum. Mirrors
8353 // the sibling three-path-convergence discipline the peer
8354 // [`RestartStrategy`] typed enum carries on its
8355 // `AsRef<str>` / `Display` / `as_str` triple
8356 // (supervisor.rs pin
8357 // `restart_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
8358 // 63eb1a4) and the [`crate::CaixaVersion`] typed newtype
8359 // carries on the same triple (version.rs pin
8360 // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
8361 // 16d5c7e).
8362 for &variant in RestartPolicy::ALL {
8363 let via_as_ref: &str = <RestartPolicy as AsRef<str>>::as_ref(&variant);
8364 let via_display: String = format!("{variant}");
8365 let via_accessor: &str = variant.as_str();
8366 assert_eq!(via_as_ref, via_accessor);
8367 assert_eq!(via_display, via_accessor);
8368 assert_eq!(via_as_ref, via_display.as_str());
8369 }
8370 }
8371
8372 #[test]
8373 fn restart_policy_all_enumerates_every_variant_exactly_once() {
8374 // Fail-before-pass-after pin on the [`RestartPolicy::ALL`]
8375 // exhaustive-iteration surface: every variant appears exactly
8376 // once, and the slice length matches the arm count of the
8377 // closed set. Every consumer that walks the accepted-policy
8378 // set (a future `feira supervisor --restart …` CLI-side
8379 // arg-parse's "did you mean" hint, a future M4 admission-
8380 // webhook's per-child rejection body naming the accepted-
8381 // `:restart` list, the [`RestartPolicy::from_wire`] reverse-
8382 // projection consumers that iterate the accept-set for
8383 // diagnostic rendering) reads through this slice, so a future
8384 // arm addition that grows the enum but forgets to grow
8385 // [`Self::ALL`] silently truncates every downstream consumer's
8386 // accept-set at the same pre-addition boundary — this pin
8387 // fails at caixa-core build time on the pairwise-distinct +
8388 // arm-count invariants.
8389 //
8390 // Peer of the sibling [`RestartStrategy::ALL`] (4eec29c) /
8391 // [`crate::CaixaKind::ALL`] (6b1f4fb) /
8392 // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
8393 // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
8394 // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
8395 // pins on the peer closed-set typed-enum axes.
8396 let all: &[RestartPolicy] = RestartPolicy::ALL;
8397 assert_eq!(
8398 all.len(),
8399 3,
8400 "RestartPolicy::ALL must enumerate every variant of the \
8401 three-arm closed set (Permanent, Temporary, Transient); \
8402 got {all:?}"
8403 );
8404 for (i, a) in all.iter().enumerate() {
8405 for (j, b) in all.iter().enumerate() {
8406 if i != j {
8407 assert_ne!(
8408 a, b,
8409 "RestartPolicy::ALL must carry every variant exactly \
8410 once — got duplicate {a:?} at indices {i} and {j}"
8411 );
8412 }
8413 }
8414 }
8415 for variant in [
8416 RestartPolicy::Permanent,
8417 RestartPolicy::Temporary,
8418 RestartPolicy::Transient,
8419 ] {
8420 assert!(
8421 all.contains(&variant),
8422 "RestartPolicy::ALL must contain {variant:?} — a future arm \
8423 addition that grows the enum but forgets to grow the ALL slice \
8424 silently truncates every downstream consumer's accept-set at \
8425 the pre-addition boundary"
8426 );
8427 }
8428 }
8429
8430 #[test]
8431 fn restart_policy_from_wire_accepts_every_lifted_constant() {
8432 // Fail-before-pass-after pin on the forward accept-set of the
8433 // [`RestartPolicy::from_wire`] reverse projection: every
8434 // canonical [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
8435 // constant the [`RestartPolicy::as_str`] emitter walks parses
8436 // back to its paired variant. Any future arm addition that
8437 // grows the emitter's `as_str` match but forgets to grow the
8438 // parser's `from_wire` match silently splits the two halves of
8439 // the round-trip — the wire byte-string one non-serde consumer
8440 // parses from the one the emitter wrote — with the failure
8441 // surfacing at the operator's reconcile posture (a `:temporary`
8442 // `oneShot` child restarted on clean exit, a `:transient` child
8443 // restarted after clean completion) far from the rebrand
8444 // commit. Pinning the three-arm accept-set here catches the
8445 // drift at caixa-core build time.
8446 //
8447 // Peer of the sibling [`RestartStrategy::from_wire`] (4eec29c)
8448 // + [`crate::CaixaKind::from_wire`] (2aa6d23)
8449 // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
8450 // accept-set pins on the peer closed-set typed-enum `str → Self`
8451 // axes.
8452 for (wire, expected) in [
8453 (
8454 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
8455 RestartPolicy::Permanent,
8456 ),
8457 (
8458 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
8459 RestartPolicy::Temporary,
8460 ),
8461 (
8462 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
8463 RestartPolicy::Transient,
8464 ),
8465 ] {
8466 let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
8467 panic!(
8468 "RestartPolicy::from_wire({wire:?}) must accept every \
8469 SUPERVISOR_CHILD_RESTART_* constant — got None for the \
8470 lifted canonical byte-string that RestartPolicy::{expected:?} \
8471 serializes as under SUPERVISOR_CHILD_KEY_RESTART"
8472 )
8473 });
8474 assert_eq!(
8475 parsed, expected,
8476 "RestartPolicy::from_wire({wire:?}) must return \
8477 RestartPolicy::{expected:?}; got RestartPolicy::{parsed:?}"
8478 );
8479 }
8480 }
8481
8482 #[test]
8483 fn restart_policy_from_wire_round_trips_through_as_str() {
8484 // Fail-before-pass-after pin on the closed round-trip between
8485 // the forward [`RestartPolicy::as_str`] emitter and the
8486 // reverse [`RestartPolicy::from_wire`] parser: for every
8487 // variant in [`RestartPolicy::ALL`], parsing the emitter's
8488 // output must return exactly the same variant. Any per-arm
8489 // divergence — a future arm added to `as_str` but not
8490 // `from_wire`, an accidental copy-paste flip in one but not
8491 // the other — silently splits the emit and parse halves and
8492 // the failure surfaces at consumer parse time far from the
8493 // drift site. The `ALL`-iterating shape means a future arm
8494 // addition picks up the coverage by construction.
8495 //
8496 // Peer of the sibling
8497 // [`restart_strategy_from_wire_round_trips_through_as_str`]
8498 // (4eec29c) round-trip pin on
8499 // [`RestartStrategy::from_wire`] and the M3
8500 // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
8501 // (18c7342) round-trip pin on
8502 // [`crate::aplicacao::PlacementStrategy::from_wire`].
8503 for &variant in RestartPolicy::ALL {
8504 let wire = variant.as_str();
8505 let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
8506 panic!(
8507 "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
8508 must be Some({variant:?}) — the two halves of the round-trip \
8509 dispatch on the same lifted SUPERVISOR_CHILD_RESTART_* consts; \
8510 got None on wire byte-string {wire:?}"
8511 )
8512 });
8513 assert_eq!(
8514 parsed, variant,
8515 "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
8516 must round-trip to the same variant; got {parsed:?}"
8517 );
8518 }
8519 }
8520
8521 #[test]
8522 fn restart_policy_from_wire_rejects_unknown_byte_strings() {
8523 // Fail-before-pass-after pin on the closed-set refusal
8524 // discipline of [`RestartPolicy::from_wire`]: every
8525 // byte-string outside the three-arm accept-set returns `None`
8526 // rather than silently collapsing onto the [`Default`]
8527 // (`Permanent`) arm or an arbitrary neighbor. The refusal set
8528 // exercised here sweeps the load-bearing drift shapes: the
8529 // empty string (a stripped serde-attribute drift), all-
8530 // whitespace strings (the canonical text-editor accidental
8531 // padding shape), the kebab-case dispatcher-catalog identities
8532 // (`"permanent"` / `"temporary"` / `"transient"` — the
8533 // [`gen_platform::FromStrKind`]-derived [`std::str::FromStr`]
8534 // accept-set, which parses the *other* axis of this enum's
8535 // two-axis split and must not leak into the `from_wire`
8536 // PascalCase-wire accept-set — a lowercase leak here would
8537 // silently accept the operator's kebab-case
8538 // dispatcher-catalog probe under the wire-axis parser and mis-
8539 // route a `:permanent` intent), the padded canonical scalar
8540 // (`" Permanent "`), the trailing-newline shapes
8541 // (`"Permanent\n"`), the uppercase-single-word forms
8542 // (`"PERMANENT"`), and neighboring-but-unknown arms
8543 // (`"Restart"` — the canonical typo direction toward the
8544 // sibling [`RestartStrategy`] enum's own wire-arm namespace).
8545 //
8546 // Peer of the sibling
8547 // [`restart_strategy_from_wire_rejects_unknown_byte_strings`]
8548 // (4eec29c) +
8549 // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
8550 // (2aa6d23) +
8551 // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
8552 // (18c7342) refusal pins on the peer closed-set typed-enum
8553 // axes.
8554 for bad in [
8555 "",
8556 " ",
8557 "\n",
8558 "\t",
8559 "permanent",
8560 "temporary",
8561 "transient",
8562 "PERMANENT",
8563 "TEMPORARY",
8564 "TRANSIENT",
8565 "Permanents",
8566 "Permanent ",
8567 " Permanent",
8568 " Transient ",
8569 "Permanent\n",
8570 "perma",
8571 "Trans",
8572 "OneForOne",
8573 "Restart",
8574 "?",
8575 ] {
8576 assert!(
8577 RestartPolicy::from_wire(bad).is_none(),
8578 "RestartPolicy::from_wire({bad:?}) must return None — the \
8579 parser's accept-set is exactly the three RestartPolicy::as_str \
8580 outputs (Permanent, Temporary, Transient), and this \
8581 byte-string is outside that closed set"
8582 );
8583 }
8584 }
8585
8586 #[test]
8587 fn restart_policy_from_wire_matches_serialize_derive_wire_byte_string() {
8588 // Fail-before-pass-after pin on the fourth path of the four-path
8589 // convergence: `from_wire` (the reverse projection) inverts the
8590 // `Serialize` derive's wire byte-string on every variant.
8591 // Together with the pre-existing three-path convergence
8592 // (`Display` + `as_str` + `Serialize` all resolve to the same
8593 // lifted [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const,
8594 // pinned by
8595 // [`restart_policy_display_matches_serialized_wire_byte_string`])
8596 // this closes the round-trip: the wire byte-string the
8597 // `Serialize` derive emits parses back to the same variant
8598 // through `from_wire`, so any future serde-attribute or variant-
8599 // rename drift on the emit half now surfaces as a matched drift
8600 // on the parse half at caixa-core build time — the two halves
8601 // migrate as a unit through the lifted consts on any future
8602 // rename, and the round-trip cannot silently split.
8603 //
8604 // Peer of the sibling
8605 // [`restart_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
8606 // (4eec29c) wire-format pin on
8607 // [`RestartStrategy::from_wire`] and the M3
8608 // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
8609 // (18c7342) wire-format pin on
8610 // [`crate::aplicacao::PlacementStrategy::from_wire`].
8611 for &variant in RestartPolicy::ALL {
8612 let wire = serde_json::to_string(&variant).unwrap();
8613 let unquoted = wire
8614 .strip_prefix('"')
8615 .and_then(|s| s.strip_suffix('"'))
8616 .expect("serialized RestartPolicy is a JSON string");
8617 let parsed = RestartPolicy::from_wire(unquoted).unwrap_or_else(|| {
8618 panic!(
8619 "RestartPolicy::from_wire({unquoted:?}) must accept the \
8620 Serialize derive's wire byte-string for \
8621 RestartPolicy::{variant:?} — the four-path convergence \
8622 (Display + as_str + Serialize + from_wire) resolves through \
8623 the same lifted SUPERVISOR_CHILD_RESTART_* const; got None"
8624 )
8625 });
8626 assert_eq!(
8627 parsed, variant,
8628 "RestartPolicy::from_wire of the Serialize derive's wire \
8629 byte-string for RestartPolicy::{variant:?} must round-trip \
8630 to the same variant; got {parsed:?}"
8631 );
8632 }
8633 }
8634
8635 // ── drift-detection: ChildSpec::nome accessor pins ────────────────────
8636 //
8637 // The M2 supervisor-tree sibling of the M3 `Membro::nome` (4a32abf) pin
8638 // pair (`membro_nome_returns_caixa_byte_equal_across_permutations` +
8639 // `membro_nome_borrows_from_caixa_storage`) — extended here to the M2
8640 // per-`:children` child-caixa `:nome` axis, sibling to the first M2
8641 // slot scalar accessor `UpgradeFromEntry::prior_versao` (75d27a8) on
8642 // the peer per-`:upgrade-from :from` axis. The three pins jointly
8643 // brace the accessor against every future silent detour that would
8644 // desynchronize it from the raw `.caixa` field access every consumer
8645 // previously open-coded.
8646
8647 #[test]
8648 fn child_spec_nome_returns_caixa_byte_equal_across_permutations() {
8649 // The canonical per-`:children` child-caixa `:nome`-scalar pin:
8650 // [`ChildSpec::nome`] must return the `:children :caixa` field
8651 // byte-for-byte across every DNS-1123-label value the upstream
8652 // [`crate::render::require_valid_dns_1123_label`] gate at
8653 // `SupervisorSpec::validate` admits. Peer of the sibling
8654 // `membro_nome_returns_caixa_byte_equal_across_permutations`
8655 // (4a32abf) pin on the M3 per-`:membros` axis — same "the
8656 // substrate-primitive accessor must byte-equal the raw field
8657 // access verbatim across every author-declared value" discipline
8658 // extended to the M2 supervisor-tree per-`:children` arm. Pins
8659 // against a future silent detour that re-normalized the child
8660 // identity (an accidental `.to_lowercase()` — every `:children
8661 // :caixa` is validated as a DNS-1123 label upstream, so any
8662 // re-normalization is redundant + a drift surface between the
8663 // validator and the accessor), a namespace-prefix rewrite (an
8664 // accidental `format!("{namespace}/{caixa}")` per-CR
8665 // fully-qualified rewrite that didn't land on the peer axes), or
8666 // a per-cluster alias stamp the future wasm-operator's
8667 // hierarchical reconciliation scheduler authors on one consumer
8668 // without the others. Five values sweep the accept-set the
8669 // DNS-1123 gate upstream admits (short single-word / dashed /
8670 // v-suffixed / mixed-digit child names).
8671 for name in [
8672 "worker",
8673 "cache-server",
8674 "scratch-job",
8675 "orders-v2",
8676 "session-8080",
8677 ] {
8678 let c = ChildSpec {
8679 caixa: name.into(),
8680 versao: "^0.1".into(),
8681 restart: RestartPolicy::Permanent,
8682 };
8683 assert_eq!(
8684 c.nome(),
8685 name,
8686 "ChildSpec::nome must return :children :caixa verbatim \
8687 (got {:?}, expected {name:?})",
8688 c.nome(),
8689 );
8690 assert_eq!(
8691 c.nome(),
8692 c.caixa.as_str(),
8693 "ChildSpec::nome must byte-equal the .caixa field access",
8694 );
8695 }
8696 }
8697
8698 #[test]
8699 fn child_spec_nome_borrows_from_caixa_storage() {
8700 // The borrow-not-copy pin: [`ChildSpec::nome`] must return a
8701 // `&str` slice that borrows from the typed slot's own [`String`]
8702 // storage — same-address invariant with `c.caixa.as_str()`. Pins
8703 // against a future silent detour that allocated a fresh `String`
8704 // (`self.caixa.clone()` in the body would type-check but silently
8705 // drop the borrow, and every downstream consumer that assumed
8706 // the returned slice outlives `&self` would break on a stale-
8707 // reference use-after-free — the [`crate::render::insert_first_seen`]
8708 // dedup key at [`SupervisorSpec::validate`], the
8709 // [`validate_no_self_supervision`] equality check against the
8710 // parent's `:nome` string slice, the DNS-1123 gate's `&str`
8711 // borrow — each would silently misbehave if this accessor
8712 // produced a detached copy). Peer of the sibling
8713 // `membro_nome_borrows_from_caixa_storage` (4a32abf) pin on the
8714 // M3 per-`:membros` axis and the
8715 // `prior_versao_borrows_from_from_storage` (75d27a8) pin on the
8716 // first M2 slot scalar accessor.
8717 let c = ChildSpec {
8718 caixa: "worker".into(),
8719 versao: "^0.1".into(),
8720 restart: RestartPolicy::Permanent,
8721 };
8722 let name = c.nome();
8723 let caixa_slice = c.caixa.as_str();
8724 assert_eq!(
8725 name.as_ptr(),
8726 caixa_slice.as_ptr(),
8727 "ChildSpec::nome must borrow from the .caixa String's backing \
8728 storage — a fresh allocation here means the accessor no \
8729 longer names the substrate-primitive typed dispatch and \
8730 every downstream consumer would silently carry a detached \
8731 copy",
8732 );
8733 assert_eq!(
8734 name.len(),
8735 caixa_slice.len(),
8736 "ChildSpec::nome and .caixa.as_str() must byte-equal in length \
8737 as well as in address",
8738 );
8739 }
8740
8741 #[test]
8742 fn validate_gates_child_nome_through_lifted_accessor() {
8743 // Bilateral coherence pin: every `:children :caixa` that
8744 // [`SupervisorSpec::validate`] accepts is one
8745 // [`crate::render::require_valid_dns_1123_label`] accepts on the
8746 // accessor-projected value, and vice versa on the reject side.
8747 // This closes the "the validator reads through the accessor"
8748 // contract structurally — a future silent detour that made the
8749 // accessor return a different byte-string than the validator
8750 // gates against would surface here as a coverage mismatch, not
8751 // as an apply-time DNS-1123 rejection at
8752 // `metadata.name: Invalid value` far from the caixa.lisp source.
8753 // Peer of the M2 sibling
8754 // `validate_parses_prior_versao_through_lifted_accessor`
8755 // (75d27a8) on the per-`:upgrade-from :from` axis and the M3
8756 // `validate_membros` peer discipline.
8757 //
8758 // Accept-set sweep: five DNS-1123-label values the upstream gate
8759 // admits.
8760 for ok_name in ["a", "worker", "cache-server", "orders-v2", "svc-8080"] {
8761 let s = SupervisorSpec {
8762 children: vec![ChildSpec {
8763 caixa: ok_name.into(),
8764 versao: "^0.1".into(),
8765 restart: RestartPolicy::Permanent,
8766 }],
8767 ..SupervisorSpec::default()
8768 };
8769 s.validate().unwrap_or_else(|e| {
8770 panic!(
8771 "SupervisorSpec::validate must accept :children :caixa {ok_name:?} \
8772 (upstream DNS-1123 gate accepts it): got {e:?}",
8773 );
8774 });
8775 let c = ChildSpec {
8776 caixa: ok_name.into(),
8777 versao: "^0.1".into(),
8778 restart: RestartPolicy::Permanent,
8779 };
8780 crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| ())
8781 .unwrap_or_else(|()| {
8782 panic!(
8783 "require_valid_dns_1123_label must accept the accessor-projected \
8784 :children :caixa {ok_name:?}",
8785 );
8786 });
8787 }
8788 // Reject-set sweep: five DNS-1123-label-violating shapes the
8789 // upstream gate refuses (empty / uppercase / underscore / dot /
8790 // leading-hyphen). Every rejection at the validator must
8791 // correspond to a rejection when the accessor's projected value
8792 // is fed back through the shared gate.
8793 for bad_name in ["", "Worker", "my_worker", "team.worker", "-worker"] {
8794 let s = SupervisorSpec {
8795 children: vec![ChildSpec {
8796 caixa: bad_name.into(),
8797 versao: "^0.1".into(),
8798 restart: RestartPolicy::Permanent,
8799 }],
8800 ..SupervisorSpec::default()
8801 };
8802 let err = s.validate().unwrap_err();
8803 assert!(
8804 matches!(
8805 err,
8806 SupervisorError::EmptyChildName | SupervisorError::ChildCaixaInvalid { .. }
8807 ),
8808 "SupervisorSpec::validate must reject :children :caixa {bad_name:?} \
8809 via the DNS-1123 gate: got {err:?}",
8810 );
8811 let c = ChildSpec {
8812 caixa: bad_name.into(),
8813 versao: "^0.1".into(),
8814 restart: RestartPolicy::Permanent,
8815 };
8816 assert!(
8817 crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| (),)
8818 .is_err(),
8819 "require_valid_dns_1123_label must reject the accessor-projected \
8820 :children :caixa {bad_name:?}",
8821 );
8822 }
8823 }
8824
8825 // ── drift-detection: ChildSpec::versao_requirement accessor pins ──────
8826 //
8827 // Sibling of the peer per-`:membros` `membro_versao_requirement_*`
8828 // (a40b0e3) pin pair on the M3 mesh-slot surface — extended here to the
8829 // M2 supervisor-tree per-`:children` child-`:versao` axis, sibling to
8830 // the just-landed [`ChildSpec::nome`] (57c61d0) child-`:nome` pin
8831 // trio on the peer per-`:children` `String`-carry axis. The three pins
8832 // jointly brace the accessor against every future silent detour that
8833 // would desynchronize it from the raw `.versao` field access the
8834 // requirement gate + error carrier previously open-coded.
8835 //
8836 // Closes the last unlifted per-`:children` `String`-carry axis: the
8837 // pair (`nome`, `versao_requirement`) now jointly projects the
8838 // (`.caixa`, `.versao`) field pair every OTP-shape supervisor-tree
8839 // consumer that fans on per-child identity + version pin reads,
8840 // matching the peer M3 (`Membro::nome`, `Membro::versao_requirement`)
8841 // pair discipline verbatim.
8842 #[test]
8843 fn child_spec_versao_requirement_returns_versao_byte_equal_across_permutations() {
8844 // The canonical per-`:children` child-`:versao`-scalar pin:
8845 // [`ChildSpec::versao_requirement`] must return the `:children
8846 // :versao` field byte-for-byte across every Cargo-shaped semver
8847 // requirement value the upstream
8848 // [`crate::render::require_valid_versao_requirement`] gate admits.
8849 // Peer of the sibling
8850 // `membro_versao_requirement_returns_versao_byte_equal_across_permutations`
8851 // (a40b0e3) pin on the M3 per-`:membros` axis — same "the
8852 // substrate-primitive accessor must byte-equal the raw field
8853 // access verbatim across every author-declared value" discipline
8854 // extended to the M2 supervisor-tree per-`:children` arm. Pins
8855 // against a future silent detour that re-canonicalized the
8856 // requirement (an accidental `.to_string()` via
8857 // [`crate::version::parse_requirement`] → [`std::fmt::Display`]
8858 // round-trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and
8859 // silently drifted the error carrier's quoted requirement away
8860 // from the source `caixa.lisp`, an accidental whitespace trim on
8861 // `"^ 0.1"` that no consumer ever produced from the field-access
8862 // side, an accidental per-cluster lacre-projected concrete-version
8863 // rewrite that didn't land on the peer requirement-gate call).
8864 // Five values sweep the accept-set the shared
8865 // [`crate::render::require_valid_versao_requirement`] gate admits
8866 // (caret / tilde / exact / wildcard / bare-major).
8867 for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
8868 let c = ChildSpec {
8869 caixa: "worker".into(),
8870 versao: req.into(),
8871 restart: RestartPolicy::Permanent,
8872 };
8873 assert_eq!(
8874 c.versao_requirement(),
8875 req,
8876 "ChildSpec::versao_requirement must return :children :versao \
8877 verbatim (got {:?}, expected {req:?})",
8878 c.versao_requirement(),
8879 );
8880 assert_eq!(
8881 c.versao_requirement(),
8882 c.versao.as_str(),
8883 "ChildSpec::versao_requirement must byte-equal the .versao \
8884 field access",
8885 );
8886 }
8887 }
8888
8889 #[test]
8890 fn child_spec_versao_requirement_borrows_from_versao_storage() {
8891 // The borrow-not-copy pin: [`ChildSpec::versao_requirement`] must
8892 // return a `&str` slice that borrows from the typed slot's own
8893 // [`String`] storage — same-address invariant with
8894 // `c.versao.as_str()`. Pins against a future silent detour that
8895 // allocated a fresh `String` (`self.versao.clone()` in the body
8896 // would type-check but silently drop the borrow, and every
8897 // downstream consumer that assumed the returned slice outlives
8898 // `&self` — the [`crate::render::require_valid_versao_requirement`]
8899 // gate's `&str` borrow, the [`SupervisorError::ChildVersaoInvalid`]
8900 // `.to_string()` carrier's byte-length assumption — would silently
8901 // misbehave if this accessor produced a detached copy). Peer of
8902 // the sibling `child_spec_nome_borrows_from_caixa_storage`
8903 // (57c61d0) pin on the per-`:children` `:nome` axis and the M3
8904 // `membro_versao_requirement_borrows_from_versao_storage` (a40b0e3)
8905 // pin on the peer per-`:membros` `:versao` axis.
8906 let c = ChildSpec {
8907 caixa: "worker".into(),
8908 versao: "^0.1".into(),
8909 restart: RestartPolicy::Permanent,
8910 };
8911 let req = c.versao_requirement();
8912 let versao_slice = c.versao.as_str();
8913 assert_eq!(
8914 req.as_ptr(),
8915 versao_slice.as_ptr(),
8916 "ChildSpec::versao_requirement must borrow from the .versao \
8917 String's backing storage — a fresh allocation here means the \
8918 accessor no longer names the substrate-primitive typed \
8919 dispatch and every downstream consumer would silently carry \
8920 a detached copy",
8921 );
8922 assert_eq!(
8923 req.len(),
8924 versao_slice.len(),
8925 "ChildSpec::versao_requirement and .versao.as_str() must \
8926 byte-equal in length as well as in address",
8927 );
8928 }
8929
8930 #[test]
8931 fn validate_gates_child_versao_through_lifted_accessor() {
8932 // Bilateral coherence pin: every `:children :versao` that
8933 // [`SupervisorSpec::validate`] accepts is one
8934 // [`crate::render::require_valid_versao_requirement`] accepts on
8935 // the accessor-projected value, and vice versa on the reject side.
8936 // This closes the "the validator reads through the accessor"
8937 // contract structurally — a future silent detour that made the
8938 // accessor return a different byte-string than the validator gates
8939 // against would surface here as a coverage mismatch, not as a
8940 // resolver-time semver-parse rejection at lacre-closure time far
8941 // from the caixa.lisp source. Peer of the sibling
8942 // `validate_gates_child_nome_through_lifted_accessor` (57c61d0) on
8943 // the per-`:children :caixa` axis and the M2
8944 // `validate_parses_prior_versao_through_lifted_accessor` (75d27a8)
8945 // on the peer per-`:upgrade-from :from` axis.
8946 //
8947 // Accept-set sweep: five Cargo-shaped semver requirement values
8948 // the upstream gate admits (caret / tilde / exact / wildcard /
8949 // bare-major).
8950 for ok_req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
8951 let s = SupervisorSpec {
8952 children: vec![ChildSpec {
8953 caixa: "worker".into(),
8954 versao: ok_req.into(),
8955 restart: RestartPolicy::Permanent,
8956 }],
8957 ..SupervisorSpec::default()
8958 };
8959 s.validate().unwrap_or_else(|e| {
8960 panic!(
8961 "SupervisorSpec::validate must accept :children :versao {ok_req:?} \
8962 (upstream versao-requirement gate accepts it): got {e:?}",
8963 );
8964 });
8965 let c = ChildSpec {
8966 caixa: "worker".into(),
8967 versao: ok_req.into(),
8968 restart: RestartPolicy::Permanent,
8969 };
8970 crate::render::require_valid_versao_requirement(
8971 c.versao_requirement(),
8972 || (),
8973 |_reason| (),
8974 )
8975 .unwrap_or_else(|()| {
8976 panic!(
8977 "require_valid_versao_requirement must accept the accessor-projected \
8978 :children :versao {ok_req:?}",
8979 );
8980 });
8981 }
8982 // Reject-set sweep: five requirement-violating shapes the upstream
8983 // gate refuses. The empty string closes the empty-first arm of the
8984 // shared [`crate::render::require_valid_versao_requirement`]
8985 // cascade; the four non-empty arms exercise distinct semver-parse
8986 // failure modes the M3 peer per-`:membros` reject-set already pins
8987 // (`rejects_invalid_membro_versao_requirement` on `^bad-version`,
8988 // `rejects_membro_versao_with_double_caret_typo` on `^^0.1`,
8989 // `rejects_membro_versao_with_v_prefixed_tag` on `v0.1`) — the
8990 // shared parser routing means the same reject-set must fail
8991 // identically at the M2 supervisor-tree per-`:children` accessor
8992 // arm here. Every rejection at the validator must correspond to a
8993 // rejection when the accessor's projected value is fed back
8994 // through the shared gate.
8995 //
8996 // (Bare partial magnitudes like `"0.1"` and bare identifiers like
8997 // `"not-a-semver"` are intentionally *not* in the reject-set: the
8998 // semver crate accepts `"0.1"` as an implicit `^0.1` requirement,
8999 // and the identifier-tail arm's grammar admits some non-canonical
9000 // shapes — matching what the M3 peer test suite already documents
9001 // as the shared parser's accept-set edges.)
9002 for bad_req in ["", "v0.1.0", "^bad-version", "^^0.1", "v0.1"] {
9003 let s = SupervisorSpec {
9004 children: vec![ChildSpec {
9005 caixa: "worker".into(),
9006 versao: bad_req.into(),
9007 restart: RestartPolicy::Permanent,
9008 }],
9009 ..SupervisorSpec::default()
9010 };
9011 let err = s.validate().unwrap_err();
9012 assert!(
9013 matches!(
9014 err,
9015 SupervisorError::EmptyChildVersion { .. }
9016 | SupervisorError::ChildVersaoInvalid { .. }
9017 ),
9018 "SupervisorSpec::validate must reject :children :versao {bad_req:?} \
9019 via the versao-requirement gate: got {err:?}",
9020 );
9021 let c = ChildSpec {
9022 caixa: "worker".into(),
9023 versao: bad_req.into(),
9024 restart: RestartPolicy::Permanent,
9025 };
9026 assert!(
9027 crate::render::require_valid_versao_requirement(
9028 c.versao_requirement(),
9029 || (),
9030 |_reason| (),
9031 )
9032 .is_err(),
9033 "require_valid_versao_requirement must reject the accessor-projected \
9034 :children :versao {bad_req:?}",
9035 );
9036 }
9037 }
9038
9039 // ── per-`:children` `:restart` typed-accessor coherence pins ──────────
9040 //
9041 // The [`ChildSpec::restart`] accessor lift closes the last unlifted
9042 // per-`:children` axis (the pair `nome()` + `versao_requirement()`
9043 // already project the `String`-carry `(caixa, versao)` fields; the
9044 // `Copy`-composite-enum `restart` field is the third and final axis).
9045 // Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
9046 // (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
9047 // scalar accessor and the M3 mesh-slot [`crate::Placement::estrategia`]
9048 // (921fe1b) `Copy`-return [`crate::PlacementStrategy`] distribution-
9049 // strategy scalar accessor — same "one typed dispatch on the substrate
9050 // primitive, `Copy`-projected closed-set enum-arm discriminator" shape
9051 // extended onto the M2 supervisor-slot per-`:children` restart-decision
9052 // axis. The pin below covers the accessor's byte-equal projection
9053 // against the raw field access across every variant in the closed
9054 // accept-set (`Permanent`, `Transient`, `Temporary`).
9055
9056 #[test]
9057 fn child_spec_restart_returns_restart_verbatim_across_permutations() {
9058 // The canonical per-`:children` restart-decision-policy-scalar
9059 // pin: [`ChildSpec::restart`] must return the `:children :restart`
9060 // field verbatim as a [`RestartPolicy`], `Copy`-projected from the
9061 // typed slot's own [`RestartPolicy`] storage across every variant
9062 // in the closed accept-set (`Permanent`, `Transient`, `Temporary`).
9063 // Pins against a future silent detour that re-derived the policy
9064 // from a peer axis (an accidental fallback to
9065 // `if is_supervisor_child { Permanent } else { Temporary }` that
9066 // collapsed the child's kind axis into the restart discriminator),
9067 // a variant remap the operator authors on one consumer without the
9068 // other, or a stale-derive detour that substituted
9069 // [`RestartPolicy::default`] when the field held any explicit
9070 // variant (which would silently collapse the distinction between
9071 // "author explicitly declared `:restart Permanent`" and "author
9072 // omitted the slot and inherited the default" the future
9073 // per-cluster restart-decision override slot depends on).
9074 //
9075 // Peer of the sibling per-`:supervisor`
9076 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
9077 // (eafb619) pin on the M2 supervisor-slot sibling-restart-strategy
9078 // axis and the M3
9079 // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
9080 // (921fe1b) pin on the per-`:placement` distribution-strategy axis
9081 // — same "the substrate-primitive accessor must byte-equal the raw
9082 // field access verbatim across every author-declared value"
9083 // discipline extended onto the M2 supervisor-slot per-`:children`
9084 // restart-decision-policy axis, closing the last unlifted axis on
9085 // the per-`:children` [`ChildSpec`] type.
9086 for restart in [
9087 RestartPolicy::Permanent,
9088 RestartPolicy::Transient,
9089 RestartPolicy::Temporary,
9090 ] {
9091 let c = ChildSpec {
9092 caixa: "worker".into(),
9093 versao: "^0.1".into(),
9094 restart,
9095 };
9096 assert_eq!(
9097 c.restart(),
9098 restart,
9099 "ChildSpec::restart must return :children :restart \
9100 verbatim (got {:?}, expected {restart:?})",
9101 c.restart(),
9102 );
9103 assert_eq!(
9104 c.restart(),
9105 c.restart,
9106 "ChildSpec::restart accessor and .restart field access \
9107 must byte-equal — the accessor is the substrate-primitive \
9108 typed dispatch every downstream per-child restart-\
9109 decision consumer must route through",
9110 );
9111 }
9112 }
9113
9114 // ── per-`:supervisor` `:estrategia` typed-accessor coherence pins ─────
9115 //
9116 // The [`SupervisorSpec::estrategia`] accessor lift extends the peer M3
9117 // [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
9118 // distribution-strategy accessor discipline onto the M2 supervisor-slot
9119 // per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
9120 // scalar axis. The two pins below cover (1) the accessor's byte-equal
9121 // projection against the raw field access across every variant in the
9122 // closed accept-set, and (2) the two-consumer coherence between the
9123 // [`SupervisorSpec::validate`] partition-dispatch `match` arm and the
9124 // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
9125 // carrier's `estrategia:` field — peer of the sibling M3
9126 // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
9127 // / `validate_placement_reads_through_lifted_estrategia_accessor` pin
9128 // pair on the per-`:placement` distribution-strategy axis.
9129
9130 #[test]
9131 fn supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations() {
9132 // The canonical per-`:supervisor` sibling-restart-strategy-scalar
9133 // pin: [`SupervisorSpec::estrategia`] must return the
9134 // `:supervisor :estrategia` field verbatim as a
9135 // [`RestartStrategy`], `Copy`-projected from the typed slot's own
9136 // [`RestartStrategy`] storage across every variant in the closed
9137 // accept-set (`OneForOne`, `OneForAll`, `RestForOne`,
9138 // `SimpleOneForOne`). Pins against a future silent detour that
9139 // re-derived the strategy from a peer axis (an accidental
9140 // fallback to `if children.is_empty() { SimpleOneForOne } else {
9141 // OneForOne }` collapse that read the children-count axis into
9142 // the strategy discriminator), a variant remap the operator
9143 // authors on one consumer without the other, or a stale-derive
9144 // detour that substituted [`RestartStrategy::default`] when the
9145 // field held any explicit variant (which would silently collapse
9146 // the distinction between "author explicitly declared
9147 // `:estrategia OneForOne`" and "author omitted the slot and
9148 // inherited the default" the future per-cluster strategy override
9149 // slot depends on). Peer of the sibling M3
9150 // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
9151 // (921fe1b) pin on the M3 mesh-slot `Copy`-composite-enum scalar
9152 // axis — same "the substrate-primitive accessor must byte-equal
9153 // the raw field access verbatim across every author-declared
9154 // value" discipline extended onto the M2 supervisor-slot
9155 // per-`:supervisor` sibling-restart-strategy axis.
9156 for &estrategia in RestartStrategy::ALL {
9157 // `SimpleOneForOne` requires `children.is_empty()`; the peer
9158 // three strategies require a non-empty static children list.
9159 // Build each shape coherently so the pin's fixture would
9160 // itself pass [`SupervisorSpec::validate`] once fed through
9161 // the sibling coherence pin below — the byte-equal projection
9162 // asserted here is a strictly weaker property (a `Copy` field
9163 // read) that does not depend on `validate` running, but
9164 // keeping the fixture validate-clean means a future extension
9165 // of the pin to exercise `validate` end-to-end does not have
9166 // to re-author the children shape.
9167 //
9168 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
9169 // shape partition through the [`gen_platform::IsVariant`]
9170 // derive-generated
9171 // [`RestartStrategy::is_simple_one_for_one`] predicate rather
9172 // than the raw `matches!(estrategia, RestartStrategy::
9173 // SimpleOneForOne)` open-coded pattern-match — same closed-
9174 // set-typed-enum arm-discriminator dispatch discipline the
9175 // sibling [`crate::upgrade::UpgradeInstruction::is_restart`]
9176 // convergence (915a934) extended onto its two paired positive
9177 // / negated `matches!` sites and the peer
9178 // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
9179 // predicate convergence (766ec63) extended onto the M3 mesh-
9180 // slot per-`:placement` distribution-strategy discriminator
9181 // axis. See the sibling `round_trip_all_strategies` and the
9182 // peer `manifest::tests::
9183 // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
9184 // fixture for the two peer sites the same lift closes on.
9185 let children = if estrategia.is_simple_one_for_one() {
9186 Vec::new()
9187 } else {
9188 vec![ChildSpec {
9189 caixa: "worker".into(),
9190 versao: "^0.1".into(),
9191 restart: RestartPolicy::Permanent,
9192 }]
9193 };
9194 let s = SupervisorSpec {
9195 estrategia,
9196 children,
9197 ..SupervisorSpec::default()
9198 };
9199 assert_eq!(
9200 s.estrategia(),
9201 estrategia,
9202 "SupervisorSpec::estrategia must return :supervisor :estrategia \
9203 verbatim (got {:?}, expected {estrategia:?})",
9204 s.estrategia(),
9205 );
9206 assert_eq!(
9207 s.estrategia(),
9208 s.estrategia,
9209 "SupervisorSpec::estrategia accessor and .estrategia field \
9210 access must byte-equal — the accessor is the substrate-\
9211 primitive typed dispatch every downstream sibling-restart-\
9212 strategy consumer must route through",
9213 );
9214 }
9215 }
9216
9217 #[test]
9218 fn validate_reads_through_lifted_estrategia_accessor() {
9219 // Two-consumer coherence pin: the [`SupervisorSpec::validate`]
9220 // `SimpleOneForOne ↔ non-SimpleOneForOne` `match` partition
9221 // dispatch (which reads through [`SupervisorSpec::estrategia`]
9222 // to fan across the strategy-arm shape-gate cascades) and the
9223 // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
9224 // error carrier's `estrategia:` field (which reads through
9225 // [`SupervisorSpec::estrategia`] to name the strategy the empty
9226 // `:children` list was declared against) must both key off the
9227 // lifted accessor, so any future rebrand on the typed slot's
9228 // reader shape lands at exactly one place. Pins the two-site
9229 // coherence by exercising the `NoChildren` error surface end-to-
9230 // end across every non-`SimpleOneForOne` variant and asserting
9231 // the surfaced `estrategia:` field byte-equals the accessor's
9232 // return. Peer of the sibling M3
9233 // `validate_placement_reads_through_lifted_estrategia_accessor`
9234 // (921fe1b) three-consumer coherence pin on the per-`:placement`
9235 // distribution-strategy axis.
9236 for estrategia in [
9237 RestartStrategy::OneForOne,
9238 RestartStrategy::OneForAll,
9239 RestartStrategy::RestForOne,
9240 ] {
9241 let s = SupervisorSpec {
9242 estrategia,
9243 children: Vec::new(),
9244 ..SupervisorSpec::default()
9245 };
9246 let err = s.validate().unwrap_err();
9247 match err {
9248 SupervisorError::NoChildren { estrategia: e } => {
9249 assert_eq!(
9250 e,
9251 s.estrategia(),
9252 "NoChildren.estrategia must byte-equal \
9253 SupervisorSpec::estrategia() — the empty-`:children` \
9254 refusal reads through the lifted accessor",
9255 );
9256 assert_eq!(
9257 e, estrategia,
9258 "NoChildren.estrategia must carry the author-declared \
9259 :supervisor :estrategia variant verbatim (got {e:?}, \
9260 expected {estrategia:?})",
9261 );
9262 }
9263 other => panic!("expected NoChildren, got {other:?} for estrategia={estrategia:?}"),
9264 }
9265 }
9266 }
9267
9268 // ── per-`:supervisor` `:max-restarts` typed-accessor coherence pins ────
9269 //
9270 // The [`SupervisorSpec::max_restarts`] accessor lift extends the peer M3
9271 // [`crate::CircuitBreaker::max_failures`] (3a74062) `Copy`-return
9272 // required-`u32` scalar accessor discipline onto the M2 supervisor-slot
9273 // per-`:supervisor` restart-budget-count `Copy`-`u32` scalar axis.
9274 // The two pins below cover (1) the accessor's byte-equal projection
9275 // against the raw field access across every representative value in
9276 // the `u32` accept-set (`1` lower boundary, `SUPERVISOR_MAX_RESTARTS_MAX`
9277 // upper boundary, `0` past-the-guard zero sentinel, `u32::MAX`
9278 // past-the-guard cap sentinel), and (2) the [`SupervisorSpec::validate`]
9279 // zero-floor / cap composition — the validate gate and the accessor
9280 // must route through the same substrate-primitive typed dispatch, so
9281 // any future silent detour that had the accessor perform a
9282 // bounds-collapsing clamp would fail here at caixa-core build time.
9283 // Peer of the sibling M3
9284 // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
9285 // (3a74062) pin on the per-`CircuitBreaker :max-failures` axis.
9286
9287 #[test]
9288 fn supervisor_spec_max_restarts_returns_max_restarts_u32_byte_equal_across_permutations() {
9289 // The canonical per-`:supervisor` restart-budget-count scalar pin:
9290 // [`SupervisorSpec::max_restarts`] must return the `:supervisor
9291 // :max-restarts` typed `u32` verbatim, `Copy`-projected from the
9292 // typed slot's own `u32` storage, byte-equal to the raw field
9293 // access across every representative value in the accept-set —
9294 // `1` (the lower boundary of the `1..=SUPERVISOR_MAX_RESTARTS_MAX`
9295 // accept-set the surrounding [`SupervisorSpec::validate`] gate
9296 // carves out on the sibling `ZeroMaxRestarts` refusal),
9297 // `SUPERVISOR_MAX_RESTARTS_MAX` (the upper boundary the same gate
9298 // carves out on the sibling `MaxRestartsExceedsCap` refusal), `0`
9299 // (a past-the-guard sentinel that pins the accessor doesn't
9300 // perform a silent bounds-collapse into `1` on the zero arm —
9301 // validate rejects zero but the accessor must ship the raw slot
9302 // verbatim so a validate-time gate regression surfaces at the
9303 // emit boundary rather than being silently absorbed), `u32::MAX`
9304 // (a past-the-guard sentinel that pins the accessor doesn't
9305 // perform a silent bounds-collapse through
9306 // `SUPERVISOR_MAX_RESTARTS_MAX` at the return path).
9307 //
9308 // Peer of the sibling M3
9309 // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
9310 // (3a74062) pin on the M3 mesh-slot `Copy`-`u32` sub-struct
9311 // required-scalar axis — same "the substrate-primitive accessor
9312 // must byte-equal the raw field access verbatim across every
9313 // value in the `u32` accept-set" discipline extended onto the M2
9314 // supervisor-slot per-`:supervisor` restart-budget-count axis.
9315 for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX, 0, u32::MAX] {
9316 let s = SupervisorSpec {
9317 max_restarts,
9318 ..SupervisorSpec::default()
9319 };
9320 assert_eq!(
9321 s.max_restarts(),
9322 max_restarts,
9323 "SupervisorSpec::max_restarts must return :supervisor \
9324 :max-restarts verbatim (got {}, expected {max_restarts})",
9325 s.max_restarts(),
9326 );
9327 assert_eq!(
9328 s.max_restarts(),
9329 s.max_restarts,
9330 "SupervisorSpec::max_restarts accessor and .max_restarts \
9331 field access must byte-equal — the accessor is the \
9332 substrate-primitive typed dispatch every downstream \
9333 restart-budget-count consumer must route through",
9334 );
9335 }
9336 }
9337
9338 #[test]
9339 fn validate_max_restarts_zero_floor_and_cap_arms_route_through_accessor() {
9340 // Composition pin: [`SupervisorSpec::validate`]'s `:max-restarts`
9341 // zero-floor + upper-cap bracket must key off
9342 // [`SupervisorSpec::max_restarts`], not the raw `.max_restarts`
9343 // field access. Structurally: a `SupervisorSpec { max_restarts:
9344 // 0, .. }` must surface the `ZeroMaxRestarts` refusal exactly, a
9345 // `SupervisorSpec { max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
9346 // .. }` must surface the `MaxRestartsExceedsCap` refusal exactly
9347 // (with the offending count carried verbatim from the accessor
9348 // return), and a `SupervisorSpec { max_restarts: 1, .. }` (the
9349 // lower boundary of the accept-set) plus a `SupervisorSpec {
9350 // max_restarts: SUPERVISOR_MAX_RESTARTS_MAX, .. }` (the upper
9351 // boundary) must pass validate. The four together jointly pin the
9352 // accessor + validate-gate composition: any future silent detour
9353 // that had the accessor return a fresh `1` on the zero arm (a
9354 // `.max_restarts().max(1)` collapse) would silently absorb the
9355 // `ZeroMaxRestarts` refusal at the accessor boundary and the
9356 // validate gate would accept a struct-literal `SupervisorSpec {
9357 // max_restarts: 0, .. }` — the composition pin catches that at
9358 // caixa-core build time.
9359 //
9360 // Peer of the sibling M3
9361 // `validate_politicas_max_failures_zero_floor_arm_routes_through_accessor`
9362 // (3a74062) pin on the sibling per-`CircuitBreaker :max-failures`
9363 // composition axis — same "the validate / shape-gate predicate
9364 // must route through the substrate-primitive typed dispatch"
9365 // discipline extended onto the peer M2 supervisor-slot
9366 // required-`u32` composition axis.
9367 let child = ChildSpec {
9368 caixa: "worker".into(),
9369 versao: "^0.1".into(),
9370 restart: RestartPolicy::Permanent,
9371 };
9372 // Zero-floor arm.
9373 let s = SupervisorSpec {
9374 max_restarts: 0,
9375 children: vec![child.clone()],
9376 ..SupervisorSpec::default()
9377 };
9378 assert_eq!(
9379 s.validate().unwrap_err(),
9380 SupervisorError::ZeroMaxRestarts,
9381 "validate must reject max_restarts == 0 with ZeroMaxRestarts \
9382 — the accessor and the validate gate must route through the \
9383 same substrate-primitive typed dispatch on the zero-floor arm",
9384 );
9385 // Cap arm — the surfaced `max_restarts:` field must byte-equal
9386 // the accessor's return so a future rebrand on the accessor
9387 // lands in the diagnostic without a coordinated rewrite.
9388 let over_cap = SUPERVISOR_MAX_RESTARTS_MAX + 1;
9389 let s = SupervisorSpec {
9390 max_restarts: over_cap,
9391 children: vec![child.clone()],
9392 ..SupervisorSpec::default()
9393 };
9394 match s.validate().unwrap_err() {
9395 SupervisorError::MaxRestartsExceedsCap { max_restarts } => {
9396 assert_eq!(
9397 max_restarts,
9398 s.max_restarts(),
9399 "MaxRestartsExceedsCap.max_restarts must byte-equal \
9400 SupervisorSpec::max_restarts() — the cap-arm refusal \
9401 reads through the lifted accessor",
9402 );
9403 assert_eq!(
9404 max_restarts, over_cap,
9405 "MaxRestartsExceedsCap.max_restarts must carry the \
9406 author-declared :supervisor :max-restarts value \
9407 verbatim (got {max_restarts}, expected {over_cap})",
9408 );
9409 }
9410 other => panic!("expected MaxRestartsExceedsCap, got {other:?}"),
9411 }
9412 // Lower + upper accept-set boundaries.
9413 for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX] {
9414 let s = SupervisorSpec {
9415 max_restarts,
9416 children: vec![child.clone()],
9417 ..SupervisorSpec::default()
9418 };
9419 assert!(
9420 s.validate().is_ok(),
9421 "validate must accept max_restarts == {max_restarts} \
9422 (an accept-set boundary of \
9423 1..=SUPERVISOR_MAX_RESTARTS_MAX)",
9424 );
9425 }
9426 }
9427
9428 // ── per-`:supervisor` `:restart-window` typed-accessor coherence pins ─
9429 //
9430 // The [`SupervisorSpec::restart_window`] accessor lift extends the peer
9431 // M2 [`crate::LimitsSpec::wall_clock`] (8cb717b) `Option<Duration>`
9432 // accessor discipline and the peer M3 [`crate::MeshPolicy::timeout`]
9433 // (7073d0f) `Option<Duration>` accessor discipline onto the M2
9434 // supervisor-slot per-`:supervisor` restart-intensity-denominator
9435 // `Option<Duration>` scalar axis — third `Copy`-return accessor on the
9436 // M2 supervisor-slot `SupervisorSpec` type, closing the last unlifted
9437 // per-`:supervisor` scalar-value axis. The three pins below cover
9438 // (1) the accessor's byte-equal projection against the raw field
9439 // access across every representative value in the `Option<Duration>`
9440 // accept-set (`None` never-reset sentinel, `Some(Duration::from_millis(1))`
9441 // lower boundary, `Some(SUPERVISOR_RESTART_WINDOW_MAX)` upper boundary,
9442 // `Some(Duration::ZERO)` past-the-guard zero sentinel, `Some(Duration::MAX)`
9443 // past-the-guard above-cap sentinel), (2) the [`SupervisorSpec::validate`]
9444 // `if let Some(w) = self.restart_window() { … }` bracket-arm
9445 // composition — the validate gate and the accessor must route through
9446 // the same substrate-primitive typed dispatch, so any future silent
9447 // detour that had the accessor perform a bounds-collapsing clamp
9448 // would fail here at caixa-core build time, and (3) the accessor's
9449 // by-copy idempotence pin — the returned `Option<Duration>` must
9450 // outlive `&self` and two successive calls must return byte-equal
9451 // values. Peer of the sibling M2
9452 // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
9453 // (8cb717b) pin on the per-`:limits :wall-clock` axis and the sibling
9454 // M3 `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
9455 // (7073d0f) pin on the per-`:politicas :timeout` axis.
9456
9457 #[test]
9458 fn supervisor_spec_restart_window_returns_option_duration_byte_equal_across_permutations() {
9459 // The canonical per-`:supervisor` restart-intensity-denominator
9460 // scalar pin: [`SupervisorSpec::restart_window`] must return the
9461 // `:supervisor :restart-window` typed [`Duration`] verbatim as an
9462 // `Option<Duration>`, `Copy`-projected from the typed slot's own
9463 // `Option<Duration>` storage, byte-equal to the raw field access
9464 // across every representative value in the accept-set — `None`
9465 // (the "never reset — every restart across the supervisor's
9466 // lifetime counts against the sibling `:max-restarts` budget"
9467 // sentinel the field's own docstring names and the peer
9468 // `validate_accepts_none_restart_window` pin locks in on the
9469 // [`SupervisorSpec::validate`] entry-side),
9470 // `Some(Duration::from_millis(1))` (the structural minimum a
9471 // validated `:restart-window` may carry, the integer-millisecond
9472 // floor [`SupervisorError::RestartWindowNotCanonical`] rejects
9473 // everything sub-ms; `Duration::ZERO` is separately rejected by
9474 // [`SupervisorError::RestartWindowZero`]),
9475 // `Some(SUPERVISOR_RESTART_WINDOW_MAX)` (the upper boundary the
9476 // surrounding [`SupervisorSpec::validate`] gate carves out on the
9477 // sibling [`SupervisorError::RestartWindowExceedsCap`] refusal),
9478 // `Some(Duration::ZERO)` (a past-the-guard sentinel that pins the
9479 // accessor doesn't perform a silent bounds-collapse into `None` on
9480 // the zero-Duration arm — validate rejects zero but the accessor
9481 // must ship the raw slot verbatim so a validate-time gate
9482 // regression surfaces at the emit boundary rather than being
9483 // silently absorbed), and `Some(Duration::MAX)` (a past-the-guard
9484 // sentinel that pins the accessor doesn't perform a silent
9485 // bounds-collapse through [`SUPERVISOR_RESTART_WINDOW_MAX`] at the
9486 // return path).
9487 //
9488 // Peer of the sibling M2
9489 // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
9490 // (8cb717b) pin on the per-`:limits :wall-clock` axis and the
9491 // sibling M3
9492 // `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
9493 // (7073d0f) pin on the per-`:politicas :timeout` axis — same "the
9494 // substrate-primitive accessor must byte-equal the raw field
9495 // access verbatim across every value in the `Option<Duration>`
9496 // accept-set" discipline extended onto the M2 supervisor-slot
9497 // per-`:supervisor` `Option<Duration>` axis. Pins against a future
9498 // silent detour that re-derived the restart-window from a peer
9499 // axis (an accidental `.max_restarts.into()` collapse that read
9500 // the restart-budget-count as a duration — the two axes serve
9501 // different halves of the `MaxIntensity / Period` restart-
9502 // intensity ratio, and confusing them silently inverts the
9503 // ratio's numerator and denominator), a `None → Some(Duration::ZERO)`
9504 // "zero means never reset" collapse (the canonical
9505 // `Option<Duration>` → `Duration` collapse footgun the
9506 // [`SupervisorError::RestartWindowZero`] validate arm guards on
9507 // the peer zero-floor axis; a zero period either trips on the
9508 // first failure or never trips depending on operator
9509 // interpretation, neither of which is the author's "never reset"
9510 // intent that `None` expresses structurally), or a per-arm
9511 // variant swap that landed on one consumer without the other.
9512 for restart_window in [
9513 None,
9514 Some(Duration::from_millis(1)),
9515 Some(SUPERVISOR_RESTART_WINDOW_MAX),
9516 Some(Duration::ZERO),
9517 Some(Duration::MAX),
9518 ] {
9519 let s = SupervisorSpec {
9520 restart_window,
9521 ..SupervisorSpec::default()
9522 };
9523 assert_eq!(
9524 s.restart_window(),
9525 restart_window,
9526 "SupervisorSpec::restart_window must return :supervisor \
9527 :restart-window verbatim (got {:?}, expected {restart_window:?})",
9528 s.restart_window(),
9529 );
9530 assert_eq!(
9531 s.restart_window(),
9532 s.restart_window,
9533 "SupervisorSpec::restart_window accessor and \
9534 .restart_window field access must byte-equal — the \
9535 accessor is the substrate-primitive typed dispatch every \
9536 downstream restart-intensity-denominator consumer must \
9537 route through",
9538 );
9539 }
9540 }
9541
9542 #[test]
9543 fn validate_restart_window_bracket_arm_routes_through_accessor() {
9544 // Composition pin: [`SupervisorSpec::validate`]'s
9545 // `:restart-window` `if let Some(w) = self.restart_window() { … }`
9546 // zero-floor + integer-millisecond canonical-form + upper-cap
9547 // bracket-arm must key off [`SupervisorSpec::restart_window`], not
9548 // the raw `.restart_window` field access. Structurally: a
9549 // `SupervisorSpec { restart_window: None, .. }` must pass the
9550 // arm gate structurally (the `if let Some(_)` shape returns
9551 // early on the `None` arm — the accessor and the validate gate
9552 // must agree on `None → skip the bracket cascade` so an authored
9553 // `:restart-window ()` structurally routes through the "never
9554 // reset" sentinel path), a `SupervisorSpec { restart_window:
9555 // Some(Duration::ZERO), .. }` must surface the `RestartWindowZero`
9556 // refusal exactly, a `SupervisorSpec { restart_window:
9557 // Some(Duration::from_micros(1500)), .. }` must surface the
9558 // `RestartWindowNotCanonical` refusal exactly (with the offending
9559 // duration carried verbatim from the accessor return), a
9560 // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX
9561 // + Duration::from_millis(1)), .. }` must surface the
9562 // `RestartWindowExceedsCap` refusal exactly (with the offending
9563 // duration carried verbatim from the accessor return), and a
9564 // `SupervisorSpec { restart_window: Some(Duration::from_millis(1)),
9565 // .. }` (the lower boundary of the accept-set) plus a
9566 // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
9567 // .. }` (the upper boundary) must pass validate. The six together
9568 // jointly pin the accessor + validate-gate composition: any future
9569 // silent detour that had the accessor return a fresh `None` on any
9570 // `Some` arm (a `.restart_window().filter(|w| !w.is_zero())`
9571 // collapse) would silently absorb the `RestartWindowZero` refusal
9572 // at the accessor boundary and the validate gate would accept a
9573 // struct-literal `SupervisorSpec { restart_window:
9574 // Some(Duration::ZERO), .. }` — the composition pin catches that
9575 // at caixa-core build time.
9576 //
9577 // Peer of the sibling M2 [`crate::LimitsSpec::wall_clock`]
9578 // (8cb717b) validate-arm-route pin on the per-`:limits :wall-clock`
9579 // axis and the peer M3 [`crate::MeshPolicy::timeout`] (7073d0f)
9580 // accessor-composition pin on the per-`:politicas :timeout` axis —
9581 // same "the validate / shape-gate predicate must route through
9582 // the substrate-primitive typed dispatch" discipline extended
9583 // onto the peer M2 supervisor-slot optional-`Duration` axis.
9584 let child = ChildSpec {
9585 caixa: "worker".into(),
9586 versao: "^0.1".into(),
9587 restart: RestartPolicy::Permanent,
9588 };
9589 // None arm — must not surface any :restart-window-shaped refusal;
9590 // the `if let Some(_)` bracket returns early on `None` structurally.
9591 let s = SupervisorSpec {
9592 restart_window: None,
9593 children: vec![child.clone()],
9594 ..SupervisorSpec::default()
9595 };
9596 assert!(
9597 s.validate().is_ok(),
9598 "validate must accept restart_window: None (the never-reset \
9599 sentinel) — the `if let Some(_)` bracket returns early on \
9600 the None arm and the accessor must agree",
9601 );
9602 // Zero-floor arm.
9603 let s = SupervisorSpec {
9604 restart_window: Some(Duration::ZERO),
9605 children: vec![child.clone()],
9606 ..SupervisorSpec::default()
9607 };
9608 assert_eq!(
9609 s.validate().unwrap_err(),
9610 SupervisorError::RestartWindowZero,
9611 "validate must reject restart_window == Some(Duration::ZERO) \
9612 with RestartWindowZero — the accessor and the validate gate \
9613 must route through the same substrate-primitive typed \
9614 dispatch on the zero-floor arm",
9615 );
9616 // Non-canonical (sub-ms) arm — the surfaced `window:` field must
9617 // byte-equal the accessor's return so a future rebrand on the
9618 // accessor lands in the diagnostic without a coordinated rewrite.
9619 let sub_ms = Duration::from_micros(1500);
9620 let s = SupervisorSpec {
9621 restart_window: Some(sub_ms),
9622 children: vec![child.clone()],
9623 ..SupervisorSpec::default()
9624 };
9625 match s.validate().unwrap_err() {
9626 SupervisorError::RestartWindowNotCanonical { window } => {
9627 assert_eq!(
9628 Some(window),
9629 s.restart_window(),
9630 "RestartWindowNotCanonical.window must byte-equal \
9631 SupervisorSpec::restart_window().unwrap() — the \
9632 non-canonical-arm refusal reads through the lifted \
9633 accessor",
9634 );
9635 assert_eq!(
9636 window, sub_ms,
9637 "RestartWindowNotCanonical.window must carry the \
9638 author-declared :supervisor :restart-window value \
9639 verbatim (got {window:?}, expected {sub_ms:?})",
9640 );
9641 }
9642 other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
9643 }
9644 // Cap arm — the surfaced `window:` field must byte-equal the
9645 // accessor's return.
9646 let over_cap = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
9647 let s = SupervisorSpec {
9648 restart_window: Some(over_cap),
9649 children: vec![child.clone()],
9650 ..SupervisorSpec::default()
9651 };
9652 match s.validate().unwrap_err() {
9653 SupervisorError::RestartWindowExceedsCap { window } => {
9654 assert_eq!(
9655 Some(window),
9656 s.restart_window(),
9657 "RestartWindowExceedsCap.window must byte-equal \
9658 SupervisorSpec::restart_window().unwrap() — the \
9659 cap-arm refusal reads through the lifted accessor",
9660 );
9661 assert_eq!(
9662 window, over_cap,
9663 "RestartWindowExceedsCap.window must carry the \
9664 author-declared :supervisor :restart-window value \
9665 verbatim (got {window:?}, expected {over_cap:?})",
9666 );
9667 }
9668 other => panic!("expected RestartWindowExceedsCap, got {other:?}"),
9669 }
9670 // Lower + upper accept-set boundaries.
9671 for restart_window in [Duration::from_millis(1), SUPERVISOR_RESTART_WINDOW_MAX] {
9672 let s = SupervisorSpec {
9673 restart_window: Some(restart_window),
9674 children: vec![child.clone()],
9675 ..SupervisorSpec::default()
9676 };
9677 assert!(
9678 s.validate().is_ok(),
9679 "validate must accept restart_window == Some({restart_window:?}) \
9680 (an accept-set boundary of \
9681 1ms..=SUPERVISOR_RESTART_WINDOW_MAX)",
9682 );
9683 }
9684 }
9685
9686 #[test]
9687 fn supervisor_spec_restart_window_projects_option_duration_by_copy() {
9688 // The by-copy pin: [`SupervisorSpec::restart_window`] returns
9689 // `Option<Duration>` by copy — `Duration` is `Copy` (so
9690 // `Option<Duration>` is `Copy`) and the accessor must return by
9691 // value, not by reference. Peer of the sibling M2
9692 // [`crate::LimitsSpec::wall_clock`] (8cb717b) by-copy pin on the
9693 // per-`:limits :wall-clock` axis and the sibling M3
9694 // [`crate::MeshPolicy::timeout`] (7073d0f) by-copy pin on the
9695 // per-`:politicas :timeout` axis, extended onto the peer M2
9696 // supervisor-slot `Option<Duration>` copy-invariant shape — the
9697 // accessor's returned `Option<Duration>` must outlive `&self`
9698 // (multiple calls must return equal values from a dropped-`&self`
9699 // copy, since the returned Option carries no borrow), and calling
9700 // the accessor twice on the same SupervisorSpec must yield the
9701 // same `Option<Duration>` verbatim (idempotent, no side effects
9702 // on `&self`).
9703 //
9704 // Pins against a future silent detour that returned
9705 // `Option<&Duration>` (which would type-check but silently break
9706 // every downstream caller — the future wasm-operator's
9707 // per-supervisor restart-intensity counter consumes `Duration` by
9708 // value and `&Duration` would fold to a detached copy at the call
9709 // site), an accidental `Option::as_ref()` projection
9710 // (`self.restart_window.as_ref()` would also type-check but
9711 // return `Option<&Duration>`), or a one-arm-only accessor that
9712 // reads `Some(*w)` in the Some arm but reads a fresh
9713 // `Default::default()` (which would collapse to `Duration::ZERO`,
9714 // not `None`) in the None arm — a footgun the
9715 // [`SupervisorError::RestartWindowZero`] validate arm explicitly
9716 // closes since Erlang/OTP's `MaxIntensity / Period` invariant
9717 // requires `Period > 0` and `None` structurally expresses "never
9718 // reset" instead.
9719 for restart_window in [
9720 None,
9721 Some(Duration::from_millis(1)),
9722 Some(Duration::from_secs(60)),
9723 Some(SUPERVISOR_RESTART_WINDOW_MAX),
9724 ] {
9725 let s = SupervisorSpec {
9726 restart_window,
9727 ..SupervisorSpec::default()
9728 };
9729 let first = s.restart_window();
9730 let second = s.restart_window();
9731 assert_eq!(
9732 first, second,
9733 "SupervisorSpec::restart_window must be idempotent — two \
9734 successive calls on the same &self must return the \
9735 same Option<Duration>",
9736 );
9737 assert_eq!(
9738 first, restart_window,
9739 "SupervisorSpec::restart_window must return :supervisor \
9740 :restart-window verbatim by copy — got {first:?}, \
9741 expected {restart_window:?}",
9742 );
9743 }
9744 }
9745
9746 // ── per-`:supervisor` `:children` typed-accessor coherence pins ─────────
9747 //
9748 // The [`SupervisorSpec::children`] accessor lift is the seed of the
9749 // slice-return (`&[T]`) accessor discipline on the substrate — the four
9750 // peer `Vec`-carry axes ([`crate::Placement::clusters`],
9751 // [`crate::AplicacaoSpec::membros`], [`crate::AplicacaoSpec::contratos`],
9752 // [`crate::UpgradeFromEntry::instructions`]) still key off the raw field
9753 // access at the time of this seed, and inherit this pin family's
9754 // discipline as future compounding runs migrate their consumers. The
9755 // three pins below cover (1) the accessor's byte-equal projection
9756 // against the raw field access across the empty / singleton / cohort
9757 // fixtures the [`SupervisorSpec::validate`] partition-dispatch fans
9758 // between, (2) the [`SupervisorSpec::validate`] `SimpleOneForOne ↔
9759 // non-SimpleOneForOne` partition dispatch's paired `.is_empty()`
9760 // consumer routing through the accessor on both arms, and (3) the
9761 // per-child validate loop's traversal reading the same slice-view the
9762 // accessor projects. Peer of the sibling M2
9763 // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
9764 // two-consumer coherence pin on the per-`:supervisor`
9765 // sibling-restart-strategy `Copy`-composite-enum scalar axis, extended
9766 // onto the per-`:supervisor` static-child-list `Vec`-carry axis.
9767
9768 #[test]
9769 fn supervisor_spec_children_returns_children_slice_byte_equal_across_permutations() {
9770 // The canonical per-`:supervisor` static-child-list scalar-shape
9771 // pin: [`SupervisorSpec::children`] must return the `:supervisor
9772 // :children` typed `Vec<ChildSpec>` verbatim as a `&[ChildSpec]`
9773 // slice-view over the same backing buffer the raw
9774 // `self.children.as_slice()` field access borrows from, byte-
9775 // equal across every representative fixture in the accept-set —
9776 // the empty slice (the `SimpleOneForOne`-arm sentinel),
9777 // the singleton slice (the minimal non-`SimpleOneForOne` shape),
9778 // and a two-child cohort (a peer non-`SimpleOneForOne` shape
9779 // with the peer three restart-policy variants in play).
9780 //
9781 // Pins against a future silent detour that returned
9782 // `&Vec<ChildSpec>` (which would type-check but leak the
9783 // storage-side `Vec`'s grow/push/reserve surface no consumer of
9784 // the typed view reaches for), a fresh-allocated
9785 // `Vec<ChildSpec>` copy (which would type-check via a coercion
9786 // but silently break every downstream caller that relied on the
9787 // slice sharing the backing buffer's identity), or an
9788 // out-of-order or length-drifted projection (which would silently
9789 // split the per-child validate loop's traversal input from the
9790 // paired partition-dispatch `.is_empty()` probe's input).
9791 //
9792 // Peer of the sibling
9793 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
9794 // (eafb619) `Copy`-composite-enum byte-equal pin on the
9795 // per-`:supervisor` sibling-restart-strategy axis, extended onto
9796 // the per-`:supervisor` static-child-list `Vec`-carry axis.
9797 let fixtures: Vec<Vec<ChildSpec>> = vec![
9798 Vec::new(),
9799 vec![child("worker", "^0.1", RestartPolicy::Permanent)],
9800 vec![
9801 child("worker", "^0.1", RestartPolicy::Permanent),
9802 child("cache-server", "^0.1", RestartPolicy::Transient),
9803 ],
9804 vec![
9805 child("worker", "^0.1", RestartPolicy::Permanent),
9806 child("cache-server", "^0.1", RestartPolicy::Transient),
9807 child("scratch-job", "^0.1", RestartPolicy::Temporary),
9808 ],
9809 ];
9810 for children in fixtures {
9811 let s = SupervisorSpec {
9812 children: children.clone(),
9813 ..SupervisorSpec::default()
9814 };
9815 assert_eq!(
9816 s.children(),
9817 children.as_slice(),
9818 "SupervisorSpec::children must return :supervisor \
9819 :children verbatim (got {:?}, expected {:?})",
9820 s.children(),
9821 children.as_slice(),
9822 );
9823 assert_eq!(
9824 s.children(),
9825 s.children.as_slice(),
9826 "SupervisorSpec::children accessor and \
9827 .children.as_slice() field access must byte-equal — \
9828 the accessor is the substrate-primitive typed \
9829 dispatch every downstream static-child-list consumer \
9830 must route through",
9831 );
9832 assert_eq!(
9833 s.children().len(),
9834 s.children.len(),
9835 "SupervisorSpec::children().len() must byte-equal \
9836 self.children.len() — a length-drift would silently \
9837 split the paired partition-dispatch `.is_empty()` \
9838 probe input from the per-child validate loop's \
9839 traversal input",
9840 );
9841 }
9842 }
9843
9844 #[test]
9845 fn validate_reads_through_lifted_children_accessor() {
9846 // Three-consumer coherence pin: the [`SupervisorSpec::validate`]
9847 // `SimpleOneForOne`-arm `!self.children().is_empty()` refusal
9848 // probe (which must trip [`SupervisorError::SimpleOneForOneWithStaticChildren`]
9849 // when the accessor projects a non-empty slice under a
9850 // `SimpleOneForOne` estrategia), the peer non-`SimpleOneForOne`-arm
9851 // `self.children().is_empty()` refusal probe (which must trip
9852 // [`SupervisorError::NoChildren`] when the accessor projects the
9853 // empty slice under any peer estrategia), and the per-child
9854 // validate loop's `for child in self.children()` traversal
9855 // (which must reach every entry in the same order the accessor
9856 // projects) must all key off the lifted accessor, so any future
9857 // rebrand on the typed slot's reader shape lands at exactly one
9858 // place. Pins the three-site coherence by exercising each
9859 // production consumer end-to-end: (1) the
9860 // `SimpleOneForOneWithStaticChildren` refusal under a non-empty
9861 // slice + `SimpleOneForOne` estrategia, (2) the `NoChildren`
9862 // refusal under the empty slice + non-`SimpleOneForOne`
9863 // estrategia across every peer variant, and (3) the per-child
9864 // duplicate-detection surface fires on the second entry of a
9865 // two-child cohort that shares a `:caixa` name (which requires
9866 // the loop to reach both entries — a first-entry-only projection
9867 // would silently pass since the dedup HashSet has room for the
9868 // first insert).
9869 //
9870 // Peer of the sibling M2
9871 // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
9872 // two-consumer coherence pin on the per-`:supervisor`
9873 // sibling-restart-strategy axis, extended onto the
9874 // per-`:supervisor` static-child-list `Vec`-carry axis.
9875
9876 // (1) `SimpleOneForOne`-arm probe: a non-empty slice under a
9877 // `SimpleOneForOne` estrategia must trip
9878 // `SimpleOneForOneWithStaticChildren`.
9879 let s = SupervisorSpec {
9880 estrategia: RestartStrategy::SimpleOneForOne,
9881 children: vec![child("worker", "^0.1", RestartPolicy::Permanent)],
9882 ..SupervisorSpec::default()
9883 };
9884 assert_eq!(
9885 s.validate().unwrap_err(),
9886 SupervisorError::SimpleOneForOneWithStaticChildren,
9887 "SimpleOneForOne + non-empty children must trip \
9888 SimpleOneForOneWithStaticChildren — the accessor projects \
9889 a non-empty slice, and the SimpleOneForOne-arm refusal \
9890 probe reads through the lifted accessor",
9891 );
9892 assert!(
9893 !s.children().is_empty(),
9894 "the SimpleOneForOne-arm refusal input must be a non-empty \
9895 slice per the accessor's projection",
9896 );
9897
9898 // (2) Peer non-`SimpleOneForOne`-arm probe: the empty slice
9899 // under any peer estrategia must trip `NoChildren`.
9900 for estrategia in [
9901 RestartStrategy::OneForOne,
9902 RestartStrategy::OneForAll,
9903 RestartStrategy::RestForOne,
9904 ] {
9905 let s = SupervisorSpec {
9906 estrategia,
9907 children: Vec::new(),
9908 ..SupervisorSpec::default()
9909 };
9910 match s.validate().unwrap_err() {
9911 SupervisorError::NoChildren { estrategia: e } => {
9912 assert_eq!(
9913 e, estrategia,
9914 "NoChildren.estrategia must carry the author-\
9915 declared :supervisor :estrategia variant \
9916 verbatim (got {e:?}, expected {estrategia:?})",
9917 );
9918 }
9919 other => panic!(
9920 "expected NoChildren, got {other:?} for \
9921 estrategia={estrategia:?}"
9922 ),
9923 }
9924 assert!(
9925 s.children().is_empty(),
9926 "the non-SimpleOneForOne-arm refusal input must be the \
9927 empty slice per the accessor's projection",
9928 );
9929 }
9930
9931 // (3) Per-child validate loop: a two-child cohort that shares a
9932 // `:caixa` name must trip `DuplicateChildCaixa` — the loop must
9933 // reach both entries through the accessor.
9934 let s = SupervisorSpec {
9935 estrategia: RestartStrategy::OneForOne,
9936 children: vec![
9937 child("worker", "^0.1", RestartPolicy::Permanent),
9938 child("worker", "^0.2", RestartPolicy::Transient),
9939 ],
9940 ..SupervisorSpec::default()
9941 };
9942 match s.validate().unwrap_err() {
9943 SupervisorError::DuplicateChildCaixa { caixa } => {
9944 assert_eq!(
9945 caixa, "worker",
9946 "DuplicateChildCaixa.caixa must carry the shared \
9947 child `:caixa` name verbatim",
9948 );
9949 }
9950 other => panic!("expected DuplicateChildCaixa, got {other:?}"),
9951 }
9952 assert_eq!(
9953 s.children().len(),
9954 2,
9955 "the per-child validate loop's traversal input must be a \
9956 two-element slice per the accessor's projection",
9957 );
9958 }
9959
9960 // Shared helper for the M2 per-`:children` per-slot-gate ≡
9961 // `validate` equivalence pins: builds an `OneForOne`-estrategia
9962 // one-cohort spec whose peer `:estrategia`↔`:children.is_empty()`
9963 // partition, `:max-restarts` zero-floor/cap, and `:restart-window`
9964 // bracket all pass cleanly so the sole failing surface is the
9965 // per-child cascade [`SupervisorSpec::validate_children`] owns, and
9966 // pins the two-altitude equivalence on the paired probe.
9967 fn assert_validate_children_matches_gate(children: Vec<ChildSpec>, expected: &SupervisorError) {
9968 let s = SupervisorSpec {
9969 estrategia: RestartStrategy::OneForOne,
9970 children,
9971 ..SupervisorSpec::default()
9972 };
9973 let via_gate = s.validate_children().unwrap_err();
9974 let via_validate = s.validate().unwrap_err();
9975 assert_eq!(&via_gate, expected, "validate_children direct dispatch",);
9976 assert_eq!(&via_validate, expected, "validate() end-to-end dispatch",);
9977 assert_eq!(
9978 via_gate, via_validate,
9979 "per-slot gate ≡ validate() must discriminate the same \
9980 refusal shape",
9981 );
9982 }
9983
9984 #[test]
9985 fn validate_children_matches_gate_on_per_axis_refusal_shapes() {
9986 // Fail-before-pass-after equivalence pin on the M2
9987 // per-`:children` per-slot gate ≡ [`SupervisorSpec::validate`]
9988 // convergence — sibling of the M3 mesh-slot
9989 // `validate_membros_*` / `validate_contratos_*` /
9990 // `validate_entrada_*` per-slot-gate ≡ `validate` pins on the
9991 // peer per-entry axes. Sweeps four of the five refusal shapes
9992 // the per-slot gate owns: (1) `EmptyChildName` on an empty-
9993 // `:caixa` child, (2) `ChildCaixaInvalid` on a structurally
9994 // invalid `:caixa` DNS-1123 label, (3) `EmptyChildVersion` on
9995 // an empty-`:versao` child, (4) `DuplicateChildCaixa` on a
9996 // duplicate-`:caixa` fan-out. Companion pin
9997 // `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
9998 // covers `ChildVersaoInvalid` (whose parser-owned reason string
9999 // needs pattern-matching, not equality) and the clean-pass
10000 // canonical fixture; together the two pins guarantee the
10001 // per-slot gate and `validate` discriminate the same set on
10002 // every per-child-covered input.
10003 assert_validate_children_matches_gate(
10004 vec![child("", "^0.1", RestartPolicy::Permanent)],
10005 &SupervisorError::EmptyChildName,
10006 );
10007 assert_validate_children_matches_gate(
10008 vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
10009 &SupervisorError::ChildCaixaInvalid {
10010 caixa: "Worker".into(),
10011 reason: "contains uppercase character 'W' (K8s DNS-1123 label names are lowercase-only; use \"worker\")".into(),
10012 },
10013 );
10014 assert_validate_children_matches_gate(
10015 vec![child("worker", "", RestartPolicy::Permanent)],
10016 &SupervisorError::EmptyChildVersion {
10017 caixa: "worker".into(),
10018 },
10019 );
10020 assert_validate_children_matches_gate(
10021 vec![
10022 child("worker", "^0.1", RestartPolicy::Permanent),
10023 child("worker", "^0.2", RestartPolicy::Transient),
10024 ],
10025 &SupervisorError::DuplicateChildCaixa {
10026 caixa: "worker".into(),
10027 },
10028 );
10029 }
10030
10031 #[test]
10032 fn validate_children_matches_gate_on_versao_invalid_and_clean_pass() {
10033 // Second half of the two-altitude equivalence pin — covers the
10034 // one refusal shape whose reason string is parser-owned
10035 // (`ChildVersaoInvalid`, whose reason comes from the shared
10036 // [`crate::version::parse_requirement`] impl and may drift) and
10037 // the clean-pass canonical fixture. Sibling pin
10038 // `validate_children_matches_gate_on_per_axis_refusal_shapes`
10039 // covers the four equality-comparable refusal shapes.
10040 let s_bad_versao = SupervisorSpec {
10041 estrategia: RestartStrategy::OneForOne,
10042 children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
10043 ..SupervisorSpec::default()
10044 };
10045 let via_gate = s_bad_versao.validate_children().unwrap_err();
10046 let via_validate = s_bad_versao.validate().unwrap_err();
10047 match (&via_gate, &via_validate) {
10048 (
10049 SupervisorError::ChildVersaoInvalid {
10050 caixa: cg,
10051 versao: vg,
10052 ..
10053 },
10054 SupervisorError::ChildVersaoInvalid {
10055 caixa: cv,
10056 versao: vv,
10057 ..
10058 },
10059 ) => {
10060 assert_eq!(cg, "worker", "per-slot gate :caixa carrier");
10061 assert_eq!(vg, "not-a-req", "per-slot gate :versao carrier");
10062 assert_eq!(cv, "worker", "validate() :caixa carrier");
10063 assert_eq!(vv, "not-a-req", "validate() :versao carrier");
10064 }
10065 other => panic!("expected ChildVersaoInvalid on both altitudes, got {other:?}"),
10066 }
10067 assert_eq!(
10068 via_gate, via_validate,
10069 "per-slot gate ≡ validate() on ChildVersaoInvalid full envelope",
10070 );
10071
10072 let s_ok = SupervisorSpec {
10073 estrategia: RestartStrategy::OneForOne,
10074 children: vec![
10075 child("worker-a", "^0.1", RestartPolicy::Permanent),
10076 child("worker-b", "~0.2.3", RestartPolicy::Transient),
10077 child("collector", "*", RestartPolicy::Temporary),
10078 ],
10079 ..SupervisorSpec::default()
10080 };
10081 s_ok.validate_children()
10082 .expect("per-slot gate must accept the clean-pass fixture");
10083 s_ok.validate()
10084 .expect("validate() must accept the clean-pass fixture");
10085 }
10086
10087 #[test]
10088 fn validate_children_is_self_contained_on_children_slot() {
10089 // Self-containment pin: [`SupervisorSpec::validate_children`]
10090 // resolves the per-child cascade against `&self` alone, without
10091 // depending on the peer `:estrategia`/`:max-restarts`/
10092 // `:restart-window` gates having run first — same posture the M3
10093 // peer per-slot gates carry (`validate_membros`,
10094 // `validate_contratos`, `validate_entrada`, `validate_placement`,
10095 // routing through their own oracles rather than borrowing state
10096 // threaded down from `validate`). A future consumer that reaches
10097 // the per-slot gate directly on a spec whose peer slots would
10098 // fail `validate` still surfaces the per-child refusal, not the
10099 // peer refusal.
10100 //
10101 // Construct a spec whose `:max-restarts` is `0` (which would
10102 // trip [`SupervisorError::ZeroMaxRestarts`] at `validate` after
10103 // the partition-dispatch) and whose `:children` carries a
10104 // `DuplicateChildCaixa` shape: the per-slot gate called directly
10105 // must surface `DuplicateChildCaixa`, proving it does not depend
10106 // on the peer `:max-restarts` gate running first.
10107 let s = SupervisorSpec {
10108 estrategia: RestartStrategy::OneForOne,
10109 max_restarts: 0,
10110 restart_window: Some(Duration::from_secs(60)),
10111 children: vec![
10112 child("worker", "^0.1", RestartPolicy::Permanent),
10113 child("worker", "^0.2", RestartPolicy::Transient),
10114 ],
10115 };
10116 assert_eq!(
10117 s.validate_children().unwrap_err(),
10118 SupervisorError::DuplicateChildCaixa {
10119 caixa: "worker".into(),
10120 },
10121 "per-slot gate must resolve per-child refusal directly against \
10122 `&self` — a dependency on the peer `:max-restarts` gate \
10123 running first would surface ZeroMaxRestarts here instead",
10124 );
10125 // The peer gate is still the surface `validate` reaches — pin
10126 // the ordering to establish that `validate_children` truly runs
10127 // last in `validate`'s dispatch, so a direct call bypasses the
10128 // peer gates on any spec whose per-child cascade would fail.
10129 assert_eq!(
10130 s.validate().unwrap_err(),
10131 SupervisorError::ZeroMaxRestarts,
10132 "validate() must surface the peer `:max-restarts` gate before \
10133 reaching the per-child cascade — this pins the dispatch \
10134 ordering the per-slot gate's self-containment complements",
10135 );
10136 }
10137
10138 #[test]
10139 fn child_spec_restart_accessor_is_const_fn() {
10140 // The [`ChildSpec::restart`] per-`:children` restart-decision-
10141 // policy `Copy`-return scalar accessor is declared
10142 // `#[must_use] pub const fn` — matching the sibling M2
10143 // per-`:supervisor` [`SupervisorSpec::estrategia`] (pinned by
10144 // [`supervisor_spec_estrategia_accessor_is_const_fn`] below,
10145 // both converted in this commit), the sibling M2
10146 // per-`:supervisor` [`SupervisorSpec::max_restarts`] (b698ec0)
10147 // `Copy`-`u32` accessor already `pub const fn`, and the peer M3
10148 // mesh-slot per-`:entrada` [`crate::Entrada::port`] (bafa004) /
10149 // per-`:placement` [`crate::Placement::estrategia`] (bafa004)
10150 // `Copy`-return `pub const fn` scalar accessors on the sibling
10151 // M3 surface. Pin the `const`-eval posture here so a future
10152 // accidental downgrade to non-`const` (an added runtime helper
10153 // reachable only from a non-`const` context, an
10154 // `Option<RestartPolicy>`-shape migration on the per-child
10155 // restart-decision axis once heterogeneous per-cluster
10156 // restart-policy overlays land that would silently drop the
10157 // `const` qualifier, a manual hand-rolled shadow) trips at
10158 // caixa-core build time rather than surfacing as a downstream
10159 // `const`-context regression far from the declaration.
10160 //
10161 // Same shape as the sibling M3
10162 // [`crate::aplicacao::tests::placement_estrategia_accessor_is_const_fn`]
10163 // and [`crate::aplicacao::tests::entrada_port_accessor_is_const_fn`]
10164 // (bafa004) pins on the peer M3 mesh-slot `Copy`-return scalar
10165 // accessor axis — the load-bearing witness lives in the
10166 // module-scope `const fn` wrapper `restart_via_const_fn` below:
10167 // a body that calls [`ChildSpec::restart`] under a `const fn`
10168 // signature is well-formed only when the callee is itself
10169 // `const fn`, so any future accidental downgrade of
10170 // [`ChildSpec::restart`] to non-`const` fails at caixa-core
10171 // build time (const-eval E0015 `cannot call non-const method`),
10172 // strictly stronger than a runtime `assert!(CONST)` and
10173 // side-stepping the destructor-in-const restriction that
10174 // blocks direct `const _: RestartPolicy = FIXTURE.restart()`
10175 // items on `ChildSpec`'s `String` carriers.
10176 //
10177 // The runtime body sweeps every closed-set [`RestartPolicy`]
10178 // arm and asserts the wrapped and direct dispatches agree.
10179 const fn restart_via_const_fn(c: &ChildSpec) -> RestartPolicy {
10180 c.restart()
10181 }
10182 for restart in [
10183 RestartPolicy::Permanent,
10184 RestartPolicy::Transient,
10185 RestartPolicy::Temporary,
10186 ] {
10187 let c = ChildSpec {
10188 caixa: "worker".into(),
10189 versao: "^0.1".into(),
10190 restart,
10191 };
10192 assert_eq!(
10193 restart_via_const_fn(&c),
10194 c.restart(),
10195 "const-fn-wrapped and direct dispatch on \
10196 ChildSpec::restart must agree for {restart:?}",
10197 );
10198 assert_eq!(
10199 c.restart(),
10200 restart,
10201 "ChildSpec::restart must return the storage-side \
10202 RestartPolicy verbatim for {restart:?} (a violation \
10203 means the accessor stopped being a raw field-return \
10204 copy)",
10205 );
10206 }
10207 }
10208
10209 #[test]
10210 fn supervisor_spec_estrategia_accessor_is_const_fn() {
10211 // The [`SupervisorSpec::estrategia`] per-`:supervisor`
10212 // sibling-restart-strategy `Copy`-return scalar accessor is
10213 // declared `#[must_use] pub const fn` — matching the sibling M2
10214 // per-`:children` [`ChildSpec::restart`] (pinned by
10215 // [`child_spec_restart_accessor_is_const_fn`] above, both
10216 // converted in this commit), the sibling M2 per-`:supervisor`
10217 // [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32`
10218 // accessor already `pub const fn`, and mirroring the peer M3
10219 // mesh-slot per-`:placement`
10220 // [`crate::Placement::estrategia`] (bafa004) `Copy`-return
10221 // `pub const fn` scalar accessor whose method-name discipline
10222 // the [`SupervisorSpec::estrategia`] method was authored to
10223 // match. Pin the `const`-eval posture here so a future
10224 // accidental downgrade to non-`const` (an added runtime helper
10225 // reachable only from a non-`const` context, an
10226 // `Option<RestartStrategy>`-shape migration once the substrate
10227 // grows per-cluster strategy overlays that would silently drop
10228 // the `const` qualifier, a manual hand-rolled shadow) trips at
10229 // caixa-core build time rather than surfacing as a downstream
10230 // `const`-context regression far from the declaration.
10231 //
10232 // Same shape as the sibling
10233 // [`child_spec_restart_accessor_is_const_fn`] pin above — the
10234 // load-bearing witness lives in the module-scope `const fn`
10235 // wrapper `estrategia_via_const_fn` below: a body that calls
10236 // [`SupervisorSpec::estrategia`] under a `const fn` signature
10237 // is well-formed only when the callee is itself `const fn`,
10238 // side-stepping the destructor-in-const restriction that would
10239 // otherwise block a direct
10240 // `const _: RestartStrategy = FIXTURE.estrategia()` item on
10241 // `SupervisorSpec`'s `Vec<ChildSpec>` / `Option<Duration>`
10242 // carriers.
10243 //
10244 // The runtime body sweeps every closed-set [`RestartStrategy`]
10245 // arm via [`RestartStrategy::ALL`] and asserts the wrapped and
10246 // direct dispatches agree.
10247 const fn estrategia_via_const_fn(s: &SupervisorSpec) -> RestartStrategy {
10248 s.estrategia()
10249 }
10250 for &estrategia in RestartStrategy::ALL {
10251 let s = SupervisorSpec {
10252 estrategia,
10253 max_restarts: 5,
10254 restart_window: Some(Duration::from_secs(60)),
10255 children: Vec::new(),
10256 };
10257 assert_eq!(
10258 estrategia_via_const_fn(&s),
10259 s.estrategia(),
10260 "const-fn-wrapped and direct dispatch on \
10261 SupervisorSpec::estrategia must agree for {estrategia:?}",
10262 );
10263 assert_eq!(
10264 s.estrategia(),
10265 estrategia,
10266 "SupervisorSpec::estrategia must return the storage-side \
10267 RestartStrategy verbatim for {estrategia:?} (a violation \
10268 means the accessor stopped being a raw field-return \
10269 copy)",
10270 );
10271 }
10272 }
10273
10274 // Per-variant equivalence pins for the [`supervisor_caixa_only_ctors!`]
10275 // macro definition (see the paired doc-block above the macro
10276 // definition) — every generated `<ctor>(caixa: &str) -> Self`
10277 // constructor folds the uniform `Self::<Variant> { caixa:
10278 // caixa.to_string() }` one-field struct-literal onto one substrate
10279 // primitive. The three per-variant equivalence pins below
10280 // (fail-before-pass-after by construction — a byte-mismatched macro
10281 // arm would trip its equivalence pin first) lock each generated
10282 // constructor to its struct-literal peer under `PartialEq`, so
10283 // every wire-up in [`SupervisorSpec::validate_children`] and
10284 // [`validate_no_self_supervision`] on that variant produces a
10285 // byte-equal `SupervisorError` to the pre-lift open-coded
10286 // struct-literal. The cross-axis pin that follows (non-default
10287 // caixa name) routes the sole constructor input axis through
10288 // `.to_string()`, so the fold does not silently collapse onto a
10289 // fixed name.
10290 //
10291 // Peer of the sibling `<slot>_ctor_matches_tuple_literal_wrap` /
10292 // `<slot>_violation_ctor_matches_struct_literal_wrap` /
10293 // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
10294 // `missing_entry_ctor_matches_struct_literal_wrap` /
10295 // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
10296 // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
10297 // `contrato_missing_target_ctor_matches_struct_literal_wrap` /
10298 // `<variant>_ctor_matches_struct_literal_wrap` equivalence pins
10299 // on the six sibling ctor families the recent trajectory closed
10300 // on the peer `LayoutError` / `AplicacaoError` envelopes.
10301
10302 #[test]
10303 fn empty_child_version_ctor_matches_struct_literal_wrap() {
10304 assert_eq!(
10305 SupervisorError::empty_child_version("worker"),
10306 SupervisorError::EmptyChildVersion {
10307 caixa: "worker".to_string(),
10308 },
10309 "generated empty_child_version ctor must produce byte-equal \
10310 SupervisorError to the open-coded struct-literal wrap on the \
10311 same &str fixture",
10312 );
10313 }
10314
10315 #[test]
10316 fn duplicate_child_caixa_ctor_matches_struct_literal_wrap() {
10317 assert_eq!(
10318 SupervisorError::duplicate_child_caixa("worker"),
10319 SupervisorError::DuplicateChildCaixa {
10320 caixa: "worker".to_string(),
10321 },
10322 "generated duplicate_child_caixa ctor must produce byte-equal \
10323 SupervisorError to the open-coded struct-literal wrap on the \
10324 same &str fixture",
10325 );
10326 }
10327
10328 #[test]
10329 fn child_supervises_self_ctor_matches_struct_literal_wrap() {
10330 assert_eq!(
10331 SupervisorError::child_supervises_self("orquestra"),
10332 SupervisorError::ChildSupervisesSelf {
10333 caixa: "orquestra".to_string(),
10334 },
10335 "generated child_supervises_self ctor must produce byte-equal \
10336 SupervisorError to the open-coded struct-literal wrap on the \
10337 same &str fixture",
10338 );
10339 }
10340
10341 // Per-variant equivalence pins for the two lifted
10342 // [`SupervisorError::child_caixa_invalid`] /
10343 // [`SupervisorError::child_versao_invalid`] inherent constructors
10344 // (fail-before-pass-after by construction — a byte-mismatched ctor body
10345 // would trip its equivalence pin first). Each pins the ctor output to
10346 // its pre-lift struct-literal peer under `PartialEq`, so every wire-up
10347 // in [`SupervisorSpec::validate_children`] on the two variants
10348 // produces a byte-equal `SupervisorError` to the pre-lift open-coded
10349 // struct-literal on the same scalar fixtures. Peers of the sibling
10350 // `membro_caixa_invalid_ctor_matches_struct_literal_wrap` /
10351 // `entrada_para_invalid_ctor_matches_struct_literal_wrap` / … pins on
10352 // the peer `AplicacaoError` envelope's
10353 // [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold.
10354
10355 #[test]
10356 fn child_caixa_invalid_ctor_matches_struct_literal_wrap() {
10357 let caixa = "Worker";
10358 let reason = "sample reason text";
10359 assert_eq!(
10360 SupervisorError::child_caixa_invalid(caixa, reason),
10361 SupervisorError::ChildCaixaInvalid {
10362 caixa: caixa.to_string(),
10363 reason: reason.to_string(),
10364 },
10365 "lifted child_caixa_invalid ctor must produce byte-equal \
10366 SupervisorError to the open-coded struct-literal wrap on the \
10367 same (&str, reason) fixture",
10368 );
10369 }
10370
10371 #[test]
10372 fn child_versao_invalid_ctor_matches_struct_literal_wrap() {
10373 let caixa = "worker";
10374 let versao = "not-a-req";
10375 let reason = "sample reason text";
10376 assert_eq!(
10377 SupervisorError::child_versao_invalid(caixa, versao, reason),
10378 SupervisorError::ChildVersaoInvalid {
10379 caixa: caixa.to_string(),
10380 versao: versao.to_string(),
10381 reason: reason.to_string(),
10382 },
10383 "lifted child_versao_invalid ctor must produce byte-equal \
10384 SupervisorError to the open-coded struct-literal wrap on the \
10385 same (&str, &str, reason) fixture",
10386 );
10387 }
10388
10389 #[test]
10390 fn supervisor_child_reason_ctors_route_reason_through_into_uniformly() {
10391 // Cross-axis pin: sweep the two lifted `{ …, reason }` ctors
10392 // against a `&str`-literal vs. `format!(…)` reason input to pin
10393 // both constructors accept the `impl Into<String>` bound
10394 // uniformly, so neither wire-up site drifts under a per-arm
10395 // wrapper transformation on the caller-side `reason` axis. Peer
10396 // of the sibling
10397 // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
10398 // sweep on the peer `AplicacaoError` envelope.
10399 let via_literal = "literal reason text";
10400 let via_format = format!("{} reason text", "literal");
10401 assert_eq!(
10402 SupervisorError::child_caixa_invalid("Worker", via_literal),
10403 SupervisorError::child_caixa_invalid("Worker", via_format.clone()),
10404 );
10405 assert_eq!(
10406 SupervisorError::child_versao_invalid("worker", "not-a-req", via_literal),
10407 SupervisorError::child_versao_invalid("worker", "not-a-req", via_format),
10408 );
10409 }
10410
10411 #[test]
10412 fn supervisor_caixa_only_ctors_route_caixa_through_to_string() {
10413 // Cross-axis pin: sweep the sole constructor input axis (`caixa:
10414 // &str`) through a non-default fixture name against every
10415 // generated arm in the [`supervisor_caixa_only_ctors!`] macro,
10416 // so any wrapper-side lowercase / trim / truncate / re-order on
10417 // the `caixa.to_string()` sole-field construction surfaces
10418 // here rather than at a downstream diagnostic-shape mismatch.
10419 // Peer of the sibling `nome_only_ctor_routes_caixa_through_
10420 // nome_accessor` / `entrada_host_invalid_ctor_routes_host_
10421 // through_to_string` / `contrato_target_ctors_route_edge_
10422 // triple_through_verbatim` / `contrato_empty_pair_ctors_
10423 // route_edge_pair_through_verbatim` cross-axis routing pins on
10424 // the peer `LayoutError` / `AplicacaoError` envelopes; extended
10425 // here onto the `SupervisorError` `{ caixa: String }` envelope
10426 // so every substrate-primitive ctor family in caixa-core
10427 // guarantees the sole-field construction routes the caller's
10428 // `&str` through `.to_string()` verbatim.
10429 let name = "cache-v2";
10430 assert_eq!(
10431 SupervisorError::empty_child_version(name),
10432 SupervisorError::EmptyChildVersion {
10433 caixa: name.to_string(),
10434 },
10435 );
10436 assert_eq!(
10437 SupervisorError::duplicate_child_caixa(name),
10438 SupervisorError::DuplicateChildCaixa {
10439 caixa: name.to_string(),
10440 },
10441 );
10442 assert_eq!(
10443 SupervisorError::child_supervises_self(name),
10444 SupervisorError::ChildSupervisesSelf {
10445 caixa: name.to_string(),
10446 },
10447 );
10448 }
10449
10450 // ── supervisor_scalar_ctors! per-variant + cross-axis pins ──────────────
10451 //
10452 // Per-variant byte-equality pins guaranteeing every generated ctor arm in
10453 // the [`supervisor_scalar_ctors!`] macro produces a `SupervisorError`
10454 // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
10455 // one-line struct-literal on the same `Copy`-`RestartStrategy | u32 |
10456 // Duration` fixture, plus one cross-axis sweep that routes each per-variant
10457 // `<field>: <ty>` scalar through the sole `$field:ident: $ty:ty` axis the
10458 // macro exposes so any wrapper-side truncation / re-order / silent `.into()`
10459 // / silent constant-substitution on any one variant surfaces here rather
10460 // than at a downstream per-`:supervisor` diagnostic-shape drift. Peer of the
10461 // sibling per-variant pins on `aplicacao_policy_scalar_ctors!` (7ef425e,
10462 // the 8-variant `AplicacaoError` `{ <field>: Duration | u32 }` fold on the
10463 // per-`:politicas` per-axis cap / canonical-form arms), plus the sibling
10464 // `supervisor_caixa_only_ctors!` (db09650), `SupervisorError::
10465 // {child_caixa_invalid,child_versao_invalid}` (d2ef2ec), and the peer
10466 // `DepError` / `AplicacaoError` / `LayoutError` / `LimitsError` /
10467 // `BehaviorError` / `UpgradeError` per-envelope ctor-macro pins.
10468 #[test]
10469 fn no_children_ctor_matches_struct_literal_wrap() {
10470 let estrategia = RestartStrategy::OneForAll;
10471 assert_eq!(
10472 SupervisorError::no_children(estrategia),
10473 SupervisorError::NoChildren { estrategia },
10474 "generated no_children ctor must produce byte-equal \
10475 `SupervisorError::NoChildren` to the pre-lift struct-literal wrap \
10476 on the same `Copy`-`RestartStrategy` fixture",
10477 );
10478 }
10479
10480 #[test]
10481 fn max_restarts_exceeds_cap_ctor_matches_struct_literal_wrap() {
10482 let max_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 1;
10483 assert_eq!(
10484 SupervisorError::max_restarts_exceeds_cap(max_restarts),
10485 SupervisorError::MaxRestartsExceedsCap { max_restarts },
10486 "generated max_restarts_exceeds_cap ctor must produce byte-equal \
10487 `SupervisorError::MaxRestartsExceedsCap` to the pre-lift \
10488 struct-literal wrap on the same `Copy`-`u32` fixture",
10489 );
10490 }
10491
10492 #[test]
10493 fn restart_window_not_canonical_ctor_matches_struct_literal_wrap() {
10494 let window = Duration::from_micros(1_500);
10495 assert_eq!(
10496 SupervisorError::restart_window_not_canonical(window),
10497 SupervisorError::RestartWindowNotCanonical { window },
10498 "generated restart_window_not_canonical ctor must produce \
10499 byte-equal `SupervisorError::RestartWindowNotCanonical` to the \
10500 pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
10501 );
10502 }
10503
10504 #[test]
10505 fn restart_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
10506 let window = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
10507 assert_eq!(
10508 SupervisorError::restart_window_exceeds_cap(window),
10509 SupervisorError::RestartWindowExceedsCap { window },
10510 "generated restart_window_exceeds_cap ctor must produce \
10511 byte-equal `SupervisorError::RestartWindowExceedsCap` to the \
10512 pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
10513 );
10514 }
10515
10516 #[test]
10517 fn supervisor_scalar_ctors_route_field_through_copy_uniformly() {
10518 // Cross-axis routing pin: sweep each generated `<field>: <ty>`
10519 // constructor input axis through a non-default `Copy` fixture against
10520 // every arm in the [`supervisor_scalar_ctors!`] macro, so any wrapper-
10521 // side silent `.into()` / silent constant-substitution / silent field
10522 // re-name away from the canonical `estrategia | max_restarts | window`
10523 // axes on any one variant, or a `RestartStrategy | u32 | Duration`
10524 // axis silently rerouted through some other `Copy` coercion, surfaces
10525 // here rather than at a downstream per-`:supervisor` diagnostic-shape
10526 // drift. Peer of the sibling
10527 // `aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly`
10528 // (7ef425e) cross-axis routing pin on the peer `AplicacaoError`
10529 // envelope's per-`:politicas` per-axis ctor family, extended here onto
10530 // the last M2 per-`:supervisor` `Copy`-scalar `SupervisorError`
10531 // variant family folded onto a substrate primitive.
10532 //
10533 // Fixtures picked out of each variant's accept-set boundary rather
10534 // than the default value so a silent constant-substitution to a per-
10535 // variant sentinel surfaces here on the structural-equality assertion.
10536 // The `RestartStrategy` fixture picks `RestForOne` (a non-default arm
10537 // that isn't the `OneForOne` [`SUPERVISOR_ESTRATEGIA_DEFAULT`] and
10538 // isn't the `SimpleOneForOne` arm the sibling
10539 // `SimpleOneForOneWithStaticChildren` unit variant intercepts). The
10540 // `max_restarts` fixture picks an above-cap magnitude the cap arm
10541 // rejects; the two `Duration` fixtures pick the sub-millisecond and
10542 // above-cap ends of the `:restart-window` canonical-form + cap
10543 // bracket respectively.
10544 let estrategia = RestartStrategy::RestForOne;
10545 let above_cap_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 137;
10546 let sub_ms = Duration::from_micros(1_500);
10547 let above_hour = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
10548 assert_eq!(
10549 SupervisorError::no_children(estrategia),
10550 SupervisorError::NoChildren { estrategia },
10551 );
10552 assert_eq!(
10553 SupervisorError::max_restarts_exceeds_cap(above_cap_restarts),
10554 SupervisorError::MaxRestartsExceedsCap {
10555 max_restarts: above_cap_restarts,
10556 },
10557 );
10558 assert_eq!(
10559 SupervisorError::restart_window_not_canonical(sub_ms),
10560 SupervisorError::RestartWindowNotCanonical { window: sub_ms },
10561 );
10562 assert_eq!(
10563 SupervisorError::restart_window_exceeds_cap(above_hour),
10564 SupervisorError::RestartWindowExceedsCap { window: above_hour },
10565 );
10566 }
10567
10568 #[test]
10569 fn supervisor_scalar_ctors_are_const_zero_runtime_work() {
10570 // Const-eval pin: the [`supervisor_scalar_ctors!`] macro spells every
10571 // generated ctor `const fn` so a caller can pin a `SupervisorError`
10572 // at compile time — the same zero-runtime-work property the pre-lift
10573 // `|<slot>| SupervisorError::<Variant> { <slot> }` closure carried on
10574 // its `Copy`-pass-through construction path (no `.to_string()` /
10575 // `.into()` allocation, no branching). If any future edit silently
10576 // drops the `const` qualifier from the macro body the per-arm `const`
10577 // bindings below fail to compile, which surfaces the regression at
10578 // the substrate-primitive definition rather than at some downstream
10579 // consumer that had come to rely on the `const`-constructibility.
10580 // Peer of the sibling
10581 // `aplicacao_policy_scalar_ctors_are_const_zero_runtime_work`
10582 // (7ef425e) const-eval pin on the peer `AplicacaoError` envelope's
10583 // per-`:politicas` per-axis ctor family.
10584 const NO_CHILDREN: SupervisorError =
10585 SupervisorError::no_children(RestartStrategy::OneForAll);
10586 const MAX_RESTARTS_CAP: SupervisorError = SupervisorError::max_restarts_exceeds_cap(1_337);
10587 const WINDOW_NC: SupervisorError =
10588 SupervisorError::restart_window_not_canonical(Duration::from_micros(1));
10589 const WINDOW_CAP: SupervisorError =
10590 SupervisorError::restart_window_exceeds_cap(Duration::from_secs(3_601));
10591 assert!(matches!(NO_CHILDREN, SupervisorError::NoChildren { .. }));
10592 assert!(matches!(
10593 MAX_RESTARTS_CAP,
10594 SupervisorError::MaxRestartsExceedsCap { .. }
10595 ));
10596 assert!(matches!(
10597 WINDOW_NC,
10598 SupervisorError::RestartWindowNotCanonical { .. }
10599 ));
10600 assert!(matches!(
10601 WINDOW_CAP,
10602 SupervisorError::RestartWindowExceedsCap { .. }
10603 ));
10604 }
10605}