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/// Per-child restart policy.
619///
620/// Permanent / Temporary / Transient match Erlang/OTP semantics 1:1.
621#[derive(
622 Serialize,
623 Deserialize,
624 Debug,
625 Clone,
626 Copy,
627 PartialEq,
628 Eq,
629 Hash,
630 gen_platform::TypedDispatcher,
631 gen_platform::Discriminant,
632 gen_platform::IsVariant,
633 gen_platform::FromStrKind,
634)]
635pub enum RestartPolicy {
636 /// Always restart the child, regardless of how it died. Used for
637 /// long-running services that must always be up.
638 Permanent,
639 /// Never restart. Used for one-shot work whose completion is
640 /// itself the success signal (`oneShot` triggers map here).
641 Temporary,
642 /// Restart only when the child died *abnormally* (non-zero exit
643 /// or unhandled exception). A clean exit completes the child.
644 Transient,
645}
646
647impl Default for RestartPolicy {
648 fn default() -> Self {
649 // Route the [`Default for RestartPolicy`] impl's return arm through
650 // the substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed
651 // `pub const` rather than a raw `Self::Permanent` arm — one source
652 // of truth for the Erlang/OTP-canonical `permanent` worker-child
653 // default across the two production consumers that currently
654 // dispatch on it (this impl at the [`RestartPolicy::default`] call
655 // and the serde-side `#[serde(default)]` on
656 // [`ChildSpec::restart`] that resolves an author-omitted
657 // `:children :restart` slot through `RestartPolicy::default()`).
658 // Peer of the sibling per-`:supervisor` axis
659 // [`Default for RestartStrategy`] → [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
660 // route (95ffacc) — the two impls now share one substrate-primitive
661 // lift discipline, so any future coherent rebrand of the OTP-shape
662 // supervisor+child default set migrates through typed constants in
663 // lockstep instead of splitting a lifted supervisor half against
664 // an open-coded child half. Pinned by
665 // `restart_policy_default_routes_through_lifted_default` +
666 // `child_spec_serde_default_restart_routes_through_lifted_default`
667 // in the tests module.
668 SUPERVISOR_CHILD_RESTART_DEFAULT
669 }
670}
671
672impl RestartPolicy {
673 /// Exhaustive iteration surface for every consumer that walks the
674 /// closed three-arm [`RestartPolicy`] discriminator set (the future
675 /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
676 /// per-child admission-webhook rejection body naming the accepted-
677 /// `:restart` list, a future `feira supervisor --restart …` CLI
678 /// arg-parse's "did you mean" hint via a [`Self::from_wire`]-scan
679 /// over the slice, the future `feira app graph` per-child restart
680 /// column, any future round-trip fuzz harness that sweeps every
681 /// arm). A future arm addition (an OTP-`intrinsic` fourth arm the
682 /// theory
683 /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
684 /// might reach for once the three canonical OTP restart policies
685 /// stop covering the substrate's discovered load-shape) extends
686 /// this slice as one edit and every consumer picks up the new entry
687 /// by construction; the compiler-checked exhaustiveness on the
688 /// sibling method `match` arms ([`Self::as_str`] / [`Self::from_wire`])
689 /// is the build-time guarantee that no arm forgets to grow.
690 ///
691 /// Peer of the sibling closed-set typed enums'
692 /// [`RestartStrategy::ALL`] (4eec29c) /
693 /// [`crate::CaixaKind::ALL`] (6b1f4fb) /
694 /// [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
695 /// [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
696 /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
697 /// surfaces — the sixth (and the third and final M2 OTP-shape)
698 /// closed-set typed enum on the caixa surface to converge onto the
699 /// same one-canonical-arm-list-per-enum discipline. Sibling axis to
700 /// the peer [`RestartStrategy::ALL`] on the per-supervisor
701 /// sibling-restart-strategy axis; this closes the per-child
702 /// restart-decision-policy axis on the same M2 `:supervisor` slot.
703 pub const ALL: &'static [Self] = &[Self::Permanent, Self::Temporary, Self::Transient];
704
705 /// Canonical PascalCase discriminator scalar this variant serializes
706 /// as under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`]. The three
707 /// arms return the paired
708 /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
709 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
710 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] lifted
711 /// constants so every substrate consumer that dispatches on the
712 /// per-child restart-decision policy (the future wasm-operator's
713 /// per-child post-exit restart-decision branch, the future M4
714 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
715 /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
716 /// reconciliation scheduler's per-child-policy fan-out) reads the
717 /// same byte-string the `Serialize` derive emits — the pin test in
718 /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
719 /// asserts the two paths agree, peer of the M2
720 /// [`RestartStrategy::as_str`] (09ffb2d) on the sibling per-supervisor
721 /// sibling-restart-strategy axis and the M3
722 /// [`crate::aplicacao::PlacementStrategy::as_str`] (cc8f749) on the
723 /// per-Aplicacao distribution-strategy axis — the third of three
724 /// OTP-shaped closed-enum discriminator axes on the caixa typed
725 /// surface to converge onto the same three-path-convergence
726 /// (`Serialize` derive → `as_str` helper → lifted constant)
727 /// drift-detection posture.
728 #[must_use]
729 pub const fn as_str(self) -> &'static str {
730 match self {
731 Self::Permanent => crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
732 Self::Temporary => crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
733 Self::Transient => crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
734 }
735 }
736
737 /// Substrate-canonical reverse projection on the `:children :restart`
738 /// closed-set axis — parses the `PascalCase` discriminator scalar
739 /// back to the typed variant, or `None` when `s` is outside the
740 /// closed-set arm-string set [`Self::as_str`] emits. Dispatches on
741 /// the same lifted
742 /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
743 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
744 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] constants
745 /// the [`Self::as_str`] emitter walks, so the parse and emit halves
746 /// of the round-trip migrate through one caixa-core edit on any
747 /// future arm addition.
748 ///
749 /// Prior to this lift the substrate carried only the forward
750 /// `Self → &str` projection on the OTP per-child restart-policy
751 /// axis (the [`Self::as_str`] emitter, the [`std::fmt::Display`]
752 /// impl routed through it, the `Serialize` derive that emits the
753 /// same byte-string under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`])
754 /// plus the kebab-case dispatcher-catalog identity via
755 /// [`Self::discriminant`] — every non-serde consumer that wanted to
756 /// parse a wire-form `PascalCase` policy scalar had to re-inline a
757 /// three-arm `match s { "Permanent" => …, "Temporary" => …,
758 /// "Transient" => …, _ => … }` cascade that expressed no
759 /// compile-time link back to the typed variant's canonical lifted
760 /// constant. A future variant rename or per-arm serde-attribute
761 /// drift would silently split the wire byte-string one non-serde
762 /// consumer parsed from the one the emitter wrote, with the failure
763 /// surfacing at the operator's reconcile posture (a `:temporary`
764 /// `oneShot` child being restarted on clean exit, treating the
765 /// successful-completion signal as failure and re-running the
766 /// completion-terminal one-shot indefinitely; a `:transient` child
767 /// that clean-exited being restarted, masking the clean-completion
768 /// contract) far from the rebrand commit and with no field naming
769 /// the drift.
770 ///
771 /// Distinct axis from the [`std::str::FromStr`] impl the
772 /// [`gen_platform::FromStrKind`] derive already installs on this
773 /// enum by design, not by drift: `FromStr` parses the *kebab-case*
774 /// dispatcher-catalog identity (`"permanent"` / `"temporary"` /
775 /// `"transient"` — the inverse of [`Self::discriminant`]), while
776 /// this method inverts the `PascalCase` wire byte-string
777 /// [`Self::as_str`] emits. The two-axis split lets the dispatcher-
778 /// catalog identity live in kebab-case (where every peer catalog
779 /// identifier already lives) without forcing a wire-format rename
780 /// on the tatara-lisp author surface (`:restart Permanent`,
781 /// `PascalCase`) — the same two-axis distinction the sibling
782 /// [`RestartStrategy::from_wire`] (4eec29c) /
783 /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
784 /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
785 /// carry on their peer closed-set typed-enum wire round-trips.
786 ///
787 /// Same closed-set-reverse-projection discipline the sibling
788 /// [`RestartStrategy::from_wire`] (4eec29c) /
789 /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
790 /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
791 /// [`crate::aplicacao::RateLimitUnit::from_suffix`] typed enums
792 /// carry on the peer wire-side `str → Self` axes — extended onto
793 /// the M2 OTP-shape per-child restart-policy closed-set axis, the
794 /// sixth substrate-side closed-set typed enum (and the third and
795 /// final OTP-shape closed-enum discriminator axis) to converge on
796 /// the two-way `str ↔ Self` round-trip. Method-named `from_wire`
797 /// (not `from_str`) to match the peer [`RestartStrategy::from_wire`]
798 /// shape verbatim and side-step the [`std::str::FromStr`] impl the
799 /// derive already installs on the sibling kebab-case axis. Returns
800 /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
801 /// shapes: the caller picks the diagnostic form appropriate for
802 /// its use site.
803 #[must_use]
804 pub fn from_wire(s: &str) -> Option<Self> {
805 match s {
806 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT => Some(Self::Permanent),
807 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY => Some(Self::Temporary),
808 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT => Some(Self::Transient),
809 _ => None,
810 }
811 }
812}
813
814/// [`std::fmt::Display`] routed through [`RestartPolicy::as_str`], so the
815/// pretty-printed byte-string every consumer that formats the policy as
816/// user-facing text lands on (the future wasm-operator's per-child
817/// post-exit restart-decision diagnostic line, the future `feira app
818/// graph` per-child restart column, the future M4
819/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
820/// admission-webhook rejection body) reaches for the same lifted
821/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
822/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
823/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
824/// wire-format `Serialize` derive already emits under
825/// [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
826/// [`RestartPolicy::as_str`] helper already returns.
827///
828/// Pre-convergence the two paths structurally disagreed — the
829/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
830/// route (now retired here) sent [`std::fmt::Display`] through the
831/// gen-platform discriminant catalog string, which arrives kebab-case as
832/// `"permanent"` / `"temporary"` / `"transient"` on this three-arm enum
833/// (whose variant names each collapse to their own lowercase form under
834/// the kebab-case transform), while the wire format ran as `PascalCase`
835/// `"Permanent"` / `"Temporary"` / `"Transient"` through the un-`rename`d
836/// serde derive. Every consumer that formatted the policy for a
837/// diagnostic line, a graph column, or a rejection body under
838/// `format!("{v}")` therefore landed under a different byte-string than
839/// the wire format the operator's per-child-policy dispatch keyed off —
840/// a silent split whose apply-time symptom (a `format!("{v}")`-carrying
841/// diagnostic quoting `"permanent"` while the wire scalar the operator
842/// probed was `"Permanent"`) surfaced as a confused correlate at
843/// operator-log time far from the two-declaration site.
844///
845/// Routing `Display` through [`RestartPolicy::as_str`] closes the third
846/// path: every `format!("{v}")` call reaches the same lifted
847/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the wire format
848/// and the [`RestartPolicy::as_str`] helper route through — `Debug` (the
849/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
850/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
851/// byte-string per variant. A future variant rename or
852/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
853/// exactly one place, structurally.
854///
855/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
856/// (from `#[derive(gen_platform::Discriminant)]`) still returns
857/// `"permanent"` / `"temporary"` / `"transient"`, and the fleet-wide
858/// [`gen_platform::register_dispatcher!("caixa.restart-policy", …)`]
859/// registration keys the catalog off the same kebab identity. The two
860/// naming worlds now live on separate typed methods (`Display` /
861/// `as_str` for the wire byte-string, `discriminant` for the catalog
862/// identity) rather than sharing one `Display` route that structurally
863/// disagrees with the wire format.
864///
865/// Pin tests
866/// [`tests::restart_policy_display_routes_through_as_str_helper`]
867/// and
868/// [`tests::restart_policy_display_matches_serialized_wire_byte_string`]
869/// assert the three paths agree byte-for-byte on every variant, so a
870/// future variant rename or per-arm serde attribute drift is a build
871/// error visible at caixa-core test time, not a silent per-consumer
872/// dispatch miss at apply / reconcile time.
873///
874/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
875/// (aplicacao.rs:2306) on the per-Aplicacao distribution-strategy axis
876/// and the sibling [`RestartStrategy`] `Display` impl on the
877/// per-supervisor sibling-restart-strategy axis — same three-path-
878/// convergence discipline, extended to close the third and final of
879/// three OTP-shaped closed-enum discriminator axes on the caixa typed
880/// surface.
881impl std::fmt::Display for RestartPolicy {
882 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
883 f.write_str(self.as_str())
884 }
885}
886
887/// Substrate-canonical [`AsRef<str>`] projection on the M2
888/// per-child-restart-policy [`RestartPolicy`] closed-set typed enum —
889/// routes through the same [`RestartPolicy::as_str`] `pub const fn`
890/// scalar accessor the paired [`std::fmt::Display`] impl and the
891/// un-`rename`d [`serde::Serialize`] derive already key off, so any
892/// future consumer that binds a [`RestartPolicy`] through the
893/// standard-library `impl AsRef<str>` bound (a future
894/// [`caixa-feira`] `feira supervisor --restart <arm>` verb that
895/// composes the emitted `PascalCase` wire scalar into a
896/// [`std::process::Command::arg`] shell-out of the future
897/// wasm-operator's per-child admission gate, a per-child structured-
898/// log recorder on the future `caixa-operator`'s hierarchical
899/// reconciliation surface that accepts `impl AsRef<str>` at the
900/// `tracing::field::Value` `Str`-arm, a [`std::collections::HashMap`]
901/// lookup keyed on the restart-policy wire byte through
902/// `map.get::<str>(policy.as_ref())` on a future per-policy
903/// dispatch table) reaches the paired
904/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
905/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
906/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
907/// lifted-const through one substrate-primitive dispatch rather
908/// than an open-coded `.as_str()` projection at every wire-up.
909///
910/// Peer of the sibling [`std::fmt::Display`] impl on the same
911/// primitive — both delegate to the shared [`RestartPolicy::as_str`]
912/// `pub const fn` accessor, so [`format!("{v}")`], `v.as_str()`, and
913/// `<RestartPolicy as AsRef<str>>::as_ref(&v)` resolve to the same
914/// byte-string per instance by construction. A future variant rename
915/// or `#[serde(rename_all = "kebab-case")]` attribute-drift on the
916/// enum reaches every one of the three paths (plus the wire-format
917/// `Serialize` derive that already routes through the same lifted
918/// const) through exactly one caixa-core edit.
919///
920/// Same "route the trait impl through the substrate-primitive
921/// accessor" discipline the sibling [`crate::CaixaVersion`]
922/// [`AsRef<str>`] impl (16d5c7e) and the paired M2
923/// [`RestartStrategy`] [`AsRef<str>`] impl (63eb1a4) carry — extends
924/// the axis onto the paired per-child-restart-decision-policy
925/// sibling on the same M2 `:supervisor` slot (the second M2
926/// OTP-shape closed-set typed enum to converge onto the standard-
927/// library [`AsRef<str>`] projection). Rust-side newtype/typed-enum
928/// convention pairs [`AsRef<str>`] and [`fmt::Display`] on the same
929/// primitive so a caller who has one has both; before this lift,
930/// [`RestartPolicy`] carried [`fmt::Display`] but not the paired
931/// [`AsRef<str>`] impl the convention names.
932///
933/// Pinned load-bearing by
934/// [`tests::restart_policy_as_ref_str_routes_through_as_str_accessor`]
935/// (byte-parity pin against [`RestartPolicy::as_str`] across the
936/// three-arm closed set) and
937/// [`tests::restart_policy_as_ref_str_routes_through_display_via_shared_accessor`]
938/// (three-path convergence: `AsRef<str>` + `Display` + `as_str` all
939/// resolve to the same lifted `SUPERVISOR_CHILD_RESTART_*` const per
940/// arm) — any future silent detour that routes the impl through a
941/// divergent projection (a per-arm inline `match self { … }`
942/// re-inlining that opens a compile-time link to the un-lifted
943/// arm-literal, a swap onto the kebab-case
944/// [`gen_platform::Discriminant`] catalog identity that would
945/// collide the wire axis with the dispatcher-catalog axis) trips at
946/// caixa-core test time under `assert_eq!` rather than at a
947/// downstream `impl AsRef<str>`-bound consumer's silent split.
948impl AsRef<str> for RestartPolicy {
949 fn as_ref(&self) -> &str {
950 self.as_str()
951 }
952}
953
954/// Trait-idiomatic reverse projection on the M2-OTP-shape per-child
955/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
956/// byte-for-byte through the paired substrate-primitive
957/// [`RestartPolicy::from_wire`] `Option<Self>` accessor so every future
958/// consumer that binds a `PascalCase` `:children :restart` wire
959/// byte-string through the standard-library `.try_into()` / [`TryFrom`]
960/// axis (a future [`caixa-feira`] `feira supervisor --restart
961/// <Permanent|Temporary|Transient>` CLI arg-parse that composes into
962/// `let restart: RestartPolicy = s.try_into()?`, a future
963/// `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook that folds a
964/// `spec.children[*].restart: String` field through
965/// `RestartPolicy::try_from(&s)?`, a generic
966/// `<T: TryFrom<&str>>`-bound loader over any of the substrate's closed-
967/// set typed enums) reaches the same three-arm accept-set the sibling
968/// [`RestartPolicy::from_wire`] resolver parses through and the sibling
969/// [`RestartPolicy::as_str`] emits, rather than an open-coded per-arm
970/// `match s { "Permanent" => …, "Temporary" => …, "Transient" => …, _ =>
971/// … }` cascade whose arm-set has no compile-time link back to the
972/// substrate primitive.
973///
974/// Complements the pre-existing forward-projection triple
975/// ([`std::fmt::Display`], [`AsRef<str>`], [`RestartPolicy::as_str`])
976/// with the paired trait-idiomatic reverse-projection axis: Rust-side
977/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
978/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so a
979/// caller who can project *out to* a `&str` can also project *in from*
980/// one. The [`TryFrom<&str>`] axis is deliberately chosen over
981/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
982/// lint the sibling method-named [`RestartPolicy::from_wire`] would
983/// trigger under a `FromStr` impl and to avoid colliding with the
984/// [`std::str::FromStr`] impl the [`gen_platform::FromStrKind`] derive
985/// already installs on the paired *kebab-case dispatcher-catalog* axis
986/// (which parses `"permanent"` / `"temporary"` / `"transient"`, the
987/// inverse of [`Self::discriminant`]) — this impl closes the trait-
988/// idiomatic reverse axis on the *`PascalCase` wire* half without
989/// disturbing either the method-named `from_wire` shape every sibling
990/// closed-set typed enum on the substrate already carries or the
991/// pre-existing `FromStr` on the dispatcher-catalog half, keeping the
992/// two-axis split the sibling [`Self::from_wire`] doc block motivates.
993///
994/// `type Error = ()` matches the sibling [`RestartPolicy::from_wire`]'s
995/// `Option<Self>` return-shape's deliberate deferral of error typing: the
996/// caller picks the diagnostic form appropriate for its use site (a
997/// future `feira supervisor --restart` arg-parse composes its own
998/// per-verb "unknown restart: <arg> — accepted: {…}" message enumerating
999/// [`RestartPolicy::ALL`], a future M4 admission-webhook rejection body
1000/// wraps the `Err(())` outcome with the accepted-set enumeration for
1001/// operator diagnostics, a `Result::map_err` at the call site lifts the
1002/// unit-error to a per-verb error type). Same shape the peer
1003/// [`RestartStrategy`] (5b828ed) on the sibling per-supervisor axis,
1004/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136), and
1005/// [`crate::aplicacao::PlacementStrategy`] (6fd00cd) blocks motivate on
1006/// their peer closed-set typed enums' reverse projections.
1007///
1008/// The paired [`TryFrom<&str>`] impl reaches the same three-arm accept-
1009/// set the [`RestartPolicy::from_wire`] resolver dispatches through, so
1010/// any future arm addition (an OTP-`intrinsic` fourth arm the theory
1011/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1012/// might reach for once the three canonical OTP restart policies stop
1013/// covering the substrate's discovered load-shape) grows the trait-
1014/// idiomatic axis by construction — one caixa-core edit on
1015/// [`RestartPolicy::from_wire`] extends both the method-named reverse
1016/// projection every existing consumer keys off and the trait-idiomatic
1017/// reverse projection this impl exposes, without a coordinated rewrite
1018/// across every future `TryFrom<&str>`-bound consumer's arm-set.
1019///
1020/// Extends the substrate-wide closed-set-enum reverse-projection family
1021/// ([`crate::CaixaKind`] via 3c83606, [`crate::CaixaDialeto`] via
1022/// bf33136, [`crate::aplicacao::PlacementStrategy`] via 6fd00cd, and
1023/// [`RestartStrategy`] via 5b828ed) onto the third and final OTP-shape
1024/// closed-enum discriminator axis on the caixa surface — the paired
1025/// per-child `:children :restart` closed set the future wasm-operator's
1026/// hierarchical reconciliation scheduler's per-child post-exit
1027/// restart-decision branch keys off end-to-end.
1028///
1029/// Pinned load-bearing by
1030/// [`tests::restart_policy_try_from_str_routes_through_from_wire_accessor`]
1031/// (byte-parity pin against [`RestartPolicy::from_wire`] across the
1032/// three-arm accept-set),
1033/// [`tests::restart_policy_try_from_str_rejects_unknown_byte_strings`]
1034/// (rejection witness against silent accept-set widening), and
1035/// [`tests::restart_policy_try_from_str_and_from_wire_partition_the_accept_set`]
1036/// (cross-axis partition pin locking the trait and method-named
1037/// projections onto one accept-set).
1038impl TryFrom<&str> for RestartPolicy {
1039 type Error = ();
1040
1041 fn try_from(s: &str) -> Result<Self, Self::Error> {
1042 Self::from_wire(s).ok_or(())
1043 }
1044}
1045
1046/// Trait-idiomatic forward projection on the M2-OTP-shape per-child
1047/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
1048/// byte-for-byte through the paired substrate-primitive
1049/// [`RestartPolicy::as_str`] `pub const fn` accessor. Return type is
1050/// `&'static str` by construction — every [`RestartPolicy::as_str`] arm
1051/// resolves to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const
1052/// &str` with `'static` lifetime, so the trait's return-type promise is
1053/// upheld structurally without a [`String::leak`] cast or a per-arm inline
1054/// literal.
1055///
1056/// Every future consumer that specifically needs `&'static str` lifetime
1057/// bytes on the per-child restart-decision axis (a
1058/// [`tracing::field::valuable::Value::Str`] recording where the `Str`
1059/// arm's typing demands `&'static str`, a
1060/// [`std::borrow::Cow::Borrowed`]`::<'static, str>(policy.into())` composer
1061/// on the future M4 admission-webhook rejection body where the
1062/// `Cow<'static, str>` typing rules out the sibling [`AsRef<str>`]
1063/// borrowed return, a generic `<T: Into<&'static str>>`-bound serializer
1064/// or error formatter that requires the `'static` bound) reaches the same
1065/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1066/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1067/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] substrate-
1068/// primitive dispatch rather than an open-coded per-arm literal cascade
1069/// whose arm-set has no compile-time link back to the substrate primitive.
1070///
1071/// Peer of the sibling M2-OTP-shape [`RestartStrategy`] forward-projection
1072/// impl (523157d) on the per-supervisor sibling-restart-strategy axis —
1073/// the second (and second-of-two-in-M2) closed-set typed enum on the
1074/// caixa surface to converge onto the paired trait-idiomatic forward-
1075/// projection axis. With this lift the paired per-child
1076/// `:children :restart` closed-set typed enum carries the full sibling
1077/// quintet ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
1078/// [`TryFrom<&str>`] via 6fdd0d9, `From<Self> for &'static str` via this
1079/// lift) plus the round-trip witness through both the trait-idiomatic
1080/// (`From<Self> for &'static str` + `TryFrom<&str>`) and the method-named
1081/// (`as_str` + `from_wire`) axis pairs — mirrors the sibling
1082/// [`RestartStrategy`] surface arm-for-arm, so every future arm addition
1083/// (an OTP-`intrinsic` fourth arm the theory
1084/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1085/// might reach for once the three canonical OTP restart policies stop
1086/// covering the substrate's discovered load-shape) grows the trait-
1087/// idiomatic forward axis by construction: one caixa-core edit on
1088/// [`RestartPolicy::as_str`] extends every one of the five sibling
1089/// forward-projection paths ([`std::fmt::Display`], [`AsRef<str>`],
1090/// [`Self::as_str`] itself, this `From<Self> for &'static str`, and the
1091/// un-`rename`d [`serde::Serialize`] derive that also emits `as_str`'s
1092/// bytes) without a coordinated rewrite across every future
1093/// `Into<&'static str>`-bound consumer's arm-set.
1094///
1095/// Pinned load-bearing by
1096/// [`tests::restart_policy_from_into_static_str_routes_through_as_str_accessor`]
1097/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1098/// three-arm emit-set, plus a `const`-context materialization witness for
1099/// the `&'static str` lifetime promise) and
1100/// [`tests::restart_policy_from_into_static_str_and_as_str_partition_the_emit_set`]
1101/// (partition pin asserting `<&'static str as From<RestartPolicy>>::from`
1102/// and [`RestartPolicy::as_str`] agree on every arm, plus a two-way
1103/// round-trip witness through the paired trait-idiomatic reverse-
1104/// projection axis [`TryFrom<&str>`] (6fdd0d9): every
1105/// `policy.into::<&'static str>()` output re-parses back through
1106/// [`RestartPolicy::try_from`] to the original variant, closing the two-
1107/// way `Self ↔ &'static str` round-trip on the trait-idiomatic axis pair).
1108impl From<RestartPolicy> for &'static str {
1109 fn from(policy: RestartPolicy) -> &'static str {
1110 policy.as_str()
1111 }
1112}
1113
1114// Fleet-wide dispatcher-catalog registrations for caixa's OTP
1115// supervisor surface — two more typed shadows over Erlang/OTP
1116// primitives the substrate now mechanically tracks (see
1117// theory/UNIFIED-COMPUTING-MODEL.md §VI for the roadmap +
1118// theory/TYPED-ABSORPTION.md for the absorption arc).
1119gen_platform::register_dispatcher!("caixa.restart-strategy", RestartStrategy);
1120gen_platform::register_dispatcher!("caixa.restart-policy", RestartPolicy);
1121
1122/// One child entry in the supervisor's `:children` list.
1123///
1124/// Every child references another caixa by `:caixa <nome>` + version
1125/// constraint. The supervisor materializes one ComputeUnit per entry.
1126#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1127#[serde(rename_all = "camelCase")]
1128pub struct ChildSpec {
1129 /// The child caixa's `:nome`. Must resolve via the same dependency
1130 /// resolution path as `:deps` (caixa-resolver).
1131 pub caixa: String,
1132
1133 /// Semver constraint (`"^0.1"`, `"~0.1.2"`, etc.) — same shape as
1134 /// [`crate::dep::Dep::versao`].
1135 pub versao: String,
1136
1137 /// Restart policy — an author-omitted slot degrades onto the
1138 /// substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`]
1139 /// (`permanent`, the Erlang/OTP worker-child default) through the
1140 /// [`Default for RestartPolicy`] impl this `#[serde(default)]` routes
1141 /// to.
1142 #[serde(default)]
1143 pub restart: RestartPolicy,
1144}
1145
1146impl ChildSpec {
1147 /// Substrate-canonical per-`:children` child-caixa `:nome` scalar
1148 /// accessor every consumer that reads the OTP-shape supervised
1149 /// child's identity keys off — returns the author-declared
1150 /// `:children :caixa` byte-string verbatim as a `&str`, borrowed
1151 /// from the typed slot's own [`String`] storage.
1152 ///
1153 /// The `:children :caixa` slot carries the DNS-1123 label — the
1154 /// child caixa's `:nome` — that every emitted cluster artifact
1155 /// derives its `metadata.name` from verbatim: the rendered
1156 /// `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name` per child, the
1157 /// [`crate::LABEL_PROGRAM`] label value on every child's pod
1158 /// identity, and the per-child K8s Service `metadata.name` the
1159 /// future wasm-operator (M3) provisions for inter-child supervision-
1160 /// tree wiring. Every downstream consumer that fans on the child's
1161 /// caixa-name keys off this scalar (the [`SupervisorSpec::validate`]
1162 /// per-child DNS-1123 gate at
1163 /// `require_valid_dns_1123_label(child.nome(), …)`, the per-child
1164 /// duplicate-detection [`crate::render::insert_first_seen`] key, the
1165 /// [`validate_no_self_supervision`] cross-slot equality check
1166 /// against the parent's `:nome`, every `SupervisorError` variant
1167 /// carrying the offending child caixa verbatim for `feira lint`
1168 /// rendering, the future wasm-operator's hierarchical reconciliation
1169 /// scheduler's per-child ComputeUnit-name projection, the future M4
1170 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1171 /// admission webhook).
1172 ///
1173 /// Prior to this lift the `.caixa` byte-string was accessed inline
1174 /// at seven sites in `supervisor.rs` — the DNS-1123 gate's
1175 /// `&child.caixa`, the four `SupervisorError::{ChildCaixaInvalid,
1176 /// EmptyChildVersion, ChildVersaoInvalid, DuplicateChildCaixa}`
1177 /// carriers' `child.caixa.clone()`, the dedup key's
1178 /// `child.caixa.as_str()`, and the [`validate_no_self_supervision`]
1179 /// `child.caixa == parent_nome` cross-slot check — seven open-coded
1180 /// field-accesses that expressed no compile-time link back to the
1181 /// typed slot. A future extension of the `:children :caixa` axis to
1182 /// a richer author surface (a per-cluster alias table the operator
1183 /// pins through a future `:placement`-scoped slot on the supervisor
1184 /// tree, a namespace-qualified rewrite the M4 CR materializer
1185 /// applies per-CR, a per-child overlay from the future `:children
1186 /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
1187 /// acknowledges) would have had to be threaded through every
1188 /// open-coded copy in lockstep or one consumer would silently
1189 /// disagree with the peers on which caixa a given child resolves to
1190 /// — a child-set lookup that treated the name as `"cart-worker"`
1191 /// while the peer duplicate-detector treated it as
1192 /// `"tenant-a/cart-worker"` would silently split the
1193 /// `DuplicateChildCaixa` membership-lookup diagnostic from the
1194 /// self-supervision detector's parent-equality check, a two-consumer
1195 /// split at the validator far from the source `caixa.lisp` with no
1196 /// field naming the identity-drift root cause. Lifting the resolution
1197 /// rule to a typed method on the substrate primitive means every
1198 /// downstream consumer of the Supervisor's per-`:children` identity
1199 /// surface reaches for exactly one typed dispatch — the resolver's
1200 /// accept-set migrates as a unit on any future axis addition.
1201 ///
1202 /// Sibling of the peer per-`:membros` [`crate::Membro::nome`]
1203 /// (4a32abf) member-caixa `:nome` scalar accessor on the M3
1204 /// mesh-slot surface — same "one typed dispatch on the substrate
1205 /// primitive, thin projections at each consumer" discipline extended
1206 /// onto the M2 supervisor-tree per-`:children` child-identity axis.
1207 /// The two typed axes (`Membro::nome` on the M3 Aplicacao side,
1208 /// `ChildSpec::nome` on the M2 Supervisor side) now share one
1209 /// accessor discipline for the shared substrate concept "another
1210 /// caixa referenced by `:nome`". Peer of the second M2 slot scalar
1211 /// accessor [`crate::UpgradeFromEntry::prior_versao`] (75d27a8) on
1212 /// the sibling per-`:upgrade-from :from` OTP-appup axis — the M2
1213 /// slot family's typed-accessor discipline now spans both the
1214 /// upgrade axis (`:upgrade-from`) and the supervision axis
1215 /// (`:children`), matching the closed M3 mesh-slot accessor family's
1216 /// shape. Named `nome()` to match the tatara-lisp author-surface
1217 /// term the field's docstring already reaches for ("The child
1218 /// caixa's `:nome`") and the peer [`crate::Membro::nome`] /
1219 /// [`crate::Caixa::nome`] / [`crate::dep::Dep::nome`] field-name
1220 /// discipline the substrate already carries — the accessor's name
1221 /// maps directly onto the canonical caixa-identity vocabulary rather
1222 /// than shadowing the field's storage-side `caixa` label.
1223 #[must_use]
1224 pub const fn nome(&self) -> &str {
1225 self.caixa.as_str()
1226 }
1227
1228 /// Substrate-canonical per-`:children` child-caixa `:versao` semver-
1229 /// requirement scalar accessor every consumer that reads the OTP-shape
1230 /// supervised child's version pin keys off — returns the author-declared
1231 /// `:children :versao` byte-string verbatim as a `&str`, borrowed from
1232 /// the typed slot's own [`String`] storage.
1233 ///
1234 /// The `:children :versao` slot carries the Cargo-shaped semver
1235 /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that pins
1236 /// which release of the supervised child caixa the OTP-shape supervisor
1237 /// tree materializes against — the same requirement grammar the peer
1238 /// `:deps :versao` / `:membros :versao` axes carry, resolved through the
1239 /// shared [`crate::render::require_valid_versao_requirement`] cascade
1240 /// and the shared [`crate::version::parse_requirement`] parser. Every
1241 /// downstream consumer that fans on the child's version pin keys off
1242 /// this scalar (the [`SupervisorSpec::validate`] per-child requirement
1243 /// gate at `require_valid_versao_requirement(child.versao_requirement(),
1244 /// …)`, the [`SupervisorError::ChildVersaoInvalid`] variant's carrier
1245 /// for `feira lint` rendering, every future per-cluster version-lock
1246 /// overlay the caixa-operator's hierarchical reconciliation scheduler
1247 /// pins through a future `:placement`-scoped supervisor-tree slot, the
1248 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1249 /// per-child version resolver, the future wasm-operator's per-child
1250 /// lacre BLAKE3-closure lookup at `ComputeUnit` materialization time).
1251 ///
1252 /// Prior to this lift the `.versao` byte-string was accessed inline at
1253 /// two `&str`-shaped sites in `caixa-core/src/supervisor.rs` — the
1254 /// [`SupervisorSpec::validate`] requirement-gate call
1255 /// `require_valid_versao_requirement(&child.versao, …)` and the
1256 /// [`SupervisorError::ChildVersaoInvalid`] carrier at
1257 /// `versao: child.versao.clone()` — two open-coded field-accesses that
1258 /// expressed no compile-time link back to the typed slot. A future
1259 /// extension of the `:children :versao` axis to a richer author surface
1260 /// (a per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
1261 /// flow, a lacre-projected concrete-version rewrite the operator
1262 /// materializes at CR-admission time, a future `:children :versao-lock`
1263 /// per-cluster override slot the wasm-operator's hierarchical
1264 /// reconciliation scheduler authors per-CR) would have had to be
1265 /// threaded through both open-coded copies in lockstep or one consumer
1266 /// would silently disagree with the peer on which release constraint a
1267 /// given child resolves to — the requirement-gate call reading
1268 /// `"^0.1"` while the error-body carrier read `"tenant-a-pin/^0.1"`
1269 /// would silently split the `ChildVersaoInvalid` diagnostic quote from
1270 /// the actual gate rejection input, a two-consumer split at the
1271 /// validator far from the source `caixa.lisp` with no field naming the
1272 /// version-pin drift root cause. Lifting the resolution rule to a typed
1273 /// method on the substrate primitive means every downstream
1274 /// requirement-facing consumer of the Supervisor's per-`:children`
1275 /// version-pin surface reaches for exactly one typed dispatch — the
1276 /// resolver's accept-set migrates as a unit on any future axis addition.
1277 ///
1278 /// Sibling of the peer per-`:membros` [`crate::Membro::versao_requirement`]
1279 /// (a40b0e3) member-caixa `:versao` scalar accessor on the M3 mesh-slot
1280 /// surface — same "one typed dispatch on the substrate primitive, thin
1281 /// projections at each consumer" discipline extended onto the M2
1282 /// supervisor-tree per-`:children` child-version-pin axis. The two typed
1283 /// axes (`Membro::versao_requirement` on the M3 Aplicacao side,
1284 /// `ChildSpec::versao_requirement` on the M2 Supervisor side) now share
1285 /// one accessor discipline for the shared substrate concept "another
1286 /// caixa referenced by a Cargo-shaped semver requirement". Peer of the
1287 /// sibling per-`:children` [`ChildSpec::nome`] (57c61d0) child-caixa
1288 /// `:nome` scalar accessor — the pair
1289 /// `(nome(), versao_requirement())` jointly projects the
1290 /// `(caixa, versao)` field pair every OTP-shape supervisor-tree consumer
1291 /// that fans on per-child identity + version pin keys off, closing the
1292 /// last unlifted per-`:children` `String`-carry axis so every downstream
1293 /// per-`:children` reader now routes through a typed dispatch on the
1294 /// substrate primitive. Named `versao_requirement()` rather than
1295 /// `versao()` because the field's storage-side `.versao` label is
1296 /// already the author-surface term (`:versao`); the accessor's name
1297 /// carries the semantic role — the semver *requirement* string the
1298 /// shared [`crate::version::parse_requirement`] entry-point consumes —
1299 /// so a raw field access and a typed dispatch read differently at every
1300 /// consumer site. Matches the peer [`crate::Membro::versao_requirement`]
1301 /// naming discipline verbatim.
1302 #[must_use]
1303 pub const fn versao_requirement(&self) -> &str {
1304 self.versao.as_str()
1305 }
1306
1307 /// Substrate-canonical per-`:children` `:restart` OTP-shaped
1308 /// per-child post-exit restart-decision policy scalar accessor every
1309 /// consumer that dispatches on the supervised child's post-exit
1310 /// reconcile posture keys off — returns the author-declared
1311 /// `:children :restart` variant verbatim as a [`RestartPolicy`],
1312 /// `Copy`-projected from the typed slot's own [`RestartPolicy`]
1313 /// storage.
1314 ///
1315 /// The `:children :restart` slot carries the closed-set OTP-shaped
1316 /// per-child restart-decision policy discriminator
1317 /// ([`RestartPolicy::Permanent`] — always restart, the OTP `permanent`
1318 /// worker-child default; [`RestartPolicy::Transient`] — restart only
1319 /// on abnormal exit, the OTP `transient` clean-completion-aware
1320 /// default; [`RestartPolicy::Temporary`] — never restart, the OTP
1321 /// `temporary` one-shot default) that every downstream consumer of
1322 /// the Supervisor's per-child post-exit reconcile branch keys off.
1323 /// Every future downstream consumer that fans on the per-child
1324 /// restart-decision keys off this scalar (the future `feira app
1325 /// graph` per-child restart column, the future wasm-operator's
1326 /// per-child post-exit restart-decision branch, the future M4
1327 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1328 /// admission webhook, the `caixa-operator`'s hierarchical
1329 /// reconciliation scheduler's per-child post-exit reconcile branch,
1330 /// the [`RestartPolicy::as_str`] `Serialize`-derive-pinning path the
1331 /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
1332 /// pin threads through).
1333 ///
1334 /// Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
1335 /// (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
1336 /// scalar accessor and the M3 mesh-slot
1337 /// [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
1338 /// [`crate::PlacementStrategy`] distribution-strategy scalar accessor
1339 /// — same "one typed dispatch on the substrate primitive,
1340 /// `Copy`-projected closed-set enum-arm discriminator that partitions
1341 /// the downstream renderer's per-arm fan-out" discipline extended
1342 /// onto the M2 supervisor-slot per-`:children` restart-decision-policy
1343 /// `Copy`-composite-enum scalar axis. Third axis on the per-`:children`
1344 /// [`ChildSpec`] type — companion to the sibling per-`:children`
1345 /// [`ChildSpec::nome`] (57c61d0) child-caixa `:nome` scalar accessor
1346 /// and the per-`:children` [`ChildSpec::versao_requirement`]
1347 /// (2c053c8) child-caixa `:versao` semver-requirement scalar accessor
1348 /// on the sibling `String`-carry axes. The triple
1349 /// `(nome(), versao_requirement(), restart())` jointly projects the
1350 /// `(caixa, versao, restart)` field trio every OTP-shape supervisor-
1351 /// tree consumer that fans on per-child identity + version pin +
1352 /// restart-decision keys off, closing the last unlifted per-`:children`
1353 /// axis so every downstream per-`:children` reader now routes through
1354 /// a typed dispatch on the substrate primitive. Named `restart()` to
1355 /// match the storage field's name and the author-surface
1356 /// `:children :restart` slot term verbatim; the accessor's identity
1357 /// name maps onto the canonical OTP-shape per-child restart-decision-
1358 /// policy vocabulary the [`RestartPolicy`] enum's docstring already
1359 /// carries.
1360 ///
1361 /// Declared `pub const fn` to close the last non-`const`
1362 /// `Copy`-return raw-field-getter posture on the M2
1363 /// per-`:children` [`ChildSpec`] substrate-primitive surface — peer
1364 /// of the sibling M2 per-`:supervisor`
1365 /// [`SupervisorSpec::estrategia`] (converted in this commit)
1366 /// `Copy`-composite-enum accessor, the sibling M2 per-`:supervisor`
1367 /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
1368 /// already lifted, and the peer M3 mesh-slot per-`:entrada`
1369 /// [`crate::Entrada::port`] (bafa004) / per-`:placement`
1370 /// [`crate::Placement::estrategia`] (bafa004) `Copy`-return
1371 /// `pub const fn` scalar accessors on the sibling M3 surface. Every
1372 /// downstream substrate-side `const`-context consumer of the
1373 /// per-`:children` restart-decision-policy scalar (a future
1374 /// module-scope `const _:() = assert!(matches!(child.restart(),
1375 /// RestartPolicy::Permanent))` invariant pin on a typed fixture, a
1376 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
1377 /// admission-webhook `const fn` per-child restart-decision floor
1378 /// over a typed [`ChildSpec`], any future `const fn` supervisor-tree
1379 /// composer over the substrate primitive that fans on the per-child
1380 /// restart-decision policy at compile time) now reaches through the
1381 /// same typed dispatch on the substrate primitive at const-eval
1382 /// time as at runtime. A future non-`Copy`-return promotion of the
1383 /// scalar (an `Option<RestartPolicy>`-shape migration on the
1384 /// per-child restart-decision axis once heterogeneous per-cluster
1385 /// restart-policy overlays land, a per-tenant restart-policy-alias
1386 /// table the M4 CR materializer resolves per-CR) that would drop
1387 /// the `const` qualifier fails the fail-before-pass-after pin
1388 /// [`tests::child_spec_restart_accessor_is_const_fn`] at caixa-core
1389 /// build time rather than surfacing as a downstream consumer
1390 /// regression.
1391 #[must_use]
1392 pub const fn restart(&self) -> RestartPolicy {
1393 self.restart
1394 }
1395}
1396
1397/// Supervisor-typed slots that live alongside the standard Caixa
1398/// fields when `:kind Supervisor`. Held flat in [`crate::Caixa`] so
1399/// the manifest stays a single typed form; this struct exists for
1400/// validation + conversion.
1401#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1402#[serde(rename_all = "camelCase")]
1403pub struct SupervisorSpec {
1404 /// Restart strategy. Defaults to [`RestartStrategy::OneForOne`].
1405 #[serde(default)]
1406 pub estrategia: RestartStrategy,
1407
1408 /// Max restarts within [`Self::restart_window`] before the
1409 /// supervisor itself terminates (and its parent supervisor decides
1410 /// what to do). Default 5.
1411 #[serde(default = "default_max_restarts")]
1412 pub max_restarts: u32,
1413
1414 /// Sliding window for `max_restarts`. Authored as a duration
1415 /// string (`"60s"`, `"5m"`); absent = "never reset". A `Some(0s)`
1416 /// is rejected by [`Self::validate`] — Erlang/OTP's
1417 /// `MaxIntensity / Period` invariant requires a positive window
1418 /// (a zero-period supervisor either trips on the first failure or
1419 /// never trips, depending on operator interpretation, neither of
1420 /// which is the author's intent). Omit the slot to express "no
1421 /// reset"; carry a positive duration to express the sliding window.
1422 #[serde(
1423 default,
1424 skip_serializing_if = "Option::is_none",
1425 with = "duration_codec"
1426 )]
1427 pub restart_window: Option<Duration>,
1428
1429 /// Static children. Empty for `SimpleOneForOne` (children added
1430 /// dynamically); required for the other three strategies.
1431 #[serde(default)]
1432 pub children: Vec<ChildSpec>,
1433}
1434
1435const fn default_max_restarts() -> u32 {
1436 // Route the private serde-`#[serde(default = "…")]` helper through
1437 // the substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] typed
1438 // `pub const` rather than the raw `5` literal — one source of truth
1439 // for the Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
1440 // default across the two production consumers that currently
1441 // dispatch on it (this helper via `#[serde(default = "…")]` on
1442 // `SupervisorSpec::max_restarts` and the [`Default for SupervisorSpec`]
1443 // impl at line 962). Pinned by
1444 // `default_max_restarts_helper_routes_through_lifted_default` +
1445 // `supervisor_spec_default_max_restarts_routes_through_lifted_default`
1446 // in the tests module; peer of the sibling caixa-core
1447 // [`crate::manifest::Caixa::supervisor_view`] `unwrap_or(…)` fold
1448 // that now routes its author-omitted `:max-restarts` arm through
1449 // the same lifted constant.
1450 SUPERVISOR_MAX_RESTARTS_DEFAULT
1451}
1452
1453/// Substrate-canonical Erlang/OTP-shaped `MaxIntensity` restart-budget-
1454/// count default for the `:supervisor :max-restarts` axis — the
1455/// canonical `{intensity, 5, 60}` `MaxIntensity` half of Learn You Some
1456/// Erlang's worker-supervisor default, extracted as a typed `pub const`
1457/// so every substrate-side consumer that resolves "what
1458/// [`SupervisorSpec::max_restarts`] value does an author-omitted
1459/// `:max-restarts` slot degrade onto?" reaches for exactly one
1460/// substrate-primitive `u32`.
1461///
1462/// The `:max-restarts` default axis has two production consumers on the
1463/// substrate side today (both prior to this lift folded onto raw `5`
1464/// literals with no compile-time link back to a shared truth): the
1465/// serde-`#[serde(default = "default_max_restarts")]` helper on
1466/// [`SupervisorSpec::max_restarts`] that every author-omitted
1467/// `:supervisor :max-restarts` slot lands in past the derive-macro's
1468/// wire-format compose, and the [`crate::manifest::Caixa::supervisor_view`]
1469/// `.max_restarts().unwrap_or(5)` fold that every downstream consumer of
1470/// the composed [`SupervisorSpec`] altitude reaches through
1471/// (`feira app graph`, the future wasm-operator's per-supervisor
1472/// restart-intensity counter, the future M4
1473/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
1474/// webhook, the caixa-operator's hierarchical reconciliation scheduler).
1475/// A pair of open-coded `5`s across two files that expressed no
1476/// compile-time link back to the shared OTP-canonical default — a
1477/// future rebrand of the default (a tightening to Elixir's
1478/// `Supervisor.max_restarts: 3`, a widening to a per-cluster overlay
1479/// the operator pins through a future
1480/// `:supervisor :max-restarts-overrides` slot the MESH-COMPOSITION
1481/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
1482/// plain `u32` count to a richer `{MaxR, MaxT}` per-child-cohort
1483/// restart-budget-partition once the INSPIRATIONS §II.2 Erlang/OTP
1484/// per-child-cohort roadmap lands) would have had to be threaded
1485/// through both open-coded copies in lockstep or the wire-format
1486/// author-omitted arm and the view-construction author-omitted arm
1487/// would silently disagree on which restart-budget an omitted
1488/// `:max-restarts` resolves to (an author writing `:supervisor
1489/// (:max-restarts ())` would round-trip through serde with the new
1490/// default while `supervisor_view` silently continued to compose the
1491/// stale `5`, or vice versa), a two-consumer split at the composition
1492/// boundary far from the source `caixa.lisp` with no field naming the
1493/// default-drift root cause. Lifting the resolution rule to a typed
1494/// `pub const` on the substrate primitive means every downstream
1495/// consumer of the per-Supervisor default-restart-budget-count surface
1496/// reaches for exactly one substrate-primitive `u32` — the resolver's
1497/// accepted value migrates as a unit on any future axis change.
1498///
1499/// The `5` value pins Learn You Some Erlang's `{intensity, 5, 60}`
1500/// worker-supervisor default (the closest canonical OTP-shape
1501/// production reference the substrate carries, matching the sibling
1502/// `60s` `Period` default the [`Default for SupervisorSpec`] impl pairs
1503/// this constant with on the paired sliding-window axis). Two orders of
1504/// magnitude below the [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` ceiling
1505/// (the upper bracket on the same axis, sibling of this lower default;
1506/// both are typed `u32` const bounds on the `:supervisor :max-restarts`
1507/// axis and now share one accessor discipline on the substrate) and
1508/// above the OTP-`supervisor` callback-module `MaxR = 1` minimum-
1509/// restart floor — the "one restart, then escalate" default is
1510/// deliberately loose enough to absorb a short burst of transient
1511/// child failures without escalating past the supervisor's parent
1512/// while remaining tight enough to trip the `MaxIntensity / Period`
1513/// ratio's escalation on a genuinely-stuck child within the sibling
1514/// `60s` sliding window.
1515///
1516/// Lifted as a typed `pub const` so the bound has exactly one source
1517/// of truth — the serde-side wire-format author-omitted arm at
1518/// [`default_max_restarts`], the [`Default for SupervisorSpec`] impl's
1519/// struct-literal default field, and the caixa-core
1520/// [`crate::manifest::Caixa::supervisor_view`] fold's author-omitted
1521/// arm all read from one place. Same shape every other typed default
1522/// in this crate carries (the sibling
1523/// [`SUPERVISOR_MAX_RESTARTS_MAX`] upper cap on the same axis, the
1524/// paired [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the
1525/// sibling `:restart-window` axis, and the peer
1526/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
1527/// per-renderer defaults on the caixa-flux / caixa-helm rendering
1528/// axes).
1529pub const SUPERVISOR_MAX_RESTARTS_DEFAULT: u32 = 5;
1530
1531/// Upper-bound ceiling on the `:supervisor :max-restarts` axis — every
1532/// validated [`SupervisorSpec::max_restarts`] past
1533/// [`SupervisorSpec::validate`] lies in `1..=SUPERVISOR_MAX_RESTARTS_MAX`.
1534///
1535/// The typed field is `u32` (the zero-floor arm
1536/// [`SupervisorError::ZeroMaxRestarts`] already brackets the bottom edge),
1537/// so a programmatic struct literal
1538/// (`SupervisorSpec { max_restarts: u32::MAX, .. }`) and the equivalent
1539/// author-surface form (`:max-restarts 4294967295` or any
1540/// `:max-restarts 100000`-shape typo landing in the slot) both round-trip
1541/// cleanly through serde — a structurally unbounded `u32` ceiling. The
1542/// runtime substrate consuming the value (Erlang/OTP's
1543/// `MaxIntensity / Period` ratio, the future wasm-operator's
1544/// per-supervisor restart-intensity counter, the M4
1545/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook)
1546/// then turned a typed `:max-restarts` policy into a no-op supervisor: the
1547/// escalation threshold is structurally so high that no realistic
1548/// restarts-per-`:restart-window` traffic shape can reach it, the
1549/// supervisor never escalates to its parent, and a bad child can loop
1550/// inside the window indefinitely with the parent supervisor structurally
1551/// never receiving the "this subtree has exceeded its restart budget"
1552/// signal the typed slot is meant to express — the canonical
1553/// "supervisor intensity declared, no escalation" footgun, exactly the
1554/// peer of the [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap
1555/// on the `:politicas :circuit-breaker :max-failures` axis (both are
1556/// "trip the next-higher protection layer after N events in a rolling
1557/// window" counters with identical degenerate-at-the-high-end shape).
1558///
1559/// The `1000` ceiling matches the sibling
1560/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] (the closest
1561/// peer — same "events-per-window trip threshold" semantics, same `u32`
1562/// type, same no-op-at-the-high-end failure mode) so the M4
1563/// `mesh.pleme.io/v1alpha1/Supervisor` / `.../Aplicacao` CR materializers
1564/// and the future wasm-operator's per-supervisor restart-intensity
1565/// counter reach for either field knowing the value is in `1..=1000`
1566/// without re-validating at the reconciler layer. The cap sits two
1567/// orders of magnitude above every documented Erlang/OTP production
1568/// playbook recommendation (Learn You Some Erlang's
1569/// `{intensity, 5, 60}` worker-supervisor default, Elixir's `Supervisor`
1570/// `max_restarts: 3` default, OTP's `supervisor` callback module
1571/// `MaxR = 1` / `MaxT = 5` "minimal-restart" default, Riak Core's
1572/// typical `MaxR ∈ 5..=100`, RabbitMQ's broker-supervisor `MaxR = 5`
1573/// default) and below the clearly-pathological "effectively no
1574/// escalation" floor (`10_000`, `100_000`, `u32::MAX`): a value the
1575/// author can plausibly want at hyperscale (a long-running supervisor
1576/// over a very-flaky pool tolerating thousands of transient restarts
1577/// before escalating), but a hard wall above which the typed policy is
1578/// structurally a no-op carried verbatim on every emitted child-restart
1579/// reconciliation contract.
1580///
1581/// Lifted as a typed `pub const` so the bound has exactly one source of
1582/// truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
1583/// materializer's admission webhook and the wasm-operator-side
1584/// per-supervisor restart-intensity reconciler read from one place. Same
1585/// shape every other typed upper bound in this crate carries
1586/// ([`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
1587/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
1588/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
1589/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
1590/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
1591/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
1592pub const SUPERVISOR_MAX_RESTARTS_MAX: u32 = 1000;
1593
1594/// Upper-bound ceiling on the `:supervisor :restart-window` axis —
1595/// every validated `Some(`[`SupervisorSpec::restart_window`]`)` past
1596/// [`SupervisorSpec::validate`] lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
1597/// (inclusive on both ends, integer-millisecond magnitudes by the
1598/// canonical-form gate immediately preceding).
1599///
1600/// The typed field is `Option<Duration>` (the zero-floor arm
1601/// [`SupervisorError::RestartWindowZero`] already rejects
1602/// `Some(Duration::ZERO)`, and the canonical-form arm
1603/// [`SupervisorError::RestartWindowNotCanonical`] already rejects
1604/// sub-millisecond residue), so a programmatic struct literal
1605/// (`SupervisorSpec { restart_window: Some(Duration::from_secs(86_400)),
1606/// .. }` — 24h) and the equivalent author-surface form
1607/// (`(:supervisor (:restart-window "24h"))` — the shared duration codec
1608/// emits `"<n>h"` for any integer-hour magnitude) both round-trip
1609/// cleanly through serde — a structurally unbounded `Duration` ceiling.
1610/// A `:restart-window` value far above the documented Erlang/OTP
1611/// `MaxIntensity / Period` production-playbook band (Learn You Some
1612/// Erlang's `{intensity, 5, 60}` worker-supervisor `Period = 60s`
1613/// default, Elixir's `Supervisor` `max_seconds: 5` default, OTP's
1614/// `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's
1615/// `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default)
1616/// degenerates the supervisor's restart-intensity counter into a
1617/// lifetime counter: the rolling failure-counting window is structurally
1618/// so long that transient restarts are never forgotten, so the
1619/// `MaxIntensity / Period` ratio degenerates from "trip the parent
1620/// supervisor when the child has exceeded its restart budget *within
1621/// the recent window*" to "trip the parent when the child has exceeded
1622/// its restart budget *over its lifetime*" — every transient restart
1623/// counts against the budget forever, the supervisor's reset semantic
1624/// never reaches the child, and the typed `:restart-window` slot
1625/// becomes a no-op rolling window carried on every emitted hierarchical
1626/// reconciliation contract. The canonical
1627/// rolling-window-degenerates-to-lifetime-counter footgun the sibling
1628/// [`crate::POLICY_BREAKER_WINDOW_MAX`] cap closes on the peer
1629/// `:politicas :circuit-breaker :window` axis with identical shape (both
1630/// are "rolling failure-counting window with a per-`Period` reset" Duration
1631/// axes whose lifetime-counter degenerate at the high end is the same
1632/// "the reset semantic never fires" CSE invariant violation).
1633///
1634/// The `1h` (3600s = `3_600_000` ms) ceiling matches the largest unit
1635/// the shared duration codec emits (`"<n>h"` for any integer-hour
1636/// magnitude) — every value in the canonical authoring form's
1637/// `<integer><unit>` grammar at or below this cap renders to a clean
1638/// canonical string — and matches the three sibling typed-`Duration`
1639/// caps already lifted to this surface
1640/// ([`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
1641/// [`crate::POLICY_BREAKER_WINDOW_MAX`]). All four typed-`Duration`
1642/// axes — per-process `:limits :wall-clock`, per-edge `:politicas
1643/// :timeout`, per-breaker `:politicas :circuit-breaker :window`, and
1644/// per-supervisor `:supervisor :restart-window` — now share a single
1645/// uniform top edge at the codec's largest emitted unit so the next
1646/// typed-slot wiring (the future wasm-operator's per-supervisor
1647/// `MaxIntensity / Period` reconciler, the M4
1648/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
1649/// webhook, the `caixa-operator`'s hierarchical reconciliation
1650/// scheduler) reaches for any of the four knowing the value is in
1651/// `1ms..=1h` without re-validating at the renderer layer. The cap sits
1652/// two orders of magnitude above every documented Erlang/OTP / Elixir /
1653/// Riak Core / RabbitMQ production-playbook recommendation band
1654/// (`5s..=300s`) and below the clearly-pathological "rolling window
1655/// degenerates to lifetime counter" floor (`24h`, `7d`, `Duration::MAX`):
1656/// a value the author can plausibly want for a very-low-traffic
1657/// long-tail failure-restart window over a hyperscale-flaky child pool,
1658/// but a hard wall above which the rolling-window contract is
1659/// structurally a lifetime-counter contract.
1660///
1661/// Lifted as a typed `pub const` so the bound has exactly one source
1662/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
1663/// materializer's admission webhook, the wasm-operator-side
1664/// per-supervisor `MaxIntensity / Period` reconciler, and the
1665/// `caixa-operator`'s hierarchical reconciliation scheduler all read
1666/// from one place. Same shape every other typed upper bound in this
1667/// crate carries ([`SUPERVISOR_MAX_RESTARTS_MAX`],
1668/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
1669/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
1670/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
1671/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
1672/// [`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
1673/// [`crate::POLICY_BREAKER_WINDOW_MAX`],
1674/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
1675/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
1676pub const SUPERVISOR_RESTART_WINDOW_MAX: Duration = Duration::from_secs(3600);
1677
1678/// Substrate-canonical Erlang/OTP-shaped `Period` sliding-window-duration
1679/// default for the `:supervisor :restart-window` axis — the canonical
1680/// `{intensity, 5, 60}` `Period` half of Learn You Some Erlang's
1681/// worker-supervisor default, extracted as a typed `pub const` so every
1682/// substrate-side consumer that resolves "what
1683/// [`SupervisorSpec::restart_window`] value does an author-omitted
1684/// `:restart-window` slot degrade onto?" reaches for exactly one
1685/// substrate-primitive [`Duration`].
1686///
1687/// The `:restart-window` default axis has one production consumer on the
1688/// substrate side today: the [`Default for SupervisorSpec`] impl's
1689/// struct-literal `restart_window` field, which prior to this lift folded
1690/// onto a raw `Duration::from_secs(60)` literal with no compile-time link
1691/// back to the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity`
1692/// half of the same `{intensity, 5, 60}` OTP-canonical default. The
1693/// [`crate::manifest::Caixa::supervisor_view`] fold deliberately does
1694/// *not* fall back to this default on the sibling `:restart-window` axis
1695/// — an author-omitted `:supervisor :restart-window` composes to
1696/// `restart_window: None` (the shared codec's soft-swallow shape),
1697/// keeping author-declared intent ("no reset — never escalate on rolling
1698/// window") distinct from the [`Default for SupervisorSpec`] "canonical
1699/// 60s Period" arm every programmatic `SupervisorSpec::default()` caller
1700/// resolves to. Prior to this lift the paired `{intensity, 5, 60}` OTP
1701/// default was split across two files with no compile-time link between
1702/// the halves: [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] pinned the
1703/// `MaxIntensity` half at the substrate primitive while the `Period`
1704/// half rode as an open-coded literal at the composition site, so a
1705/// future coherent rebrand of the paired canonical (a tightening to
1706/// Elixir's `{max_restarts: 3, max_seconds: 5}`, a widening to a
1707/// per-cluster overlay the operator pins through a future
1708/// `:supervisor :restart-window-overrides` slot the MESH-COMPOSITION
1709/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
1710/// paired constants to a per-child-cohort `{MaxR, MaxT}` restart-budget-
1711/// partition once the INSPIRATIONS §II.2 Erlang/OTP per-child-cohort
1712/// roadmap lands) would have had to migrate the `MaxIntensity` half
1713/// through the lifted constant and the `Period` half through a raw
1714/// literal in lockstep or the two halves of the same OTP-canonical
1715/// default would silently drift out of pairing. Lifting the resolution
1716/// rule to a typed `pub const` on the substrate primitive means the
1717/// paired OTP-canonical default migrates as one unit on any future
1718/// axis change.
1719///
1720/// The `60s` value pins Learn You Some Erlang's `{intensity, 5, 60}`
1721/// worker-supervisor default (the closest canonical OTP-shape
1722/// production reference the substrate carries, matching the paired
1723/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5` `MaxIntensity` half this
1724/// constant is the `Period` denominator of on the same
1725/// `MaxIntensity / Period` restart-intensity ratio). Two orders of
1726/// magnitude below the [`SUPERVISOR_RESTART_WINDOW_MAX`] `3600s`
1727/// (`1h`) ceiling (the upper bracket on the same axis, sibling of
1728/// this lower default; both are typed [`Duration`] const bounds on the
1729/// `:supervisor :restart-window` axis and now share one accessor
1730/// discipline on the substrate) and above the OTP-`supervisor`
1731/// callback-module `MaxT = 5` seconds "minimal-window" floor — the "60s
1732/// rolling window" default is deliberately loose enough to absorb a
1733/// short burst of transient child failures without escalating past the
1734/// supervisor's parent while remaining tight enough for the paired
1735/// `MaxIntensity / Period` ratio's escalation to trip on a genuinely-
1736/// stuck child within a human-scale observation window.
1737///
1738/// Lifted as a typed `pub const` so the paired OTP-canonical default has
1739/// exactly one source of truth on each half — the sibling
1740/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half and this
1741/// `Period` `60s` half now share the same substrate-primitive lift
1742/// discipline. Same shape every other typed default in this crate
1743/// carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] paired
1744/// `MaxIntensity` half on the same OTP-canonical `{intensity, 5, 60}`,
1745/// the sibling [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the same
1746/// axis, and the peer [`crate::render::DEFAULT_NAMESPACE`] /
1747/// [`crate::render::DEFAULT_LIBRARY_NAME`] per-renderer defaults on the
1748/// caixa-flux / caixa-helm rendering axes).
1749pub const SUPERVISOR_RESTART_WINDOW_DEFAULT: Duration = Duration::from_secs(60);
1750
1751/// Substrate-canonical Erlang/OTP-shaped sibling-restart-strategy default
1752/// for the `:supervisor :estrategia` axis — the canonical `one_for_one`
1753/// half of Learn You Some Erlang's `{one_for_one, intensity, 5, 60}`
1754/// worker-supervisor default, extracted as a typed `pub const` so every
1755/// substrate-side consumer that resolves "what
1756/// [`SupervisorSpec::estrategia`] variant does an author-omitted
1757/// `:estrategia` slot degrade onto?" reaches for exactly one substrate-
1758/// primitive [`RestartStrategy`].
1759///
1760/// The `:estrategia` default axis has three production consumers on the
1761/// substrate side today: the [`Default for RestartStrategy`] impl's
1762/// return arm, the [`Default for SupervisorSpec`] impl's struct-literal
1763/// `estrategia` field, and the
1764/// [`crate::manifest::Caixa::supervisor_view`] fold's
1765/// `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)` `Option<RestartStrategy>`
1766/// collapse arm — three entry points onto the same OTP-canonical
1767/// `one_for_one` value that prior to this lift folded onto a raw
1768/// `Self::OneForOne` arm at the [`Default for RestartStrategy`] impl and
1769/// implicit `RestartStrategy::default()` routes at the sibling consumers,
1770/// with no compile-time link back to the paired
1771/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` half + the paired
1772/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` half of the same
1773/// `{one_for_one, intensity, 5, 60}` OTP-canonical default. The paired
1774/// triple was split across three altitudes with no compile-time link
1775/// between the halves: the `MaxIntensity` half rode through the lifted
1776/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant (b698ec0) and the `Period`
1777/// half rode through the lifted [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
1778/// constant (f7dcd0e) while the `one_for_one` half rode as an open-coded
1779/// discriminator at the [`Default for RestartStrategy`] impl, so a future
1780/// coherent rebrand of the triple (Elixir's `{:one_for_one,
1781/// max_restarts: 3, max_seconds: 5}` — same strategy, different
1782/// intensity/period; an OTP `rest_for_one` widening once the substrate
1783/// discovers startup-order-coupled child cohorts as the more common
1784/// worker-supervisor default; a per-cluster overlay the operator pins
1785/// through a future `:estrategia-overrides` slot the MESH-COMPOSITION
1786/// §III.2 supervision-canary roadmap acknowledges) would have had to
1787/// migrate the `MaxIntensity` + `Period` halves through the lifted
1788/// constants and the `one_for_one` half through an open-coded arm in
1789/// lockstep or the three halves of the same OTP-canonical default would
1790/// silently drift out of pairing. Lifting the resolution rule to a typed
1791/// `pub const` on the substrate primitive means the paired OTP-canonical
1792/// worker-supervisor default migrates as one unit on any future axis
1793/// change.
1794///
1795/// The [`RestartStrategy::OneForOne`] value pins Learn You Some Erlang's
1796/// `{one_for_one, intensity, 5, 60}` worker-supervisor default (the
1797/// closest canonical OTP-shape production reference the substrate
1798/// carries, matching the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5`
1799/// `MaxIntensity` half and the paired [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
1800/// `60s` `Period` half). The `one_for_one` strategy — restart only the
1801/// failed child, leaving siblings untouched — is the default for tree-of-
1802/// independent-workers use cases the substrate's [`RestartStrategy`]
1803/// discriminator's own docstring already carries as the default arm; it
1804/// composes with the `{5, 60}` restart-intensity ratio to name the same
1805/// substrate-canonical "canonical worker-supervisor" shape the paired
1806/// halves close on their respective axes.
1807///
1808/// Lifted as a typed `pub const` so the paired OTP-canonical default has
1809/// exactly one source of truth on each of its three halves — the sibling
1810/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half, the
1811/// sibling [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` `60s` half, and
1812/// this `one_for_one` strategy half now share the same substrate-
1813/// primitive lift discipline. Same shape every other typed default in
1814/// this crate carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] +
1815/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] paired halves on the same OTP-
1816/// canonical `{one_for_one, intensity, 5, 60}`, the sibling
1817/// [`SUPERVISOR_MAX_RESTARTS_MAX`] + [`SUPERVISOR_RESTART_WINDOW_MAX`]
1818/// upper caps on the paired sibling axes, and the peer
1819/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
1820/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes).
1821pub const SUPERVISOR_ESTRATEGIA_DEFAULT: RestartStrategy = RestartStrategy::OneForOne;
1822
1823/// Substrate-canonical Erlang/OTP-shaped per-child restart-decision-policy
1824/// default for the `:children :restart` axis — the OTP `permanent`
1825/// worker-child default (`{ChildId, StartFunc, permanent, …}` in a
1826/// `supervisor`'s `init/1` child-spec tuple), extracted as a typed
1827/// `pub const` so every substrate-side consumer that resolves "what
1828/// [`ChildSpec::restart`] variant does an author-omitted `:children
1829/// :restart` slot degrade onto?" reaches for exactly one substrate-
1830/// primitive [`RestartPolicy`].
1831///
1832/// Completes the OTP-shape supervisor-tree default set at the substrate
1833/// primitive. The per-`:supervisor` axis already carries all three of its
1834/// halves as lifted typed constants — [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
1835/// (`one_for_one`, 95ffacc), [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
1836/// (`MaxIntensity` `5`, b698ec0), [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
1837/// (`Period` `60s`, f7dcd0e) — while the per-`:children` axis's own
1838/// OTP-canonical default rode as an open-coded `Self::Permanent` arm in
1839/// the [`Default for RestartPolicy`] impl, the last un-lifted default on
1840/// the M2 `:supervisor` slot family. The split mattered because the two
1841/// axes resolve *together* on every author-omitted supervisor: a
1842/// `(defcaixa :kind Supervisor :children ((:caixa "worker" :versao
1843/// "^0.1")))` with no `:estrategia` and no per-child `:restart` degrades
1844/// onto `{one_for_one, 5, 60}` through three lifted constants and onto
1845/// `permanent` through an open-coded enum arm, so a future coherent
1846/// rebrand of the OTP-shape default set (an Elixir-shaped
1847/// `{:one_for_one, max_restarts: 3, max_seconds: 5}` tightening, a
1848/// per-cluster overlay the operator pins through the MESH-COMPOSITION
1849/// §III.2 supervision-canary roadmap slots, an OTP-`transient` widening
1850/// once the substrate discovers clean-completion-aware children as the
1851/// more common child shape) would have had to migrate three halves
1852/// through typed constants and the fourth through a raw enum arm in
1853/// lockstep or the supervisor-level and child-level defaults would
1854/// silently drift apart.
1855///
1856/// The `:children :restart` default axis has two production consumers on
1857/// the substrate side today: the [`Default for RestartPolicy`] impl's
1858/// return arm, and the serde-side `#[serde(default)]` on
1859/// [`ChildSpec::restart`] that resolves an author-omitted `:children
1860/// :restart` slot through that same impl. Both now key off this one
1861/// substrate primitive, so the future wasm-operator's per-child post-exit
1862/// restart-decision branch, the future M4
1863/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1864/// admission webhook, and the `caixa-operator`'s hierarchical
1865/// reconciliation scheduler's per-child fan-out all reach for one typed
1866/// identifier when they resolve an omitted per-child restart posture.
1867///
1868/// The [`RestartPolicy::Permanent`] value pins Erlang/OTP's `permanent`
1869/// worker-child restart type — always restart the child regardless of how
1870/// it died, the canonical posture for long-running services that must
1871/// always be up, matching the sibling [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
1872/// `one_for_one` tree-of-independent-workers strategy this constant pairs
1873/// with under the same `{one_for_one, intensity, 5, 60}` worker-supervisor
1874/// shape. The two alternatives the closed [`RestartPolicy::ALL`] accept-set
1875/// carries ([`RestartPolicy::Transient`] — restart only on abnormal exit;
1876/// [`RestartPolicy::Temporary`] — never restart) express deliberate
1877/// one-shot / clean-completion-aware postures an author declares
1878/// explicitly, never a posture an omitted slot should silently assume.
1879pub const SUPERVISOR_CHILD_RESTART_DEFAULT: RestartPolicy = RestartPolicy::Permanent;
1880
1881/// Route the manually-authored [`Default`] impl on [`SupervisorSpec`]
1882/// through the substrate-canonical [`SupervisorSpec::otp_canonical`]
1883/// `pub const fn` constructor rather than a struct-literal cascade over
1884/// the paired [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
1885/// [`default_max_restarts`] / [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
1886/// lifted consts — one source of truth for the Erlang/OTP-canonical
1887/// `{one_for_one, 5, 60}` worker-supervisor baseline across the two
1888/// paths every downstream consumer already reaches through (the
1889/// hand-authored-until-now [`Default::default`] the
1890/// `..SupervisorSpec::default()` struct-update-syntax on every
1891/// one-axis-under-test fixture in this crate's test module rests on,
1892/// and the `pub const fn` [`SupervisorSpec::otp_canonical`] constructor
1893/// every `const`-context consumer reaches through).
1894///
1895/// Extends the [`Default`]-through-const-ctor fold discipline the
1896/// [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
1897/// (abd52c2), [`crate::aplicacao::MeshPolicy`]
1898/// [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`] (91641a4),
1899/// and [`crate::BehaviorSpec`]
1900/// [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c) folds
1901/// closed on the M2 / M3 `Option`-only "canonical unset baseline"
1902/// typed-slot spec family — extended here onto the M2 supervisor-slot
1903/// [`SupervisorSpec`] whose canonical baseline is not "everything
1904/// `None`" but the OTP-canonical `{one_for_one, 5, 60}` worker-
1905/// supervisor triple. The `empty()` peer's naming did not fit
1906/// (`SupervisorSpec` carries a discriminator-shaped `estrategia` field
1907/// and a non-zero `max_restarts`/`restart_window` pair whose canonical
1908/// shape is Erlang/OTP-descended, not the "no axis declared" bottom
1909/// the sibling `Option`-only slots fold to), so this peer is named
1910/// [`SupervisorSpec::otp_canonical`] instead — the same phrasing the
1911/// existing per-arm pin tests
1912/// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`] /
1913/// [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`] /
1914/// [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
1915/// already reach for. Pinned load-bearing by
1916/// [`tests::supervisor_spec_default_routes_through_otp_canonical_ctor`]
1917/// (byte-parity pin against [`SupervisorSpec::otp_canonical`] under
1918/// [`PartialEq`], sharpening the sibling
1919/// `supervisor_spec_default_*_routes_through_lifted_default` per-arm
1920/// pins from a per-field lift into a whole-struct one-source-of-truth
1921/// pin — the derived-until-now [`Default::default`] and the
1922/// [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
1923/// construction, not by coincidence).
1924impl Default for SupervisorSpec {
1925 #[inline]
1926 fn default() -> Self {
1927 Self::otp_canonical()
1928 }
1929}
1930
1931impl SupervisorSpec {
1932 /// `const`-context peer of the [`Default for SupervisorSpec`]
1933 /// impl (which routes through this constructor) — returns the
1934 /// Erlang/OTP-canonical `{one_for_one, 5, 60}` worker-supervisor
1935 /// baseline this crate reaches for in every fixture-builder
1936 /// `..SupervisorSpec::default()` struct-update expression and
1937 /// every downstream `SupervisorSpec::default()` seed.
1938 ///
1939 /// Each field routes through the same substrate-canonical
1940 /// [`SUPERVISOR_ESTRATEGIA_DEFAULT`] / [`default_max_restarts`] /
1941 /// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] lifted consts the
1942 /// per-arm pin tests
1943 /// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`]
1944 /// / [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`]
1945 /// / [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
1946 /// already assert, so a future coherent rebrand of the OTP-canonical
1947 /// triple (Elixir's `{max_restarts: 3, max_seconds: 5}`, a per-
1948 /// cluster overlay via a future `:restart-window-overrides` slot, a
1949 /// per-child-cohort promotion the INSPIRATIONS.md §II.2 Erlang/OTP
1950 /// absorption roadmap acknowledges) migrates through three typed
1951 /// constants in lockstep, and the paired [`Default`] impl inherits
1952 /// every future extension by construction.
1953 ///
1954 /// `pub const fn` rather than the derived-style `Default::default`
1955 /// or a `pub const SUPERVISOR_SPEC_DEFAULT: SupervisorSpec` item —
1956 /// [`Default::default`] is not `const` on stable Rust, and
1957 /// `SupervisorSpec` is non-`Copy` so a `pub const` item would force
1958 /// every consumer through a [`Clone::clone`]. The `pub const fn`
1959 /// discipline lets `const`-context callers construct the OTP-
1960 /// canonical baseline at compile time without runtime dispatch on
1961 /// the derived [`Default::default`], the same posture the sibling
1962 /// [`crate::LimitsSpec::empty`] (9739971) /
1963 /// [`crate::aplicacao::MeshPolicy::empty`] (6df969b) /
1964 /// [`crate::BehaviorSpec::empty`] (f9b18e3) `Option`-only typed-slot
1965 /// spec `pub const fn` constructors carry on the sibling
1966 /// "everything `None`" baseline axis.
1967 ///
1968 /// Fourth peer on the M2 / M3 typed-slot-spec "const-context peer
1969 /// of the derived-style [`Default`]" family — sibling of the
1970 /// [`crate::LimitsSpec::empty`] / [`crate::aplicacao::MeshPolicy::empty`]
1971 /// / [`crate::BehaviorSpec::empty`] `Option`-only "canonical unset
1972 /// baseline" trio, extended here onto the M2 supervisor-slot
1973 /// [`SupervisorSpec`] whose canonical baseline is not "everything
1974 /// `None`" but the Erlang/OTP-canonical `{one_for_one, 5, 60}`
1975 /// worker-supervisor triple. Named [`Self::otp_canonical`] rather
1976 /// than `empty()` to name the actual invariant the return value
1977 /// pins — the same phrasing already used in the per-arm pin tests
1978 /// on this file. Pinned load-bearing by
1979 /// [`tests::supervisor_spec_otp_canonical_byte_equals_default`] and
1980 /// [`tests::supervisor_spec_otp_canonical_is_usable_in_const_context`].
1981 #[must_use]
1982 pub const fn otp_canonical() -> Self {
1983 Self {
1984 estrategia: SUPERVISOR_ESTRATEGIA_DEFAULT,
1985 max_restarts: default_max_restarts(),
1986 restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
1987 children: Vec::new(),
1988 }
1989 }
1990
1991 /// Substrate-canonical per-`:supervisor` `:estrategia` OTP-shaped
1992 /// sibling-restart-strategy scalar accessor every consumer that
1993 /// dispatches on the supervisor's per-sibling restart-decision shape
1994 /// keys off — returns the author-declared `:supervisor :estrategia`
1995 /// variant verbatim as a [`RestartStrategy`], `Copy`-projected from
1996 /// the typed slot's own [`RestartStrategy`] storage.
1997 ///
1998 /// The `:supervisor :estrategia` slot carries the closed-set
1999 /// OTP-shaped sibling-restart-strategy discriminator ([`RestartStrategy::OneForOne`]
2000 /// — restart only the failed child, the Erlang/OTP `one_for_one` default;
2001 /// [`RestartStrategy::OneForAll`] — restart every child on any child
2002 /// failure, the Erlang/OTP `one_for_all` shared-state cohort default;
2003 /// [`RestartStrategy::RestForOne`] — restart the failed child and
2004 /// every child started after it, the Erlang/OTP `rest_for_one`
2005 /// startup-order default; [`RestartStrategy::SimpleOneForOne`] —
2006 /// dynamic children of the same shape, the Erlang/OTP
2007 /// `simple_one_for_one` per-session default) that every downstream
2008 /// consumer of the Supervisor's per-sibling restart-decision fan-out
2009 /// shape keys off. Validated by [`SupervisorSpec::validate`] to be
2010 /// paired coherently with the sibling `:children` axis
2011 /// (`SimpleOneForOne ↔ children.is_empty()` — the cross-slot
2012 /// partition the strategy-arm's [`SupervisorError::SimpleOneForOneWithStaticChildren`]
2013 /// / [`SupervisorError::NoChildren`] refusal cascade pins), and every
2014 /// downstream consumer that reads the strategy keys off this scalar
2015 /// (the [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
2016 /// partition-dispatch `match` arm, the non-`SimpleOneForOne`-arm
2017 /// declared-but-empty [`SupervisorError::NoChildren`] error carrier's
2018 /// `estrategia:` field, the future `feira app graph` per-Supervisor
2019 /// strategy print line, the future wasm-operator's per-supervisor
2020 /// sibling-restart-strategy branch, the future M4
2021 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-strategy
2022 /// admission-webhook resolver, the `caixa-operator`'s hierarchical
2023 /// reconciliation scheduler's per-strategy fan-out).
2024 ///
2025 /// Prior to this lift the `.estrategia` field was accessed inline at
2026 /// two production sites in `caixa-core/src/supervisor.rs` — the
2027 /// [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
2028 /// `match self.estrategia { … }` partition dispatch, and the
2029 /// non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
2030 /// carrier at `estrategia: self.estrategia` — two open-coded
2031 /// field-accesses that expressed no compile-time link back to the
2032 /// typed slot. A future extension of the `:supervisor :estrategia`
2033 /// axis to a richer author surface (a per-cluster strategy override
2034 /// the operator pins through a future `:supervisor :estrategia-overrides`
2035 /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
2036 /// acknowledges, a per-tenant strategy-alias table the M4 CR
2037 /// materializer resolves per-CR, a per-Supervisor dynamic strategy
2038 /// derivation the future adaptive-supervision engine computes from
2039 /// child-failure-history topology, a per-child-cohort strategy split
2040 /// the future `RestForCohort` extension acknowledged by the
2041 /// INSPIRATIONS.md §II.2 Erlang/OTP absorption roadmap acknowledges)
2042 /// would have had to be threaded through every open-coded copy in
2043 /// lockstep — one consumer reading the raw variant while a peer read
2044 /// the operator-resolved variant would silently split the
2045 /// [`SupervisorError::NoChildren`] diagnostic's quoted strategy from
2046 /// the actual partition-dispatch input the empty-children refusal
2047 /// arm reached under, a two-consumer split at the validator far from
2048 /// the source `caixa.lisp` with no field naming the strategy-drift
2049 /// root cause. Lifting the resolution rule to a typed method on the
2050 /// substrate primitive means every downstream consumer of the
2051 /// Supervisor's per-`:supervisor` sibling-restart-strategy surface
2052 /// reaches for exactly one typed dispatch — the resolver's accept-set
2053 /// migrates as a unit on any future axis addition.
2054 ///
2055 /// Peer of the sibling M3 mesh-slot [`crate::Placement::estrategia`]
2056 /// (921fe1b) `Copy`-return `PlacementStrategy` scalar accessor on the
2057 /// per-`:placement` distribution-strategy axis — same "one typed
2058 /// dispatch on the substrate primitive, thin projections at each
2059 /// consumer" discipline extended onto the M2 supervisor-slot
2060 /// per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
2061 /// scalar axis. The two typed axes (`Placement::estrategia` on the
2062 /// M3 Aplicacao side, `SupervisorSpec::estrategia` on the M2
2063 /// Supervisor side) now share one accessor discipline for the shared
2064 /// substrate concept "a `Copy`-projected closed-set enum-arm
2065 /// discriminator that partitions the downstream renderer's per-arm
2066 /// fan-out". First `Copy`-return accessor on the M2 supervisor-slot
2067 /// `SupervisorSpec` type — companion to the sibling per-`:children`
2068 /// [`crate::ChildSpec::nome`] (57c61d0) /
2069 /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
2070 /// scalar accessors on the sibling per-`:children` `String`-carry
2071 /// axes. Named `estrategia()` to match the storage field's name and
2072 /// the peer [`crate::Placement::estrategia`] method-name discipline
2073 /// verbatim; the accessor's identity name maps onto the canonical
2074 /// OTP-shape supervision vocabulary the [`RestartStrategy`] enum's
2075 /// docstring already carries.
2076 ///
2077 /// Declared `pub const fn` to close the M2 supervisor-slot
2078 /// `Copy`-return raw-field-getter `const`-eval-surface pass —
2079 /// sibling of the peer M2 per-`:children` [`ChildSpec::restart`]
2080 /// (converted in this commit) `Copy`-composite-enum accessor, peer
2081 /// of the sibling M2 per-`:supervisor`
2082 /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
2083 /// already lifted, and mirror of the peer M3 mesh-slot
2084 /// per-`:placement` [`crate::Placement::estrategia`] (bafa004)
2085 /// `Copy`-return `pub const fn` scalar accessor whose method-name
2086 /// discipline this accessor was authored to match. Every downstream
2087 /// substrate-side `const`-context consumer of the per-`:supervisor`
2088 /// sibling-restart-strategy scalar (a future module-scope `const
2089 /// _:() = assert!(matches!(sup.estrategia(),
2090 /// RestartStrategy::OneForOne))` invariant pin on a typed fixture,
2091 /// a future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
2092 /// admission-webhook `const fn` per-supervisor strategy-arm floor
2093 /// over a typed [`SupervisorSpec`], any future `const fn`
2094 /// supervisor-tree composer over the substrate primitive that fans
2095 /// on the sibling-restart-strategy at compile time) now reaches
2096 /// through the same typed dispatch on the substrate primitive at
2097 /// const-eval time as at runtime. A future non-`Copy`-return
2098 /// promotion of the scalar (an `Option<RestartStrategy>`-shape
2099 /// migration once the substrate grows per-cluster strategy overlays
2100 /// the [`SupervisorSpec`] docstring already anticipates, a
2101 /// per-tenant strategy-alias table the M4 CR materializer resolves
2102 /// per-CR) that would drop the `const` qualifier fails the
2103 /// fail-before-pass-after pin
2104 /// [`tests::supervisor_spec_estrategia_accessor_is_const_fn`] at
2105 /// caixa-core build time rather than surfacing as a downstream
2106 /// consumer regression.
2107 #[must_use]
2108 pub const fn estrategia(&self) -> RestartStrategy {
2109 self.estrategia
2110 }
2111
2112 /// Substrate-canonical per-`:supervisor` `:max-restarts` OTP-shaped
2113 /// `MaxIntensity` restart-budget scalar accessor every consumer that
2114 /// reads the supervisor's per-`:restart-window` restart-budget count
2115 /// keys off — returns the author-declared `:supervisor :max-restarts`
2116 /// typed `u32` verbatim, `Copy`-projected from the typed slot's own
2117 /// `u32` storage (`u32` is `Copy`, so the accessor returns by value; no
2118 /// borrow of `&self` past the call). Non-optional (the `u32` field
2119 /// carries the restart-budget count as a required axis with a
2120 /// [`default_max_restarts`]-supplied default; the zero-floor arm
2121 /// [`SupervisorError::ZeroMaxRestarts`] and the cap arm
2122 /// [`SupervisorError::MaxRestartsExceedsCap`] jointly bracket the
2123 /// accept-set to `1..=SUPERVISOR_MAX_RESTARTS_MAX`).
2124 ///
2125 /// The `:supervisor :max-restarts` slot carries the Erlang/OTP
2126 /// `MaxIntensity` restart-budget count that pairs with the sibling
2127 /// `:restart-window` `Period` to form the `MaxIntensity / Period`
2128 /// restart-intensity ratio the supervisor trips its own escalation on
2129 /// (`theory/RUNTIME-PATTERNS.md` §II.2, Learn You Some Erlang's
2130 /// `{intensity, 5, 60}` worker-supervisor default). Every downstream
2131 /// consumer of the Supervisor's per-`:supervisor` restart-budget count
2132 /// keys off this scalar (the [`SupervisorSpec::validate`] zero-floor +
2133 /// upper-cap bracket at
2134 /// `require_positive_bounded_u32(self.max_restarts(), …)`, the future
2135 /// wasm-operator's per-supervisor restart-intensity counter's
2136 /// budget-vs-count comparator, the future M4
2137 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2138 /// webhook, the `caixa-operator`'s hierarchical reconciliation
2139 /// scheduler's per-supervisor escalation-decision branch, every
2140 /// `SupervisorError::MaxRestartsExceedsCap` variant carrying the
2141 /// offending count verbatim for `feira lint` rendering).
2142 ///
2143 /// Prior to this lift the `.max_restarts` field was accessed inline at
2144 /// one production site in `caixa-core/src/supervisor.rs` — the
2145 /// [`SupervisorSpec::validate`] `require_positive_bounded_u32(self
2146 /// .max_restarts, …)` bracket-gate call — one open-coded field-access
2147 /// that expressed no compile-time link back to the typed slot. A
2148 /// future extension of the `:max-restarts` axis to a richer author
2149 /// surface (a per-cluster restart-budget override the operator pins
2150 /// through a future `:supervisor :max-restarts-overrides` slot the
2151 /// MESH-COMPOSITION §III.2 supervision-canary roadmap acknowledges,
2152 /// a per-tenant restart-budget-alias table the M4 CR materializer
2153 /// resolves per-CR, a per-supervisor dynamic restart-budget derivation
2154 /// the future adaptive-supervision engine computes from child-failure-
2155 /// history topology, a promotion of the plain `u32` count to a richer
2156 /// `{MaxR, MaxT}` tuple once Erlang/OTP's per-child-cohort restart-
2157 /// budget-partition slot comes into scope) would have had to be
2158 /// threaded through every open-coded copy in lockstep or the validate
2159 /// gate and the future M4 emit path would silently disagree on which
2160 /// restart-budget count a given supervisor resolves to — an author's
2161 /// `:max-restarts 5` would satisfy validate while the emit path
2162 /// silently read a drifted other value (a `:max-restarts 10000`
2163 /// no-op supervisor at the emit boundary would carry the author's
2164 /// declared `5` verbatim in `feira lint` output while the future
2165 /// wasm-operator's restart-intensity counter operated under the
2166 /// drifted count), a two-consumer split at the validator far from the
2167 /// source `caixa.lisp` with no field naming the restart-budget-drift
2168 /// root cause. Lifting the resolution rule to a typed method on the
2169 /// substrate primitive means every downstream consumer of the
2170 /// Supervisor's per-`:supervisor` restart-budget-count surface reaches
2171 /// for exactly one typed dispatch — the resolver's accept-set migrates
2172 /// as a unit on any future axis addition.
2173 ///
2174 /// Peer of the sibling M3 mesh-slot [`crate::CircuitBreaker::max_failures`]
2175 /// (3a74062) `Copy`-return `u32` sub-struct required-scalar accessor
2176 /// on the per-`:politicas :circuit-breaker :max-failures` Envoy-
2177 /// outlier-detection trip-threshold axis — same "one typed dispatch on
2178 /// the substrate primitive, thin projections at each consumer"
2179 /// discipline extended onto the M2 supervisor-slot per-`:supervisor`
2180 /// restart-budget-count `Copy`-`u32` scalar axis. The two typed axes
2181 /// (`CircuitBreaker::max_failures` on the M3 Aplicacao side,
2182 /// `SupervisorSpec::max_restarts` on the M2 Supervisor side) now share
2183 /// one accessor discipline for the shared substrate concept "a
2184 /// `Copy`-projected required `u32` count that trips the next-higher
2185 /// protection layer after N events in a rolling window" — both are
2186 /// counters with identical degenerate-at-the-high-end shape and share
2187 /// the paired [`crate::POLICY_BREAKER_MAX_FAILURES_MAX`] /
2188 /// [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` cap. Second `Copy`-return
2189 /// accessor on the M2 supervisor-slot `SupervisorSpec` type, sibling
2190 /// to the [`SupervisorSpec::estrategia`] (eafb619) `Copy`-composite-
2191 /// enum `RestartStrategy` accessor. Named `max_restarts()` to match
2192 /// the storage field's name verbatim and the peer
2193 /// [`crate::CircuitBreaker::max_failures`] method-name discipline; the
2194 /// accessor's identity maps onto the canonical OTP-shape supervision
2195 /// vocabulary the [`SupervisorSpec::max_restarts`] field's docstring
2196 /// already carries.
2197 #[must_use]
2198 pub const fn max_restarts(&self) -> u32 {
2199 self.max_restarts
2200 }
2201
2202 /// Substrate-canonical per-`:supervisor` `:restart-window` OTP-shaped
2203 /// `Period` sliding-window scalar accessor every consumer of the
2204 /// supervisor's `MaxIntensity / Period` restart-intensity denominator
2205 /// keys off — returns the author-declared `:supervisor :restart-window`
2206 /// typed [`Duration`] verbatim as an `Option<Duration>`, copied out of
2207 /// the typed slot's own `Option<Duration>` storage (`Duration` is
2208 /// `Copy`, so `Option<Duration>` is `Copy` and the accessor returns by
2209 /// value; no borrow of `&self` past the call). `None` when the slot is
2210 /// absent (the canonical "never reset — every restart across the
2211 /// supervisor's lifetime counts against the sibling `:max-restarts`
2212 /// budget" sentinel the field's own docstring names and the peer
2213 /// `validate_accepts_none_restart_window` pin locks in on the
2214 /// [`SupervisorSpec::validate`] entry-side).
2215 ///
2216 /// The `:supervisor :restart-window` slot carries the Erlang/OTP
2217 /// `Period` sliding-observation-interval that pairs with the sibling
2218 /// `:max-restarts` `MaxIntensity` restart-budget count to form the
2219 /// `MaxIntensity / Period` restart-intensity ratio the supervisor
2220 /// trips its own escalation on (`theory/RUNTIME-PATTERNS.md` §II.2,
2221 /// Learn You Some Erlang's `{intensity, 5, 60}` worker-supervisor
2222 /// default). The typed slot's `Option<Duration>` accept-set —
2223 /// zero-floor rejected through [`SupervisorError::RestartWindowZero`]
2224 /// (Erlang/OTP's `MaxIntensity / Period` invariant requires
2225 /// `Period > 0`; a zero period either trips on the first failure or
2226 /// never trips depending on operator interpretation, neither of which
2227 /// is the author's intent — omit the slot to express "no reset";
2228 /// carry a positive duration to express the sliding window),
2229 /// integer-millisecond canonical form enforced through
2230 /// [`SupervisorError::RestartWindowNotCanonical`] (the duration
2231 /// codec's canonical form emits `"1500ms"` not `"1.5s"` and the
2232 /// future wasm-operator's per-supervisor restart-intensity counter
2233 /// quantizes at milliseconds), upper-bounded by
2234 /// [`SUPERVISOR_RESTART_WINDOW_MAX`] (1h — the coarsest per-
2235 /// supervisor rolling window any operationally-reachable supervisor
2236 /// can honor without spanning multiple scheduler epochs the
2237 /// hierarchical-reconciliation scheduler treats as independent) —
2238 /// maps onto the future wasm-operator (M3) per-supervisor
2239 /// restart-intensity counter's rolling-observation-interval, the
2240 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2241 /// per-`spec.restartWindow` admission webhook, and the sibling
2242 /// `duration_codec`-serialized wire scalar every downstream consumer
2243 /// of the supervisor's per-`:supervisor` restart-intensity denominator
2244 /// keys off.
2245 ///
2246 /// Prior to this lift the `.restart_window` field was accessed inline
2247 /// at one production site in `caixa-core/src/supervisor.rs` — the
2248 /// [`SupervisorSpec::validate`] `if let Some(w) = self.restart_window {
2249 /// … }` zero-floor + canonical-form + upper-cap bracket arm — one
2250 /// open-coded field-access that expressed no compile-time link back to
2251 /// the typed slot. A future extension of the `:restart-window` axis to
2252 /// a richer author surface (a per-cluster restart-window override the
2253 /// operator pins through a future `:supervisor :restart-window-overrides`
2254 /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
2255 /// acknowledges, a per-tenant restart-window-alias table the M4 CR
2256 /// materializer resolves per-CR, a per-supervisor dynamic
2257 /// restart-window derivation the future adaptive-supervision engine
2258 /// computes from child-failure-history topology, a promotion of the
2259 /// plain `Option<Duration>` window to a richer `{observation, cooldown}`
2260 /// pair once Erlang/OTP's per-child-cohort observation-interval-
2261 /// partition slot comes into scope) would have had to be threaded
2262 /// through every open-coded copy in lockstep or the validate gate and
2263 /// the future M4 emit path would silently disagree on which
2264 /// restart-window a given supervisor resolves to — an author's
2265 /// `:restart-window "60s"` would satisfy validate while the emit path
2266 /// silently read a drifted other value (a `Some(Duration::from_secs(60))`
2267 /// authored slot at the emit boundary would carry the author's
2268 /// declared window verbatim in `feira lint` output while the future
2269 /// wasm-operator's restart-intensity counter operated under a
2270 /// drifted window, or vice versa: an author's `:restart-window ()`
2271 /// would carry the "never reset" sentinel through validate while the
2272 /// emit path silently substituted a default sliding window), a
2273 /// two-consumer split at the validator far from the source
2274 /// `caixa.lisp` with no field naming the restart-window-drift root
2275 /// cause. Lifting the resolution rule to a typed method on the
2276 /// substrate primitive means every downstream consumer of the
2277 /// Supervisor's per-`:supervisor` restart-intensity-denominator
2278 /// surface reaches for exactly one typed dispatch — the resolver's
2279 /// accept-set migrates as a unit on any future axis addition.
2280 ///
2281 /// Third `Copy`-return accessor on the M2 supervisor-slot
2282 /// `SupervisorSpec` type, closing the last unlifted per-`:supervisor`
2283 /// scalar-value axis (`children: Vec<ChildSpec>` carries a `Vec`
2284 /// payload rather than a `Copy`-scalar, and the per-`:children`
2285 /// [`crate::ChildSpec::nome`] (57c61d0) /
2286 /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
2287 /// scalar accessors already close the per-element `String`-carry
2288 /// axes). Sibling to the peer M2 [`crate::LimitsSpec::wall_clock`]
2289 /// (8cb717b) `Option<Duration>` accessor on the `:limits` slot's
2290 /// per-outermost-call wall-clock-deadline axis and the peer M3
2291 /// [`crate::MeshPolicy::timeout`] (7073d0f) `Option<Duration>`
2292 /// accessor on the `:politicas` slot's per-call-deadline axis — all
2293 /// three share the shared substrate concept "a `Copy`-projected
2294 /// optional `Duration` that carries a positive integer-millisecond
2295 /// canonical value with a `1ms..=<axis-specific>_MAX` accept-set and
2296 /// the paired zero-floor / non-canonical / above-cap refusal cascade"
2297 /// through the same [`crate::render::require_positive_canonical_bounded_duration`]
2298 /// bracket-helper the three axes each route through. Named
2299 /// `restart_window()` to match the storage field's name verbatim and
2300 /// the peer [`crate::LimitsSpec::wall_clock`] /
2301 /// [`crate::MeshPolicy::timeout`] method-name discipline; the
2302 /// accessor's identity maps onto the canonical OTP-shape supervision
2303 /// vocabulary the [`SupervisorSpec::restart_window`] field's docstring
2304 /// already carries.
2305 #[must_use]
2306 pub const fn restart_window(&self) -> Option<Duration> {
2307 self.restart_window
2308 }
2309
2310 /// Substrate-canonical per-`:supervisor` `:children` OTP-shaped
2311 /// static-child-list slice accessor every consumer that walks the
2312 /// supervisor's declared child set keys off — returns the author-
2313 /// declared `:supervisor :children` `Vec<ChildSpec>` verbatim as a
2314 /// `&[ChildSpec]` slice-view, borrowed from the typed slot's own
2315 /// `Vec<ChildSpec>` storage (a zero-copy slice-view over the same
2316 /// backing buffer the `Serialize`/`Deserialize` derives round-trip
2317 /// through). Non-optional: an empty slice is the load-bearing
2318 /// "author declared `:children ()`" sentinel every consumer of the
2319 /// cross-slot `SimpleOneForOne ↔ children.is_empty()` partition
2320 /// keys off (`SimpleOneForOne` requires the empty slice; the peer
2321 /// three strategies require a non-empty slice — the paired
2322 /// [`SupervisorError::SimpleOneForOneWithStaticChildren`] /
2323 /// [`SupervisorError::NoChildren`] refusal cascade pins the
2324 /// partition on both arms).
2325 ///
2326 /// The `:supervisor :children` slot carries the OTP-shaped static
2327 /// child list the supervisor materializes one ComputeUnit per
2328 /// entry from — the Erlang/OTP `supervisor:init/1`'s
2329 /// `{ok, {SupFlags, ChildSpecs}}` `ChildSpecs` list, projected
2330 /// through the tatara-lisp `:children` author surface onto a typed
2331 /// `Vec<ChildSpec>` whose per-element `(nome(),
2332 /// versao_requirement(), restart)` triple the per-child
2333 /// [`SupervisorSpec::validate`] loop already gates through the
2334 /// lifted [`ChildSpec::nome`] (57c61d0) /
2335 /// [`ChildSpec::versao_requirement`] (2c053c8) scalar accessors.
2336 /// Every downstream consumer that fans on the static child list
2337 /// keys off this slice (the [`SupervisorSpec::validate`]
2338 /// `SimpleOneForOne ↔ non-SimpleOneForOne` partition dispatch's
2339 /// `.is_empty()` probe on both arms, the [`SupervisorSpec::validate`]
2340 /// per-child DNS-1123 / semver-requirement / duplicate-detection
2341 /// fan-out loop, every future wasm-operator (M3) per-supervisor
2342 /// hierarchical-reconciliation scheduler's per-child ComputeUnit
2343 /// materialization loop, the future M4
2344 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2345 /// admission-webhook fan-out, the future `feira app graph`
2346 /// per-supervisor tree-print traversal).
2347 ///
2348 /// Prior to this lift the `.children` `Vec<ChildSpec>` was accessed
2349 /// inline at three production sites in `caixa-core/src/supervisor.rs`
2350 /// — the [`SupervisorSpec::validate`] `SimpleOneForOne`-arm
2351 /// `!self.children.is_empty()` cross-slot refusal probe, the peer
2352 /// non-`SimpleOneForOne`-arm `self.children.is_empty()`
2353 /// [`SupervisorError::NoChildren`] refusal probe, and the per-child
2354 /// validate loop's `for child in &self.children` traversal head —
2355 /// three open-coded field-accesses that expressed no compile-time
2356 /// link back to the typed slot. A future extension of the
2357 /// `:supervisor :children` axis to a richer author surface (a
2358 /// per-cluster child-set overlay the operator pins through a future
2359 /// `:supervisor :children-overrides` slot the MESH-COMPOSITION §III.2
2360 /// supervision-canary roadmap acknowledges, a per-tenant
2361 /// child-set-alias table the M4 CR materializer resolves per-CR,
2362 /// a per-supervisor dynamic-child derivation the future adaptive-
2363 /// supervision engine computes from child-failure-history topology,
2364 /// a promotion of the plain `Vec<ChildSpec>` to a richer
2365 /// `{static, dynamic}` partition once Erlang/OTP's
2366 /// `simple_one_for_one` dynamic-child slot comes into typed scope)
2367 /// would have had to be threaded through all three open-coded copies
2368 /// in lockstep or one consumer would silently disagree with the
2369 /// peers on which child-set a given supervisor resolves to — the
2370 /// `SimpleOneForOne`-arm probe reading the raw slot while the peer
2371 /// non-`SimpleOneForOne`-arm probe read an operator-resolved slot
2372 /// would silently split the partition-dispatch's two-arm coherence
2373 /// (a supervisor that satisfies neither arm's precondition, or that
2374 /// satisfies both, at the cost of the paired
2375 /// `SimpleOneForOneWithStaticChildren`/`NoChildren` refusal cascade
2376 /// silently drifting from the per-child validate loop's actual
2377 /// traversal input), a three-consumer split at the validator far
2378 /// from the source `caixa.lisp` with no field naming the
2379 /// child-set-drift root cause. Lifting the resolution rule to a
2380 /// typed method on the substrate primitive means every downstream
2381 /// consumer of the Supervisor's per-`:supervisor` static-child-list
2382 /// surface reaches for exactly one typed dispatch — the resolver's
2383 /// accept-set migrates as a unit on any future axis addition.
2384 ///
2385 /// First slice-return (`&[T]`) accessor on any M2 or M3 typed slot
2386 /// — the seed for the same "one typed dispatch on the substrate
2387 /// primitive, thin projections at each consumer" discipline the
2388 /// closed [`crate::LimitsSpec`] / [`BehaviorSpec`] /
2389 /// [`crate::UpgradeFromEntry`] scalar-accessor families each carry
2390 /// on their `Copy` / `Option<Copy>` / `Option<&str>` axes, extended
2391 /// onto the first `Vec`-carry axis on the substrate. The four peer
2392 /// `Vec`-carry axes still unlifted at the time of this seed —
2393 /// [`crate::Placement::clusters`] (`Vec<String>` per-cluster
2394 /// distribution-target list), [`crate::AplicacaoSpec::membros`]
2395 /// (`Vec<Membro>` per-Aplicacao member list),
2396 /// [`crate::AplicacaoSpec::contratos`] (`Vec<WitContract>`
2397 /// per-Aplicacao WIT-typed edge list),
2398 /// [`crate::UpgradeFromEntry::instructions`]
2399 /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
2400 /// — inherit this accessor's discipline as future compounding runs
2401 /// migrate their consumers onto the shared slice-return shape.
2402 /// Fourth (and final) accessor on the M2 supervisor-slot
2403 /// `SupervisorSpec` type, sibling to the three `Copy`-return
2404 /// [`SupervisorSpec::estrategia`] (eafb619) /
2405 /// [`SupervisorSpec::max_restarts`] (7844f4e) /
2406 /// [`SupervisorSpec::restart_window`] (7e7b32f) accessors — closes
2407 /// the last unlifted per-`:supervisor` field axis (the
2408 /// `Vec<ChildSpec>` static-child-list carrier) so every downstream
2409 /// per-`:supervisor` reader now routes through a typed dispatch on
2410 /// the substrate primitive. Named `children()` to match the storage
2411 /// field's name verbatim and the tatara-lisp author-surface term
2412 /// (`:children`) the field's own docstring already carries; the
2413 /// accessor's identity maps onto the canonical OTP-shape
2414 /// supervision vocabulary the [`SupervisorSpec::children`] field's
2415 /// docstring already reaches for ("Static children ..."). Returns
2416 /// `&[ChildSpec]` (not `&Vec<ChildSpec>`) because every downstream
2417 /// consumer of the child list treats it as a read-only sequence —
2418 /// the slice-view is the narrowest borrow that supports every
2419 /// present + roadmapped consumer (`.is_empty()`, `.iter()`,
2420 /// index, `.len()`) without leaking the backing `Vec`'s
2421 /// grow/push/reserve surface that no consumer of the typed view
2422 /// reaches for (the storage-side `Vec` remains reachable through
2423 /// the `pub children` field for the mutation-carrying
2424 /// `Caixa::supervisor_view` fold-in path in
2425 /// `manifest.rs:supervisor_view`).
2426 #[must_use]
2427 pub const fn children(&self) -> &[ChildSpec] {
2428 self.children.as_slice()
2429 }
2430
2431 /// Validate the supervisor's typed shape — strategy ↔ children
2432 /// invariants, max_restarts > 0, restart_window > 0 when set,
2433 /// per-child non-empty + duplicate-free names.
2434 ///
2435 /// Mirrors the value-shape discipline applied to every other
2436 /// typed slot:
2437 ///
2438 /// - `Some(Duration::ZERO)` on a Duration-bearing axis is the
2439 /// same "0 means the opposite of what you think" footgun
2440 /// closed for `:politicas :timeout` (Envoy interprets a zero
2441 /// timeout as `infinite`), `:politicas :circuit-breaker
2442 /// :window`, and `:limits :wall-clock`. The
2443 /// `MaxIntensity / Period` ratio in Erlang/OTP's
2444 /// `supervisor` requires `Period > 0`; a zero period either
2445 /// trips on the first failure or never trips depending on
2446 /// operator interpretation, neither of which is the
2447 /// author's intent. Omit `:restart-window` to express "no
2448 /// reset"; carry a positive duration to express the window.
2449 /// - duplicate `:children` `:caixa` names are the same
2450 /// graph-node-set / multiset distinction closed for
2451 /// `:membros` (4bb3f3d), `:placement :clusters` (c7c7799),
2452 /// and `:entrada :paths` (eb3456d). Two children with the
2453 /// same `:caixa` materialize as two ComputeUnits with the
2454 /// same name in the cluster's HelmRelease values, one
2455 /// silently overwriting the other. Erlang/OTP's
2456 /// `child_spec.id` is required-unique per supervisor;
2457 /// pleme-io enforces the same set-not-multiset shape on
2458 /// `:caixa` (the load-bearing identity in our renderer).
2459 pub fn validate(&self) -> Result<(), SupervisorError> {
2460 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition
2461 // dispatch and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
2462 // error carrier's `estrategia:` field through the lifted
2463 // [`SupervisorSpec::estrategia`] accessor rather than the raw
2464 // `self.estrategia` field access — the two production consumers
2465 // of the per-`:supervisor` sibling-restart-strategy scalar now
2466 // key off exactly one typed dispatch on the substrate primitive,
2467 // so any future rebrand on the axis (a per-cluster strategy
2468 // override the operator pins through a future `:supervisor
2469 // :estrategia-overrides` slot, a per-tenant strategy-alias table
2470 // the M4 CR materializer resolves per-CR) migrates as a single
2471 // caixa-core edit rather than a coordinated rewrite of the two
2472 // call sites — sibling of the peer M3 [`crate::Placement::estrategia`]
2473 // (921fe1b) four-consumer migration on the per-`:placement`
2474 // distribution-strategy axis.
2475 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition-
2476 // dispatch's paired `.is_empty()` cross-slot refusal probes
2477 // (the `SimpleOneForOne`-arm
2478 // [`SupervisorError::SimpleOneForOneWithStaticChildren`] refusal
2479 // and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
2480 // refusal) through the lifted [`SupervisorSpec::children`]
2481 // slice-return accessor rather than the raw `self.children`
2482 // field access — the two paired production consumers of the
2483 // per-`:supervisor` static-child-list scalar-shape now key off
2484 // exactly one typed dispatch on the substrate primitive, so any
2485 // future rebrand on the axis (a per-cluster child-set overlay
2486 // the operator pins through a future `:supervisor
2487 // :children-overrides` slot, a per-tenant child-set-alias table
2488 // the M4 CR materializer resolves per-CR) migrates as a single
2489 // caixa-core edit rather than a coordinated rewrite of the
2490 // paired arms — first slice-return migration on any typed slot,
2491 // seed for the peer per-`:placement :clusters`,
2492 // per-`:membros`, per-`:contratos`, and per-`:upgrade-from
2493 // :instructions` `Vec`-carry axes.
2494 match self.estrategia() {
2495 RestartStrategy::SimpleOneForOne => {
2496 // SimpleOneForOne: children added at runtime. Static
2497 // list must be empty (one shape declared elsewhere).
2498 if !self.children().is_empty() {
2499 return Err(SupervisorError::SimpleOneForOneWithStaticChildren);
2500 }
2501 }
2502 _ => {
2503 if self.children().is_empty() {
2504 return Err(SupervisorError::no_children(self.estrategia()));
2505 }
2506 }
2507 }
2508 // Zero-floor + upper-cap bracket on the typed `:max-restarts`
2509 // axis. See [`crate::render::require_positive_bounded_u32`] for
2510 // the ordering discipline (zero-floor arm strictly precedes cap
2511 // arm so `0` surfaces the self-locating `ZeroMaxRestarts`
2512 // diagnostic with its counter-axis remediation directly named,
2513 // not the misleading `0 > SUPERVISOR_MAX_RESTARTS_MAX == false`
2514 // cap-arm miss). Until this bracket landed the top edge ran all
2515 // the way to `u32::MAX` and a struct-literal
2516 // `SupervisorSpec { max_restarts: 100_000, .. }` (or the
2517 // equivalent author-surface `:max-restarts 100000` /
2518 // `:max-restarts 4294967295` typo landing in the slot) silently
2519 // passed validate. The runtime substrate consuming the value
2520 // (Erlang/OTP's `MaxIntensity / Period` ratio, the future
2521 // wasm-operator's per-supervisor restart-intensity counter, the
2522 // M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2523 // admission webhook) then turned a typed `:max-restarts`
2524 // policy into a no-op supervisor: the escalation threshold is
2525 // structurally so high that no realistic
2526 // restarts-per-`:restart-window` traffic shape can reach it,
2527 // the supervisor never escalates to its parent, and a bad
2528 // child can loop inside the window indefinitely with the
2529 // parent supervisor structurally never receiving the "this
2530 // subtree has exceeded its restart budget" signal the typed
2531 // slot is meant to express. The bracket set is
2532 // `1..=SUPERVISOR_MAX_RESTARTS_MAX`, peer with the
2533 // [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap on
2534 // the sibling `:politicas :circuit-breaker :max-failures` axis:
2535 // both are "trip the next-higher protection layer after N
2536 // events in a rolling window" counters with identical
2537 // degenerate-at-the-high-end shape and now share one canonical
2538 // bracket helper. The bracket precedes the sibling
2539 // `:restart-window` zero-floor / canonical-millisecond arms so
2540 // an over-cap `max_restarts` paired with a structurally invalid
2541 // window surfaces the bracket diagnostic first, mirroring the
2542 // `PolicyBreakerMaxFailuresExceedsCap` / window-axis cross-arm
2543 // ordering on the peer `:politicas :circuit-breaker` slot.
2544 // Route the [`SupervisorSpec::validate`] `:max-restarts` zero-floor +
2545 // upper-cap bracket-gate through the lifted [`SupervisorSpec::max_restarts`]
2546 // accessor rather than the raw `self.max_restarts` field access —
2547 // the one production consumer of the per-`:supervisor`
2548 // restart-budget-count scalar now keys off exactly one typed
2549 // dispatch on the substrate primitive, so any future rebrand on
2550 // the axis (a per-cluster restart-budget override the operator
2551 // pins through a future `:supervisor :max-restarts-overrides`
2552 // slot, a per-tenant restart-budget-alias table the M4 CR
2553 // materializer resolves per-CR) migrates as a single caixa-core
2554 // edit rather than a coordinated rewrite — sibling of the peer M3
2555 // [`crate::CircuitBreaker::max_failures`] (3a74062) migration on
2556 // the per-`:politicas :circuit-breaker :max-failures` axis.
2557 crate::render::require_positive_bounded_u32(
2558 self.max_restarts(),
2559 SUPERVISOR_MAX_RESTARTS_MAX,
2560 || SupervisorError::ZeroMaxRestarts,
2561 SupervisorError::max_restarts_exceeds_cap,
2562 )?;
2563 // Route the [`SupervisorSpec::validate`] `:restart-window`
2564 // zero-floor + integer-millisecond canonical-form + upper-cap
2565 // bracket-gate through the lifted [`SupervisorSpec::restart_window`]
2566 // accessor rather than the raw `self.restart_window` field access —
2567 // the one production consumer of the per-`:supervisor`
2568 // restart-intensity-denominator scalar now keys off exactly one
2569 // typed dispatch on the substrate primitive, so any future rebrand
2570 // on the axis (a per-cluster restart-window override the operator
2571 // pins through a future `:supervisor :restart-window-overrides`
2572 // slot, a per-tenant restart-window-alias table the M4 CR
2573 // materializer resolves per-CR) migrates as a single caixa-core
2574 // edit rather than a coordinated rewrite — sibling of the peer M2
2575 // [`crate::LimitsSpec::wall_clock`] (8cb717b) validate-arm-route
2576 // on the per-`:limits :wall-clock` axis and the peer M3
2577 // [`crate::MeshPolicy::timeout`] (7073d0f) accessor-route on the
2578 // per-`:politicas :timeout` axis.
2579 if let Some(w) = self.restart_window() {
2580 // Zero-floor + integer-millisecond canonical-form +
2581 // upper-cap bracket on the typed `:restart-window` axis.
2582 // See
2583 // [`crate::render::require_positive_canonical_bounded_duration`]
2584 // for the full three-arm ordering discipline (zero-floor
2585 // strictly precedes canonical-form so `Duration::ZERO`
2586 // surfaces the self-locating `RestartWindowZero`
2587 // diagnostic; canonical-form strictly precedes the cap arm
2588 // so a sub-millisecond above-cap value surfaces the more
2589 // fundamental round-trip-shape diagnostic first) and the
2590 // three peer typed-`Duration` sites that share this
2591 // canonical bracket ([`crate::MeshPolicy::timeout`],
2592 // [`crate::CircuitBreaker::window`],
2593 // [`crate::LimitsSpec::wall_clock`]). Every validated
2594 // value lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
2595 // (1ms..=1h), integer-millisecond granularity.
2596 crate::render::require_positive_canonical_bounded_duration(
2597 w,
2598 SUPERVISOR_RESTART_WINDOW_MAX,
2599 || SupervisorError::RestartWindowZero,
2600 SupervisorError::restart_window_not_canonical,
2601 SupervisorError::restart_window_exceeds_cap,
2602 )?;
2603 }
2604 // Route the per-child DNS-1123 / semver-requirement / duplicate-
2605 // detection fan-out loop through the lifted named per-slot gate
2606 // [`SupervisorSpec::validate_children`] rather than an inline
2607 // three-per-child cascade — every future consumer that wants to
2608 // re-check only the `:children` slot's per-entry axes (the M4
2609 // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2610 // admission webhook re-validating one added/renamed child, the
2611 // future wasm-operator's per-child dynamic-add re-validator on
2612 // the `SimpleOneForOne` runtime-add path once dynamic-children
2613 // graduate to a typed slot, a future partial re-validator on a
2614 // per-`:children`-entry patch) reaches every per-entry axis
2615 // through one dispatch rather than re-inlining the three-arm
2616 // cascade in lockstep with `validate` or paying the peer
2617 // `:estrategia`/`:max-restarts`/`:restart-window` gates to
2618 // reach one entry check. Sibling of the peer M3 mesh-slot
2619 // per-slot gate family (`validate_membros` — the exact peer on
2620 // the M3 side, [`crate::AplicacaoSpec::validate_membros`];
2621 // `validate_contratos` — 906a5c6; `validate_entrada` — 20cd523;
2622 // `validate_placement`; `validate_politicas` routing through
2623 // `MeshPolicy::validate` — f03a154) — the M2 supervisor-slot
2624 // per-slot gate discipline now spans both the M3 mesh-slot
2625 // family and the M2 `:children` per-child-cascade axis on one
2626 // shape: one named per-slot gate per typed per-entry loop.
2627 self.validate_children()?;
2628 Ok(())
2629 }
2630
2631 /// Named per-slot gate on the M2 `:supervisor :children` per-entry
2632 /// axis — folds the per-child DNS-1123 name gate, semver-requirement
2633 /// gate, and duplicate-`:caixa` dedup arm into one call every
2634 /// consumer that wants to re-validate one `:children` entry (or the
2635 /// whole list) against the same accept-set [`SupervisorSpec::validate`]
2636 /// admits reaches through.
2637 ///
2638 /// Peer of the M3 mesh-slot [`crate::AplicacaoSpec::validate_membros`]
2639 /// per-slot gate on the analogous per-entry axis (`:membros`) — same
2640 /// three-per-entry shape (DNS-1123 name + semver-requirement +
2641 /// duplicate-`:caixa` dedup), lifted to one named substrate
2642 /// primitive per slot. The M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
2643 /// materializer's admission webhook re-checking one added or renamed
2644 /// child, the future wasm-operator's per-child dynamic-add
2645 /// re-validator on the `SimpleOneForOne` runtime-add path once
2646 /// dynamic-children graduate to a typed slot, a future partial
2647 /// re-validator on a per-`:children`-entry patch — each reaches the
2648 /// three per-entry axes through this one dispatch rather than
2649 /// re-inlining the three-arm cascade in lockstep with `validate`
2650 /// (the duplication the PRIME DIRECTIVE names as a bug) or paying
2651 /// the peer `:estrategia`/`:max-restarts`/`:restart-window` gates to
2652 /// reach one entry check.
2653 ///
2654 /// Self-contained on `&self` — resolves its own dedup `HashSet`
2655 /// through [`SupervisorSpec::children`] rather than borrowing one
2656 /// threaded down from `validate`, the same posture the peer M3
2657 /// mesh-slot per-slot gates ([`crate::AplicacaoSpec::validate_membros`],
2658 /// [`crate::AplicacaoSpec::validate_contratos`],
2659 /// [`crate::AplicacaoSpec::validate_entrada`],
2660 /// [`crate::AplicacaoSpec::validate_placement`]) each carry, so a
2661 /// consumer that reaches this gate directly (without first calling
2662 /// `validate`) still runs the full per-child cascade — pinned by
2663 /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
2664 /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
2665 /// + `validate_children_is_self_contained_on_children_slot`.
2666 ///
2667 /// The three per-entry arms run in the same canonical order the
2668 /// pre-lift inline cascade encoded (DNS-1123 → semver → dedup), so
2669 /// the diagnostic every author-declared per-`:children` entry surfaces
2670 /// through `validate` is byte-equal to the diagnostic this gate
2671 /// surfaces when called directly — the equivalence-pin pair
2672 /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
2673 /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
2674 /// asserts the two altitudes discriminate the same set on every
2675 /// per-entry-covered input.
2676 pub fn validate_children(&self) -> Result<(), SupervisorError> {
2677 let mut seen = std::collections::HashSet::new();
2678 for child in self.children() {
2679 // Every emitted cluster artifact's `metadata.name` for a
2680 // supervised child derives from this `:children :caixa` value
2681 // verbatim — the rendered `wasm.pleme.io/v1alpha1/ComputeUnit
2682 // .metadata.name` per child, the [`crate::LABEL_PROGRAM`]
2683 // label value on every child's pod identity, and the per-
2684 // child K8s [`Service`][svc] `metadata.name` the future
2685 // wasm-operator (M3) provisions for inter-child supervision
2686 // tree wiring. Each apiserver-side schema on each landing
2687 // site enforces the DNS-1123 label rule on admission; a
2688 // structurally invalid child name (`"Worker"`, `"my_worker"`,
2689 // `"team.worker"`, `"-worker"`, `"worker-"`, the >63-byte
2690 // UUID-shaped mistaken-identity slug) silently passes the
2691 // prior empty-/duplicate-only gate and the failure surfaces
2692 // at `kubectl apply` time as a `metadata.name: Invalid value`
2693 // rejection, far from the source caixa.lisp, with no field
2694 // naming the offending `:children` entry. Lifting the gate
2695 // to caixa-build time mirrors the `:membros :caixa` value-
2696 // shape trajectory (3f9d7a0) and the `:placement :clusters`
2697 // trajectory (6cbb900) onto the third DNS-1123-label-shaped
2698 // identifier axis — the supervisor tree's child names —
2699 // through the lifted
2700 // [`crate::render::require_valid_dns_1123_label`] gate the
2701 // seven peer name axes (`:membros :caixa`, `:placement
2702 // :clusters`, `:placement :affinity`, `:contratos :de`/`:para`,
2703 // `:entrada :para`, `:nome`, `:upgrade-from :module`) each
2704 // route through, so drift between the eight axes' accepted
2705 // DNS-1123-label sets is structurally impossible.
2706 //
2707 // [svc]: https://kubernetes.io/docs/concepts/services-networking/service/
2708 crate::render::require_valid_dns_1123_label(
2709 child.nome(),
2710 || SupervisorError::EmptyChildName,
2711 |reason| SupervisorError::child_caixa_invalid(child.nome(), reason),
2712 )?;
2713 // The author surface for `:children :versao` is the same
2714 // Cargo-shaped semver requirement string `:deps :versao` and
2715 // `:membros :versao` carry — and the lacre pipeline resolves
2716 // all three axes through the same
2717 // [`crate::version::parse_requirement`] entry-point. The
2718 // shared [`crate::render::require_valid_versao_requirement`]
2719 // helper brackets the empty-first + parse cascade both peer
2720 // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
2721 // [`crate::AplicacaoSpec::validate_membros`] on `:membros
2722 // :versao`) route through, so drift between the three axes'
2723 // accepted requirement sets is structurally impossible and
2724 // the parse-side no-op the empty-first arm closes (semver's
2725 // empty parse yields an implicit `*`) lives in exactly one
2726 // predicate. Every `ChildSpec::versao` past validate is
2727 // round-trippable through [`crate::parse_requirement`]
2728 // without re-checking at the resolver layer, and the three
2729 // `:versao` typed surfaces (`:deps`, `:membros`, `:children`)
2730 // are now structurally equivalent by construction.
2731 crate::render::require_valid_versao_requirement(
2732 child.versao_requirement(),
2733 || SupervisorError::empty_child_version(child.nome()),
2734 |reason| {
2735 SupervisorError::child_versao_invalid(
2736 child.nome(),
2737 child.versao_requirement(),
2738 reason,
2739 )
2740 },
2741 )?;
2742 crate::render::insert_first_seen(&mut seen, child.nome(), || {
2743 SupervisorError::duplicate_child_caixa(child.nome())
2744 })?;
2745 }
2746 Ok(())
2747 }
2748}
2749
2750/// Cross-slot coherence gate on the supervision tree: no
2751/// `:children :caixa` entry may name the supervisor's own `:nome`.
2752///
2753/// A supervisor that lists itself as a child is a degenerate self-parent
2754/// — the supervision tree is a DAG rooted at the supervisor (OTP child
2755/// specs reference *distinct* child processes; a supervisor is never its
2756/// own child), and the wasm-operator's hierarchical reconciliation would
2757/// otherwise be handed a node that is its own parent: a one-node cycle it
2758/// either rejects far from the source `caixa.lisp` or recurses on. Because
2759/// every `:nome` is a globally-unique substrate identity (DNS-1123 label +
2760/// lacre closure root), a child whose `:caixa` equals the supervisor's
2761/// `:nome` *is* the supervisor itself, not a coincidentally-named peer.
2762///
2763/// Lives outside [`SupervisorSpec::validate`] because the typed view
2764/// carries the children but not the parent `:nome`; mirrors the
2765/// cross-slot precedence gate `validate_upgrade_from_against_versao`
2766/// (which likewise reads one slot against another at the
2767/// [`crate::layout`] wire-up site) and the mesh self-edge gate
2768/// `AplicacaoSpec`'s `ContratoSelfLoop` — the same "an edge from a graph
2769/// node to itself is structurally not a tree/mesh edge" discipline, here
2770/// on the supervision-tree axis.
2771pub fn validate_no_self_supervision(
2772 children: &[ChildSpec],
2773 parent_nome: &str,
2774) -> Result<(), SupervisorError> {
2775 for child in children {
2776 if child.nome() == parent_nome {
2777 return Err(SupervisorError::child_supervises_self(parent_nome));
2778 }
2779 }
2780 Ok(())
2781}
2782
2783#[derive(Debug, Error, PartialEq, Eq)]
2784pub enum SupervisorError {
2785 #[error("supervisor :estrategia {estrategia:?} requires at least one :children entry")]
2786 NoChildren { estrategia: RestartStrategy },
2787 #[error(
2788 "SimpleOneForOne supervisors must declare zero static children (children spawn dynamically)"
2789 )]
2790 SimpleOneForOneWithStaticChildren,
2791 #[error(":max-restarts must be > 0")]
2792 ZeroMaxRestarts,
2793 #[error(
2794 ":supervisor :max-restarts ({max_restarts}) exceeds the supervisor-policy ceiling \
2795 (SUPERVISOR_MAX_RESTARTS_MAX = 1000) — a value above this cap turns the typed \
2796 restart-intensity policy into a no-op supervisor: the escalation threshold is \
2797 structurally so high that no realistic restarts-per-:restart-window traffic shape \
2798 can reach it, so the supervisor never escalates to its parent and a bad child can \
2799 loop inside the window indefinitely. Every typed-slot consumer (Erlang/OTP's \
2800 MaxIntensity/Period ratio, the future wasm-operator's per-supervisor \
2801 restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
2802 materializer's admission webhook) emits a `:max-restarts` declaration that is \
2803 structurally never reached. Pin a value in 1..=1000 (Erlang/OTP / Elixir / Riak \
2804 Core / RabbitMQ production playbooks recommend 3..=100; the OTP `supervisor` \
2805 callback module's `MaxR = 1` minimal-restart default sits at the bottom of the \
2806 band) or restructure the supervision tree (split the flaky child into its own \
2807 sub-supervisor with a tighter budget) if you need a higher restart tolerance."
2808 )]
2809 MaxRestartsExceedsCap { max_restarts: u32 },
2810 #[error(
2811 ":restart-window must be > 0 when set — Erlang/OTP's MaxIntensity/Period \
2812 requires Period > 0; a zero window either trips on the first failure or \
2813 never trips depending on operator interpretation. Omit :restart-window to \
2814 express `never reset`; carry a positive duration to express the window."
2815 )]
2816 RestartWindowZero,
2817 #[error(
2818 ":supervisor :restart-window ({window:?}) carries a sub-millisecond residue the shared `duration_codec` cannot round-trip — \
2819 the codec truncates to `as_millis()` before picking the canonical unit, so a value with `subsec_nanos() % 1_000_000 != 0` either \
2820 truncates on first serialize (e.g. `Duration::from_micros(1500)` → \"1ms\" → `Duration::from_millis(1)` ≠ original) or renders \
2821 as \"0s\" the `RestartWindowZero` arm then rejects on re-validate. Pin an integer-millisecond magnitude in the canonical authoring form \
2822 (`<integer><unit>` for unit ∈ {{ms, s, m, h}}, e.g. `\"500ms\"`, `\"30s\"`, `\"2m\"`, `\"1h\"`) or omit the field for `never reset`"
2823 )]
2824 RestartWindowNotCanonical { window: Duration },
2825 #[error(
2826 ":supervisor :restart-window ({window:?}) exceeds the supervisor-policy ceiling \
2827 (SUPERVISOR_RESTART_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
2828 per-supervisor rolling-window restart-intensity counter into a lifetime counter: the \
2829 failure-counting window is structurally so long that transient restarts are never \
2830 forgotten, the MaxIntensity/Period ratio degenerates from `trip the parent supervisor \
2831 when the child has exceeded its restart budget within the recent window` to `trip the \
2832 parent when the child has exceeded its restart budget over its lifetime`, and the \
2833 supervisor's reset semantic never reaches the child — every typed-slot consumer \
2834 (Erlang/OTP's MaxIntensity/Period reconciler, the future wasm-operator's \
2835 per-supervisor restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
2836 materializer's admission webhook, the caixa-operator's hierarchical reconciliation \
2837 scheduler) emits a `:restart-window` declaration that is structurally a no-op rolling \
2838 window. Pin a value in 1ms..=1h (Learn You Some Erlang's `{{intensity, 5, 60}}` \
2839 worker-supervisor `Period = 60s` default, Elixir's `Supervisor` `max_seconds: 5` \
2840 default, OTP's `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's \
2841 `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default — every Erlang/OTP \
2842 / Elixir production playbook sits in the 5s..=300s band; the longest documented \
2843 per-supervisor restart-window any pleme-io substrate playbook recommends maxes at \
2844 ~30m) or omit :restart-window to express `never reset` (the supervisor's restart \
2845 budget then becomes a strict lifetime counter by design, not a degenerate one — the \
2846 author surfaces the lifetime-counter semantic explicitly at the slot, rather than \
2847 hiding it behind a rolling-window declaration the cap arm rejects)"
2848 )]
2849 RestartWindowExceedsCap { window: Duration },
2850 #[error("child entry has empty :caixa name")]
2851 EmptyChildName,
2852 #[error(
2853 "child :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
2854 (the K8s apiserver enforces this rule on every `metadata.name` / Service \
2855 name / label value the child name lands in — the per-child \
2856 `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name`, the `LABEL_PROGRAM` \
2857 label value, and the future wasm-operator per-child Service `metadata.name` \
2858 — each apiserver-side schema rejects names that don't match; use a \
2859 lowercase alphanumeric + hyphen identifier like `\"worker\"` or `\"cache-v2\"`)"
2860 )]
2861 ChildCaixaInvalid { caixa: String, reason: String },
2862 #[error("child {caixa:?} has empty :versao constraint")]
2863 EmptyChildVersion { caixa: String },
2864 #[error(
2865 "child {caixa:?} :versao {versao:?} is not a valid semver requirement: \
2866 {reason} (use Cargo-shaped forms like `\"^0.1\"`, `\"~0.1.2\"`, \
2867 `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` and \
2868 `:membros :versao` carry; the lacre pipeline resolves all three \
2869 through the same parser)"
2870 )]
2871 ChildVersaoInvalid {
2872 caixa: String,
2873 versao: String,
2874 reason: String,
2875 },
2876 #[error(
2877 "child {caixa:?} appears more than once (Erlang/OTP requires unique \
2878 child_spec.id per supervisor; duplicate children materialize as duplicate \
2879 ComputeUnits in the rendered chart, one silently overwriting the other)"
2880 )]
2881 DuplicateChildCaixa { caixa: String },
2882 #[error(
2883 "supervisor {caixa:?} lists itself as a :children entry — a supervisor is \
2884 never its own child (the supervision tree is a DAG rooted at the supervisor; \
2885 OTP child specs reference distinct child processes). Since every :nome is a \
2886 globally-unique substrate identity, a child naming the supervisor's own :nome \
2887 is a one-node reconciliation cycle, not a coincidentally-named peer; drop the \
2888 self-referential :children entry or rename it to the actual child caixa."
2889 )]
2890 ChildSupervisesSelf { caixa: String },
2891}
2892
2893// Fold the three `SupervisorError::<Variant> { caixa: <&str>.to_string() }`
2894// caixa-only struct-variant wire-up sites at [`SupervisorSpec::validate_children`]
2895// and [`validate_no_self_supervision`] onto one substrate primitive per
2896// typed variant — the sibling on `SupervisorError` of the four uniform-shape
2897// `LayoutError`-envelope constructor families the peer
2898// [`crate::layout::layout_violation_ctors!`] macro closed (131ca0d, 16
2899// variants on `{ caixa, issue }`), the [`crate::layout::layout_slot_kind_ctors!`]
2900// macro closed (0419438, 4 variants on `{ caixa, kind, slots }`), the
2901// [`crate::LayoutError::missing_entry`] one-variant ctor closed (1b09f9d,
2902// on `{ kind, path }`), and the [`crate::layout::layout_nome_only_ctors!`]
2903// macro closed (3fe3dd7, 6 variants on `<Variant>(String)`), plus the
2904// [`crate::AplicacaoError::entrada_host_invalid`] one-variant ctor
2905// (17dd504, `{ host, reason }`), the [`crate::aplicacao::contrato_target_ctors!`]
2906// macro (14b81d5, 2 variants on `{ de, para, wit, expected }`), and the
2907// [`crate::aplicacao::contrato_empty_pair_ctors!`] macro (8580068, 4
2908// variants on `{ de, para }`) already at that discipline on the peer
2909// `AplicacaoError` envelopes.
2910//
2911// Each of the three wire-up sites on this shape (`EmptyChildVersion` at
2912// the per-`:children` semver-requirement empty-first arm, `DuplicateChildCaixa`
2913// at the per-`:children` dedup arm, `ChildSupervisesSelf` at the cross-slot
2914// self-supervision arm) opened the identical
2915// `SupervisorError::<Variant> { caixa: <&str>.to_string() }` struct-literal —
2916// the exact "same block re-inlined at every consumer" shape the PRIME
2917// DIRECTIVE names as a bug, on the same altitude the peer `LayoutError` /
2918// `AplicacaoError` families each closed on their sibling envelopes. The
2919// three variants share one `{ caixa: String }` shape, so the fold routes
2920// each wire-up site through one dispatch per typed variant.
2921//
2922// The macro below generates one static constructor per variant of shape
2923// `fn <slot>(caixa: &str) -> SupervisorError`, so every wire-up site
2924// collapses onto one dispatch:
2925// `SupervisorError::<slot>(<&str>)`, byte-equal to the pre-lift
2926// struct-literal on the same `&str` fixture. The uniform one-field
2927// construction (`caixa: caixa.to_string()`) is spelled once — inside the
2928// macro — rather than at every wire-up site. Every constructor is
2929// `#[must_use]` so a caller who mistakenly discards the constructed error
2930// trips a compile warning at the wire-up site.
2931//
2932// Every future consumer that wants to construct one of these three
2933// variants outside `SupervisorSpec::validate_children` /
2934// `validate_no_self_supervision` — a deferred
2935// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2936// webhook re-checking one added/renamed child, a future
2937// `feira validate --supervisor` per-caixa admission verb, a per-child
2938// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path
2939// once dynamic-children graduate to a typed slot, a per-Supervisor
2940// overlay resolver rejecting a duplicate/self-supervising child against
2941// a cluster-local snapshot — now reaches each variant through one call
2942// rather than re-inlining the three-line struct-literal in lockstep
2943// with the three in-crate wire-up sites.
2944macro_rules! supervisor_caixa_only_ctors {
2945 ($($ctor:ident => $variant:ident),* $(,)?) => {
2946 impl SupervisorError {
2947 $(
2948 #[doc = concat!(
2949 "Construct a [`SupervisorError::",
2950 stringify!($variant),
2951 "`] naming the offending `:children :caixa` (or ",
2952 "supervisor `:nome`, on the self-supervision arm). ",
2953 "Folds the uniform `Self::",
2954 stringify!($variant),
2955 " { caixa: caixa.to_string() }` one-field ",
2956 "struct-literal onto one substrate primitive so ",
2957 "every [`SupervisorSpec::validate_children`] / ",
2958 "[`validate_no_self_supervision`] wire-up on this ",
2959 "variant reads through one dispatch rather than the ",
2960 "pre-lift open-coded struct-literal block."
2961 )]
2962 #[must_use]
2963 pub fn $ctor(caixa: &str) -> Self {
2964 Self::$variant { caixa: caixa.to_string() }
2965 }
2966 )*
2967 }
2968 };
2969}
2970
2971supervisor_caixa_only_ctors! {
2972 empty_child_version => EmptyChildVersion,
2973 duplicate_child_caixa => DuplicateChildCaixa,
2974 child_supervises_self => ChildSupervisesSelf,
2975}
2976
2977// Fold the two `SupervisorError::{ChildCaixaInvalid, ChildVersaoInvalid}`
2978// struct-variant wire-up sites at [`SupervisorSpec::validate_children`] onto
2979// one substrate primitive per typed variant — the M2 supervisor-side siblings
2980// of the peer [`crate::AplicacaoError::membro_caixa_invalid`] two-slot ctor
2981// already lifted through the sibling
2982// [`crate::aplicacao::aplicacao_field_reason_ctors!`] macro (981060b) on the
2983// peer `AplicacaoError { caixa: String, reason: String }` envelope. The
2984// `ChildCaixaInvalid` variant carries the same `{ <name>: String, reason:
2985// String }` two-slot shape the peer seven-variant
2986// [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold closed on the
2987// `AplicacaoError` envelope (`MembroCaixaInvalid`, `EntradaParaInvalid`,
2988// `EntradaHostInvalid`, `EntradaPathInvalid`, `PlacementClusterInvalid`,
2989// `PlacementAffinityInvalid`, `ShardKeyInvalid`); the `ChildVersaoInvalid`
2990// variant carries the `{ caixa: String, versao: String, reason: String }`
2991// three-slot shape the sibling `AplicacaoError::MembroVersaoInvalid` axis
2992// carries on the same `:versao` value-shape.
2993//
2994// Each of the two wire-up sites opened the same closure-shaped
2995// `|reason| SupervisorError::<Variant> { caixa: child.nome().to_string(),
2996// [versao: child.versao_requirement().to_string(),] reason }` block inside
2997// the paired [`crate::render::require_valid_dns_1123_label`] and
2998// [`crate::render::require_valid_versao_requirement`] callbacks — the exact
2999// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE names
3000// as a bug, on the same altitude the peer `AplicacaoError` /
3001// `SupervisorError` / `LayoutError` / `DepError` / `LimitsError` ctor
3002// families already closed on their sibling envelopes.
3003//
3004// The two `#[must_use]` inherent constructors below fold each wire-up onto
3005// one dispatch: `SupervisorError::child_caixa_invalid(<name>, <reason>)`
3006// and `SupervisorError::child_versao_invalid(<name>, <versao>, <reason>)`,
3007// byte-equal to the pre-lift struct-literal on the same scalar fixtures.
3008// The uniform per-field `.to_string()` / `.into()` construction is spelled
3009// once — inside each ctor body — rather than at every wire-up site. The
3010// `reason: impl Into<String>` bound accepts both `&str` literals and
3011// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
3012// diagnostic shape at the lift, matching the peer
3013// [`aplicacao_field_reason_ctors!`] and
3014// [`crate::aplicacao::contrato_pair_value_reason_ctors!`] bounds on the
3015// sibling envelopes.
3016//
3017// Every future consumer that wants to construct one of these two variants
3018// outside `SupervisorSpec::validate_children` — a deferred
3019// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook
3020// re-checking one added/renamed child's `:caixa` or `:versao`, a future
3021// `feira validate --supervisor` per-caixa admission verb, a per-child
3022// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path once
3023// dynamic-children graduate to a typed slot, a per-Supervisor overlay
3024// resolver rejecting a shape-invalid child `:caixa`/`:versao` against a
3025// cluster-local snapshot — now reaches each variant through one call rather
3026// than re-inlining the per-shape struct-literal block in lockstep with the
3027// two in-crate wire-up sites.
3028impl SupervisorError {
3029 /// Construct a [`SupervisorError::ChildCaixaInvalid`] naming the
3030 /// offending `:children :caixa` value under the given `reason`. Folds
3031 /// the uniform `Self::ChildCaixaInvalid { caixa: caixa.to_string(),
3032 /// reason: reason.into() }` two-slot struct-literal onto one substrate
3033 /// primitive so every wire-up on this variant reads through one
3034 /// dispatch, matching the peer
3035 /// [`crate::AplicacaoError::membro_caixa_invalid`] ctor's shape on the
3036 /// sibling `AplicacaoError { caixa: String, reason: String }`
3037 /// envelope. `reason` accepts both `&str` literals and `format!(…)`
3038 /// outputs through the `impl Into<String>` bound.
3039 #[must_use]
3040 pub fn child_caixa_invalid(caixa: &str, reason: impl Into<String>) -> Self {
3041 Self::ChildCaixaInvalid {
3042 caixa: caixa.to_string(),
3043 reason: reason.into(),
3044 }
3045 }
3046
3047 /// Construct a [`SupervisorError::ChildVersaoInvalid`] naming the
3048 /// offending `:children :caixa` and its `:versao` requirement under
3049 /// the given `reason`. Folds the uniform `Self::ChildVersaoInvalid {
3050 /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
3051 /// reason.into() }` three-slot struct-literal onto one substrate
3052 /// primitive so every wire-up on this variant reads through one
3053 /// dispatch, matching the sibling `AplicacaoError::MembroVersaoInvalid
3054 /// { caixa, versao, reason }` three-slot axis on the peer
3055 /// `AplicacaoError` envelope. `reason` accepts both `&str` literals
3056 /// and `format!(…)` outputs through the `impl Into<String>` bound.
3057 #[must_use]
3058 pub fn child_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
3059 Self::ChildVersaoInvalid {
3060 caixa: caixa.to_string(),
3061 versao: versao.to_string(),
3062 reason: reason.into(),
3063 }
3064 }
3065}
3066
3067// Fold the four `SupervisorError::<Variant> { <field>: <Copy> }` one-field
3068// Copy-scalar struct-variant wire-up sites at [`SupervisorSpec::validate`]'s
3069// three bracket-arms — one struct-literal at the `:children`-empty
3070// non-`SimpleOneForOne` refusal cascade (`NoChildren { estrategia }`) plus
3071// three `impl FnOnce(<ty>) -> SupervisorError` bracket-closures at the
3072// [`crate::render::require_positive_bounded_u32`] `:max-restarts` cap arm
3073// (`MaxRestartsExceedsCap { max_restarts }`) and the paired
3074// [`crate::render::require_positive_canonical_bounded_duration`]
3075// `:restart-window` canonical-form + cap arms (`RestartWindowNotCanonical
3076// { window }`, `RestartWindowExceedsCap { window }`) — onto one substrate
3077// primitive per typed variant, matching the sibling
3078// [`crate::aplicacao::aplicacao_policy_scalar_ctors!`] macro (7ef425e, 8
3079// variants on the same `{ <field>: Duration | u32 }` shape) at that
3080// discipline on the peer `AplicacaoError` envelope's per-`:politicas`
3081// scalar axis. Every variant is a one-field `Copy`-pass-through struct-
3082// literal — `RestartStrategy | u32 | Duration` — so the fold routes each
3083// wire-up site through one dispatch per typed variant without a runtime-
3084// work delta.
3085//
3086// Each of the four wire-up sites opened the identical
3087// `SupervisorError::<Variant> { <field>: <val> }` struct-literal — the
3088// exact "same block re-inlined at every consumer" shape the PRIME
3089// DIRECTIVE names as a bug, on the same altitude the peer
3090// `aplicacao_policy_scalar_ctors!` fold closed on the sibling
3091// `AplicacaoError` envelope's per-`:politicas` per-axis cap / canonical-
3092// form arms. The four variants share one `{ <field>: <Copy> }` shape, so
3093// the fold routes each wire-up site through one dispatch per typed
3094// variant.
3095//
3096// The macro below generates one static constructor per variant of shape
3097// `const fn <ctor>(<field>: <ty>) -> SupervisorError`, so every wire-up
3098// site collapses onto one dispatch: `SupervisorError::<ctor>(<val>)`,
3099// byte-equal to the pre-lift struct-literal on the same `Copy`-`<ty>`
3100// fixture — as a direct call at the [`SupervisorSpec::validate`]
3101// `:children`-empty refusal, or as a bare function pointer in the
3102// `impl FnOnce(<ty>) -> SupervisorError` bracket-closure slot every
3103// [`crate::render::require_positive_bounded_u32`] /
3104// [`crate::render::require_positive_canonical_bounded_duration`] gate
3105// carries — rather than the pre-lift open-coded one-line closure over
3106// the same one-field struct-literal. `const fn` preserves the `Copy`-
3107// pass-through's zero-runtime-work property verbatim. Every constructor
3108// is `#[must_use]` so a caller who mistakenly discards the constructed
3109// error trips a compile warning at the wire-up site.
3110//
3111// Every future consumer that wants to construct one of these four
3112// variants outside `SupervisorSpec::validate` — a deferred
3113// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3114// webhook re-checking one edited `:estrategia` / `:max-restarts` /
3115// `:restart-window` slot against the cap + canonical-form cascade, a
3116// future `feira validate --supervisor` per-caixa admission verb re-
3117// running the shape gates on demand, a per-Supervisor overlay resolver
3118// rejecting an author-supplied slot against a cluster-local snapshot —
3119// now reaches each variant through one call rather than re-inlining the
3120// per-shape struct-literal block in lockstep with the four in-crate
3121// wire-up sites.
3122macro_rules! supervisor_scalar_ctors {
3123 ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
3124 impl SupervisorError {
3125 $(
3126 #[doc = concat!(
3127 "Construct a [`SupervisorError::",
3128 stringify!($variant),
3129 "`] naming the offending per-`:supervisor` `",
3130 stringify!($field),
3131 "` scalar. Folds the uniform `Self::",
3132 stringify!($variant),
3133 " { ",
3134 stringify!($field),
3135 " }` one-field `Copy`-pass-through struct-literal onto ",
3136 "one substrate primitive so every per-axis wire-up on ",
3137 "this variant reads through one dispatch — as a direct ",
3138 "call (`SupervisorError::",
3139 stringify!($ctor),
3140 "(<val>)`, byte-equal to the pre-lift struct-literal on ",
3141 "the same `Copy`-`",
3142 stringify!($ty),
3143 "` fixture) or as a bare function pointer in the ",
3144 "`impl FnOnce(",
3145 stringify!($ty),
3146 ") -> SupervisorError` bracket-closure slot every ",
3147 "`crate::render::require_positive_bounded_*` / ",
3148 "`crate::render::require_positive_canonical_bounded_*` ",
3149 "gate carries — rather than the pre-lift open-coded ",
3150 "one-line closure over the same one-field struct-",
3151 "literal. `const fn` preserves the `Copy`-pass-through's ",
3152 "zero-runtime-work property verbatim."
3153 )]
3154 #[must_use]
3155 pub const fn $ctor($field: $ty) -> Self {
3156 Self::$variant { $field }
3157 }
3158 )*
3159 }
3160 };
3161}
3162
3163supervisor_scalar_ctors! {
3164 no_children => NoChildren { estrategia: RestartStrategy },
3165 max_restarts_exceeds_cap => MaxRestartsExceedsCap { max_restarts: u32 },
3166 restart_window_not_canonical => RestartWindowNotCanonical { window: Duration },
3167 restart_window_exceeds_cap => RestartWindowExceedsCap { window: Duration },
3168}
3169
3170/// Shared duration string codec for the typed slots that take a
3171/// duration (`restart_window`, `MeshPolicy::timeout`,
3172/// `CircuitBreaker::window`, …). Public so [`crate::aplicacao`] can
3173/// reuse it without duplicating the parser.
3174pub mod duration_codec {
3175 use super::Duration;
3176 use serde::{Deserializer, Serializer};
3177
3178 pub fn serialize<S: Serializer>(v: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
3179 // Route through the canonical [`crate::render::serialize_option_via_str`]
3180 // — the substrate-side single-owner primitive for the forward
3181 // arm of the typed-magnitude codec family. See its docstring
3182 // for the full sibling roster.
3183 crate::render::serialize_option_via_str(v, s, render)
3184 }
3185
3186 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
3187 // Route through the canonical [`crate::render::deserialize_option_via_str`]
3188 // — the substrate-side single-owner primitive for the reverse
3189 // arm of the typed-magnitude codec family. See its docstring
3190 // for the full sibling roster.
3191 crate::render::deserialize_option_via_str(d, parse)
3192 }
3193
3194 pub(crate) fn parse(s: &str) -> Result<Duration, String> {
3195 // Paired whitespace-rejection arm — same canonical-form
3196 // render-determinism discipline as the peer
3197 // `limits::parse_byte_size` / `limits::parse_duration` /
3198 // `limits::parse_millicores` /
3199 // `aplicacao::rate_limit_codec::parse` sites: the ASCII
3200 // byte-scan closes the WhatWG-conformant whitespace bytes
3201 // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
3202 // `char::is_whitespace` scan closes the strictly-complementary
3203 // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
3204 // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
3205 // codepoints) that `str::trim` at parse entry silently strips.
3206 // Either drift class would round-trip through `render` to a
3207 // *different* canonical form on next emit — breaking the
3208 // THEORY.md Part V render-determinism contract on three typed-
3209 // duration slots at once (`:supervisor :restart-window`,
3210 // `:politicas :timeout`, `:politicas :circuit-breaker :window`)
3211 // via the shared codec.
3212 //
3213 // Routed through the lifted [`crate::render::reject_whitespace`]
3214 // primitive — the substrate-side single-owner paired-arm gate
3215 // every typed-magnitude codec in caixa-core shares.
3216 crate::render::reject_whitespace::<String, _, _>(
3217 s,
3218 |b| {
3219 format!(
3220 "duration: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
3221 authoring form for the typed duration slots routed through this shared codec \
3222 (`:supervisor :restart-window`, `:politicas :timeout`, \
3223 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
3224 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no whitespace bytes \
3225 anywhere. A whitespace-carrying shape (`\" 30s\"`, `\"30s \"`, `\"30 s\"`, \
3226 `\"\\t30s\"`, `\"30s\\n\"`) round-trips through `render` to a *different* \
3227 canonical form (`\"30s\"`) on first serialize — breaking the THEORY.md \
3228 Part V render-determinism contract every typed slot carries. Strip every \
3229 whitespace byte (write `\"30s\"` verbatim)"
3230 )
3231 },
3232 |ch| {
3233 format!(
3234 "duration: value {s:?} contains non-ASCII Unicode whitespace character \
3235 {ch:?} (U+{cp:04X}) — the canonical authoring form for the typed \
3236 duration slots routed through this shared codec (`:supervisor \
3237 :restart-window`, `:politicas :timeout`, `:politicas :circuit-breaker \
3238 :window`) is `<integer><unit>` (e.g. `\"30s\"`, `\"500ms\"`, `\"2m\"`, \
3239 `\"1h\"`) with no whitespace characters anywhere (ASCII or Unicode). A \
3240 non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}30s\"`, \
3241 `\"30s\\u{{2028}}\"`, `\"30\\u{{2003}}s\"`) survives the ASCII byte-scan \
3242 but `str::trim` (which uses `char::is_whitespace` — the Unicode \
3243 `White_Space` property, strictly wider than the ASCII byte set) silently \
3244 strips it at parse entry, and the value round-trips through `render` to \
3245 a *different* canonical form (`\"30s\"`) on first serialize — breaking \
3246 the THEORY.md Part V render-determinism contract every typed slot \
3247 carries. Strip every non-ASCII whitespace character (write `\"30s\"` \
3248 verbatim with only ASCII bytes)",
3249 cp = ch as u32
3250 )
3251 },
3252 )?;
3253 let s = s.trim();
3254 // Routed through the lifted
3255 // [`crate::render::split_magnitude_and_alpha_unit`] primitive —
3256 // the single-owner split every ASCII-alphabetic-unit typed-
3257 // magnitude codec in caixa-core (`limits::parse_byte_size` /
3258 // `limits::parse_duration` / this shared duration codec) shares.
3259 // See its docstring for the full sibling roster on the same
3260 // primitive altitude.
3261 let (num_part, unit) = crate::render::split_magnitude_and_alpha_unit(s);
3262 let num_trim = num_part.trim();
3263 // The canonical authoring form for every typed slot routed
3264 // through this shared codec — `:supervisor :restart-window`,
3265 // `:politicas :timeout`, `:politicas :circuit-breaker :window`
3266 // — is `<integer><unit>`. Every magnitude [`render`] emits is a
3267 // non-negative integer with no decimal point and no leading
3268 // sign, so the parser's accepted set must match for
3269 // serialize/deserialize to round-trip without canonical-form
3270 // drift. Until this gate landed the parser accepted any
3271 // `f64`-shaped magnitude (`"1.5s"` → 1500ms, `"1.0s"` → 1s,
3272 // `"0.5m"` → 30s, `"+30s"` → 30s) and serde silently round-
3273 // tripped the value to a *different* canonical string on the
3274 // next emit (`"1.5s"` → 1500ms → `"1500ms"`, `"1.0s"` → 1s →
3275 // `"1s"`, `"0.5m"` → 30s → `"30s"`, `"+30s"` → 30s → `"30s"`)
3276 // — breaking the THEORY.md Part V render-determinism contract
3277 // on three typed slots at once. Same canonical-form discipline
3278 // `crate::limits::parse_duration` (818dd38, the immediate
3279 // predecessor on the peer `:limits :wall-clock` codec) applies;
3280 // this gate lifts the discipline onto the shared codec that
3281 // backs the remaining three typed-duration slots in caixa-core.
3282 //
3283 // Strict canonical form: every byte of the magnitude is an
3284 // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
3285 // inputs the gate distinguishes "non-canonical-but-numeric"
3286 // (parses as f64 or i64 — surfaced with a self-locating
3287 // diagnostic naming the canonical authoring form, the
3288 // round-trip drift each rejected shape would produce on first
3289 // serialize, and the canonical-form remediation) from
3290 // "garbage" (parses as neither — surfaced with the existing
3291 // narrower "bad duration magnitude" wording so its diagnostic
3292 // shape remains stable for the parser-shape footgun case).
3293 // The pre-existing `num < 0.0` arm is now unreachable — the
3294 // digit-only gate strictly precedes magnitude parsing, and a
3295 // leading `-` is not an ASCII digit, so `"-30s"` lands on the
3296 // non-canonical-but-numeric branch with the `-30` named
3297 // verbatim in the diagnostic rather than the prior
3298 // value-laundered "negative duration in \"-30s\"" wording.
3299 //
3300 // Routed through the lifted
3301 // [`crate::render::is_digit_only_magnitude`] predicate — the
3302 // same source of truth the four peer typed-magnitude codec
3303 // sites share.
3304 let digit_only = crate::render::is_digit_only_magnitude(num_trim);
3305 if !digit_only {
3306 let numeric = num_trim.parse::<f64>().is_ok() || num_trim.parse::<i64>().is_ok();
3307 if numeric {
3308 return Err(format!(
3309 "duration: magnitude {num_trim:?} is not a non-negative integer — the \
3310 canonical authoring form for the typed duration slots routed through \
3311 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
3312 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
3313 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no decimal point and \
3314 no leading `+` / `-` sign. A fractional / decimal-shaped magnitude \
3315 (`\"1.5s\"`, `\"1.0s\"`, `\"0.5m\"`, `\"+30s\"`, `\"-30s\"`) round-trips \
3316 through `render` to a *different* canonical form (`\"1500ms\"`, `\"1s\"`, \
3317 `\"30s\"`, `\"30s\"`, `\"30s\"`) on first serialize — breaking the \
3318 THEORY.md Part V render-determinism contract every typed slot carries. \
3319 Pick an integer magnitude in the unit that divides cleanly (write \
3320 `\"1500ms\"` instead of `\"1.5s\"`; `\"30s\"` instead of `\"0.5m\"`)"
3321 ));
3322 }
3323 return Err(format!("bad duration magnitude in {s:?}"));
3324 }
3325 // Leading-zero arm — peer with the `rate_limit_codec` leading-
3326 // zero arm (4f46830) on the same canonical-form render-
3327 // determinism axis. The digit-only gate accepts `"030s"`,
3328 // `"00s"`, `"01h"`, `"0500ms"` as `u64::from_str` parses them
3329 // losslessly (= 30, 0, 1, 500), but `render` emits the leading-
3330 // zero-stripped form (`"30s"`, `"0s"`, `"1h"`, `"500ms"`) — a
3331 // *different* canonical string on the next emit, breaking the
3332 // THEORY.md Part V render-determinism contract the same way
3333 // `"+30s"` did before the leading-`+` arm landed. The single-
3334 // byte magnitude `"0"` (or `"0s"` / `"0ms"`) round-trips
3335 // losslessly through `render` (`render(Duration::ZERO)` emits
3336 // `"0s"`) — the downstream semantic-zero gates (e.g.
3337 // `SupervisorError::ZeroRestartWindow` on
3338 // `:supervisor :restart-window`,
3339 // `AplicacaoError::PolicyTimeoutZero` /
3340 // `PolicyCircuitBreakerWindowZero` on the typed `:politicas`
3341 // duration slots) refuse zero-magnitude authoring at the typed-
3342 // validate layer above, so the single-byte `"0"` stays in the
3343 // accepted set at this codec layer and the diagnostic
3344 // partitioning between canonical-form drift (this arm) and
3345 // semantic-zero (the downstream gates) remains stable.
3346 // Peer with the future leading-zero arms on the two remaining
3347 // typed-magnitude codecs the trajectory acknowledges:
3348 // `limits::parse_duration` backing `:limits :wall-clock`,
3349 // `limits::parse_byte_size` backing `:limits :memory` — each
3350 // carries the same canonical-form-drift class today; this
3351 // gate lands the discipline on the shared duration codec
3352 // first because the `rate_limit_codec` predecessor on the
3353 // same canonical-form-drift axis is the closest peer on the
3354 // trajectory.
3355 //
3356 // Routed through the lifted
3357 // [`crate::render::is_leading_zero_padded_magnitude`]
3358 // predicate — the same source of truth the four peer
3359 // typed-magnitude codec sites share.
3360 if crate::render::is_leading_zero_padded_magnitude(num_trim) {
3361 return Err(format!(
3362 "duration: magnitude {num_trim:?} has a non-canonical leading zero — the \
3363 canonical authoring form for the typed duration slots routed through \
3364 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
3365 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
3366 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no leading-zero padding \
3367 on the magnitude. A leading-zero magnitude (`\"030s\"`, `\"00s\"`, \
3368 `\"01h\"`, `\"0500ms\"`) round-trips through `render` to a *different* \
3369 canonical form (`\"30s\"`, `\"0s\"`, `\"1h\"`, `\"500ms\"`) on first \
3370 serialize — breaking the THEORY.md Part V render-determinism contract \
3371 every typed slot carries. Strip the leading zeros (write \
3372 `\"30s\"` instead of `\"030s\"`)"
3373 ));
3374 }
3375 // The digit-only gate guarantees every byte is `[0-9]`, and
3376 // the leading-zero arm above guarantees the magnitude is
3377 // either the single byte `"0"` or starts with `[1-9]`, so
3378 // the only way `u64::from_str` can fail here is overflow (the
3379 // magnitude exceeds `u64::MAX`). Surface that with an
3380 // overflow-shaped wording so the diagnostic names the offending
3381 // magnitude verbatim rather than collapsing onto the
3382 // non-canonical arm. The codec now operates on `u64` end-to-end
3383 // — every accepted magnitude is integer-exact; no f64 mantissa
3384 // drift between author-supplied magnitude and the consumer's
3385 // `Duration` value. Same shape `crate::limits::parse_duration`
3386 // (818dd38) carries on the peer `:limits :wall-clock` axis.
3387 let num: u64 = num_trim.parse::<u64>().map_err(|_| {
3388 format!("bad duration magnitude in {s:?} (digit-only magnitude overflows u64)")
3389 })?;
3390 // Route the `{"ms" | "s" | "" | "m" | "h"} → Duration`
3391 // unit-arm dispatch through the canonical
3392 // [`crate::render::duration_from_integer_magnitude_and_unit`]
3393 // primitive — the substrate-side single-owner unit-dispatch
3394 // table every typed-duration codec in caixa-core routes
3395 // through (peer: `crate::limits::parse_duration` backing
3396 // `:limits :wall-clock`). Every unit conversion is integer-
3397 // exact for an integer magnitude; overflow surfaces via the
3398 // typed `DurationUnitError::Overflow { multiplier }`
3399 // discriminant so this arm reconstructs the pre-lift
3400 // `"duration <num><unit> overflows u64 (magnitude × 60 …)"`
3401 // wording verbatim from `num` / `unit_trim` / the returned
3402 // `multiplier`, and the unknown-unit arm reconstructs the
3403 // pre-lift `"unknown duration unit \"<other>\""` wording from
3404 // the caller-scoped `unit_trim`. Load-bearing pinned by
3405 // `crate::render::tests::duration_from_integer_magnitude_and_unit_matches_pre_lift_unit_dispatch_table`.
3406 let unit_trim = unit.trim();
3407 let dur = crate::render::duration_from_integer_magnitude_and_unit(num, unit_trim).map_err(
3408 |e| match e {
3409 crate::render::DurationUnitError::Overflow { multiplier } => format!(
3410 "duration {num}{unit_trim} overflows u64 (magnitude × {multiplier} > 2^64-1)"
3411 ),
3412 crate::render::DurationUnitError::UnknownUnit => {
3413 format!("unknown duration unit {unit_trim:?}")
3414 }
3415 },
3416 )?;
3417 Ok(dur)
3418 }
3419
3420 /// Render a [`Duration`] in the canonical pleme-io duration string
3421 /// form (`"30s"`, `"1m"`, `"1h"`, `"500ms"`). The same form every
3422 /// caixa typed-duration slot serializes to and the same form K8s
3423 /// Gateway API HTTPRoute `timeouts` / `backendRequest` and Cilium
3424 /// EnvoyConfig per-route timeouts both expect (an integer
3425 /// followed by `s`/`m`/`h`/`ms`, no fractional values, no leading
3426 /// `+`). Lifted to `pub` so caixa-side renderers
3427 /// (`caixa-mesh::gateway_routes`'s :politicas :timeout overlay,
3428 /// the future per-:politicas `CiliumClusterwideEnvoyConfig`
3429 /// emitter, the future caixa-otel collector pipeline emitter) can
3430 /// consume the same canonical formatter without re-inlining the
3431 /// magnitude/unit decision tree (and inheriting the same drift
3432 /// footguns: a subtly different `300ms` vs `0.3s` rendering breaks
3433 /// downstream apply-time parsing in non-obvious ways).
3434 pub fn render(d: Duration) -> String {
3435 let total_ms = d.as_millis();
3436 if total_ms == 0 {
3437 return "0s".into();
3438 }
3439 if total_ms.is_multiple_of(3600 * 1000) {
3440 return format!("{}h", total_ms / (3600 * 1000));
3441 }
3442 if total_ms.is_multiple_of(60 * 1000) {
3443 return format!("{}m", total_ms / (60 * 1000));
3444 }
3445 if total_ms.is_multiple_of(1000) {
3446 return format!("{}s", total_ms / 1000);
3447 }
3448 format!("{total_ms}ms")
3449 }
3450
3451 /// True iff `d` round-trips losslessly through [`render`] + [`parse`].
3452 ///
3453 /// [`render`] truncates a `Duration` to `as_millis()` before picking the
3454 /// largest divisor unit, so any sub-millisecond residue
3455 /// (`d.subsec_nanos() % 1_000_000 != 0`) silently breaks the THEORY.md
3456 /// §V.2.7 render-determinism contract:
3457 ///
3458 /// - `Duration::from_micros(1500)` (= `1_500_000` ns) → `as_millis() == 1`
3459 /// → renders `"1ms"` → parses back to `Duration::from_millis(1)` =
3460 /// `1_000_000` ns ≠ original `1_500_000` ns;
3461 /// - `Duration::from_nanos(1)` (= 1 ns) → `as_millis() == 0` →
3462 /// renders the literal `"0s"`, which the per-axis zero-floor gate
3463 /// on every typed-`Duration` slot then rejects on re-validate.
3464 ///
3465 /// Lifted to a `pub` predicate next to the [`render`] / [`parse`] pair so
3466 /// the codec's round-trippable accepted set lives in exactly one place —
3467 /// every typed-`Duration` slot that routes through this shared codec
3468 /// (`SupervisorSpec::restart_window` via [`super::duration_codec`],
3469 /// [`crate::MeshPolicy::timeout`] / [`crate::CircuitBreaker::window`] via
3470 /// `supervisor::duration_codec` + [`super::duration_codec_required`]) and
3471 /// every typed-`Duration` slot whose own codec shares the same
3472 /// `as_millis()`-truncation shape ([`crate::LimitsSpec::wall_clock`] via
3473 /// [`crate::limits`]'s in-module `parse_duration` / `render_duration`
3474 /// pair) calls this predicate from its `validate()` to bracket the
3475 /// accepted set against the codec's accepted set, structurally. Drift
3476 /// between the codec's granularity and any typed slot's accepted set is
3477 /// then a single-source-of-truth edit at this predicate rather than a
3478 /// silent round-trip break the next consumer discovers at apply time.
3479 ///
3480 /// Peer of [`crate::aplicacao::POLICY_RETRIES_MAX`] /
3481 /// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] and the
3482 /// `is_dns_1123_label` / `is_canonical_rate_limit_window` predicate
3483 /// family — same "typed-slot's valid set matches its codec's accepted
3484 /// set, structurally" discipline carried at the codec layer.
3485 #[must_use]
3486 pub fn is_integer_millisecond_duration(d: Duration) -> bool {
3487 d.subsec_nanos().is_multiple_of(1_000_000)
3488 }
3489}
3490
3491/// Required-Duration variant for fields that aren't Option<Duration>.
3492pub mod duration_codec_required {
3493 use super::Duration;
3494 use serde::{Deserialize, Deserializer, Serializer};
3495
3496 pub fn serialize<S: Serializer>(v: &Duration, s: S) -> Result<S::Ok, S::Error> {
3497 s.serialize_str(&super::duration_codec::render(*v))
3498 }
3499
3500 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
3501 let s = String::deserialize(d)?;
3502 super::duration_codec::parse(&s).map_err(serde::de::Error::custom)
3503 }
3504}
3505
3506#[cfg(test)]
3507mod tests {
3508 use super::*;
3509
3510 fn child(name: &str, ver: &str, restart: RestartPolicy) -> ChildSpec {
3511 ChildSpec {
3512 caixa: name.into(),
3513 versao: ver.into(),
3514 restart,
3515 }
3516 }
3517
3518 #[test]
3519 fn child_spec_string_scalar_accessor_pair_is_const_fn() {
3520 // Fail-before-pass-after pin on [`ChildSpec::nome`] +
3521 // [`ChildSpec::versao_requirement`]'s `const`-eval-surface
3522 // posture. Each accessor projects the per-`:children :caixa`
3523 // / per-`:children :versao` [`String`] storage through the
3524 // `pub const fn` [`String::as_str`] (const-stable since Rust
3525 // 1.87, well within the workspace MSRV) — any future
3526 // accidental downgrade to non-`const` fails the corresponding
3527 // `<name>_via_const_fn` wrapper at caixa-core build time with
3528 // E0015 (`cannot call non-const method`), strictly stronger
3529 // than a runtime `assert!`. Sibling of the peer
3530 // per-M2/M3/universal-axis `String → &str` scalar-accessor
3531 // family pins on the sibling `const`-eval-surface passes
3532 // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
3533 // top-level manifest, [`crate::CaixaVersion::as_str`] at the
3534 // typed-newtype wrapper, [`crate::aplicacao::Membro::nome`] /
3535 // [`crate::aplicacao::Membro::versao_requirement`] at the M3
3536 // membership axis, [`crate::aplicacao::Entrada::hostname`] /
3537 // [`crate::aplicacao::Entrada::destination`] at the M3
3538 // ingress axis,
3539 // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
3540 // M2 upgrade axis, [`crate::dep::Dep::nome`] /
3541 // [`crate::dep::Dep::versao_requirement`] at the dep-graph
3542 // axis, and the per-`:contratos`
3543 // [`crate::aplicacao::WitContract::source`] /
3544 // [`crate::aplicacao::WitContract::destination`] /
3545 // [`crate::aplicacao::WitContract::world_ref`] trio the
3546 // sibling pin at 279823b already anchors).
3547 const fn nome_via_const_fn(c: &ChildSpec) -> &str {
3548 c.nome()
3549 }
3550 const fn versao_via_const_fn(c: &ChildSpec) -> &str {
3551 c.versao_requirement()
3552 }
3553 for (caixa, versao) in [
3554 ("worker-a", "^0.1"),
3555 ("worker-b", "~0.2.3"),
3556 ("collector", "*"),
3557 ] {
3558 let c = child(caixa, versao, RestartPolicy::Permanent);
3559 assert_eq!(nome_via_const_fn(&c), c.nome());
3560 assert_eq!(versao_via_const_fn(&c), c.versao_requirement());
3561 assert_eq!(c.nome(), caixa);
3562 assert_eq!(c.versao_requirement(), versao);
3563 }
3564 }
3565
3566 #[test]
3567 fn supervisor_children_slice_return_accessor_is_const_fn() {
3568 // Fail-before-pass-after pin on [`SupervisorSpec::children`]'s
3569 // `const`-eval-surface posture. The accessor destructures the
3570 // per-`:children` `Vec<ChildSpec>` storage through the
3571 // `pub const fn` [`Vec::as_slice`] (const-stable since Rust
3572 // 1.66, well within the workspace MSRV) — any future
3573 // accidental downgrade to non-`const` fails
3574 // `children_via_const_fn` at caixa-core build time with E0015
3575 // (`cannot call non-const method`), strictly stronger than a
3576 // runtime `assert!`. Sibling of the peer per-M3-mesh-slot
3577 // `Vec → &[T]` slice-return accessor family pin
3578 // [`crate::aplicacao::tests::m3_reference_return_accessor_family_is_const_fn`]
3579 // on the M3 mesh-slot per-`:clusters` / per-`:paths` /
3580 // per-`:membros` / per-`:contratos` slice-return axes, and of
3581 // the peer M2 upgrade-appup axis pin
3582 // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
3583 // on the per-`:upgrade-from :instructions` slice-return axis.
3584 const fn children_via_const_fn(s: &SupervisorSpec) -> &[ChildSpec] {
3585 s.children()
3586 }
3587 // Sweep both the empty-children (leaf-supervisor with no
3588 // static children — the `SimpleOneForOne` dynamic-child
3589 // arm's canonical shape) and the populated-children
3590 // (`OneForOne` / `OneForAll` / `RestForOne` static-child
3591 // arm's canonical shape) axes so the accessor carries a
3592 // const-dispatch pin on both arms.
3593 let s_empty = SupervisorSpec {
3594 estrategia: RestartStrategy::SimpleOneForOne,
3595 max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
3596 restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3597 children: vec![],
3598 };
3599 assert!(children_via_const_fn(&s_empty).is_empty());
3600 assert_eq!(children_via_const_fn(&s_empty), s_empty.children());
3601 let s_full = SupervisorSpec {
3602 estrategia: RestartStrategy::OneForOne,
3603 max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
3604 restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3605 children: vec![
3606 child("worker-a", "^0.1", RestartPolicy::Permanent),
3607 child("worker-b", "~0.2.3", RestartPolicy::Transient),
3608 child("collector", "*", RestartPolicy::Temporary),
3609 ],
3610 };
3611 assert_eq!(children_via_const_fn(&s_full).len(), 3);
3612 assert_eq!(children_via_const_fn(&s_full), s_full.children());
3613 }
3614
3615 #[test]
3616 fn default_has_one_for_one_and_5_restarts_in_60s() {
3617 let s = SupervisorSpec::default();
3618 assert_eq!(s.estrategia, RestartStrategy::OneForOne);
3619 assert_eq!(s.max_restarts, 5);
3620 assert_eq!(s.restart_window, Some(Duration::from_secs(60)));
3621 assert!(s.children.is_empty());
3622 }
3623
3624 #[test]
3625 fn validate_one_for_one_requires_children() {
3626 let mut s = SupervisorSpec::default();
3627 s.children = vec![];
3628 assert!(matches!(
3629 s.validate().unwrap_err(),
3630 SupervisorError::NoChildren { .. }
3631 ));
3632 s.children = vec![child("worker", "^0.1", RestartPolicy::Permanent)];
3633 s.validate().unwrap();
3634 }
3635
3636 #[test]
3637 fn validate_simple_one_for_one_forbids_static_children() {
3638 let mut s = SupervisorSpec {
3639 estrategia: RestartStrategy::SimpleOneForOne,
3640 ..SupervisorSpec::default()
3641 };
3642 s.children
3643 .push(child("w", "^0.1", RestartPolicy::Permanent));
3644 assert_eq!(
3645 s.validate().unwrap_err(),
3646 SupervisorError::SimpleOneForOneWithStaticChildren
3647 );
3648 s.children.clear();
3649 s.validate().unwrap();
3650 }
3651
3652 #[test]
3653 fn validate_rejects_zero_max_restarts() {
3654 let s = SupervisorSpec {
3655 max_restarts: 0,
3656 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3657 ..SupervisorSpec::default()
3658 };
3659 assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
3660 }
3661
3662 // ── upper-cap: SUPERVISOR_MAX_RESTARTS_MAX brackets the typed slot ─────
3663 //
3664 // The cap arm lifts the `:politicas :circuit-breaker :max-failures` /
3665 // `POLICY_BREAKER_MAX_FAILURES_MAX` (2b51ace) discipline onto the peer
3666 // `:supervisor :max-restarts` axis — both fields are "trip the
3667 // next-higher protection layer after N events in a rolling window"
3668 // counters with identical degenerate-at-the-high-end shape, so the
3669 // typed-slot's accepted set lies in `1..=1000` on the supervisor side
3670 // exactly as it lies in `1..=1000` on the breaker side.
3671
3672 #[test]
3673 fn validate_rejects_max_restarts_above_cap() {
3674 // The fail-before-pass-after pin: `SUPERVISOR_MAX_RESTARTS_MAX +
3675 // 1` is structurally one past the cap and silently passed
3676 // validate on every pre-gate codebase because the typed slot's
3677 // only check was the zero-floor arm. The no-op-supervisor vector
3678 // only surfaced at the runtime substrate (Erlang/OTP
3679 // MaxIntensity/Period ratio, the future wasm-operator's
3680 // per-supervisor restart-intensity counter) far from the source
3681 // caixa.lisp with no field naming the offending supervisor.
3682 let s = SupervisorSpec {
3683 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3684 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3685 ..SupervisorSpec::default()
3686 };
3687 assert_eq!(
3688 s.validate().unwrap_err(),
3689 SupervisorError::MaxRestartsExceedsCap {
3690 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3691 }
3692 );
3693 }
3694
3695 #[test]
3696 fn validate_rejects_max_restarts_far_above_cap() {
3697 // The `u32::MAX` worst case — the four-billion-restart
3698 // threshold a typo (`:max-restarts 4294967295`) or a
3699 // struct-literal copy-paste lands in the slot. Pin the cap
3700 // arm's coverage explicitly across the full `u32` overflow so
3701 // a future relaxation that drops the upper bound surfaces
3702 // here. Same shape every other typed-cap arm on this surface
3703 // carries (POLICY_BREAKER_MAX_FAILURES_MAX,
3704 // POLICY_RETRIES_MAX, POLICY_RATE_LIMIT_MAX).
3705 let s = SupervisorSpec {
3706 max_restarts: u32::MAX,
3707 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3708 ..SupervisorSpec::default()
3709 };
3710 assert_eq!(
3711 s.validate().unwrap_err(),
3712 SupervisorError::MaxRestartsExceedsCap {
3713 max_restarts: u32::MAX,
3714 }
3715 );
3716 }
3717
3718 #[test]
3719 fn validate_accepts_max_restarts_at_cap() {
3720 // The boundary value — exactly SUPERVISOR_MAX_RESTARTS_MAX —
3721 // must validate. The cap is inclusive on the top edge,
3722 // matching the POLICY_BREAKER_MAX_FAILURES_MAX /
3723 // POLICY_RETRIES_MAX / LIMITS_MEMORY_WASM32_MAX_BYTES
3724 // discipline on the sibling capped axes. Pin the boundary
3725 // explicitly so a future off-by-one tightening
3726 // (`>= SUPERVISOR_MAX_RESTARTS_MAX` instead of `>`) surfaces
3727 // here as a test failure rather than a silent contract
3728 // narrowing.
3729 let s = SupervisorSpec {
3730 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX,
3731 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3732 ..SupervisorSpec::default()
3733 };
3734 s.validate()
3735 .expect("max_restarts == SUPERVISOR_MAX_RESTARTS_MAX must validate");
3736 }
3737
3738 #[test]
3739 fn validate_accepts_max_restarts_typical_values() {
3740 // The documented production-playbook band positive-control
3741 // sweep — every value Erlang/OTP / Elixir / Riak Core /
3742 // RabbitMQ recommend (1..=100) must pass, plus a sweep
3743 // through the hyperscale band (200, 500, 1000) the cap
3744 // accepts. Pin the inclusive validated set explicitly so a
3745 // future tightening of the ceiling surfaces here.
3746 for n in [1u32, 3, 5, 10, 20, 50, 100, 200, 500, 1000] {
3747 let s = SupervisorSpec {
3748 max_restarts: n,
3749 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3750 ..SupervisorSpec::default()
3751 };
3752 s.validate()
3753 .unwrap_or_else(|e| panic!("max_restarts={n} must validate; got {e:?}"));
3754 }
3755 }
3756
3757 #[test]
3758 fn zero_max_restarts_takes_precedence_over_cap() {
3759 // The cross-arm ordering pin: `0` is structurally outside
3760 // both `1..` (zero-floor) and `..=SUPERVISOR_MAX_RESTARTS_MAX`
3761 // (cap), but the zero-floor diagnostic is the more
3762 // self-locating one (it directly names the counter-axis
3763 // remediation), so the validate gate must fire on zero first.
3764 // Same shape every other zero-then-shape ordering on this
3765 // surface uses (PolicyRetriesZero then
3766 // PolicyRetriesExceedsCap; PolicyBreakerZeroFailures then
3767 // PolicyBreakerMaxFailuresExceedsCap).
3768 let s = SupervisorSpec {
3769 max_restarts: 0,
3770 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3771 ..SupervisorSpec::default()
3772 };
3773 assert_eq!(
3774 s.validate().unwrap_err(),
3775 SupervisorError::ZeroMaxRestarts,
3776 "max_restarts == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
3777 );
3778 }
3779
3780 #[test]
3781 fn max_restarts_cap_takes_precedence_over_restart_window_gates() {
3782 // The cross-arm ordering pin between the cap and the sibling
3783 // `:restart-window` gates (zero-window, canonical-window). A
3784 // supervisor carrying both an over-cap `max_restarts` AND a
3785 // structurally invalid window (zero, sub-ms) must surface the
3786 // cap diagnostic first — the cap arm is wired immediately
3787 // after the zero-restart arm and strictly before the window
3788 // arms, so the offending value the diagnostic names matches
3789 // the order the author would discover the gates by reading
3790 // top-to-bottom through `SupervisorSpec::validate`. Pin the
3791 // order so a future refactor that reorders the arms surfaces
3792 // here as a test failure rather than a silent diagnostic
3793 // regression. Peer of
3794 // `circuit_breaker_max_failures_cap_takes_precedence_over_window_gates`
3795 // on the sibling `:politicas :circuit-breaker` slot.
3796 let s = SupervisorSpec {
3797 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3798 restart_window: Some(Duration::ZERO),
3799 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3800 ..SupervisorSpec::default()
3801 };
3802 assert_eq!(
3803 s.validate().unwrap_err(),
3804 SupervisorError::MaxRestartsExceedsCap {
3805 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3806 },
3807 "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
3808 );
3809 }
3810
3811 #[test]
3812 fn max_restarts_cap_diagnostic_carries_offending_value() {
3813 // The diagnostic-shape pin: the offending `u32` is carried
3814 // verbatim into the `SupervisorError::MaxRestartsExceedsCap`
3815 // variant so the surfaced error message names the value the
3816 // author wrote (`":supervisor :max-restarts (50000) exceeds the
3817 // supervisor-policy ceiling …"`), not just the cap. Same
3818 // self-locating diagnostic shape every other typed-cap arm on
3819 // this surface carries
3820 // (`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` carries
3821 // the offending failure count verbatim,
3822 // `AplicacaoError::PolicyRetriesExceedsCap` carries the offending
3823 // retries count verbatim).
3824 let s = SupervisorSpec {
3825 max_restarts: 50_000,
3826 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3827 ..SupervisorSpec::default()
3828 };
3829 let err = s.validate().unwrap_err();
3830 assert!(
3831 matches!(
3832 err,
3833 SupervisorError::MaxRestartsExceedsCap {
3834 max_restarts: 50_000
3835 }
3836 ),
3837 "got {err:?}"
3838 );
3839 let msg = err.to_string();
3840 assert!(
3841 msg.contains("50000"),
3842 ":supervisor :max-restarts cap diagnostic must carry the offending value verbatim (got: {msg})"
3843 );
3844 }
3845
3846 #[test]
3847 fn supervisor_max_restarts_default_pins_otp_canonical_value() {
3848 // Pin [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] at `5` — the
3849 // Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
3850 // half of Learn You Some Erlang's worker-supervisor default,
3851 // sibling of the `60s` `Period` half that the paired
3852 // [`Default for SupervisorSpec`] impl already pins on the
3853 // sibling `restart_window` axis. Pinning the literal here
3854 // surfaces a future rebrand (a tightening to Elixir's `3`,
3855 // a widening to a per-cluster overlay the operator pins
3856 // through a future `:max-restarts-overrides` slot) as a
3857 // deliberate test edit, not a silent contract migration.
3858 // Peer of the sibling
3859 // [`supervisor_max_restarts_cap_pins_canonical_value`]
3860 // upper-bracket pin on the same axis.
3861 assert_eq!(SUPERVISOR_MAX_RESTARTS_DEFAULT, 5);
3862 }
3863
3864 #[test]
3865 fn default_max_restarts_helper_routes_through_lifted_default() {
3866 // Composition pin: the private `default_max_restarts()`
3867 // serde-`#[serde(default = "…")]` helper on
3868 // [`SupervisorSpec::max_restarts`] must route through the
3869 // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
3870 // typed `pub const` rather than a raw `5` literal. Prior to
3871 // the lift the helper carried an inline `5` with no compile-
3872 // time link back to the shared default, so the wire-format
3873 // author-omitted arm and the caixa-core
3874 // [`crate::manifest::Caixa::supervisor_view`] fold's `unwrap_or(5)`
3875 // arm could silently split on any future default rebrand.
3876 // Byte-parity against the lifted constant closes the split.
3877 assert_eq!(default_max_restarts(), SUPERVISOR_MAX_RESTARTS_DEFAULT);
3878 }
3879
3880 #[test]
3881 fn supervisor_spec_default_max_restarts_routes_through_lifted_default() {
3882 // Composition pin: the [`Default for SupervisorSpec`] impl's
3883 // struct-literal `max_restarts` field must route through the
3884 // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
3885 // typed `pub const` (via the private helper this test's
3886 // sibling `default_max_restarts_helper_routes_through_lifted_default`
3887 // already pins onto the constant). Structurally: every
3888 // `SupervisorSpec::default()` call must yield a
3889 // `max_restarts` field byte-equal to the lifted constant
3890 // (the two paired defaults — the serde-side wire-format arm
3891 // and the struct-literal default arm — cannot silently split
3892 // on any future default rebrand). Peer of the sibling
3893 // `default_has_one_for_one_and_5_restarts_in_60s` shape pin
3894 // — this pin closes the byte-parity arm on the two paired
3895 // altitude entry points onto the shared substrate constant.
3896 assert_eq!(
3897 SupervisorSpec::default().max_restarts(),
3898 SUPERVISOR_MAX_RESTARTS_DEFAULT,
3899 );
3900 }
3901
3902 #[test]
3903 fn supervisor_restart_window_default_pins_otp_canonical_value() {
3904 // Pin [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] at `60s` — the
3905 // Erlang/OTP-canonical `{intensity, 5, 60}` `Period` half of
3906 // Learn You Some Erlang's worker-supervisor default, paired
3907 // with the sibling `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5`
3908 // `MaxIntensity` half this constant is the sliding-window
3909 // denominator of on the same `MaxIntensity / Period`
3910 // restart-intensity ratio. Pinning the literal here surfaces a
3911 // future coherent rebrand of the paired default (Elixir's
3912 // `{max_restarts: 3, max_seconds: 5}`, a per-cluster overlay
3913 // the operator pins through a future
3914 // `:restart-window-overrides` slot) as a deliberate test edit,
3915 // not a silent contract migration. Peer of the sibling
3916 // [`supervisor_max_restarts_default_pins_otp_canonical_value`]
3917 // paired-half pin on the same OTP-canonical default and the
3918 // [`supervisor_restart_window_cap_pins_canonical_value`]
3919 // upper-bracket pin on the same axis.
3920 assert_eq!(SUPERVISOR_RESTART_WINDOW_DEFAULT, Duration::from_secs(60),);
3921 }
3922
3923 #[test]
3924 fn supervisor_spec_default_restart_window_routes_through_lifted_default() {
3925 // Composition pin: the [`Default for SupervisorSpec`] impl's
3926 // struct-literal `restart_window` field must route through the
3927 // substrate-canonical [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3928 // typed `pub const` rather than a raw
3929 // `Duration::from_secs(60)` literal. Prior to this lift the
3930 // paired `{intensity, 5, 60}` OTP-canonical default was split
3931 // across two altitudes with no compile-time link between the
3932 // halves — the `MaxIntensity` half rode through the lifted
3933 // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant while the
3934 // `Period` half rode as an open-coded literal at the
3935 // composition site, so a future coherent rebrand of the paired
3936 // canonical would have had to migrate one half through the
3937 // constant and the other through a raw literal in lockstep.
3938 // Byte-parity against the lifted constant on the `Period` half
3939 // closes the split — the paired OTP-canonical default now
3940 // migrates as one unit on any future axis change. Peer of the
3941 // sibling
3942 // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
3943 // byte-parity pin on the paired `MaxIntensity` half.
3944 assert_eq!(
3945 SupervisorSpec::default().restart_window(),
3946 Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3947 );
3948 }
3949
3950 #[test]
3951 fn supervisor_estrategia_default_pins_otp_canonical_value() {
3952 // Pin [`SUPERVISOR_ESTRATEGIA_DEFAULT`] at [`RestartStrategy::OneForOne`]
3953 // — the Erlang/OTP-canonical `one_for_one` half of Learn You Some
3954 // Erlang's `{one_for_one, intensity, 5, 60}` worker-supervisor
3955 // canonical default, paired with the sibling
3956 // `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5` `MaxIntensity` half and the
3957 // sibling `SUPERVISOR_RESTART_WINDOW_DEFAULT` `60s` `Period` half
3958 // this constant is the strategy discriminator of on the same
3959 // OTP-canonical worker-supervisor default. Pinning the arm here
3960 // surfaces a future coherent rebrand of the paired triple (Elixir's
3961 // `{:one_for_one, max_restarts: 3, max_seconds: 5}` on the sibling
3962 // intensity/period axes leaving this strategy arm untouched, an OTP
3963 // `rest_for_one` widening once the substrate discovers startup-
3964 // order-coupled child cohorts as the more common worker-supervisor
3965 // shape, a per-cluster overlay the operator pins through a future
3966 // `:estrategia-overrides` slot the MESH-COMPOSITION §III.2
3967 // supervision-canary roadmap acknowledges) as a deliberate test
3968 // edit, not a silent contract migration. Peer of the sibling
3969 // [`supervisor_max_restarts_default_pins_otp_canonical_value`] +
3970 // [`supervisor_restart_window_default_pins_otp_canonical_value`]
3971 // paired-half pins on the same OTP-canonical default.
3972 assert_eq!(SUPERVISOR_ESTRATEGIA_DEFAULT, RestartStrategy::OneForOne);
3973 }
3974
3975 #[test]
3976 fn restart_strategy_default_routes_through_lifted_default() {
3977 // Composition pin: the [`Default for RestartStrategy`] impl's
3978 // return arm must route through the substrate-canonical
3979 // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
3980 // a raw `Self::OneForOne` arm. Prior to the lift the impl carried
3981 // an inline `Self::OneForOne` with no compile-time link back to
3982 // the shared OTP-canonical `one_for_one` strategy the paired
3983 // [`Default for SupervisorSpec`] impl's struct-literal `estrategia`
3984 // field and the [`crate::manifest::Caixa::supervisor_view`] fold's
3985 // `.unwrap_or_default()` (now
3986 // `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)`) arm both key off —
3987 // so a future rebrand of the OTP-canonical strategy default (an
3988 // OTP `rest_for_one` widening once the substrate discovers
3989 // startup-order-coupled child cohorts as the more common worker-
3990 // supervisor shape, a per-cluster overlay the operator pins
3991 // through a future `:estrategia-overrides` slot) would have had to
3992 // be threaded through the `Default` impl and the two peer routes
3993 // in lockstep or the three consumers would silently split. Byte-
3994 // parity against the lifted constant closes the split. Peer of
3995 // the sibling
3996 // [`default_max_restarts_helper_routes_through_lifted_default`] +
3997 // [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
3998 // composition pins on the paired `MaxIntensity` + `Period` halves.
3999 assert_eq!(RestartStrategy::default(), SUPERVISOR_ESTRATEGIA_DEFAULT,);
4000 }
4001
4002 #[test]
4003 fn supervisor_spec_default_estrategia_routes_through_lifted_default() {
4004 // Composition pin: the [`Default for SupervisorSpec`] impl's
4005 // struct-literal `estrategia` field must route through the
4006 // substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed
4007 // `pub const` (either directly, or via the
4008 // [`RestartStrategy::default`] impl that the sibling
4009 // `restart_strategy_default_routes_through_lifted_default` pin
4010 // already routes onto the constant). Structurally: every
4011 // `SupervisorSpec::default()` call must yield an `estrategia`
4012 // field byte-equal to the lifted constant (the three paired
4013 // defaults — the [`Default for RestartStrategy`] impl arm, the
4014 // struct-literal default arm here, and the
4015 // [`crate::manifest::Caixa::supervisor_view`] fold arm — cannot
4016 // silently split on any future default rebrand). Peer of the
4017 // sibling
4018 // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
4019 // + [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
4020 // byte-parity pins on the paired `MaxIntensity` + `Period` halves
4021 // of the same `SupervisorSpec::default()` composed altitude.
4022 assert_eq!(
4023 SupervisorSpec::default().estrategia(),
4024 SUPERVISOR_ESTRATEGIA_DEFAULT,
4025 );
4026 }
4027
4028 #[test]
4029 fn supervisor_spec_default_routes_through_otp_canonical_ctor() {
4030 // Composition pin: the [`Default for SupervisorSpec`] impl must
4031 // route through the substrate-canonical
4032 // [`SupervisorSpec::otp_canonical`] `pub const fn` constructor
4033 // rather than a re-hand-authored struct-literal cascade. Sharpens
4034 // the sibling per-arm
4035 // `supervisor_spec_default_*_routes_through_lifted_default` pins
4036 // from a per-field lift into a whole-struct one-source-of-truth
4037 // pin — the derived-until-now [`Default::default`] and the
4038 // [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
4039 // construction, not by coincidence.
4040 //
4041 // A future extension of the OTP-canonical baseline (a fifth
4042 // `restart_intensity` field the Erlang/OTP `#supervisor` record
4043 // grows, a per-child-cohort split of the `restart_window` /
4044 // `max_restarts` pair, an M4 `mesh.pleme.io/v1alpha1/Supervisor`
4045 // CR materializer's admission-time overlay pass) reaches both
4046 // paths through exactly one edit on
4047 // [`SupervisorSpec::otp_canonical`] — the derived path could
4048 // silently disagree with the constructor's shape on any new
4049 // field whose [`Default::default`] resolves to a different arm
4050 // than the OTP-canonical baseline the constructor names, while
4051 // this delegated impl reaches the constructor directly and
4052 // picks up every future extension by construction.
4053 //
4054 // Fourth peer on the M2 / M3 typed-slot-spec
4055 // [`Default`]-through-const-ctor fold family — sibling of the
4056 // [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
4057 // (abd52c2), [`crate::aplicacao::MeshPolicy`]
4058 // [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`]
4059 // (91641a4), and [`crate::BehaviorSpec`]
4060 // [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c)
4061 // per-`Option`-only-typed-slot folds — extended here onto the
4062 // M2 supervisor-slot [`SupervisorSpec`] whose canonical baseline
4063 // is not "everything `None`" but the Erlang/OTP-canonical
4064 // `{one_for_one, 5, 60}` worker-supervisor triple.
4065 assert_eq!(SupervisorSpec::default(), SupervisorSpec::otp_canonical());
4066 }
4067
4068 #[test]
4069 fn supervisor_spec_otp_canonical_byte_equals_default() {
4070 // Value pin: [`SupervisorSpec::otp_canonical`] must byte-equal
4071 // the hand-authored `{one_for_one, 5, 60, []}` OTP-canonical
4072 // baseline the sibling `default_has_one_for_one_and_5_restarts_in_60s`
4073 // pin already asserts against the [`Default::default`] path.
4074 // Sharpens the pair-invariant into a per-constructor pin so a
4075 // future extension of [`SupervisorSpec`] with a fifth field
4076 // whose OTP-canonical shape is non-`Default::default`-equivalent
4077 // trips at caixa-core test time rather than at a downstream
4078 // consumer that composed [`SupervisorSpec::otp_canonical`] with
4079 // [`SupervisorSpec::validate`] as its "canonical baseline
4080 // seed".
4081 let canonical = SupervisorSpec::otp_canonical();
4082 assert_eq!(canonical.estrategia, RestartStrategy::OneForOne);
4083 assert_eq!(canonical.max_restarts, 5);
4084 assert_eq!(canonical.restart_window, Some(Duration::from_secs(60)));
4085 assert!(canonical.children.is_empty());
4086 }
4087
4088 #[test]
4089 fn supervisor_spec_otp_canonical_is_usable_in_const_context() {
4090 // Const-context pin: [`SupervisorSpec::otp_canonical`] must
4091 // remain callable from a `const`-bound position so downstream
4092 // `const`-context callers wanting a canonical OTP-baseline seed
4093 // can construct one at compile time without runtime dispatch on
4094 // the derived [`Default::default`]. Peer of the sibling
4095 // `pub const fn` [`crate::LimitsSpec::empty`] /
4096 // [`crate::aplicacao::MeshPolicy::empty`] /
4097 // [`crate::BehaviorSpec::empty`] constructors on the sibling
4098 // typed-slot-spec `pub const fn` axis. If a future edit breaks
4099 // the `const`-eligibility of [`SupervisorSpec::otp_canonical`]
4100 // (a non-`const` field-default helper, a non-`const`-stable
4101 // container type promotion), this evaluation fails at
4102 // build time on this file rather than at a downstream
4103 // `const`-context call site.
4104 const CANONICAL: SupervisorSpec = SupervisorSpec::otp_canonical();
4105 assert_eq!(CANONICAL.estrategia, SUPERVISOR_ESTRATEGIA_DEFAULT);
4106 assert_eq!(CANONICAL.max_restarts, SUPERVISOR_MAX_RESTARTS_DEFAULT);
4107 assert_eq!(
4108 CANONICAL.restart_window,
4109 Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
4110 );
4111 assert!(CANONICAL.children.is_empty());
4112 }
4113
4114 #[test]
4115 fn supervisor_child_restart_default_pins_otp_canonical_value() {
4116 // Pin [`SUPERVISOR_CHILD_RESTART_DEFAULT`] at
4117 // [`RestartPolicy::Permanent`] — Erlang/OTP's `permanent`
4118 // worker-child restart type (`{ChildId, StartFunc, permanent, …}`
4119 // in a `supervisor`'s `init/1` child-spec tuple), the per-child
4120 // half of the same OTP-shape supervisor-tree default set whose
4121 // per-`:supervisor` halves the sibling
4122 // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
4123 // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] /
4124 // [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] constants pin. Pinning the
4125 // arm here surfaces a future rebrand of the per-child default (an
4126 // OTP-`transient` widening once the substrate discovers clean-
4127 // completion-aware children as the more common child shape, a
4128 // per-cluster overlay the operator pins through a future
4129 // `:restart-overrides` slot the MESH-COMPOSITION §III.2
4130 // supervision-canary roadmap acknowledges) as a deliberate test
4131 // edit, not a silent contract migration. Peer of the sibling
4132 // [`supervisor_estrategia_default_pins_otp_canonical_value`] /
4133 // [`supervisor_max_restarts_default_pins_otp_canonical_value`] /
4134 // [`supervisor_restart_window_default_pins_otp_canonical_value`]
4135 // value pins on the per-`:supervisor` halves.
4136 assert_eq!(SUPERVISOR_CHILD_RESTART_DEFAULT, RestartPolicy::Permanent);
4137 }
4138
4139 #[test]
4140 fn restart_policy_default_routes_through_lifted_default() {
4141 // Composition pin: the [`Default for RestartPolicy`] impl's return
4142 // arm must route through the substrate-canonical
4143 // [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const` rather
4144 // than a raw `Self::Permanent` arm. Prior to the lift the impl
4145 // carried an inline `Self::Permanent` with no compile-time link
4146 // back to the OTP-shape supervisor-tree default set whose three
4147 // per-`:supervisor` halves already rode through lifted constants
4148 // — so a future coherent rebrand of the set would have had to
4149 // migrate three halves through typed constants and this fourth
4150 // through a raw enum arm in lockstep or the supervisor-level and
4151 // child-level defaults would silently drift apart. Byte-parity
4152 // against the lifted constant closes the split. Peer of the
4153 // sibling
4154 // [`restart_strategy_default_routes_through_lifted_default`]
4155 // composition pin on the per-`:supervisor` `:estrategia` axis.
4156 assert_eq!(RestartPolicy::default(), SUPERVISOR_CHILD_RESTART_DEFAULT);
4157 }
4158
4159 #[test]
4160 fn child_spec_serde_default_restart_routes_through_lifted_default() {
4161 // Composition pin: the serde-side `#[serde(default)]` on
4162 // [`ChildSpec::restart`] — the wire-format author-omitted
4163 // `:children :restart` arm — must resolve onto the substrate-
4164 // canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const`
4165 // (via the [`Default for RestartPolicy`] impl the sibling
4166 // `restart_policy_default_routes_through_lifted_default` pin
4167 // already routes onto the constant). Structurally: a `ChildSpec`
4168 // deserialized from a payload that omits the `restart` key must
4169 // yield a `restart` field byte-equal to the lifted constant, so
4170 // the wire-format author-omitted arm and the
4171 // [`RestartPolicy::default`] impl arm cannot silently split on any
4172 // future default rebrand. Peer of the sibling
4173 // [`supervisor_spec_default_estrategia_routes_through_lifted_default`]
4174 // / [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
4175 // / [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
4176 // byte-parity pins on the per-`:supervisor` halves of the same
4177 // author-omitted-slot resolution surface.
4178 let omitted: ChildSpec = serde_json::from_str(r#"{"caixa":"worker","versao":"^0.1"}"#)
4179 .expect("ChildSpec must deserialize with the restart key omitted");
4180 assert_eq!(
4181 omitted.restart(),
4182 SUPERVISOR_CHILD_RESTART_DEFAULT,
4183 "an author-omitted :children :restart slot must degrade onto \
4184 the SUPERVISOR_CHILD_RESTART_DEFAULT typed pub const (got \
4185 {:?}, expected {:?})",
4186 omitted.restart(),
4187 SUPERVISOR_CHILD_RESTART_DEFAULT,
4188 );
4189 }
4190
4191 #[test]
4192 fn supervisor_max_restarts_cap_pins_canonical_value() {
4193 // The SUPERVISOR_MAX_RESTARTS_MAX constant pins the value at
4194 // 1000 — the same ceiling the peer
4195 // POLICY_BREAKER_MAX_FAILURES_MAX cap carries on the
4196 // `:politicas :circuit-breaker :max-failures` axis (both are
4197 // "trip the next-higher protection layer after N events in a
4198 // rolling window" counters with identical
4199 // degenerate-at-the-high-end shape; uniform top edge so the
4200 // M4 CR materializers and the wasm-operator reconciler reach
4201 // for either field knowing the value is in `1..=1000`). Two
4202 // orders of magnitude above every documented Erlang/OTP /
4203 // Elixir / Riak Core / RabbitMQ production-playbook
4204 // recommendation band and below the clearly-pathological
4205 // "effectively no escalation" floor (10_000, 100_000,
4206 // u32::MAX). Pinning the literal value here surfaces a future
4207 // drift (a relaxation to 10_000, a tightening to 100) as a
4208 // deliberate test edit, not a silent contract narrowing.
4209 assert_eq!(SUPERVISOR_MAX_RESTARTS_MAX, 1000);
4210 }
4211
4212 #[test]
4213 fn validate_rejects_empty_child_name() {
4214 let s = SupervisorSpec {
4215 children: vec![child("", "^0.1", RestartPolicy::Permanent)],
4216 ..SupervisorSpec::default()
4217 };
4218 assert_eq!(s.validate().unwrap_err(), SupervisorError::EmptyChildName);
4219 }
4220
4221 #[test]
4222 fn validate_rejects_empty_child_version() {
4223 let s = SupervisorSpec {
4224 children: vec![child("w", "", RestartPolicy::Permanent)],
4225 ..SupervisorSpec::default()
4226 };
4227 assert!(matches!(
4228 s.validate().unwrap_err(),
4229 SupervisorError::EmptyChildVersion { .. }
4230 ));
4231 }
4232
4233 // ── value-shape: parse-as-VersionReq on :children :versao ─────────────
4234
4235 #[test]
4236 fn validate_rejects_invalid_child_versao_requirement() {
4237 // The fail-before-pass-after pin: a non-empty but malformed
4238 // semver requirement (`"^bad-version"`) silently passed
4239 // `validate()` on every pre-gate codebase because the prior
4240 // shape only refused the empty string. The parse failure
4241 // surfaced far downstream at lacre-resolve time with a
4242 // `semver::Error` that didn't name which `:children` entry
4243 // carried the typo. The new gate moves the check to caixa-build
4244 // time at the source caixa.lisp — the third `:versao` typed
4245 // axis (`:children`) joins `:deps` and `:membros` (9888b13) at
4246 // structural parity.
4247 let s = SupervisorSpec {
4248 children: vec![
4249 child("worker", "^0.1", RestartPolicy::Permanent),
4250 child("cache", "^bad-version", RestartPolicy::Transient),
4251 ],
4252 ..SupervisorSpec::default()
4253 };
4254 let err = s.validate().unwrap_err();
4255 assert!(
4256 matches!(
4257 err,
4258 SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
4259 if caixa == "cache" && versao == "^bad-version"
4260 ),
4261 "got {err:?}"
4262 );
4263 }
4264
4265 #[test]
4266 fn validate_rejects_child_versao_with_double_caret_typo() {
4267 // `"^^0.1"` is the canonical doubled-caret typo — looks
4268 // Cargo-shaped on first glance but fails the parser because
4269 // semver doesn't accept stacked operators. Pin this
4270 // adjacent-shape footgun explicitly so a future relaxation that
4271 // accepts "looks-canonical-but-isn't" forms surfaces here.
4272 let s = SupervisorSpec {
4273 children: vec![child("worker", "^^0.1", RestartPolicy::Permanent)],
4274 ..SupervisorSpec::default()
4275 };
4276 let err = s.validate().unwrap_err();
4277 assert!(
4278 matches!(
4279 err,
4280 SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
4281 if caixa == "worker" && versao == "^^0.1"
4282 ),
4283 "got {err:?}"
4284 );
4285 }
4286
4287 #[test]
4288 fn validate_rejects_child_versao_with_v_prefixed_tag() {
4289 // `"v0.1"` is the canonical "git-tag-shape leaking into the
4290 // semver requirement slot" typo — an author copies the
4291 // publish-side git-tag string verbatim into `:versao`, but
4292 // Cargo's semver parser rejects the leading `v`. Same
4293 // adjacent-shape footgun pinned for `:membros :versao`
4294 // (9888b13).
4295 let s = SupervisorSpec {
4296 children: vec![child("worker", "v0.1", RestartPolicy::Permanent)],
4297 ..SupervisorSpec::default()
4298 };
4299 let err = s.validate().unwrap_err();
4300 assert!(
4301 matches!(
4302 err,
4303 SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
4304 if caixa == "worker" && versao == "v0.1"
4305 ),
4306 "got {err:?}"
4307 );
4308 }
4309
4310 #[test]
4311 fn validate_accepts_canonical_child_versao_forms() {
4312 // The Cargo-shaped requirement forms `:deps :versao` and
4313 // `:membros :versao` already accept via
4314 // `crate::parse_requirement` must pass the children gate
4315 // without re-validating at the resolver layer. Pin every leg so
4316 // a future tightening of the canonical set surfaces here as a
4317 // test failure.
4318 for form in [
4319 "^0.1", // caret — minor-range pin (the most common shape)
4320 "~0.1.2", // tilde — patch-range pin
4321 "0.1.0", // exact — single-version pin
4322 "*", // wildcard — any version (semver::VersionReq::STAR)
4323 ">=0.1, <2", // multi-range — comma-separated comparators
4324 ] {
4325 let s = SupervisorSpec {
4326 children: vec![child("worker", form, RestartPolicy::Permanent)],
4327 ..SupervisorSpec::default()
4328 };
4329 s.validate()
4330 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
4331 }
4332 }
4333
4334 #[test]
4335 fn child_versao_empty_takes_precedence_over_invalid() {
4336 // Order pin: the existing `EmptyChildVersion` diagnostic (which
4337 // doesn't try to parse) fires before the new
4338 // `ChildVersaoInvalid` parse-side diagnostic, so an empty
4339 // `:versao` keeps its narrower error message —
4340 // `parse_requirement` would also reject `""`, but the
4341 // empty-string arm is the more self-locating diagnostic for the
4342 // author. Same ordering discipline as
4343 // `membro_versao_empty_takes_precedence_over_invalid` in
4344 // aplicacao.rs.
4345 let s = SupervisorSpec {
4346 children: vec![child("worker", "", RestartPolicy::Permanent)],
4347 ..SupervisorSpec::default()
4348 };
4349 let err = s.validate().unwrap_err();
4350 assert!(
4351 matches!(err, SupervisorError::EmptyChildVersion { ref caixa } if caixa == "worker"),
4352 "got {err:?}"
4353 );
4354 }
4355
4356 #[test]
4357 fn child_versao_invalid_fires_before_duplicate_check() {
4358 // Order pin: a malformed requirement on a non-duplicate entry
4359 // surfaces *its own* diagnostic (which names the offending
4360 // `:versao` string), even when a later entry would otherwise
4361 // collapse onto an earlier name. The per-entry shape gate runs
4362 // inline before the duplicate-key insert — parallel to
4363 // `membro_versao_invalid_fires_before_duplicate_check` in
4364 // aplicacao.rs and the b0c8389 / c4213a4 ordering discipline.
4365 let s = SupervisorSpec {
4366 children: vec![
4367 child("worker", "^bad", RestartPolicy::Permanent),
4368 child("cache", "^0.1", RestartPolicy::Transient),
4369 child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
4370 ],
4371 ..SupervisorSpec::default()
4372 };
4373 let err = s.validate().unwrap_err();
4374 assert!(
4375 matches!(
4376 err,
4377 SupervisorError::ChildVersaoInvalid { ref caixa, .. } if caixa == "worker"
4378 ),
4379 "got {err:?}"
4380 );
4381 }
4382
4383 #[test]
4384 fn child_versao_invalid_diagnostic_carries_offending_versao() {
4385 // The diagnostic-shape pin: the error names the offending
4386 // `:versao` value verbatim so the author can grep their
4387 // caixa.lisp without re-running the build, and carries a
4388 // non-empty `reason` from `semver::VersionReq::parse` so the
4389 // parser's own wording flows through to the diagnostic.
4390 let s = SupervisorSpec {
4391 children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
4392 ..SupervisorSpec::default()
4393 };
4394 let err = s.validate().unwrap_err();
4395 let SupervisorError::ChildVersaoInvalid {
4396 caixa,
4397 versao,
4398 reason,
4399 } = err
4400 else {
4401 panic!("expected ChildVersaoInvalid, got other variant");
4402 };
4403 assert_eq!(caixa, "worker");
4404 assert_eq!(versao, "not-a-req");
4405 assert!(
4406 !reason.is_empty(),
4407 "ChildVersaoInvalid `reason` must carry the parser's wording verbatim"
4408 );
4409 }
4410
4411 // ── value-shape: DNS-1123 label rule on :children :caixa ──────────────
4412
4413 #[test]
4414 fn validate_rejects_child_caixa_with_uppercase() {
4415 // The canonical "I copied the Servico's display name verbatim"
4416 // typo — child caixa names are lowercase per K8s DNS-1123 label
4417 // rule. The diagnostic names the offending name and suggests the
4418 // lower-cased fix in one edit, mirroring the
4419 // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0).
4420 let s = SupervisorSpec {
4421 children: vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
4422 ..SupervisorSpec::default()
4423 };
4424 let err = s.validate().unwrap_err();
4425 let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
4426 panic!("expected ChildCaixaInvalid, got other variant");
4427 };
4428 assert_eq!(caixa, "Worker");
4429 assert!(
4430 reason.contains("uppercase"),
4431 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
4432 );
4433 assert!(
4434 reason.contains("\"worker\""),
4435 "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
4436 );
4437 }
4438
4439 #[test]
4440 fn validate_rejects_child_caixa_with_underscore() {
4441 // The canonical "I'm thinking of a Python module / Postgres
4442 // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
4443 // label schema. K8s rejects `metadata.name: my_worker` at
4444 // admission time with an opaque `field is invalid` (no source-
4445 // citing diagnostic). The gate moves it to caixa-build time.
4446 let s = SupervisorSpec {
4447 children: vec![child("my_worker", "^0.1", RestartPolicy::Permanent)],
4448 ..SupervisorSpec::default()
4449 };
4450 let err = s.validate().unwrap_err();
4451 assert!(
4452 matches!(
4453 err,
4454 SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
4455 if caixa == "my_worker" && reason.contains('_')
4456 ),
4457 "got {err:?}"
4458 );
4459 }
4460
4461 #[test]
4462 fn validate_rejects_child_caixa_with_dot() {
4463 // A `:children :caixa` entry is a single DNS-1123 label, not a
4464 // subdomain. The K8s Service / ComputeUnit `metadata.name` rules
4465 // forbid dots. Same shape as `rejects_membro_caixa_with_dot`
4466 // (3f9d7a0) on the peer name axis.
4467 let s = SupervisorSpec {
4468 children: vec![child("team.worker", "^0.1", RestartPolicy::Permanent)],
4469 ..SupervisorSpec::default()
4470 };
4471 let err = s.validate().unwrap_err();
4472 assert!(
4473 matches!(
4474 err,
4475 SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
4476 if caixa == "team.worker" && reason.contains('.')
4477 ),
4478 "got {err:?}"
4479 );
4480 }
4481
4482 #[test]
4483 fn validate_rejects_child_caixa_with_leading_hyphen() {
4484 // DNS-1123 / DNS-1035 boundary rule: labels must start and end
4485 // with an alphanumeric. The K8s apiserver rejects `-worker`
4486 // outright; the renderer would emit a `metadata.name: "-worker"`
4487 // that fails admission far from the source caixa.lisp.
4488 let s = SupervisorSpec {
4489 children: vec![child("-worker", "^0.1", RestartPolicy::Permanent)],
4490 ..SupervisorSpec::default()
4491 };
4492 let err = s.validate().unwrap_err();
4493 assert!(
4494 matches!(
4495 err,
4496 SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
4497 if caixa == "-worker" && reason.contains("start and end")
4498 ),
4499 "got {err:?}"
4500 );
4501 }
4502
4503 #[test]
4504 fn validate_rejects_child_caixa_with_trailing_hyphen() {
4505 // The symmetric arm of the boundary rule. Pin separately so
4506 // both ends of the label are covered against a future relaxation
4507 // that only checks one boundary.
4508 let s = SupervisorSpec {
4509 children: vec![child("worker-", "^0.1", RestartPolicy::Permanent)],
4510 ..SupervisorSpec::default()
4511 };
4512 let err = s.validate().unwrap_err();
4513 assert!(
4514 matches!(
4515 err,
4516 SupervisorError::ChildCaixaInvalid { ref caixa, .. }
4517 if caixa == "worker-"
4518 ),
4519 "got {err:?}"
4520 );
4521 }
4522
4523 #[test]
4524 fn validate_rejects_child_caixa_with_unicode() {
4525 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
4526 // (`xn--…`) by the author before it reaches K8s. The byte-by-
4527 // byte ASCII validity check rejects multi-byte UTF-8 sequences
4528 // by the first byte that fails the `[a-z0-9-]` predicate.
4529 let s = SupervisorSpec {
4530 children: vec![child("café", "^0.1", RestartPolicy::Permanent)],
4531 ..SupervisorSpec::default()
4532 };
4533 let err = s.validate().unwrap_err();
4534 assert!(
4535 matches!(
4536 err,
4537 SupervisorError::ChildCaixaInvalid { ref caixa, .. }
4538 if caixa == "café"
4539 ),
4540 "got {err:?}"
4541 );
4542 }
4543
4544 #[test]
4545 fn validate_rejects_child_caixa_with_whitespace() {
4546 // Whitespace is the canonical "I pasted from a sketch / doc"
4547 // footgun. The apiserver rejects every `metadata.name` value
4548 // carrying whitespace; pin the gate fires at the right boundary.
4549 let s = SupervisorSpec {
4550 children: vec![child("my worker", "^0.1", RestartPolicy::Permanent)],
4551 ..SupervisorSpec::default()
4552 };
4553 let err = s.validate().unwrap_err();
4554 assert!(
4555 matches!(
4556 err,
4557 SupervisorError::ChildCaixaInvalid { ref caixa, .. }
4558 if caixa == "my worker"
4559 ),
4560 "got {err:?}"
4561 );
4562 }
4563
4564 #[test]
4565 fn validate_rejects_child_caixa_too_long() {
4566 // The 64-byte boundary pin. DNS-1123 / DNS-1035 cap labels at
4567 // 63 bytes; the K8s apiserver rejects every `metadata.name`
4568 // axis over the limit at admission time. The diagnostic names
4569 // both the cap and the actual length so the author can shorten
4570 // in one edit, mirroring `rejects_membro_caixa_too_long`
4571 // (3f9d7a0) and `rejects_placement_cluster_too_long` (6cbb900).
4572 let too_long = "a".repeat(64);
4573 let s = SupervisorSpec {
4574 children: vec![child(&too_long, "^0.1", RestartPolicy::Permanent)],
4575 ..SupervisorSpec::default()
4576 };
4577 let err = s.validate().unwrap_err();
4578 let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
4579 panic!("expected ChildCaixaInvalid, got other variant");
4580 };
4581 assert_eq!(caixa, too_long);
4582 assert!(
4583 reason.contains("63"),
4584 "diagnostic must name the 63-byte cap (got: {reason:?})"
4585 );
4586 assert!(
4587 reason.contains("64"),
4588 "diagnostic must name the actual length (got: {reason:?})"
4589 );
4590 }
4591
4592 #[test]
4593 fn child_caixa_max_length_validates() {
4594 // The 63-byte boundary control pin — exactly-at-the-cap is
4595 // accepted, mirroring `membro_caixa_max_length_validates`
4596 // (3f9d7a0) and `placement_cluster_max_length_validates`
4597 // (6cbb900). Pinned separately so a future off-by-one tightening
4598 // surfaces here.
4599 let max_label = "a".repeat(63);
4600 let s = SupervisorSpec {
4601 children: vec![child(&max_label, "^0.1", RestartPolicy::Permanent)],
4602 ..SupervisorSpec::default()
4603 };
4604 s.validate().unwrap();
4605 }
4606
4607 #[test]
4608 fn validate_accepts_canonical_child_caixa_forms() {
4609 // The realistic shapes a supervised child's `:caixa` carries —
4610 // single-word `worker`, version-suffixed `cache-v2`, single-char
4611 // `a`, two-char `db`, digit-start `2-pool`, longer hyphen-joined
4612 // `payment-retry`, all-digit `0`. Pin every leg so a future
4613 // tightening (e.g. requiring a leading lowercase letter) surfaces
4614 // here as a test failure. Mirrors `accepts_canonical_membro_caixa_forms`
4615 // (3f9d7a0) and `accepts_canonical_placement_cluster_forms`
4616 // (6cbb900).
4617 for form in [
4618 "worker",
4619 "cache-v2",
4620 "a",
4621 "db",
4622 "2-pool",
4623 "payment-retry",
4624 "0",
4625 ] {
4626 let s = SupervisorSpec {
4627 children: vec![child(form, "^0.1", RestartPolicy::Permanent)],
4628 ..SupervisorSpec::default()
4629 };
4630 s.validate()
4631 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
4632 }
4633 }
4634
4635 #[test]
4636 fn child_caixa_empty_takes_precedence_over_invalid() {
4637 // Order pin: the existing `EmptyChildName` diagnostic (which
4638 // doesn't try to parse the DNS-1123 shape) fires before the new
4639 // `ChildCaixaInvalid` per-axis gate, so an empty `:caixa` keeps
4640 // its narrower error message — `is_dns_1123_label` would reject
4641 // the empty string too (boundary check on the first byte), but
4642 // the empty-string arm is the more self-locating diagnostic for
4643 // the author. Same ordering discipline as
4644 // `membro_caixa_empty_takes_precedence_over_invalid` in
4645 // aplicacao.rs.
4646 let s = SupervisorSpec {
4647 children: vec![child("", "^0.1", RestartPolicy::Permanent)],
4648 ..SupervisorSpec::default()
4649 };
4650 let err = s.validate().unwrap_err();
4651 assert_eq!(err, SupervisorError::EmptyChildName);
4652 }
4653
4654 #[test]
4655 fn child_caixa_invalid_fires_before_versao_check() {
4656 // Order pin: the per-axis shape gate runs inline before the
4657 // per-entry versao check, so a malformed `:caixa` on an entry
4658 // whose `:versao` would also fail surfaces the more self-
4659 // locating name-axis diagnostic first. Parallel to
4660 // `membro_versao_invalid_fires_before_duplicate_check` (9888b13)
4661 // and `placement_cluster_invalid_fires_before_duplicate_check`
4662 // (6cbb900).
4663 let s = SupervisorSpec {
4664 children: vec![child("My_Worker", "", RestartPolicy::Permanent)],
4665 ..SupervisorSpec::default()
4666 };
4667 let err = s.validate().unwrap_err();
4668 assert!(
4669 matches!(
4670 err,
4671 SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "My_Worker"
4672 ),
4673 "got {err:?}"
4674 );
4675 }
4676
4677 #[test]
4678 fn child_caixa_invalid_fires_before_duplicate_check() {
4679 // Order pin: a malformed name on a non-duplicate entry surfaces
4680 // its own diagnostic, even when a later entry would otherwise
4681 // collapse onto an earlier name. The per-entry shape gate runs
4682 // inline before the duplicate-key HashSet insert, mirroring
4683 // `placement_cluster_invalid_fires_before_duplicate_check`
4684 // (6cbb900).
4685 let s = SupervisorSpec {
4686 children: vec![
4687 child("Worker", "^0.1", RestartPolicy::Permanent),
4688 child("cache", "^0.1", RestartPolicy::Transient),
4689 child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
4690 ],
4691 ..SupervisorSpec::default()
4692 };
4693 let err = s.validate().unwrap_err();
4694 assert!(
4695 matches!(
4696 err,
4697 SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "Worker"
4698 ),
4699 "got {err:?}"
4700 );
4701 }
4702
4703 #[test]
4704 fn child_caixa_invalid_diagnostic_carries_offending_caixa() {
4705 // The diagnostic-shape pin: the error names the offending
4706 // `:caixa` verbatim plus a non-empty parser-shaped `reason` so
4707 // the author can grep their caixa.lisp without re-running the
4708 // build. Mirrors the diagnostic-shape sweep on every prior
4709 // value-shape gate (3f9d7a0, 6cbb900, c7d05ec).
4710 let s = SupervisorSpec {
4711 children: vec![child("My_Worker", "^0.1", RestartPolicy::Permanent)],
4712 ..SupervisorSpec::default()
4713 };
4714 let err = s.validate().unwrap_err();
4715 let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
4716 panic!("expected ChildCaixaInvalid, got other variant");
4717 };
4718 assert_eq!(caixa, "My_Worker");
4719 assert!(
4720 !reason.is_empty(),
4721 "ChildCaixaInvalid `reason` must carry the parser's wording verbatim"
4722 );
4723 }
4724
4725 // ── value-shape: zero restart_window + duplicate child names ──────────
4726
4727 #[test]
4728 fn validate_accepts_none_restart_window() {
4729 // Omitted `:restart-window` is the "never reset" sentinel —
4730 // valid by design. Mirrors :limits axes where None = unbounded.
4731 let s = SupervisorSpec {
4732 restart_window: None,
4733 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4734 ..SupervisorSpec::default()
4735 };
4736 s.validate().unwrap();
4737 }
4738
4739 #[test]
4740 fn validate_rejects_zero_restart_window() {
4741 // Same "0 means the opposite of what you think" footgun closed
4742 // for :politicas :timeout (Envoy treats 0s as infinite) and
4743 // :limits :wall-clock (wasmtime traps before the call starts).
4744 // Erlang/OTP's MaxIntensity/Period requires Period > 0.
4745 let s = SupervisorSpec {
4746 restart_window: Some(Duration::ZERO),
4747 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4748 ..SupervisorSpec::default()
4749 };
4750 assert_eq!(
4751 s.validate().unwrap_err(),
4752 SupervisorError::RestartWindowZero
4753 );
4754 }
4755
4756 // ── value-shape: integer-ms canonical-form on :restart-window ─────────
4757 //
4758 // The fourth (and last) typed-`Duration` axis in caixa-core to get
4759 // the integer-millisecond canonical-form gate — peer with
4760 // `:limits :wall-clock` (82fc3ef), `:politicas :timeout` (a4ae535),
4761 // and `:politicas :circuit-breaker :window` (a4ae535). The serde
4762 // path is already gated at the shared codec layer (see
4763 // `restart_window_serde_rejects_fractional_seconds`); this arm
4764 // closes the programmatic-struct-literal path the codec gate can't
4765 // see.
4766
4767 #[test]
4768 fn validate_rejects_sub_millisecond_restart_window() {
4769 // The fail-before-pass-after pin: a programmatic
4770 // `Duration::from_micros(1500)` (= 1_500_000 ns) silently passed
4771 // `validate` on every pre-gate codebase, then truncated to
4772 // `as_millis() == 1` on first serialize — the shared codec
4773 // emits `"1ms"`, parses it back to `Duration::from_millis(1)` =
4774 // 1_000_000 ns, the typed `restart_window` no longer matches
4775 // its rendered form.
4776 let s = SupervisorSpec {
4777 restart_window: Some(Duration::from_micros(1500)),
4778 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4779 ..SupervisorSpec::default()
4780 };
4781 match s.validate().unwrap_err() {
4782 SupervisorError::RestartWindowNotCanonical { window } => {
4783 assert_eq!(window, Duration::from_micros(1500));
4784 }
4785 other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
4786 }
4787 }
4788
4789 #[test]
4790 fn validate_rejects_one_nanosecond_restart_window() {
4791 // The far-sub-ms case: `Duration::from_nanos(1)` is non-zero
4792 // (so `RestartWindowZero` doesn't fire) but `as_millis() == 0`,
4793 // so the shared codec emits the literal `"0s"` — the next
4794 // serde round-trip would parse back to `Duration::ZERO`, which
4795 // the `RestartWindowZero` arm then rejects on re-validate. The
4796 // canonical-form gate at this layer surfaces a self-locating
4797 // diagnostic naming the offending Duration verbatim rather
4798 // than a downstream `RestartWindowZero` whose remediation
4799 // points at omitting the slot.
4800 let s = SupervisorSpec {
4801 restart_window: Some(Duration::from_nanos(1)),
4802 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4803 ..SupervisorSpec::default()
4804 };
4805 match s.validate().unwrap_err() {
4806 SupervisorError::RestartWindowNotCanonical { window } => {
4807 assert_eq!(window, Duration::from_nanos(1));
4808 }
4809 other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
4810 }
4811 }
4812
4813 #[test]
4814 fn validate_rejects_nanosecond_past_canonical_boundary_restart_window() {
4815 // The 1-ns-past-1ms boundary case: a `Duration` carrying
4816 // 1_000_001 ns is structurally past the integer-ms granularity
4817 // floor — `subsec_nanos() % 1_000_000 == 1`. The codec round-
4818 // trip would truncate to `1ms` and the consumer would observe
4819 // a 1-ns drift on every emit. Same boundary the peer
4820 // `validate_rejects_nanosecond_past_canonical_boundary` test
4821 // in limits.rs pins for the `:limits :wall-clock` axis.
4822 let w = Duration::from_nanos(1_000_001);
4823 let s = SupervisorSpec {
4824 restart_window: Some(w),
4825 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4826 ..SupervisorSpec::default()
4827 };
4828 assert_eq!(
4829 s.validate().unwrap_err(),
4830 SupervisorError::RestartWindowNotCanonical { window: w }
4831 );
4832 }
4833
4834 #[test]
4835 fn validate_accepts_integer_millisecond_restart_window_values() {
4836 // The positive-control sweep: every `Duration` the shared
4837 // codec can round-trip losslessly — the canonical
4838 // `<integer>{ms,s,m,h}` set the codec's `render` / `parse`
4839 // pair emits and accepts — passes `validate` without
4840 // surfacing the new canonical-form arm. Mirrors
4841 // `validate_accepts_integer_millisecond_wall_clock_values` on
4842 // the sibling `:limits :wall-clock` axis.
4843 for w in [
4844 Duration::from_millis(1),
4845 Duration::from_millis(500),
4846 Duration::from_millis(1500),
4847 Duration::from_secs(1),
4848 Duration::from_secs(30),
4849 Duration::from_secs(60),
4850 Duration::from_secs(120),
4851 Duration::from_secs(3600),
4852 ] {
4853 let s = SupervisorSpec {
4854 restart_window: Some(w),
4855 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4856 ..SupervisorSpec::default()
4857 };
4858 s.validate()
4859 .unwrap_or_else(|e| panic!("integer-ms {w:?} must validate, got {e:?}"));
4860 }
4861 }
4862
4863 #[test]
4864 fn validate_restart_window_zero_takes_precedence_over_canonical_gate() {
4865 // Cross-arm ordering pin: `Duration::ZERO` has
4866 // `subsec_nanos() == 0` and would otherwise pass the
4867 // canonical-form arm — the zero-floor arm must fire first so
4868 // the more self-locating `RestartWindowZero` diagnostic (with
4869 // its omit-axis remediation directly named) leads. Same
4870 // posture every peer zero-then-shape gate uses
4871 // (`WallClockZero` → `WallClockNotCanonical`,
4872 // `PolicyTimeoutZero` → `PolicyTimeoutNotCanonical`,
4873 // `PolicyBreakerZeroWindow` → `PolicyBreakerWindowNotCanonical`).
4874 let s = SupervisorSpec {
4875 restart_window: Some(Duration::ZERO),
4876 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4877 ..SupervisorSpec::default()
4878 };
4879 assert_eq!(
4880 s.validate().unwrap_err(),
4881 SupervisorError::RestartWindowZero
4882 );
4883 }
4884
4885 #[test]
4886 fn restart_window_canonical_diagnostic_carries_offending_duration() {
4887 // Diagnostic-shape pin: the canonical-form arm names the
4888 // offending `Duration` verbatim so the author's grep lands on
4889 // the field's value, not a generic "duration not canonical"
4890 // message. Same shape every other typed-canonical-form arm
4891 // on this surface carries (`WallClockNotCanonical` carries
4892 // the offending `Duration` verbatim,
4893 // `PolicyTimeoutNotCanonical` carries the offending
4894 // `Duration` verbatim).
4895 let w = Duration::from_micros(500);
4896 let s = SupervisorSpec {
4897 restart_window: Some(w),
4898 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4899 ..SupervisorSpec::default()
4900 };
4901 let err = s.validate().unwrap_err();
4902 let msg = err.to_string();
4903 assert!(
4904 msg.contains("500"),
4905 "diagnostic must carry the offending magnitude verbatim (got {msg:?})"
4906 );
4907 assert!(
4908 msg.contains("sub-millisecond"),
4909 "diagnostic must name the sub-millisecond residue class (got {msg:?})"
4910 );
4911 }
4912
4913 #[test]
4914 fn restart_window_validated_value_round_trips_through_codec() {
4915 // The structural property the canonical-ms gate enforces:
4916 // every `SupervisorSpec::restart_window` past
4917 // `SupervisorSpec::validate` round-trips losslessly through
4918 // the shared duration codec (serialize → string →
4919 // deserialize → equal value). Pin this end-to-end so a future
4920 // change to either side (the validate gate's accepted
4921 // granularity, the codec's parse/render unit set) that breaks
4922 // the alignment surfaces here. Peer of
4923 // `wall_clock_validated_value_round_trips_through_codec` on
4924 // the sibling `:limits :wall-clock` axis.
4925 for w in [
4926 Duration::from_millis(1),
4927 Duration::from_millis(1500),
4928 Duration::from_secs(30),
4929 Duration::from_secs(3600),
4930 ] {
4931 let s = SupervisorSpec {
4932 restart_window: Some(w),
4933 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4934 ..SupervisorSpec::default()
4935 };
4936 s.validate().unwrap();
4937 let json = serde_json::to_string(&s).unwrap();
4938 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
4939 assert_eq!(back.restart_window, Some(w));
4940 }
4941 }
4942
4943 // ── value-shape: upper cap on :restart-window ─────────────────────────
4944 //
4945 // The fourth (and last) typed-`Duration` axis in caixa-core to get
4946 // the 1h upper cap — peer with `:limits :wall-clock` (51e0dbd),
4947 // `:politicas :timeout` (2e8ee7e), and `:politicas
4948 // :circuit-breaker :window` (379a814). Brackets the typed
4949 // `:restart-window` axis structurally: every validated value lies
4950 // in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`, integer-millisecond
4951 // granularity, closing the
4952 // rolling-window-degenerates-to-lifetime-counter footgun the prior
4953 // zero-floor-and-canonical-form-only checks left open.
4954
4955 #[test]
4956 fn validate_rejects_restart_window_above_cap() {
4957 // The fail-before-pass-after pin: 3601s = 1h + 1s is
4958 // structurally one canonical-tick past the
4959 // [`SUPERVISOR_RESTART_WINDOW_MAX`] ceiling (1h = 3600s) — an
4960 // integer-millisecond magnitude the canonical-form arm above
4961 // accepts cleanly, that the shared duration codec round-trips
4962 // losslessly as `"3601s"`, and that silently passed validate on
4963 // every pre-gate codebase because the typed slot's only checks
4964 // were the zero-floor and canonical-form arms. The runtime
4965 // substrate consuming the value (Erlang/OTP's MaxIntensity/
4966 // Period reconciler, the future wasm-operator's per-supervisor
4967 // restart-intensity counter) reaches for a `Duration` so long
4968 // no realistic restart-recovery pattern resets the counter,
4969 // far from the source caixa.lisp.
4970 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
4971 let s = SupervisorSpec {
4972 restart_window: Some(w),
4973 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4974 ..SupervisorSpec::default()
4975 };
4976 assert_eq!(
4977 s.validate().unwrap_err(),
4978 SupervisorError::RestartWindowExceedsCap { window: w }
4979 );
4980 }
4981
4982 #[test]
4983 fn validate_rejects_restart_window_one_millisecond_above_cap() {
4984 // Boundary case: exactly 1ms past the cap (the granularity the
4985 // canonical-form gate enforces). Catches a future "strictly
4986 // less than" half-measure and pins the diagnostic to name the
4987 // offending `Duration` verbatim. Peer of
4988 // `validate_rejects_wall_clock_one_millisecond_above_cap` /
4989 // `rejects_policy_timeout_one_millisecond_above_cap` /
4990 // `rejects_circuit_breaker_window_one_millisecond_above_cap`
4991 // on the sibling typed-`Duration` axes' top edges.
4992 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
4993 let s = SupervisorSpec {
4994 restart_window: Some(w),
4995 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4996 ..SupervisorSpec::default()
4997 };
4998 assert_eq!(
4999 s.validate().unwrap_err(),
5000 SupervisorError::RestartWindowExceedsCap { window: w }
5001 );
5002 }
5003
5004 #[test]
5005 fn validate_rejects_restart_window_far_above_cap() {
5006 // The "obvious authoring footgun" case: a `(:restart-window "24h")`,
5007 // `(:restart-window "7d")`, or any "I want a lifetime counter
5008 // but wrote a `<integer>h` magnitude anyway" typo — values the
5009 // canonical-form arm accepts as integer-millisecond magnitudes,
5010 // the codec round-trips losslessly through serde, but the
5011 // operator's `MaxIntensity / Period` reconciler cannot honor
5012 // as a meaningful rolling window. Until this gate landed
5013 // validate accepted them. Pin the common above-cap values (24h,
5014 // 7d, ~11.5d) so a future relaxation that drops the upper bound
5015 // surfaces here.
5016 for w in [
5017 Duration::from_secs(86_400), // 24h
5018 Duration::from_secs(604_800), // 7d
5019 Duration::from_secs(1_000_000), // ~11.5 days
5020 ] {
5021 let s = SupervisorSpec {
5022 restart_window: Some(w),
5023 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5024 ..SupervisorSpec::default()
5025 };
5026 assert_eq!(
5027 s.validate().unwrap_err(),
5028 SupervisorError::RestartWindowExceedsCap { window: w }
5029 );
5030 }
5031 }
5032
5033 #[test]
5034 fn validate_accepts_restart_window_at_cap() {
5035 // The boundary value — exactly [`SUPERVISOR_RESTART_WINDOW_MAX`]
5036 // (1h) — must validate. The cap is inclusive on the top edge,
5037 // matching the [`crate::LIMITS_WALL_CLOCK_MAX`] /
5038 // [`crate::POLICY_TIMEOUT_MAX`] /
5039 // [`crate::POLICY_BREAKER_WINDOW_MAX`] discipline on the sibling
5040 // capped axes. Pin the boundary explicitly so a future
5041 // off-by-one tightening (`>= SUPERVISOR_RESTART_WINDOW_MAX`
5042 // instead of `>`) surfaces here as a test failure rather than a
5043 // silent contract narrowing.
5044 let s = SupervisorSpec {
5045 restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
5046 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5047 ..SupervisorSpec::default()
5048 };
5049 s.validate()
5050 .expect("restart_window == SUPERVISOR_RESTART_WINDOW_MAX must validate");
5051 }
5052
5053 #[test]
5054 fn validate_accepts_restart_window_typical_values() {
5055 // The documented Erlang/OTP / Elixir / Riak Core / RabbitMQ
5056 // per-supervisor production-playbook band positive-control
5057 // sweep — every value Learn You Some Erlang's `{intensity, 5,
5058 // 60}` worker-supervisor `Period = 60s` default, Elixir's
5059 // `Supervisor` `max_seconds: 5` default, OTP's `supervisor`
5060 // callback module `MaxT = 5..=60` typical, Riak Core's `MaxT ∈
5061 // 10s..=300s`, and RabbitMQ broker-supervisor `MaxT = 5s`
5062 // default recommend (5s..=300s) must pass, plus a sweep
5063 // through the long-tail-flaky-pool band (5m, 15m, 30m, 1h) the
5064 // cap accepts. Mirrors `validate_accepts_wall_clock_typical_values`
5065 // on the sibling `:limits :wall-clock` axis.
5066 for w in [
5067 Duration::from_millis(1),
5068 Duration::from_millis(500),
5069 Duration::from_secs(1),
5070 Duration::from_secs(5), // RabbitMQ broker-supervisor default
5071 Duration::from_secs(10), // Riak Core lower
5072 Duration::from_secs(30),
5073 Duration::from_secs(60), // Learn You Some Erlang default
5074 Duration::from_secs(120), // OTP supervisor MaxT typical
5075 Duration::from_secs(300), // Riak Core upper
5076 Duration::from_secs(900), // 15m
5077 Duration::from_secs(1800),
5078 Duration::from_secs(3600), // exactly 1h, the cap
5079 ] {
5080 let s = SupervisorSpec {
5081 restart_window: Some(w),
5082 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5083 ..SupervisorSpec::default()
5084 };
5085 s.validate()
5086 .unwrap_or_else(|e| panic!("restart_window={w:?} must validate; got {e:?}"));
5087 }
5088 }
5089
5090 #[test]
5091 fn restart_window_zero_takes_precedence_over_cap() {
5092 // The cross-arm ordering pin: `Duration::ZERO` is structurally
5093 // outside both `>= 1ms` (zero-floor) and `<=
5094 // SUPERVISOR_RESTART_WINDOW_MAX` (cap), but the zero-floor
5095 // diagnostic is the more self-locating one (it directly names
5096 // the omit-axis remediation), so the validate gate must fire
5097 // on zero first. Same shape every other zero-then-cap ordering
5098 // on this surface uses (`WallClockZero` then
5099 // `WallClockExceedsCap`, `PolicyTimeoutZero` then
5100 // `PolicyTimeoutExceedsCap`, `PolicyBreakerZeroWindow` then
5101 // `PolicyBreakerWindowExceedsCap`).
5102 let s = SupervisorSpec {
5103 restart_window: Some(Duration::ZERO),
5104 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5105 ..SupervisorSpec::default()
5106 };
5107 assert_eq!(
5108 s.validate().unwrap_err(),
5109 SupervisorError::RestartWindowZero,
5110 "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
5111 );
5112 }
5113
5114 #[test]
5115 fn restart_window_canonical_takes_precedence_over_cap() {
5116 // The cross-arm ordering pin: a `Duration` that is *both*
5117 // sub-millisecond (non-canonical-form) and structurally above
5118 // the cap surfaces the canonical-form diagnostic first,
5119 // because the round-trip-shape break is the more fundamental
5120 // issue (the value can't even round-trip through the codec,
5121 // so the cap diagnostic naming `1ms..=1h` would be misleading
5122 // — there's no integer-ms form of the offending value). Pin
5123 // the order so a future refactor that reorders the arms
5124 // surfaces here as a test failure rather than a silent
5125 // diagnostic regression. Peer of
5126 // `wall_clock_canonical_takes_precedence_over_cap` /
5127 // `policy_timeout_canonical_takes_precedence_over_cap`.
5128 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_nanos(1);
5129 let s = SupervisorSpec {
5130 restart_window: Some(w),
5131 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5132 ..SupervisorSpec::default()
5133 };
5134 assert_eq!(
5135 s.validate().unwrap_err(),
5136 SupervisorError::RestartWindowNotCanonical { window: w },
5137 "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
5138 );
5139 }
5140
5141 #[test]
5142 fn max_restarts_cap_takes_precedence_over_restart_window_cap() {
5143 // The cross-arm ordering pin between the `:max-restarts` cap
5144 // and the sibling `:restart-window` cap. A supervisor carrying
5145 // both an over-cap `max_restarts` AND an over-cap window must
5146 // surface the `MaxRestartsExceedsCap` diagnostic first — the
5147 // cap arm is wired immediately after the zero-restart arm and
5148 // strictly before every window-axis arm (zero / canonical /
5149 // cap), so the offending value the diagnostic names matches
5150 // the order the author would discover the gates by reading
5151 // top-to-bottom through `SupervisorSpec::validate`. Pin the
5152 // order so a future refactor that reorders the arms surfaces
5153 // here as a test failure rather than a silent diagnostic
5154 // regression. Peer of
5155 // `max_restarts_cap_takes_precedence_over_restart_window_gates`
5156 // on the sibling zero / canonical window arms.
5157 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
5158 let s = SupervisorSpec {
5159 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5160 restart_window: Some(w),
5161 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5162 ..SupervisorSpec::default()
5163 };
5164 assert_eq!(
5165 s.validate().unwrap_err(),
5166 SupervisorError::MaxRestartsExceedsCap {
5167 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5168 },
5169 "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
5170 );
5171 }
5172
5173 #[test]
5174 fn restart_window_cap_diagnostic_carries_offending_value() {
5175 // The diagnostic-shape pin: the offending `Duration` is
5176 // carried verbatim into the
5177 // [`SupervisorError::RestartWindowExceedsCap`] variant so the
5178 // surfaced error message names the value the author wrote,
5179 // not just the cap. Same self-locating diagnostic shape every
5180 // other typed-cap arm on this surface carries
5181 // (`WallClockExceedsCap` carries the offending `Duration`
5182 // verbatim, `PolicyTimeoutExceedsCap` carries the offending
5183 // `Duration` verbatim, `PolicyBreakerWindowExceedsCap` carries
5184 // the offending `Duration` verbatim).
5185 let w = Duration::from_secs(7200); // 2h
5186 let s = SupervisorSpec {
5187 restart_window: Some(w),
5188 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5189 ..SupervisorSpec::default()
5190 };
5191 let err = s.validate().unwrap_err();
5192 assert!(
5193 matches!(err, SupervisorError::RestartWindowExceedsCap { window } if window == w),
5194 "got {err:?}"
5195 );
5196 let msg = err.to_string();
5197 assert!(
5198 msg.contains("7200"),
5199 ":supervisor :restart-window cap diagnostic must carry the offending value verbatim (got: {msg})"
5200 );
5201 }
5202
5203 #[test]
5204 fn supervisor_restart_window_cap_pins_canonical_value() {
5205 // The SUPERVISOR_RESTART_WINDOW_MAX constant pins the value at
5206 // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
5207 // shared duration codec emits as a clean canonical string
5208 // (`"<n>h"`). Pinning the literal value here surfaces a future
5209 // drift (a relaxation to 24h, a tightening to 5m) as a
5210 // deliberate test edit, not a silent contract narrowing.
5211 //
5212 // The four typed-`Duration` caps on the validation surface
5213 // (`LIMITS_WALL_CLOCK_MAX` per-process, `POLICY_TIMEOUT_MAX`
5214 // per-edge, `POLICY_BREAKER_WINDOW_MAX` per-breaker,
5215 // `SUPERVISOR_RESTART_WINDOW_MAX` per-supervisor) share a
5216 // single uniform top edge at the codec's largest emitted unit
5217 // — a structural-property invariant the equality assertions
5218 // here enshrine, so a future drift on any of the four
5219 // surfaces as a deliberate test edit. Same shape every other
5220 // typed-cap value pin uses
5221 // (`wall_clock_cap_pins_canonical_value`,
5222 // `policy_timeout_cap_pins_canonical_value`,
5223 // `circuit_breaker_window_cap_pins_canonical_value`).
5224 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, Duration::from_secs(3600));
5225 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX.as_millis(), 3_600_000);
5226 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::LIMITS_WALL_CLOCK_MAX);
5227 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::POLICY_TIMEOUT_MAX);
5228 assert_eq!(
5229 SUPERVISOR_RESTART_WINDOW_MAX,
5230 crate::POLICY_BREAKER_WINDOW_MAX
5231 );
5232 }
5233
5234 #[test]
5235 fn restart_window_cap_value_round_trips_through_codec() {
5236 // The codec round-trip property the cap arm preserves: the
5237 // [`SUPERVISOR_RESTART_WINDOW_MAX`] constant itself round-trips
5238 // through the shared duration codec — every value at the cap
5239 // serializes to the canonical `"1h"` form and parses back
5240 // identically. Pin the round-trip so a future change to the
5241 // codec's unit set or to the cap's magnitude that breaks the
5242 // round-trip property surfaces here. Peer of
5243 // `wall_clock_cap_value_round_trips_through_codec` on the
5244 // sibling `:limits :wall-clock` axis.
5245 let s = SupervisorSpec {
5246 restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
5247 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5248 ..SupervisorSpec::default()
5249 };
5250 s.validate().unwrap();
5251 let json = serde_json::to_string(&s).unwrap();
5252 assert!(
5253 json.contains("\"1h\""),
5254 "SUPERVISOR_RESTART_WINDOW_MAX must serialize to the canonical `\"1h\"` form (got {json})"
5255 );
5256 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5257 assert_eq!(back.restart_window, Some(SUPERVISOR_RESTART_WINDOW_MAX));
5258 }
5259
5260 #[test]
5261 fn validate_rejects_duplicate_child_caixa() {
5262 // Two children with the same :caixa render to two ComputeUnits
5263 // with the same name in the cluster's HelmRelease values —
5264 // one silently overwrites the other. Erlang/OTP's child_spec.id
5265 // is required-unique per supervisor; same set-not-multiset
5266 // discipline applied here as for :membros / :placement
5267 // :clusters / :entrada :paths.
5268 let s = SupervisorSpec {
5269 children: vec![
5270 child("worker", "^0.1", RestartPolicy::Permanent),
5271 child("cache", "^0.1", RestartPolicy::Transient),
5272 child("worker", "^0.2", RestartPolicy::Permanent),
5273 ],
5274 ..SupervisorSpec::default()
5275 };
5276 let err = s.validate().unwrap_err();
5277 assert!(
5278 matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "worker"),
5279 "got {err:?}"
5280 );
5281 }
5282
5283 #[test]
5284 fn validate_duplicate_child_diagnostic_names_first_collision() {
5285 // Iteration walks the :children list in declaration order —
5286 // the diagnostic names the first repeat, deterministically,
5287 // even when multiple names duplicate.
5288 let s = SupervisorSpec {
5289 children: vec![
5290 child("a", "^0.1", RestartPolicy::Permanent),
5291 child("b", "^0.1", RestartPolicy::Permanent),
5292 child("a", "^0.1", RestartPolicy::Permanent),
5293 child("b", "^0.1", RestartPolicy::Permanent),
5294 ],
5295 ..SupervisorSpec::default()
5296 };
5297 let err = s.validate().unwrap_err();
5298 assert!(
5299 matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "a"),
5300 "got {err:?}"
5301 );
5302 }
5303
5304 // ── self-supervision cross-slot gate ──────────────────────────
5305
5306 #[test]
5307 fn validate_no_self_supervision_rejects_self_referential_child() {
5308 // A supervisor whose `:children` lists its own `:nome` is a
5309 // one-node reconciliation cycle — rejected, naming the parent.
5310 let children = vec![
5311 child("worker", "^0.1", RestartPolicy::Permanent),
5312 child("orquestra", "^0.1", RestartPolicy::Permanent),
5313 ];
5314 let err = validate_no_self_supervision(&children, "orquestra").unwrap_err();
5315 assert!(
5316 matches!(err, SupervisorError::ChildSupervisesSelf { ref caixa } if caixa == "orquestra"),
5317 "got {err:?}"
5318 );
5319 }
5320
5321 #[test]
5322 fn validate_no_self_supervision_accepts_distinct_children() {
5323 // Positive control: distinct child names (including a child that
5324 // is itself a supervisor — nested trees are valid OTP) pass.
5325 let children = vec![
5326 child("worker", "^0.1", RestartPolicy::Permanent),
5327 child("sub-tree", "^0.1", RestartPolicy::Permanent),
5328 ];
5329 validate_no_self_supervision(&children, "orquestra").unwrap();
5330 }
5331
5332 #[test]
5333 fn validate_no_self_supervision_empty_children_is_ok() {
5334 // SimpleOneForOne / no-static-children supervisors have nothing
5335 // to self-reference — the gate is vacuously satisfied.
5336 validate_no_self_supervision(&[], "orquestra").unwrap();
5337 }
5338
5339 #[test]
5340 fn validate_simple_one_for_one_skips_uniqueness_check() {
5341 // SimpleOneForOne supervisors carry no static children — the
5342 // duplicate-child loop never runs. A zero-window declaration
5343 // on a SimpleOneForOne supervisor still trips the window check
5344 // (window applies to dynamic children too).
5345 let s = SupervisorSpec {
5346 estrategia: RestartStrategy::SimpleOneForOne,
5347 restart_window: None,
5348 children: vec![],
5349 ..SupervisorSpec::default()
5350 };
5351 s.validate().unwrap();
5352 let s_zero = SupervisorSpec {
5353 estrategia: RestartStrategy::SimpleOneForOne,
5354 restart_window: Some(Duration::ZERO),
5355 children: vec![],
5356 ..SupervisorSpec::default()
5357 };
5358 assert_eq!(
5359 s_zero.validate().unwrap_err(),
5360 SupervisorError::RestartWindowZero
5361 );
5362 }
5363
5364 #[test]
5365 fn validate_zero_window_runs_after_max_restarts_check() {
5366 // Pin the order: max_restarts == 0 fires before
5367 // restart_window == 0s, so an author with both wrong sees the
5368 // counter-axis diagnostic first (matches the order in the
5369 // struct and in the doc comment).
5370 let s = SupervisorSpec {
5371 max_restarts: 0,
5372 restart_window: Some(Duration::ZERO),
5373 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5374 ..SupervisorSpec::default()
5375 };
5376 assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
5377 }
5378
5379 #[test]
5380 fn round_trip_all_strategies() {
5381 for &strat in RestartStrategy::ALL {
5382 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
5383 // shape partition through the [`gen_platform::IsVariant`]
5384 // derive-generated [`RestartStrategy::is_simple_one_for_one`]
5385 // predicate rather than the raw
5386 // `matches!(strat, RestartStrategy::SimpleOneForOne)`
5387 // open-coded pattern-match — same closed-set-typed-enum
5388 // arm-discriminator dispatch discipline the sibling
5389 // [`crate::upgrade::UpgradeInstruction::is_restart`] convergence
5390 // (915a934) extended onto its two paired positive / negated
5391 // `matches!` filter sites, and the sibling
5392 // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
5393 // predicate convergence (766ec63) extended onto the M3 mesh-
5394 // slot per-`:placement` distribution-strategy `matches!`
5395 // discriminator axis. See the sibling
5396 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
5397 // fixture and the peer `manifest::tests::
5398 // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
5399 // fixture — all three sites (the last unlifted
5400 // `matches!`-based arm-discriminator axis on the OTP-shape
5401 // supervisor sibling-restart-strategy closed-set typed enum,
5402 // acknowledged in 915a934's Prior-commits footnote as the
5403 // outstanding follow-up) now consult one typed dispatch on
5404 // the substrate primitive.
5405 let s = SupervisorSpec {
5406 estrategia: strat,
5407 children: if strat.is_simple_one_for_one() {
5408 vec![]
5409 } else {
5410 vec![child("w", "^0.1", RestartPolicy::Permanent)]
5411 },
5412 ..SupervisorSpec::default()
5413 };
5414 let json = serde_json::to_string(&s).unwrap();
5415 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5416 assert_eq!(s, back);
5417 }
5418 }
5419
5420 #[test]
5421 fn round_trip_all_restart_policies() {
5422 for policy in [
5423 RestartPolicy::Permanent,
5424 RestartPolicy::Temporary,
5425 RestartPolicy::Transient,
5426 ] {
5427 let c = child("w", "^0.1", policy);
5428 let json = serde_json::to_string(&c).unwrap();
5429 let back: ChildSpec = serde_json::from_str(&json).unwrap();
5430 assert_eq!(c, back);
5431 }
5432 }
5433
5434 #[test]
5435 fn restart_strategy_is_simple_one_for_one_predicate_partitions_the_arm_set() {
5436 // The fail-before-pass-after pin on the `gen_platform::IsVariant`
5437 // derive's [`RestartStrategy::is_simple_one_for_one`] arm-
5438 // discriminator predicate: [`RestartStrategy::SimpleOneForOne`]
5439 // is the only variant that satisfies `.is_simple_one_for_one()`;
5440 // every static-children-bearing arm (`OneForOne` / `OneForAll`
5441 // / `RestForOne`) returns `false`. This pin makes the partition
5442 // invariant load-bearing at caixa-core test time so a future
5443 // derive regression (a hole that returns `false` for
5444 // `SimpleOneForOne` too, or a byte-collision that flips a second
5445 // variant to `true`) trips here rather than laundering the arm
5446 // at the three test-fixture builder sites (a hole flips the
5447 // `SimpleOneForOne` fixture to carry a non-empty children list
5448 // and the subsequent `SupervisorSpec::validate` would refuse the
5449 // fixture with [`SupervisorError::SimpleOneForOneWithStaticChildren`];
5450 // a collision flips a peer strategy's fixture to carry an empty
5451 // children list and the subsequent `validate` would refuse with
5452 // [`SupervisorError::NoChildren`] — either way, the pin fires
5453 // here, at the derive site, rather than at the fixture-refusal
5454 // site far away). Peer of the sibling
5455 // [`crate::upgrade::tests::upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
5456 // (915a934) pin on the M2 OTP-appup axis and the sibling
5457 // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
5458 // pin on the M0 `:kind` axis.
5459 let cases: &[(RestartStrategy, bool)] = &[
5460 (RestartStrategy::OneForOne, false),
5461 (RestartStrategy::OneForAll, false),
5462 (RestartStrategy::RestForOne, false),
5463 (RestartStrategy::SimpleOneForOne, true),
5464 ];
5465 for (variant, expected) in cases {
5466 assert_eq!(
5467 variant.is_simple_one_for_one(),
5468 *expected,
5469 "RestartStrategy::{variant:?}.is_simple_one_for_one() must \
5470 return {expected} (partition invariant on the \
5471 IsVariant-derived arm-discriminator predicate — every \
5472 test-fixture site that partitions the `:children` slot \
5473 shape on `SimpleOneForOne ↔ non-SimpleOneForOne` keys \
5474 off this typed dispatch, so a derive regression must \
5475 surface here rather than at the fixture-refusal site)"
5476 );
5477 }
5478 }
5479
5480 #[test]
5481 fn restart_strategy_fixture_partition_routes_through_is_simple_one_for_one_predicate() {
5482 // Byte-identity pin on the `SimpleOneForOne ↔ non-SimpleOneForOne`
5483 // fixture-shape partition against the pre-lift
5484 // `matches!(strat, RestartStrategy::SimpleOneForOne)` open-coded
5485 // pattern-match every test-fixture builder site previously
5486 // coupled to inline. Asserts the two projections agree byte-for-
5487 // byte on every arm of the enum, so a future derive regression
5488 // that flipped either predicate's arm-set would surface here at
5489 // caixa-core test time rather than at the three fixture-builder
5490 // sites (`supervisor::tests::round_trip_all_strategies`,
5491 // `supervisor::tests::supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`,
5492 // `manifest::tests::caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`)
5493 // far from the derive site. Same peer-shape byte-identity pin
5494 // every sibling `IsVariant`-derive-routed convergence carries on
5495 // the substrate's closed-set typed-enum surface (peer of
5496 // [`crate::upgrade::tests::validate_restart_exclusive_routes_through_is_restart_predicate`]
5497 // on the M2 OTP-appup axis).
5498 for &strat in RestartStrategy::ALL {
5499 let via_predicate = strat.is_simple_one_for_one();
5500 let via_matches = matches!(strat, RestartStrategy::SimpleOneForOne);
5501 assert_eq!(
5502 via_predicate, via_matches,
5503 "RestartStrategy::{strat:?}: is_simple_one_for_one() must \
5504 byte-equal matches!(_, RestartStrategy::SimpleOneForOne) — \
5505 the pre-lift open-coded pattern and the \
5506 IsVariant-derived predicate are the same axis, \
5507 one typed dispatch"
5508 );
5509 }
5510 }
5511
5512 #[test]
5513 fn duration_codec_round_trip_canonical_units() {
5514 // Note the canonical-form rule: durations serialize to the
5515 // *largest* unit that divides cleanly, so 60s ↔ "1m" and not
5516 // "60s" — but the round-trip preserves the underlying Duration.
5517 let cases = [
5518 ("30s", Duration::from_secs(30)),
5519 ("5m", Duration::from_secs(300)),
5520 ("1h", Duration::from_secs(3600)),
5521 ("500ms", Duration::from_millis(500)),
5522 ];
5523 for (lit, dur) in cases {
5524 let s = SupervisorSpec {
5525 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5526 restart_window: Some(dur),
5527 ..SupervisorSpec::default()
5528 };
5529 let json = serde_json::to_string(&s).unwrap();
5530 assert!(
5531 json.contains(&format!("\"{lit}\"")),
5532 "expected \"{lit}\" in {json}"
5533 );
5534 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5535 assert_eq!(back.restart_window, Some(dur));
5536 }
5537 }
5538
5539 #[test]
5540 fn duration_canonicalizes_to_largest_unit() {
5541 // 60 seconds → "1m" (largest cleanly-divisible unit), but the
5542 // typed Duration still equals 60s on the way back.
5543 let s = SupervisorSpec {
5544 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5545 restart_window: Some(Duration::from_secs(60)),
5546 ..SupervisorSpec::default()
5547 };
5548 let json = serde_json::to_string(&s).unwrap();
5549 assert!(json.contains("\"1m\""), "{json}");
5550 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5551 assert_eq!(back.restart_window, Some(Duration::from_secs(60)));
5552 }
5553
5554 #[test]
5555 fn three_child_one_for_one_validates() {
5556 let s = SupervisorSpec {
5557 estrategia: RestartStrategy::OneForOne,
5558 max_restarts: 5,
5559 restart_window: Some(Duration::from_secs(60)),
5560 children: vec![
5561 child("worker", "^0.1", RestartPolicy::Permanent),
5562 child("cache", "^0.1", RestartPolicy::Transient),
5563 child("scratch", "^0.1", RestartPolicy::Temporary),
5564 ],
5565 };
5566 s.validate().unwrap();
5567 }
5568
5569 #[test]
5570 fn json_uses_pascal_case_for_strategy_and_policy() {
5571 // Variant names are PascalCase by default in serde, matching
5572 // tatara-lisp's enum convention (`:estrategia OneForOne`).
5573 let c = child("w", "^0.1", RestartPolicy::Permanent);
5574 let json = serde_json::to_string(&c).unwrap();
5575 assert!(json.contains("\"Permanent\""));
5576 assert!(!json.contains("\"permanent\""));
5577
5578 let s = SupervisorSpec {
5579 estrategia: RestartStrategy::OneForOne,
5580 children: vec![c],
5581 ..SupervisorSpec::default()
5582 };
5583 let json = serde_json::to_string(&s).unwrap();
5584 assert!(json.contains("\"estrategia\":\"OneForOne\""));
5585 }
5586
5587 // ── shared duration codec: integer-magnitude canonical-form gate ──
5588 //
5589 // The gate lifts the discipline `crate::limits::parse_duration`
5590 // (818dd38) carries on the peer `:limits :wall-clock` codec onto
5591 // the shared codec backing the remaining three typed-duration
5592 // slots: `:supervisor :restart-window`, `:politicas :timeout`, and
5593 // `:politicas :circuit-breaker :window`. Every magnitude `render`
5594 // emits is a non-negative integer with no decimal point and no
5595 // leading sign, so the codec's accepted set must match for
5596 // serialize/deserialize to round-trip without canonical-form
5597 // drift.
5598
5599 #[test]
5600 fn parse_accepts_integer_canonical_units() {
5601 // Pin the happy-path: every canonical author shape `render`
5602 // ever emits parses to the same `Duration` value, so the
5603 // codec's accepted set is at least a superset of its emitted
5604 // set on the canonical-unit axis.
5605 for (lit, dur) in [
5606 ("30s", Duration::from_secs(30)),
5607 ("500ms", Duration::from_millis(500)),
5608 ("2m", Duration::from_secs(120)),
5609 ("1h", Duration::from_secs(3600)),
5610 ("0s", Duration::ZERO),
5611 ] {
5612 assert_eq!(
5613 duration_codec::parse(lit).unwrap(),
5614 dur,
5615 "parse({lit:?}) should be {dur:?}"
5616 );
5617 }
5618 }
5619
5620 #[test]
5621 fn parse_accepts_bare_integer_as_seconds() {
5622 // The `"s" | ""` arm: a bare integer with no unit is read as
5623 // seconds. Pin this so the unit-empty form keeps parsing (it
5624 // renders to `"<n>s"` on serialize — that's a unit-choice
5625 // drift the integer-magnitude gate does NOT close, matching
5626 // the `parse_byte_size` `"1024"` → `"1KiB"` scope decision in
5627 // the peer `:limits :memory` codec).
5628 assert_eq!(
5629 duration_codec::parse("30").unwrap(),
5630 Duration::from_secs(30)
5631 );
5632 }
5633
5634 #[test]
5635 fn parse_rejects_fractional_seconds_with_canonical_form_diagnostic() {
5636 // `"1.5s"` parses as f64 to 1.5 → renders back as `"1500ms"`
5637 // on first serialize — DRIFT. The integer-magnitude gate names
5638 // the offending `"1.5"` verbatim and points at the canonical
5639 // remediation `"1500ms"`.
5640 let err = duration_codec::parse("1.5s").unwrap_err();
5641 assert!(err.contains("\"1.5\""), "missing magnitude in {err:?}");
5642 assert!(
5643 err.contains("not a non-negative integer"),
5644 "missing canonical-form reason in {err:?}"
5645 );
5646 assert!(
5647 err.contains("\"1500ms\""),
5648 "missing canonical-form remediation in {err:?}"
5649 );
5650 }
5651
5652 #[test]
5653 fn parse_rejects_decimal_shaped_integer_seconds() {
5654 // `"1.0s"` is the trickiest drift class: numerically `1.0s` is
5655 // `1s` exactly, so the round-trip looks correct — but the
5656 // emitted canonical form is `"1s"`, not `"1.0s"`. Gate the
5657 // decimal-shape-with-integer-value form so author intent is
5658 // never silently rewritten.
5659 let err = duration_codec::parse("1.0s").unwrap_err();
5660 assert!(err.contains("\"1.0\""), "missing magnitude in {err:?}");
5661 assert!(
5662 err.contains("not a non-negative integer"),
5663 "missing canonical-form reason in {err:?}"
5664 );
5665 }
5666
5667 #[test]
5668 fn parse_rejects_half_unit_minute() {
5669 // `"0.5m"` is the unit-fraction footgun — author writes a
5670 // human-readable half-minute, serde silently rewrites to
5671 // `"30s"` on next emit. The gate names the offending
5672 // magnitude `"0.5"` and points at the integer-in-smaller-unit
5673 // form.
5674 let err = duration_codec::parse("0.5m").unwrap_err();
5675 assert!(err.contains("\"0.5\""), "missing magnitude in {err:?}");
5676 assert!(
5677 err.contains("\"30s\""),
5678 "missing canonical-form remediation in {err:?}"
5679 );
5680 }
5681
5682 #[test]
5683 fn parse_rejects_leading_plus_sign() {
5684 // `u64::from_str` rejects `"+30"` but `f64::from_str` accepts
5685 // it as `30.0` — the prior parser used f64 so `"+30s"` parsed
5686 // cleanly to 30s and round-tripped to `"30s"` on next emit
5687 // (DRIFT). The digit-only gate closes the leading-sign class
5688 // first; the diagnostic names `"+30"` verbatim.
5689 let err = duration_codec::parse("+30s").unwrap_err();
5690 assert!(err.contains("\"+30\""), "missing magnitude in {err:?}");
5691 assert!(
5692 err.contains("not a non-negative integer"),
5693 "missing canonical-form reason in {err:?}"
5694 );
5695 }
5696
5697 #[test]
5698 fn parse_rejects_leading_minus_sign() {
5699 // The former `num < 0.0` arm: `"-30s"` parsed as f64 to -30,
5700 // rejected with `"negative duration in \"-30s\""`. Under the
5701 // integer-magnitude gate the diagnostic is unified — `-30` is
5702 // non-digit-only, f64-numeric, and surfaces with the canonical-
5703 // form reason (no leading `+` / `-` sign) naming the offending
5704 // `"-30"` verbatim. Same diagnostic shape as every other
5705 // rejected non-integer magnitude.
5706 let err = duration_codec::parse("-30s").unwrap_err();
5707 assert!(err.contains("\"-30\""), "missing magnitude in {err:?}");
5708 assert!(
5709 err.contains("not a non-negative integer"),
5710 "missing canonical-form reason in {err:?}"
5711 );
5712 }
5713
5714 #[test]
5715 fn parse_garbage_still_falls_through_to_bad_magnitude() {
5716 // Non-digit-only AND non-numeric (`"--1s"`, `"abc"`) falls
5717 // through to the narrower "bad duration magnitude" arm — the
5718 // canonical-form diagnostic is reserved for the parser-shape
5719 // footgun case, not the "not a number at all" case. Same
5720 // shape `parse_byte_size`'s `BadByteMagnitude` arm carries on
5721 // the peer `:limits :memory` codec.
5722 let err = duration_codec::parse("--1s").unwrap_err();
5723 assert!(
5724 err.contains("bad duration magnitude"),
5725 "expected bad-magnitude wording in {err:?}"
5726 );
5727 }
5728
5729 #[test]
5730 fn parse_digit_only_magnitude_carries_zero_f64_drift() {
5731 // The accepted set is now closed under `u64`-exact integer
5732 // arithmetic: `"500ms"` → `Duration::from_millis(500)` exactly,
5733 // `"3600s"` → `Duration::from_secs(3600)` exactly, `"1h"` →
5734 // `Duration::from_secs(3600)` exactly, no f64 mantissa drift
5735 // possible. Pin the integer-exact arms across the four unit
5736 // suffixes so a future refactor that reaches back for f64
5737 // (`from_secs_f64`, `mul_f64`) surfaces here.
5738 assert_eq!(
5739 duration_codec::parse("3600s").unwrap(),
5740 Duration::from_secs(3600)
5741 );
5742 assert_eq!(
5743 duration_codec::parse("60m").unwrap(),
5744 Duration::from_secs(3600)
5745 );
5746 assert_eq!(
5747 duration_codec::parse("1h").unwrap(),
5748 Duration::from_secs(3600)
5749 );
5750 assert_eq!(
5751 duration_codec::parse("999ms").unwrap(),
5752 Duration::from_millis(999)
5753 );
5754 }
5755
5756 #[test]
5757 fn restart_window_serde_rejects_fractional_seconds() {
5758 // The shared codec backs `SupervisorSpec::restart_window`
5759 // (`with = "duration_codec"`) — so the gate applies on serde
5760 // deserialize for the typed Supervisor slot. A
5761 // `{"restartWindow":"1.5s"}` payload that previously round-
5762 // tripped to a different canonical string on next serialize
5763 // is now refused at deserialize with the integer-magnitude
5764 // diagnostic.
5765 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
5766 "restartWindow":"1.5s",
5767 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
5768 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5769 let msg = err.to_string();
5770 assert!(
5771 msg.contains("not a non-negative integer"),
5772 "expected integer-magnitude diagnostic in {msg:?}"
5773 );
5774 assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
5775 }
5776
5777 #[test]
5778 fn restart_window_serde_rejects_leading_plus() {
5779 // The `u64::from_str` leading-`+` permissiveness gap that
5780 // motivated the digit-only gate (the `f64`-side accepted
5781 // `"+30"`, the prior parser silently round-tripped to `"30s"`)
5782 // is now closed on the shared codec — surfaces as a structured
5783 // diagnostic at the serde layer for every typed-duration slot.
5784 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
5785 "restartWindow":"+30s",
5786 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
5787 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5788 let msg = err.to_string();
5789 assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
5790 assert!(
5791 msg.contains("not a non-negative integer"),
5792 "missing canonical-form reason in {msg:?}"
5793 );
5794 }
5795
5796 #[test]
5797 fn parse_rejects_leading_zero_magnitude() {
5798 // `"030s"` is digit-only, so the existing non-digit-only / sign
5799 // / fractional arm doesn't catch it — `u64::from_str("030")`
5800 // returns `Ok(30)`, so before this gate `"030s"` parsed to
5801 // `Duration::from_secs(30)` and round-tripped through `render`
5802 // to `"30s"` — a *different* canonical string on the next emit,
5803 // breaking the THEORY.md Part V render-determinism contract
5804 // exactly the way `"+30s"` did before the leading-`+` arm
5805 // landed. Peer with the `rate_limit_codec` leading-zero arm
5806 // (4f46830) on the same canonical-form-drift axis.
5807 let err = duration_codec::parse("030s").unwrap_err();
5808 assert!(
5809 err.contains("non-canonical leading zero"),
5810 "expected leading-zero diagnostic in {err:?}"
5811 );
5812 assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
5813 assert!(
5814 err.contains("\"30s\""),
5815 "missing canonical-form remediation in {err:?}"
5816 );
5817 assert!(
5818 err.contains("THEORY.md"),
5819 "missing render-determinism citation in {err:?}"
5820 );
5821 }
5822
5823 #[test]
5824 fn parse_rejects_multi_digit_zero_magnitude() {
5825 // `"00s"` and `"00ms"` are the all-zero leading-zero footgun —
5826 // digit-only, parse losslessly to `Duration::ZERO`, but render
5827 // back to `"0s"` (the single-byte canonical form) on the next
5828 // emit. The leading-zero arm refuses the drift class at the
5829 // codec layer; the semantic-zero gate downstream
5830 // (`SupervisorError::ZeroRestartWindow`, etc.) would refuse
5831 // the single-byte canonical form `"0s"` separately on the
5832 // typed-validate layer.
5833 let err = duration_codec::parse("00s").unwrap_err();
5834 assert!(
5835 err.contains("non-canonical leading zero"),
5836 "expected leading-zero diagnostic in {err:?}"
5837 );
5838 assert!(err.contains("\"00\""), "missing magnitude in {err:?}");
5839 }
5840
5841 #[test]
5842 fn parse_rejects_leading_zero_per_hour_window() {
5843 // `"01h"` is the per-hour-window footgun — multi-byte magnitude
5844 // starting with `0`, parses losslessly to `Duration::from_secs(3600)`,
5845 // renders to `"1h"` (DRIFT). The arm is unit-agnostic: every
5846 // canonical unit suffix the codec accepts (`ms` / `s` / `m` /
5847 // `h` / bare-integer-as-seconds) inherits the same gate.
5848 let err = duration_codec::parse("01h").unwrap_err();
5849 assert!(
5850 err.contains("non-canonical leading zero"),
5851 "expected leading-zero diagnostic in {err:?}"
5852 );
5853 assert!(err.contains("\"01\""), "missing magnitude in {err:?}");
5854 }
5855
5856 #[test]
5857 fn parse_rejects_leading_zero_bare_integer_as_seconds() {
5858 // The `parse_accepts_bare_integer_as_seconds` happy-path
5859 // (`"30"` → 30s) inherits the leading-zero arm: `"030"` is
5860 // multi-byte starts-with-`0`, parses losslessly to
5861 // `Duration::from_secs(30)`, renders to `"30s"` (DRIFT). The
5862 // bare-integer surface accepts permissive unit-empty
5863 // shorthand but still must reject leading-zero padding.
5864 let err = duration_codec::parse("030").unwrap_err();
5865 assert!(
5866 err.contains("non-canonical leading zero"),
5867 "expected leading-zero diagnostic in {err:?}"
5868 );
5869 assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
5870 }
5871
5872 #[test]
5873 fn parse_accepts_single_zero_magnitude_at_codec_layer() {
5874 // The codec-layer / typed-validate-layer boundary: `"0s"` /
5875 // `"0ms"` / `"0"` are the single-byte canonical-zero forms —
5876 // each round-trips losslessly through `render`
5877 // (`render(Duration::ZERO)` → `"0s"`), so the codec layer
5878 // accepts them. The downstream semantic-zero gates
5879 // (`SupervisorError::ZeroRestartWindow`,
5880 // `AplicacaoError::PolicyTimeoutZero`,
5881 // `AplicacaoError::PolicyCircuitBreakerWindowZero`) refuse
5882 // zero-magnitude authoring at the typed-validate layer above,
5883 // peer with the `rate_limit_codec` codec-layer / typed-
5884 // validate-layer partition for `"0/s"`.
5885 assert_eq!(duration_codec::parse("0s").unwrap(), Duration::ZERO);
5886 assert_eq!(duration_codec::parse("0ms").unwrap(), Duration::ZERO);
5887 assert_eq!(duration_codec::parse("0").unwrap(), Duration::ZERO);
5888 }
5889
5890 #[test]
5891 fn parse_accepts_canonical_magnitude_with_leading_one() {
5892 // The complementary boundary: a future tightening cannot
5893 // drift into rejecting valid canonical magnitudes that
5894 // happen to start with `1` (or any digit `[1-9]`). Pin
5895 // every canonical-unit suffix so the leading-zero arm
5896 // remains strictly narrower than the digit-only arm.
5897 assert_eq!(
5898 duration_codec::parse("100ms").unwrap(),
5899 Duration::from_millis(100)
5900 );
5901 assert_eq!(
5902 duration_codec::parse("100s").unwrap(),
5903 Duration::from_secs(100)
5904 );
5905 assert_eq!(
5906 duration_codec::parse("10m").unwrap(),
5907 Duration::from_secs(600)
5908 );
5909 assert_eq!(
5910 duration_codec::parse("10h").unwrap(),
5911 Duration::from_secs(36_000)
5912 );
5913 }
5914
5915 #[test]
5916 fn restart_window_serde_rejects_leading_zero() {
5917 // The shared codec backs `SupervisorSpec::restart_window`
5918 // (`with = "duration_codec"`) — so the leading-zero arm
5919 // applies on serde deserialize for the typed Supervisor slot.
5920 // A `{"restartWindow":"030s"}` payload that previously round-
5921 // tripped to a different canonical string on next serialize
5922 // is now refused at deserialize with the leading-zero
5923 // diagnostic. Peer with `restart_window_serde_rejects_leading_plus`
5924 // / `restart_window_serde_rejects_fractional_seconds` on the
5925 // same canonical-form-drift axis.
5926 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
5927 "restartWindow":"030s",
5928 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
5929 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5930 let msg = err.to_string();
5931 assert!(
5932 msg.contains("non-canonical leading zero"),
5933 "expected leading-zero diagnostic in {msg:?}"
5934 );
5935 assert!(msg.contains("\"030\""), "missing magnitude in {msg:?}");
5936 }
5937
5938 #[test]
5939 fn parse_rejects_leading_whitespace() {
5940 // `" 30s"` — the canonical paste-from-aligned-doc /
5941 // paste-from-YAML-quoted-plain-scalar footgun. Before this
5942 // gate the top-level `s.trim()` at parse entry silently ate
5943 // the leading space and parsed the value to
5944 // `Duration::from_secs(30)`, which then round-tripped through
5945 // `render` to `"30s"` (a *different* canonical string on the
5946 // next emit) — the exact canonical-form-drift class the
5947 // leading-`+` / leading-zero arms already close, extended
5948 // to the whitespace-byte class. Peer with the sibling
5949 // `rate_limit_codec` whitespace-rejection arm (1ad7755) on
5950 // the M3 `:politicas` axis.
5951 let err = duration_codec::parse(" 30s").unwrap_err();
5952 assert!(
5953 err.contains("contains whitespace byte"),
5954 "expected whitespace diagnostic in {err:?}"
5955 );
5956 assert!(err.contains("0x20"), "missing offending byte in {err:?}");
5957 assert!(
5958 err.contains("THEORY.md"),
5959 "missing render-determinism contract citation in {err:?}"
5960 );
5961 }
5962
5963 #[test]
5964 fn parse_rejects_trailing_whitespace() {
5965 // `"30s "` — the canonical shell-history / trailing-space
5966 // paste footgun. Before this gate the top-level `s.trim()`
5967 // silently ate the trailing space and parsed to
5968 // `Duration::from_secs(30)`, round-tripping to `"30s"` on the
5969 // next emit — same canonical-form drift as the leading-space
5970 // sibling, closed on the same whitespace-byte arm.
5971 let err = duration_codec::parse("30s ").unwrap_err();
5972 assert!(
5973 err.contains("contains whitespace byte"),
5974 "expected whitespace diagnostic in {err:?}"
5975 );
5976 assert!(err.contains("0x20"), "missing offending byte in {err:?}");
5977 }
5978
5979 #[test]
5980 fn parse_rejects_internal_whitespace_between_magnitude_and_unit() {
5981 // `"30 s"` — the canonical typographically-spaced author
5982 // shape (the same idiom every prose reference to a duration
5983 // renders as, mistakenly retained when the value is pasted
5984 // into a codec-shaped slot). Before this gate the per-part
5985 // `num_part.trim()` / `unit.trim()` calls silently ate the
5986 // whitespace between the magnitude and the unit and parsed
5987 // the value to `Duration::from_secs(30)`, round-tripping to
5988 // `"30s"` — the codec's *internal* whitespace-tolerance
5989 // vector, orthogonal to the leading / trailing surface but
5990 // the same canonical-form-drift class. Pins the arm as
5991 // strictly stronger than the pre-existing top-level
5992 // `s.trim()` behavior: it fires on whitespace anywhere in
5993 // the value, not just at the string boundary.
5994 let err = duration_codec::parse("30 s").unwrap_err();
5995 assert!(
5996 err.contains("contains whitespace byte"),
5997 "expected whitespace diagnostic in {err:?}"
5998 );
5999 assert!(err.contains("0x20"), "missing offending byte in {err:?}");
6000 }
6001
6002 #[test]
6003 fn parse_rejects_tab_byte() {
6004 // `"\t30s"` — the canonical paste-from-indented-doc /
6005 // paste-from-YAML-block-scalar footgun where a tab byte leads
6006 // the magnitude. Pins that the gate covers tab (`0x09`) as
6007 // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
6008 // members and both would be silently swallowed by `s.trim()`
6009 // pre-gate. The `is_ascii_whitespace` coverage extends beyond
6010 // space alone to the full ASCII-whitespace set (space `0x20`,
6011 // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
6012 // the tab arm as a representative of the non-space members.
6013 let err = duration_codec::parse("\t30s").unwrap_err();
6014 assert!(
6015 err.contains("contains whitespace byte"),
6016 "expected whitespace diagnostic in {err:?}"
6017 );
6018 assert!(
6019 err.contains("0x09"),
6020 "missing offending tab byte in {err:?}"
6021 );
6022 }
6023
6024 #[test]
6025 fn restart_window_serde_rejects_whitespace() {
6026 // The shared codec backs `SupervisorSpec::restart_window`
6027 // (`with = "duration_codec"`) — so the whitespace arm
6028 // applies on serde deserialize for the typed Supervisor slot.
6029 // A `{"restartWindow":" 30s"}` payload that previously round-
6030 // tripped to a different canonical string on next serialize
6031 // is now refused at deserialize with the whitespace-byte
6032 // diagnostic. Peer with `restart_window_serde_rejects_leading_zero`
6033 // / `restart_window_serde_rejects_leading_plus` /
6034 // `restart_window_serde_rejects_fractional_seconds` on the
6035 // same canonical-form-drift axis.
6036 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
6037 "restartWindow":" 30s",
6038 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
6039 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6040 let msg = err.to_string();
6041 assert!(
6042 msg.contains("contains whitespace byte"),
6043 "expected whitespace diagnostic in {msg:?}"
6044 );
6045 assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
6046 }
6047
6048 // ── canonical-form: non-ASCII Unicode `White_Space` duration gate ─────
6049 //
6050 // Successor to the ASCII-whitespace arm (a7ae622) on the shared
6051 // duration codec — closes the strictly-complementary class the
6052 // byte-scan cannot see, through the lifted
6053 // [`crate::render::find_non_ascii_whitespace_char`] predicate.
6054 // Applies to `:supervisor :restart-window`, `:politicas :timeout`,
6055 // and `:politicas :circuit-breaker :window` simultaneously via
6056 // this shared codec.
6057
6058 #[test]
6059 fn duration_codec_parse_rejects_leading_nbsp() {
6060 // NBSP prefix — the strictly-complementary drift class the
6061 // ASCII byte-scan cannot see. `str::trim` strips it silently
6062 // and the value drifts to `"30s"` on next serialize.
6063 let err = duration_codec::parse("\u{00A0}30s").unwrap_err();
6064 assert!(
6065 err.contains("non-ASCII Unicode whitespace character"),
6066 "expected non-ASCII whitespace diagnostic in {err:?}"
6067 );
6068 assert!(err.contains("U+00A0"), "missing codepoint in {err:?}");
6069 }
6070
6071 #[test]
6072 fn duration_codec_parse_rejects_trailing_line_separator() {
6073 // LINE SEPARATOR (`\u{2028}`) trailing — paste-from-web-doc
6074 // footgun.
6075 let err = duration_codec::parse("30s\u{2028}").unwrap_err();
6076 assert!(
6077 err.contains("non-ASCII Unicode whitespace character"),
6078 "expected non-ASCII whitespace diagnostic in {err:?}"
6079 );
6080 assert!(err.contains("U+2028"), "missing codepoint in {err:?}");
6081 }
6082
6083 #[test]
6084 fn duration_codec_parse_accepts_ascii_only_forms_after_unicode_arm() {
6085 // Positive-control pin: every ASCII-only canonical form the
6086 // renderer emits stays accepted through the new arm.
6087 assert_eq!(
6088 duration_codec::parse("30s").unwrap(),
6089 Duration::from_secs(30)
6090 );
6091 assert_eq!(
6092 duration_codec::parse("500ms").unwrap(),
6093 Duration::from_millis(500)
6094 );
6095 assert_eq!(
6096 duration_codec::parse("1h").unwrap(),
6097 Duration::from_secs(3600)
6098 );
6099 }
6100
6101 #[test]
6102 fn restart_window_serde_rejects_non_ascii_whitespace() {
6103 // The shared codec backs `SupervisorSpec::restart_window` — so
6104 // the new non-ASCII Unicode whitespace arm applies on serde
6105 // deserialize for the typed Supervisor slot. A
6106 // `{"restartWindow":" 30s"}` payload that previously
6107 // survived the ASCII byte-scan (only ASCII whitespace was
6108 // refused) is now refused at deserialize with the
6109 // non-ASCII-whitespace-and-codepoint diagnostic.
6110 let payload = "{\"estrategia\":\"OneForOne\",\"maxRestarts\":5,\
6111 \"restartWindow\":\"\u{00A0}30s\",\
6112 \"children\":[{\"caixa\":\"w\",\"versao\":\"^0.1\",\"restart\":\"Permanent\"}]}";
6113 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
6114 let msg = err.to_string();
6115 assert!(
6116 msg.contains("non-ASCII Unicode whitespace character"),
6117 "expected non-ASCII whitespace diagnostic in {msg:?}"
6118 );
6119 assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
6120 }
6121
6122 // ── drift-detection: serde-derive-to-SUPERVISOR_KEY_* identity ────────
6123
6124 #[test]
6125 fn supervisor_spec_serde_keys_match_lifted_supervisor_key_consts() {
6126 // Load-bearing invariant: the four `SUPERVISOR_KEY_*` consts
6127 // (`SUPERVISOR_KEY_ESTRATEGIA` / `SUPERVISOR_KEY_MAX_RESTARTS` /
6128 // `SUPERVISOR_KEY_RESTART_WINDOW` / `SUPERVISOR_KEY_CHILDREN`)
6129 // name the exact camelCase JSON keys the
6130 // `#[serde(rename_all = "camelCase")]` attribute on
6131 // `SupervisorSpec` emits. Serialize a fully-populated spec (each
6132 // field carries `Some(_)` / non-empty) and pin that each canonical
6133 // byte-sequence appears verbatim in the JSON — a future accidental
6134 // `rename_all = "snake_case"` / `"kebab-case"` / verbatim-field-
6135 // name flip at the derive attribute (any of which would silently
6136 // break every downstream JSON consumer that reaches for one of the
6137 // four consts via `Value::get(...)`) surfaces here as a build-time
6138 // test failure at `supervisor.rs`, not as an apply-time
6139 // `.get(<stale-canonical-const>)` returning `None` far from the
6140 // derive-attr drift's commit. Peer with the sibling
6141 // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
6142 // (d8b8b4f) pin on the M2 `:limits` axis — same discipline the
6143 // M2 typed-slot family established, extended here to close the
6144 // top-level Supervisor axis.
6145 let spec = SupervisorSpec {
6146 estrategia: RestartStrategy::OneForOne,
6147 max_restarts: 5,
6148 restart_window: Some(Duration::from_secs(60)),
6149 children: vec![ChildSpec {
6150 caixa: "w".into(),
6151 versao: "^0.1".into(),
6152 restart: RestartPolicy::Permanent,
6153 }],
6154 };
6155 let json = serde_json::to_string(&spec).unwrap();
6156 for key in [
6157 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6158 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6159 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6160 crate::render::SUPERVISOR_KEY_CHILDREN,
6161 ] {
6162 let quoted = format!("\"{key}\"");
6163 assert!(
6164 json.contains("ed),
6165 "serialized SupervisorSpec must carry the lifted \
6166 SUPERVISOR_KEY_* byte-sequence {quoted} verbatim in \
6167 the JSON emission (got: {json})",
6168 );
6169 }
6170 }
6171
6172 #[test]
6173 fn supervisor_key_consts_are_pairwise_distinct() {
6174 // Cross-axis drift-detection pin: a future collapse of two
6175 // canonical top-level byte-strings onto the same value (e.g. an
6176 // accidental copy-paste flip of `SUPERVISOR_KEY_CHILDREN` to
6177 // also read `"estrategia"`) would silently reroute every
6178 // downstream probe on one axis onto the sibling axis's overlay
6179 // entry and pass every propagation-probe test that expected only
6180 // the stale axis's value. Peer of the sibling four-way distinct
6181 // pin on the `M2_LIMITS_KEY_*` tetrad (d8b8b4f).
6182 let all = [
6183 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6184 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6185 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6186 crate::render::SUPERVISOR_KEY_CHILDREN,
6187 ];
6188 for (i, a) in all.iter().enumerate() {
6189 for b in all.iter().skip(i + 1) {
6190 assert_ne!(
6191 a, b,
6192 "SUPERVISOR_KEY_* consts must be pairwise-distinct \
6193 canonical byte-sequences — got `{a}` == `{b}`",
6194 );
6195 }
6196 }
6197 }
6198
6199 #[test]
6200 fn supervisor_key_consts_are_lower_camel_case_shape() {
6201 // Shape-pin: every `SUPERVISOR_KEY_*` const must be a
6202 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
6203 // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
6204 // capital, no whitespace / dots) — the canonical shape the
6205 // `#[serde(rename_all = "camelCase")]` derive produces on
6206 // `SupervisorSpec`. A future flip to a non-camelCase attribute
6207 // at the derive surfaces both here (this test fails on the
6208 // stale-constant shape) and at
6209 // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
6210 // (that test fails on the mismatch between const and derive).
6211 // Peer with `m2_limits_key_consts_are_lower_camel_case_shape`
6212 // (d8b8b4f) on the sibling M2 `:limits` axis.
6213 for key in [
6214 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6215 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6216 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6217 crate::render::SUPERVISOR_KEY_CHILDREN,
6218 ] {
6219 assert!(
6220 !key.is_empty(),
6221 "SUPERVISOR_KEY_* must be non-empty (got {key:?})"
6222 );
6223 let first = key.chars().next().unwrap();
6224 assert!(
6225 first.is_ascii_lowercase(),
6226 "SUPERVISOR_KEY_* must lead with an ASCII-lowercase byte \
6227 (got {key:?}, leads with {first:?})",
6228 );
6229 assert!(
6230 key.chars().all(|c| c.is_ascii_alphanumeric()),
6231 "SUPERVISOR_KEY_* must be ASCII-alphanumeric only \
6232 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
6233 );
6234 }
6235 }
6236
6237 #[test]
6238 fn supervisor_key_consts_are_byte_distinct_from_supervisor_author_key_peers() {
6239 // Cross-axis drift pin: the four `SUPERVISOR_KEY_*` consts
6240 // (camelCase JSON keys, no leading colon) must never collide
6241 // byte-for-byte with the four peer `SUPERVISOR_AUTHOR_KEY_*`
6242 // consts (kebab-case author-facing labels with leading colon)
6243 // that sit next to them at `caixa_core::render`. Both families
6244 // cover the same four typed Supervisor slots on two distinct
6245 // axes (author-side kebab vs renderer-side camelCase);
6246 // collapsing either family onto the other's byte-shape would
6247 // silently reroute the render-side probe onto the author-facing
6248 // surface, or vice versa. Peer of the byte-distinctness
6249 // discipline the `M3_PLACEMENT_KEY_ESTRATEGIA` docstring names
6250 // against the peer `M3_AUTHOR_KEY_PLACEMENT`.
6251 let pairs = [
6252 (
6253 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
6254 crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA,
6255 ),
6256 (
6257 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
6258 crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS,
6259 ),
6260 (
6261 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
6262 crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW,
6263 ),
6264 (
6265 crate::render::SUPERVISOR_KEY_CHILDREN,
6266 crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN,
6267 ),
6268 ];
6269 for (json_key, author_key) in pairs {
6270 assert_ne!(
6271 json_key, author_key,
6272 "SUPERVISOR_KEY_* (JSON side) must differ byte-for-byte \
6273 from the peer SUPERVISOR_AUTHOR_KEY_* (author side); \
6274 got JSON `{json_key}` == author `{author_key}`",
6275 );
6276 }
6277 }
6278
6279 // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_KEY_* identity ──
6280
6281 #[test]
6282 fn child_spec_serde_keys_match_lifted_supervisor_child_key_consts() {
6283 // Load-bearing invariant: the three `SUPERVISOR_CHILD_KEY_*` consts
6284 // (`SUPERVISOR_CHILD_KEY_CAIXA` / `SUPERVISOR_CHILD_KEY_VERSAO` /
6285 // `SUPERVISOR_CHILD_KEY_RESTART`) name the exact camelCase JSON
6286 // keys the `#[serde(rename_all = "camelCase")]` attribute on
6287 // `ChildSpec` emits. Serialize a fully-populated `ChildSpec` and
6288 // pin that each canonical byte-sequence appears verbatim in the
6289 // JSON — a future accidental `rename_all = "snake_case"` /
6290 // `"kebab-case"` / verbatim-field-name flip at the derive
6291 // attribute (any of which would silently break every downstream
6292 // JSON consumer that reaches for one of the three consts via
6293 // `Value::get(...)`) surfaces here as a build-time test failure at
6294 // `supervisor.rs`, not as an apply-time
6295 // `.get(<stale-canonical-const>)` returning `None` far from the
6296 // derive-attr drift's commit. Peer with the enclosing
6297 // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
6298 // (40cc4e5) pin on the M2 supervision-tree top-level axis — same
6299 // discipline the SupervisorSpec top-level lift established,
6300 // extended here to the sibling per-`:children` entry `ChildSpec`
6301 // derive so the last M2 typed-struct sub-block
6302 // `#[serde(rename_all = "camelCase")]` axis on the Supervisor
6303 // surface without a lifted serde-key peer joins the substrate's
6304 // "one canonical byte-string per typed serialized-key axis"
6305 // discipline.
6306 let c = ChildSpec {
6307 caixa: "worker".into(),
6308 versao: "^0.1".into(),
6309 restart: RestartPolicy::Permanent,
6310 };
6311 let json = serde_json::to_string(&c).unwrap();
6312 for key in [
6313 crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
6314 crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
6315 crate::render::SUPERVISOR_CHILD_KEY_RESTART,
6316 ] {
6317 let quoted = format!("\"{key}\"");
6318 assert!(
6319 json.contains("ed),
6320 "serialized ChildSpec must carry the lifted \
6321 SUPERVISOR_CHILD_KEY_* byte-sequence {quoted} verbatim \
6322 in the JSON emission (got: {json})",
6323 );
6324 }
6325 }
6326
6327 #[test]
6328 fn supervisor_child_key_consts_are_pairwise_distinct() {
6329 // Cross-axis drift-detection pin: a future collapse of two
6330 // canonical `ChildSpec` per-entry byte-strings onto the same
6331 // value (e.g. an accidental copy-paste flip of
6332 // `SUPERVISOR_CHILD_KEY_RESTART` to also read `"caixa"`) would
6333 // silently reroute every downstream probe on one axis onto the
6334 // sibling axis's overlay entry and pass every propagation-probe
6335 // test that expected only the stale axis's value. Peer of the
6336 // sibling three-way distinct pin on the `CONTRATO_KEY_*` triad
6337 // (ca463a4) and the two-way distinct pin on the `MEMBRO_KEY_*`
6338 // pair (ce80ca0).
6339 let all = [
6340 crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
6341 crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
6342 crate::render::SUPERVISOR_CHILD_KEY_RESTART,
6343 ];
6344 for (i, a) in all.iter().enumerate() {
6345 for b in all.iter().skip(i + 1) {
6346 assert_ne!(
6347 a, b,
6348 "SUPERVISOR_CHILD_KEY_* consts must be pairwise-\
6349 distinct canonical byte-sequences — got `{a}` == `{b}`",
6350 );
6351 }
6352 }
6353 }
6354
6355 #[test]
6356 fn supervisor_child_key_consts_are_lower_camel_case_shape() {
6357 // Shape-pin: every `SUPERVISOR_CHILD_KEY_*` const must be a
6358 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
6359 // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
6360 // capital, no whitespace / dots) — the canonical shape the
6361 // `#[serde(rename_all = "camelCase")]` derive produces on
6362 // `ChildSpec`. A future flip to a non-camelCase attribute at the
6363 // derive surfaces both here (this test fails on the
6364 // stale-constant shape) and at
6365 // `child_spec_serde_keys_match_lifted_supervisor_child_key_consts`
6366 // (that test fails on the mismatch between const and derive).
6367 // Peer with `supervisor_key_consts_are_lower_camel_case_shape`
6368 // (40cc4e5) on the sibling `SupervisorSpec` top-level axis.
6369 for key in [
6370 crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
6371 crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
6372 crate::render::SUPERVISOR_CHILD_KEY_RESTART,
6373 ] {
6374 assert!(
6375 !key.is_empty(),
6376 "SUPERVISOR_CHILD_KEY_* must be non-empty (got {key:?})"
6377 );
6378 let first = key.chars().next().unwrap();
6379 assert!(
6380 first.is_ascii_lowercase(),
6381 "SUPERVISOR_CHILD_KEY_* must lead with an ASCII-lowercase \
6382 byte (got {key:?}, leads with {first:?})",
6383 );
6384 assert!(
6385 key.chars().all(|c| c.is_ascii_alphanumeric()),
6386 "SUPERVISOR_CHILD_KEY_* must be ASCII-alphanumeric only \
6387 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
6388 );
6389 }
6390 }
6391
6392 // ── drift-detection: serde-derive-to-SUPERVISOR_ESTRATEGIA_* identity ────
6393
6394 #[test]
6395 fn restart_strategy_variants_serialize_to_lifted_scalar_values() {
6396 // The fail-before-pass-after pin: pre-lift there was no
6397 // single-source binding between the [`RestartStrategy`] variant
6398 // name the un-`rename`d `Serialize` derive emits under
6399 // [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the byte-string
6400 // every downstream cluster-side dispatcher (the future
6401 // wasm-operator's per-supervisor sibling-restart branch, the
6402 // future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
6403 // admission-time enum-arm bind, the `caixa-operator`'s
6404 // hierarchical reconciliation scheduler's per-strategy fan-out)
6405 // probes verbatim. A future `#[serde(rename_all = "kebab-case")]`
6406 // attribute on the enum — or a per-variant `#[serde(rename = "…")]`
6407 // override, or a variant rename in the source — would silently
6408 // rebrand the emitted scalar under one spelling while every
6409 // downstream dispatcher still probed the other, with the failure
6410 // surfacing at the operator's reconcile posture (subtrees coming
6411 // up under the `default()` `OneForOne` arm rather than the typed
6412 // slot's declared strategy — a bad child would then only take
6413 // itself down instead of the sibling set the author intended, so
6414 // shared-state children fall out of sync) far from the source
6415 // rebrand commit and with no field naming the drift. Pinning the
6416 // two paths (the `Serialize` derive's serialized string AND the
6417 // [`RestartStrategy::as_str`] helper) to the same four lifted
6418 // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
6419 // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
6420 // [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
6421 // [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
6422 // byte-strings makes any future drift on either endpoint fail
6423 // here at caixa-core build time. Peer of the M3
6424 // `placement_strategy_variants_serialize_to_lifted_scalar_values`
6425 // (3f0e21c) on the sibling `PlacementStrategy` axis — same
6426 // three-path-convergence discipline, extended to close the
6427 // OTP-shaped per-supervisor sibling-restart axis.
6428 for (variant, expected) in [
6429 (
6430 RestartStrategy::OneForOne,
6431 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
6432 ),
6433 (
6434 RestartStrategy::OneForAll,
6435 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
6436 ),
6437 (
6438 RestartStrategy::RestForOne,
6439 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
6440 ),
6441 (
6442 RestartStrategy::SimpleOneForOne,
6443 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
6444 ),
6445 ] {
6446 let json = serde_json::to_string(&variant).unwrap();
6447 assert_eq!(
6448 json,
6449 format!("\"{expected}\""),
6450 "RestartStrategy::{variant:?} must serialize to {expected:?}"
6451 );
6452 assert_eq!(
6453 variant.as_str(),
6454 expected,
6455 "RestartStrategy::{variant:?}.as_str() must return the lifted \
6456 SUPERVISOR_ESTRATEGIA_* constant"
6457 );
6458 }
6459 }
6460
6461 #[test]
6462 fn supervisor_estrategia_consts_are_pairwise_distinct() {
6463 // Cross-arm drift-detection pin: a future collapse of two
6464 // canonical variant byte-strings onto the same value (e.g. an
6465 // accidental copy-paste flip of `SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`
6466 // to also read `"OneForOne"`) would silently reroute every
6467 // downstream operator's per-strategy dispatch onto the sibling
6468 // arm's reconcile branch and pass every propagation-probe test
6469 // that expected only the stale arm's value — the mis-strategied
6470 // subtree would come up with the wrong sibling-restart posture
6471 // on every subsequent failure. Peer of the sibling four-way
6472 // distinct pin `supervisor_key_consts_are_pairwise_distinct`
6473 // (40cc4e5) on the top-level `SUPERVISOR_KEY_*` axis.
6474 let all = [
6475 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
6476 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
6477 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
6478 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
6479 ];
6480 for (i, a) in all.iter().enumerate() {
6481 for (j, b) in all.iter().enumerate() {
6482 if i != j {
6483 assert_ne!(
6484 a, b,
6485 "SUPERVISOR_ESTRATEGIA_* consts must be pairwise distinct \
6486 — got duplicate {a:?} at indices {i} and {j}",
6487 );
6488 }
6489 }
6490 }
6491 }
6492
6493 #[test]
6494 fn restart_strategy_display_routes_through_as_str_helper() {
6495 // The fail-before-pass-after pin on the first half of the
6496 // three-path convergence: pre-convergence the sibling
6497 // OTP-shape typed enum [`RestartStrategy`] carried a
6498 // [`std::fmt::Display`] surface via its
6499 // `#[discriminant(also_display)]` gen-platform derive route,
6500 // which arrived kebab-case as `"one-for-one"` /
6501 // `"one-for-all"` / `"rest-for-one"` /
6502 // `"simple-one-for-one"` while the wire format ran as
6503 // PascalCase `"OneForOne"` / `"OneForAll"` / `"RestForOne"` /
6504 // `"SimpleOneForOne"` through the un-`rename`d serde derive.
6505 // Every consumer reaching for a strategy byte-string past the
6506 // wire format had to pick between three paths
6507 // ([`RestartStrategy::as_str`], the `Serialize` derive's
6508 // serialized string, or `format!("{v}")` on the
6509 // discriminant-Display route), any two of which a future
6510 // variant rename or `#[serde(rename_all = "kebab-case")]`
6511 // attribute would silently desynchronize. Wiring
6512 // [`std::fmt::Display`] through [`RestartStrategy::as_str`]
6513 // closes the third path: every `format!("{v}")` call reaches
6514 // the same lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
6515 // const the wire format and the [`RestartStrategy::as_str`]
6516 // helper already route through, so a future variant rename
6517 // lands at exactly one place. Pin the routing here so a future
6518 // `impl std::fmt::Display for RestartStrategy`
6519 // reimplementation that hand-rolls the arms instead of
6520 // delegating to [`RestartStrategy::as_str`] fails at
6521 // caixa-core build time. Peer of the M3
6522 // `placement_strategy_display_routes_through_as_str_helper`
6523 // (cc8f749) which the M3 axis converged first.
6524 for &variant in RestartStrategy::ALL {
6525 assert_eq!(
6526 variant.to_string(),
6527 variant.as_str(),
6528 "RestartStrategy::{variant:?} Display must route through \
6529 RestartStrategy::as_str (single source of truth: the lifted \
6530 SUPERVISOR_ESTRATEGIA_* const the wire format also emits)"
6531 );
6532 }
6533 }
6534
6535 #[test]
6536 fn restart_strategy_display_matches_serialized_wire_byte_string() {
6537 // The fail-before-pass-after pin on the second half of the
6538 // three-path convergence: `Display` (user-facing text) agrees
6539 // byte-for-byte with the `Serialize` derive's wire format
6540 // (canonical camelCase-schema `SUPERVISOR_KEY_ESTRATEGIA`
6541 // scalar) on every variant. Pre-convergence the two paths
6542 // were structurally independent — a future
6543 // `#[serde(rename_all = "kebab-case")]` attribute on the
6544 // enum would silently rebrand the emitted wire scalar
6545 // (`one-for-one`, `one-for-all`, `rest-for-one`,
6546 // `simple-one-for-one`) while every consumer that
6547 // pretty-prints the strategy (the future wasm-operator's
6548 // per-supervisor sibling-restart-strategy diagnostic line,
6549 // the future `feira app graph` per-supervisor strategy line,
6550 // the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
6551 // materializer's admission-webhook rejection body) would
6552 // still emit the PascalCase form the `as_str` / `Display`
6553 // route returns, with the mismatch surfacing at consumer
6554 // parse time / operator dispatch time far from the source
6555 // rebrand commit. Pin the two paths byte-for-byte here so any
6556 // future serde-attribute or variant-rename drift is a
6557 // caixa-core-build-time test failure at this call, not a
6558 // silent per-consumer dispatch miss. Peer of the M3
6559 // `placement_strategy_display_matches_serialized_wire_byte_string`
6560 // (cc8f749) which the M3 axis converged first.
6561 for &variant in RestartStrategy::ALL {
6562 let wire = serde_json::to_string(&variant).unwrap();
6563 let unquoted = wire
6564 .strip_prefix('"')
6565 .and_then(|s| s.strip_suffix('"'))
6566 .expect("serialized RestartStrategy is a JSON string");
6567 assert_eq!(
6568 variant.to_string(),
6569 unquoted,
6570 "RestartStrategy::{variant:?} Display byte-string must match the \
6571 Serialize derive's wire byte-string (three-path convergence: \
6572 Display + as_str + Serialize all resolve to the same \
6573 SUPERVISOR_ESTRATEGIA_* const)"
6574 );
6575 }
6576 }
6577
6578 #[test]
6579 fn restart_strategy_as_ref_str_routes_through_as_str_accessor() {
6580 // Fail-before-pass-after byte-parity pin on the lifted
6581 // `impl AsRef<str> for RestartStrategy` — asserts the
6582 // standard-library trait impl and the substrate-primitive
6583 // [`RestartStrategy::as_str`] `pub const fn` accessor resolve
6584 // to the same `&str` per instance across the four-arm
6585 // closed set, so any future silent detour that routes the
6586 // impl through a divergent projection (a per-arm inline
6587 // `match self { RestartStrategy::OneForOne => "OneForOne", … }`
6588 // re-inlining that opens a compile-time link to the un-lifted
6589 // arm-literal, a swap onto the kebab-case
6590 // [`gen_platform::Discriminant`] catalog identity that would
6591 // collide the wire axis with the dispatcher-catalog axis) trips
6592 // at caixa-core test time under `PartialEq` rather than at a
6593 // downstream `impl AsRef<str>`-bound consumer's silent split.
6594 // Sweeps every one of the four arms
6595 // [`RestartStrategy::ALL`] carries so no arm's projection is
6596 // covered only by the sibling wire-format `Serialize` derive
6597 // path. Peer of the sibling
6598 // [`crate::version::tests::caixa_version_as_ref_str_routes_through_as_str_accessor`]
6599 // (16d5c7e) `AsRef<str>`-byte-parity pin on the paired
6600 // top-level `:versao` typed newtype — the two pins together
6601 // cover the substrate primitive's `AsRef<str>` projection axis
6602 // on the paired newtype + closed-set-typed-enum surface.
6603 for &variant in RestartStrategy::ALL {
6604 assert_eq!(
6605 <RestartStrategy as AsRef<str>>::as_ref(&variant),
6606 variant.as_str(),
6607 "AsRef<str> impl on RestartStrategy::{variant:?} must \
6608 byte-equal RestartStrategy::as_str on the same instance \
6609 — divergence signals a silent detour off the substrate-\
6610 primitive accessor"
6611 );
6612 }
6613 }
6614
6615 #[test]
6616 fn restart_strategy_as_ref_str_routes_through_display_via_shared_accessor() {
6617 // Fail-before-pass-after byte-parity pin on the three-path
6618 // convergence discipline the M2 sibling-restart primitive now
6619 // carries on the `&str`-projection axis:
6620 // `<RestartStrategy as AsRef<str>>::as_ref(&s)` (the newly
6621 // lifted impl), `format!("{s}")` (the pre-existing
6622 // [`fmt::Display`] impl), and `s.as_str()` (the substrate-
6623 // primitive `pub const fn` accessor both trait impls delegate
6624 // through) must resolve to the same byte-string on every
6625 // instance across the four-arm closed set. Refuses any future
6626 // divergence between the two trait impls (a stray
6627 // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
6628 // rather than delegating through the shared accessor; a
6629 // hypothetical `AsRef<str>` rewrite that inlines a per-arm
6630 // literal cascade) that would silently split the two
6631 // projection paths of the same closed-set typed enum. Mirrors
6632 // the sibling three-path-convergence discipline the peer
6633 // [`crate::CaixaVersion`] typed newtype carries on its
6634 // `AsRef<str>` / `Display` / `as_str` triple
6635 // (version.rs pin
6636 // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
6637 // 16d5c7e).
6638 for &variant in RestartStrategy::ALL {
6639 let via_as_ref: &str = <RestartStrategy as AsRef<str>>::as_ref(&variant);
6640 let via_display: String = format!("{variant}");
6641 let via_accessor: &str = variant.as_str();
6642 assert_eq!(via_as_ref, via_accessor);
6643 assert_eq!(via_display, via_accessor);
6644 assert_eq!(via_as_ref, via_display.as_str());
6645 }
6646 }
6647
6648 #[test]
6649 fn restart_strategy_all_enumerates_every_variant_exactly_once() {
6650 // Fail-before-pass-after pin on the [`RestartStrategy::ALL`]
6651 // exhaustive-iteration surface: every variant appears exactly
6652 // once, and the slice length matches the arm count of the
6653 // closed set. Every consumer that walks the accepted-strategy
6654 // set (a future `feira supervisor --estrategia …` CLI-side
6655 // arg-parse's "did you mean" hint, a future M4 admission-
6656 // webhook's rejection body naming the accepted-`:estrategia`
6657 // list, the [`RestartStrategy::from_wire`] reverse-projection
6658 // consumers that iterate the accept-set for diagnostic
6659 // rendering) reads through this slice, so a future arm addition
6660 // that grows the enum but forgets to grow [`Self::ALL`]
6661 // silently truncates every downstream consumer's accept-set at
6662 // the same pre-addition boundary — this pin fails at caixa-core
6663 // build time on the pairwise-distinct + arm-count invariants.
6664 //
6665 // Peer of the sibling [`crate::CaixaKind::ALL`] (6b1f4fb) /
6666 // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
6667 // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
6668 // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
6669 // pins on the peer closed-set typed-enum axes.
6670 let all: &[RestartStrategy] = RestartStrategy::ALL;
6671 assert_eq!(
6672 all.len(),
6673 4,
6674 "RestartStrategy::ALL must enumerate every variant of the \
6675 four-arm closed set (OneForOne, OneForAll, RestForOne, \
6676 SimpleOneForOne); got {all:?}"
6677 );
6678 for (i, a) in all.iter().enumerate() {
6679 for (j, b) in all.iter().enumerate() {
6680 if i != j {
6681 assert_ne!(
6682 a, b,
6683 "RestartStrategy::ALL must carry every variant exactly \
6684 once — got duplicate {a:?} at indices {i} and {j}"
6685 );
6686 }
6687 }
6688 }
6689 for variant in [
6690 RestartStrategy::OneForOne,
6691 RestartStrategy::OneForAll,
6692 RestartStrategy::RestForOne,
6693 RestartStrategy::SimpleOneForOne,
6694 ] {
6695 assert!(
6696 all.contains(&variant),
6697 "RestartStrategy::ALL must contain {variant:?} — a future arm \
6698 addition that grows the enum but forgets to grow the ALL slice \
6699 silently truncates every downstream consumer's accept-set at \
6700 the pre-addition boundary"
6701 );
6702 }
6703 }
6704
6705 #[test]
6706 fn restart_strategy_from_wire_accepts_every_lifted_constant() {
6707 // Fail-before-pass-after pin on the forward accept-set of the
6708 // [`RestartStrategy::from_wire`] reverse projection: every
6709 // canonical [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
6710 // constant the [`RestartStrategy::as_str`] emitter walks parses
6711 // back to its paired variant. Any future arm addition that
6712 // grows the emitter's `as_str` match but forgets to grow the
6713 // parser's `from_wire` match silently splits the two halves of
6714 // the round-trip — the wire byte-string one non-serde consumer
6715 // parses from the one the emitter wrote — with the failure
6716 // surfacing at parse time far from the rebrand commit. Pinning
6717 // the four-arm accept-set here catches the drift at caixa-core
6718 // build time.
6719 //
6720 // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
6721 // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
6722 // accept-set pins on the peer closed-set typed-enum `str → Self`
6723 // axes.
6724 for (wire, expected) in [
6725 (
6726 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
6727 RestartStrategy::OneForOne,
6728 ),
6729 (
6730 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
6731 RestartStrategy::OneForAll,
6732 ),
6733 (
6734 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
6735 RestartStrategy::RestForOne,
6736 ),
6737 (
6738 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
6739 RestartStrategy::SimpleOneForOne,
6740 ),
6741 ] {
6742 let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
6743 panic!(
6744 "RestartStrategy::from_wire({wire:?}) must accept every \
6745 SUPERVISOR_ESTRATEGIA_* constant — got None for the \
6746 lifted canonical byte-string that RestartStrategy::{expected:?} \
6747 serializes as under SUPERVISOR_KEY_ESTRATEGIA"
6748 )
6749 });
6750 assert_eq!(
6751 parsed, expected,
6752 "RestartStrategy::from_wire({wire:?}) must return \
6753 RestartStrategy::{expected:?}; got RestartStrategy::{parsed:?}"
6754 );
6755 }
6756 }
6757
6758 #[test]
6759 fn restart_strategy_from_wire_round_trips_through_as_str() {
6760 // Fail-before-pass-after pin on the closed round-trip between
6761 // the forward [`RestartStrategy::as_str`] emitter and the
6762 // reverse [`RestartStrategy::from_wire`] parser: for every
6763 // variant in [`RestartStrategy::ALL`], parsing the emitter's
6764 // output must return exactly the same variant. Any per-arm
6765 // divergence — a future arm added to `as_str` but not
6766 // `from_wire`, an accidental copy-paste flip in one but not
6767 // the other — silently splits the emit and parse halves and
6768 // the failure surfaces at consumer parse time far from the
6769 // drift site. The `ALL`-iterating shape means a future arm
6770 // addition picks up the coverage by construction.
6771 //
6772 // Peer of the sibling
6773 // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
6774 // (18c7342) round-trip pin on
6775 // [`crate::aplicacao::PlacementStrategy::from_wire`] and
6776 // [`crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`]
6777 // (6b1f4fb) round-trip pin on [`crate::CaixaKind::from_wire`].
6778 for &variant in RestartStrategy::ALL {
6779 let wire = variant.as_str();
6780 let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
6781 panic!(
6782 "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
6783 must be Some({variant:?}) — the two halves of the round-trip \
6784 dispatch on the same lifted SUPERVISOR_ESTRATEGIA_* consts; \
6785 got None on wire byte-string {wire:?}"
6786 )
6787 });
6788 assert_eq!(
6789 parsed, variant,
6790 "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
6791 must round-trip to the same variant; got {parsed:?}"
6792 );
6793 }
6794 }
6795
6796 #[test]
6797 fn restart_strategy_from_wire_rejects_unknown_byte_strings() {
6798 // Fail-before-pass-after pin on the closed-set refusal
6799 // discipline of [`RestartStrategy::from_wire`]: every
6800 // byte-string outside the four-arm accept-set returns `None`
6801 // rather than silently collapsing onto the [`Default`]
6802 // (`OneForOne`) arm or an arbitrary neighbor. The refusal set
6803 // exercised here sweeps the load-bearing drift shapes: the
6804 // empty string (a stripped serde-attribute drift), all-
6805 // whitespace strings (the canonical text-editor accidental
6806 // padding shape), the kebab-case dispatcher-catalog identities
6807 // (`"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
6808 // `"simple-one-for-one"` — the [`gen_platform::FromStrKind`]-
6809 // derived [`std::str::FromStr`] accept-set, which parses the
6810 // *other* axis of this enum's two-axis split and must not leak
6811 // into the `from_wire` PascalCase-wire accept-set), the
6812 // lowercased single-word forms (`"oneforone"`), the padded
6813 // canonical scalar (`" OneForOne "`), the trailing-newline
6814 // shapes (`"OneForOne\n"`), and neighboring-but-unknown arms
6815 // (`"AllForOne"` — the canonical typo direction).
6816 //
6817 // Peer of the sibling
6818 // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
6819 // (2aa6d23) +
6820 // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
6821 // (18c7342) refusal pins on the peer closed-set typed-enum
6822 // axes.
6823 for bad in [
6824 "",
6825 " ",
6826 "\n",
6827 "\t",
6828 "one-for-one",
6829 "one-for-all",
6830 "rest-for-one",
6831 "simple-one-for-one",
6832 "oneforone",
6833 "OneForOnes",
6834 "one_for_one",
6835 "one for one",
6836 "ONEFORONE",
6837 "OneForOne ",
6838 " OneForOne",
6839 " SimpleOneForOne ",
6840 "OneForOne\n",
6841 "restforone",
6842 "REST_FOR_ONE",
6843 "AllForOne",
6844 "Simple",
6845 "?",
6846 ] {
6847 assert!(
6848 RestartStrategy::from_wire(bad).is_none(),
6849 "RestartStrategy::from_wire({bad:?}) must return None — the \
6850 parser's accept-set is exactly the four RestartStrategy::as_str \
6851 outputs (OneForOne, OneForAll, RestForOne, SimpleOneForOne), \
6852 and this byte-string is outside that closed set"
6853 );
6854 }
6855 }
6856
6857 #[test]
6858 fn restart_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
6859 // Fail-before-pass-after pin on the fourth path of the four-path
6860 // convergence: `from_wire` (the reverse projection) inverts the
6861 // `Serialize` derive's wire byte-string on every variant.
6862 // Together with the pre-existing three-path convergence
6863 // (`Display` + `as_str` + `Serialize` all resolve to the same
6864 // lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const,
6865 // pinned by
6866 // [`restart_strategy_display_matches_serialized_wire_byte_string`])
6867 // this closes the round-trip: the wire byte-string the
6868 // `Serialize` derive emits parses back to the same variant
6869 // through `from_wire`, so any future serde-attribute or variant-
6870 // rename drift on the emit half now surfaces as a matched drift
6871 // on the parse half at caixa-core build time — the two halves
6872 // migrate as a unit through the lifted consts on any future
6873 // rename, and the round-trip cannot silently split.
6874 //
6875 // Peer of the sibling
6876 // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
6877 // (18c7342) wire-format pin on
6878 // [`crate::aplicacao::PlacementStrategy::from_wire`].
6879 for &variant in RestartStrategy::ALL {
6880 let wire = serde_json::to_string(&variant).unwrap();
6881 let unquoted = wire
6882 .strip_prefix('"')
6883 .and_then(|s| s.strip_suffix('"'))
6884 .expect("serialized RestartStrategy is a JSON string");
6885 let parsed = RestartStrategy::from_wire(unquoted).unwrap_or_else(|| {
6886 panic!(
6887 "RestartStrategy::from_wire({unquoted:?}) must accept the \
6888 Serialize derive's wire byte-string for \
6889 RestartStrategy::{variant:?} — the four-path convergence \
6890 (Display + as_str + Serialize + from_wire) resolves through \
6891 the same lifted SUPERVISOR_ESTRATEGIA_* const; got None"
6892 )
6893 });
6894 assert_eq!(
6895 parsed, variant,
6896 "RestartStrategy::from_wire of the Serialize derive's wire \
6897 byte-string for RestartStrategy::{variant:?} must round-trip \
6898 to the same variant; got {parsed:?}"
6899 );
6900 }
6901 }
6902
6903 #[test]
6904 fn restart_strategy_try_from_str_routes_through_from_wire_accessor() {
6905 // Fail-before-pass-after byte-parity pin on the newly lifted
6906 // `impl TryFrom<&str> for RestartStrategy` — asserts the standard-
6907 // library trait impl and the substrate-primitive
6908 // [`RestartStrategy::from_wire`] `Option<Self>` accessor resolve to
6909 // the same four-arm accept-set across every arm the exhaustive
6910 // [`RestartStrategy::ALL`] slice enumerates. Any future silent
6911 // detour that routes the trait impl through a divergent projection
6912 // (a per-arm inline `match s { "OneForOne" => Ok(Self::OneForOne),
6913 // … }` re-inlining that opens a compile-time link to the un-
6914 // lifted arm-literal, a hypothetical `#[serde(rename_all = "…")]`
6915 // attribute drift that silently splits the wire byte-string from
6916 // every consumer that reaches for this typed dispatch, an
6917 // accidental swap onto the kebab-case dispatcher-catalog axis the
6918 // pre-existing [`std::str::FromStr`] impl parses through and which
6919 // would collide the two-axis wire/catalog split the sibling
6920 // [`RestartStrategy::from_wire`] doc block makes load-bearing)
6921 // trips at caixa-core test time under `assert_eq!` rather than at
6922 // a downstream `impl TryFrom<&str>`-bound consumer's silent split.
6923 // Sweeps every one of the four arms [`RestartStrategy::ALL`]
6924 // carries so no arm's projection is covered only by the sibling
6925 // method-named `from_wire` path. Peer of the sibling
6926 // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
6927 // (3c83606),
6928 // [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
6929 // (bf33136), and the M3
6930 // [`crate::aplicacao::tests::placement_strategy_try_from_str_routes_through_from_wire_accessor`]
6931 // (6fd00cd) — extends the trait-idiomatic reverse-projection axis
6932 // onto the first M2-OTP-shape closed-set typed enum on the caixa
6933 // surface.
6934 for &variant in RestartStrategy::ALL {
6935 let wire = variant.as_str();
6936 assert_eq!(
6937 <RestartStrategy as TryFrom<&str>>::try_from(wire),
6938 Ok(variant),
6939 "TryFrom<&str> impl on RestartStrategy must round-trip \
6940 RestartStrategy::{variant:?}.as_str() = {wire:?} back to \
6941 Ok(RestartStrategy::{variant:?}) — divergence from \
6942 RestartStrategy::from_wire signals a silent detour off \
6943 the substrate-primitive accessor"
6944 );
6945 assert_eq!(
6946 <RestartStrategy as TryFrom<&str>>::try_from(wire).ok(),
6947 RestartStrategy::from_wire(wire),
6948 "TryFrom<&str> ok()-projection on {wire:?} must byte-equal \
6949 RestartStrategy::from_wire on the same input"
6950 );
6951 }
6952 }
6953
6954 #[test]
6955 fn restart_strategy_try_from_str_rejects_unknown_byte_strings() {
6956 // Rejection witness on the `impl TryFrom<&str> for
6957 // RestartStrategy` — sweeps a candidate set of byte-strings
6958 // outside the four-arm PascalCase wire accept-set the sibling
6959 // [`RestartStrategy::as_str`] emits and asserts every one lands on
6960 // `Err(())`, so a future accidental widening of the trait impl's
6961 // accept-set (a stray additional
6962 // `_ if s.eq_ignore_ascii_case("OneForOne") => Ok(…)` case-fold
6963 // path, a silent inclusion of the kebab-case dispatcher-catalog
6964 // byte-string the pre-existing [`std::str::FromStr`] impl the
6965 // [`gen_platform::FromStrKind`] derive installs parses onto the
6966 // wire axis — which would collide the two-axis
6967 // wire/dispatcher-catalog split the sibling
6968 // [`RestartStrategy::from_wire`] doc block makes load-bearing —
6969 // an English-rebrand or plural-arm silent alias that would
6970 // widen the wire accept-set past the OTP-canonical four) trips at
6971 // caixa-core test time. The candidate set includes the empty
6972 // string, whitespace-only padding, the kebab-case dispatcher-
6973 // catalog byte-strings on the sibling axis (a caller who confuses
6974 // the two axes trips here rather than at a downstream consumer's
6975 // silent reject), a lowercase / uppercase / mixed-case fold of
6976 // each PascalCase arm (a caller who assumes case-fold acceptance
6977 // trips here), leading/trailing whitespace padding, the trailing-
6978 // newline shape, quote-wrapped candidates, and a residual set of
6979 // plausible-but-wrong English rebrand candidates. Peer of the
6980 // sibling
6981 // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
6982 // (3c83606) and
6983 // [`crate::aplicacao::tests::placement_strategy_try_from_str_rejects_unknown_byte_strings`]
6984 // (6fd00cd) rejection witnesses.
6985 let rejected: &[&str] = &[
6986 "",
6987 " ",
6988 "\n",
6989 "\t",
6990 "one-for-one",
6991 "one-for-all",
6992 "rest-for-one",
6993 "simple-one-for-one",
6994 "oneforone",
6995 "one_for_one",
6996 "OneForOnes",
6997 "ONEFORONE",
6998 "oneforall",
6999 "restforone",
7000 "simpleoneforone",
7001 "OneForOne ",
7002 " OneForOne",
7003 " OneForAll ",
7004 "OneForOne\n",
7005 "RestForOne\t",
7006 "OneForEach",
7007 "AllForOne",
7008 "one for one",
7009 "\"OneForOne\"",
7010 "?",
7011 ];
7012 for &input in rejected {
7013 assert_eq!(
7014 <RestartStrategy as TryFrom<&str>>::try_from(input),
7015 Err(()),
7016 "TryFrom<&str> impl on RestartStrategy must reject the \
7017 non-wire byte-string {input:?} — silent acceptance signals \
7018 an accept-set widening off the paired \
7019 RestartStrategy::from_wire resolver"
7020 );
7021 }
7022 }
7023
7024 #[test]
7025 fn restart_strategy_try_from_str_and_from_wire_partition_the_accept_set() {
7026 // Cross-axis partition pin: the paired `TryFrom<&str>` and
7027 // `from_wire` reverse projections must resolve identically on
7028 // *every* input, not just the ones [`RestartStrategy::ALL`]
7029 // enumerates. Sweeps a mixed candidate set spanning accepted
7030 // (four-arm PascalCase wire byte-strings) and rejected (kebab-case
7031 // dispatcher-catalog byte-strings, empty, whitespace-padded,
7032 // quoted, English-rebrand candidates) inputs and asserts the
7033 // trait's `Result::ok()` projection byte-equals the method-named
7034 // resolver's `Option<Self>` return-shape on each, locking the two
7035 // paths together by construction so any future detour (a stray
7036 // `try_from` special-case that widens or narrows the accept-set
7037 // outside the paired `from_wire` resolver, an accidental swap
7038 // onto the kebab-case [`std::str::FromStr`] impl the
7039 // [`gen_platform::FromStrKind`] derive installs on the sibling
7040 // dispatcher-catalog axis) trips at caixa-core test time. Peer of
7041 // the sibling
7042 // [`crate::kind::tests::caixa_kind_try_from_str_and_from_wire_partition_the_accept_set`]
7043 // pin — extends the round-trip discipline onto the M2-OTP-shape
7044 // sibling-restart axis.
7045 let candidates: &[&str] = &[
7046 "OneForOne",
7047 "OneForAll",
7048 "RestForOne",
7049 "SimpleOneForOne",
7050 "",
7051 "one-for-one",
7052 "one-for-all",
7053 "rest-for-one",
7054 "simple-one-for-one",
7055 "oneforone",
7056 "unknown",
7057 "OneForOne ",
7058 " OneForOne",
7059 "\"OneForOne\"",
7060 "OneForEach",
7061 "?",
7062 ];
7063 for &input in candidates {
7064 let via_trait: Option<RestartStrategy> =
7065 <RestartStrategy as TryFrom<&str>>::try_from(input).ok();
7066 let via_method: Option<RestartStrategy> = RestartStrategy::from_wire(input);
7067 assert_eq!(
7068 via_trait, via_method,
7069 "TryFrom<&str> and from_wire must resolve identically on \
7070 input {input:?} — divergence signals the two reverse-\
7071 projection paths have drifted onto different accept-sets"
7072 );
7073 }
7074 }
7075
7076 #[test]
7077 fn restart_strategy_from_into_static_str_routes_through_as_str_accessor() {
7078 // Fail-before-pass-after byte-parity pin on the newly lifted
7079 // `impl From<RestartStrategy> for &'static str` — asserts the
7080 // standard-library trait impl and the substrate-primitive
7081 // [`RestartStrategy::as_str`] `pub const fn` accessor resolve to
7082 // the same four-arm emit-set across every arm the exhaustive
7083 // [`RestartStrategy::ALL`] slice enumerates. Any future silent
7084 // detour that routes the trait impl through a divergent
7085 // projection (a per-arm inline `match strategy { OneForOne =>
7086 // "OneForOne", … }` re-inlining that opens a compile-time link to
7087 // the un-lifted arm-literal, an accidental swap onto the sibling
7088 // kebab-case [`Self::discriminant`] dispatcher-catalog axis that
7089 // would collide the two-axis wire/catalog split the sibling
7090 // [`RestartStrategy::from_wire`] doc block makes load-bearing) trips
7091 // at caixa-core test time under `assert_eq!` rather than at a
7092 // downstream `impl Into<&'static str>`-bound consumer's silent
7093 // split. Sweeps every one of the four arms
7094 // [`RestartStrategy::ALL`] carries so no arm's projection is
7095 // covered only by the sibling method-named `as_str` /
7096 // [`std::fmt::Display`] / [`AsRef<str>`] paths. Materializes the
7097 // `<&'static str as From<RestartStrategy>>::from` output in a
7098 // `const`-shape binding to make the `'static` lifetime promise a
7099 // build-time invariant — a future accidental downgrade of any of
7100 // the four arms' [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
7101 // constants to a non-`&'static str` (a `String::leak()`-produced
7102 // return, a `Box::leak`-cast) trips at caixa-core build time
7103 // rather than at a downstream `'static`-bound consumer.
7104 const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
7105 const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
7106 const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
7107 const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
7108 for &variant in RestartStrategy::ALL {
7109 let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
7110 let via_method: &'static str = variant.as_str();
7111 assert_eq!(
7112 via_trait, via_method,
7113 "From<RestartStrategy> for &'static str impl must round-trip \
7114 RestartStrategy::{variant:?} to the same lifted \
7115 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str returns — \
7116 divergence signals a silent detour off the substrate-primitive \
7117 accessor"
7118 );
7119 let via_into: &'static str = variant.into();
7120 assert_eq!(
7121 via_into, via_method,
7122 "Into<&'static str>::into on RestartStrategy::{variant:?} must \
7123 byte-equal RestartStrategy::as_str on the same input — the \
7124 blanket-derived Into shape must resolve to the same as_str \
7125 dispatch as the explicit From impl"
7126 );
7127 }
7128 assert_eq!(
7129 [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
7130 [
7131 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7132 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7133 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7134 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7135 ],
7136 "const-context RestartStrategy::as_str must resolve to the four \
7137 lifted SUPERVISOR_ESTRATEGIA_* consts — a future accidental \
7138 downgrade of any arm to a non-const or non-static byte-string \
7139 breaks the `&'static str`-lifetime promise the paired \
7140 From<RestartStrategy> for &'static str impl carries by \
7141 construction"
7142 );
7143 }
7144
7145 #[test]
7146 fn restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set() {
7147 // Cross-axis partition pin: the paired trait-idiomatic
7148 // `From<RestartStrategy> for &'static str` forward projection and
7149 // the method-named [`RestartStrategy::as_str`] forward projection
7150 // must resolve identically on *every* arm, not just the ones
7151 // named in the primary byte-parity pin above. Sweeps every
7152 // [`RestartStrategy::ALL`] arm and asserts the trait's `From::from`
7153 // output byte-equals the method-named accessor's return-value on
7154 // each, locking the two forward-projection paths together by
7155 // construction so any future detour (a stray `From` special-case
7156 // that lands on a divergent per-arm literal outside the paired
7157 // `as_str` dispatch, a hypothetical rebrand touching one axis
7158 // without the other) trips at caixa-core test time. Peer of the
7159 // sibling reverse-projection partition pin
7160 // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
7161 // — extends the round-trip discipline onto the trait-idiomatic
7162 // *forward* axis, closing the two-way `Self ↔ &'static str`
7163 // round-trip on the trait-idiomatic pair
7164 // (`From<Self> for &'static str` + `TryFrom<&str> for Self`) as
7165 // well as the pre-existing method-named pair
7166 // (`as_str` + `from_wire`).
7167 for &variant in RestartStrategy::ALL {
7168 let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
7169 let via_method: &'static str = variant.as_str();
7170 assert_eq!(
7171 via_trait, via_method,
7172 "From<RestartStrategy> for &'static str and \
7173 RestartStrategy::as_str must resolve identically on \
7174 RestartStrategy::{variant:?} — divergence signals the \
7175 two forward-projection paths have drifted onto different \
7176 emit-sets"
7177 );
7178 }
7179 // Round-trip witness: every arm's forward `From` output re-parses
7180 // through the paired trait-idiomatic reverse `TryFrom<&str>` back
7181 // to the original variant. Closes the two-way `RestartStrategy ↔
7182 // &'static str` round-trip on the trait-idiomatic axis pair,
7183 // mirroring the pre-existing method-named `as_str` + `from_wire`
7184 // round-trip on the substrate-primitive axis pair.
7185 for &variant in RestartStrategy::ALL {
7186 let emitted: &'static str = variant.into();
7187 let re_parsed: Result<RestartStrategy, ()> =
7188 <RestartStrategy as TryFrom<&str>>::try_from(emitted);
7189 assert_eq!(
7190 re_parsed,
7191 Ok(variant),
7192 "trait-idiomatic axis pair must round-trip \
7193 RestartStrategy::{variant:?} through `.into::<&'static \
7194 str>()` and back through `TryFrom<&str>` — a break signals \
7195 the forward-emit and reverse-parse axes have drifted onto \
7196 different vocabularies"
7197 );
7198 }
7199 }
7200
7201 #[test]
7202 fn restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
7203 // Fail-before-pass-after byte-parity pin on the newly lifted
7204 // `impl From<&RestartStrategy> for &'static str` — asserts the
7205 // borrowed-input standard-library trait impl and the substrate-
7206 // primitive [`RestartStrategy::as_str`] `pub const fn` accessor
7207 // resolve to the same four-arm emit-set across every arm the
7208 // exhaustive [`RestartStrategy::ALL`] slice enumerates. Rust's
7209 // `From` trait does not auto-derive the borrowed-input sibling
7210 // from a paired owned-input impl (no `impl<T, U> From<&T> for U
7211 // where T: Copy, U: From<T>` blanket in `core`), so the
7212 // borrowed-input axis is a distinct trait-idiomatic surface
7213 // that a `.iter().map(Into::into)` shape over
7214 // [`RestartStrategy::ALL`] (whose iterator yields
7215 // `&RestartStrategy`, not `RestartStrategy`) reaches through
7216 // this impl and no other — the paired owned-input
7217 // [`From<RestartStrategy>`] impl requires an explicit
7218 // `.copied()` / dereference before the trait fires.
7219 // Materializes the `<&'static str as
7220 // From<&RestartStrategy>>::from` output in a `const`-shape
7221 // binding to make the `'static` lifetime promise a build-time
7222 // invariant.
7223 const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
7224 const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
7225 const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
7226 const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
7227 for variant in RestartStrategy::ALL {
7228 let via_trait: &'static str = <&'static str as From<&RestartStrategy>>::from(variant);
7229 let via_method: &'static str = variant.as_str();
7230 assert_eq!(
7231 via_trait, via_method,
7232 "From<&RestartStrategy> for &'static str impl must \
7233 round-trip &RestartStrategy::{variant:?} to the same \
7234 lifted SUPERVISOR_ESTRATEGIA_* const \
7235 RestartStrategy::as_str returns — divergence signals a \
7236 silent detour off the substrate-primitive accessor"
7237 );
7238 let via_into: &'static str = variant.into();
7239 assert_eq!(
7240 via_into, via_method,
7241 "Into<&'static str>::into on &RestartStrategy::{variant:?} \
7242 must byte-equal RestartStrategy::as_str on the same input — \
7243 the blanket-derived Into shape must resolve to the same \
7244 as_str dispatch as the explicit From impl"
7245 );
7246 }
7247 assert_eq!(
7248 [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
7249 [
7250 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7251 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7252 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7253 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7254 ],
7255 "const-context RestartStrategy::as_str must resolve to the \
7256 four lifted SUPERVISOR_ESTRATEGIA_* consts — the borrowed-\
7257 input From<&RestartStrategy> for &'static str impl inherits \
7258 its `'static` lifetime promise from the same accessor the \
7259 owned-input sibling routes through"
7260 );
7261 }
7262
7263 #[test]
7264 fn restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
7265 // Cross-axis partition pin: the paired trait-idiomatic
7266 // owned-input `From<RestartStrategy> for &'static str` (523157d
7267 // campaign-shape) and borrowed-input `From<&RestartStrategy> for
7268 // &'static str` (this lift) forward projections must resolve
7269 // identically on every arm, locking the two input-shape paths
7270 // together so any future detour trips at caixa-core test time.
7271 // Then a witness that a `.iter().map(Into::into)` pipe over
7272 // [`RestartStrategy::ALL`] (whose iterator yields
7273 // `&RestartStrategy`) materializes the four-arm accept-set
7274 // through the borrowed-input axis alone — the exact shape a
7275 // future wasm-operator per-supervisor sibling-restart-strategy
7276 // diagnostic line, a future substrate-wide per-arm diagnostic
7277 // column, or a
7278 // `HashMap::<&'static str, RestartStrategy>::from_iter(
7279 // RestartStrategy::ALL.iter().map(|s| (s.into(), *s)))`-style
7280 // per-strategy lookup reaches through — closing the two-way
7281 // owned/borrowed input-shape symmetry on the forward-projection
7282 // trait-idiomatic axis. Peer of the sibling
7283 // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
7284 // (64aa742) /
7285 // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
7286 // (5ab993a) /
7287 // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
7288 // (807b0b5) partition pins on the sibling closed-set typed-enum
7289 // discriminator axes — extends the borrowed-input axis
7290 // discipline onto the first M2 OTP-shape sibling-restart
7291 // closed-set typed enum on the caixa surface. Also closes the
7292 // direct two-way `&Self → &'static str → Self` round-trip via
7293 // the paired [`TryFrom<&str>`] axis — unlike the peer
7294 // [`crate::CaixaKind`] axis pair (whose forward `From` emits
7295 // lowercase Portuguese diagnostic bytes while the reverse
7296 // `TryFrom` parses `PascalCase` wire bytes, forcing the round-
7297 // trip through an intermediate wire-vocab hop), the
7298 // [`RestartStrategy::as_str`] emit and
7299 // [`RestartStrategy::from_wire`] parse share the same
7300 // `PascalCase` vocabulary by construction, so the borrowed-
7301 // input forward axis and the reverse axis compose directly.
7302 for &variant in RestartStrategy::ALL {
7303 let owned: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
7304 let borrowed: &'static str = <&'static str as From<&RestartStrategy>>::from(&variant);
7305 assert_eq!(
7306 owned, borrowed,
7307 "From<RestartStrategy> and From<&RestartStrategy> for \
7308 &'static str must resolve identically on \
7309 RestartStrategy::{variant:?} — divergence signals the \
7310 owned-input and borrowed-input forward-projection paths \
7311 have drifted onto different emit-sets"
7312 );
7313 }
7314 let via_iter: Vec<&'static str> = RestartStrategy::ALL.iter().map(Into::into).collect();
7315 let via_method: Vec<&'static str> =
7316 RestartStrategy::ALL.iter().map(|s| s.as_str()).collect();
7317 assert_eq!(
7318 via_iter, via_method,
7319 "`.iter().map(Into::into)` over RestartStrategy::ALL must \
7320 byte-equal `.iter().map(|s| s.as_str())` on every arm — the \
7321 borrowed-input `From<&RestartStrategy> for &'static str` \
7322 axis is what makes the `.iter().map(Into::into)` shape route \
7323 through the substrate-primitive `RestartStrategy::as_str` \
7324 accessor rather than through a per-call-site `.copied()` / \
7325 dereference detour"
7326 );
7327 for variant in RestartStrategy::ALL {
7328 let emitted: &'static str = variant.into();
7329 let re_parsed: Result<RestartStrategy, ()> =
7330 <RestartStrategy as TryFrom<&str>>::try_from(emitted);
7331 assert_eq!(
7332 re_parsed,
7333 Ok(*variant),
7334 "trait-idiomatic borrowed-input forward-projection + \
7335 reverse-projection axis pair must round-trip \
7336 &RestartStrategy::{variant:?} through `.into::<&'static \
7337 str>()` (via the borrowed-input axis) and back through \
7338 `TryFrom<&str>` — a break signals the borrowed-input \
7339 forward-emit and reverse-parse axes have drifted onto \
7340 different vocabularies"
7341 );
7342 }
7343 }
7344
7345 #[test]
7346 fn restart_policy_try_from_str_routes_through_from_wire_accessor() {
7347 // Fail-before-pass-after byte-parity pin on the newly lifted
7348 // `impl TryFrom<&str> for RestartPolicy` — asserts the standard-
7349 // library trait impl and the substrate-primitive
7350 // [`RestartPolicy::from_wire`] `Option<Self>` accessor resolve to
7351 // the same three-arm accept-set across every arm the exhaustive
7352 // [`RestartPolicy::ALL`] slice enumerates. Any future silent
7353 // detour that routes the trait impl through a divergent
7354 // projection (a per-arm inline `match s { "Permanent" =>
7355 // Ok(Self::Permanent), … }` re-inlining that opens a compile-time
7356 // link to the un-lifted arm-literal, a hypothetical
7357 // `#[serde(rename_all = "…")]` attribute drift that silently
7358 // splits the wire byte-string from every consumer that reaches
7359 // for this typed dispatch, an accidental swap onto the kebab-case
7360 // dispatcher-catalog axis the pre-existing [`std::str::FromStr`]
7361 // impl parses through and which would collide the two-axis
7362 // wire/catalog split the sibling [`RestartPolicy::from_wire`]
7363 // doc block makes load-bearing) trips at caixa-core test time
7364 // under `assert_eq!` rather than at a downstream
7365 // `impl TryFrom<&str>`-bound consumer's silent split. Sweeps
7366 // every one of the three arms [`RestartPolicy::ALL`] carries so
7367 // no arm's projection is covered only by the sibling method-
7368 // named `from_wire` path. Peer of the sibling
7369 // [`restart_strategy_try_from_str_routes_through_from_wire_accessor`]
7370 // (5b828ed) — extends the trait-idiomatic reverse-projection
7371 // axis onto the third and final M2-OTP-shape closed-set typed
7372 // enum on the caixa surface (the paired per-child restart-
7373 // decision-policy sibling on the same M2 `:supervisor` slot).
7374 for &variant in RestartPolicy::ALL {
7375 let wire = variant.as_str();
7376 assert_eq!(
7377 <RestartPolicy as TryFrom<&str>>::try_from(wire),
7378 Ok(variant),
7379 "TryFrom<&str> impl on RestartPolicy must round-trip \
7380 RestartPolicy::{variant:?}.as_str() = {wire:?} back to \
7381 Ok(RestartPolicy::{variant:?}) — divergence from \
7382 RestartPolicy::from_wire signals a silent detour off \
7383 the substrate-primitive accessor"
7384 );
7385 assert_eq!(
7386 <RestartPolicy as TryFrom<&str>>::try_from(wire).ok(),
7387 RestartPolicy::from_wire(wire),
7388 "TryFrom<&str> ok()-projection on {wire:?} must byte-\
7389 equal RestartPolicy::from_wire on the same input"
7390 );
7391 }
7392 }
7393
7394 #[test]
7395 fn restart_policy_try_from_str_rejects_unknown_byte_strings() {
7396 // Rejection witness on the `impl TryFrom<&str> for
7397 // RestartPolicy` — sweeps a candidate set of byte-strings
7398 // outside the three-arm PascalCase wire accept-set the sibling
7399 // [`RestartPolicy::as_str`] emits and asserts every one lands on
7400 // `Err(())`, so a future accidental widening of the trait impl's
7401 // accept-set (a stray additional
7402 // `_ if s.eq_ignore_ascii_case("Permanent") => Ok(…)` case-fold
7403 // path, a silent inclusion of the kebab-case dispatcher-catalog
7404 // byte-string the pre-existing [`std::str::FromStr`] impl the
7405 // [`gen_platform::FromStrKind`] derive installs parses onto the
7406 // wire axis — which would collide the two-axis
7407 // wire/dispatcher-catalog split the sibling
7408 // [`RestartPolicy::from_wire`] doc block makes load-bearing —
7409 // an English-rebrand or plural-arm silent alias that would widen
7410 // the wire accept-set past the OTP-canonical three) trips at
7411 // caixa-core test time. The candidate set includes the empty
7412 // string, whitespace-only padding, the kebab-case dispatcher-
7413 // catalog byte-strings on the sibling axis (a caller who
7414 // confuses the two axes trips here rather than at a downstream
7415 // consumer's silent reject), a lowercase / uppercase / mixed-case
7416 // fold of each PascalCase arm (a caller who assumes case-fold
7417 // acceptance trips here), leading/trailing whitespace padding,
7418 // the trailing-newline shape, quote-wrapped candidates, and a
7419 // residual set of plausible-but-wrong English rebrand
7420 // candidates. Peer of the sibling
7421 // [`restart_strategy_try_from_str_rejects_unknown_byte_strings`]
7422 // (5b828ed) rejection witness.
7423 let rejected: &[&str] = &[
7424 "",
7425 " ",
7426 "\n",
7427 "\t",
7428 "permanent",
7429 "temporary",
7430 "transient",
7431 "PERMANENT",
7432 "TEMPORARY",
7433 "TRANSIENT",
7434 "Permanents",
7435 "Permanent ",
7436 " Permanent",
7437 " Temporary ",
7438 "Permanent\n",
7439 "Transient\t",
7440 "\"Permanent\"",
7441 "Ephemeral",
7442 "Always",
7443 "Never",
7444 "OnAbnormalExit",
7445 "intrinsic",
7446 "?",
7447 ];
7448 for &input in rejected {
7449 assert_eq!(
7450 <RestartPolicy as TryFrom<&str>>::try_from(input),
7451 Err(()),
7452 "TryFrom<&str> impl on RestartPolicy must reject the \
7453 non-wire byte-string {input:?} — silent acceptance \
7454 signals an accept-set widening off the paired \
7455 RestartPolicy::from_wire resolver"
7456 );
7457 }
7458 }
7459
7460 #[test]
7461 fn restart_policy_try_from_str_and_from_wire_partition_the_accept_set() {
7462 // Cross-axis partition pin: the paired `TryFrom<&str>` and
7463 // `from_wire` reverse projections must resolve identically on
7464 // *every* input, not just the ones [`RestartPolicy::ALL`]
7465 // enumerates. Sweeps a mixed candidate set spanning accepted
7466 // (three-arm PascalCase wire byte-strings) and rejected (kebab-
7467 // case dispatcher-catalog byte-strings, empty, whitespace-
7468 // padded, quoted, English-rebrand candidates) inputs and asserts
7469 // the trait's `Result::ok()` projection byte-equals the method-
7470 // named resolver's `Option<Self>` return-shape on each, locking
7471 // the two paths together by construction so any future detour
7472 // (a stray `try_from` special-case that widens or narrows the
7473 // accept-set outside the paired `from_wire` resolver, an
7474 // accidental swap onto the kebab-case [`std::str::FromStr`]
7475 // impl the [`gen_platform::FromStrKind`] derive installs on the
7476 // sibling dispatcher-catalog axis) trips at caixa-core test
7477 // time. Peer of the sibling
7478 // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
7479 // pin — extends the round-trip discipline onto the M2-OTP-shape
7480 // per-child restart-policy axis.
7481 let candidates: &[&str] = &[
7482 "Permanent",
7483 "Temporary",
7484 "Transient",
7485 "",
7486 "permanent",
7487 "temporary",
7488 "transient",
7489 "PERMANENT",
7490 "unknown",
7491 "Permanent ",
7492 " Permanent",
7493 "\"Permanent\"",
7494 "Ephemeral",
7495 "OnAbnormalExit",
7496 "?",
7497 ];
7498 for &input in candidates {
7499 let via_trait: Option<RestartPolicy> =
7500 <RestartPolicy as TryFrom<&str>>::try_from(input).ok();
7501 let via_method: Option<RestartPolicy> = RestartPolicy::from_wire(input);
7502 assert_eq!(
7503 via_trait, via_method,
7504 "TryFrom<&str> and from_wire must resolve identically on \
7505 input {input:?} — divergence signals the two reverse-\
7506 projection paths have drifted onto different accept-sets"
7507 );
7508 }
7509 }
7510
7511 #[test]
7512 fn restart_policy_from_into_static_str_routes_through_as_str_accessor() {
7513 // Fail-before-pass-after byte-parity pin on the newly lifted
7514 // `impl From<RestartPolicy> for &'static str` — asserts the
7515 // standard-library trait impl and the substrate-primitive
7516 // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
7517 // the same three-arm emit-set across every arm the exhaustive
7518 // [`RestartPolicy::ALL`] slice enumerates. Any future silent
7519 // detour that routes the trait impl through a divergent
7520 // projection (a per-arm inline `match policy { Permanent =>
7521 // "Permanent", … }` re-inlining that opens a compile-time link
7522 // to the un-lifted arm-literal, an accidental swap onto the
7523 // sibling kebab-case [`Self::discriminant`] dispatcher-catalog
7524 // axis that would collide the two-axis wire/catalog split the
7525 // sibling [`RestartPolicy::from_wire`] doc block makes
7526 // load-bearing) trips at caixa-core test time under
7527 // `assert_eq!` rather than at a downstream
7528 // `impl Into<&'static str>`-bound consumer's silent split.
7529 // Sweeps every one of the three arms [`RestartPolicy::ALL`]
7530 // carries so no arm's projection is covered only by the sibling
7531 // method-named `as_str` / [`std::fmt::Display`] / [`AsRef<str>`]
7532 // paths. Materializes the `<&'static str as
7533 // From<RestartPolicy>>::from` output in a `const`-shape binding
7534 // to make the `'static` lifetime promise a build-time invariant
7535 // — a future accidental downgrade of any of the three arms'
7536 // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] constants to a
7537 // non-`&'static str` (a `String::leak()`-produced return, a
7538 // `Box::leak`-cast) trips at caixa-core build time rather than
7539 // at a downstream `'static`-bound consumer. Peer of the sibling
7540 // [`restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
7541 // (523157d) — extends the trait-idiomatic forward-projection
7542 // axis onto the second (and second-of-two-in-M2) closed-set
7543 // typed enum on the caixa surface (the paired per-child
7544 // restart-decision-policy sibling on the same M2 `:supervisor`
7545 // slot).
7546 const PERMANENT: &str = RestartPolicy::Permanent.as_str();
7547 const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
7548 const TRANSIENT: &str = RestartPolicy::Transient.as_str();
7549 for &variant in RestartPolicy::ALL {
7550 let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
7551 let via_method: &'static str = variant.as_str();
7552 assert_eq!(
7553 via_trait, via_method,
7554 "From<RestartPolicy> for &'static str impl must round-trip \
7555 RestartPolicy::{variant:?} to the same lifted \
7556 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str returns — \
7557 divergence signals a silent detour off the substrate-primitive \
7558 accessor"
7559 );
7560 let via_into: &'static str = variant.into();
7561 assert_eq!(
7562 via_into, via_method,
7563 "Into<&'static str>::into on RestartPolicy::{variant:?} must \
7564 byte-equal RestartPolicy::as_str on the same input — the \
7565 blanket-derived Into shape must resolve to the same as_str \
7566 dispatch as the explicit From impl"
7567 );
7568 }
7569 assert_eq!(
7570 [PERMANENT, TEMPORARY, TRANSIENT],
7571 [
7572 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
7573 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
7574 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
7575 ],
7576 "const-context RestartPolicy::as_str must resolve to the three \
7577 lifted SUPERVISOR_CHILD_RESTART_* consts — a future accidental \
7578 downgrade of any arm to a non-const or non-static byte-string \
7579 breaks the `&'static str`-lifetime promise the paired \
7580 From<RestartPolicy> for &'static str impl carries by \
7581 construction"
7582 );
7583 }
7584
7585 #[test]
7586 fn restart_policy_from_into_static_str_and_as_str_partition_the_emit_set() {
7587 // Cross-axis partition pin: the paired trait-idiomatic
7588 // `From<RestartPolicy> for &'static str` forward projection and
7589 // the method-named [`RestartPolicy::as_str`] forward projection
7590 // must resolve identically on *every* arm, not just the ones
7591 // named in the primary byte-parity pin above. Sweeps every
7592 // [`RestartPolicy::ALL`] arm and asserts the trait's `From::from`
7593 // output byte-equals the method-named accessor's return-value on
7594 // each, locking the two forward-projection paths together by
7595 // construction so any future detour (a stray `From` special-case
7596 // that lands on a divergent per-arm literal outside the paired
7597 // `as_str` dispatch, a hypothetical rebrand touching one axis
7598 // without the other) trips at caixa-core test time. Peer of the
7599 // sibling forward-projection partition pin
7600 // [`restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
7601 // (523157d) — extends the round-trip discipline onto the
7602 // second-of-two M2-OTP-shape closed-set typed enum on the caixa
7603 // surface, closing the two-way `Self ↔ &'static str` round-trip
7604 // on the trait-idiomatic pair (`From<Self> for &'static str` +
7605 // `TryFrom<&str> for Self`) as well as the pre-existing method-
7606 // named pair (`as_str` + `from_wire`).
7607 for &variant in RestartPolicy::ALL {
7608 let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
7609 let via_method: &'static str = variant.as_str();
7610 assert_eq!(
7611 via_trait, via_method,
7612 "From<RestartPolicy> for &'static str and \
7613 RestartPolicy::as_str must resolve identically on \
7614 RestartPolicy::{variant:?} — divergence signals the \
7615 two forward-projection paths have drifted onto different \
7616 emit-sets"
7617 );
7618 }
7619 // Round-trip witness: every arm's forward `From` output re-parses
7620 // through the paired trait-idiomatic reverse `TryFrom<&str>` back
7621 // to the original variant. Closes the two-way `RestartPolicy ↔
7622 // &'static str` round-trip on the trait-idiomatic axis pair,
7623 // mirroring the pre-existing method-named `as_str` + `from_wire`
7624 // round-trip on the substrate-primitive axis pair.
7625 for &variant in RestartPolicy::ALL {
7626 let emitted: &'static str = variant.into();
7627 let re_parsed: Result<RestartPolicy, ()> =
7628 <RestartPolicy as TryFrom<&str>>::try_from(emitted);
7629 assert_eq!(
7630 re_parsed,
7631 Ok(variant),
7632 "trait-idiomatic axis pair must round-trip \
7633 RestartPolicy::{variant:?} through `.into::<&'static \
7634 str>()` and back through `TryFrom<&str>` — a break signals \
7635 the forward-emit and reverse-parse axes have drifted onto \
7636 different vocabularies"
7637 );
7638 }
7639 }
7640
7641 // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_RESTART_* identity ─
7642
7643 #[test]
7644 fn restart_policy_variants_serialize_to_lifted_scalar_values() {
7645 // The fail-before-pass-after pin: pre-lift there was no
7646 // single-source binding between the [`RestartPolicy`] variant
7647 // name the un-`rename`d `Serialize` derive emits under
7648 // [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
7649 // byte-string every downstream cluster-side dispatcher (the
7650 // future wasm-operator's per-child post-exit restart-decision
7651 // branch, the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
7652 // materializer's admission-time enum-arm bind, the
7653 // `caixa-operator`'s hierarchical reconciliation scheduler's
7654 // per-child-policy fan-out) probes verbatim. A future
7655 // `#[serde(rename_all = "kebab-case")]` attribute on the enum —
7656 // or a per-variant `#[serde(rename = "…")]` override, or a
7657 // variant rename in the source — would silently rebrand the
7658 // emitted scalar under one spelling while every downstream
7659 // dispatcher still probed the other, with the failure surfacing
7660 // at the operator's reconcile posture (children coming up under
7661 // the `default()` `Permanent` arm rather than the typed slot's
7662 // declared policy — a `:temporary` `oneShot` child would be
7663 // restarted on clean exit, treating the successful-completion
7664 // signal as failure and re-running the completion-terminal
7665 // one-shot indefinitely; a `:transient` child that clean-exited
7666 // would be restarted, masking the clean-completion contract)
7667 // far from the source rebrand commit and with no field naming
7668 // the drift. Pinning the two paths (the `Serialize` derive's
7669 // serialized string AND the [`RestartPolicy::as_str`] helper)
7670 // to the same three lifted
7671 // [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
7672 // [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
7673 // [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
7674 // byte-strings makes any future drift on either endpoint fail
7675 // here at caixa-core build time. Peer of the sibling
7676 // [`restart_strategy_variants_serialize_to_lifted_scalar_values`]
7677 // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
7678 // and the M3
7679 // `placement_strategy_variants_serialize_to_lifted_scalar_values`
7680 // (3f0e21c) on the per-Aplicacao distribution-strategy axis —
7681 // same three-path-convergence discipline, extended to close the
7682 // third OTP-shaped closed-enum discriminator axis on the caixa
7683 // typed surface (per-child restart-decision policy).
7684 for (variant, expected) in [
7685 (
7686 RestartPolicy::Permanent,
7687 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
7688 ),
7689 (
7690 RestartPolicy::Temporary,
7691 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
7692 ),
7693 (
7694 RestartPolicy::Transient,
7695 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
7696 ),
7697 ] {
7698 let json = serde_json::to_string(&variant).unwrap();
7699 assert_eq!(
7700 json,
7701 format!("\"{expected}\""),
7702 "RestartPolicy::{variant:?} must serialize to {expected:?}"
7703 );
7704 assert_eq!(
7705 variant.as_str(),
7706 expected,
7707 "RestartPolicy::{variant:?}.as_str() must return the lifted \
7708 SUPERVISOR_CHILD_RESTART_* constant"
7709 );
7710 }
7711 }
7712
7713 #[test]
7714 fn supervisor_child_restart_consts_are_pairwise_distinct() {
7715 // Cross-arm drift-detection pin: a future collapse of two
7716 // canonical variant byte-strings onto the same value (e.g. an
7717 // accidental copy-paste flip of `SUPERVISOR_CHILD_RESTART_TRANSIENT`
7718 // to also read `"Permanent"`) would silently reroute every
7719 // downstream operator's per-child-policy dispatch onto the
7720 // sibling arm's reconcile branch and pass every propagation-probe
7721 // test that expected only the stale arm's value — a `:transient`
7722 // child would come up under the `:permanent` restart-decision
7723 // posture on every subsequent clean exit, so a completion-terminal
7724 // child would be restarted indefinitely against its declared
7725 // policy. Peer of the sibling
7726 // [`supervisor_estrategia_consts_are_pairwise_distinct`]
7727 // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
7728 // and the four-way distinct pin
7729 // `supervisor_key_consts_are_pairwise_distinct` (40cc4e5) on the
7730 // top-level `SUPERVISOR_KEY_*` axis.
7731 let all = [
7732 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
7733 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
7734 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
7735 ];
7736 for (i, a) in all.iter().enumerate() {
7737 for (j, b) in all.iter().enumerate() {
7738 if i != j {
7739 assert_ne!(
7740 a, b,
7741 "SUPERVISOR_CHILD_RESTART_* consts must be pairwise distinct \
7742 — got duplicate {a:?} at indices {i} and {j}",
7743 );
7744 }
7745 }
7746 }
7747 }
7748
7749 #[test]
7750 fn restart_policy_display_routes_through_as_str_helper() {
7751 // The fail-before-pass-after pin on the first half of the
7752 // three-path convergence: pre-convergence [`RestartPolicy`]
7753 // carried a [`std::fmt::Display`] surface via its
7754 // `#[discriminant(also_display)]` gen-platform derive route,
7755 // which arrived kebab-case as `"permanent"` / `"temporary"`
7756 // / `"transient"` on this three-arm enum (whose variant
7757 // names each collapse to their own lowercase form under the
7758 // kebab-case transform) while the wire format ran as
7759 // PascalCase `"Permanent"` / `"Temporary"` / `"Transient"`
7760 // through the un-`rename`d serde derive. Every consumer
7761 // reaching for a policy byte-string past the wire format had
7762 // to pick between three paths ([`RestartPolicy::as_str`],
7763 // the `Serialize` derive's serialized string, or
7764 // `format!("{v}")` on the discriminant-Display route), any
7765 // two of which a future variant rename or
7766 // `#[serde(rename_all = "kebab-case")]` attribute would
7767 // silently desynchronize. Wiring [`std::fmt::Display`]
7768 // through [`RestartPolicy::as_str`] closes the third path:
7769 // every `format!("{v}")` call reaches the same lifted
7770 // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the
7771 // wire format and the [`RestartPolicy::as_str`] helper
7772 // already route through, so a future variant rename lands at
7773 // exactly one place. Pin the routing here so a future
7774 // `impl std::fmt::Display for RestartPolicy`
7775 // reimplementation that hand-rolls the arms instead of
7776 // delegating to [`RestartPolicy::as_str`] fails at
7777 // caixa-core build time. Peer of the sibling
7778 // [`restart_strategy_display_routes_through_as_str_helper`]
7779 // on the per-supervisor sibling-restart-strategy axis and
7780 // the M3
7781 // `placement_strategy_display_routes_through_as_str_helper`
7782 // (cc8f749) — the third of three OTP-shape closed-enum
7783 // discriminator axes on the caixa typed surface now
7784 // converged onto the same three-path
7785 // (Display → as_str → lifted const) discipline.
7786 for variant in [
7787 RestartPolicy::Permanent,
7788 RestartPolicy::Temporary,
7789 RestartPolicy::Transient,
7790 ] {
7791 assert_eq!(
7792 variant.to_string(),
7793 variant.as_str(),
7794 "RestartPolicy::{variant:?} Display must route through \
7795 RestartPolicy::as_str (single source of truth: the lifted \
7796 SUPERVISOR_CHILD_RESTART_* const the wire format also emits)"
7797 );
7798 }
7799 }
7800
7801 #[test]
7802 fn restart_policy_display_matches_serialized_wire_byte_string() {
7803 // The fail-before-pass-after pin on the second half of the
7804 // three-path convergence: `Display` (user-facing text) agrees
7805 // byte-for-byte with the `Serialize` derive's wire format
7806 // (canonical camelCase-schema `SUPERVISOR_CHILD_KEY_RESTART`
7807 // scalar) on every variant. Pre-convergence the two paths
7808 // were structurally independent — a future
7809 // `#[serde(rename_all = "kebab-case")]` attribute on the
7810 // enum would silently rebrand the emitted wire scalar
7811 // (`permanent`, `temporary`, `transient`) while every
7812 // consumer that pretty-prints the policy (the future
7813 // wasm-operator's per-child post-exit restart-decision
7814 // diagnostic line, the future `feira app graph` per-child
7815 // restart column, the future M4
7816 // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
7817 // per-child admission-webhook rejection body) would still
7818 // emit the PascalCase form the `as_str` / `Display` route
7819 // returns, with the mismatch surfacing at consumer parse
7820 // time / operator dispatch time far from the source rebrand
7821 // commit. Pin the two paths byte-for-byte here so any future
7822 // serde-attribute or variant-rename drift is a
7823 // caixa-core-build-time test failure at this call, not a
7824 // silent per-consumer dispatch miss. Peer of the sibling
7825 // [`restart_strategy_display_matches_serialized_wire_byte_string`]
7826 // on the per-supervisor sibling-restart-strategy axis and
7827 // the M3
7828 // `placement_strategy_display_matches_serialized_wire_byte_string`
7829 // (cc8f749).
7830 for variant in [
7831 RestartPolicy::Permanent,
7832 RestartPolicy::Temporary,
7833 RestartPolicy::Transient,
7834 ] {
7835 let wire = serde_json::to_string(&variant).unwrap();
7836 let unquoted = wire
7837 .strip_prefix('"')
7838 .and_then(|s| s.strip_suffix('"'))
7839 .expect("serialized RestartPolicy is a JSON string");
7840 assert_eq!(
7841 variant.to_string(),
7842 unquoted,
7843 "RestartPolicy::{variant:?} Display byte-string must match the \
7844 Serialize derive's wire byte-string (three-path convergence: \
7845 Display + as_str + Serialize all resolve to the same \
7846 SUPERVISOR_CHILD_RESTART_* const)"
7847 );
7848 }
7849 }
7850
7851 #[test]
7852 fn restart_policy_as_ref_str_routes_through_as_str_accessor() {
7853 // Fail-before-pass-after byte-parity pin on the lifted
7854 // `impl AsRef<str> for RestartPolicy` — asserts the
7855 // standard-library trait impl and the substrate-primitive
7856 // [`RestartPolicy::as_str`] `pub const fn` accessor resolve
7857 // to the same `&str` per instance across the three-arm
7858 // closed set, so any future silent detour that routes the
7859 // impl through a divergent projection (a per-arm inline
7860 // `match self { RestartPolicy::Permanent => "Permanent", … }`
7861 // re-inlining that opens a compile-time link to the un-lifted
7862 // arm-literal, a swap onto the kebab-case
7863 // [`gen_platform::Discriminant`] catalog identity that would
7864 // collide the wire axis with the dispatcher-catalog axis) trips
7865 // at caixa-core test time under `PartialEq` rather than at a
7866 // downstream `impl AsRef<str>`-bound consumer's silent split.
7867 // Sweeps every one of the three arms
7868 // [`RestartPolicy::ALL`] carries so no arm's projection is
7869 // covered only by the sibling wire-format `Serialize` derive
7870 // path. Peer of the sibling
7871 // [`restart_strategy_as_ref_str_routes_through_as_str_accessor`]
7872 // (63eb1a4) on the paired per-supervisor sibling-restart-
7873 // strategy axis and the [`crate::CaixaVersion`]
7874 // `AsRef<str>`-byte-parity pin (16d5c7e) on the paired
7875 // top-level `:versao` typed newtype — the three pins together
7876 // cover the substrate primitive's `AsRef<str>` projection axis
7877 // on the paired newtype + M2 closed-set-typed-enum surface.
7878 for &variant in RestartPolicy::ALL {
7879 assert_eq!(
7880 <RestartPolicy as AsRef<str>>::as_ref(&variant),
7881 variant.as_str(),
7882 "AsRef<str> impl on RestartPolicy::{variant:?} must \
7883 byte-equal RestartPolicy::as_str on the same instance \
7884 — divergence signals a silent detour off the substrate-\
7885 primitive accessor"
7886 );
7887 }
7888 }
7889
7890 #[test]
7891 fn restart_policy_as_ref_str_routes_through_display_via_shared_accessor() {
7892 // Fail-before-pass-after byte-parity pin on the three-path
7893 // convergence discipline the M2 per-child-restart-policy
7894 // primitive now carries on the `&str`-projection axis:
7895 // `<RestartPolicy as AsRef<str>>::as_ref(&v)` (the newly
7896 // lifted impl), `format!("{v}")` (the pre-existing
7897 // [`fmt::Display`] impl), and `v.as_str()` (the substrate-
7898 // primitive `pub const fn` accessor both trait impls delegate
7899 // through) must resolve to the same byte-string on every
7900 // instance across the three-arm closed set. Refuses any future
7901 // divergence between the two trait impls (a stray
7902 // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
7903 // rather than delegating through the shared accessor; a
7904 // hypothetical `AsRef<str>` rewrite that inlines a per-arm
7905 // literal cascade) that would silently split the two
7906 // projection paths of the same closed-set typed enum. Mirrors
7907 // the sibling three-path-convergence discipline the peer
7908 // [`RestartStrategy`] typed enum carries on its
7909 // `AsRef<str>` / `Display` / `as_str` triple
7910 // (supervisor.rs pin
7911 // `restart_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
7912 // 63eb1a4) and the [`crate::CaixaVersion`] typed newtype
7913 // carries on the same triple (version.rs pin
7914 // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
7915 // 16d5c7e).
7916 for &variant in RestartPolicy::ALL {
7917 let via_as_ref: &str = <RestartPolicy as AsRef<str>>::as_ref(&variant);
7918 let via_display: String = format!("{variant}");
7919 let via_accessor: &str = variant.as_str();
7920 assert_eq!(via_as_ref, via_accessor);
7921 assert_eq!(via_display, via_accessor);
7922 assert_eq!(via_as_ref, via_display.as_str());
7923 }
7924 }
7925
7926 #[test]
7927 fn restart_policy_all_enumerates_every_variant_exactly_once() {
7928 // Fail-before-pass-after pin on the [`RestartPolicy::ALL`]
7929 // exhaustive-iteration surface: every variant appears exactly
7930 // once, and the slice length matches the arm count of the
7931 // closed set. Every consumer that walks the accepted-policy
7932 // set (a future `feira supervisor --restart …` CLI-side
7933 // arg-parse's "did you mean" hint, a future M4 admission-
7934 // webhook's per-child rejection body naming the accepted-
7935 // `:restart` list, the [`RestartPolicy::from_wire`] reverse-
7936 // projection consumers that iterate the accept-set for
7937 // diagnostic rendering) reads through this slice, so a future
7938 // arm addition that grows the enum but forgets to grow
7939 // [`Self::ALL`] silently truncates every downstream consumer's
7940 // accept-set at the same pre-addition boundary — this pin
7941 // fails at caixa-core build time on the pairwise-distinct +
7942 // arm-count invariants.
7943 //
7944 // Peer of the sibling [`RestartStrategy::ALL`] (4eec29c) /
7945 // [`crate::CaixaKind::ALL`] (6b1f4fb) /
7946 // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
7947 // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
7948 // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
7949 // pins on the peer closed-set typed-enum axes.
7950 let all: &[RestartPolicy] = RestartPolicy::ALL;
7951 assert_eq!(
7952 all.len(),
7953 3,
7954 "RestartPolicy::ALL must enumerate every variant of the \
7955 three-arm closed set (Permanent, Temporary, Transient); \
7956 got {all:?}"
7957 );
7958 for (i, a) in all.iter().enumerate() {
7959 for (j, b) in all.iter().enumerate() {
7960 if i != j {
7961 assert_ne!(
7962 a, b,
7963 "RestartPolicy::ALL must carry every variant exactly \
7964 once — got duplicate {a:?} at indices {i} and {j}"
7965 );
7966 }
7967 }
7968 }
7969 for variant in [
7970 RestartPolicy::Permanent,
7971 RestartPolicy::Temporary,
7972 RestartPolicy::Transient,
7973 ] {
7974 assert!(
7975 all.contains(&variant),
7976 "RestartPolicy::ALL must contain {variant:?} — a future arm \
7977 addition that grows the enum but forgets to grow the ALL slice \
7978 silently truncates every downstream consumer's accept-set at \
7979 the pre-addition boundary"
7980 );
7981 }
7982 }
7983
7984 #[test]
7985 fn restart_policy_from_wire_accepts_every_lifted_constant() {
7986 // Fail-before-pass-after pin on the forward accept-set of the
7987 // [`RestartPolicy::from_wire`] reverse projection: every
7988 // canonical [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
7989 // constant the [`RestartPolicy::as_str`] emitter walks parses
7990 // back to its paired variant. Any future arm addition that
7991 // grows the emitter's `as_str` match but forgets to grow the
7992 // parser's `from_wire` match silently splits the two halves of
7993 // the round-trip — the wire byte-string one non-serde consumer
7994 // parses from the one the emitter wrote — with the failure
7995 // surfacing at the operator's reconcile posture (a `:temporary`
7996 // `oneShot` child restarted on clean exit, a `:transient` child
7997 // restarted after clean completion) far from the rebrand
7998 // commit. Pinning the three-arm accept-set here catches the
7999 // drift at caixa-core build time.
8000 //
8001 // Peer of the sibling [`RestartStrategy::from_wire`] (4eec29c)
8002 // + [`crate::CaixaKind::from_wire`] (2aa6d23)
8003 // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
8004 // accept-set pins on the peer closed-set typed-enum `str → Self`
8005 // axes.
8006 for (wire, expected) in [
8007 (
8008 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
8009 RestartPolicy::Permanent,
8010 ),
8011 (
8012 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
8013 RestartPolicy::Temporary,
8014 ),
8015 (
8016 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
8017 RestartPolicy::Transient,
8018 ),
8019 ] {
8020 let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
8021 panic!(
8022 "RestartPolicy::from_wire({wire:?}) must accept every \
8023 SUPERVISOR_CHILD_RESTART_* constant — got None for the \
8024 lifted canonical byte-string that RestartPolicy::{expected:?} \
8025 serializes as under SUPERVISOR_CHILD_KEY_RESTART"
8026 )
8027 });
8028 assert_eq!(
8029 parsed, expected,
8030 "RestartPolicy::from_wire({wire:?}) must return \
8031 RestartPolicy::{expected:?}; got RestartPolicy::{parsed:?}"
8032 );
8033 }
8034 }
8035
8036 #[test]
8037 fn restart_policy_from_wire_round_trips_through_as_str() {
8038 // Fail-before-pass-after pin on the closed round-trip between
8039 // the forward [`RestartPolicy::as_str`] emitter and the
8040 // reverse [`RestartPolicy::from_wire`] parser: for every
8041 // variant in [`RestartPolicy::ALL`], parsing the emitter's
8042 // output must return exactly the same variant. Any per-arm
8043 // divergence — a future arm added to `as_str` but not
8044 // `from_wire`, an accidental copy-paste flip in one but not
8045 // the other — silently splits the emit and parse halves and
8046 // the failure surfaces at consumer parse time far from the
8047 // drift site. The `ALL`-iterating shape means a future arm
8048 // addition picks up the coverage by construction.
8049 //
8050 // Peer of the sibling
8051 // [`restart_strategy_from_wire_round_trips_through_as_str`]
8052 // (4eec29c) round-trip pin on
8053 // [`RestartStrategy::from_wire`] and the M3
8054 // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
8055 // (18c7342) round-trip pin on
8056 // [`crate::aplicacao::PlacementStrategy::from_wire`].
8057 for &variant in RestartPolicy::ALL {
8058 let wire = variant.as_str();
8059 let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
8060 panic!(
8061 "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
8062 must be Some({variant:?}) — the two halves of the round-trip \
8063 dispatch on the same lifted SUPERVISOR_CHILD_RESTART_* consts; \
8064 got None on wire byte-string {wire:?}"
8065 )
8066 });
8067 assert_eq!(
8068 parsed, variant,
8069 "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
8070 must round-trip to the same variant; got {parsed:?}"
8071 );
8072 }
8073 }
8074
8075 #[test]
8076 fn restart_policy_from_wire_rejects_unknown_byte_strings() {
8077 // Fail-before-pass-after pin on the closed-set refusal
8078 // discipline of [`RestartPolicy::from_wire`]: every
8079 // byte-string outside the three-arm accept-set returns `None`
8080 // rather than silently collapsing onto the [`Default`]
8081 // (`Permanent`) arm or an arbitrary neighbor. The refusal set
8082 // exercised here sweeps the load-bearing drift shapes: the
8083 // empty string (a stripped serde-attribute drift), all-
8084 // whitespace strings (the canonical text-editor accidental
8085 // padding shape), the kebab-case dispatcher-catalog identities
8086 // (`"permanent"` / `"temporary"` / `"transient"` — the
8087 // [`gen_platform::FromStrKind`]-derived [`std::str::FromStr`]
8088 // accept-set, which parses the *other* axis of this enum's
8089 // two-axis split and must not leak into the `from_wire`
8090 // PascalCase-wire accept-set — a lowercase leak here would
8091 // silently accept the operator's kebab-case
8092 // dispatcher-catalog probe under the wire-axis parser and mis-
8093 // route a `:permanent` intent), the padded canonical scalar
8094 // (`" Permanent "`), the trailing-newline shapes
8095 // (`"Permanent\n"`), the uppercase-single-word forms
8096 // (`"PERMANENT"`), and neighboring-but-unknown arms
8097 // (`"Restart"` — the canonical typo direction toward the
8098 // sibling [`RestartStrategy`] enum's own wire-arm namespace).
8099 //
8100 // Peer of the sibling
8101 // [`restart_strategy_from_wire_rejects_unknown_byte_strings`]
8102 // (4eec29c) +
8103 // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
8104 // (2aa6d23) +
8105 // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
8106 // (18c7342) refusal pins on the peer closed-set typed-enum
8107 // axes.
8108 for bad in [
8109 "",
8110 " ",
8111 "\n",
8112 "\t",
8113 "permanent",
8114 "temporary",
8115 "transient",
8116 "PERMANENT",
8117 "TEMPORARY",
8118 "TRANSIENT",
8119 "Permanents",
8120 "Permanent ",
8121 " Permanent",
8122 " Transient ",
8123 "Permanent\n",
8124 "perma",
8125 "Trans",
8126 "OneForOne",
8127 "Restart",
8128 "?",
8129 ] {
8130 assert!(
8131 RestartPolicy::from_wire(bad).is_none(),
8132 "RestartPolicy::from_wire({bad:?}) must return None — the \
8133 parser's accept-set is exactly the three RestartPolicy::as_str \
8134 outputs (Permanent, Temporary, Transient), and this \
8135 byte-string is outside that closed set"
8136 );
8137 }
8138 }
8139
8140 #[test]
8141 fn restart_policy_from_wire_matches_serialize_derive_wire_byte_string() {
8142 // Fail-before-pass-after pin on the fourth path of the four-path
8143 // convergence: `from_wire` (the reverse projection) inverts the
8144 // `Serialize` derive's wire byte-string on every variant.
8145 // Together with the pre-existing three-path convergence
8146 // (`Display` + `as_str` + `Serialize` all resolve to the same
8147 // lifted [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const,
8148 // pinned by
8149 // [`restart_policy_display_matches_serialized_wire_byte_string`])
8150 // this closes the round-trip: the wire byte-string the
8151 // `Serialize` derive emits parses back to the same variant
8152 // through `from_wire`, so any future serde-attribute or variant-
8153 // rename drift on the emit half now surfaces as a matched drift
8154 // on the parse half at caixa-core build time — the two halves
8155 // migrate as a unit through the lifted consts on any future
8156 // rename, and the round-trip cannot silently split.
8157 //
8158 // Peer of the sibling
8159 // [`restart_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
8160 // (4eec29c) wire-format pin on
8161 // [`RestartStrategy::from_wire`] and the M3
8162 // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
8163 // (18c7342) wire-format pin on
8164 // [`crate::aplicacao::PlacementStrategy::from_wire`].
8165 for &variant in RestartPolicy::ALL {
8166 let wire = serde_json::to_string(&variant).unwrap();
8167 let unquoted = wire
8168 .strip_prefix('"')
8169 .and_then(|s| s.strip_suffix('"'))
8170 .expect("serialized RestartPolicy is a JSON string");
8171 let parsed = RestartPolicy::from_wire(unquoted).unwrap_or_else(|| {
8172 panic!(
8173 "RestartPolicy::from_wire({unquoted:?}) must accept the \
8174 Serialize derive's wire byte-string for \
8175 RestartPolicy::{variant:?} — the four-path convergence \
8176 (Display + as_str + Serialize + from_wire) resolves through \
8177 the same lifted SUPERVISOR_CHILD_RESTART_* const; got None"
8178 )
8179 });
8180 assert_eq!(
8181 parsed, variant,
8182 "RestartPolicy::from_wire of the Serialize derive's wire \
8183 byte-string for RestartPolicy::{variant:?} must round-trip \
8184 to the same variant; got {parsed:?}"
8185 );
8186 }
8187 }
8188
8189 // ── drift-detection: ChildSpec::nome accessor pins ────────────────────
8190 //
8191 // The M2 supervisor-tree sibling of the M3 `Membro::nome` (4a32abf) pin
8192 // pair (`membro_nome_returns_caixa_byte_equal_across_permutations` +
8193 // `membro_nome_borrows_from_caixa_storage`) — extended here to the M2
8194 // per-`:children` child-caixa `:nome` axis, sibling to the first M2
8195 // slot scalar accessor `UpgradeFromEntry::prior_versao` (75d27a8) on
8196 // the peer per-`:upgrade-from :from` axis. The three pins jointly
8197 // brace the accessor against every future silent detour that would
8198 // desynchronize it from the raw `.caixa` field access every consumer
8199 // previously open-coded.
8200
8201 #[test]
8202 fn child_spec_nome_returns_caixa_byte_equal_across_permutations() {
8203 // The canonical per-`:children` child-caixa `:nome`-scalar pin:
8204 // [`ChildSpec::nome`] must return the `:children :caixa` field
8205 // byte-for-byte across every DNS-1123-label value the upstream
8206 // [`crate::render::require_valid_dns_1123_label`] gate at
8207 // `SupervisorSpec::validate` admits. Peer of the sibling
8208 // `membro_nome_returns_caixa_byte_equal_across_permutations`
8209 // (4a32abf) pin on the M3 per-`:membros` axis — same "the
8210 // substrate-primitive accessor must byte-equal the raw field
8211 // access verbatim across every author-declared value" discipline
8212 // extended to the M2 supervisor-tree per-`:children` arm. Pins
8213 // against a future silent detour that re-normalized the child
8214 // identity (an accidental `.to_lowercase()` — every `:children
8215 // :caixa` is validated as a DNS-1123 label upstream, so any
8216 // re-normalization is redundant + a drift surface between the
8217 // validator and the accessor), a namespace-prefix rewrite (an
8218 // accidental `format!("{namespace}/{caixa}")` per-CR
8219 // fully-qualified rewrite that didn't land on the peer axes), or
8220 // a per-cluster alias stamp the future wasm-operator's
8221 // hierarchical reconciliation scheduler authors on one consumer
8222 // without the others. Five values sweep the accept-set the
8223 // DNS-1123 gate upstream admits (short single-word / dashed /
8224 // v-suffixed / mixed-digit child names).
8225 for name in [
8226 "worker",
8227 "cache-server",
8228 "scratch-job",
8229 "orders-v2",
8230 "session-8080",
8231 ] {
8232 let c = ChildSpec {
8233 caixa: name.into(),
8234 versao: "^0.1".into(),
8235 restart: RestartPolicy::Permanent,
8236 };
8237 assert_eq!(
8238 c.nome(),
8239 name,
8240 "ChildSpec::nome must return :children :caixa verbatim \
8241 (got {:?}, expected {name:?})",
8242 c.nome(),
8243 );
8244 assert_eq!(
8245 c.nome(),
8246 c.caixa.as_str(),
8247 "ChildSpec::nome must byte-equal the .caixa field access",
8248 );
8249 }
8250 }
8251
8252 #[test]
8253 fn child_spec_nome_borrows_from_caixa_storage() {
8254 // The borrow-not-copy pin: [`ChildSpec::nome`] must return a
8255 // `&str` slice that borrows from the typed slot's own [`String`]
8256 // storage — same-address invariant with `c.caixa.as_str()`. Pins
8257 // against a future silent detour that allocated a fresh `String`
8258 // (`self.caixa.clone()` in the body would type-check but silently
8259 // drop the borrow, and every downstream consumer that assumed
8260 // the returned slice outlives `&self` would break on a stale-
8261 // reference use-after-free — the [`crate::render::insert_first_seen`]
8262 // dedup key at [`SupervisorSpec::validate`], the
8263 // [`validate_no_self_supervision`] equality check against the
8264 // parent's `:nome` string slice, the DNS-1123 gate's `&str`
8265 // borrow — each would silently misbehave if this accessor
8266 // produced a detached copy). Peer of the sibling
8267 // `membro_nome_borrows_from_caixa_storage` (4a32abf) pin on the
8268 // M3 per-`:membros` axis and the
8269 // `prior_versao_borrows_from_from_storage` (75d27a8) pin on the
8270 // first M2 slot scalar accessor.
8271 let c = ChildSpec {
8272 caixa: "worker".into(),
8273 versao: "^0.1".into(),
8274 restart: RestartPolicy::Permanent,
8275 };
8276 let name = c.nome();
8277 let caixa_slice = c.caixa.as_str();
8278 assert_eq!(
8279 name.as_ptr(),
8280 caixa_slice.as_ptr(),
8281 "ChildSpec::nome must borrow from the .caixa String's backing \
8282 storage — a fresh allocation here means the accessor no \
8283 longer names the substrate-primitive typed dispatch and \
8284 every downstream consumer would silently carry a detached \
8285 copy",
8286 );
8287 assert_eq!(
8288 name.len(),
8289 caixa_slice.len(),
8290 "ChildSpec::nome and .caixa.as_str() must byte-equal in length \
8291 as well as in address",
8292 );
8293 }
8294
8295 #[test]
8296 fn validate_gates_child_nome_through_lifted_accessor() {
8297 // Bilateral coherence pin: every `:children :caixa` that
8298 // [`SupervisorSpec::validate`] accepts is one
8299 // [`crate::render::require_valid_dns_1123_label`] accepts on the
8300 // accessor-projected value, and vice versa on the reject side.
8301 // This closes the "the validator reads through the accessor"
8302 // contract structurally — a future silent detour that made the
8303 // accessor return a different byte-string than the validator
8304 // gates against would surface here as a coverage mismatch, not
8305 // as an apply-time DNS-1123 rejection at
8306 // `metadata.name: Invalid value` far from the caixa.lisp source.
8307 // Peer of the M2 sibling
8308 // `validate_parses_prior_versao_through_lifted_accessor`
8309 // (75d27a8) on the per-`:upgrade-from :from` axis and the M3
8310 // `validate_membros` peer discipline.
8311 //
8312 // Accept-set sweep: five DNS-1123-label values the upstream gate
8313 // admits.
8314 for ok_name in ["a", "worker", "cache-server", "orders-v2", "svc-8080"] {
8315 let s = SupervisorSpec {
8316 children: vec![ChildSpec {
8317 caixa: ok_name.into(),
8318 versao: "^0.1".into(),
8319 restart: RestartPolicy::Permanent,
8320 }],
8321 ..SupervisorSpec::default()
8322 };
8323 s.validate().unwrap_or_else(|e| {
8324 panic!(
8325 "SupervisorSpec::validate must accept :children :caixa {ok_name:?} \
8326 (upstream DNS-1123 gate accepts it): got {e:?}",
8327 );
8328 });
8329 let c = ChildSpec {
8330 caixa: ok_name.into(),
8331 versao: "^0.1".into(),
8332 restart: RestartPolicy::Permanent,
8333 };
8334 crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| ())
8335 .unwrap_or_else(|()| {
8336 panic!(
8337 "require_valid_dns_1123_label must accept the accessor-projected \
8338 :children :caixa {ok_name:?}",
8339 );
8340 });
8341 }
8342 // Reject-set sweep: five DNS-1123-label-violating shapes the
8343 // upstream gate refuses (empty / uppercase / underscore / dot /
8344 // leading-hyphen). Every rejection at the validator must
8345 // correspond to a rejection when the accessor's projected value
8346 // is fed back through the shared gate.
8347 for bad_name in ["", "Worker", "my_worker", "team.worker", "-worker"] {
8348 let s = SupervisorSpec {
8349 children: vec![ChildSpec {
8350 caixa: bad_name.into(),
8351 versao: "^0.1".into(),
8352 restart: RestartPolicy::Permanent,
8353 }],
8354 ..SupervisorSpec::default()
8355 };
8356 let err = s.validate().unwrap_err();
8357 assert!(
8358 matches!(
8359 err,
8360 SupervisorError::EmptyChildName | SupervisorError::ChildCaixaInvalid { .. }
8361 ),
8362 "SupervisorSpec::validate must reject :children :caixa {bad_name:?} \
8363 via the DNS-1123 gate: got {err:?}",
8364 );
8365 let c = ChildSpec {
8366 caixa: bad_name.into(),
8367 versao: "^0.1".into(),
8368 restart: RestartPolicy::Permanent,
8369 };
8370 assert!(
8371 crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| (),)
8372 .is_err(),
8373 "require_valid_dns_1123_label must reject the accessor-projected \
8374 :children :caixa {bad_name:?}",
8375 );
8376 }
8377 }
8378
8379 // ── drift-detection: ChildSpec::versao_requirement accessor pins ──────
8380 //
8381 // Sibling of the peer per-`:membros` `membro_versao_requirement_*`
8382 // (a40b0e3) pin pair on the M3 mesh-slot surface — extended here to the
8383 // M2 supervisor-tree per-`:children` child-`:versao` axis, sibling to
8384 // the just-landed [`ChildSpec::nome`] (57c61d0) child-`:nome` pin
8385 // trio on the peer per-`:children` `String`-carry axis. The three pins
8386 // jointly brace the accessor against every future silent detour that
8387 // would desynchronize it from the raw `.versao` field access the
8388 // requirement gate + error carrier previously open-coded.
8389 //
8390 // Closes the last unlifted per-`:children` `String`-carry axis: the
8391 // pair (`nome`, `versao_requirement`) now jointly projects the
8392 // (`.caixa`, `.versao`) field pair every OTP-shape supervisor-tree
8393 // consumer that fans on per-child identity + version pin reads,
8394 // matching the peer M3 (`Membro::nome`, `Membro::versao_requirement`)
8395 // pair discipline verbatim.
8396 #[test]
8397 fn child_spec_versao_requirement_returns_versao_byte_equal_across_permutations() {
8398 // The canonical per-`:children` child-`:versao`-scalar pin:
8399 // [`ChildSpec::versao_requirement`] must return the `:children
8400 // :versao` field byte-for-byte across every Cargo-shaped semver
8401 // requirement value the upstream
8402 // [`crate::render::require_valid_versao_requirement`] gate admits.
8403 // Peer of the sibling
8404 // `membro_versao_requirement_returns_versao_byte_equal_across_permutations`
8405 // (a40b0e3) pin on the M3 per-`:membros` axis — same "the
8406 // substrate-primitive accessor must byte-equal the raw field
8407 // access verbatim across every author-declared value" discipline
8408 // extended to the M2 supervisor-tree per-`:children` arm. Pins
8409 // against a future silent detour that re-canonicalized the
8410 // requirement (an accidental `.to_string()` via
8411 // [`crate::version::parse_requirement`] → [`std::fmt::Display`]
8412 // round-trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and
8413 // silently drifted the error carrier's quoted requirement away
8414 // from the source `caixa.lisp`, an accidental whitespace trim on
8415 // `"^ 0.1"` that no consumer ever produced from the field-access
8416 // side, an accidental per-cluster lacre-projected concrete-version
8417 // rewrite that didn't land on the peer requirement-gate call).
8418 // Five values sweep the accept-set the shared
8419 // [`crate::render::require_valid_versao_requirement`] gate admits
8420 // (caret / tilde / exact / wildcard / bare-major).
8421 for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
8422 let c = ChildSpec {
8423 caixa: "worker".into(),
8424 versao: req.into(),
8425 restart: RestartPolicy::Permanent,
8426 };
8427 assert_eq!(
8428 c.versao_requirement(),
8429 req,
8430 "ChildSpec::versao_requirement must return :children :versao \
8431 verbatim (got {:?}, expected {req:?})",
8432 c.versao_requirement(),
8433 );
8434 assert_eq!(
8435 c.versao_requirement(),
8436 c.versao.as_str(),
8437 "ChildSpec::versao_requirement must byte-equal the .versao \
8438 field access",
8439 );
8440 }
8441 }
8442
8443 #[test]
8444 fn child_spec_versao_requirement_borrows_from_versao_storage() {
8445 // The borrow-not-copy pin: [`ChildSpec::versao_requirement`] must
8446 // return a `&str` slice that borrows from the typed slot's own
8447 // [`String`] storage — same-address invariant with
8448 // `c.versao.as_str()`. Pins against a future silent detour that
8449 // allocated a fresh `String` (`self.versao.clone()` in the body
8450 // would type-check but silently drop the borrow, and every
8451 // downstream consumer that assumed the returned slice outlives
8452 // `&self` — the [`crate::render::require_valid_versao_requirement`]
8453 // gate's `&str` borrow, the [`SupervisorError::ChildVersaoInvalid`]
8454 // `.to_string()` carrier's byte-length assumption — would silently
8455 // misbehave if this accessor produced a detached copy). Peer of
8456 // the sibling `child_spec_nome_borrows_from_caixa_storage`
8457 // (57c61d0) pin on the per-`:children` `:nome` axis and the M3
8458 // `membro_versao_requirement_borrows_from_versao_storage` (a40b0e3)
8459 // pin on the peer per-`:membros` `:versao` axis.
8460 let c = ChildSpec {
8461 caixa: "worker".into(),
8462 versao: "^0.1".into(),
8463 restart: RestartPolicy::Permanent,
8464 };
8465 let req = c.versao_requirement();
8466 let versao_slice = c.versao.as_str();
8467 assert_eq!(
8468 req.as_ptr(),
8469 versao_slice.as_ptr(),
8470 "ChildSpec::versao_requirement must borrow from the .versao \
8471 String's backing storage — a fresh allocation here means the \
8472 accessor no longer names the substrate-primitive typed \
8473 dispatch and every downstream consumer would silently carry \
8474 a detached copy",
8475 );
8476 assert_eq!(
8477 req.len(),
8478 versao_slice.len(),
8479 "ChildSpec::versao_requirement and .versao.as_str() must \
8480 byte-equal in length as well as in address",
8481 );
8482 }
8483
8484 #[test]
8485 fn validate_gates_child_versao_through_lifted_accessor() {
8486 // Bilateral coherence pin: every `:children :versao` that
8487 // [`SupervisorSpec::validate`] accepts is one
8488 // [`crate::render::require_valid_versao_requirement`] accepts on
8489 // the accessor-projected value, and vice versa on the reject side.
8490 // This closes the "the validator reads through the accessor"
8491 // contract structurally — a future silent detour that made the
8492 // accessor return a different byte-string than the validator gates
8493 // against would surface here as a coverage mismatch, not as a
8494 // resolver-time semver-parse rejection at lacre-closure time far
8495 // from the caixa.lisp source. Peer of the sibling
8496 // `validate_gates_child_nome_through_lifted_accessor` (57c61d0) on
8497 // the per-`:children :caixa` axis and the M2
8498 // `validate_parses_prior_versao_through_lifted_accessor` (75d27a8)
8499 // on the peer per-`:upgrade-from :from` axis.
8500 //
8501 // Accept-set sweep: five Cargo-shaped semver requirement values
8502 // the upstream gate admits (caret / tilde / exact / wildcard /
8503 // bare-major).
8504 for ok_req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
8505 let s = SupervisorSpec {
8506 children: vec![ChildSpec {
8507 caixa: "worker".into(),
8508 versao: ok_req.into(),
8509 restart: RestartPolicy::Permanent,
8510 }],
8511 ..SupervisorSpec::default()
8512 };
8513 s.validate().unwrap_or_else(|e| {
8514 panic!(
8515 "SupervisorSpec::validate must accept :children :versao {ok_req:?} \
8516 (upstream versao-requirement gate accepts it): got {e:?}",
8517 );
8518 });
8519 let c = ChildSpec {
8520 caixa: "worker".into(),
8521 versao: ok_req.into(),
8522 restart: RestartPolicy::Permanent,
8523 };
8524 crate::render::require_valid_versao_requirement(
8525 c.versao_requirement(),
8526 || (),
8527 |_reason| (),
8528 )
8529 .unwrap_or_else(|()| {
8530 panic!(
8531 "require_valid_versao_requirement must accept the accessor-projected \
8532 :children :versao {ok_req:?}",
8533 );
8534 });
8535 }
8536 // Reject-set sweep: five requirement-violating shapes the upstream
8537 // gate refuses. The empty string closes the empty-first arm of the
8538 // shared [`crate::render::require_valid_versao_requirement`]
8539 // cascade; the four non-empty arms exercise distinct semver-parse
8540 // failure modes the M3 peer per-`:membros` reject-set already pins
8541 // (`rejects_invalid_membro_versao_requirement` on `^bad-version`,
8542 // `rejects_membro_versao_with_double_caret_typo` on `^^0.1`,
8543 // `rejects_membro_versao_with_v_prefixed_tag` on `v0.1`) — the
8544 // shared parser routing means the same reject-set must fail
8545 // identically at the M2 supervisor-tree per-`:children` accessor
8546 // arm here. Every rejection at the validator must correspond to a
8547 // rejection when the accessor's projected value is fed back
8548 // through the shared gate.
8549 //
8550 // (Bare partial magnitudes like `"0.1"` and bare identifiers like
8551 // `"not-a-semver"` are intentionally *not* in the reject-set: the
8552 // semver crate accepts `"0.1"` as an implicit `^0.1` requirement,
8553 // and the identifier-tail arm's grammar admits some non-canonical
8554 // shapes — matching what the M3 peer test suite already documents
8555 // as the shared parser's accept-set edges.)
8556 for bad_req in ["", "v0.1.0", "^bad-version", "^^0.1", "v0.1"] {
8557 let s = SupervisorSpec {
8558 children: vec![ChildSpec {
8559 caixa: "worker".into(),
8560 versao: bad_req.into(),
8561 restart: RestartPolicy::Permanent,
8562 }],
8563 ..SupervisorSpec::default()
8564 };
8565 let err = s.validate().unwrap_err();
8566 assert!(
8567 matches!(
8568 err,
8569 SupervisorError::EmptyChildVersion { .. }
8570 | SupervisorError::ChildVersaoInvalid { .. }
8571 ),
8572 "SupervisorSpec::validate must reject :children :versao {bad_req:?} \
8573 via the versao-requirement gate: got {err:?}",
8574 );
8575 let c = ChildSpec {
8576 caixa: "worker".into(),
8577 versao: bad_req.into(),
8578 restart: RestartPolicy::Permanent,
8579 };
8580 assert!(
8581 crate::render::require_valid_versao_requirement(
8582 c.versao_requirement(),
8583 || (),
8584 |_reason| (),
8585 )
8586 .is_err(),
8587 "require_valid_versao_requirement must reject the accessor-projected \
8588 :children :versao {bad_req:?}",
8589 );
8590 }
8591 }
8592
8593 // ── per-`:children` `:restart` typed-accessor coherence pins ──────────
8594 //
8595 // The [`ChildSpec::restart`] accessor lift closes the last unlifted
8596 // per-`:children` axis (the pair `nome()` + `versao_requirement()`
8597 // already project the `String`-carry `(caixa, versao)` fields; the
8598 // `Copy`-composite-enum `restart` field is the third and final axis).
8599 // Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
8600 // (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
8601 // scalar accessor and the M3 mesh-slot [`crate::Placement::estrategia`]
8602 // (921fe1b) `Copy`-return [`crate::PlacementStrategy`] distribution-
8603 // strategy scalar accessor — same "one typed dispatch on the substrate
8604 // primitive, `Copy`-projected closed-set enum-arm discriminator" shape
8605 // extended onto the M2 supervisor-slot per-`:children` restart-decision
8606 // axis. The pin below covers the accessor's byte-equal projection
8607 // against the raw field access across every variant in the closed
8608 // accept-set (`Permanent`, `Transient`, `Temporary`).
8609
8610 #[test]
8611 fn child_spec_restart_returns_restart_verbatim_across_permutations() {
8612 // The canonical per-`:children` restart-decision-policy-scalar
8613 // pin: [`ChildSpec::restart`] must return the `:children :restart`
8614 // field verbatim as a [`RestartPolicy`], `Copy`-projected from the
8615 // typed slot's own [`RestartPolicy`] storage across every variant
8616 // in the closed accept-set (`Permanent`, `Transient`, `Temporary`).
8617 // Pins against a future silent detour that re-derived the policy
8618 // from a peer axis (an accidental fallback to
8619 // `if is_supervisor_child { Permanent } else { Temporary }` that
8620 // collapsed the child's kind axis into the restart discriminator),
8621 // a variant remap the operator authors on one consumer without the
8622 // other, or a stale-derive detour that substituted
8623 // [`RestartPolicy::default`] when the field held any explicit
8624 // variant (which would silently collapse the distinction between
8625 // "author explicitly declared `:restart Permanent`" and "author
8626 // omitted the slot and inherited the default" the future
8627 // per-cluster restart-decision override slot depends on).
8628 //
8629 // Peer of the sibling per-`:supervisor`
8630 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
8631 // (eafb619) pin on the M2 supervisor-slot sibling-restart-strategy
8632 // axis and the M3
8633 // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
8634 // (921fe1b) pin on the per-`:placement` distribution-strategy axis
8635 // — same "the substrate-primitive accessor must byte-equal the raw
8636 // field access verbatim across every author-declared value"
8637 // discipline extended onto the M2 supervisor-slot per-`:children`
8638 // restart-decision-policy axis, closing the last unlifted axis on
8639 // the per-`:children` [`ChildSpec`] type.
8640 for restart in [
8641 RestartPolicy::Permanent,
8642 RestartPolicy::Transient,
8643 RestartPolicy::Temporary,
8644 ] {
8645 let c = ChildSpec {
8646 caixa: "worker".into(),
8647 versao: "^0.1".into(),
8648 restart,
8649 };
8650 assert_eq!(
8651 c.restart(),
8652 restart,
8653 "ChildSpec::restart must return :children :restart \
8654 verbatim (got {:?}, expected {restart:?})",
8655 c.restart(),
8656 );
8657 assert_eq!(
8658 c.restart(),
8659 c.restart,
8660 "ChildSpec::restart accessor and .restart field access \
8661 must byte-equal — the accessor is the substrate-primitive \
8662 typed dispatch every downstream per-child restart-\
8663 decision consumer must route through",
8664 );
8665 }
8666 }
8667
8668 // ── per-`:supervisor` `:estrategia` typed-accessor coherence pins ─────
8669 //
8670 // The [`SupervisorSpec::estrategia`] accessor lift extends the peer M3
8671 // [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
8672 // distribution-strategy accessor discipline onto the M2 supervisor-slot
8673 // per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
8674 // scalar axis. The two pins below cover (1) the accessor's byte-equal
8675 // projection against the raw field access across every variant in the
8676 // closed accept-set, and (2) the two-consumer coherence between the
8677 // [`SupervisorSpec::validate`] partition-dispatch `match` arm and the
8678 // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
8679 // carrier's `estrategia:` field — peer of the sibling M3
8680 // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
8681 // / `validate_placement_reads_through_lifted_estrategia_accessor` pin
8682 // pair on the per-`:placement` distribution-strategy axis.
8683
8684 #[test]
8685 fn supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations() {
8686 // The canonical per-`:supervisor` sibling-restart-strategy-scalar
8687 // pin: [`SupervisorSpec::estrategia`] must return the
8688 // `:supervisor :estrategia` field verbatim as a
8689 // [`RestartStrategy`], `Copy`-projected from the typed slot's own
8690 // [`RestartStrategy`] storage across every variant in the closed
8691 // accept-set (`OneForOne`, `OneForAll`, `RestForOne`,
8692 // `SimpleOneForOne`). Pins against a future silent detour that
8693 // re-derived the strategy from a peer axis (an accidental
8694 // fallback to `if children.is_empty() { SimpleOneForOne } else {
8695 // OneForOne }` collapse that read the children-count axis into
8696 // the strategy discriminator), a variant remap the operator
8697 // authors on one consumer without the other, or a stale-derive
8698 // detour that substituted [`RestartStrategy::default`] when the
8699 // field held any explicit variant (which would silently collapse
8700 // the distinction between "author explicitly declared
8701 // `:estrategia OneForOne`" and "author omitted the slot and
8702 // inherited the default" the future per-cluster strategy override
8703 // slot depends on). Peer of the sibling M3
8704 // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
8705 // (921fe1b) pin on the M3 mesh-slot `Copy`-composite-enum scalar
8706 // axis — same "the substrate-primitive accessor must byte-equal
8707 // the raw field access verbatim across every author-declared
8708 // value" discipline extended onto the M2 supervisor-slot
8709 // per-`:supervisor` sibling-restart-strategy axis.
8710 for &estrategia in RestartStrategy::ALL {
8711 // `SimpleOneForOne` requires `children.is_empty()`; the peer
8712 // three strategies require a non-empty static children list.
8713 // Build each shape coherently so the pin's fixture would
8714 // itself pass [`SupervisorSpec::validate`] once fed through
8715 // the sibling coherence pin below — the byte-equal projection
8716 // asserted here is a strictly weaker property (a `Copy` field
8717 // read) that does not depend on `validate` running, but
8718 // keeping the fixture validate-clean means a future extension
8719 // of the pin to exercise `validate` end-to-end does not have
8720 // to re-author the children shape.
8721 //
8722 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
8723 // shape partition through the [`gen_platform::IsVariant`]
8724 // derive-generated
8725 // [`RestartStrategy::is_simple_one_for_one`] predicate rather
8726 // than the raw `matches!(estrategia, RestartStrategy::
8727 // SimpleOneForOne)` open-coded pattern-match — same closed-
8728 // set-typed-enum arm-discriminator dispatch discipline the
8729 // sibling [`crate::upgrade::UpgradeInstruction::is_restart`]
8730 // convergence (915a934) extended onto its two paired positive
8731 // / negated `matches!` sites and the peer
8732 // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
8733 // predicate convergence (766ec63) extended onto the M3 mesh-
8734 // slot per-`:placement` distribution-strategy discriminator
8735 // axis. See the sibling `round_trip_all_strategies` and the
8736 // peer `manifest::tests::
8737 // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
8738 // fixture for the two peer sites the same lift closes on.
8739 let children = if estrategia.is_simple_one_for_one() {
8740 Vec::new()
8741 } else {
8742 vec![ChildSpec {
8743 caixa: "worker".into(),
8744 versao: "^0.1".into(),
8745 restart: RestartPolicy::Permanent,
8746 }]
8747 };
8748 let s = SupervisorSpec {
8749 estrategia,
8750 children,
8751 ..SupervisorSpec::default()
8752 };
8753 assert_eq!(
8754 s.estrategia(),
8755 estrategia,
8756 "SupervisorSpec::estrategia must return :supervisor :estrategia \
8757 verbatim (got {:?}, expected {estrategia:?})",
8758 s.estrategia(),
8759 );
8760 assert_eq!(
8761 s.estrategia(),
8762 s.estrategia,
8763 "SupervisorSpec::estrategia accessor and .estrategia field \
8764 access must byte-equal — the accessor is the substrate-\
8765 primitive typed dispatch every downstream sibling-restart-\
8766 strategy consumer must route through",
8767 );
8768 }
8769 }
8770
8771 #[test]
8772 fn validate_reads_through_lifted_estrategia_accessor() {
8773 // Two-consumer coherence pin: the [`SupervisorSpec::validate`]
8774 // `SimpleOneForOne ↔ non-SimpleOneForOne` `match` partition
8775 // dispatch (which reads through [`SupervisorSpec::estrategia`]
8776 // to fan across the strategy-arm shape-gate cascades) and the
8777 // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
8778 // error carrier's `estrategia:` field (which reads through
8779 // [`SupervisorSpec::estrategia`] to name the strategy the empty
8780 // `:children` list was declared against) must both key off the
8781 // lifted accessor, so any future rebrand on the typed slot's
8782 // reader shape lands at exactly one place. Pins the two-site
8783 // coherence by exercising the `NoChildren` error surface end-to-
8784 // end across every non-`SimpleOneForOne` variant and asserting
8785 // the surfaced `estrategia:` field byte-equals the accessor's
8786 // return. Peer of the sibling M3
8787 // `validate_placement_reads_through_lifted_estrategia_accessor`
8788 // (921fe1b) three-consumer coherence pin on the per-`:placement`
8789 // distribution-strategy axis.
8790 for estrategia in [
8791 RestartStrategy::OneForOne,
8792 RestartStrategy::OneForAll,
8793 RestartStrategy::RestForOne,
8794 ] {
8795 let s = SupervisorSpec {
8796 estrategia,
8797 children: Vec::new(),
8798 ..SupervisorSpec::default()
8799 };
8800 let err = s.validate().unwrap_err();
8801 match err {
8802 SupervisorError::NoChildren { estrategia: e } => {
8803 assert_eq!(
8804 e,
8805 s.estrategia(),
8806 "NoChildren.estrategia must byte-equal \
8807 SupervisorSpec::estrategia() — the empty-`:children` \
8808 refusal reads through the lifted accessor",
8809 );
8810 assert_eq!(
8811 e, estrategia,
8812 "NoChildren.estrategia must carry the author-declared \
8813 :supervisor :estrategia variant verbatim (got {e:?}, \
8814 expected {estrategia:?})",
8815 );
8816 }
8817 other => panic!("expected NoChildren, got {other:?} for estrategia={estrategia:?}"),
8818 }
8819 }
8820 }
8821
8822 // ── per-`:supervisor` `:max-restarts` typed-accessor coherence pins ────
8823 //
8824 // The [`SupervisorSpec::max_restarts`] accessor lift extends the peer M3
8825 // [`crate::CircuitBreaker::max_failures`] (3a74062) `Copy`-return
8826 // required-`u32` scalar accessor discipline onto the M2 supervisor-slot
8827 // per-`:supervisor` restart-budget-count `Copy`-`u32` scalar axis.
8828 // The two pins below cover (1) the accessor's byte-equal projection
8829 // against the raw field access across every representative value in
8830 // the `u32` accept-set (`1` lower boundary, `SUPERVISOR_MAX_RESTARTS_MAX`
8831 // upper boundary, `0` past-the-guard zero sentinel, `u32::MAX`
8832 // past-the-guard cap sentinel), and (2) the [`SupervisorSpec::validate`]
8833 // zero-floor / cap composition — the validate gate and the accessor
8834 // must route through the same substrate-primitive typed dispatch, so
8835 // any future silent detour that had the accessor perform a
8836 // bounds-collapsing clamp would fail here at caixa-core build time.
8837 // Peer of the sibling M3
8838 // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
8839 // (3a74062) pin on the per-`CircuitBreaker :max-failures` axis.
8840
8841 #[test]
8842 fn supervisor_spec_max_restarts_returns_max_restarts_u32_byte_equal_across_permutations() {
8843 // The canonical per-`:supervisor` restart-budget-count scalar pin:
8844 // [`SupervisorSpec::max_restarts`] must return the `:supervisor
8845 // :max-restarts` typed `u32` verbatim, `Copy`-projected from the
8846 // typed slot's own `u32` storage, byte-equal to the raw field
8847 // access across every representative value in the accept-set —
8848 // `1` (the lower boundary of the `1..=SUPERVISOR_MAX_RESTARTS_MAX`
8849 // accept-set the surrounding [`SupervisorSpec::validate`] gate
8850 // carves out on the sibling `ZeroMaxRestarts` refusal),
8851 // `SUPERVISOR_MAX_RESTARTS_MAX` (the upper boundary the same gate
8852 // carves out on the sibling `MaxRestartsExceedsCap` refusal), `0`
8853 // (a past-the-guard sentinel that pins the accessor doesn't
8854 // perform a silent bounds-collapse into `1` on the zero arm —
8855 // validate rejects zero but the accessor must ship the raw slot
8856 // verbatim so a validate-time gate regression surfaces at the
8857 // emit boundary rather than being silently absorbed), `u32::MAX`
8858 // (a past-the-guard sentinel that pins the accessor doesn't
8859 // perform a silent bounds-collapse through
8860 // `SUPERVISOR_MAX_RESTARTS_MAX` at the return path).
8861 //
8862 // Peer of the sibling M3
8863 // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
8864 // (3a74062) pin on the M3 mesh-slot `Copy`-`u32` sub-struct
8865 // required-scalar axis — same "the substrate-primitive accessor
8866 // must byte-equal the raw field access verbatim across every
8867 // value in the `u32` accept-set" discipline extended onto the M2
8868 // supervisor-slot per-`:supervisor` restart-budget-count axis.
8869 for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX, 0, u32::MAX] {
8870 let s = SupervisorSpec {
8871 max_restarts,
8872 ..SupervisorSpec::default()
8873 };
8874 assert_eq!(
8875 s.max_restarts(),
8876 max_restarts,
8877 "SupervisorSpec::max_restarts must return :supervisor \
8878 :max-restarts verbatim (got {}, expected {max_restarts})",
8879 s.max_restarts(),
8880 );
8881 assert_eq!(
8882 s.max_restarts(),
8883 s.max_restarts,
8884 "SupervisorSpec::max_restarts accessor and .max_restarts \
8885 field access must byte-equal — the accessor is the \
8886 substrate-primitive typed dispatch every downstream \
8887 restart-budget-count consumer must route through",
8888 );
8889 }
8890 }
8891
8892 #[test]
8893 fn validate_max_restarts_zero_floor_and_cap_arms_route_through_accessor() {
8894 // Composition pin: [`SupervisorSpec::validate`]'s `:max-restarts`
8895 // zero-floor + upper-cap bracket must key off
8896 // [`SupervisorSpec::max_restarts`], not the raw `.max_restarts`
8897 // field access. Structurally: a `SupervisorSpec { max_restarts:
8898 // 0, .. }` must surface the `ZeroMaxRestarts` refusal exactly, a
8899 // `SupervisorSpec { max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
8900 // .. }` must surface the `MaxRestartsExceedsCap` refusal exactly
8901 // (with the offending count carried verbatim from the accessor
8902 // return), and a `SupervisorSpec { max_restarts: 1, .. }` (the
8903 // lower boundary of the accept-set) plus a `SupervisorSpec {
8904 // max_restarts: SUPERVISOR_MAX_RESTARTS_MAX, .. }` (the upper
8905 // boundary) must pass validate. The four together jointly pin the
8906 // accessor + validate-gate composition: any future silent detour
8907 // that had the accessor return a fresh `1` on the zero arm (a
8908 // `.max_restarts().max(1)` collapse) would silently absorb the
8909 // `ZeroMaxRestarts` refusal at the accessor boundary and the
8910 // validate gate would accept a struct-literal `SupervisorSpec {
8911 // max_restarts: 0, .. }` — the composition pin catches that at
8912 // caixa-core build time.
8913 //
8914 // Peer of the sibling M3
8915 // `validate_politicas_max_failures_zero_floor_arm_routes_through_accessor`
8916 // (3a74062) pin on the sibling per-`CircuitBreaker :max-failures`
8917 // composition axis — same "the validate / shape-gate predicate
8918 // must route through the substrate-primitive typed dispatch"
8919 // discipline extended onto the peer M2 supervisor-slot
8920 // required-`u32` composition axis.
8921 let child = ChildSpec {
8922 caixa: "worker".into(),
8923 versao: "^0.1".into(),
8924 restart: RestartPolicy::Permanent,
8925 };
8926 // Zero-floor arm.
8927 let s = SupervisorSpec {
8928 max_restarts: 0,
8929 children: vec![child.clone()],
8930 ..SupervisorSpec::default()
8931 };
8932 assert_eq!(
8933 s.validate().unwrap_err(),
8934 SupervisorError::ZeroMaxRestarts,
8935 "validate must reject max_restarts == 0 with ZeroMaxRestarts \
8936 — the accessor and the validate gate must route through the \
8937 same substrate-primitive typed dispatch on the zero-floor arm",
8938 );
8939 // Cap arm — the surfaced `max_restarts:` field must byte-equal
8940 // the accessor's return so a future rebrand on the accessor
8941 // lands in the diagnostic without a coordinated rewrite.
8942 let over_cap = SUPERVISOR_MAX_RESTARTS_MAX + 1;
8943 let s = SupervisorSpec {
8944 max_restarts: over_cap,
8945 children: vec![child.clone()],
8946 ..SupervisorSpec::default()
8947 };
8948 match s.validate().unwrap_err() {
8949 SupervisorError::MaxRestartsExceedsCap { max_restarts } => {
8950 assert_eq!(
8951 max_restarts,
8952 s.max_restarts(),
8953 "MaxRestartsExceedsCap.max_restarts must byte-equal \
8954 SupervisorSpec::max_restarts() — the cap-arm refusal \
8955 reads through the lifted accessor",
8956 );
8957 assert_eq!(
8958 max_restarts, over_cap,
8959 "MaxRestartsExceedsCap.max_restarts must carry the \
8960 author-declared :supervisor :max-restarts value \
8961 verbatim (got {max_restarts}, expected {over_cap})",
8962 );
8963 }
8964 other => panic!("expected MaxRestartsExceedsCap, got {other:?}"),
8965 }
8966 // Lower + upper accept-set boundaries.
8967 for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX] {
8968 let s = SupervisorSpec {
8969 max_restarts,
8970 children: vec![child.clone()],
8971 ..SupervisorSpec::default()
8972 };
8973 assert!(
8974 s.validate().is_ok(),
8975 "validate must accept max_restarts == {max_restarts} \
8976 (an accept-set boundary of \
8977 1..=SUPERVISOR_MAX_RESTARTS_MAX)",
8978 );
8979 }
8980 }
8981
8982 // ── per-`:supervisor` `:restart-window` typed-accessor coherence pins ─
8983 //
8984 // The [`SupervisorSpec::restart_window`] accessor lift extends the peer
8985 // M2 [`crate::LimitsSpec::wall_clock`] (8cb717b) `Option<Duration>`
8986 // accessor discipline and the peer M3 [`crate::MeshPolicy::timeout`]
8987 // (7073d0f) `Option<Duration>` accessor discipline onto the M2
8988 // supervisor-slot per-`:supervisor` restart-intensity-denominator
8989 // `Option<Duration>` scalar axis — third `Copy`-return accessor on the
8990 // M2 supervisor-slot `SupervisorSpec` type, closing the last unlifted
8991 // per-`:supervisor` scalar-value axis. The three pins below cover
8992 // (1) the accessor's byte-equal projection against the raw field
8993 // access across every representative value in the `Option<Duration>`
8994 // accept-set (`None` never-reset sentinel, `Some(Duration::from_millis(1))`
8995 // lower boundary, `Some(SUPERVISOR_RESTART_WINDOW_MAX)` upper boundary,
8996 // `Some(Duration::ZERO)` past-the-guard zero sentinel, `Some(Duration::MAX)`
8997 // past-the-guard above-cap sentinel), (2) the [`SupervisorSpec::validate`]
8998 // `if let Some(w) = self.restart_window() { … }` bracket-arm
8999 // composition — the validate gate and the accessor must route through
9000 // the same substrate-primitive typed dispatch, so any future silent
9001 // detour that had the accessor perform a bounds-collapsing clamp
9002 // would fail here at caixa-core build time, and (3) the accessor's
9003 // by-copy idempotence pin — the returned `Option<Duration>` must
9004 // outlive `&self` and two successive calls must return byte-equal
9005 // values. Peer of the sibling M2
9006 // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
9007 // (8cb717b) pin on the per-`:limits :wall-clock` axis and the sibling
9008 // M3 `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
9009 // (7073d0f) pin on the per-`:politicas :timeout` axis.
9010
9011 #[test]
9012 fn supervisor_spec_restart_window_returns_option_duration_byte_equal_across_permutations() {
9013 // The canonical per-`:supervisor` restart-intensity-denominator
9014 // scalar pin: [`SupervisorSpec::restart_window`] must return the
9015 // `:supervisor :restart-window` typed [`Duration`] verbatim as an
9016 // `Option<Duration>`, `Copy`-projected from the typed slot's own
9017 // `Option<Duration>` storage, byte-equal to the raw field access
9018 // across every representative value in the accept-set — `None`
9019 // (the "never reset — every restart across the supervisor's
9020 // lifetime counts against the sibling `:max-restarts` budget"
9021 // sentinel the field's own docstring names and the peer
9022 // `validate_accepts_none_restart_window` pin locks in on the
9023 // [`SupervisorSpec::validate`] entry-side),
9024 // `Some(Duration::from_millis(1))` (the structural minimum a
9025 // validated `:restart-window` may carry, the integer-millisecond
9026 // floor [`SupervisorError::RestartWindowNotCanonical`] rejects
9027 // everything sub-ms; `Duration::ZERO` is separately rejected by
9028 // [`SupervisorError::RestartWindowZero`]),
9029 // `Some(SUPERVISOR_RESTART_WINDOW_MAX)` (the upper boundary the
9030 // surrounding [`SupervisorSpec::validate`] gate carves out on the
9031 // sibling [`SupervisorError::RestartWindowExceedsCap`] refusal),
9032 // `Some(Duration::ZERO)` (a past-the-guard sentinel that pins the
9033 // accessor doesn't perform a silent bounds-collapse into `None` on
9034 // the zero-Duration arm — validate rejects zero but the accessor
9035 // must ship the raw slot verbatim so a validate-time gate
9036 // regression surfaces at the emit boundary rather than being
9037 // silently absorbed), and `Some(Duration::MAX)` (a past-the-guard
9038 // sentinel that pins the accessor doesn't perform a silent
9039 // bounds-collapse through [`SUPERVISOR_RESTART_WINDOW_MAX`] at the
9040 // return path).
9041 //
9042 // Peer of the sibling M2
9043 // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
9044 // (8cb717b) pin on the per-`:limits :wall-clock` axis and the
9045 // sibling M3
9046 // `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
9047 // (7073d0f) pin on the per-`:politicas :timeout` axis — same "the
9048 // substrate-primitive accessor must byte-equal the raw field
9049 // access verbatim across every value in the `Option<Duration>`
9050 // accept-set" discipline extended onto the M2 supervisor-slot
9051 // per-`:supervisor` `Option<Duration>` axis. Pins against a future
9052 // silent detour that re-derived the restart-window from a peer
9053 // axis (an accidental `.max_restarts.into()` collapse that read
9054 // the restart-budget-count as a duration — the two axes serve
9055 // different halves of the `MaxIntensity / Period` restart-
9056 // intensity ratio, and confusing them silently inverts the
9057 // ratio's numerator and denominator), a `None → Some(Duration::ZERO)`
9058 // "zero means never reset" collapse (the canonical
9059 // `Option<Duration>` → `Duration` collapse footgun the
9060 // [`SupervisorError::RestartWindowZero`] validate arm guards on
9061 // the peer zero-floor axis; a zero period either trips on the
9062 // first failure or never trips depending on operator
9063 // interpretation, neither of which is the author's "never reset"
9064 // intent that `None` expresses structurally), or a per-arm
9065 // variant swap that landed on one consumer without the other.
9066 for restart_window in [
9067 None,
9068 Some(Duration::from_millis(1)),
9069 Some(SUPERVISOR_RESTART_WINDOW_MAX),
9070 Some(Duration::ZERO),
9071 Some(Duration::MAX),
9072 ] {
9073 let s = SupervisorSpec {
9074 restart_window,
9075 ..SupervisorSpec::default()
9076 };
9077 assert_eq!(
9078 s.restart_window(),
9079 restart_window,
9080 "SupervisorSpec::restart_window must return :supervisor \
9081 :restart-window verbatim (got {:?}, expected {restart_window:?})",
9082 s.restart_window(),
9083 );
9084 assert_eq!(
9085 s.restart_window(),
9086 s.restart_window,
9087 "SupervisorSpec::restart_window accessor and \
9088 .restart_window field access must byte-equal — the \
9089 accessor is the substrate-primitive typed dispatch every \
9090 downstream restart-intensity-denominator consumer must \
9091 route through",
9092 );
9093 }
9094 }
9095
9096 #[test]
9097 fn validate_restart_window_bracket_arm_routes_through_accessor() {
9098 // Composition pin: [`SupervisorSpec::validate`]'s
9099 // `:restart-window` `if let Some(w) = self.restart_window() { … }`
9100 // zero-floor + integer-millisecond canonical-form + upper-cap
9101 // bracket-arm must key off [`SupervisorSpec::restart_window`], not
9102 // the raw `.restart_window` field access. Structurally: a
9103 // `SupervisorSpec { restart_window: None, .. }` must pass the
9104 // arm gate structurally (the `if let Some(_)` shape returns
9105 // early on the `None` arm — the accessor and the validate gate
9106 // must agree on `None → skip the bracket cascade` so an authored
9107 // `:restart-window ()` structurally routes through the "never
9108 // reset" sentinel path), a `SupervisorSpec { restart_window:
9109 // Some(Duration::ZERO), .. }` must surface the `RestartWindowZero`
9110 // refusal exactly, a `SupervisorSpec { restart_window:
9111 // Some(Duration::from_micros(1500)), .. }` must surface the
9112 // `RestartWindowNotCanonical` refusal exactly (with the offending
9113 // duration carried verbatim from the accessor return), a
9114 // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX
9115 // + Duration::from_millis(1)), .. }` must surface the
9116 // `RestartWindowExceedsCap` refusal exactly (with the offending
9117 // duration carried verbatim from the accessor return), and a
9118 // `SupervisorSpec { restart_window: Some(Duration::from_millis(1)),
9119 // .. }` (the lower boundary of the accept-set) plus a
9120 // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
9121 // .. }` (the upper boundary) must pass validate. The six together
9122 // jointly pin the accessor + validate-gate composition: any future
9123 // silent detour that had the accessor return a fresh `None` on any
9124 // `Some` arm (a `.restart_window().filter(|w| !w.is_zero())`
9125 // collapse) would silently absorb the `RestartWindowZero` refusal
9126 // at the accessor boundary and the validate gate would accept a
9127 // struct-literal `SupervisorSpec { restart_window:
9128 // Some(Duration::ZERO), .. }` — the composition pin catches that
9129 // at caixa-core build time.
9130 //
9131 // Peer of the sibling M2 [`crate::LimitsSpec::wall_clock`]
9132 // (8cb717b) validate-arm-route pin on the per-`:limits :wall-clock`
9133 // axis and the peer M3 [`crate::MeshPolicy::timeout`] (7073d0f)
9134 // accessor-composition pin on the per-`:politicas :timeout` axis —
9135 // same "the validate / shape-gate predicate must route through
9136 // the substrate-primitive typed dispatch" discipline extended
9137 // onto the peer M2 supervisor-slot optional-`Duration` axis.
9138 let child = ChildSpec {
9139 caixa: "worker".into(),
9140 versao: "^0.1".into(),
9141 restart: RestartPolicy::Permanent,
9142 };
9143 // None arm — must not surface any :restart-window-shaped refusal;
9144 // the `if let Some(_)` bracket returns early on `None` structurally.
9145 let s = SupervisorSpec {
9146 restart_window: None,
9147 children: vec![child.clone()],
9148 ..SupervisorSpec::default()
9149 };
9150 assert!(
9151 s.validate().is_ok(),
9152 "validate must accept restart_window: None (the never-reset \
9153 sentinel) — the `if let Some(_)` bracket returns early on \
9154 the None arm and the accessor must agree",
9155 );
9156 // Zero-floor arm.
9157 let s = SupervisorSpec {
9158 restart_window: Some(Duration::ZERO),
9159 children: vec![child.clone()],
9160 ..SupervisorSpec::default()
9161 };
9162 assert_eq!(
9163 s.validate().unwrap_err(),
9164 SupervisorError::RestartWindowZero,
9165 "validate must reject restart_window == Some(Duration::ZERO) \
9166 with RestartWindowZero — the accessor and the validate gate \
9167 must route through the same substrate-primitive typed \
9168 dispatch on the zero-floor arm",
9169 );
9170 // Non-canonical (sub-ms) arm — the surfaced `window:` field must
9171 // byte-equal the accessor's return so a future rebrand on the
9172 // accessor lands in the diagnostic without a coordinated rewrite.
9173 let sub_ms = Duration::from_micros(1500);
9174 let s = SupervisorSpec {
9175 restart_window: Some(sub_ms),
9176 children: vec![child.clone()],
9177 ..SupervisorSpec::default()
9178 };
9179 match s.validate().unwrap_err() {
9180 SupervisorError::RestartWindowNotCanonical { window } => {
9181 assert_eq!(
9182 Some(window),
9183 s.restart_window(),
9184 "RestartWindowNotCanonical.window must byte-equal \
9185 SupervisorSpec::restart_window().unwrap() — the \
9186 non-canonical-arm refusal reads through the lifted \
9187 accessor",
9188 );
9189 assert_eq!(
9190 window, sub_ms,
9191 "RestartWindowNotCanonical.window must carry the \
9192 author-declared :supervisor :restart-window value \
9193 verbatim (got {window:?}, expected {sub_ms:?})",
9194 );
9195 }
9196 other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
9197 }
9198 // Cap arm — the surfaced `window:` field must byte-equal the
9199 // accessor's return.
9200 let over_cap = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
9201 let s = SupervisorSpec {
9202 restart_window: Some(over_cap),
9203 children: vec![child.clone()],
9204 ..SupervisorSpec::default()
9205 };
9206 match s.validate().unwrap_err() {
9207 SupervisorError::RestartWindowExceedsCap { window } => {
9208 assert_eq!(
9209 Some(window),
9210 s.restart_window(),
9211 "RestartWindowExceedsCap.window must byte-equal \
9212 SupervisorSpec::restart_window().unwrap() — the \
9213 cap-arm refusal reads through the lifted accessor",
9214 );
9215 assert_eq!(
9216 window, over_cap,
9217 "RestartWindowExceedsCap.window must carry the \
9218 author-declared :supervisor :restart-window value \
9219 verbatim (got {window:?}, expected {over_cap:?})",
9220 );
9221 }
9222 other => panic!("expected RestartWindowExceedsCap, got {other:?}"),
9223 }
9224 // Lower + upper accept-set boundaries.
9225 for restart_window in [Duration::from_millis(1), SUPERVISOR_RESTART_WINDOW_MAX] {
9226 let s = SupervisorSpec {
9227 restart_window: Some(restart_window),
9228 children: vec![child.clone()],
9229 ..SupervisorSpec::default()
9230 };
9231 assert!(
9232 s.validate().is_ok(),
9233 "validate must accept restart_window == Some({restart_window:?}) \
9234 (an accept-set boundary of \
9235 1ms..=SUPERVISOR_RESTART_WINDOW_MAX)",
9236 );
9237 }
9238 }
9239
9240 #[test]
9241 fn supervisor_spec_restart_window_projects_option_duration_by_copy() {
9242 // The by-copy pin: [`SupervisorSpec::restart_window`] returns
9243 // `Option<Duration>` by copy — `Duration` is `Copy` (so
9244 // `Option<Duration>` is `Copy`) and the accessor must return by
9245 // value, not by reference. Peer of the sibling M2
9246 // [`crate::LimitsSpec::wall_clock`] (8cb717b) by-copy pin on the
9247 // per-`:limits :wall-clock` axis and the sibling M3
9248 // [`crate::MeshPolicy::timeout`] (7073d0f) by-copy pin on the
9249 // per-`:politicas :timeout` axis, extended onto the peer M2
9250 // supervisor-slot `Option<Duration>` copy-invariant shape — the
9251 // accessor's returned `Option<Duration>` must outlive `&self`
9252 // (multiple calls must return equal values from a dropped-`&self`
9253 // copy, since the returned Option carries no borrow), and calling
9254 // the accessor twice on the same SupervisorSpec must yield the
9255 // same `Option<Duration>` verbatim (idempotent, no side effects
9256 // on `&self`).
9257 //
9258 // Pins against a future silent detour that returned
9259 // `Option<&Duration>` (which would type-check but silently break
9260 // every downstream caller — the future wasm-operator's
9261 // per-supervisor restart-intensity counter consumes `Duration` by
9262 // value and `&Duration` would fold to a detached copy at the call
9263 // site), an accidental `Option::as_ref()` projection
9264 // (`self.restart_window.as_ref()` would also type-check but
9265 // return `Option<&Duration>`), or a one-arm-only accessor that
9266 // reads `Some(*w)` in the Some arm but reads a fresh
9267 // `Default::default()` (which would collapse to `Duration::ZERO`,
9268 // not `None`) in the None arm — a footgun the
9269 // [`SupervisorError::RestartWindowZero`] validate arm explicitly
9270 // closes since Erlang/OTP's `MaxIntensity / Period` invariant
9271 // requires `Period > 0` and `None` structurally expresses "never
9272 // reset" instead.
9273 for restart_window in [
9274 None,
9275 Some(Duration::from_millis(1)),
9276 Some(Duration::from_secs(60)),
9277 Some(SUPERVISOR_RESTART_WINDOW_MAX),
9278 ] {
9279 let s = SupervisorSpec {
9280 restart_window,
9281 ..SupervisorSpec::default()
9282 };
9283 let first = s.restart_window();
9284 let second = s.restart_window();
9285 assert_eq!(
9286 first, second,
9287 "SupervisorSpec::restart_window must be idempotent — two \
9288 successive calls on the same &self must return the \
9289 same Option<Duration>",
9290 );
9291 assert_eq!(
9292 first, restart_window,
9293 "SupervisorSpec::restart_window must return :supervisor \
9294 :restart-window verbatim by copy — got {first:?}, \
9295 expected {restart_window:?}",
9296 );
9297 }
9298 }
9299
9300 // ── per-`:supervisor` `:children` typed-accessor coherence pins ─────────
9301 //
9302 // The [`SupervisorSpec::children`] accessor lift is the seed of the
9303 // slice-return (`&[T]`) accessor discipline on the substrate — the four
9304 // peer `Vec`-carry axes ([`crate::Placement::clusters`],
9305 // [`crate::AplicacaoSpec::membros`], [`crate::AplicacaoSpec::contratos`],
9306 // [`crate::UpgradeFromEntry::instructions`]) still key off the raw field
9307 // access at the time of this seed, and inherit this pin family's
9308 // discipline as future compounding runs migrate their consumers. The
9309 // three pins below cover (1) the accessor's byte-equal projection
9310 // against the raw field access across the empty / singleton / cohort
9311 // fixtures the [`SupervisorSpec::validate`] partition-dispatch fans
9312 // between, (2) the [`SupervisorSpec::validate`] `SimpleOneForOne ↔
9313 // non-SimpleOneForOne` partition dispatch's paired `.is_empty()`
9314 // consumer routing through the accessor on both arms, and (3) the
9315 // per-child validate loop's traversal reading the same slice-view the
9316 // accessor projects. Peer of the sibling M2
9317 // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
9318 // two-consumer coherence pin on the per-`:supervisor`
9319 // sibling-restart-strategy `Copy`-composite-enum scalar axis, extended
9320 // onto the per-`:supervisor` static-child-list `Vec`-carry axis.
9321
9322 #[test]
9323 fn supervisor_spec_children_returns_children_slice_byte_equal_across_permutations() {
9324 // The canonical per-`:supervisor` static-child-list scalar-shape
9325 // pin: [`SupervisorSpec::children`] must return the `:supervisor
9326 // :children` typed `Vec<ChildSpec>` verbatim as a `&[ChildSpec]`
9327 // slice-view over the same backing buffer the raw
9328 // `self.children.as_slice()` field access borrows from, byte-
9329 // equal across every representative fixture in the accept-set —
9330 // the empty slice (the `SimpleOneForOne`-arm sentinel),
9331 // the singleton slice (the minimal non-`SimpleOneForOne` shape),
9332 // and a two-child cohort (a peer non-`SimpleOneForOne` shape
9333 // with the peer three restart-policy variants in play).
9334 //
9335 // Pins against a future silent detour that returned
9336 // `&Vec<ChildSpec>` (which would type-check but leak the
9337 // storage-side `Vec`'s grow/push/reserve surface no consumer of
9338 // the typed view reaches for), a fresh-allocated
9339 // `Vec<ChildSpec>` copy (which would type-check via a coercion
9340 // but silently break every downstream caller that relied on the
9341 // slice sharing the backing buffer's identity), or an
9342 // out-of-order or length-drifted projection (which would silently
9343 // split the per-child validate loop's traversal input from the
9344 // paired partition-dispatch `.is_empty()` probe's input).
9345 //
9346 // Peer of the sibling
9347 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
9348 // (eafb619) `Copy`-composite-enum byte-equal pin on the
9349 // per-`:supervisor` sibling-restart-strategy axis, extended onto
9350 // the per-`:supervisor` static-child-list `Vec`-carry axis.
9351 let fixtures: Vec<Vec<ChildSpec>> = vec![
9352 Vec::new(),
9353 vec![child("worker", "^0.1", RestartPolicy::Permanent)],
9354 vec![
9355 child("worker", "^0.1", RestartPolicy::Permanent),
9356 child("cache-server", "^0.1", RestartPolicy::Transient),
9357 ],
9358 vec![
9359 child("worker", "^0.1", RestartPolicy::Permanent),
9360 child("cache-server", "^0.1", RestartPolicy::Transient),
9361 child("scratch-job", "^0.1", RestartPolicy::Temporary),
9362 ],
9363 ];
9364 for children in fixtures {
9365 let s = SupervisorSpec {
9366 children: children.clone(),
9367 ..SupervisorSpec::default()
9368 };
9369 assert_eq!(
9370 s.children(),
9371 children.as_slice(),
9372 "SupervisorSpec::children must return :supervisor \
9373 :children verbatim (got {:?}, expected {:?})",
9374 s.children(),
9375 children.as_slice(),
9376 );
9377 assert_eq!(
9378 s.children(),
9379 s.children.as_slice(),
9380 "SupervisorSpec::children accessor and \
9381 .children.as_slice() field access must byte-equal — \
9382 the accessor is the substrate-primitive typed \
9383 dispatch every downstream static-child-list consumer \
9384 must route through",
9385 );
9386 assert_eq!(
9387 s.children().len(),
9388 s.children.len(),
9389 "SupervisorSpec::children().len() must byte-equal \
9390 self.children.len() — a length-drift would silently \
9391 split the paired partition-dispatch `.is_empty()` \
9392 probe input from the per-child validate loop's \
9393 traversal input",
9394 );
9395 }
9396 }
9397
9398 #[test]
9399 fn validate_reads_through_lifted_children_accessor() {
9400 // Three-consumer coherence pin: the [`SupervisorSpec::validate`]
9401 // `SimpleOneForOne`-arm `!self.children().is_empty()` refusal
9402 // probe (which must trip [`SupervisorError::SimpleOneForOneWithStaticChildren`]
9403 // when the accessor projects a non-empty slice under a
9404 // `SimpleOneForOne` estrategia), the peer non-`SimpleOneForOne`-arm
9405 // `self.children().is_empty()` refusal probe (which must trip
9406 // [`SupervisorError::NoChildren`] when the accessor projects the
9407 // empty slice under any peer estrategia), and the per-child
9408 // validate loop's `for child in self.children()` traversal
9409 // (which must reach every entry in the same order the accessor
9410 // projects) must all key off the lifted accessor, so any future
9411 // rebrand on the typed slot's reader shape lands at exactly one
9412 // place. Pins the three-site coherence by exercising each
9413 // production consumer end-to-end: (1) the
9414 // `SimpleOneForOneWithStaticChildren` refusal under a non-empty
9415 // slice + `SimpleOneForOne` estrategia, (2) the `NoChildren`
9416 // refusal under the empty slice + non-`SimpleOneForOne`
9417 // estrategia across every peer variant, and (3) the per-child
9418 // duplicate-detection surface fires on the second entry of a
9419 // two-child cohort that shares a `:caixa` name (which requires
9420 // the loop to reach both entries — a first-entry-only projection
9421 // would silently pass since the dedup HashSet has room for the
9422 // first insert).
9423 //
9424 // Peer of the sibling M2
9425 // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
9426 // two-consumer coherence pin on the per-`:supervisor`
9427 // sibling-restart-strategy axis, extended onto the
9428 // per-`:supervisor` static-child-list `Vec`-carry axis.
9429
9430 // (1) `SimpleOneForOne`-arm probe: a non-empty slice under a
9431 // `SimpleOneForOne` estrategia must trip
9432 // `SimpleOneForOneWithStaticChildren`.
9433 let s = SupervisorSpec {
9434 estrategia: RestartStrategy::SimpleOneForOne,
9435 children: vec![child("worker", "^0.1", RestartPolicy::Permanent)],
9436 ..SupervisorSpec::default()
9437 };
9438 assert_eq!(
9439 s.validate().unwrap_err(),
9440 SupervisorError::SimpleOneForOneWithStaticChildren,
9441 "SimpleOneForOne + non-empty children must trip \
9442 SimpleOneForOneWithStaticChildren — the accessor projects \
9443 a non-empty slice, and the SimpleOneForOne-arm refusal \
9444 probe reads through the lifted accessor",
9445 );
9446 assert!(
9447 !s.children().is_empty(),
9448 "the SimpleOneForOne-arm refusal input must be a non-empty \
9449 slice per the accessor's projection",
9450 );
9451
9452 // (2) Peer non-`SimpleOneForOne`-arm probe: the empty slice
9453 // under any peer estrategia must trip `NoChildren`.
9454 for estrategia in [
9455 RestartStrategy::OneForOne,
9456 RestartStrategy::OneForAll,
9457 RestartStrategy::RestForOne,
9458 ] {
9459 let s = SupervisorSpec {
9460 estrategia,
9461 children: Vec::new(),
9462 ..SupervisorSpec::default()
9463 };
9464 match s.validate().unwrap_err() {
9465 SupervisorError::NoChildren { estrategia: e } => {
9466 assert_eq!(
9467 e, estrategia,
9468 "NoChildren.estrategia must carry the author-\
9469 declared :supervisor :estrategia variant \
9470 verbatim (got {e:?}, expected {estrategia:?})",
9471 );
9472 }
9473 other => panic!(
9474 "expected NoChildren, got {other:?} for \
9475 estrategia={estrategia:?}"
9476 ),
9477 }
9478 assert!(
9479 s.children().is_empty(),
9480 "the non-SimpleOneForOne-arm refusal input must be the \
9481 empty slice per the accessor's projection",
9482 );
9483 }
9484
9485 // (3) Per-child validate loop: a two-child cohort that shares a
9486 // `:caixa` name must trip `DuplicateChildCaixa` — the loop must
9487 // reach both entries through the accessor.
9488 let s = SupervisorSpec {
9489 estrategia: RestartStrategy::OneForOne,
9490 children: vec![
9491 child("worker", "^0.1", RestartPolicy::Permanent),
9492 child("worker", "^0.2", RestartPolicy::Transient),
9493 ],
9494 ..SupervisorSpec::default()
9495 };
9496 match s.validate().unwrap_err() {
9497 SupervisorError::DuplicateChildCaixa { caixa } => {
9498 assert_eq!(
9499 caixa, "worker",
9500 "DuplicateChildCaixa.caixa must carry the shared \
9501 child `:caixa` name verbatim",
9502 );
9503 }
9504 other => panic!("expected DuplicateChildCaixa, got {other:?}"),
9505 }
9506 assert_eq!(
9507 s.children().len(),
9508 2,
9509 "the per-child validate loop's traversal input must be a \
9510 two-element slice per the accessor's projection",
9511 );
9512 }
9513
9514 // Shared helper for the M2 per-`:children` per-slot-gate ≡
9515 // `validate` equivalence pins: builds an `OneForOne`-estrategia
9516 // one-cohort spec whose peer `:estrategia`↔`:children.is_empty()`
9517 // partition, `:max-restarts` zero-floor/cap, and `:restart-window`
9518 // bracket all pass cleanly so the sole failing surface is the
9519 // per-child cascade [`SupervisorSpec::validate_children`] owns, and
9520 // pins the two-altitude equivalence on the paired probe.
9521 fn assert_validate_children_matches_gate(children: Vec<ChildSpec>, expected: &SupervisorError) {
9522 let s = SupervisorSpec {
9523 estrategia: RestartStrategy::OneForOne,
9524 children,
9525 ..SupervisorSpec::default()
9526 };
9527 let via_gate = s.validate_children().unwrap_err();
9528 let via_validate = s.validate().unwrap_err();
9529 assert_eq!(&via_gate, expected, "validate_children direct dispatch",);
9530 assert_eq!(&via_validate, expected, "validate() end-to-end dispatch",);
9531 assert_eq!(
9532 via_gate, via_validate,
9533 "per-slot gate ≡ validate() must discriminate the same \
9534 refusal shape",
9535 );
9536 }
9537
9538 #[test]
9539 fn validate_children_matches_gate_on_per_axis_refusal_shapes() {
9540 // Fail-before-pass-after equivalence pin on the M2
9541 // per-`:children` per-slot gate ≡ [`SupervisorSpec::validate`]
9542 // convergence — sibling of the M3 mesh-slot
9543 // `validate_membros_*` / `validate_contratos_*` /
9544 // `validate_entrada_*` per-slot-gate ≡ `validate` pins on the
9545 // peer per-entry axes. Sweeps four of the five refusal shapes
9546 // the per-slot gate owns: (1) `EmptyChildName` on an empty-
9547 // `:caixa` child, (2) `ChildCaixaInvalid` on a structurally
9548 // invalid `:caixa` DNS-1123 label, (3) `EmptyChildVersion` on
9549 // an empty-`:versao` child, (4) `DuplicateChildCaixa` on a
9550 // duplicate-`:caixa` fan-out. Companion pin
9551 // `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
9552 // covers `ChildVersaoInvalid` (whose parser-owned reason string
9553 // needs pattern-matching, not equality) and the clean-pass
9554 // canonical fixture; together the two pins guarantee the
9555 // per-slot gate and `validate` discriminate the same set on
9556 // every per-child-covered input.
9557 assert_validate_children_matches_gate(
9558 vec![child("", "^0.1", RestartPolicy::Permanent)],
9559 &SupervisorError::EmptyChildName,
9560 );
9561 assert_validate_children_matches_gate(
9562 vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
9563 &SupervisorError::ChildCaixaInvalid {
9564 caixa: "Worker".into(),
9565 reason: "contains uppercase character 'W' (K8s DNS-1123 label names are lowercase-only; use \"worker\")".into(),
9566 },
9567 );
9568 assert_validate_children_matches_gate(
9569 vec![child("worker", "", RestartPolicy::Permanent)],
9570 &SupervisorError::EmptyChildVersion {
9571 caixa: "worker".into(),
9572 },
9573 );
9574 assert_validate_children_matches_gate(
9575 vec![
9576 child("worker", "^0.1", RestartPolicy::Permanent),
9577 child("worker", "^0.2", RestartPolicy::Transient),
9578 ],
9579 &SupervisorError::DuplicateChildCaixa {
9580 caixa: "worker".into(),
9581 },
9582 );
9583 }
9584
9585 #[test]
9586 fn validate_children_matches_gate_on_versao_invalid_and_clean_pass() {
9587 // Second half of the two-altitude equivalence pin — covers the
9588 // one refusal shape whose reason string is parser-owned
9589 // (`ChildVersaoInvalid`, whose reason comes from the shared
9590 // [`crate::version::parse_requirement`] impl and may drift) and
9591 // the clean-pass canonical fixture. Sibling pin
9592 // `validate_children_matches_gate_on_per_axis_refusal_shapes`
9593 // covers the four equality-comparable refusal shapes.
9594 let s_bad_versao = SupervisorSpec {
9595 estrategia: RestartStrategy::OneForOne,
9596 children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
9597 ..SupervisorSpec::default()
9598 };
9599 let via_gate = s_bad_versao.validate_children().unwrap_err();
9600 let via_validate = s_bad_versao.validate().unwrap_err();
9601 match (&via_gate, &via_validate) {
9602 (
9603 SupervisorError::ChildVersaoInvalid {
9604 caixa: cg,
9605 versao: vg,
9606 ..
9607 },
9608 SupervisorError::ChildVersaoInvalid {
9609 caixa: cv,
9610 versao: vv,
9611 ..
9612 },
9613 ) => {
9614 assert_eq!(cg, "worker", "per-slot gate :caixa carrier");
9615 assert_eq!(vg, "not-a-req", "per-slot gate :versao carrier");
9616 assert_eq!(cv, "worker", "validate() :caixa carrier");
9617 assert_eq!(vv, "not-a-req", "validate() :versao carrier");
9618 }
9619 other => panic!("expected ChildVersaoInvalid on both altitudes, got {other:?}"),
9620 }
9621 assert_eq!(
9622 via_gate, via_validate,
9623 "per-slot gate ≡ validate() on ChildVersaoInvalid full envelope",
9624 );
9625
9626 let s_ok = SupervisorSpec {
9627 estrategia: RestartStrategy::OneForOne,
9628 children: vec![
9629 child("worker-a", "^0.1", RestartPolicy::Permanent),
9630 child("worker-b", "~0.2.3", RestartPolicy::Transient),
9631 child("collector", "*", RestartPolicy::Temporary),
9632 ],
9633 ..SupervisorSpec::default()
9634 };
9635 s_ok.validate_children()
9636 .expect("per-slot gate must accept the clean-pass fixture");
9637 s_ok.validate()
9638 .expect("validate() must accept the clean-pass fixture");
9639 }
9640
9641 #[test]
9642 fn validate_children_is_self_contained_on_children_slot() {
9643 // Self-containment pin: [`SupervisorSpec::validate_children`]
9644 // resolves the per-child cascade against `&self` alone, without
9645 // depending on the peer `:estrategia`/`:max-restarts`/
9646 // `:restart-window` gates having run first — same posture the M3
9647 // peer per-slot gates carry (`validate_membros`,
9648 // `validate_contratos`, `validate_entrada`, `validate_placement`,
9649 // routing through their own oracles rather than borrowing state
9650 // threaded down from `validate`). A future consumer that reaches
9651 // the per-slot gate directly on a spec whose peer slots would
9652 // fail `validate` still surfaces the per-child refusal, not the
9653 // peer refusal.
9654 //
9655 // Construct a spec whose `:max-restarts` is `0` (which would
9656 // trip [`SupervisorError::ZeroMaxRestarts`] at `validate` after
9657 // the partition-dispatch) and whose `:children` carries a
9658 // `DuplicateChildCaixa` shape: the per-slot gate called directly
9659 // must surface `DuplicateChildCaixa`, proving it does not depend
9660 // on the peer `:max-restarts` gate running first.
9661 let s = SupervisorSpec {
9662 estrategia: RestartStrategy::OneForOne,
9663 max_restarts: 0,
9664 restart_window: Some(Duration::from_secs(60)),
9665 children: vec![
9666 child("worker", "^0.1", RestartPolicy::Permanent),
9667 child("worker", "^0.2", RestartPolicy::Transient),
9668 ],
9669 };
9670 assert_eq!(
9671 s.validate_children().unwrap_err(),
9672 SupervisorError::DuplicateChildCaixa {
9673 caixa: "worker".into(),
9674 },
9675 "per-slot gate must resolve per-child refusal directly against \
9676 `&self` — a dependency on the peer `:max-restarts` gate \
9677 running first would surface ZeroMaxRestarts here instead",
9678 );
9679 // The peer gate is still the surface `validate` reaches — pin
9680 // the ordering to establish that `validate_children` truly runs
9681 // last in `validate`'s dispatch, so a direct call bypasses the
9682 // peer gates on any spec whose per-child cascade would fail.
9683 assert_eq!(
9684 s.validate().unwrap_err(),
9685 SupervisorError::ZeroMaxRestarts,
9686 "validate() must surface the peer `:max-restarts` gate before \
9687 reaching the per-child cascade — this pins the dispatch \
9688 ordering the per-slot gate's self-containment complements",
9689 );
9690 }
9691
9692 #[test]
9693 fn child_spec_restart_accessor_is_const_fn() {
9694 // The [`ChildSpec::restart`] per-`:children` restart-decision-
9695 // policy `Copy`-return scalar accessor is declared
9696 // `#[must_use] pub const fn` — matching the sibling M2
9697 // per-`:supervisor` [`SupervisorSpec::estrategia`] (pinned by
9698 // [`supervisor_spec_estrategia_accessor_is_const_fn`] below,
9699 // both converted in this commit), the sibling M2
9700 // per-`:supervisor` [`SupervisorSpec::max_restarts`] (b698ec0)
9701 // `Copy`-`u32` accessor already `pub const fn`, and the peer M3
9702 // mesh-slot per-`:entrada` [`crate::Entrada::port`] (bafa004) /
9703 // per-`:placement` [`crate::Placement::estrategia`] (bafa004)
9704 // `Copy`-return `pub const fn` scalar accessors on the sibling
9705 // M3 surface. Pin the `const`-eval posture here so a future
9706 // accidental downgrade to non-`const` (an added runtime helper
9707 // reachable only from a non-`const` context, an
9708 // `Option<RestartPolicy>`-shape migration on the per-child
9709 // restart-decision axis once heterogeneous per-cluster
9710 // restart-policy overlays land that would silently drop the
9711 // `const` qualifier, a manual hand-rolled shadow) trips at
9712 // caixa-core build time rather than surfacing as a downstream
9713 // `const`-context regression far from the declaration.
9714 //
9715 // Same shape as the sibling M3
9716 // [`crate::aplicacao::tests::placement_estrategia_accessor_is_const_fn`]
9717 // and [`crate::aplicacao::tests::entrada_port_accessor_is_const_fn`]
9718 // (bafa004) pins on the peer M3 mesh-slot `Copy`-return scalar
9719 // accessor axis — the load-bearing witness lives in the
9720 // module-scope `const fn` wrapper `restart_via_const_fn` below:
9721 // a body that calls [`ChildSpec::restart`] under a `const fn`
9722 // signature is well-formed only when the callee is itself
9723 // `const fn`, so any future accidental downgrade of
9724 // [`ChildSpec::restart`] to non-`const` fails at caixa-core
9725 // build time (const-eval E0015 `cannot call non-const method`),
9726 // strictly stronger than a runtime `assert!(CONST)` and
9727 // side-stepping the destructor-in-const restriction that
9728 // blocks direct `const _: RestartPolicy = FIXTURE.restart()`
9729 // items on `ChildSpec`'s `String` carriers.
9730 //
9731 // The runtime body sweeps every closed-set [`RestartPolicy`]
9732 // arm and asserts the wrapped and direct dispatches agree.
9733 const fn restart_via_const_fn(c: &ChildSpec) -> RestartPolicy {
9734 c.restart()
9735 }
9736 for restart in [
9737 RestartPolicy::Permanent,
9738 RestartPolicy::Transient,
9739 RestartPolicy::Temporary,
9740 ] {
9741 let c = ChildSpec {
9742 caixa: "worker".into(),
9743 versao: "^0.1".into(),
9744 restart,
9745 };
9746 assert_eq!(
9747 restart_via_const_fn(&c),
9748 c.restart(),
9749 "const-fn-wrapped and direct dispatch on \
9750 ChildSpec::restart must agree for {restart:?}",
9751 );
9752 assert_eq!(
9753 c.restart(),
9754 restart,
9755 "ChildSpec::restart must return the storage-side \
9756 RestartPolicy verbatim for {restart:?} (a violation \
9757 means the accessor stopped being a raw field-return \
9758 copy)",
9759 );
9760 }
9761 }
9762
9763 #[test]
9764 fn supervisor_spec_estrategia_accessor_is_const_fn() {
9765 // The [`SupervisorSpec::estrategia`] per-`:supervisor`
9766 // sibling-restart-strategy `Copy`-return scalar accessor is
9767 // declared `#[must_use] pub const fn` — matching the sibling M2
9768 // per-`:children` [`ChildSpec::restart`] (pinned by
9769 // [`child_spec_restart_accessor_is_const_fn`] above, both
9770 // converted in this commit), the sibling M2 per-`:supervisor`
9771 // [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32`
9772 // accessor already `pub const fn`, and mirroring the peer M3
9773 // mesh-slot per-`:placement`
9774 // [`crate::Placement::estrategia`] (bafa004) `Copy`-return
9775 // `pub const fn` scalar accessor whose method-name discipline
9776 // the [`SupervisorSpec::estrategia`] method was authored to
9777 // match. Pin the `const`-eval posture here so a future
9778 // accidental downgrade to non-`const` (an added runtime helper
9779 // reachable only from a non-`const` context, an
9780 // `Option<RestartStrategy>`-shape migration once the substrate
9781 // grows per-cluster strategy overlays that would silently drop
9782 // the `const` qualifier, a manual hand-rolled shadow) trips at
9783 // caixa-core build time rather than surfacing as a downstream
9784 // `const`-context regression far from the declaration.
9785 //
9786 // Same shape as the sibling
9787 // [`child_spec_restart_accessor_is_const_fn`] pin above — the
9788 // load-bearing witness lives in the module-scope `const fn`
9789 // wrapper `estrategia_via_const_fn` below: a body that calls
9790 // [`SupervisorSpec::estrategia`] under a `const fn` signature
9791 // is well-formed only when the callee is itself `const fn`,
9792 // side-stepping the destructor-in-const restriction that would
9793 // otherwise block a direct
9794 // `const _: RestartStrategy = FIXTURE.estrategia()` item on
9795 // `SupervisorSpec`'s `Vec<ChildSpec>` / `Option<Duration>`
9796 // carriers.
9797 //
9798 // The runtime body sweeps every closed-set [`RestartStrategy`]
9799 // arm via [`RestartStrategy::ALL`] and asserts the wrapped and
9800 // direct dispatches agree.
9801 const fn estrategia_via_const_fn(s: &SupervisorSpec) -> RestartStrategy {
9802 s.estrategia()
9803 }
9804 for &estrategia in RestartStrategy::ALL {
9805 let s = SupervisorSpec {
9806 estrategia,
9807 max_restarts: 5,
9808 restart_window: Some(Duration::from_secs(60)),
9809 children: Vec::new(),
9810 };
9811 assert_eq!(
9812 estrategia_via_const_fn(&s),
9813 s.estrategia(),
9814 "const-fn-wrapped and direct dispatch on \
9815 SupervisorSpec::estrategia must agree for {estrategia:?}",
9816 );
9817 assert_eq!(
9818 s.estrategia(),
9819 estrategia,
9820 "SupervisorSpec::estrategia must return the storage-side \
9821 RestartStrategy verbatim for {estrategia:?} (a violation \
9822 means the accessor stopped being a raw field-return \
9823 copy)",
9824 );
9825 }
9826 }
9827
9828 // Per-variant equivalence pins for the [`supervisor_caixa_only_ctors!`]
9829 // macro definition (see the paired doc-block above the macro
9830 // definition) — every generated `<ctor>(caixa: &str) -> Self`
9831 // constructor folds the uniform `Self::<Variant> { caixa:
9832 // caixa.to_string() }` one-field struct-literal onto one substrate
9833 // primitive. The three per-variant equivalence pins below
9834 // (fail-before-pass-after by construction — a byte-mismatched macro
9835 // arm would trip its equivalence pin first) lock each generated
9836 // constructor to its struct-literal peer under `PartialEq`, so
9837 // every wire-up in [`SupervisorSpec::validate_children`] and
9838 // [`validate_no_self_supervision`] on that variant produces a
9839 // byte-equal `SupervisorError` to the pre-lift open-coded
9840 // struct-literal. The cross-axis pin that follows (non-default
9841 // caixa name) routes the sole constructor input axis through
9842 // `.to_string()`, so the fold does not silently collapse onto a
9843 // fixed name.
9844 //
9845 // Peer of the sibling `<slot>_ctor_matches_tuple_literal_wrap` /
9846 // `<slot>_violation_ctor_matches_struct_literal_wrap` /
9847 // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
9848 // `missing_entry_ctor_matches_struct_literal_wrap` /
9849 // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
9850 // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
9851 // `contrato_missing_target_ctor_matches_struct_literal_wrap` /
9852 // `<variant>_ctor_matches_struct_literal_wrap` equivalence pins
9853 // on the six sibling ctor families the recent trajectory closed
9854 // on the peer `LayoutError` / `AplicacaoError` envelopes.
9855
9856 #[test]
9857 fn empty_child_version_ctor_matches_struct_literal_wrap() {
9858 assert_eq!(
9859 SupervisorError::empty_child_version("worker"),
9860 SupervisorError::EmptyChildVersion {
9861 caixa: "worker".to_string(),
9862 },
9863 "generated empty_child_version ctor must produce byte-equal \
9864 SupervisorError to the open-coded struct-literal wrap on the \
9865 same &str fixture",
9866 );
9867 }
9868
9869 #[test]
9870 fn duplicate_child_caixa_ctor_matches_struct_literal_wrap() {
9871 assert_eq!(
9872 SupervisorError::duplicate_child_caixa("worker"),
9873 SupervisorError::DuplicateChildCaixa {
9874 caixa: "worker".to_string(),
9875 },
9876 "generated duplicate_child_caixa ctor must produce byte-equal \
9877 SupervisorError to the open-coded struct-literal wrap on the \
9878 same &str fixture",
9879 );
9880 }
9881
9882 #[test]
9883 fn child_supervises_self_ctor_matches_struct_literal_wrap() {
9884 assert_eq!(
9885 SupervisorError::child_supervises_self("orquestra"),
9886 SupervisorError::ChildSupervisesSelf {
9887 caixa: "orquestra".to_string(),
9888 },
9889 "generated child_supervises_self ctor must produce byte-equal \
9890 SupervisorError to the open-coded struct-literal wrap on the \
9891 same &str fixture",
9892 );
9893 }
9894
9895 // Per-variant equivalence pins for the two lifted
9896 // [`SupervisorError::child_caixa_invalid`] /
9897 // [`SupervisorError::child_versao_invalid`] inherent constructors
9898 // (fail-before-pass-after by construction — a byte-mismatched ctor body
9899 // would trip its equivalence pin first). Each pins the ctor output to
9900 // its pre-lift struct-literal peer under `PartialEq`, so every wire-up
9901 // in [`SupervisorSpec::validate_children`] on the two variants
9902 // produces a byte-equal `SupervisorError` to the pre-lift open-coded
9903 // struct-literal on the same scalar fixtures. Peers of the sibling
9904 // `membro_caixa_invalid_ctor_matches_struct_literal_wrap` /
9905 // `entrada_para_invalid_ctor_matches_struct_literal_wrap` / … pins on
9906 // the peer `AplicacaoError` envelope's
9907 // [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold.
9908
9909 #[test]
9910 fn child_caixa_invalid_ctor_matches_struct_literal_wrap() {
9911 let caixa = "Worker";
9912 let reason = "sample reason text";
9913 assert_eq!(
9914 SupervisorError::child_caixa_invalid(caixa, reason),
9915 SupervisorError::ChildCaixaInvalid {
9916 caixa: caixa.to_string(),
9917 reason: reason.to_string(),
9918 },
9919 "lifted child_caixa_invalid ctor must produce byte-equal \
9920 SupervisorError to the open-coded struct-literal wrap on the \
9921 same (&str, reason) fixture",
9922 );
9923 }
9924
9925 #[test]
9926 fn child_versao_invalid_ctor_matches_struct_literal_wrap() {
9927 let caixa = "worker";
9928 let versao = "not-a-req";
9929 let reason = "sample reason text";
9930 assert_eq!(
9931 SupervisorError::child_versao_invalid(caixa, versao, reason),
9932 SupervisorError::ChildVersaoInvalid {
9933 caixa: caixa.to_string(),
9934 versao: versao.to_string(),
9935 reason: reason.to_string(),
9936 },
9937 "lifted child_versao_invalid ctor must produce byte-equal \
9938 SupervisorError to the open-coded struct-literal wrap on the \
9939 same (&str, &str, reason) fixture",
9940 );
9941 }
9942
9943 #[test]
9944 fn supervisor_child_reason_ctors_route_reason_through_into_uniformly() {
9945 // Cross-axis pin: sweep the two lifted `{ …, reason }` ctors
9946 // against a `&str`-literal vs. `format!(…)` reason input to pin
9947 // both constructors accept the `impl Into<String>` bound
9948 // uniformly, so neither wire-up site drifts under a per-arm
9949 // wrapper transformation on the caller-side `reason` axis. Peer
9950 // of the sibling
9951 // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
9952 // sweep on the peer `AplicacaoError` envelope.
9953 let via_literal = "literal reason text";
9954 let via_format = format!("{} reason text", "literal");
9955 assert_eq!(
9956 SupervisorError::child_caixa_invalid("Worker", via_literal),
9957 SupervisorError::child_caixa_invalid("Worker", via_format.clone()),
9958 );
9959 assert_eq!(
9960 SupervisorError::child_versao_invalid("worker", "not-a-req", via_literal),
9961 SupervisorError::child_versao_invalid("worker", "not-a-req", via_format),
9962 );
9963 }
9964
9965 #[test]
9966 fn supervisor_caixa_only_ctors_route_caixa_through_to_string() {
9967 // Cross-axis pin: sweep the sole constructor input axis (`caixa:
9968 // &str`) through a non-default fixture name against every
9969 // generated arm in the [`supervisor_caixa_only_ctors!`] macro,
9970 // so any wrapper-side lowercase / trim / truncate / re-order on
9971 // the `caixa.to_string()` sole-field construction surfaces
9972 // here rather than at a downstream diagnostic-shape mismatch.
9973 // Peer of the sibling `nome_only_ctor_routes_caixa_through_
9974 // nome_accessor` / `entrada_host_invalid_ctor_routes_host_
9975 // through_to_string` / `contrato_target_ctors_route_edge_
9976 // triple_through_verbatim` / `contrato_empty_pair_ctors_
9977 // route_edge_pair_through_verbatim` cross-axis routing pins on
9978 // the peer `LayoutError` / `AplicacaoError` envelopes; extended
9979 // here onto the `SupervisorError` `{ caixa: String }` envelope
9980 // so every substrate-primitive ctor family in caixa-core
9981 // guarantees the sole-field construction routes the caller's
9982 // `&str` through `.to_string()` verbatim.
9983 let name = "cache-v2";
9984 assert_eq!(
9985 SupervisorError::empty_child_version(name),
9986 SupervisorError::EmptyChildVersion {
9987 caixa: name.to_string(),
9988 },
9989 );
9990 assert_eq!(
9991 SupervisorError::duplicate_child_caixa(name),
9992 SupervisorError::DuplicateChildCaixa {
9993 caixa: name.to_string(),
9994 },
9995 );
9996 assert_eq!(
9997 SupervisorError::child_supervises_self(name),
9998 SupervisorError::ChildSupervisesSelf {
9999 caixa: name.to_string(),
10000 },
10001 );
10002 }
10003
10004 // ── supervisor_scalar_ctors! per-variant + cross-axis pins ──────────────
10005 //
10006 // Per-variant byte-equality pins guaranteeing every generated ctor arm in
10007 // the [`supervisor_scalar_ctors!`] macro produces a `SupervisorError`
10008 // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
10009 // one-line struct-literal on the same `Copy`-`RestartStrategy | u32 |
10010 // Duration` fixture, plus one cross-axis sweep that routes each per-variant
10011 // `<field>: <ty>` scalar through the sole `$field:ident: $ty:ty` axis the
10012 // macro exposes so any wrapper-side truncation / re-order / silent `.into()`
10013 // / silent constant-substitution on any one variant surfaces here rather
10014 // than at a downstream per-`:supervisor` diagnostic-shape drift. Peer of the
10015 // sibling per-variant pins on `aplicacao_policy_scalar_ctors!` (7ef425e,
10016 // the 8-variant `AplicacaoError` `{ <field>: Duration | u32 }` fold on the
10017 // per-`:politicas` per-axis cap / canonical-form arms), plus the sibling
10018 // `supervisor_caixa_only_ctors!` (db09650), `SupervisorError::
10019 // {child_caixa_invalid,child_versao_invalid}` (d2ef2ec), and the peer
10020 // `DepError` / `AplicacaoError` / `LayoutError` / `LimitsError` /
10021 // `BehaviorError` / `UpgradeError` per-envelope ctor-macro pins.
10022 #[test]
10023 fn no_children_ctor_matches_struct_literal_wrap() {
10024 let estrategia = RestartStrategy::OneForAll;
10025 assert_eq!(
10026 SupervisorError::no_children(estrategia),
10027 SupervisorError::NoChildren { estrategia },
10028 "generated no_children ctor must produce byte-equal \
10029 `SupervisorError::NoChildren` to the pre-lift struct-literal wrap \
10030 on the same `Copy`-`RestartStrategy` fixture",
10031 );
10032 }
10033
10034 #[test]
10035 fn max_restarts_exceeds_cap_ctor_matches_struct_literal_wrap() {
10036 let max_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 1;
10037 assert_eq!(
10038 SupervisorError::max_restarts_exceeds_cap(max_restarts),
10039 SupervisorError::MaxRestartsExceedsCap { max_restarts },
10040 "generated max_restarts_exceeds_cap ctor must produce byte-equal \
10041 `SupervisorError::MaxRestartsExceedsCap` to the pre-lift \
10042 struct-literal wrap on the same `Copy`-`u32` fixture",
10043 );
10044 }
10045
10046 #[test]
10047 fn restart_window_not_canonical_ctor_matches_struct_literal_wrap() {
10048 let window = Duration::from_micros(1_500);
10049 assert_eq!(
10050 SupervisorError::restart_window_not_canonical(window),
10051 SupervisorError::RestartWindowNotCanonical { window },
10052 "generated restart_window_not_canonical ctor must produce \
10053 byte-equal `SupervisorError::RestartWindowNotCanonical` to the \
10054 pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
10055 );
10056 }
10057
10058 #[test]
10059 fn restart_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
10060 let window = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
10061 assert_eq!(
10062 SupervisorError::restart_window_exceeds_cap(window),
10063 SupervisorError::RestartWindowExceedsCap { window },
10064 "generated restart_window_exceeds_cap ctor must produce \
10065 byte-equal `SupervisorError::RestartWindowExceedsCap` to the \
10066 pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
10067 );
10068 }
10069
10070 #[test]
10071 fn supervisor_scalar_ctors_route_field_through_copy_uniformly() {
10072 // Cross-axis routing pin: sweep each generated `<field>: <ty>`
10073 // constructor input axis through a non-default `Copy` fixture against
10074 // every arm in the [`supervisor_scalar_ctors!`] macro, so any wrapper-
10075 // side silent `.into()` / silent constant-substitution / silent field
10076 // re-name away from the canonical `estrategia | max_restarts | window`
10077 // axes on any one variant, or a `RestartStrategy | u32 | Duration`
10078 // axis silently rerouted through some other `Copy` coercion, surfaces
10079 // here rather than at a downstream per-`:supervisor` diagnostic-shape
10080 // drift. Peer of the sibling
10081 // `aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly`
10082 // (7ef425e) cross-axis routing pin on the peer `AplicacaoError`
10083 // envelope's per-`:politicas` per-axis ctor family, extended here onto
10084 // the last M2 per-`:supervisor` `Copy`-scalar `SupervisorError`
10085 // variant family folded onto a substrate primitive.
10086 //
10087 // Fixtures picked out of each variant's accept-set boundary rather
10088 // than the default value so a silent constant-substitution to a per-
10089 // variant sentinel surfaces here on the structural-equality assertion.
10090 // The `RestartStrategy` fixture picks `RestForOne` (a non-default arm
10091 // that isn't the `OneForOne` [`SUPERVISOR_ESTRATEGIA_DEFAULT`] and
10092 // isn't the `SimpleOneForOne` arm the sibling
10093 // `SimpleOneForOneWithStaticChildren` unit variant intercepts). The
10094 // `max_restarts` fixture picks an above-cap magnitude the cap arm
10095 // rejects; the two `Duration` fixtures pick the sub-millisecond and
10096 // above-cap ends of the `:restart-window` canonical-form + cap
10097 // bracket respectively.
10098 let estrategia = RestartStrategy::RestForOne;
10099 let above_cap_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 137;
10100 let sub_ms = Duration::from_micros(1_500);
10101 let above_hour = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
10102 assert_eq!(
10103 SupervisorError::no_children(estrategia),
10104 SupervisorError::NoChildren { estrategia },
10105 );
10106 assert_eq!(
10107 SupervisorError::max_restarts_exceeds_cap(above_cap_restarts),
10108 SupervisorError::MaxRestartsExceedsCap {
10109 max_restarts: above_cap_restarts,
10110 },
10111 );
10112 assert_eq!(
10113 SupervisorError::restart_window_not_canonical(sub_ms),
10114 SupervisorError::RestartWindowNotCanonical { window: sub_ms },
10115 );
10116 assert_eq!(
10117 SupervisorError::restart_window_exceeds_cap(above_hour),
10118 SupervisorError::RestartWindowExceedsCap { window: above_hour },
10119 );
10120 }
10121
10122 #[test]
10123 fn supervisor_scalar_ctors_are_const_zero_runtime_work() {
10124 // Const-eval pin: the [`supervisor_scalar_ctors!`] macro spells every
10125 // generated ctor `const fn` so a caller can pin a `SupervisorError`
10126 // at compile time — the same zero-runtime-work property the pre-lift
10127 // `|<slot>| SupervisorError::<Variant> { <slot> }` closure carried on
10128 // its `Copy`-pass-through construction path (no `.to_string()` /
10129 // `.into()` allocation, no branching). If any future edit silently
10130 // drops the `const` qualifier from the macro body the per-arm `const`
10131 // bindings below fail to compile, which surfaces the regression at
10132 // the substrate-primitive definition rather than at some downstream
10133 // consumer that had come to rely on the `const`-constructibility.
10134 // Peer of the sibling
10135 // `aplicacao_policy_scalar_ctors_are_const_zero_runtime_work`
10136 // (7ef425e) const-eval pin on the peer `AplicacaoError` envelope's
10137 // per-`:politicas` per-axis ctor family.
10138 const NO_CHILDREN: SupervisorError =
10139 SupervisorError::no_children(RestartStrategy::OneForAll);
10140 const MAX_RESTARTS_CAP: SupervisorError = SupervisorError::max_restarts_exceeds_cap(1_337);
10141 const WINDOW_NC: SupervisorError =
10142 SupervisorError::restart_window_not_canonical(Duration::from_micros(1));
10143 const WINDOW_CAP: SupervisorError =
10144 SupervisorError::restart_window_exceeds_cap(Duration::from_secs(3_601));
10145 assert!(matches!(NO_CHILDREN, SupervisorError::NoChildren { .. }));
10146 assert!(matches!(
10147 MAX_RESTARTS_CAP,
10148 SupervisorError::MaxRestartsExceedsCap { .. }
10149 ));
10150 assert!(matches!(
10151 WINDOW_NC,
10152 SupervisorError::RestartWindowNotCanonical { .. }
10153 ));
10154 assert!(matches!(
10155 WINDOW_CAP,
10156 SupervisorError::RestartWindowExceedsCap { .. }
10157 ));
10158 }
10159}