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/// Per-child restart policy.
434///
435/// Permanent / Temporary / Transient match Erlang/OTP semantics 1:1.
436#[derive(
437 Serialize,
438 Deserialize,
439 Debug,
440 Clone,
441 Copy,
442 PartialEq,
443 Eq,
444 Hash,
445 gen_platform::TypedDispatcher,
446 gen_platform::Discriminant,
447 gen_platform::IsVariant,
448 gen_platform::FromStrKind,
449)]
450pub enum RestartPolicy {
451 /// Always restart the child, regardless of how it died. Used for
452 /// long-running services that must always be up.
453 Permanent,
454 /// Never restart. Used for one-shot work whose completion is
455 /// itself the success signal (`oneShot` triggers map here).
456 Temporary,
457 /// Restart only when the child died *abnormally* (non-zero exit
458 /// or unhandled exception). A clean exit completes the child.
459 Transient,
460}
461
462impl Default for RestartPolicy {
463 fn default() -> Self {
464 // Route the [`Default for RestartPolicy`] impl's return arm through
465 // the substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed
466 // `pub const` rather than a raw `Self::Permanent` arm — one source
467 // of truth for the Erlang/OTP-canonical `permanent` worker-child
468 // default across the two production consumers that currently
469 // dispatch on it (this impl at the [`RestartPolicy::default`] call
470 // and the serde-side `#[serde(default)]` on
471 // [`ChildSpec::restart`] that resolves an author-omitted
472 // `:children :restart` slot through `RestartPolicy::default()`).
473 // Peer of the sibling per-`:supervisor` axis
474 // [`Default for RestartStrategy`] → [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
475 // route (95ffacc) — the two impls now share one substrate-primitive
476 // lift discipline, so any future coherent rebrand of the OTP-shape
477 // supervisor+child default set migrates through typed constants in
478 // lockstep instead of splitting a lifted supervisor half against
479 // an open-coded child half. Pinned by
480 // `restart_policy_default_routes_through_lifted_default` +
481 // `child_spec_serde_default_restart_routes_through_lifted_default`
482 // in the tests module.
483 SUPERVISOR_CHILD_RESTART_DEFAULT
484 }
485}
486
487impl RestartPolicy {
488 /// Exhaustive iteration surface for every consumer that walks the
489 /// closed three-arm [`RestartPolicy`] discriminator set (the future
490 /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
491 /// per-child admission-webhook rejection body naming the accepted-
492 /// `:restart` list, a future `feira supervisor --restart …` CLI
493 /// arg-parse's "did you mean" hint via a [`Self::from_wire`]-scan
494 /// over the slice, the future `feira app graph` per-child restart
495 /// column, any future round-trip fuzz harness that sweeps every
496 /// arm). A future arm addition (an OTP-`intrinsic` fourth arm the
497 /// theory
498 /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
499 /// might reach for once the three canonical OTP restart policies
500 /// stop covering the substrate's discovered load-shape) extends
501 /// this slice as one edit and every consumer picks up the new entry
502 /// by construction; the compiler-checked exhaustiveness on the
503 /// sibling method `match` arms ([`Self::as_str`] / [`Self::from_wire`])
504 /// is the build-time guarantee that no arm forgets to grow.
505 ///
506 /// Peer of the sibling closed-set typed enums'
507 /// [`RestartStrategy::ALL`] (4eec29c) /
508 /// [`crate::CaixaKind::ALL`] (6b1f4fb) /
509 /// [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
510 /// [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
511 /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
512 /// surfaces — the sixth (and the third and final M2 OTP-shape)
513 /// closed-set typed enum on the caixa surface to converge onto the
514 /// same one-canonical-arm-list-per-enum discipline. Sibling axis to
515 /// the peer [`RestartStrategy::ALL`] on the per-supervisor
516 /// sibling-restart-strategy axis; this closes the per-child
517 /// restart-decision-policy axis on the same M2 `:supervisor` slot.
518 pub const ALL: &'static [Self] = &[Self::Permanent, Self::Temporary, Self::Transient];
519
520 /// Canonical PascalCase discriminator scalar this variant serializes
521 /// as under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`]. The three
522 /// arms return the paired
523 /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
524 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
525 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] lifted
526 /// constants so every substrate consumer that dispatches on the
527 /// per-child restart-decision policy (the future wasm-operator's
528 /// per-child post-exit restart-decision branch, the future M4
529 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
530 /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
531 /// reconciliation scheduler's per-child-policy fan-out) reads the
532 /// same byte-string the `Serialize` derive emits — the pin test in
533 /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
534 /// asserts the two paths agree, peer of the M2
535 /// [`RestartStrategy::as_str`] (09ffb2d) on the sibling per-supervisor
536 /// sibling-restart-strategy axis and the M3
537 /// [`crate::aplicacao::PlacementStrategy::as_str`] (cc8f749) on the
538 /// per-Aplicacao distribution-strategy axis — the third of three
539 /// OTP-shaped closed-enum discriminator axes on the caixa typed
540 /// surface to converge onto the same three-path-convergence
541 /// (`Serialize` derive → `as_str` helper → lifted constant)
542 /// drift-detection posture.
543 #[must_use]
544 pub const fn as_str(self) -> &'static str {
545 match self {
546 Self::Permanent => crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
547 Self::Temporary => crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
548 Self::Transient => crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
549 }
550 }
551
552 /// Substrate-canonical reverse projection on the `:children :restart`
553 /// closed-set axis — parses the `PascalCase` discriminator scalar
554 /// back to the typed variant, or `None` when `s` is outside the
555 /// closed-set arm-string set [`Self::as_str`] emits. Dispatches on
556 /// the same lifted
557 /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
558 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
559 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] constants
560 /// the [`Self::as_str`] emitter walks, so the parse and emit halves
561 /// of the round-trip migrate through one caixa-core edit on any
562 /// future arm addition.
563 ///
564 /// Prior to this lift the substrate carried only the forward
565 /// `Self → &str` projection on the OTP per-child restart-policy
566 /// axis (the [`Self::as_str`] emitter, the [`std::fmt::Display`]
567 /// impl routed through it, the `Serialize` derive that emits the
568 /// same byte-string under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`])
569 /// plus the kebab-case dispatcher-catalog identity via
570 /// [`Self::discriminant`] — every non-serde consumer that wanted to
571 /// parse a wire-form `PascalCase` policy scalar had to re-inline a
572 /// three-arm `match s { "Permanent" => …, "Temporary" => …,
573 /// "Transient" => …, _ => … }` cascade that expressed no
574 /// compile-time link back to the typed variant's canonical lifted
575 /// constant. A future variant rename or per-arm serde-attribute
576 /// drift would silently split the wire byte-string one non-serde
577 /// consumer parsed from the one the emitter wrote, with the failure
578 /// surfacing at the operator's reconcile posture (a `:temporary`
579 /// `oneShot` child being restarted on clean exit, treating the
580 /// successful-completion signal as failure and re-running the
581 /// completion-terminal one-shot indefinitely; a `:transient` child
582 /// that clean-exited being restarted, masking the clean-completion
583 /// contract) far from the rebrand commit and with no field naming
584 /// the drift.
585 ///
586 /// Distinct axis from the [`std::str::FromStr`] impl the
587 /// [`gen_platform::FromStrKind`] derive already installs on this
588 /// enum by design, not by drift: `FromStr` parses the *kebab-case*
589 /// dispatcher-catalog identity (`"permanent"` / `"temporary"` /
590 /// `"transient"` — the inverse of [`Self::discriminant`]), while
591 /// this method inverts the `PascalCase` wire byte-string
592 /// [`Self::as_str`] emits. The two-axis split lets the dispatcher-
593 /// catalog identity live in kebab-case (where every peer catalog
594 /// identifier already lives) without forcing a wire-format rename
595 /// on the tatara-lisp author surface (`:restart Permanent`,
596 /// `PascalCase`) — the same two-axis distinction the sibling
597 /// [`RestartStrategy::from_wire`] (4eec29c) /
598 /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
599 /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
600 /// carry on their peer closed-set typed-enum wire round-trips.
601 ///
602 /// Same closed-set-reverse-projection discipline the sibling
603 /// [`RestartStrategy::from_wire`] (4eec29c) /
604 /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
605 /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
606 /// [`crate::aplicacao::RateLimitUnit::from_suffix`] typed enums
607 /// carry on the peer wire-side `str → Self` axes — extended onto
608 /// the M2 OTP-shape per-child restart-policy closed-set axis, the
609 /// sixth substrate-side closed-set typed enum (and the third and
610 /// final OTP-shape closed-enum discriminator axis) to converge on
611 /// the two-way `str ↔ Self` round-trip. Method-named `from_wire`
612 /// (not `from_str`) to match the peer [`RestartStrategy::from_wire`]
613 /// shape verbatim and side-step the [`std::str::FromStr`] impl the
614 /// derive already installs on the sibling kebab-case axis. Returns
615 /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
616 /// shapes: the caller picks the diagnostic form appropriate for
617 /// its use site.
618 #[must_use]
619 pub fn from_wire(s: &str) -> Option<Self> {
620 match s {
621 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT => Some(Self::Permanent),
622 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY => Some(Self::Temporary),
623 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT => Some(Self::Transient),
624 _ => None,
625 }
626 }
627}
628
629/// [`std::fmt::Display`] routed through [`RestartPolicy::as_str`], so the
630/// pretty-printed byte-string every consumer that formats the policy as
631/// user-facing text lands on (the future wasm-operator's per-child
632/// post-exit restart-decision diagnostic line, the future `feira app
633/// graph` per-child restart column, the future M4
634/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
635/// admission-webhook rejection body) reaches for the same lifted
636/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
637/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
638/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
639/// wire-format `Serialize` derive already emits under
640/// [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
641/// [`RestartPolicy::as_str`] helper already returns.
642///
643/// Pre-convergence the two paths structurally disagreed — the
644/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
645/// route (now retired here) sent [`std::fmt::Display`] through the
646/// gen-platform discriminant catalog string, which arrives kebab-case as
647/// `"permanent"` / `"temporary"` / `"transient"` on this three-arm enum
648/// (whose variant names each collapse to their own lowercase form under
649/// the kebab-case transform), while the wire format ran as `PascalCase`
650/// `"Permanent"` / `"Temporary"` / `"Transient"` through the un-`rename`d
651/// serde derive. Every consumer that formatted the policy for a
652/// diagnostic line, a graph column, or a rejection body under
653/// `format!("{v}")` therefore landed under a different byte-string than
654/// the wire format the operator's per-child-policy dispatch keyed off —
655/// a silent split whose apply-time symptom (a `format!("{v}")`-carrying
656/// diagnostic quoting `"permanent"` while the wire scalar the operator
657/// probed was `"Permanent"`) surfaced as a confused correlate at
658/// operator-log time far from the two-declaration site.
659///
660/// Routing `Display` through [`RestartPolicy::as_str`] closes the third
661/// path: every `format!("{v}")` call reaches the same lifted
662/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the wire format
663/// and the [`RestartPolicy::as_str`] helper route through — `Debug` (the
664/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
665/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
666/// byte-string per variant. A future variant rename or
667/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
668/// exactly one place, structurally.
669///
670/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
671/// (from `#[derive(gen_platform::Discriminant)]`) still returns
672/// `"permanent"` / `"temporary"` / `"transient"`, and the fleet-wide
673/// [`gen_platform::register_dispatcher!("caixa.restart-policy", …)`]
674/// registration keys the catalog off the same kebab identity. The two
675/// naming worlds now live on separate typed methods (`Display` /
676/// `as_str` for the wire byte-string, `discriminant` for the catalog
677/// identity) rather than sharing one `Display` route that structurally
678/// disagrees with the wire format.
679///
680/// Pin tests
681/// [`tests::restart_policy_display_routes_through_as_str_helper`]
682/// and
683/// [`tests::restart_policy_display_matches_serialized_wire_byte_string`]
684/// assert the three paths agree byte-for-byte on every variant, so a
685/// future variant rename or per-arm serde attribute drift is a build
686/// error visible at caixa-core test time, not a silent per-consumer
687/// dispatch miss at apply / reconcile time.
688///
689/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
690/// (aplicacao.rs:2306) on the per-Aplicacao distribution-strategy axis
691/// and the sibling [`RestartStrategy`] `Display` impl on the
692/// per-supervisor sibling-restart-strategy axis — same three-path-
693/// convergence discipline, extended to close the third and final of
694/// three OTP-shaped closed-enum discriminator axes on the caixa typed
695/// surface.
696impl std::fmt::Display for RestartPolicy {
697 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
698 f.write_str(self.as_str())
699 }
700}
701
702/// Substrate-canonical [`AsRef<str>`] projection on the M2
703/// per-child-restart-policy [`RestartPolicy`] closed-set typed enum —
704/// routes through the same [`RestartPolicy::as_str`] `pub const fn`
705/// scalar accessor the paired [`std::fmt::Display`] impl and the
706/// un-`rename`d [`serde::Serialize`] derive already key off, so any
707/// future consumer that binds a [`RestartPolicy`] through the
708/// standard-library `impl AsRef<str>` bound (a future
709/// [`caixa-feira`] `feira supervisor --restart <arm>` verb that
710/// composes the emitted `PascalCase` wire scalar into a
711/// [`std::process::Command::arg`] shell-out of the future
712/// wasm-operator's per-child admission gate, a per-child structured-
713/// log recorder on the future `caixa-operator`'s hierarchical
714/// reconciliation surface that accepts `impl AsRef<str>` at the
715/// `tracing::field::Value` `Str`-arm, a [`std::collections::HashMap`]
716/// lookup keyed on the restart-policy wire byte through
717/// `map.get::<str>(policy.as_ref())` on a future per-policy
718/// dispatch table) reaches the paired
719/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
720/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
721/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
722/// lifted-const through one substrate-primitive dispatch rather
723/// than an open-coded `.as_str()` projection at every wire-up.
724///
725/// Peer of the sibling [`std::fmt::Display`] impl on the same
726/// primitive — both delegate to the shared [`RestartPolicy::as_str`]
727/// `pub const fn` accessor, so [`format!("{v}")`], `v.as_str()`, and
728/// `<RestartPolicy as AsRef<str>>::as_ref(&v)` resolve to the same
729/// byte-string per instance by construction. A future variant rename
730/// or `#[serde(rename_all = "kebab-case")]` attribute-drift on the
731/// enum reaches every one of the three paths (plus the wire-format
732/// `Serialize` derive that already routes through the same lifted
733/// const) through exactly one caixa-core edit.
734///
735/// Same "route the trait impl through the substrate-primitive
736/// accessor" discipline the sibling [`crate::CaixaVersion`]
737/// [`AsRef<str>`] impl (16d5c7e) and the paired M2
738/// [`RestartStrategy`] [`AsRef<str>`] impl (63eb1a4) carry — extends
739/// the axis onto the paired per-child-restart-decision-policy
740/// sibling on the same M2 `:supervisor` slot (the second M2
741/// OTP-shape closed-set typed enum to converge onto the standard-
742/// library [`AsRef<str>`] projection). Rust-side newtype/typed-enum
743/// convention pairs [`AsRef<str>`] and [`fmt::Display`] on the same
744/// primitive so a caller who has one has both; before this lift,
745/// [`RestartPolicy`] carried [`fmt::Display`] but not the paired
746/// [`AsRef<str>`] impl the convention names.
747///
748/// Pinned load-bearing by
749/// [`tests::restart_policy_as_ref_str_routes_through_as_str_accessor`]
750/// (byte-parity pin against [`RestartPolicy::as_str`] across the
751/// three-arm closed set) and
752/// [`tests::restart_policy_as_ref_str_routes_through_display_via_shared_accessor`]
753/// (three-path convergence: `AsRef<str>` + `Display` + `as_str` all
754/// resolve to the same lifted `SUPERVISOR_CHILD_RESTART_*` const per
755/// arm) — any future silent detour that routes the impl through a
756/// divergent projection (a per-arm inline `match self { … }`
757/// re-inlining that opens a compile-time link to the un-lifted
758/// arm-literal, a swap onto the kebab-case
759/// [`gen_platform::Discriminant`] catalog identity that would
760/// collide the wire axis with the dispatcher-catalog axis) trips at
761/// caixa-core test time under `assert_eq!` rather than at a
762/// downstream `impl AsRef<str>`-bound consumer's silent split.
763impl AsRef<str> for RestartPolicy {
764 fn as_ref(&self) -> &str {
765 self.as_str()
766 }
767}
768
769// Fleet-wide dispatcher-catalog registrations for caixa's OTP
770// supervisor surface — two more typed shadows over Erlang/OTP
771// primitives the substrate now mechanically tracks (see
772// theory/UNIFIED-COMPUTING-MODEL.md §VI for the roadmap +
773// theory/TYPED-ABSORPTION.md for the absorption arc).
774gen_platform::register_dispatcher!("caixa.restart-strategy", RestartStrategy);
775gen_platform::register_dispatcher!("caixa.restart-policy", RestartPolicy);
776
777/// One child entry in the supervisor's `:children` list.
778///
779/// Every child references another caixa by `:caixa <nome>` + version
780/// constraint. The supervisor materializes one ComputeUnit per entry.
781#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
782#[serde(rename_all = "camelCase")]
783pub struct ChildSpec {
784 /// The child caixa's `:nome`. Must resolve via the same dependency
785 /// resolution path as `:deps` (caixa-resolver).
786 pub caixa: String,
787
788 /// Semver constraint (`"^0.1"`, `"~0.1.2"`, etc.) — same shape as
789 /// [`crate::dep::Dep::versao`].
790 pub versao: String,
791
792 /// Restart policy — an author-omitted slot degrades onto the
793 /// substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`]
794 /// (`permanent`, the Erlang/OTP worker-child default) through the
795 /// [`Default for RestartPolicy`] impl this `#[serde(default)]` routes
796 /// to.
797 #[serde(default)]
798 pub restart: RestartPolicy,
799}
800
801impl ChildSpec {
802 /// Substrate-canonical per-`:children` child-caixa `:nome` scalar
803 /// accessor every consumer that reads the OTP-shape supervised
804 /// child's identity keys off — returns the author-declared
805 /// `:children :caixa` byte-string verbatim as a `&str`, borrowed
806 /// from the typed slot's own [`String`] storage.
807 ///
808 /// The `:children :caixa` slot carries the DNS-1123 label — the
809 /// child caixa's `:nome` — that every emitted cluster artifact
810 /// derives its `metadata.name` from verbatim: the rendered
811 /// `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name` per child, the
812 /// [`crate::LABEL_PROGRAM`] label value on every child's pod
813 /// identity, and the per-child K8s Service `metadata.name` the
814 /// future wasm-operator (M3) provisions for inter-child supervision-
815 /// tree wiring. Every downstream consumer that fans on the child's
816 /// caixa-name keys off this scalar (the [`SupervisorSpec::validate`]
817 /// per-child DNS-1123 gate at
818 /// `require_valid_dns_1123_label(child.nome(), …)`, the per-child
819 /// duplicate-detection [`crate::render::insert_first_seen`] key, the
820 /// [`validate_no_self_supervision`] cross-slot equality check
821 /// against the parent's `:nome`, every `SupervisorError` variant
822 /// carrying the offending child caixa verbatim for `feira lint`
823 /// rendering, the future wasm-operator's hierarchical reconciliation
824 /// scheduler's per-child ComputeUnit-name projection, the future M4
825 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
826 /// admission webhook).
827 ///
828 /// Prior to this lift the `.caixa` byte-string was accessed inline
829 /// at seven sites in `supervisor.rs` — the DNS-1123 gate's
830 /// `&child.caixa`, the four `SupervisorError::{ChildCaixaInvalid,
831 /// EmptyChildVersion, ChildVersaoInvalid, DuplicateChildCaixa}`
832 /// carriers' `child.caixa.clone()`, the dedup key's
833 /// `child.caixa.as_str()`, and the [`validate_no_self_supervision`]
834 /// `child.caixa == parent_nome` cross-slot check — seven open-coded
835 /// field-accesses that expressed no compile-time link back to the
836 /// typed slot. A future extension of the `:children :caixa` axis to
837 /// a richer author surface (a per-cluster alias table the operator
838 /// pins through a future `:placement`-scoped slot on the supervisor
839 /// tree, a namespace-qualified rewrite the M4 CR materializer
840 /// applies per-CR, a per-child overlay from the future `:children
841 /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
842 /// acknowledges) would have had to be threaded through every
843 /// open-coded copy in lockstep or one consumer would silently
844 /// disagree with the peers on which caixa a given child resolves to
845 /// — a child-set lookup that treated the name as `"cart-worker"`
846 /// while the peer duplicate-detector treated it as
847 /// `"tenant-a/cart-worker"` would silently split the
848 /// `DuplicateChildCaixa` membership-lookup diagnostic from the
849 /// self-supervision detector's parent-equality check, a two-consumer
850 /// split at the validator far from the source `caixa.lisp` with no
851 /// field naming the identity-drift root cause. Lifting the resolution
852 /// rule to a typed method on the substrate primitive means every
853 /// downstream consumer of the Supervisor's per-`:children` identity
854 /// surface reaches for exactly one typed dispatch — the resolver's
855 /// accept-set migrates as a unit on any future axis addition.
856 ///
857 /// Sibling of the peer per-`:membros` [`crate::Membro::nome`]
858 /// (4a32abf) member-caixa `:nome` scalar accessor on the M3
859 /// mesh-slot surface — same "one typed dispatch on the substrate
860 /// primitive, thin projections at each consumer" discipline extended
861 /// onto the M2 supervisor-tree per-`:children` child-identity axis.
862 /// The two typed axes (`Membro::nome` on the M3 Aplicacao side,
863 /// `ChildSpec::nome` on the M2 Supervisor side) now share one
864 /// accessor discipline for the shared substrate concept "another
865 /// caixa referenced by `:nome`". Peer of the second M2 slot scalar
866 /// accessor [`crate::UpgradeFromEntry::prior_versao`] (75d27a8) on
867 /// the sibling per-`:upgrade-from :from` OTP-appup axis — the M2
868 /// slot family's typed-accessor discipline now spans both the
869 /// upgrade axis (`:upgrade-from`) and the supervision axis
870 /// (`:children`), matching the closed M3 mesh-slot accessor family's
871 /// shape. Named `nome()` to match the tatara-lisp author-surface
872 /// term the field's docstring already reaches for ("The child
873 /// caixa's `:nome`") and the peer [`crate::Membro::nome`] /
874 /// [`crate::Caixa::nome`] / [`crate::dep::Dep::nome`] field-name
875 /// discipline the substrate already carries — the accessor's name
876 /// maps directly onto the canonical caixa-identity vocabulary rather
877 /// than shadowing the field's storage-side `caixa` label.
878 #[must_use]
879 pub const fn nome(&self) -> &str {
880 self.caixa.as_str()
881 }
882
883 /// Substrate-canonical per-`:children` child-caixa `:versao` semver-
884 /// requirement scalar accessor every consumer that reads the OTP-shape
885 /// supervised child's version pin keys off — returns the author-declared
886 /// `:children :versao` byte-string verbatim as a `&str`, borrowed from
887 /// the typed slot's own [`String`] storage.
888 ///
889 /// The `:children :versao` slot carries the Cargo-shaped semver
890 /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that pins
891 /// which release of the supervised child caixa the OTP-shape supervisor
892 /// tree materializes against — the same requirement grammar the peer
893 /// `:deps :versao` / `:membros :versao` axes carry, resolved through the
894 /// shared [`crate::render::require_valid_versao_requirement`] cascade
895 /// and the shared [`crate::version::parse_requirement`] parser. Every
896 /// downstream consumer that fans on the child's version pin keys off
897 /// this scalar (the [`SupervisorSpec::validate`] per-child requirement
898 /// gate at `require_valid_versao_requirement(child.versao_requirement(),
899 /// …)`, the [`SupervisorError::ChildVersaoInvalid`] variant's carrier
900 /// for `feira lint` rendering, every future per-cluster version-lock
901 /// overlay the caixa-operator's hierarchical reconciliation scheduler
902 /// pins through a future `:placement`-scoped supervisor-tree slot, the
903 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
904 /// per-child version resolver, the future wasm-operator's per-child
905 /// lacre BLAKE3-closure lookup at `ComputeUnit` materialization time).
906 ///
907 /// Prior to this lift the `.versao` byte-string was accessed inline at
908 /// two `&str`-shaped sites in `caixa-core/src/supervisor.rs` — the
909 /// [`SupervisorSpec::validate`] requirement-gate call
910 /// `require_valid_versao_requirement(&child.versao, …)` and the
911 /// [`SupervisorError::ChildVersaoInvalid`] carrier at
912 /// `versao: child.versao.clone()` — two open-coded field-accesses that
913 /// expressed no compile-time link back to the typed slot. A future
914 /// extension of the `:children :versao` axis to a richer author surface
915 /// (a per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
916 /// flow, a lacre-projected concrete-version rewrite the operator
917 /// materializes at CR-admission time, a future `:children :versao-lock`
918 /// per-cluster override slot the wasm-operator's hierarchical
919 /// reconciliation scheduler authors per-CR) would have had to be
920 /// threaded through both open-coded copies in lockstep or one consumer
921 /// would silently disagree with the peer on which release constraint a
922 /// given child resolves to — the requirement-gate call reading
923 /// `"^0.1"` while the error-body carrier read `"tenant-a-pin/^0.1"`
924 /// would silently split the `ChildVersaoInvalid` diagnostic quote from
925 /// the actual gate rejection input, a two-consumer split at the
926 /// validator far from the source `caixa.lisp` with no field naming the
927 /// version-pin drift root cause. Lifting the resolution rule to a typed
928 /// method on the substrate primitive means every downstream
929 /// requirement-facing consumer of the Supervisor's per-`:children`
930 /// version-pin surface reaches for exactly one typed dispatch — the
931 /// resolver's accept-set migrates as a unit on any future axis addition.
932 ///
933 /// Sibling of the peer per-`:membros` [`crate::Membro::versao_requirement`]
934 /// (a40b0e3) member-caixa `:versao` scalar accessor on the M3 mesh-slot
935 /// surface — same "one typed dispatch on the substrate primitive, thin
936 /// projections at each consumer" discipline extended onto the M2
937 /// supervisor-tree per-`:children` child-version-pin axis. The two typed
938 /// axes (`Membro::versao_requirement` on the M3 Aplicacao side,
939 /// `ChildSpec::versao_requirement` on the M2 Supervisor side) now share
940 /// one accessor discipline for the shared substrate concept "another
941 /// caixa referenced by a Cargo-shaped semver requirement". Peer of the
942 /// sibling per-`:children` [`ChildSpec::nome`] (57c61d0) child-caixa
943 /// `:nome` scalar accessor — the pair
944 /// `(nome(), versao_requirement())` jointly projects the
945 /// `(caixa, versao)` field pair every OTP-shape supervisor-tree consumer
946 /// that fans on per-child identity + version pin keys off, closing the
947 /// last unlifted per-`:children` `String`-carry axis so every downstream
948 /// per-`:children` reader now routes through a typed dispatch on the
949 /// substrate primitive. Named `versao_requirement()` rather than
950 /// `versao()` because the field's storage-side `.versao` label is
951 /// already the author-surface term (`:versao`); the accessor's name
952 /// carries the semantic role — the semver *requirement* string the
953 /// shared [`crate::version::parse_requirement`] entry-point consumes —
954 /// so a raw field access and a typed dispatch read differently at every
955 /// consumer site. Matches the peer [`crate::Membro::versao_requirement`]
956 /// naming discipline verbatim.
957 #[must_use]
958 pub const fn versao_requirement(&self) -> &str {
959 self.versao.as_str()
960 }
961
962 /// Substrate-canonical per-`:children` `:restart` OTP-shaped
963 /// per-child post-exit restart-decision policy scalar accessor every
964 /// consumer that dispatches on the supervised child's post-exit
965 /// reconcile posture keys off — returns the author-declared
966 /// `:children :restart` variant verbatim as a [`RestartPolicy`],
967 /// `Copy`-projected from the typed slot's own [`RestartPolicy`]
968 /// storage.
969 ///
970 /// The `:children :restart` slot carries the closed-set OTP-shaped
971 /// per-child restart-decision policy discriminator
972 /// ([`RestartPolicy::Permanent`] — always restart, the OTP `permanent`
973 /// worker-child default; [`RestartPolicy::Transient`] — restart only
974 /// on abnormal exit, the OTP `transient` clean-completion-aware
975 /// default; [`RestartPolicy::Temporary`] — never restart, the OTP
976 /// `temporary` one-shot default) that every downstream consumer of
977 /// the Supervisor's per-child post-exit reconcile branch keys off.
978 /// Every future downstream consumer that fans on the per-child
979 /// restart-decision keys off this scalar (the future `feira app
980 /// graph` per-child restart column, the future wasm-operator's
981 /// per-child post-exit restart-decision branch, the future M4
982 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
983 /// admission webhook, the `caixa-operator`'s hierarchical
984 /// reconciliation scheduler's per-child post-exit reconcile branch,
985 /// the [`RestartPolicy::as_str`] `Serialize`-derive-pinning path the
986 /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
987 /// pin threads through).
988 ///
989 /// Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
990 /// (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
991 /// scalar accessor and the M3 mesh-slot
992 /// [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
993 /// [`crate::PlacementStrategy`] distribution-strategy scalar accessor
994 /// — same "one typed dispatch on the substrate primitive,
995 /// `Copy`-projected closed-set enum-arm discriminator that partitions
996 /// the downstream renderer's per-arm fan-out" discipline extended
997 /// onto the M2 supervisor-slot per-`:children` restart-decision-policy
998 /// `Copy`-composite-enum scalar axis. Third axis on the per-`:children`
999 /// [`ChildSpec`] type — companion to the sibling per-`:children`
1000 /// [`ChildSpec::nome`] (57c61d0) child-caixa `:nome` scalar accessor
1001 /// and the per-`:children` [`ChildSpec::versao_requirement`]
1002 /// (2c053c8) child-caixa `:versao` semver-requirement scalar accessor
1003 /// on the sibling `String`-carry axes. The triple
1004 /// `(nome(), versao_requirement(), restart())` jointly projects the
1005 /// `(caixa, versao, restart)` field trio every OTP-shape supervisor-
1006 /// tree consumer that fans on per-child identity + version pin +
1007 /// restart-decision keys off, closing the last unlifted per-`:children`
1008 /// axis so every downstream per-`:children` reader now routes through
1009 /// a typed dispatch on the substrate primitive. Named `restart()` to
1010 /// match the storage field's name and the author-surface
1011 /// `:children :restart` slot term verbatim; the accessor's identity
1012 /// name maps onto the canonical OTP-shape per-child restart-decision-
1013 /// policy vocabulary the [`RestartPolicy`] enum's docstring already
1014 /// carries.
1015 ///
1016 /// Declared `pub const fn` to close the last non-`const`
1017 /// `Copy`-return raw-field-getter posture on the M2
1018 /// per-`:children` [`ChildSpec`] substrate-primitive surface — peer
1019 /// of the sibling M2 per-`:supervisor`
1020 /// [`SupervisorSpec::estrategia`] (converted in this commit)
1021 /// `Copy`-composite-enum accessor, the sibling M2 per-`:supervisor`
1022 /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
1023 /// already lifted, and the peer M3 mesh-slot per-`:entrada`
1024 /// [`crate::Entrada::port`] (bafa004) / per-`:placement`
1025 /// [`crate::Placement::estrategia`] (bafa004) `Copy`-return
1026 /// `pub const fn` scalar accessors on the sibling M3 surface. Every
1027 /// downstream substrate-side `const`-context consumer of the
1028 /// per-`:children` restart-decision-policy scalar (a future
1029 /// module-scope `const _:() = assert!(matches!(child.restart(),
1030 /// RestartPolicy::Permanent))` invariant pin on a typed fixture, a
1031 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
1032 /// admission-webhook `const fn` per-child restart-decision floor
1033 /// over a typed [`ChildSpec`], any future `const fn` supervisor-tree
1034 /// composer over the substrate primitive that fans on the per-child
1035 /// restart-decision policy at compile time) now reaches through the
1036 /// same typed dispatch on the substrate primitive at const-eval
1037 /// time as at runtime. A future non-`Copy`-return promotion of the
1038 /// scalar (an `Option<RestartPolicy>`-shape migration on the
1039 /// per-child restart-decision axis once heterogeneous per-cluster
1040 /// restart-policy overlays land, a per-tenant restart-policy-alias
1041 /// table the M4 CR materializer resolves per-CR) that would drop
1042 /// the `const` qualifier fails the fail-before-pass-after pin
1043 /// [`tests::child_spec_restart_accessor_is_const_fn`] at caixa-core
1044 /// build time rather than surfacing as a downstream consumer
1045 /// regression.
1046 #[must_use]
1047 pub const fn restart(&self) -> RestartPolicy {
1048 self.restart
1049 }
1050}
1051
1052/// Supervisor-typed slots that live alongside the standard Caixa
1053/// fields when `:kind Supervisor`. Held flat in [`crate::Caixa`] so
1054/// the manifest stays a single typed form; this struct exists for
1055/// validation + conversion.
1056#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
1057#[serde(rename_all = "camelCase")]
1058pub struct SupervisorSpec {
1059 /// Restart strategy. Defaults to [`RestartStrategy::OneForOne`].
1060 #[serde(default)]
1061 pub estrategia: RestartStrategy,
1062
1063 /// Max restarts within [`Self::restart_window`] before the
1064 /// supervisor itself terminates (and its parent supervisor decides
1065 /// what to do). Default 5.
1066 #[serde(default = "default_max_restarts")]
1067 pub max_restarts: u32,
1068
1069 /// Sliding window for `max_restarts`. Authored as a duration
1070 /// string (`"60s"`, `"5m"`); absent = "never reset". A `Some(0s)`
1071 /// is rejected by [`Self::validate`] — Erlang/OTP's
1072 /// `MaxIntensity / Period` invariant requires a positive window
1073 /// (a zero-period supervisor either trips on the first failure or
1074 /// never trips, depending on operator interpretation, neither of
1075 /// which is the author's intent). Omit the slot to express "no
1076 /// reset"; carry a positive duration to express the sliding window.
1077 #[serde(
1078 default,
1079 skip_serializing_if = "Option::is_none",
1080 with = "duration_codec"
1081 )]
1082 pub restart_window: Option<Duration>,
1083
1084 /// Static children. Empty for `SimpleOneForOne` (children added
1085 /// dynamically); required for the other three strategies.
1086 #[serde(default)]
1087 pub children: Vec<ChildSpec>,
1088}
1089
1090const fn default_max_restarts() -> u32 {
1091 // Route the private serde-`#[serde(default = "…")]` helper through
1092 // the substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] typed
1093 // `pub const` rather than the raw `5` literal — one source of truth
1094 // for the Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
1095 // default across the two production consumers that currently
1096 // dispatch on it (this helper via `#[serde(default = "…")]` on
1097 // `SupervisorSpec::max_restarts` and the [`Default for SupervisorSpec`]
1098 // impl at line 962). Pinned by
1099 // `default_max_restarts_helper_routes_through_lifted_default` +
1100 // `supervisor_spec_default_max_restarts_routes_through_lifted_default`
1101 // in the tests module; peer of the sibling caixa-core
1102 // [`crate::manifest::Caixa::supervisor_view`] `unwrap_or(…)` fold
1103 // that now routes its author-omitted `:max-restarts` arm through
1104 // the same lifted constant.
1105 SUPERVISOR_MAX_RESTARTS_DEFAULT
1106}
1107
1108/// Substrate-canonical Erlang/OTP-shaped `MaxIntensity` restart-budget-
1109/// count default for the `:supervisor :max-restarts` axis — the
1110/// canonical `{intensity, 5, 60}` `MaxIntensity` half of Learn You Some
1111/// Erlang's worker-supervisor default, extracted as a typed `pub const`
1112/// so every substrate-side consumer that resolves "what
1113/// [`SupervisorSpec::max_restarts`] value does an author-omitted
1114/// `:max-restarts` slot degrade onto?" reaches for exactly one
1115/// substrate-primitive `u32`.
1116///
1117/// The `:max-restarts` default axis has two production consumers on the
1118/// substrate side today (both prior to this lift folded onto raw `5`
1119/// literals with no compile-time link back to a shared truth): the
1120/// serde-`#[serde(default = "default_max_restarts")]` helper on
1121/// [`SupervisorSpec::max_restarts`] that every author-omitted
1122/// `:supervisor :max-restarts` slot lands in past the derive-macro's
1123/// wire-format compose, and the [`crate::manifest::Caixa::supervisor_view`]
1124/// `.max_restarts().unwrap_or(5)` fold that every downstream consumer of
1125/// the composed [`SupervisorSpec`] altitude reaches through
1126/// (`feira app graph`, the future wasm-operator's per-supervisor
1127/// restart-intensity counter, the future M4
1128/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
1129/// webhook, the caixa-operator's hierarchical reconciliation scheduler).
1130/// A pair of open-coded `5`s across two files that expressed no
1131/// compile-time link back to the shared OTP-canonical default — a
1132/// future rebrand of the default (a tightening to Elixir's
1133/// `Supervisor.max_restarts: 3`, a widening to a per-cluster overlay
1134/// the operator pins through a future
1135/// `:supervisor :max-restarts-overrides` slot the MESH-COMPOSITION
1136/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
1137/// plain `u32` count to a richer `{MaxR, MaxT}` per-child-cohort
1138/// restart-budget-partition once the INSPIRATIONS §II.2 Erlang/OTP
1139/// per-child-cohort roadmap lands) would have had to be threaded
1140/// through both open-coded copies in lockstep or the wire-format
1141/// author-omitted arm and the view-construction author-omitted arm
1142/// would silently disagree on which restart-budget an omitted
1143/// `:max-restarts` resolves to (an author writing `:supervisor
1144/// (:max-restarts ())` would round-trip through serde with the new
1145/// default while `supervisor_view` silently continued to compose the
1146/// stale `5`, or vice versa), a two-consumer split at the composition
1147/// boundary far from the source `caixa.lisp` with no field naming the
1148/// default-drift root cause. Lifting the resolution rule to a typed
1149/// `pub const` on the substrate primitive means every downstream
1150/// consumer of the per-Supervisor default-restart-budget-count surface
1151/// reaches for exactly one substrate-primitive `u32` — the resolver's
1152/// accepted value migrates as a unit on any future axis change.
1153///
1154/// The `5` value pins Learn You Some Erlang's `{intensity, 5, 60}`
1155/// worker-supervisor default (the closest canonical OTP-shape
1156/// production reference the substrate carries, matching the sibling
1157/// `60s` `Period` default the [`Default for SupervisorSpec`] impl pairs
1158/// this constant with on the paired sliding-window axis). Two orders of
1159/// magnitude below the [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` ceiling
1160/// (the upper bracket on the same axis, sibling of this lower default;
1161/// both are typed `u32` const bounds on the `:supervisor :max-restarts`
1162/// axis and now share one accessor discipline on the substrate) and
1163/// above the OTP-`supervisor` callback-module `MaxR = 1` minimum-
1164/// restart floor — the "one restart, then escalate" default is
1165/// deliberately loose enough to absorb a short burst of transient
1166/// child failures without escalating past the supervisor's parent
1167/// while remaining tight enough to trip the `MaxIntensity / Period`
1168/// ratio's escalation on a genuinely-stuck child within the sibling
1169/// `60s` sliding window.
1170///
1171/// Lifted as a typed `pub const` so the bound has exactly one source
1172/// of truth — the serde-side wire-format author-omitted arm at
1173/// [`default_max_restarts`], the [`Default for SupervisorSpec`] impl's
1174/// struct-literal default field, and the caixa-core
1175/// [`crate::manifest::Caixa::supervisor_view`] fold's author-omitted
1176/// arm all read from one place. Same shape every other typed default
1177/// in this crate carries (the sibling
1178/// [`SUPERVISOR_MAX_RESTARTS_MAX`] upper cap on the same axis, the
1179/// paired [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the
1180/// sibling `:restart-window` axis, and the peer
1181/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
1182/// per-renderer defaults on the caixa-flux / caixa-helm rendering
1183/// axes).
1184pub const SUPERVISOR_MAX_RESTARTS_DEFAULT: u32 = 5;
1185
1186/// Upper-bound ceiling on the `:supervisor :max-restarts` axis — every
1187/// validated [`SupervisorSpec::max_restarts`] past
1188/// [`SupervisorSpec::validate`] lies in `1..=SUPERVISOR_MAX_RESTARTS_MAX`.
1189///
1190/// The typed field is `u32` (the zero-floor arm
1191/// [`SupervisorError::ZeroMaxRestarts`] already brackets the bottom edge),
1192/// so a programmatic struct literal
1193/// (`SupervisorSpec { max_restarts: u32::MAX, .. }`) and the equivalent
1194/// author-surface form (`:max-restarts 4294967295` or any
1195/// `:max-restarts 100000`-shape typo landing in the slot) both round-trip
1196/// cleanly through serde — a structurally unbounded `u32` ceiling. The
1197/// runtime substrate consuming the value (Erlang/OTP's
1198/// `MaxIntensity / Period` ratio, the future wasm-operator's
1199/// per-supervisor restart-intensity counter, the M4
1200/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook)
1201/// then turned a typed `:max-restarts` policy into a no-op supervisor: the
1202/// escalation threshold is structurally so high that no realistic
1203/// restarts-per-`:restart-window` traffic shape can reach it, the
1204/// supervisor never escalates to its parent, and a bad child can loop
1205/// inside the window indefinitely with the parent supervisor structurally
1206/// never receiving the "this subtree has exceeded its restart budget"
1207/// signal the typed slot is meant to express — the canonical
1208/// "supervisor intensity declared, no escalation" footgun, exactly the
1209/// peer of the [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap
1210/// on the `:politicas :circuit-breaker :max-failures` axis (both are
1211/// "trip the next-higher protection layer after N events in a rolling
1212/// window" counters with identical degenerate-at-the-high-end shape).
1213///
1214/// The `1000` ceiling matches the sibling
1215/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] (the closest
1216/// peer — same "events-per-window trip threshold" semantics, same `u32`
1217/// type, same no-op-at-the-high-end failure mode) so the M4
1218/// `mesh.pleme.io/v1alpha1/Supervisor` / `.../Aplicacao` CR materializers
1219/// and the future wasm-operator's per-supervisor restart-intensity
1220/// counter reach for either field knowing the value is in `1..=1000`
1221/// without re-validating at the reconciler layer. The cap sits two
1222/// orders of magnitude above every documented Erlang/OTP production
1223/// playbook recommendation (Learn You Some Erlang's
1224/// `{intensity, 5, 60}` worker-supervisor default, Elixir's `Supervisor`
1225/// `max_restarts: 3` default, OTP's `supervisor` callback module
1226/// `MaxR = 1` / `MaxT = 5` "minimal-restart" default, Riak Core's
1227/// typical `MaxR ∈ 5..=100`, RabbitMQ's broker-supervisor `MaxR = 5`
1228/// default) and below the clearly-pathological "effectively no
1229/// escalation" floor (`10_000`, `100_000`, `u32::MAX`): a value the
1230/// author can plausibly want at hyperscale (a long-running supervisor
1231/// over a very-flaky pool tolerating thousands of transient restarts
1232/// before escalating), but a hard wall above which the typed policy is
1233/// structurally a no-op carried verbatim on every emitted child-restart
1234/// reconciliation contract.
1235///
1236/// Lifted as a typed `pub const` so the bound has exactly one source of
1237/// truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
1238/// materializer's admission webhook and the wasm-operator-side
1239/// per-supervisor restart-intensity reconciler read from one place. Same
1240/// shape every other typed upper bound in this crate carries
1241/// ([`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
1242/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
1243/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
1244/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
1245/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
1246/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
1247pub const SUPERVISOR_MAX_RESTARTS_MAX: u32 = 1000;
1248
1249/// Upper-bound ceiling on the `:supervisor :restart-window` axis —
1250/// every validated `Some(`[`SupervisorSpec::restart_window`]`)` past
1251/// [`SupervisorSpec::validate`] lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
1252/// (inclusive on both ends, integer-millisecond magnitudes by the
1253/// canonical-form gate immediately preceding).
1254///
1255/// The typed field is `Option<Duration>` (the zero-floor arm
1256/// [`SupervisorError::RestartWindowZero`] already rejects
1257/// `Some(Duration::ZERO)`, and the canonical-form arm
1258/// [`SupervisorError::RestartWindowNotCanonical`] already rejects
1259/// sub-millisecond residue), so a programmatic struct literal
1260/// (`SupervisorSpec { restart_window: Some(Duration::from_secs(86_400)),
1261/// .. }` — 24h) and the equivalent author-surface form
1262/// (`(:supervisor (:restart-window "24h"))` — the shared duration codec
1263/// emits `"<n>h"` for any integer-hour magnitude) both round-trip
1264/// cleanly through serde — a structurally unbounded `Duration` ceiling.
1265/// A `:restart-window` value far above the documented Erlang/OTP
1266/// `MaxIntensity / Period` production-playbook band (Learn You Some
1267/// Erlang's `{intensity, 5, 60}` worker-supervisor `Period = 60s`
1268/// default, Elixir's `Supervisor` `max_seconds: 5` default, OTP's
1269/// `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's
1270/// `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default)
1271/// degenerates the supervisor's restart-intensity counter into a
1272/// lifetime counter: the rolling failure-counting window is structurally
1273/// so long that transient restarts are never forgotten, so the
1274/// `MaxIntensity / Period` ratio degenerates from "trip the parent
1275/// supervisor when the child has exceeded its restart budget *within
1276/// the recent window*" to "trip the parent when the child has exceeded
1277/// its restart budget *over its lifetime*" — every transient restart
1278/// counts against the budget forever, the supervisor's reset semantic
1279/// never reaches the child, and the typed `:restart-window` slot
1280/// becomes a no-op rolling window carried on every emitted hierarchical
1281/// reconciliation contract. The canonical
1282/// rolling-window-degenerates-to-lifetime-counter footgun the sibling
1283/// [`crate::POLICY_BREAKER_WINDOW_MAX`] cap closes on the peer
1284/// `:politicas :circuit-breaker :window` axis with identical shape (both
1285/// are "rolling failure-counting window with a per-`Period` reset" Duration
1286/// axes whose lifetime-counter degenerate at the high end is the same
1287/// "the reset semantic never fires" CSE invariant violation).
1288///
1289/// The `1h` (3600s = `3_600_000` ms) ceiling matches the largest unit
1290/// the shared duration codec emits (`"<n>h"` for any integer-hour
1291/// magnitude) — every value in the canonical authoring form's
1292/// `<integer><unit>` grammar at or below this cap renders to a clean
1293/// canonical string — and matches the three sibling typed-`Duration`
1294/// caps already lifted to this surface
1295/// ([`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
1296/// [`crate::POLICY_BREAKER_WINDOW_MAX`]). All four typed-`Duration`
1297/// axes — per-process `:limits :wall-clock`, per-edge `:politicas
1298/// :timeout`, per-breaker `:politicas :circuit-breaker :window`, and
1299/// per-supervisor `:supervisor :restart-window` — now share a single
1300/// uniform top edge at the codec's largest emitted unit so the next
1301/// typed-slot wiring (the future wasm-operator's per-supervisor
1302/// `MaxIntensity / Period` reconciler, the M4
1303/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
1304/// webhook, the `caixa-operator`'s hierarchical reconciliation
1305/// scheduler) reaches for any of the four knowing the value is in
1306/// `1ms..=1h` without re-validating at the renderer layer. The cap sits
1307/// two orders of magnitude above every documented Erlang/OTP / Elixir /
1308/// Riak Core / RabbitMQ production-playbook recommendation band
1309/// (`5s..=300s`) and below the clearly-pathological "rolling window
1310/// degenerates to lifetime counter" floor (`24h`, `7d`, `Duration::MAX`):
1311/// a value the author can plausibly want for a very-low-traffic
1312/// long-tail failure-restart window over a hyperscale-flaky child pool,
1313/// but a hard wall above which the rolling-window contract is
1314/// structurally a lifetime-counter contract.
1315///
1316/// Lifted as a typed `pub const` so the bound has exactly one source
1317/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
1318/// materializer's admission webhook, the wasm-operator-side
1319/// per-supervisor `MaxIntensity / Period` reconciler, and the
1320/// `caixa-operator`'s hierarchical reconciliation scheduler all read
1321/// from one place. Same shape every other typed upper bound in this
1322/// crate carries ([`SUPERVISOR_MAX_RESTARTS_MAX`],
1323/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
1324/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
1325/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
1326/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
1327/// [`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
1328/// [`crate::POLICY_BREAKER_WINDOW_MAX`],
1329/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
1330/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
1331pub const SUPERVISOR_RESTART_WINDOW_MAX: Duration = Duration::from_secs(3600);
1332
1333/// Substrate-canonical Erlang/OTP-shaped `Period` sliding-window-duration
1334/// default for the `:supervisor :restart-window` axis — the canonical
1335/// `{intensity, 5, 60}` `Period` half of Learn You Some Erlang's
1336/// worker-supervisor default, extracted as a typed `pub const` so every
1337/// substrate-side consumer that resolves "what
1338/// [`SupervisorSpec::restart_window`] value does an author-omitted
1339/// `:restart-window` slot degrade onto?" reaches for exactly one
1340/// substrate-primitive [`Duration`].
1341///
1342/// The `:restart-window` default axis has one production consumer on the
1343/// substrate side today: the [`Default for SupervisorSpec`] impl's
1344/// struct-literal `restart_window` field, which prior to this lift folded
1345/// onto a raw `Duration::from_secs(60)` literal with no compile-time link
1346/// back to the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity`
1347/// half of the same `{intensity, 5, 60}` OTP-canonical default. The
1348/// [`crate::manifest::Caixa::supervisor_view`] fold deliberately does
1349/// *not* fall back to this default on the sibling `:restart-window` axis
1350/// — an author-omitted `:supervisor :restart-window` composes to
1351/// `restart_window: None` (the shared codec's soft-swallow shape),
1352/// keeping author-declared intent ("no reset — never escalate on rolling
1353/// window") distinct from the [`Default for SupervisorSpec`] "canonical
1354/// 60s Period" arm every programmatic `SupervisorSpec::default()` caller
1355/// resolves to. Prior to this lift the paired `{intensity, 5, 60}` OTP
1356/// default was split across two files with no compile-time link between
1357/// the halves: [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] pinned the
1358/// `MaxIntensity` half at the substrate primitive while the `Period`
1359/// half rode as an open-coded literal at the composition site, so a
1360/// future coherent rebrand of the paired canonical (a tightening to
1361/// Elixir's `{max_restarts: 3, max_seconds: 5}`, a widening to a
1362/// per-cluster overlay the operator pins through a future
1363/// `:supervisor :restart-window-overrides` slot the MESH-COMPOSITION
1364/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
1365/// paired constants to a per-child-cohort `{MaxR, MaxT}` restart-budget-
1366/// partition once the INSPIRATIONS §II.2 Erlang/OTP per-child-cohort
1367/// roadmap lands) would have had to migrate the `MaxIntensity` half
1368/// through the lifted constant and the `Period` half through a raw
1369/// literal in lockstep or the two halves of the same OTP-canonical
1370/// default would silently drift out of pairing. Lifting the resolution
1371/// rule to a typed `pub const` on the substrate primitive means the
1372/// paired OTP-canonical default migrates as one unit on any future
1373/// axis change.
1374///
1375/// The `60s` value pins Learn You Some Erlang's `{intensity, 5, 60}`
1376/// worker-supervisor default (the closest canonical OTP-shape
1377/// production reference the substrate carries, matching the paired
1378/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5` `MaxIntensity` half this
1379/// constant is the `Period` denominator of on the same
1380/// `MaxIntensity / Period` restart-intensity ratio). Two orders of
1381/// magnitude below the [`SUPERVISOR_RESTART_WINDOW_MAX`] `3600s`
1382/// (`1h`) ceiling (the upper bracket on the same axis, sibling of
1383/// this lower default; both are typed [`Duration`] const bounds on the
1384/// `:supervisor :restart-window` axis and now share one accessor
1385/// discipline on the substrate) and above the OTP-`supervisor`
1386/// callback-module `MaxT = 5` seconds "minimal-window" floor — the "60s
1387/// rolling window" default is deliberately loose enough to absorb a
1388/// short burst of transient child failures without escalating past the
1389/// supervisor's parent while remaining tight enough for the paired
1390/// `MaxIntensity / Period` ratio's escalation to trip on a genuinely-
1391/// stuck child within a human-scale observation window.
1392///
1393/// Lifted as a typed `pub const` so the paired OTP-canonical default has
1394/// exactly one source of truth on each half — the sibling
1395/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half and this
1396/// `Period` `60s` half now share the same substrate-primitive lift
1397/// discipline. Same shape every other typed default in this crate
1398/// carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] paired
1399/// `MaxIntensity` half on the same OTP-canonical `{intensity, 5, 60}`,
1400/// the sibling [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the same
1401/// axis, and the peer [`crate::render::DEFAULT_NAMESPACE`] /
1402/// [`crate::render::DEFAULT_LIBRARY_NAME`] per-renderer defaults on the
1403/// caixa-flux / caixa-helm rendering axes).
1404pub const SUPERVISOR_RESTART_WINDOW_DEFAULT: Duration = Duration::from_secs(60);
1405
1406/// Substrate-canonical Erlang/OTP-shaped sibling-restart-strategy default
1407/// for the `:supervisor :estrategia` axis — the canonical `one_for_one`
1408/// half of Learn You Some Erlang's `{one_for_one, intensity, 5, 60}`
1409/// worker-supervisor default, extracted as a typed `pub const` so every
1410/// substrate-side consumer that resolves "what
1411/// [`SupervisorSpec::estrategia`] variant does an author-omitted
1412/// `:estrategia` slot degrade onto?" reaches for exactly one substrate-
1413/// primitive [`RestartStrategy`].
1414///
1415/// The `:estrategia` default axis has three production consumers on the
1416/// substrate side today: the [`Default for RestartStrategy`] impl's
1417/// return arm, the [`Default for SupervisorSpec`] impl's struct-literal
1418/// `estrategia` field, and the
1419/// [`crate::manifest::Caixa::supervisor_view`] fold's
1420/// `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)` `Option<RestartStrategy>`
1421/// collapse arm — three entry points onto the same OTP-canonical
1422/// `one_for_one` value that prior to this lift folded onto a raw
1423/// `Self::OneForOne` arm at the [`Default for RestartStrategy`] impl and
1424/// implicit `RestartStrategy::default()` routes at the sibling consumers,
1425/// with no compile-time link back to the paired
1426/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` half + the paired
1427/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` half of the same
1428/// `{one_for_one, intensity, 5, 60}` OTP-canonical default. The paired
1429/// triple was split across three altitudes with no compile-time link
1430/// between the halves: the `MaxIntensity` half rode through the lifted
1431/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant (b698ec0) and the `Period`
1432/// half rode through the lifted [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
1433/// constant (f7dcd0e) while the `one_for_one` half rode as an open-coded
1434/// discriminator at the [`Default for RestartStrategy`] impl, so a future
1435/// coherent rebrand of the triple (Elixir's `{:one_for_one,
1436/// max_restarts: 3, max_seconds: 5}` — same strategy, different
1437/// intensity/period; an OTP `rest_for_one` widening once the substrate
1438/// discovers startup-order-coupled child cohorts as the more common
1439/// worker-supervisor default; a per-cluster overlay the operator pins
1440/// through a future `:estrategia-overrides` slot the MESH-COMPOSITION
1441/// §III.2 supervision-canary roadmap acknowledges) would have had to
1442/// migrate the `MaxIntensity` + `Period` halves through the lifted
1443/// constants and the `one_for_one` half through an open-coded arm in
1444/// lockstep or the three halves of the same OTP-canonical default would
1445/// silently drift out of pairing. Lifting the resolution rule to a typed
1446/// `pub const` on the substrate primitive means the paired OTP-canonical
1447/// worker-supervisor default migrates as one unit on any future axis
1448/// change.
1449///
1450/// The [`RestartStrategy::OneForOne`] value pins Learn You Some Erlang's
1451/// `{one_for_one, intensity, 5, 60}` worker-supervisor default (the
1452/// closest canonical OTP-shape production reference the substrate
1453/// carries, matching the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5`
1454/// `MaxIntensity` half and the paired [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
1455/// `60s` `Period` half). The `one_for_one` strategy — restart only the
1456/// failed child, leaving siblings untouched — is the default for tree-of-
1457/// independent-workers use cases the substrate's [`RestartStrategy`]
1458/// discriminator's own docstring already carries as the default arm; it
1459/// composes with the `{5, 60}` restart-intensity ratio to name the same
1460/// substrate-canonical "canonical worker-supervisor" shape the paired
1461/// halves close on their respective axes.
1462///
1463/// Lifted as a typed `pub const` so the paired OTP-canonical default has
1464/// exactly one source of truth on each of its three halves — the sibling
1465/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half, the
1466/// sibling [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` `60s` half, and
1467/// this `one_for_one` strategy half now share the same substrate-
1468/// primitive lift discipline. Same shape every other typed default in
1469/// this crate carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] +
1470/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] paired halves on the same OTP-
1471/// canonical `{one_for_one, intensity, 5, 60}`, the sibling
1472/// [`SUPERVISOR_MAX_RESTARTS_MAX`] + [`SUPERVISOR_RESTART_WINDOW_MAX`]
1473/// upper caps on the paired sibling axes, and the peer
1474/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
1475/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes).
1476pub const SUPERVISOR_ESTRATEGIA_DEFAULT: RestartStrategy = RestartStrategy::OneForOne;
1477
1478/// Substrate-canonical Erlang/OTP-shaped per-child restart-decision-policy
1479/// default for the `:children :restart` axis — the OTP `permanent`
1480/// worker-child default (`{ChildId, StartFunc, permanent, …}` in a
1481/// `supervisor`'s `init/1` child-spec tuple), extracted as a typed
1482/// `pub const` so every substrate-side consumer that resolves "what
1483/// [`ChildSpec::restart`] variant does an author-omitted `:children
1484/// :restart` slot degrade onto?" reaches for exactly one substrate-
1485/// primitive [`RestartPolicy`].
1486///
1487/// Completes the OTP-shape supervisor-tree default set at the substrate
1488/// primitive. The per-`:supervisor` axis already carries all three of its
1489/// halves as lifted typed constants — [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
1490/// (`one_for_one`, 95ffacc), [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
1491/// (`MaxIntensity` `5`, b698ec0), [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
1492/// (`Period` `60s`, f7dcd0e) — while the per-`:children` axis's own
1493/// OTP-canonical default rode as an open-coded `Self::Permanent` arm in
1494/// the [`Default for RestartPolicy`] impl, the last un-lifted default on
1495/// the M2 `:supervisor` slot family. The split mattered because the two
1496/// axes resolve *together* on every author-omitted supervisor: a
1497/// `(defcaixa :kind Supervisor :children ((:caixa "worker" :versao
1498/// "^0.1")))` with no `:estrategia` and no per-child `:restart` degrades
1499/// onto `{one_for_one, 5, 60}` through three lifted constants and onto
1500/// `permanent` through an open-coded enum arm, so a future coherent
1501/// rebrand of the OTP-shape default set (an Elixir-shaped
1502/// `{:one_for_one, max_restarts: 3, max_seconds: 5}` tightening, a
1503/// per-cluster overlay the operator pins through the MESH-COMPOSITION
1504/// §III.2 supervision-canary roadmap slots, an OTP-`transient` widening
1505/// once the substrate discovers clean-completion-aware children as the
1506/// more common child shape) would have had to migrate three halves
1507/// through typed constants and the fourth through a raw enum arm in
1508/// lockstep or the supervisor-level and child-level defaults would
1509/// silently drift apart.
1510///
1511/// The `:children :restart` default axis has two production consumers on
1512/// the substrate side today: the [`Default for RestartPolicy`] impl's
1513/// return arm, and the serde-side `#[serde(default)]` on
1514/// [`ChildSpec::restart`] that resolves an author-omitted `:children
1515/// :restart` slot through that same impl. Both now key off this one
1516/// substrate primitive, so the future wasm-operator's per-child post-exit
1517/// restart-decision branch, the future M4
1518/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1519/// admission webhook, and the `caixa-operator`'s hierarchical
1520/// reconciliation scheduler's per-child fan-out all reach for one typed
1521/// identifier when they resolve an omitted per-child restart posture.
1522///
1523/// The [`RestartPolicy::Permanent`] value pins Erlang/OTP's `permanent`
1524/// worker-child restart type — always restart the child regardless of how
1525/// it died, the canonical posture for long-running services that must
1526/// always be up, matching the sibling [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
1527/// `one_for_one` tree-of-independent-workers strategy this constant pairs
1528/// with under the same `{one_for_one, intensity, 5, 60}` worker-supervisor
1529/// shape. The two alternatives the closed [`RestartPolicy::ALL`] accept-set
1530/// carries ([`RestartPolicy::Transient`] — restart only on abnormal exit;
1531/// [`RestartPolicy::Temporary`] — never restart) express deliberate
1532/// one-shot / clean-completion-aware postures an author declares
1533/// explicitly, never a posture an omitted slot should silently assume.
1534pub const SUPERVISOR_CHILD_RESTART_DEFAULT: RestartPolicy = RestartPolicy::Permanent;
1535
1536/// Route the manually-authored [`Default`] impl on [`SupervisorSpec`]
1537/// through the substrate-canonical [`SupervisorSpec::otp_canonical`]
1538/// `pub const fn` constructor rather than a struct-literal cascade over
1539/// the paired [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
1540/// [`default_max_restarts`] / [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
1541/// lifted consts — one source of truth for the Erlang/OTP-canonical
1542/// `{one_for_one, 5, 60}` worker-supervisor baseline across the two
1543/// paths every downstream consumer already reaches through (the
1544/// hand-authored-until-now [`Default::default`] the
1545/// `..SupervisorSpec::default()` struct-update-syntax on every
1546/// one-axis-under-test fixture in this crate's test module rests on,
1547/// and the `pub const fn` [`SupervisorSpec::otp_canonical`] constructor
1548/// every `const`-context consumer reaches through).
1549///
1550/// Extends the [`Default`]-through-const-ctor fold discipline the
1551/// [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
1552/// (abd52c2), [`crate::aplicacao::MeshPolicy`]
1553/// [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`] (91641a4),
1554/// and [`crate::BehaviorSpec`]
1555/// [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c) folds
1556/// closed on the M2 / M3 `Option`-only "canonical unset baseline"
1557/// typed-slot spec family — extended here onto the M2 supervisor-slot
1558/// [`SupervisorSpec`] whose canonical baseline is not "everything
1559/// `None`" but the OTP-canonical `{one_for_one, 5, 60}` worker-
1560/// supervisor triple. The `empty()` peer's naming did not fit
1561/// (`SupervisorSpec` carries a discriminator-shaped `estrategia` field
1562/// and a non-zero `max_restarts`/`restart_window` pair whose canonical
1563/// shape is Erlang/OTP-descended, not the "no axis declared" bottom
1564/// the sibling `Option`-only slots fold to), so this peer is named
1565/// [`SupervisorSpec::otp_canonical`] instead — the same phrasing the
1566/// existing per-arm pin tests
1567/// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`] /
1568/// [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`] /
1569/// [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
1570/// already reach for. Pinned load-bearing by
1571/// [`tests::supervisor_spec_default_routes_through_otp_canonical_ctor`]
1572/// (byte-parity pin against [`SupervisorSpec::otp_canonical`] under
1573/// [`PartialEq`], sharpening the sibling
1574/// `supervisor_spec_default_*_routes_through_lifted_default` per-arm
1575/// pins from a per-field lift into a whole-struct one-source-of-truth
1576/// pin — the derived-until-now [`Default::default`] and the
1577/// [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
1578/// construction, not by coincidence).
1579impl Default for SupervisorSpec {
1580 #[inline]
1581 fn default() -> Self {
1582 Self::otp_canonical()
1583 }
1584}
1585
1586impl SupervisorSpec {
1587 /// `const`-context peer of the [`Default for SupervisorSpec`]
1588 /// impl (which routes through this constructor) — returns the
1589 /// Erlang/OTP-canonical `{one_for_one, 5, 60}` worker-supervisor
1590 /// baseline this crate reaches for in every fixture-builder
1591 /// `..SupervisorSpec::default()` struct-update expression and
1592 /// every downstream `SupervisorSpec::default()` seed.
1593 ///
1594 /// Each field routes through the same substrate-canonical
1595 /// [`SUPERVISOR_ESTRATEGIA_DEFAULT`] / [`default_max_restarts`] /
1596 /// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] lifted consts the
1597 /// per-arm pin tests
1598 /// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`]
1599 /// / [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`]
1600 /// / [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
1601 /// already assert, so a future coherent rebrand of the OTP-canonical
1602 /// triple (Elixir's `{max_restarts: 3, max_seconds: 5}`, a per-
1603 /// cluster overlay via a future `:restart-window-overrides` slot, a
1604 /// per-child-cohort promotion the INSPIRATIONS.md §II.2 Erlang/OTP
1605 /// absorption roadmap acknowledges) migrates through three typed
1606 /// constants in lockstep, and the paired [`Default`] impl inherits
1607 /// every future extension by construction.
1608 ///
1609 /// `pub const fn` rather than the derived-style `Default::default`
1610 /// or a `pub const SUPERVISOR_SPEC_DEFAULT: SupervisorSpec` item —
1611 /// [`Default::default`] is not `const` on stable Rust, and
1612 /// `SupervisorSpec` is non-`Copy` so a `pub const` item would force
1613 /// every consumer through a [`Clone::clone`]. The `pub const fn`
1614 /// discipline lets `const`-context callers construct the OTP-
1615 /// canonical baseline at compile time without runtime dispatch on
1616 /// the derived [`Default::default`], the same posture the sibling
1617 /// [`crate::LimitsSpec::empty`] (9739971) /
1618 /// [`crate::aplicacao::MeshPolicy::empty`] (6df969b) /
1619 /// [`crate::BehaviorSpec::empty`] (f9b18e3) `Option`-only typed-slot
1620 /// spec `pub const fn` constructors carry on the sibling
1621 /// "everything `None`" baseline axis.
1622 ///
1623 /// Fourth peer on the M2 / M3 typed-slot-spec "const-context peer
1624 /// of the derived-style [`Default`]" family — sibling of the
1625 /// [`crate::LimitsSpec::empty`] / [`crate::aplicacao::MeshPolicy::empty`]
1626 /// / [`crate::BehaviorSpec::empty`] `Option`-only "canonical unset
1627 /// baseline" trio, extended here onto the M2 supervisor-slot
1628 /// [`SupervisorSpec`] whose canonical baseline is not "everything
1629 /// `None`" but the Erlang/OTP-canonical `{one_for_one, 5, 60}`
1630 /// worker-supervisor triple. Named [`Self::otp_canonical`] rather
1631 /// than `empty()` to name the actual invariant the return value
1632 /// pins — the same phrasing already used in the per-arm pin tests
1633 /// on this file. Pinned load-bearing by
1634 /// [`tests::supervisor_spec_otp_canonical_byte_equals_default`] and
1635 /// [`tests::supervisor_spec_otp_canonical_is_usable_in_const_context`].
1636 #[must_use]
1637 pub const fn otp_canonical() -> Self {
1638 Self {
1639 estrategia: SUPERVISOR_ESTRATEGIA_DEFAULT,
1640 max_restarts: default_max_restarts(),
1641 restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
1642 children: Vec::new(),
1643 }
1644 }
1645
1646 /// Substrate-canonical per-`:supervisor` `:estrategia` OTP-shaped
1647 /// sibling-restart-strategy scalar accessor every consumer that
1648 /// dispatches on the supervisor's per-sibling restart-decision shape
1649 /// keys off — returns the author-declared `:supervisor :estrategia`
1650 /// variant verbatim as a [`RestartStrategy`], `Copy`-projected from
1651 /// the typed slot's own [`RestartStrategy`] storage.
1652 ///
1653 /// The `:supervisor :estrategia` slot carries the closed-set
1654 /// OTP-shaped sibling-restart-strategy discriminator ([`RestartStrategy::OneForOne`]
1655 /// — restart only the failed child, the Erlang/OTP `one_for_one` default;
1656 /// [`RestartStrategy::OneForAll`] — restart every child on any child
1657 /// failure, the Erlang/OTP `one_for_all` shared-state cohort default;
1658 /// [`RestartStrategy::RestForOne`] — restart the failed child and
1659 /// every child started after it, the Erlang/OTP `rest_for_one`
1660 /// startup-order default; [`RestartStrategy::SimpleOneForOne`] —
1661 /// dynamic children of the same shape, the Erlang/OTP
1662 /// `simple_one_for_one` per-session default) that every downstream
1663 /// consumer of the Supervisor's per-sibling restart-decision fan-out
1664 /// shape keys off. Validated by [`SupervisorSpec::validate`] to be
1665 /// paired coherently with the sibling `:children` axis
1666 /// (`SimpleOneForOne ↔ children.is_empty()` — the cross-slot
1667 /// partition the strategy-arm's [`SupervisorError::SimpleOneForOneWithStaticChildren`]
1668 /// / [`SupervisorError::NoChildren`] refusal cascade pins), and every
1669 /// downstream consumer that reads the strategy keys off this scalar
1670 /// (the [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
1671 /// partition-dispatch `match` arm, the non-`SimpleOneForOne`-arm
1672 /// declared-but-empty [`SupervisorError::NoChildren`] error carrier's
1673 /// `estrategia:` field, the future `feira app graph` per-Supervisor
1674 /// strategy print line, the future wasm-operator's per-supervisor
1675 /// sibling-restart-strategy branch, the future M4
1676 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-strategy
1677 /// admission-webhook resolver, the `caixa-operator`'s hierarchical
1678 /// reconciliation scheduler's per-strategy fan-out).
1679 ///
1680 /// Prior to this lift the `.estrategia` field was accessed inline at
1681 /// two production sites in `caixa-core/src/supervisor.rs` — the
1682 /// [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
1683 /// `match self.estrategia { … }` partition dispatch, and the
1684 /// non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
1685 /// carrier at `estrategia: self.estrategia` — two open-coded
1686 /// field-accesses that expressed no compile-time link back to the
1687 /// typed slot. A future extension of the `:supervisor :estrategia`
1688 /// axis to a richer author surface (a per-cluster strategy override
1689 /// the operator pins through a future `:supervisor :estrategia-overrides`
1690 /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
1691 /// acknowledges, a per-tenant strategy-alias table the M4 CR
1692 /// materializer resolves per-CR, a per-Supervisor dynamic strategy
1693 /// derivation the future adaptive-supervision engine computes from
1694 /// child-failure-history topology, a per-child-cohort strategy split
1695 /// the future `RestForCohort` extension acknowledged by the
1696 /// INSPIRATIONS.md §II.2 Erlang/OTP absorption roadmap acknowledges)
1697 /// would have had to be threaded through every open-coded copy in
1698 /// lockstep — one consumer reading the raw variant while a peer read
1699 /// the operator-resolved variant would silently split the
1700 /// [`SupervisorError::NoChildren`] diagnostic's quoted strategy from
1701 /// the actual partition-dispatch input the empty-children refusal
1702 /// arm reached under, a two-consumer split at the validator far from
1703 /// the source `caixa.lisp` with no field naming the strategy-drift
1704 /// root cause. Lifting the resolution rule to a typed method on the
1705 /// substrate primitive means every downstream consumer of the
1706 /// Supervisor's per-`:supervisor` sibling-restart-strategy surface
1707 /// reaches for exactly one typed dispatch — the resolver's accept-set
1708 /// migrates as a unit on any future axis addition.
1709 ///
1710 /// Peer of the sibling M3 mesh-slot [`crate::Placement::estrategia`]
1711 /// (921fe1b) `Copy`-return `PlacementStrategy` scalar accessor on the
1712 /// per-`:placement` distribution-strategy axis — same "one typed
1713 /// dispatch on the substrate primitive, thin projections at each
1714 /// consumer" discipline extended onto the M2 supervisor-slot
1715 /// per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
1716 /// scalar axis. The two typed axes (`Placement::estrategia` on the
1717 /// M3 Aplicacao side, `SupervisorSpec::estrategia` on the M2
1718 /// Supervisor side) now share one accessor discipline for the shared
1719 /// substrate concept "a `Copy`-projected closed-set enum-arm
1720 /// discriminator that partitions the downstream renderer's per-arm
1721 /// fan-out". First `Copy`-return accessor on the M2 supervisor-slot
1722 /// `SupervisorSpec` type — companion to the sibling per-`:children`
1723 /// [`crate::ChildSpec::nome`] (57c61d0) /
1724 /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
1725 /// scalar accessors on the sibling per-`:children` `String`-carry
1726 /// axes. Named `estrategia()` to match the storage field's name and
1727 /// the peer [`crate::Placement::estrategia`] method-name discipline
1728 /// verbatim; the accessor's identity name maps onto the canonical
1729 /// OTP-shape supervision vocabulary the [`RestartStrategy`] enum's
1730 /// docstring already carries.
1731 ///
1732 /// Declared `pub const fn` to close the M2 supervisor-slot
1733 /// `Copy`-return raw-field-getter `const`-eval-surface pass —
1734 /// sibling of the peer M2 per-`:children` [`ChildSpec::restart`]
1735 /// (converted in this commit) `Copy`-composite-enum accessor, peer
1736 /// of the sibling M2 per-`:supervisor`
1737 /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
1738 /// already lifted, and mirror of the peer M3 mesh-slot
1739 /// per-`:placement` [`crate::Placement::estrategia`] (bafa004)
1740 /// `Copy`-return `pub const fn` scalar accessor whose method-name
1741 /// discipline this accessor was authored to match. Every downstream
1742 /// substrate-side `const`-context consumer of the per-`:supervisor`
1743 /// sibling-restart-strategy scalar (a future module-scope `const
1744 /// _:() = assert!(matches!(sup.estrategia(),
1745 /// RestartStrategy::OneForOne))` invariant pin on a typed fixture,
1746 /// a future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
1747 /// admission-webhook `const fn` per-supervisor strategy-arm floor
1748 /// over a typed [`SupervisorSpec`], any future `const fn`
1749 /// supervisor-tree composer over the substrate primitive that fans
1750 /// on the sibling-restart-strategy at compile time) now reaches
1751 /// through the same typed dispatch on the substrate primitive at
1752 /// const-eval time as at runtime. A future non-`Copy`-return
1753 /// promotion of the scalar (an `Option<RestartStrategy>`-shape
1754 /// migration once the substrate grows per-cluster strategy overlays
1755 /// the [`SupervisorSpec`] docstring already anticipates, a
1756 /// per-tenant strategy-alias table the M4 CR materializer resolves
1757 /// per-CR) that would drop the `const` qualifier fails the
1758 /// fail-before-pass-after pin
1759 /// [`tests::supervisor_spec_estrategia_accessor_is_const_fn`] at
1760 /// caixa-core build time rather than surfacing as a downstream
1761 /// consumer regression.
1762 #[must_use]
1763 pub const fn estrategia(&self) -> RestartStrategy {
1764 self.estrategia
1765 }
1766
1767 /// Substrate-canonical per-`:supervisor` `:max-restarts` OTP-shaped
1768 /// `MaxIntensity` restart-budget scalar accessor every consumer that
1769 /// reads the supervisor's per-`:restart-window` restart-budget count
1770 /// keys off — returns the author-declared `:supervisor :max-restarts`
1771 /// typed `u32` verbatim, `Copy`-projected from the typed slot's own
1772 /// `u32` storage (`u32` is `Copy`, so the accessor returns by value; no
1773 /// borrow of `&self` past the call). Non-optional (the `u32` field
1774 /// carries the restart-budget count as a required axis with a
1775 /// [`default_max_restarts`]-supplied default; the zero-floor arm
1776 /// [`SupervisorError::ZeroMaxRestarts`] and the cap arm
1777 /// [`SupervisorError::MaxRestartsExceedsCap`] jointly bracket the
1778 /// accept-set to `1..=SUPERVISOR_MAX_RESTARTS_MAX`).
1779 ///
1780 /// The `:supervisor :max-restarts` slot carries the Erlang/OTP
1781 /// `MaxIntensity` restart-budget count that pairs with the sibling
1782 /// `:restart-window` `Period` to form the `MaxIntensity / Period`
1783 /// restart-intensity ratio the supervisor trips its own escalation on
1784 /// (`theory/RUNTIME-PATTERNS.md` §II.2, Learn You Some Erlang's
1785 /// `{intensity, 5, 60}` worker-supervisor default). Every downstream
1786 /// consumer of the Supervisor's per-`:supervisor` restart-budget count
1787 /// keys off this scalar (the [`SupervisorSpec::validate`] zero-floor +
1788 /// upper-cap bracket at
1789 /// `require_positive_bounded_u32(self.max_restarts(), …)`, the future
1790 /// wasm-operator's per-supervisor restart-intensity counter's
1791 /// budget-vs-count comparator, the future M4
1792 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
1793 /// webhook, the `caixa-operator`'s hierarchical reconciliation
1794 /// scheduler's per-supervisor escalation-decision branch, every
1795 /// `SupervisorError::MaxRestartsExceedsCap` variant carrying the
1796 /// offending count verbatim for `feira lint` rendering).
1797 ///
1798 /// Prior to this lift the `.max_restarts` field was accessed inline at
1799 /// one production site in `caixa-core/src/supervisor.rs` — the
1800 /// [`SupervisorSpec::validate`] `require_positive_bounded_u32(self
1801 /// .max_restarts, …)` bracket-gate call — one open-coded field-access
1802 /// that expressed no compile-time link back to the typed slot. A
1803 /// future extension of the `:max-restarts` axis to a richer author
1804 /// surface (a per-cluster restart-budget override the operator pins
1805 /// through a future `:supervisor :max-restarts-overrides` slot the
1806 /// MESH-COMPOSITION §III.2 supervision-canary roadmap acknowledges,
1807 /// a per-tenant restart-budget-alias table the M4 CR materializer
1808 /// resolves per-CR, a per-supervisor dynamic restart-budget derivation
1809 /// the future adaptive-supervision engine computes from child-failure-
1810 /// history topology, a promotion of the plain `u32` count to a richer
1811 /// `{MaxR, MaxT}` tuple once Erlang/OTP's per-child-cohort restart-
1812 /// budget-partition slot comes into scope) would have had to be
1813 /// threaded through every open-coded copy in lockstep or the validate
1814 /// gate and the future M4 emit path would silently disagree on which
1815 /// restart-budget count a given supervisor resolves to — an author's
1816 /// `:max-restarts 5` would satisfy validate while the emit path
1817 /// silently read a drifted other value (a `:max-restarts 10000`
1818 /// no-op supervisor at the emit boundary would carry the author's
1819 /// declared `5` verbatim in `feira lint` output while the future
1820 /// wasm-operator's restart-intensity counter operated under the
1821 /// drifted count), a two-consumer split at the validator far from the
1822 /// source `caixa.lisp` with no field naming the restart-budget-drift
1823 /// root cause. Lifting the resolution rule to a typed method on the
1824 /// substrate primitive means every downstream consumer of the
1825 /// Supervisor's per-`:supervisor` restart-budget-count surface reaches
1826 /// for exactly one typed dispatch — the resolver's accept-set migrates
1827 /// as a unit on any future axis addition.
1828 ///
1829 /// Peer of the sibling M3 mesh-slot [`crate::CircuitBreaker::max_failures`]
1830 /// (3a74062) `Copy`-return `u32` sub-struct required-scalar accessor
1831 /// on the per-`:politicas :circuit-breaker :max-failures` Envoy-
1832 /// outlier-detection trip-threshold axis — same "one typed dispatch on
1833 /// the substrate primitive, thin projections at each consumer"
1834 /// discipline extended onto the M2 supervisor-slot per-`:supervisor`
1835 /// restart-budget-count `Copy`-`u32` scalar axis. The two typed axes
1836 /// (`CircuitBreaker::max_failures` on the M3 Aplicacao side,
1837 /// `SupervisorSpec::max_restarts` on the M2 Supervisor side) now share
1838 /// one accessor discipline for the shared substrate concept "a
1839 /// `Copy`-projected required `u32` count that trips the next-higher
1840 /// protection layer after N events in a rolling window" — both are
1841 /// counters with identical degenerate-at-the-high-end shape and share
1842 /// the paired [`crate::POLICY_BREAKER_MAX_FAILURES_MAX`] /
1843 /// [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` cap. Second `Copy`-return
1844 /// accessor on the M2 supervisor-slot `SupervisorSpec` type, sibling
1845 /// to the [`SupervisorSpec::estrategia`] (eafb619) `Copy`-composite-
1846 /// enum `RestartStrategy` accessor. Named `max_restarts()` to match
1847 /// the storage field's name verbatim and the peer
1848 /// [`crate::CircuitBreaker::max_failures`] method-name discipline; the
1849 /// accessor's identity maps onto the canonical OTP-shape supervision
1850 /// vocabulary the [`SupervisorSpec::max_restarts`] field's docstring
1851 /// already carries.
1852 #[must_use]
1853 pub const fn max_restarts(&self) -> u32 {
1854 self.max_restarts
1855 }
1856
1857 /// Substrate-canonical per-`:supervisor` `:restart-window` OTP-shaped
1858 /// `Period` sliding-window scalar accessor every consumer of the
1859 /// supervisor's `MaxIntensity / Period` restart-intensity denominator
1860 /// keys off — returns the author-declared `:supervisor :restart-window`
1861 /// typed [`Duration`] verbatim as an `Option<Duration>`, copied out of
1862 /// the typed slot's own `Option<Duration>` storage (`Duration` is
1863 /// `Copy`, so `Option<Duration>` is `Copy` and the accessor returns by
1864 /// value; no borrow of `&self` past the call). `None` when the slot is
1865 /// absent (the canonical "never reset — every restart across the
1866 /// supervisor's lifetime counts against the sibling `:max-restarts`
1867 /// budget" sentinel the field's own docstring names and the peer
1868 /// `validate_accepts_none_restart_window` pin locks in on the
1869 /// [`SupervisorSpec::validate`] entry-side).
1870 ///
1871 /// The `:supervisor :restart-window` slot carries the Erlang/OTP
1872 /// `Period` sliding-observation-interval that pairs with the sibling
1873 /// `:max-restarts` `MaxIntensity` restart-budget count to form the
1874 /// `MaxIntensity / Period` restart-intensity ratio the supervisor
1875 /// trips its own escalation on (`theory/RUNTIME-PATTERNS.md` §II.2,
1876 /// Learn You Some Erlang's `{intensity, 5, 60}` worker-supervisor
1877 /// default). The typed slot's `Option<Duration>` accept-set —
1878 /// zero-floor rejected through [`SupervisorError::RestartWindowZero`]
1879 /// (Erlang/OTP's `MaxIntensity / Period` invariant requires
1880 /// `Period > 0`; a zero period either trips on the first failure or
1881 /// never trips depending on operator interpretation, neither of which
1882 /// is the author's intent — omit the slot to express "no reset";
1883 /// carry a positive duration to express the sliding window),
1884 /// integer-millisecond canonical form enforced through
1885 /// [`SupervisorError::RestartWindowNotCanonical`] (the duration
1886 /// codec's canonical form emits `"1500ms"` not `"1.5s"` and the
1887 /// future wasm-operator's per-supervisor restart-intensity counter
1888 /// quantizes at milliseconds), upper-bounded by
1889 /// [`SUPERVISOR_RESTART_WINDOW_MAX`] (1h — the coarsest per-
1890 /// supervisor rolling window any operationally-reachable supervisor
1891 /// can honor without spanning multiple scheduler epochs the
1892 /// hierarchical-reconciliation scheduler treats as independent) —
1893 /// maps onto the future wasm-operator (M3) per-supervisor
1894 /// restart-intensity counter's rolling-observation-interval, the
1895 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1896 /// per-`spec.restartWindow` admission webhook, and the sibling
1897 /// `duration_codec`-serialized wire scalar every downstream consumer
1898 /// of the supervisor's per-`:supervisor` restart-intensity denominator
1899 /// keys off.
1900 ///
1901 /// Prior to this lift the `.restart_window` field was accessed inline
1902 /// at one production site in `caixa-core/src/supervisor.rs` — the
1903 /// [`SupervisorSpec::validate`] `if let Some(w) = self.restart_window {
1904 /// … }` zero-floor + canonical-form + upper-cap bracket arm — one
1905 /// open-coded field-access that expressed no compile-time link back to
1906 /// the typed slot. A future extension of the `:restart-window` axis to
1907 /// a richer author surface (a per-cluster restart-window override the
1908 /// operator pins through a future `:supervisor :restart-window-overrides`
1909 /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
1910 /// acknowledges, a per-tenant restart-window-alias table the M4 CR
1911 /// materializer resolves per-CR, a per-supervisor dynamic
1912 /// restart-window derivation the future adaptive-supervision engine
1913 /// computes from child-failure-history topology, a promotion of the
1914 /// plain `Option<Duration>` window to a richer `{observation, cooldown}`
1915 /// pair once Erlang/OTP's per-child-cohort observation-interval-
1916 /// partition slot comes into scope) would have had to be threaded
1917 /// through every open-coded copy in lockstep or the validate gate and
1918 /// the future M4 emit path would silently disagree on which
1919 /// restart-window a given supervisor resolves to — an author's
1920 /// `:restart-window "60s"` would satisfy validate while the emit path
1921 /// silently read a drifted other value (a `Some(Duration::from_secs(60))`
1922 /// authored slot at the emit boundary would carry the author's
1923 /// declared window verbatim in `feira lint` output while the future
1924 /// wasm-operator's restart-intensity counter operated under a
1925 /// drifted window, or vice versa: an author's `:restart-window ()`
1926 /// would carry the "never reset" sentinel through validate while the
1927 /// emit path silently substituted a default sliding window), a
1928 /// two-consumer split at the validator far from the source
1929 /// `caixa.lisp` with no field naming the restart-window-drift root
1930 /// cause. Lifting the resolution rule to a typed method on the
1931 /// substrate primitive means every downstream consumer of the
1932 /// Supervisor's per-`:supervisor` restart-intensity-denominator
1933 /// surface reaches for exactly one typed dispatch — the resolver's
1934 /// accept-set migrates as a unit on any future axis addition.
1935 ///
1936 /// Third `Copy`-return accessor on the M2 supervisor-slot
1937 /// `SupervisorSpec` type, closing the last unlifted per-`:supervisor`
1938 /// scalar-value axis (`children: Vec<ChildSpec>` carries a `Vec`
1939 /// payload rather than a `Copy`-scalar, and the per-`:children`
1940 /// [`crate::ChildSpec::nome`] (57c61d0) /
1941 /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
1942 /// scalar accessors already close the per-element `String`-carry
1943 /// axes). Sibling to the peer M2 [`crate::LimitsSpec::wall_clock`]
1944 /// (8cb717b) `Option<Duration>` accessor on the `:limits` slot's
1945 /// per-outermost-call wall-clock-deadline axis and the peer M3
1946 /// [`crate::MeshPolicy::timeout`] (7073d0f) `Option<Duration>`
1947 /// accessor on the `:politicas` slot's per-call-deadline axis — all
1948 /// three share the shared substrate concept "a `Copy`-projected
1949 /// optional `Duration` that carries a positive integer-millisecond
1950 /// canonical value with a `1ms..=<axis-specific>_MAX` accept-set and
1951 /// the paired zero-floor / non-canonical / above-cap refusal cascade"
1952 /// through the same [`crate::render::require_positive_canonical_bounded_duration`]
1953 /// bracket-helper the three axes each route through. Named
1954 /// `restart_window()` to match the storage field's name verbatim and
1955 /// the peer [`crate::LimitsSpec::wall_clock`] /
1956 /// [`crate::MeshPolicy::timeout`] method-name discipline; the
1957 /// accessor's identity maps onto the canonical OTP-shape supervision
1958 /// vocabulary the [`SupervisorSpec::restart_window`] field's docstring
1959 /// already carries.
1960 #[must_use]
1961 pub const fn restart_window(&self) -> Option<Duration> {
1962 self.restart_window
1963 }
1964
1965 /// Substrate-canonical per-`:supervisor` `:children` OTP-shaped
1966 /// static-child-list slice accessor every consumer that walks the
1967 /// supervisor's declared child set keys off — returns the author-
1968 /// declared `:supervisor :children` `Vec<ChildSpec>` verbatim as a
1969 /// `&[ChildSpec]` slice-view, borrowed from the typed slot's own
1970 /// `Vec<ChildSpec>` storage (a zero-copy slice-view over the same
1971 /// backing buffer the `Serialize`/`Deserialize` derives round-trip
1972 /// through). Non-optional: an empty slice is the load-bearing
1973 /// "author declared `:children ()`" sentinel every consumer of the
1974 /// cross-slot `SimpleOneForOne ↔ children.is_empty()` partition
1975 /// keys off (`SimpleOneForOne` requires the empty slice; the peer
1976 /// three strategies require a non-empty slice — the paired
1977 /// [`SupervisorError::SimpleOneForOneWithStaticChildren`] /
1978 /// [`SupervisorError::NoChildren`] refusal cascade pins the
1979 /// partition on both arms).
1980 ///
1981 /// The `:supervisor :children` slot carries the OTP-shaped static
1982 /// child list the supervisor materializes one ComputeUnit per
1983 /// entry from — the Erlang/OTP `supervisor:init/1`'s
1984 /// `{ok, {SupFlags, ChildSpecs}}` `ChildSpecs` list, projected
1985 /// through the tatara-lisp `:children` author surface onto a typed
1986 /// `Vec<ChildSpec>` whose per-element `(nome(),
1987 /// versao_requirement(), restart)` triple the per-child
1988 /// [`SupervisorSpec::validate`] loop already gates through the
1989 /// lifted [`ChildSpec::nome`] (57c61d0) /
1990 /// [`ChildSpec::versao_requirement`] (2c053c8) scalar accessors.
1991 /// Every downstream consumer that fans on the static child list
1992 /// keys off this slice (the [`SupervisorSpec::validate`]
1993 /// `SimpleOneForOne ↔ non-SimpleOneForOne` partition dispatch's
1994 /// `.is_empty()` probe on both arms, the [`SupervisorSpec::validate`]
1995 /// per-child DNS-1123 / semver-requirement / duplicate-detection
1996 /// fan-out loop, every future wasm-operator (M3) per-supervisor
1997 /// hierarchical-reconciliation scheduler's per-child ComputeUnit
1998 /// materialization loop, the future M4
1999 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2000 /// admission-webhook fan-out, the future `feira app graph`
2001 /// per-supervisor tree-print traversal).
2002 ///
2003 /// Prior to this lift the `.children` `Vec<ChildSpec>` was accessed
2004 /// inline at three production sites in `caixa-core/src/supervisor.rs`
2005 /// — the [`SupervisorSpec::validate`] `SimpleOneForOne`-arm
2006 /// `!self.children.is_empty()` cross-slot refusal probe, the peer
2007 /// non-`SimpleOneForOne`-arm `self.children.is_empty()`
2008 /// [`SupervisorError::NoChildren`] refusal probe, and the per-child
2009 /// validate loop's `for child in &self.children` traversal head —
2010 /// three open-coded field-accesses that expressed no compile-time
2011 /// link back to the typed slot. A future extension of the
2012 /// `:supervisor :children` axis to a richer author surface (a
2013 /// per-cluster child-set overlay the operator pins through a future
2014 /// `:supervisor :children-overrides` slot the MESH-COMPOSITION §III.2
2015 /// supervision-canary roadmap acknowledges, a per-tenant
2016 /// child-set-alias table the M4 CR materializer resolves per-CR,
2017 /// a per-supervisor dynamic-child derivation the future adaptive-
2018 /// supervision engine computes from child-failure-history topology,
2019 /// a promotion of the plain `Vec<ChildSpec>` to a richer
2020 /// `{static, dynamic}` partition once Erlang/OTP's
2021 /// `simple_one_for_one` dynamic-child slot comes into typed scope)
2022 /// would have had to be threaded through all three open-coded copies
2023 /// in lockstep or one consumer would silently disagree with the
2024 /// peers on which child-set a given supervisor resolves to — the
2025 /// `SimpleOneForOne`-arm probe reading the raw slot while the peer
2026 /// non-`SimpleOneForOne`-arm probe read an operator-resolved slot
2027 /// would silently split the partition-dispatch's two-arm coherence
2028 /// (a supervisor that satisfies neither arm's precondition, or that
2029 /// satisfies both, at the cost of the paired
2030 /// `SimpleOneForOneWithStaticChildren`/`NoChildren` refusal cascade
2031 /// silently drifting from the per-child validate loop's actual
2032 /// traversal input), a three-consumer split at the validator far
2033 /// from the source `caixa.lisp` with no field naming the
2034 /// child-set-drift root cause. Lifting the resolution rule to a
2035 /// typed method on the substrate primitive means every downstream
2036 /// consumer of the Supervisor's per-`:supervisor` static-child-list
2037 /// surface reaches for exactly one typed dispatch — the resolver's
2038 /// accept-set migrates as a unit on any future axis addition.
2039 ///
2040 /// First slice-return (`&[T]`) accessor on any M2 or M3 typed slot
2041 /// — the seed for the same "one typed dispatch on the substrate
2042 /// primitive, thin projections at each consumer" discipline the
2043 /// closed [`crate::LimitsSpec`] / [`BehaviorSpec`] /
2044 /// [`crate::UpgradeFromEntry`] scalar-accessor families each carry
2045 /// on their `Copy` / `Option<Copy>` / `Option<&str>` axes, extended
2046 /// onto the first `Vec`-carry axis on the substrate. The four peer
2047 /// `Vec`-carry axes still unlifted at the time of this seed —
2048 /// [`crate::Placement::clusters`] (`Vec<String>` per-cluster
2049 /// distribution-target list), [`crate::AplicacaoSpec::membros`]
2050 /// (`Vec<Membro>` per-Aplicacao member list),
2051 /// [`crate::AplicacaoSpec::contratos`] (`Vec<WitContract>`
2052 /// per-Aplicacao WIT-typed edge list),
2053 /// [`crate::UpgradeFromEntry::instructions`]
2054 /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
2055 /// — inherit this accessor's discipline as future compounding runs
2056 /// migrate their consumers onto the shared slice-return shape.
2057 /// Fourth (and final) accessor on the M2 supervisor-slot
2058 /// `SupervisorSpec` type, sibling to the three `Copy`-return
2059 /// [`SupervisorSpec::estrategia`] (eafb619) /
2060 /// [`SupervisorSpec::max_restarts`] (7844f4e) /
2061 /// [`SupervisorSpec::restart_window`] (7e7b32f) accessors — closes
2062 /// the last unlifted per-`:supervisor` field axis (the
2063 /// `Vec<ChildSpec>` static-child-list carrier) so every downstream
2064 /// per-`:supervisor` reader now routes through a typed dispatch on
2065 /// the substrate primitive. Named `children()` to match the storage
2066 /// field's name verbatim and the tatara-lisp author-surface term
2067 /// (`:children`) the field's own docstring already carries; the
2068 /// accessor's identity maps onto the canonical OTP-shape
2069 /// supervision vocabulary the [`SupervisorSpec::children`] field's
2070 /// docstring already reaches for ("Static children ..."). Returns
2071 /// `&[ChildSpec]` (not `&Vec<ChildSpec>`) because every downstream
2072 /// consumer of the child list treats it as a read-only sequence —
2073 /// the slice-view is the narrowest borrow that supports every
2074 /// present + roadmapped consumer (`.is_empty()`, `.iter()`,
2075 /// index, `.len()`) without leaking the backing `Vec`'s
2076 /// grow/push/reserve surface that no consumer of the typed view
2077 /// reaches for (the storage-side `Vec` remains reachable through
2078 /// the `pub children` field for the mutation-carrying
2079 /// `Caixa::supervisor_view` fold-in path in
2080 /// `manifest.rs:supervisor_view`).
2081 #[must_use]
2082 pub const fn children(&self) -> &[ChildSpec] {
2083 self.children.as_slice()
2084 }
2085
2086 /// Validate the supervisor's typed shape — strategy ↔ children
2087 /// invariants, max_restarts > 0, restart_window > 0 when set,
2088 /// per-child non-empty + duplicate-free names.
2089 ///
2090 /// Mirrors the value-shape discipline applied to every other
2091 /// typed slot:
2092 ///
2093 /// - `Some(Duration::ZERO)` on a Duration-bearing axis is the
2094 /// same "0 means the opposite of what you think" footgun
2095 /// closed for `:politicas :timeout` (Envoy interprets a zero
2096 /// timeout as `infinite`), `:politicas :circuit-breaker
2097 /// :window`, and `:limits :wall-clock`. The
2098 /// `MaxIntensity / Period` ratio in Erlang/OTP's
2099 /// `supervisor` requires `Period > 0`; a zero period either
2100 /// trips on the first failure or never trips depending on
2101 /// operator interpretation, neither of which is the
2102 /// author's intent. Omit `:restart-window` to express "no
2103 /// reset"; carry a positive duration to express the window.
2104 /// - duplicate `:children` `:caixa` names are the same
2105 /// graph-node-set / multiset distinction closed for
2106 /// `:membros` (4bb3f3d), `:placement :clusters` (c7c7799),
2107 /// and `:entrada :paths` (eb3456d). Two children with the
2108 /// same `:caixa` materialize as two ComputeUnits with the
2109 /// same name in the cluster's HelmRelease values, one
2110 /// silently overwriting the other. Erlang/OTP's
2111 /// `child_spec.id` is required-unique per supervisor;
2112 /// pleme-io enforces the same set-not-multiset shape on
2113 /// `:caixa` (the load-bearing identity in our renderer).
2114 pub fn validate(&self) -> Result<(), SupervisorError> {
2115 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition
2116 // dispatch and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
2117 // error carrier's `estrategia:` field through the lifted
2118 // [`SupervisorSpec::estrategia`] accessor rather than the raw
2119 // `self.estrategia` field access — the two production consumers
2120 // of the per-`:supervisor` sibling-restart-strategy scalar now
2121 // key off exactly one typed dispatch on the substrate primitive,
2122 // so any future rebrand on the axis (a per-cluster strategy
2123 // override the operator pins through a future `:supervisor
2124 // :estrategia-overrides` slot, a per-tenant strategy-alias table
2125 // the M4 CR materializer resolves per-CR) migrates as a single
2126 // caixa-core edit rather than a coordinated rewrite of the two
2127 // call sites — sibling of the peer M3 [`crate::Placement::estrategia`]
2128 // (921fe1b) four-consumer migration on the per-`:placement`
2129 // distribution-strategy axis.
2130 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition-
2131 // dispatch's paired `.is_empty()` cross-slot refusal probes
2132 // (the `SimpleOneForOne`-arm
2133 // [`SupervisorError::SimpleOneForOneWithStaticChildren`] refusal
2134 // and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
2135 // refusal) through the lifted [`SupervisorSpec::children`]
2136 // slice-return accessor rather than the raw `self.children`
2137 // field access — the two paired production consumers of the
2138 // per-`:supervisor` static-child-list scalar-shape now key off
2139 // exactly one typed dispatch on the substrate primitive, so any
2140 // future rebrand on the axis (a per-cluster child-set overlay
2141 // the operator pins through a future `:supervisor
2142 // :children-overrides` slot, a per-tenant child-set-alias table
2143 // the M4 CR materializer resolves per-CR) migrates as a single
2144 // caixa-core edit rather than a coordinated rewrite of the
2145 // paired arms — first slice-return migration on any typed slot,
2146 // seed for the peer per-`:placement :clusters`,
2147 // per-`:membros`, per-`:contratos`, and per-`:upgrade-from
2148 // :instructions` `Vec`-carry axes.
2149 match self.estrategia() {
2150 RestartStrategy::SimpleOneForOne => {
2151 // SimpleOneForOne: children added at runtime. Static
2152 // list must be empty (one shape declared elsewhere).
2153 if !self.children().is_empty() {
2154 return Err(SupervisorError::SimpleOneForOneWithStaticChildren);
2155 }
2156 }
2157 _ => {
2158 if self.children().is_empty() {
2159 return Err(SupervisorError::no_children(self.estrategia()));
2160 }
2161 }
2162 }
2163 // Zero-floor + upper-cap bracket on the typed `:max-restarts`
2164 // axis. See [`crate::render::require_positive_bounded_u32`] for
2165 // the ordering discipline (zero-floor arm strictly precedes cap
2166 // arm so `0` surfaces the self-locating `ZeroMaxRestarts`
2167 // diagnostic with its counter-axis remediation directly named,
2168 // not the misleading `0 > SUPERVISOR_MAX_RESTARTS_MAX == false`
2169 // cap-arm miss). Until this bracket landed the top edge ran all
2170 // the way to `u32::MAX` and a struct-literal
2171 // `SupervisorSpec { max_restarts: 100_000, .. }` (or the
2172 // equivalent author-surface `:max-restarts 100000` /
2173 // `:max-restarts 4294967295` typo landing in the slot) silently
2174 // passed validate. The runtime substrate consuming the value
2175 // (Erlang/OTP's `MaxIntensity / Period` ratio, the future
2176 // wasm-operator's per-supervisor restart-intensity counter, the
2177 // M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2178 // admission webhook) then turned a typed `:max-restarts`
2179 // policy into a no-op supervisor: the escalation threshold is
2180 // structurally so high that no realistic
2181 // restarts-per-`:restart-window` traffic shape can reach it,
2182 // the supervisor never escalates to its parent, and a bad
2183 // child can loop inside the window indefinitely with the
2184 // parent supervisor structurally never receiving the "this
2185 // subtree has exceeded its restart budget" signal the typed
2186 // slot is meant to express. The bracket set is
2187 // `1..=SUPERVISOR_MAX_RESTARTS_MAX`, peer with the
2188 // [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap on
2189 // the sibling `:politicas :circuit-breaker :max-failures` axis:
2190 // both are "trip the next-higher protection layer after N
2191 // events in a rolling window" counters with identical
2192 // degenerate-at-the-high-end shape and now share one canonical
2193 // bracket helper. The bracket precedes the sibling
2194 // `:restart-window` zero-floor / canonical-millisecond arms so
2195 // an over-cap `max_restarts` paired with a structurally invalid
2196 // window surfaces the bracket diagnostic first, mirroring the
2197 // `PolicyBreakerMaxFailuresExceedsCap` / window-axis cross-arm
2198 // ordering on the peer `:politicas :circuit-breaker` slot.
2199 // Route the [`SupervisorSpec::validate`] `:max-restarts` zero-floor +
2200 // upper-cap bracket-gate through the lifted [`SupervisorSpec::max_restarts`]
2201 // accessor rather than the raw `self.max_restarts` field access —
2202 // the one production consumer of the per-`:supervisor`
2203 // restart-budget-count scalar now keys off exactly one typed
2204 // dispatch on the substrate primitive, so any future rebrand on
2205 // the axis (a per-cluster restart-budget override the operator
2206 // pins through a future `:supervisor :max-restarts-overrides`
2207 // slot, a per-tenant restart-budget-alias table the M4 CR
2208 // materializer resolves per-CR) migrates as a single caixa-core
2209 // edit rather than a coordinated rewrite — sibling of the peer M3
2210 // [`crate::CircuitBreaker::max_failures`] (3a74062) migration on
2211 // the per-`:politicas :circuit-breaker :max-failures` axis.
2212 crate::render::require_positive_bounded_u32(
2213 self.max_restarts(),
2214 SUPERVISOR_MAX_RESTARTS_MAX,
2215 || SupervisorError::ZeroMaxRestarts,
2216 SupervisorError::max_restarts_exceeds_cap,
2217 )?;
2218 // Route the [`SupervisorSpec::validate`] `:restart-window`
2219 // zero-floor + integer-millisecond canonical-form + upper-cap
2220 // bracket-gate through the lifted [`SupervisorSpec::restart_window`]
2221 // accessor rather than the raw `self.restart_window` field access —
2222 // the one production consumer of the per-`:supervisor`
2223 // restart-intensity-denominator scalar now keys off exactly one
2224 // typed dispatch on the substrate primitive, so any future rebrand
2225 // on the axis (a per-cluster restart-window override the operator
2226 // pins through a future `:supervisor :restart-window-overrides`
2227 // slot, a per-tenant restart-window-alias table the M4 CR
2228 // materializer resolves per-CR) migrates as a single caixa-core
2229 // edit rather than a coordinated rewrite — sibling of the peer M2
2230 // [`crate::LimitsSpec::wall_clock`] (8cb717b) validate-arm-route
2231 // on the per-`:limits :wall-clock` axis and the peer M3
2232 // [`crate::MeshPolicy::timeout`] (7073d0f) accessor-route on the
2233 // per-`:politicas :timeout` axis.
2234 if let Some(w) = self.restart_window() {
2235 // Zero-floor + integer-millisecond canonical-form +
2236 // upper-cap bracket on the typed `:restart-window` axis.
2237 // See
2238 // [`crate::render::require_positive_canonical_bounded_duration`]
2239 // for the full three-arm ordering discipline (zero-floor
2240 // strictly precedes canonical-form so `Duration::ZERO`
2241 // surfaces the self-locating `RestartWindowZero`
2242 // diagnostic; canonical-form strictly precedes the cap arm
2243 // so a sub-millisecond above-cap value surfaces the more
2244 // fundamental round-trip-shape diagnostic first) and the
2245 // three peer typed-`Duration` sites that share this
2246 // canonical bracket ([`crate::MeshPolicy::timeout`],
2247 // [`crate::CircuitBreaker::window`],
2248 // [`crate::LimitsSpec::wall_clock`]). Every validated
2249 // value lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
2250 // (1ms..=1h), integer-millisecond granularity.
2251 crate::render::require_positive_canonical_bounded_duration(
2252 w,
2253 SUPERVISOR_RESTART_WINDOW_MAX,
2254 || SupervisorError::RestartWindowZero,
2255 SupervisorError::restart_window_not_canonical,
2256 SupervisorError::restart_window_exceeds_cap,
2257 )?;
2258 }
2259 // Route the per-child DNS-1123 / semver-requirement / duplicate-
2260 // detection fan-out loop through the lifted named per-slot gate
2261 // [`SupervisorSpec::validate_children`] rather than an inline
2262 // three-per-child cascade — every future consumer that wants to
2263 // re-check only the `:children` slot's per-entry axes (the M4
2264 // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2265 // admission webhook re-validating one added/renamed child, the
2266 // future wasm-operator's per-child dynamic-add re-validator on
2267 // the `SimpleOneForOne` runtime-add path once dynamic-children
2268 // graduate to a typed slot, a future partial re-validator on a
2269 // per-`:children`-entry patch) reaches every per-entry axis
2270 // through one dispatch rather than re-inlining the three-arm
2271 // cascade in lockstep with `validate` or paying the peer
2272 // `:estrategia`/`:max-restarts`/`:restart-window` gates to
2273 // reach one entry check. Sibling of the peer M3 mesh-slot
2274 // per-slot gate family (`validate_membros` — the exact peer on
2275 // the M3 side, [`crate::AplicacaoSpec::validate_membros`];
2276 // `validate_contratos` — 906a5c6; `validate_entrada` — 20cd523;
2277 // `validate_placement`; `validate_politicas` routing through
2278 // `MeshPolicy::validate` — f03a154) — the M2 supervisor-slot
2279 // per-slot gate discipline now spans both the M3 mesh-slot
2280 // family and the M2 `:children` per-child-cascade axis on one
2281 // shape: one named per-slot gate per typed per-entry loop.
2282 self.validate_children()?;
2283 Ok(())
2284 }
2285
2286 /// Named per-slot gate on the M2 `:supervisor :children` per-entry
2287 /// axis — folds the per-child DNS-1123 name gate, semver-requirement
2288 /// gate, and duplicate-`:caixa` dedup arm into one call every
2289 /// consumer that wants to re-validate one `:children` entry (or the
2290 /// whole list) against the same accept-set [`SupervisorSpec::validate`]
2291 /// admits reaches through.
2292 ///
2293 /// Peer of the M3 mesh-slot [`crate::AplicacaoSpec::validate_membros`]
2294 /// per-slot gate on the analogous per-entry axis (`:membros`) — same
2295 /// three-per-entry shape (DNS-1123 name + semver-requirement +
2296 /// duplicate-`:caixa` dedup), lifted to one named substrate
2297 /// primitive per slot. The M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
2298 /// materializer's admission webhook re-checking one added or renamed
2299 /// child, the future wasm-operator's per-child dynamic-add
2300 /// re-validator on the `SimpleOneForOne` runtime-add path once
2301 /// dynamic-children graduate to a typed slot, a future partial
2302 /// re-validator on a per-`:children`-entry patch — each reaches the
2303 /// three per-entry axes through this one dispatch rather than
2304 /// re-inlining the three-arm cascade in lockstep with `validate`
2305 /// (the duplication the PRIME DIRECTIVE names as a bug) or paying
2306 /// the peer `:estrategia`/`:max-restarts`/`:restart-window` gates to
2307 /// reach one entry check.
2308 ///
2309 /// Self-contained on `&self` — resolves its own dedup `HashSet`
2310 /// through [`SupervisorSpec::children`] rather than borrowing one
2311 /// threaded down from `validate`, the same posture the peer M3
2312 /// mesh-slot per-slot gates ([`crate::AplicacaoSpec::validate_membros`],
2313 /// [`crate::AplicacaoSpec::validate_contratos`],
2314 /// [`crate::AplicacaoSpec::validate_entrada`],
2315 /// [`crate::AplicacaoSpec::validate_placement`]) each carry, so a
2316 /// consumer that reaches this gate directly (without first calling
2317 /// `validate`) still runs the full per-child cascade — pinned by
2318 /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
2319 /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
2320 /// + `validate_children_is_self_contained_on_children_slot`.
2321 ///
2322 /// The three per-entry arms run in the same canonical order the
2323 /// pre-lift inline cascade encoded (DNS-1123 → semver → dedup), so
2324 /// the diagnostic every author-declared per-`:children` entry surfaces
2325 /// through `validate` is byte-equal to the diagnostic this gate
2326 /// surfaces when called directly — the equivalence-pin pair
2327 /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
2328 /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
2329 /// asserts the two altitudes discriminate the same set on every
2330 /// per-entry-covered input.
2331 pub fn validate_children(&self) -> Result<(), SupervisorError> {
2332 let mut seen = std::collections::HashSet::new();
2333 for child in self.children() {
2334 // Every emitted cluster artifact's `metadata.name` for a
2335 // supervised child derives from this `:children :caixa` value
2336 // verbatim — the rendered `wasm.pleme.io/v1alpha1/ComputeUnit
2337 // .metadata.name` per child, the [`crate::LABEL_PROGRAM`]
2338 // label value on every child's pod identity, and the per-
2339 // child K8s [`Service`][svc] `metadata.name` the future
2340 // wasm-operator (M3) provisions for inter-child supervision
2341 // tree wiring. Each apiserver-side schema on each landing
2342 // site enforces the DNS-1123 label rule on admission; a
2343 // structurally invalid child name (`"Worker"`, `"my_worker"`,
2344 // `"team.worker"`, `"-worker"`, `"worker-"`, the >63-byte
2345 // UUID-shaped mistaken-identity slug) silently passes the
2346 // prior empty-/duplicate-only gate and the failure surfaces
2347 // at `kubectl apply` time as a `metadata.name: Invalid value`
2348 // rejection, far from the source caixa.lisp, with no field
2349 // naming the offending `:children` entry. Lifting the gate
2350 // to caixa-build time mirrors the `:membros :caixa` value-
2351 // shape trajectory (3f9d7a0) and the `:placement :clusters`
2352 // trajectory (6cbb900) onto the third DNS-1123-label-shaped
2353 // identifier axis — the supervisor tree's child names —
2354 // through the lifted
2355 // [`crate::render::require_valid_dns_1123_label`] gate the
2356 // seven peer name axes (`:membros :caixa`, `:placement
2357 // :clusters`, `:placement :affinity`, `:contratos :de`/`:para`,
2358 // `:entrada :para`, `:nome`, `:upgrade-from :module`) each
2359 // route through, so drift between the eight axes' accepted
2360 // DNS-1123-label sets is structurally impossible.
2361 //
2362 // [svc]: https://kubernetes.io/docs/concepts/services-networking/service/
2363 crate::render::require_valid_dns_1123_label(
2364 child.nome(),
2365 || SupervisorError::EmptyChildName,
2366 |reason| SupervisorError::child_caixa_invalid(child.nome(), reason),
2367 )?;
2368 // The author surface for `:children :versao` is the same
2369 // Cargo-shaped semver requirement string `:deps :versao` and
2370 // `:membros :versao` carry — and the lacre pipeline resolves
2371 // all three axes through the same
2372 // [`crate::version::parse_requirement`] entry-point. The
2373 // shared [`crate::render::require_valid_versao_requirement`]
2374 // helper brackets the empty-first + parse cascade both peer
2375 // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
2376 // [`crate::AplicacaoSpec::validate_membros`] on `:membros
2377 // :versao`) route through, so drift between the three axes'
2378 // accepted requirement sets is structurally impossible and
2379 // the parse-side no-op the empty-first arm closes (semver's
2380 // empty parse yields an implicit `*`) lives in exactly one
2381 // predicate. Every `ChildSpec::versao` past validate is
2382 // round-trippable through [`crate::parse_requirement`]
2383 // without re-checking at the resolver layer, and the three
2384 // `:versao` typed surfaces (`:deps`, `:membros`, `:children`)
2385 // are now structurally equivalent by construction.
2386 crate::render::require_valid_versao_requirement(
2387 child.versao_requirement(),
2388 || SupervisorError::empty_child_version(child.nome()),
2389 |reason| {
2390 SupervisorError::child_versao_invalid(
2391 child.nome(),
2392 child.versao_requirement(),
2393 reason,
2394 )
2395 },
2396 )?;
2397 crate::render::insert_first_seen(&mut seen, child.nome(), || {
2398 SupervisorError::duplicate_child_caixa(child.nome())
2399 })?;
2400 }
2401 Ok(())
2402 }
2403}
2404
2405/// Cross-slot coherence gate on the supervision tree: no
2406/// `:children :caixa` entry may name the supervisor's own `:nome`.
2407///
2408/// A supervisor that lists itself as a child is a degenerate self-parent
2409/// — the supervision tree is a DAG rooted at the supervisor (OTP child
2410/// specs reference *distinct* child processes; a supervisor is never its
2411/// own child), and the wasm-operator's hierarchical reconciliation would
2412/// otherwise be handed a node that is its own parent: a one-node cycle it
2413/// either rejects far from the source `caixa.lisp` or recurses on. Because
2414/// every `:nome` is a globally-unique substrate identity (DNS-1123 label +
2415/// lacre closure root), a child whose `:caixa` equals the supervisor's
2416/// `:nome` *is* the supervisor itself, not a coincidentally-named peer.
2417///
2418/// Lives outside [`SupervisorSpec::validate`] because the typed view
2419/// carries the children but not the parent `:nome`; mirrors the
2420/// cross-slot precedence gate `validate_upgrade_from_against_versao`
2421/// (which likewise reads one slot against another at the
2422/// [`crate::layout`] wire-up site) and the mesh self-edge gate
2423/// `AplicacaoSpec`'s `ContratoSelfLoop` — the same "an edge from a graph
2424/// node to itself is structurally not a tree/mesh edge" discipline, here
2425/// on the supervision-tree axis.
2426pub fn validate_no_self_supervision(
2427 children: &[ChildSpec],
2428 parent_nome: &str,
2429) -> Result<(), SupervisorError> {
2430 for child in children {
2431 if child.nome() == parent_nome {
2432 return Err(SupervisorError::child_supervises_self(parent_nome));
2433 }
2434 }
2435 Ok(())
2436}
2437
2438#[derive(Debug, Error, PartialEq, Eq)]
2439pub enum SupervisorError {
2440 #[error("supervisor :estrategia {estrategia:?} requires at least one :children entry")]
2441 NoChildren { estrategia: RestartStrategy },
2442 #[error(
2443 "SimpleOneForOne supervisors must declare zero static children (children spawn dynamically)"
2444 )]
2445 SimpleOneForOneWithStaticChildren,
2446 #[error(":max-restarts must be > 0")]
2447 ZeroMaxRestarts,
2448 #[error(
2449 ":supervisor :max-restarts ({max_restarts}) exceeds the supervisor-policy ceiling \
2450 (SUPERVISOR_MAX_RESTARTS_MAX = 1000) — a value above this cap turns the typed \
2451 restart-intensity policy into a no-op supervisor: the escalation threshold is \
2452 structurally so high that no realistic restarts-per-:restart-window traffic shape \
2453 can reach it, so the supervisor never escalates to its parent and a bad child can \
2454 loop inside the window indefinitely. Every typed-slot consumer (Erlang/OTP's \
2455 MaxIntensity/Period ratio, the future wasm-operator's per-supervisor \
2456 restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
2457 materializer's admission webhook) emits a `:max-restarts` declaration that is \
2458 structurally never reached. Pin a value in 1..=1000 (Erlang/OTP / Elixir / Riak \
2459 Core / RabbitMQ production playbooks recommend 3..=100; the OTP `supervisor` \
2460 callback module's `MaxR = 1` minimal-restart default sits at the bottom of the \
2461 band) or restructure the supervision tree (split the flaky child into its own \
2462 sub-supervisor with a tighter budget) if you need a higher restart tolerance."
2463 )]
2464 MaxRestartsExceedsCap { max_restarts: u32 },
2465 #[error(
2466 ":restart-window must be > 0 when set — Erlang/OTP's MaxIntensity/Period \
2467 requires Period > 0; a zero window either trips on the first failure or \
2468 never trips depending on operator interpretation. Omit :restart-window to \
2469 express `never reset`; carry a positive duration to express the window."
2470 )]
2471 RestartWindowZero,
2472 #[error(
2473 ":supervisor :restart-window ({window:?}) carries a sub-millisecond residue the shared `duration_codec` cannot round-trip — \
2474 the codec truncates to `as_millis()` before picking the canonical unit, so a value with `subsec_nanos() % 1_000_000 != 0` either \
2475 truncates on first serialize (e.g. `Duration::from_micros(1500)` → \"1ms\" → `Duration::from_millis(1)` ≠ original) or renders \
2476 as \"0s\" the `RestartWindowZero` arm then rejects on re-validate. Pin an integer-millisecond magnitude in the canonical authoring form \
2477 (`<integer><unit>` for unit ∈ {{ms, s, m, h}}, e.g. `\"500ms\"`, `\"30s\"`, `\"2m\"`, `\"1h\"`) or omit the field for `never reset`"
2478 )]
2479 RestartWindowNotCanonical { window: Duration },
2480 #[error(
2481 ":supervisor :restart-window ({window:?}) exceeds the supervisor-policy ceiling \
2482 (SUPERVISOR_RESTART_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
2483 per-supervisor rolling-window restart-intensity counter into a lifetime counter: the \
2484 failure-counting window is structurally so long that transient restarts are never \
2485 forgotten, the MaxIntensity/Period ratio degenerates from `trip the parent supervisor \
2486 when the child has exceeded its restart budget within the recent window` to `trip the \
2487 parent when the child has exceeded its restart budget over its lifetime`, and the \
2488 supervisor's reset semantic never reaches the child — every typed-slot consumer \
2489 (Erlang/OTP's MaxIntensity/Period reconciler, the future wasm-operator's \
2490 per-supervisor restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
2491 materializer's admission webhook, the caixa-operator's hierarchical reconciliation \
2492 scheduler) emits a `:restart-window` declaration that is structurally a no-op rolling \
2493 window. Pin a value in 1ms..=1h (Learn You Some Erlang's `{{intensity, 5, 60}}` \
2494 worker-supervisor `Period = 60s` default, Elixir's `Supervisor` `max_seconds: 5` \
2495 default, OTP's `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's \
2496 `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default — every Erlang/OTP \
2497 / Elixir production playbook sits in the 5s..=300s band; the longest documented \
2498 per-supervisor restart-window any pleme-io substrate playbook recommends maxes at \
2499 ~30m) or omit :restart-window to express `never reset` (the supervisor's restart \
2500 budget then becomes a strict lifetime counter by design, not a degenerate one — the \
2501 author surfaces the lifetime-counter semantic explicitly at the slot, rather than \
2502 hiding it behind a rolling-window declaration the cap arm rejects)"
2503 )]
2504 RestartWindowExceedsCap { window: Duration },
2505 #[error("child entry has empty :caixa name")]
2506 EmptyChildName,
2507 #[error(
2508 "child :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
2509 (the K8s apiserver enforces this rule on every `metadata.name` / Service \
2510 name / label value the child name lands in — the per-child \
2511 `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name`, the `LABEL_PROGRAM` \
2512 label value, and the future wasm-operator per-child Service `metadata.name` \
2513 — each apiserver-side schema rejects names that don't match; use a \
2514 lowercase alphanumeric + hyphen identifier like `\"worker\"` or `\"cache-v2\"`)"
2515 )]
2516 ChildCaixaInvalid { caixa: String, reason: String },
2517 #[error("child {caixa:?} has empty :versao constraint")]
2518 EmptyChildVersion { caixa: String },
2519 #[error(
2520 "child {caixa:?} :versao {versao:?} is not a valid semver requirement: \
2521 {reason} (use Cargo-shaped forms like `\"^0.1\"`, `\"~0.1.2\"`, \
2522 `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` and \
2523 `:membros :versao` carry; the lacre pipeline resolves all three \
2524 through the same parser)"
2525 )]
2526 ChildVersaoInvalid {
2527 caixa: String,
2528 versao: String,
2529 reason: String,
2530 },
2531 #[error(
2532 "child {caixa:?} appears more than once (Erlang/OTP requires unique \
2533 child_spec.id per supervisor; duplicate children materialize as duplicate \
2534 ComputeUnits in the rendered chart, one silently overwriting the other)"
2535 )]
2536 DuplicateChildCaixa { caixa: String },
2537 #[error(
2538 "supervisor {caixa:?} lists itself as a :children entry — a supervisor is \
2539 never its own child (the supervision tree is a DAG rooted at the supervisor; \
2540 OTP child specs reference distinct child processes). Since every :nome is a \
2541 globally-unique substrate identity, a child naming the supervisor's own :nome \
2542 is a one-node reconciliation cycle, not a coincidentally-named peer; drop the \
2543 self-referential :children entry or rename it to the actual child caixa."
2544 )]
2545 ChildSupervisesSelf { caixa: String },
2546}
2547
2548// Fold the three `SupervisorError::<Variant> { caixa: <&str>.to_string() }`
2549// caixa-only struct-variant wire-up sites at [`SupervisorSpec::validate_children`]
2550// and [`validate_no_self_supervision`] onto one substrate primitive per
2551// typed variant — the sibling on `SupervisorError` of the four uniform-shape
2552// `LayoutError`-envelope constructor families the peer
2553// [`crate::layout::layout_violation_ctors!`] macro closed (131ca0d, 16
2554// variants on `{ caixa, issue }`), the [`crate::layout::layout_slot_kind_ctors!`]
2555// macro closed (0419438, 4 variants on `{ caixa, kind, slots }`), the
2556// [`crate::LayoutError::missing_entry`] one-variant ctor closed (1b09f9d,
2557// on `{ kind, path }`), and the [`crate::layout::layout_nome_only_ctors!`]
2558// macro closed (3fe3dd7, 6 variants on `<Variant>(String)`), plus the
2559// [`crate::AplicacaoError::entrada_host_invalid`] one-variant ctor
2560// (17dd504, `{ host, reason }`), the [`crate::aplicacao::contrato_target_ctors!`]
2561// macro (14b81d5, 2 variants on `{ de, para, wit, expected }`), and the
2562// [`crate::aplicacao::contrato_empty_pair_ctors!`] macro (8580068, 4
2563// variants on `{ de, para }`) already at that discipline on the peer
2564// `AplicacaoError` envelopes.
2565//
2566// Each of the three wire-up sites on this shape (`EmptyChildVersion` at
2567// the per-`:children` semver-requirement empty-first arm, `DuplicateChildCaixa`
2568// at the per-`:children` dedup arm, `ChildSupervisesSelf` at the cross-slot
2569// self-supervision arm) opened the identical
2570// `SupervisorError::<Variant> { caixa: <&str>.to_string() }` struct-literal —
2571// the exact "same block re-inlined at every consumer" shape the PRIME
2572// DIRECTIVE names as a bug, on the same altitude the peer `LayoutError` /
2573// `AplicacaoError` families each closed on their sibling envelopes. The
2574// three variants share one `{ caixa: String }` shape, so the fold routes
2575// each wire-up site through one dispatch per typed variant.
2576//
2577// The macro below generates one static constructor per variant of shape
2578// `fn <slot>(caixa: &str) -> SupervisorError`, so every wire-up site
2579// collapses onto one dispatch:
2580// `SupervisorError::<slot>(<&str>)`, byte-equal to the pre-lift
2581// struct-literal on the same `&str` fixture. The uniform one-field
2582// construction (`caixa: caixa.to_string()`) is spelled once — inside the
2583// macro — rather than at every wire-up site. Every constructor is
2584// `#[must_use]` so a caller who mistakenly discards the constructed error
2585// trips a compile warning at the wire-up site.
2586//
2587// Every future consumer that wants to construct one of these three
2588// variants outside `SupervisorSpec::validate_children` /
2589// `validate_no_self_supervision` — a deferred
2590// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2591// webhook re-checking one added/renamed child, a future
2592// `feira validate --supervisor` per-caixa admission verb, a per-child
2593// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path
2594// once dynamic-children graduate to a typed slot, a per-Supervisor
2595// overlay resolver rejecting a duplicate/self-supervising child against
2596// a cluster-local snapshot — now reaches each variant through one call
2597// rather than re-inlining the three-line struct-literal in lockstep
2598// with the three in-crate wire-up sites.
2599macro_rules! supervisor_caixa_only_ctors {
2600 ($($ctor:ident => $variant:ident),* $(,)?) => {
2601 impl SupervisorError {
2602 $(
2603 #[doc = concat!(
2604 "Construct a [`SupervisorError::",
2605 stringify!($variant),
2606 "`] naming the offending `:children :caixa` (or ",
2607 "supervisor `:nome`, on the self-supervision arm). ",
2608 "Folds the uniform `Self::",
2609 stringify!($variant),
2610 " { caixa: caixa.to_string() }` one-field ",
2611 "struct-literal onto one substrate primitive so ",
2612 "every [`SupervisorSpec::validate_children`] / ",
2613 "[`validate_no_self_supervision`] wire-up on this ",
2614 "variant reads through one dispatch rather than the ",
2615 "pre-lift open-coded struct-literal block."
2616 )]
2617 #[must_use]
2618 pub fn $ctor(caixa: &str) -> Self {
2619 Self::$variant { caixa: caixa.to_string() }
2620 }
2621 )*
2622 }
2623 };
2624}
2625
2626supervisor_caixa_only_ctors! {
2627 empty_child_version => EmptyChildVersion,
2628 duplicate_child_caixa => DuplicateChildCaixa,
2629 child_supervises_self => ChildSupervisesSelf,
2630}
2631
2632// Fold the two `SupervisorError::{ChildCaixaInvalid, ChildVersaoInvalid}`
2633// struct-variant wire-up sites at [`SupervisorSpec::validate_children`] onto
2634// one substrate primitive per typed variant — the M2 supervisor-side siblings
2635// of the peer [`crate::AplicacaoError::membro_caixa_invalid`] two-slot ctor
2636// already lifted through the sibling
2637// [`crate::aplicacao::aplicacao_field_reason_ctors!`] macro (981060b) on the
2638// peer `AplicacaoError { caixa: String, reason: String }` envelope. The
2639// `ChildCaixaInvalid` variant carries the same `{ <name>: String, reason:
2640// String }` two-slot shape the peer seven-variant
2641// [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold closed on the
2642// `AplicacaoError` envelope (`MembroCaixaInvalid`, `EntradaParaInvalid`,
2643// `EntradaHostInvalid`, `EntradaPathInvalid`, `PlacementClusterInvalid`,
2644// `PlacementAffinityInvalid`, `ShardKeyInvalid`); the `ChildVersaoInvalid`
2645// variant carries the `{ caixa: String, versao: String, reason: String }`
2646// three-slot shape the sibling `AplicacaoError::MembroVersaoInvalid` axis
2647// carries on the same `:versao` value-shape.
2648//
2649// Each of the two wire-up sites opened the same closure-shaped
2650// `|reason| SupervisorError::<Variant> { caixa: child.nome().to_string(),
2651// [versao: child.versao_requirement().to_string(),] reason }` block inside
2652// the paired [`crate::render::require_valid_dns_1123_label`] and
2653// [`crate::render::require_valid_versao_requirement`] callbacks — the exact
2654// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE names
2655// as a bug, on the same altitude the peer `AplicacaoError` /
2656// `SupervisorError` / `LayoutError` / `DepError` / `LimitsError` ctor
2657// families already closed on their sibling envelopes.
2658//
2659// The two `#[must_use]` inherent constructors below fold each wire-up onto
2660// one dispatch: `SupervisorError::child_caixa_invalid(<name>, <reason>)`
2661// and `SupervisorError::child_versao_invalid(<name>, <versao>, <reason>)`,
2662// byte-equal to the pre-lift struct-literal on the same scalar fixtures.
2663// The uniform per-field `.to_string()` / `.into()` construction is spelled
2664// once — inside each ctor body — rather than at every wire-up site. The
2665// `reason: impl Into<String>` bound accepts both `&str` literals and
2666// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
2667// diagnostic shape at the lift, matching the peer
2668// [`aplicacao_field_reason_ctors!`] and
2669// [`crate::aplicacao::contrato_pair_value_reason_ctors!`] bounds on the
2670// sibling envelopes.
2671//
2672// Every future consumer that wants to construct one of these two variants
2673// outside `SupervisorSpec::validate_children` — a deferred
2674// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook
2675// re-checking one added/renamed child's `:caixa` or `:versao`, a future
2676// `feira validate --supervisor` per-caixa admission verb, a per-child
2677// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path once
2678// dynamic-children graduate to a typed slot, a per-Supervisor overlay
2679// resolver rejecting a shape-invalid child `:caixa`/`:versao` against a
2680// cluster-local snapshot — now reaches each variant through one call rather
2681// than re-inlining the per-shape struct-literal block in lockstep with the
2682// two in-crate wire-up sites.
2683impl SupervisorError {
2684 /// Construct a [`SupervisorError::ChildCaixaInvalid`] naming the
2685 /// offending `:children :caixa` value under the given `reason`. Folds
2686 /// the uniform `Self::ChildCaixaInvalid { caixa: caixa.to_string(),
2687 /// reason: reason.into() }` two-slot struct-literal onto one substrate
2688 /// primitive so every wire-up on this variant reads through one
2689 /// dispatch, matching the peer
2690 /// [`crate::AplicacaoError::membro_caixa_invalid`] ctor's shape on the
2691 /// sibling `AplicacaoError { caixa: String, reason: String }`
2692 /// envelope. `reason` accepts both `&str` literals and `format!(…)`
2693 /// outputs through the `impl Into<String>` bound.
2694 #[must_use]
2695 pub fn child_caixa_invalid(caixa: &str, reason: impl Into<String>) -> Self {
2696 Self::ChildCaixaInvalid {
2697 caixa: caixa.to_string(),
2698 reason: reason.into(),
2699 }
2700 }
2701
2702 /// Construct a [`SupervisorError::ChildVersaoInvalid`] naming the
2703 /// offending `:children :caixa` and its `:versao` requirement under
2704 /// the given `reason`. Folds the uniform `Self::ChildVersaoInvalid {
2705 /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
2706 /// reason.into() }` three-slot struct-literal onto one substrate
2707 /// primitive so every wire-up on this variant reads through one
2708 /// dispatch, matching the sibling `AplicacaoError::MembroVersaoInvalid
2709 /// { caixa, versao, reason }` three-slot axis on the peer
2710 /// `AplicacaoError` envelope. `reason` accepts both `&str` literals
2711 /// and `format!(…)` outputs through the `impl Into<String>` bound.
2712 #[must_use]
2713 pub fn child_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
2714 Self::ChildVersaoInvalid {
2715 caixa: caixa.to_string(),
2716 versao: versao.to_string(),
2717 reason: reason.into(),
2718 }
2719 }
2720}
2721
2722// Fold the four `SupervisorError::<Variant> { <field>: <Copy> }` one-field
2723// Copy-scalar struct-variant wire-up sites at [`SupervisorSpec::validate`]'s
2724// three bracket-arms — one struct-literal at the `:children`-empty
2725// non-`SimpleOneForOne` refusal cascade (`NoChildren { estrategia }`) plus
2726// three `impl FnOnce(<ty>) -> SupervisorError` bracket-closures at the
2727// [`crate::render::require_positive_bounded_u32`] `:max-restarts` cap arm
2728// (`MaxRestartsExceedsCap { max_restarts }`) and the paired
2729// [`crate::render::require_positive_canonical_bounded_duration`]
2730// `:restart-window` canonical-form + cap arms (`RestartWindowNotCanonical
2731// { window }`, `RestartWindowExceedsCap { window }`) — onto one substrate
2732// primitive per typed variant, matching the sibling
2733// [`crate::aplicacao::aplicacao_policy_scalar_ctors!`] macro (7ef425e, 8
2734// variants on the same `{ <field>: Duration | u32 }` shape) at that
2735// discipline on the peer `AplicacaoError` envelope's per-`:politicas`
2736// scalar axis. Every variant is a one-field `Copy`-pass-through struct-
2737// literal — `RestartStrategy | u32 | Duration` — so the fold routes each
2738// wire-up site through one dispatch per typed variant without a runtime-
2739// work delta.
2740//
2741// Each of the four wire-up sites opened the identical
2742// `SupervisorError::<Variant> { <field>: <val> }` struct-literal — the
2743// exact "same block re-inlined at every consumer" shape the PRIME
2744// DIRECTIVE names as a bug, on the same altitude the peer
2745// `aplicacao_policy_scalar_ctors!` fold closed on the sibling
2746// `AplicacaoError` envelope's per-`:politicas` per-axis cap / canonical-
2747// form arms. The four variants share one `{ <field>: <Copy> }` shape, so
2748// the fold routes each wire-up site through one dispatch per typed
2749// variant.
2750//
2751// The macro below generates one static constructor per variant of shape
2752// `const fn <ctor>(<field>: <ty>) -> SupervisorError`, so every wire-up
2753// site collapses onto one dispatch: `SupervisorError::<ctor>(<val>)`,
2754// byte-equal to the pre-lift struct-literal on the same `Copy`-`<ty>`
2755// fixture — as a direct call at the [`SupervisorSpec::validate`]
2756// `:children`-empty refusal, or as a bare function pointer in the
2757// `impl FnOnce(<ty>) -> SupervisorError` bracket-closure slot every
2758// [`crate::render::require_positive_bounded_u32`] /
2759// [`crate::render::require_positive_canonical_bounded_duration`] gate
2760// carries — rather than the pre-lift open-coded one-line closure over
2761// the same one-field struct-literal. `const fn` preserves the `Copy`-
2762// pass-through's zero-runtime-work property verbatim. Every constructor
2763// is `#[must_use]` so a caller who mistakenly discards the constructed
2764// error trips a compile warning at the wire-up site.
2765//
2766// Every future consumer that wants to construct one of these four
2767// variants outside `SupervisorSpec::validate` — a deferred
2768// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
2769// webhook re-checking one edited `:estrategia` / `:max-restarts` /
2770// `:restart-window` slot against the cap + canonical-form cascade, a
2771// future `feira validate --supervisor` per-caixa admission verb re-
2772// running the shape gates on demand, a per-Supervisor overlay resolver
2773// rejecting an author-supplied slot against a cluster-local snapshot —
2774// now reaches each variant through one call rather than re-inlining the
2775// per-shape struct-literal block in lockstep with the four in-crate
2776// wire-up sites.
2777macro_rules! supervisor_scalar_ctors {
2778 ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
2779 impl SupervisorError {
2780 $(
2781 #[doc = concat!(
2782 "Construct a [`SupervisorError::",
2783 stringify!($variant),
2784 "`] naming the offending per-`:supervisor` `",
2785 stringify!($field),
2786 "` scalar. Folds the uniform `Self::",
2787 stringify!($variant),
2788 " { ",
2789 stringify!($field),
2790 " }` one-field `Copy`-pass-through struct-literal onto ",
2791 "one substrate primitive so every per-axis wire-up on ",
2792 "this variant reads through one dispatch — as a direct ",
2793 "call (`SupervisorError::",
2794 stringify!($ctor),
2795 "(<val>)`, byte-equal to the pre-lift struct-literal on ",
2796 "the same `Copy`-`",
2797 stringify!($ty),
2798 "` fixture) or as a bare function pointer in the ",
2799 "`impl FnOnce(",
2800 stringify!($ty),
2801 ") -> SupervisorError` bracket-closure slot every ",
2802 "`crate::render::require_positive_bounded_*` / ",
2803 "`crate::render::require_positive_canonical_bounded_*` ",
2804 "gate carries — rather than the pre-lift open-coded ",
2805 "one-line closure over the same one-field struct-",
2806 "literal. `const fn` preserves the `Copy`-pass-through's ",
2807 "zero-runtime-work property verbatim."
2808 )]
2809 #[must_use]
2810 pub const fn $ctor($field: $ty) -> Self {
2811 Self::$variant { $field }
2812 }
2813 )*
2814 }
2815 };
2816}
2817
2818supervisor_scalar_ctors! {
2819 no_children => NoChildren { estrategia: RestartStrategy },
2820 max_restarts_exceeds_cap => MaxRestartsExceedsCap { max_restarts: u32 },
2821 restart_window_not_canonical => RestartWindowNotCanonical { window: Duration },
2822 restart_window_exceeds_cap => RestartWindowExceedsCap { window: Duration },
2823}
2824
2825/// Shared duration string codec for the typed slots that take a
2826/// duration (`restart_window`, `MeshPolicy::timeout`,
2827/// `CircuitBreaker::window`, …). Public so [`crate::aplicacao`] can
2828/// reuse it without duplicating the parser.
2829pub mod duration_codec {
2830 use super::Duration;
2831 use serde::{Deserializer, Serializer};
2832
2833 pub fn serialize<S: Serializer>(v: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
2834 // Route through the canonical [`crate::render::serialize_option_via_str`]
2835 // — the substrate-side single-owner primitive for the forward
2836 // arm of the typed-magnitude codec family. See its docstring
2837 // for the full sibling roster.
2838 crate::render::serialize_option_via_str(v, s, render)
2839 }
2840
2841 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
2842 // Route through the canonical [`crate::render::deserialize_option_via_str`]
2843 // — the substrate-side single-owner primitive for the reverse
2844 // arm of the typed-magnitude codec family. See its docstring
2845 // for the full sibling roster.
2846 crate::render::deserialize_option_via_str(d, parse)
2847 }
2848
2849 pub(crate) fn parse(s: &str) -> Result<Duration, String> {
2850 // Paired whitespace-rejection arm — same canonical-form
2851 // render-determinism discipline as the peer
2852 // `limits::parse_byte_size` / `limits::parse_duration` /
2853 // `limits::parse_millicores` /
2854 // `aplicacao::rate_limit_codec::parse` sites: the ASCII
2855 // byte-scan closes the WhatWG-conformant whitespace bytes
2856 // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
2857 // `char::is_whitespace` scan closes the strictly-complementary
2858 // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
2859 // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
2860 // codepoints) that `str::trim` at parse entry silently strips.
2861 // Either drift class would round-trip through `render` to a
2862 // *different* canonical form on next emit — breaking the
2863 // THEORY.md Part V render-determinism contract on three typed-
2864 // duration slots at once (`:supervisor :restart-window`,
2865 // `:politicas :timeout`, `:politicas :circuit-breaker :window`)
2866 // via the shared codec.
2867 //
2868 // Routed through the lifted [`crate::render::reject_whitespace`]
2869 // primitive — the substrate-side single-owner paired-arm gate
2870 // every typed-magnitude codec in caixa-core shares.
2871 crate::render::reject_whitespace::<String, _, _>(
2872 s,
2873 |b| {
2874 format!(
2875 "duration: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
2876 authoring form for the typed duration slots routed through this shared codec \
2877 (`:supervisor :restart-window`, `:politicas :timeout`, \
2878 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
2879 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no whitespace bytes \
2880 anywhere. A whitespace-carrying shape (`\" 30s\"`, `\"30s \"`, `\"30 s\"`, \
2881 `\"\\t30s\"`, `\"30s\\n\"`) round-trips through `render` to a *different* \
2882 canonical form (`\"30s\"`) on first serialize — breaking the THEORY.md \
2883 Part V render-determinism contract every typed slot carries. Strip every \
2884 whitespace byte (write `\"30s\"` verbatim)"
2885 )
2886 },
2887 |ch| {
2888 format!(
2889 "duration: value {s:?} contains non-ASCII Unicode whitespace character \
2890 {ch:?} (U+{cp:04X}) — the canonical authoring form for the typed \
2891 duration slots routed through this shared codec (`:supervisor \
2892 :restart-window`, `:politicas :timeout`, `:politicas :circuit-breaker \
2893 :window`) is `<integer><unit>` (e.g. `\"30s\"`, `\"500ms\"`, `\"2m\"`, \
2894 `\"1h\"`) with no whitespace characters anywhere (ASCII or Unicode). A \
2895 non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}30s\"`, \
2896 `\"30s\\u{{2028}}\"`, `\"30\\u{{2003}}s\"`) survives the ASCII byte-scan \
2897 but `str::trim` (which uses `char::is_whitespace` — the Unicode \
2898 `White_Space` property, strictly wider than the ASCII byte set) silently \
2899 strips it at parse entry, and the value round-trips through `render` to \
2900 a *different* canonical form (`\"30s\"`) on first serialize — breaking \
2901 the THEORY.md Part V render-determinism contract every typed slot \
2902 carries. Strip every non-ASCII whitespace character (write `\"30s\"` \
2903 verbatim with only ASCII bytes)",
2904 cp = ch as u32
2905 )
2906 },
2907 )?;
2908 let s = s.trim();
2909 // Routed through the lifted
2910 // [`crate::render::split_magnitude_and_alpha_unit`] primitive —
2911 // the single-owner split every ASCII-alphabetic-unit typed-
2912 // magnitude codec in caixa-core (`limits::parse_byte_size` /
2913 // `limits::parse_duration` / this shared duration codec) shares.
2914 // See its docstring for the full sibling roster on the same
2915 // primitive altitude.
2916 let (num_part, unit) = crate::render::split_magnitude_and_alpha_unit(s);
2917 let num_trim = num_part.trim();
2918 // The canonical authoring form for every typed slot routed
2919 // through this shared codec — `:supervisor :restart-window`,
2920 // `:politicas :timeout`, `:politicas :circuit-breaker :window`
2921 // — is `<integer><unit>`. Every magnitude [`render`] emits is a
2922 // non-negative integer with no decimal point and no leading
2923 // sign, so the parser's accepted set must match for
2924 // serialize/deserialize to round-trip without canonical-form
2925 // drift. Until this gate landed the parser accepted any
2926 // `f64`-shaped magnitude (`"1.5s"` → 1500ms, `"1.0s"` → 1s,
2927 // `"0.5m"` → 30s, `"+30s"` → 30s) and serde silently round-
2928 // tripped the value to a *different* canonical string on the
2929 // next emit (`"1.5s"` → 1500ms → `"1500ms"`, `"1.0s"` → 1s →
2930 // `"1s"`, `"0.5m"` → 30s → `"30s"`, `"+30s"` → 30s → `"30s"`)
2931 // — breaking the THEORY.md Part V render-determinism contract
2932 // on three typed slots at once. Same canonical-form discipline
2933 // `crate::limits::parse_duration` (818dd38, the immediate
2934 // predecessor on the peer `:limits :wall-clock` codec) applies;
2935 // this gate lifts the discipline onto the shared codec that
2936 // backs the remaining three typed-duration slots in caixa-core.
2937 //
2938 // Strict canonical form: every byte of the magnitude is an
2939 // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
2940 // inputs the gate distinguishes "non-canonical-but-numeric"
2941 // (parses as f64 or i64 — surfaced with a self-locating
2942 // diagnostic naming the canonical authoring form, the
2943 // round-trip drift each rejected shape would produce on first
2944 // serialize, and the canonical-form remediation) from
2945 // "garbage" (parses as neither — surfaced with the existing
2946 // narrower "bad duration magnitude" wording so its diagnostic
2947 // shape remains stable for the parser-shape footgun case).
2948 // The pre-existing `num < 0.0` arm is now unreachable — the
2949 // digit-only gate strictly precedes magnitude parsing, and a
2950 // leading `-` is not an ASCII digit, so `"-30s"` lands on the
2951 // non-canonical-but-numeric branch with the `-30` named
2952 // verbatim in the diagnostic rather than the prior
2953 // value-laundered "negative duration in \"-30s\"" wording.
2954 //
2955 // Routed through the lifted
2956 // [`crate::render::is_digit_only_magnitude`] predicate — the
2957 // same source of truth the four peer typed-magnitude codec
2958 // sites share.
2959 let digit_only = crate::render::is_digit_only_magnitude(num_trim);
2960 if !digit_only {
2961 let numeric = num_trim.parse::<f64>().is_ok() || num_trim.parse::<i64>().is_ok();
2962 if numeric {
2963 return Err(format!(
2964 "duration: magnitude {num_trim:?} is not a non-negative integer — the \
2965 canonical authoring form for the typed duration slots routed through \
2966 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
2967 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
2968 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no decimal point and \
2969 no leading `+` / `-` sign. A fractional / decimal-shaped magnitude \
2970 (`\"1.5s\"`, `\"1.0s\"`, `\"0.5m\"`, `\"+30s\"`, `\"-30s\"`) round-trips \
2971 through `render` to a *different* canonical form (`\"1500ms\"`, `\"1s\"`, \
2972 `\"30s\"`, `\"30s\"`, `\"30s\"`) on first serialize — breaking the \
2973 THEORY.md Part V render-determinism contract every typed slot carries. \
2974 Pick an integer magnitude in the unit that divides cleanly (write \
2975 `\"1500ms\"` instead of `\"1.5s\"`; `\"30s\"` instead of `\"0.5m\"`)"
2976 ));
2977 }
2978 return Err(format!("bad duration magnitude in {s:?}"));
2979 }
2980 // Leading-zero arm — peer with the `rate_limit_codec` leading-
2981 // zero arm (4f46830) on the same canonical-form render-
2982 // determinism axis. The digit-only gate accepts `"030s"`,
2983 // `"00s"`, `"01h"`, `"0500ms"` as `u64::from_str` parses them
2984 // losslessly (= 30, 0, 1, 500), but `render` emits the leading-
2985 // zero-stripped form (`"30s"`, `"0s"`, `"1h"`, `"500ms"`) — a
2986 // *different* canonical string on the next emit, breaking the
2987 // THEORY.md Part V render-determinism contract the same way
2988 // `"+30s"` did before the leading-`+` arm landed. The single-
2989 // byte magnitude `"0"` (or `"0s"` / `"0ms"`) round-trips
2990 // losslessly through `render` (`render(Duration::ZERO)` emits
2991 // `"0s"`) — the downstream semantic-zero gates (e.g.
2992 // `SupervisorError::ZeroRestartWindow` on
2993 // `:supervisor :restart-window`,
2994 // `AplicacaoError::PolicyTimeoutZero` /
2995 // `PolicyCircuitBreakerWindowZero` on the typed `:politicas`
2996 // duration slots) refuse zero-magnitude authoring at the typed-
2997 // validate layer above, so the single-byte `"0"` stays in the
2998 // accepted set at this codec layer and the diagnostic
2999 // partitioning between canonical-form drift (this arm) and
3000 // semantic-zero (the downstream gates) remains stable.
3001 // Peer with the future leading-zero arms on the two remaining
3002 // typed-magnitude codecs the trajectory acknowledges:
3003 // `limits::parse_duration` backing `:limits :wall-clock`,
3004 // `limits::parse_byte_size` backing `:limits :memory` — each
3005 // carries the same canonical-form-drift class today; this
3006 // gate lands the discipline on the shared duration codec
3007 // first because the `rate_limit_codec` predecessor on the
3008 // same canonical-form-drift axis is the closest peer on the
3009 // trajectory.
3010 //
3011 // Routed through the lifted
3012 // [`crate::render::is_leading_zero_padded_magnitude`]
3013 // predicate — the same source of truth the four peer
3014 // typed-magnitude codec sites share.
3015 if crate::render::is_leading_zero_padded_magnitude(num_trim) {
3016 return Err(format!(
3017 "duration: magnitude {num_trim:?} has a non-canonical leading zero — the \
3018 canonical authoring form for the typed duration slots routed through \
3019 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
3020 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
3021 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no leading-zero padding \
3022 on the magnitude. A leading-zero magnitude (`\"030s\"`, `\"00s\"`, \
3023 `\"01h\"`, `\"0500ms\"`) round-trips through `render` to a *different* \
3024 canonical form (`\"30s\"`, `\"0s\"`, `\"1h\"`, `\"500ms\"`) on first \
3025 serialize — breaking the THEORY.md Part V render-determinism contract \
3026 every typed slot carries. Strip the leading zeros (write \
3027 `\"30s\"` instead of `\"030s\"`)"
3028 ));
3029 }
3030 // The digit-only gate guarantees every byte is `[0-9]`, and
3031 // the leading-zero arm above guarantees the magnitude is
3032 // either the single byte `"0"` or starts with `[1-9]`, so
3033 // the only way `u64::from_str` can fail here is overflow (the
3034 // magnitude exceeds `u64::MAX`). Surface that with an
3035 // overflow-shaped wording so the diagnostic names the offending
3036 // magnitude verbatim rather than collapsing onto the
3037 // non-canonical arm. The codec now operates on `u64` end-to-end
3038 // — every accepted magnitude is integer-exact; no f64 mantissa
3039 // drift between author-supplied magnitude and the consumer's
3040 // `Duration` value. Same shape `crate::limits::parse_duration`
3041 // (818dd38) carries on the peer `:limits :wall-clock` axis.
3042 let num: u64 = num_trim.parse::<u64>().map_err(|_| {
3043 format!("bad duration magnitude in {s:?} (digit-only magnitude overflows u64)")
3044 })?;
3045 // Route the `{"ms" | "s" | "" | "m" | "h"} → Duration`
3046 // unit-arm dispatch through the canonical
3047 // [`crate::render::duration_from_integer_magnitude_and_unit`]
3048 // primitive — the substrate-side single-owner unit-dispatch
3049 // table every typed-duration codec in caixa-core routes
3050 // through (peer: `crate::limits::parse_duration` backing
3051 // `:limits :wall-clock`). Every unit conversion is integer-
3052 // exact for an integer magnitude; overflow surfaces via the
3053 // typed `DurationUnitError::Overflow { multiplier }`
3054 // discriminant so this arm reconstructs the pre-lift
3055 // `"duration <num><unit> overflows u64 (magnitude × 60 …)"`
3056 // wording verbatim from `num` / `unit_trim` / the returned
3057 // `multiplier`, and the unknown-unit arm reconstructs the
3058 // pre-lift `"unknown duration unit \"<other>\""` wording from
3059 // the caller-scoped `unit_trim`. Load-bearing pinned by
3060 // `crate::render::tests::duration_from_integer_magnitude_and_unit_matches_pre_lift_unit_dispatch_table`.
3061 let unit_trim = unit.trim();
3062 let dur = crate::render::duration_from_integer_magnitude_and_unit(num, unit_trim).map_err(
3063 |e| match e {
3064 crate::render::DurationUnitError::Overflow { multiplier } => format!(
3065 "duration {num}{unit_trim} overflows u64 (magnitude × {multiplier} > 2^64-1)"
3066 ),
3067 crate::render::DurationUnitError::UnknownUnit => {
3068 format!("unknown duration unit {unit_trim:?}")
3069 }
3070 },
3071 )?;
3072 Ok(dur)
3073 }
3074
3075 /// Render a [`Duration`] in the canonical pleme-io duration string
3076 /// form (`"30s"`, `"1m"`, `"1h"`, `"500ms"`). The same form every
3077 /// caixa typed-duration slot serializes to and the same form K8s
3078 /// Gateway API HTTPRoute `timeouts` / `backendRequest` and Cilium
3079 /// EnvoyConfig per-route timeouts both expect (an integer
3080 /// followed by `s`/`m`/`h`/`ms`, no fractional values, no leading
3081 /// `+`). Lifted to `pub` so caixa-side renderers
3082 /// (`caixa-mesh::gateway_routes`'s :politicas :timeout overlay,
3083 /// the future per-:politicas `CiliumClusterwideEnvoyConfig`
3084 /// emitter, the future caixa-otel collector pipeline emitter) can
3085 /// consume the same canonical formatter without re-inlining the
3086 /// magnitude/unit decision tree (and inheriting the same drift
3087 /// footguns: a subtly different `300ms` vs `0.3s` rendering breaks
3088 /// downstream apply-time parsing in non-obvious ways).
3089 pub fn render(d: Duration) -> String {
3090 let total_ms = d.as_millis();
3091 if total_ms == 0 {
3092 return "0s".into();
3093 }
3094 if total_ms.is_multiple_of(3600 * 1000) {
3095 return format!("{}h", total_ms / (3600 * 1000));
3096 }
3097 if total_ms.is_multiple_of(60 * 1000) {
3098 return format!("{}m", total_ms / (60 * 1000));
3099 }
3100 if total_ms.is_multiple_of(1000) {
3101 return format!("{}s", total_ms / 1000);
3102 }
3103 format!("{total_ms}ms")
3104 }
3105
3106 /// True iff `d` round-trips losslessly through [`render`] + [`parse`].
3107 ///
3108 /// [`render`] truncates a `Duration` to `as_millis()` before picking the
3109 /// largest divisor unit, so any sub-millisecond residue
3110 /// (`d.subsec_nanos() % 1_000_000 != 0`) silently breaks the THEORY.md
3111 /// §V.2.7 render-determinism contract:
3112 ///
3113 /// - `Duration::from_micros(1500)` (= `1_500_000` ns) → `as_millis() == 1`
3114 /// → renders `"1ms"` → parses back to `Duration::from_millis(1)` =
3115 /// `1_000_000` ns ≠ original `1_500_000` ns;
3116 /// - `Duration::from_nanos(1)` (= 1 ns) → `as_millis() == 0` →
3117 /// renders the literal `"0s"`, which the per-axis zero-floor gate
3118 /// on every typed-`Duration` slot then rejects on re-validate.
3119 ///
3120 /// Lifted to a `pub` predicate next to the [`render`] / [`parse`] pair so
3121 /// the codec's round-trippable accepted set lives in exactly one place —
3122 /// every typed-`Duration` slot that routes through this shared codec
3123 /// (`SupervisorSpec::restart_window` via [`super::duration_codec`],
3124 /// [`crate::MeshPolicy::timeout`] / [`crate::CircuitBreaker::window`] via
3125 /// `supervisor::duration_codec` + [`super::duration_codec_required`]) and
3126 /// every typed-`Duration` slot whose own codec shares the same
3127 /// `as_millis()`-truncation shape ([`crate::LimitsSpec::wall_clock`] via
3128 /// [`crate::limits`]'s in-module `parse_duration` / `render_duration`
3129 /// pair) calls this predicate from its `validate()` to bracket the
3130 /// accepted set against the codec's accepted set, structurally. Drift
3131 /// between the codec's granularity and any typed slot's accepted set is
3132 /// then a single-source-of-truth edit at this predicate rather than a
3133 /// silent round-trip break the next consumer discovers at apply time.
3134 ///
3135 /// Peer of [`crate::aplicacao::POLICY_RETRIES_MAX`] /
3136 /// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] and the
3137 /// `is_dns_1123_label` / `is_canonical_rate_limit_window` predicate
3138 /// family — same "typed-slot's valid set matches its codec's accepted
3139 /// set, structurally" discipline carried at the codec layer.
3140 #[must_use]
3141 pub fn is_integer_millisecond_duration(d: Duration) -> bool {
3142 d.subsec_nanos().is_multiple_of(1_000_000)
3143 }
3144}
3145
3146/// Required-Duration variant for fields that aren't Option<Duration>.
3147pub mod duration_codec_required {
3148 use super::Duration;
3149 use serde::{Deserialize, Deserializer, Serializer};
3150
3151 pub fn serialize<S: Serializer>(v: &Duration, s: S) -> Result<S::Ok, S::Error> {
3152 s.serialize_str(&super::duration_codec::render(*v))
3153 }
3154
3155 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
3156 let s = String::deserialize(d)?;
3157 super::duration_codec::parse(&s).map_err(serde::de::Error::custom)
3158 }
3159}
3160
3161#[cfg(test)]
3162mod tests {
3163 use super::*;
3164
3165 fn child(name: &str, ver: &str, restart: RestartPolicy) -> ChildSpec {
3166 ChildSpec {
3167 caixa: name.into(),
3168 versao: ver.into(),
3169 restart,
3170 }
3171 }
3172
3173 #[test]
3174 fn child_spec_string_scalar_accessor_pair_is_const_fn() {
3175 // Fail-before-pass-after pin on [`ChildSpec::nome`] +
3176 // [`ChildSpec::versao_requirement`]'s `const`-eval-surface
3177 // posture. Each accessor projects the per-`:children :caixa`
3178 // / per-`:children :versao` [`String`] storage through the
3179 // `pub const fn` [`String::as_str`] (const-stable since Rust
3180 // 1.87, well within the workspace MSRV) — any future
3181 // accidental downgrade to non-`const` fails the corresponding
3182 // `<name>_via_const_fn` wrapper at caixa-core build time with
3183 // E0015 (`cannot call non-const method`), strictly stronger
3184 // than a runtime `assert!`. Sibling of the peer
3185 // per-M2/M3/universal-axis `String → &str` scalar-accessor
3186 // family pins on the sibling `const`-eval-surface passes
3187 // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
3188 // top-level manifest, [`crate::CaixaVersion::as_str`] at the
3189 // typed-newtype wrapper, [`crate::aplicacao::Membro::nome`] /
3190 // [`crate::aplicacao::Membro::versao_requirement`] at the M3
3191 // membership axis, [`crate::aplicacao::Entrada::hostname`] /
3192 // [`crate::aplicacao::Entrada::destination`] at the M3
3193 // ingress axis,
3194 // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
3195 // M2 upgrade axis, [`crate::dep::Dep::nome`] /
3196 // [`crate::dep::Dep::versao_requirement`] at the dep-graph
3197 // axis, and the per-`:contratos`
3198 // [`crate::aplicacao::WitContract::source`] /
3199 // [`crate::aplicacao::WitContract::destination`] /
3200 // [`crate::aplicacao::WitContract::world_ref`] trio the
3201 // sibling pin at 279823b already anchors).
3202 const fn nome_via_const_fn(c: &ChildSpec) -> &str {
3203 c.nome()
3204 }
3205 const fn versao_via_const_fn(c: &ChildSpec) -> &str {
3206 c.versao_requirement()
3207 }
3208 for (caixa, versao) in [
3209 ("worker-a", "^0.1"),
3210 ("worker-b", "~0.2.3"),
3211 ("collector", "*"),
3212 ] {
3213 let c = child(caixa, versao, RestartPolicy::Permanent);
3214 assert_eq!(nome_via_const_fn(&c), c.nome());
3215 assert_eq!(versao_via_const_fn(&c), c.versao_requirement());
3216 assert_eq!(c.nome(), caixa);
3217 assert_eq!(c.versao_requirement(), versao);
3218 }
3219 }
3220
3221 #[test]
3222 fn supervisor_children_slice_return_accessor_is_const_fn() {
3223 // Fail-before-pass-after pin on [`SupervisorSpec::children`]'s
3224 // `const`-eval-surface posture. The accessor destructures the
3225 // per-`:children` `Vec<ChildSpec>` storage through the
3226 // `pub const fn` [`Vec::as_slice`] (const-stable since Rust
3227 // 1.66, well within the workspace MSRV) — any future
3228 // accidental downgrade to non-`const` fails
3229 // `children_via_const_fn` at caixa-core build time with E0015
3230 // (`cannot call non-const method`), strictly stronger than a
3231 // runtime `assert!`. Sibling of the peer per-M3-mesh-slot
3232 // `Vec → &[T]` slice-return accessor family pin
3233 // [`crate::aplicacao::tests::m3_reference_return_accessor_family_is_const_fn`]
3234 // on the M3 mesh-slot per-`:clusters` / per-`:paths` /
3235 // per-`:membros` / per-`:contratos` slice-return axes, and of
3236 // the peer M2 upgrade-appup axis pin
3237 // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
3238 // on the per-`:upgrade-from :instructions` slice-return axis.
3239 const fn children_via_const_fn(s: &SupervisorSpec) -> &[ChildSpec] {
3240 s.children()
3241 }
3242 // Sweep both the empty-children (leaf-supervisor with no
3243 // static children — the `SimpleOneForOne` dynamic-child
3244 // arm's canonical shape) and the populated-children
3245 // (`OneForOne` / `OneForAll` / `RestForOne` static-child
3246 // arm's canonical shape) axes so the accessor carries a
3247 // const-dispatch pin on both arms.
3248 let s_empty = SupervisorSpec {
3249 estrategia: RestartStrategy::SimpleOneForOne,
3250 max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
3251 restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3252 children: vec![],
3253 };
3254 assert!(children_via_const_fn(&s_empty).is_empty());
3255 assert_eq!(children_via_const_fn(&s_empty), s_empty.children());
3256 let s_full = SupervisorSpec {
3257 estrategia: RestartStrategy::OneForOne,
3258 max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
3259 restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3260 children: vec![
3261 child("worker-a", "^0.1", RestartPolicy::Permanent),
3262 child("worker-b", "~0.2.3", RestartPolicy::Transient),
3263 child("collector", "*", RestartPolicy::Temporary),
3264 ],
3265 };
3266 assert_eq!(children_via_const_fn(&s_full).len(), 3);
3267 assert_eq!(children_via_const_fn(&s_full), s_full.children());
3268 }
3269
3270 #[test]
3271 fn default_has_one_for_one_and_5_restarts_in_60s() {
3272 let s = SupervisorSpec::default();
3273 assert_eq!(s.estrategia, RestartStrategy::OneForOne);
3274 assert_eq!(s.max_restarts, 5);
3275 assert_eq!(s.restart_window, Some(Duration::from_secs(60)));
3276 assert!(s.children.is_empty());
3277 }
3278
3279 #[test]
3280 fn validate_one_for_one_requires_children() {
3281 let mut s = SupervisorSpec::default();
3282 s.children = vec![];
3283 assert!(matches!(
3284 s.validate().unwrap_err(),
3285 SupervisorError::NoChildren { .. }
3286 ));
3287 s.children = vec![child("worker", "^0.1", RestartPolicy::Permanent)];
3288 s.validate().unwrap();
3289 }
3290
3291 #[test]
3292 fn validate_simple_one_for_one_forbids_static_children() {
3293 let mut s = SupervisorSpec {
3294 estrategia: RestartStrategy::SimpleOneForOne,
3295 ..SupervisorSpec::default()
3296 };
3297 s.children
3298 .push(child("w", "^0.1", RestartPolicy::Permanent));
3299 assert_eq!(
3300 s.validate().unwrap_err(),
3301 SupervisorError::SimpleOneForOneWithStaticChildren
3302 );
3303 s.children.clear();
3304 s.validate().unwrap();
3305 }
3306
3307 #[test]
3308 fn validate_rejects_zero_max_restarts() {
3309 let s = SupervisorSpec {
3310 max_restarts: 0,
3311 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3312 ..SupervisorSpec::default()
3313 };
3314 assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
3315 }
3316
3317 // ── upper-cap: SUPERVISOR_MAX_RESTARTS_MAX brackets the typed slot ─────
3318 //
3319 // The cap arm lifts the `:politicas :circuit-breaker :max-failures` /
3320 // `POLICY_BREAKER_MAX_FAILURES_MAX` (2b51ace) discipline onto the peer
3321 // `:supervisor :max-restarts` axis — both fields are "trip the
3322 // next-higher protection layer after N events in a rolling window"
3323 // counters with identical degenerate-at-the-high-end shape, so the
3324 // typed-slot's accepted set lies in `1..=1000` on the supervisor side
3325 // exactly as it lies in `1..=1000` on the breaker side.
3326
3327 #[test]
3328 fn validate_rejects_max_restarts_above_cap() {
3329 // The fail-before-pass-after pin: `SUPERVISOR_MAX_RESTARTS_MAX +
3330 // 1` is structurally one past the cap and silently passed
3331 // validate on every pre-gate codebase because the typed slot's
3332 // only check was the zero-floor arm. The no-op-supervisor vector
3333 // only surfaced at the runtime substrate (Erlang/OTP
3334 // MaxIntensity/Period ratio, the future wasm-operator's
3335 // per-supervisor restart-intensity counter) far from the source
3336 // caixa.lisp with no field naming the offending supervisor.
3337 let s = SupervisorSpec {
3338 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3339 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3340 ..SupervisorSpec::default()
3341 };
3342 assert_eq!(
3343 s.validate().unwrap_err(),
3344 SupervisorError::MaxRestartsExceedsCap {
3345 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3346 }
3347 );
3348 }
3349
3350 #[test]
3351 fn validate_rejects_max_restarts_far_above_cap() {
3352 // The `u32::MAX` worst case — the four-billion-restart
3353 // threshold a typo (`:max-restarts 4294967295`) or a
3354 // struct-literal copy-paste lands in the slot. Pin the cap
3355 // arm's coverage explicitly across the full `u32` overflow so
3356 // a future relaxation that drops the upper bound surfaces
3357 // here. Same shape every other typed-cap arm on this surface
3358 // carries (POLICY_BREAKER_MAX_FAILURES_MAX,
3359 // POLICY_RETRIES_MAX, POLICY_RATE_LIMIT_MAX).
3360 let s = SupervisorSpec {
3361 max_restarts: u32::MAX,
3362 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3363 ..SupervisorSpec::default()
3364 };
3365 assert_eq!(
3366 s.validate().unwrap_err(),
3367 SupervisorError::MaxRestartsExceedsCap {
3368 max_restarts: u32::MAX,
3369 }
3370 );
3371 }
3372
3373 #[test]
3374 fn validate_accepts_max_restarts_at_cap() {
3375 // The boundary value — exactly SUPERVISOR_MAX_RESTARTS_MAX —
3376 // must validate. The cap is inclusive on the top edge,
3377 // matching the POLICY_BREAKER_MAX_FAILURES_MAX /
3378 // POLICY_RETRIES_MAX / LIMITS_MEMORY_WASM32_MAX_BYTES
3379 // discipline on the sibling capped axes. Pin the boundary
3380 // explicitly so a future off-by-one tightening
3381 // (`>= SUPERVISOR_MAX_RESTARTS_MAX` instead of `>`) surfaces
3382 // here as a test failure rather than a silent contract
3383 // narrowing.
3384 let s = SupervisorSpec {
3385 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX,
3386 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3387 ..SupervisorSpec::default()
3388 };
3389 s.validate()
3390 .expect("max_restarts == SUPERVISOR_MAX_RESTARTS_MAX must validate");
3391 }
3392
3393 #[test]
3394 fn validate_accepts_max_restarts_typical_values() {
3395 // The documented production-playbook band positive-control
3396 // sweep — every value Erlang/OTP / Elixir / Riak Core /
3397 // RabbitMQ recommend (1..=100) must pass, plus a sweep
3398 // through the hyperscale band (200, 500, 1000) the cap
3399 // accepts. Pin the inclusive validated set explicitly so a
3400 // future tightening of the ceiling surfaces here.
3401 for n in [1u32, 3, 5, 10, 20, 50, 100, 200, 500, 1000] {
3402 let s = SupervisorSpec {
3403 max_restarts: n,
3404 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3405 ..SupervisorSpec::default()
3406 };
3407 s.validate()
3408 .unwrap_or_else(|e| panic!("max_restarts={n} must validate; got {e:?}"));
3409 }
3410 }
3411
3412 #[test]
3413 fn zero_max_restarts_takes_precedence_over_cap() {
3414 // The cross-arm ordering pin: `0` is structurally outside
3415 // both `1..` (zero-floor) and `..=SUPERVISOR_MAX_RESTARTS_MAX`
3416 // (cap), but the zero-floor diagnostic is the more
3417 // self-locating one (it directly names the counter-axis
3418 // remediation), so the validate gate must fire on zero first.
3419 // Same shape every other zero-then-shape ordering on this
3420 // surface uses (PolicyRetriesZero then
3421 // PolicyRetriesExceedsCap; PolicyBreakerZeroFailures then
3422 // PolicyBreakerMaxFailuresExceedsCap).
3423 let s = SupervisorSpec {
3424 max_restarts: 0,
3425 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3426 ..SupervisorSpec::default()
3427 };
3428 assert_eq!(
3429 s.validate().unwrap_err(),
3430 SupervisorError::ZeroMaxRestarts,
3431 "max_restarts == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
3432 );
3433 }
3434
3435 #[test]
3436 fn max_restarts_cap_takes_precedence_over_restart_window_gates() {
3437 // The cross-arm ordering pin between the cap and the sibling
3438 // `:restart-window` gates (zero-window, canonical-window). A
3439 // supervisor carrying both an over-cap `max_restarts` AND a
3440 // structurally invalid window (zero, sub-ms) must surface the
3441 // cap diagnostic first — the cap arm is wired immediately
3442 // after the zero-restart arm and strictly before the window
3443 // arms, so the offending value the diagnostic names matches
3444 // the order the author would discover the gates by reading
3445 // top-to-bottom through `SupervisorSpec::validate`. Pin the
3446 // order so a future refactor that reorders the arms surfaces
3447 // here as a test failure rather than a silent diagnostic
3448 // regression. Peer of
3449 // `circuit_breaker_max_failures_cap_takes_precedence_over_window_gates`
3450 // on the sibling `:politicas :circuit-breaker` slot.
3451 let s = SupervisorSpec {
3452 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3453 restart_window: Some(Duration::ZERO),
3454 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3455 ..SupervisorSpec::default()
3456 };
3457 assert_eq!(
3458 s.validate().unwrap_err(),
3459 SupervisorError::MaxRestartsExceedsCap {
3460 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
3461 },
3462 "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
3463 );
3464 }
3465
3466 #[test]
3467 fn max_restarts_cap_diagnostic_carries_offending_value() {
3468 // The diagnostic-shape pin: the offending `u32` is carried
3469 // verbatim into the `SupervisorError::MaxRestartsExceedsCap`
3470 // variant so the surfaced error message names the value the
3471 // author wrote (`":supervisor :max-restarts (50000) exceeds the
3472 // supervisor-policy ceiling …"`), not just the cap. Same
3473 // self-locating diagnostic shape every other typed-cap arm on
3474 // this surface carries
3475 // (`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` carries
3476 // the offending failure count verbatim,
3477 // `AplicacaoError::PolicyRetriesExceedsCap` carries the offending
3478 // retries count verbatim).
3479 let s = SupervisorSpec {
3480 max_restarts: 50_000,
3481 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
3482 ..SupervisorSpec::default()
3483 };
3484 let err = s.validate().unwrap_err();
3485 assert!(
3486 matches!(
3487 err,
3488 SupervisorError::MaxRestartsExceedsCap {
3489 max_restarts: 50_000
3490 }
3491 ),
3492 "got {err:?}"
3493 );
3494 let msg = err.to_string();
3495 assert!(
3496 msg.contains("50000"),
3497 ":supervisor :max-restarts cap diagnostic must carry the offending value verbatim (got: {msg})"
3498 );
3499 }
3500
3501 #[test]
3502 fn supervisor_max_restarts_default_pins_otp_canonical_value() {
3503 // Pin [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] at `5` — the
3504 // Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
3505 // half of Learn You Some Erlang's worker-supervisor default,
3506 // sibling of the `60s` `Period` half that the paired
3507 // [`Default for SupervisorSpec`] impl already pins on the
3508 // sibling `restart_window` axis. Pinning the literal here
3509 // surfaces a future rebrand (a tightening to Elixir's `3`,
3510 // a widening to a per-cluster overlay the operator pins
3511 // through a future `:max-restarts-overrides` slot) as a
3512 // deliberate test edit, not a silent contract migration.
3513 // Peer of the sibling
3514 // [`supervisor_max_restarts_cap_pins_canonical_value`]
3515 // upper-bracket pin on the same axis.
3516 assert_eq!(SUPERVISOR_MAX_RESTARTS_DEFAULT, 5);
3517 }
3518
3519 #[test]
3520 fn default_max_restarts_helper_routes_through_lifted_default() {
3521 // Composition pin: the private `default_max_restarts()`
3522 // serde-`#[serde(default = "…")]` helper on
3523 // [`SupervisorSpec::max_restarts`] must route through the
3524 // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
3525 // typed `pub const` rather than a raw `5` literal. Prior to
3526 // the lift the helper carried an inline `5` with no compile-
3527 // time link back to the shared default, so the wire-format
3528 // author-omitted arm and the caixa-core
3529 // [`crate::manifest::Caixa::supervisor_view`] fold's `unwrap_or(5)`
3530 // arm could silently split on any future default rebrand.
3531 // Byte-parity against the lifted constant closes the split.
3532 assert_eq!(default_max_restarts(), SUPERVISOR_MAX_RESTARTS_DEFAULT);
3533 }
3534
3535 #[test]
3536 fn supervisor_spec_default_max_restarts_routes_through_lifted_default() {
3537 // Composition pin: the [`Default for SupervisorSpec`] impl's
3538 // struct-literal `max_restarts` field must route through the
3539 // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
3540 // typed `pub const` (via the private helper this test's
3541 // sibling `default_max_restarts_helper_routes_through_lifted_default`
3542 // already pins onto the constant). Structurally: every
3543 // `SupervisorSpec::default()` call must yield a
3544 // `max_restarts` field byte-equal to the lifted constant
3545 // (the two paired defaults — the serde-side wire-format arm
3546 // and the struct-literal default arm — cannot silently split
3547 // on any future default rebrand). Peer of the sibling
3548 // `default_has_one_for_one_and_5_restarts_in_60s` shape pin
3549 // — this pin closes the byte-parity arm on the two paired
3550 // altitude entry points onto the shared substrate constant.
3551 assert_eq!(
3552 SupervisorSpec::default().max_restarts(),
3553 SUPERVISOR_MAX_RESTARTS_DEFAULT,
3554 );
3555 }
3556
3557 #[test]
3558 fn supervisor_restart_window_default_pins_otp_canonical_value() {
3559 // Pin [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] at `60s` — the
3560 // Erlang/OTP-canonical `{intensity, 5, 60}` `Period` half of
3561 // Learn You Some Erlang's worker-supervisor default, paired
3562 // with the sibling `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5`
3563 // `MaxIntensity` half this constant is the sliding-window
3564 // denominator of on the same `MaxIntensity / Period`
3565 // restart-intensity ratio. Pinning the literal here surfaces a
3566 // future coherent rebrand of the paired default (Elixir's
3567 // `{max_restarts: 3, max_seconds: 5}`, a per-cluster overlay
3568 // the operator pins through a future
3569 // `:restart-window-overrides` slot) as a deliberate test edit,
3570 // not a silent contract migration. Peer of the sibling
3571 // [`supervisor_max_restarts_default_pins_otp_canonical_value`]
3572 // paired-half pin on the same OTP-canonical default and the
3573 // [`supervisor_restart_window_cap_pins_canonical_value`]
3574 // upper-bracket pin on the same axis.
3575 assert_eq!(SUPERVISOR_RESTART_WINDOW_DEFAULT, Duration::from_secs(60),);
3576 }
3577
3578 #[test]
3579 fn supervisor_spec_default_restart_window_routes_through_lifted_default() {
3580 // Composition pin: the [`Default for SupervisorSpec`] impl's
3581 // struct-literal `restart_window` field must route through the
3582 // substrate-canonical [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3583 // typed `pub const` rather than a raw
3584 // `Duration::from_secs(60)` literal. Prior to this lift the
3585 // paired `{intensity, 5, 60}` OTP-canonical default was split
3586 // across two altitudes with no compile-time link between the
3587 // halves — the `MaxIntensity` half rode through the lifted
3588 // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant while the
3589 // `Period` half rode as an open-coded literal at the
3590 // composition site, so a future coherent rebrand of the paired
3591 // canonical would have had to migrate one half through the
3592 // constant and the other through a raw literal in lockstep.
3593 // Byte-parity against the lifted constant on the `Period` half
3594 // closes the split — the paired OTP-canonical default now
3595 // migrates as one unit on any future axis change. Peer of the
3596 // sibling
3597 // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
3598 // byte-parity pin on the paired `MaxIntensity` half.
3599 assert_eq!(
3600 SupervisorSpec::default().restart_window(),
3601 Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3602 );
3603 }
3604
3605 #[test]
3606 fn supervisor_estrategia_default_pins_otp_canonical_value() {
3607 // Pin [`SUPERVISOR_ESTRATEGIA_DEFAULT`] at [`RestartStrategy::OneForOne`]
3608 // — the Erlang/OTP-canonical `one_for_one` half of Learn You Some
3609 // Erlang's `{one_for_one, intensity, 5, 60}` worker-supervisor
3610 // canonical default, paired with the sibling
3611 // `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5` `MaxIntensity` half and the
3612 // sibling `SUPERVISOR_RESTART_WINDOW_DEFAULT` `60s` `Period` half
3613 // this constant is the strategy discriminator of on the same
3614 // OTP-canonical worker-supervisor default. Pinning the arm here
3615 // surfaces a future coherent rebrand of the paired triple (Elixir's
3616 // `{:one_for_one, max_restarts: 3, max_seconds: 5}` on the sibling
3617 // intensity/period axes leaving this strategy arm untouched, an OTP
3618 // `rest_for_one` widening once the substrate discovers startup-
3619 // order-coupled child cohorts as the more common worker-supervisor
3620 // shape, a per-cluster overlay the operator pins through a future
3621 // `:estrategia-overrides` slot the MESH-COMPOSITION §III.2
3622 // supervision-canary roadmap acknowledges) as a deliberate test
3623 // edit, not a silent contract migration. Peer of the sibling
3624 // [`supervisor_max_restarts_default_pins_otp_canonical_value`] +
3625 // [`supervisor_restart_window_default_pins_otp_canonical_value`]
3626 // paired-half pins on the same OTP-canonical default.
3627 assert_eq!(SUPERVISOR_ESTRATEGIA_DEFAULT, RestartStrategy::OneForOne);
3628 }
3629
3630 #[test]
3631 fn restart_strategy_default_routes_through_lifted_default() {
3632 // Composition pin: the [`Default for RestartStrategy`] impl's
3633 // return arm must route through the substrate-canonical
3634 // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
3635 // a raw `Self::OneForOne` arm. Prior to the lift the impl carried
3636 // an inline `Self::OneForOne` with no compile-time link back to
3637 // the shared OTP-canonical `one_for_one` strategy the paired
3638 // [`Default for SupervisorSpec`] impl's struct-literal `estrategia`
3639 // field and the [`crate::manifest::Caixa::supervisor_view`] fold's
3640 // `.unwrap_or_default()` (now
3641 // `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)`) arm both key off —
3642 // so a future rebrand of the OTP-canonical strategy default (an
3643 // OTP `rest_for_one` widening once the substrate discovers
3644 // startup-order-coupled child cohorts as the more common worker-
3645 // supervisor shape, a per-cluster overlay the operator pins
3646 // through a future `:estrategia-overrides` slot) would have had to
3647 // be threaded through the `Default` impl and the two peer routes
3648 // in lockstep or the three consumers would silently split. Byte-
3649 // parity against the lifted constant closes the split. Peer of
3650 // the sibling
3651 // [`default_max_restarts_helper_routes_through_lifted_default`] +
3652 // [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
3653 // composition pins on the paired `MaxIntensity` + `Period` halves.
3654 assert_eq!(RestartStrategy::default(), SUPERVISOR_ESTRATEGIA_DEFAULT,);
3655 }
3656
3657 #[test]
3658 fn supervisor_spec_default_estrategia_routes_through_lifted_default() {
3659 // Composition pin: the [`Default for SupervisorSpec`] impl's
3660 // struct-literal `estrategia` field must route through the
3661 // substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed
3662 // `pub const` (either directly, or via the
3663 // [`RestartStrategy::default`] impl that the sibling
3664 // `restart_strategy_default_routes_through_lifted_default` pin
3665 // already routes onto the constant). Structurally: every
3666 // `SupervisorSpec::default()` call must yield an `estrategia`
3667 // field byte-equal to the lifted constant (the three paired
3668 // defaults — the [`Default for RestartStrategy`] impl arm, the
3669 // struct-literal default arm here, and the
3670 // [`crate::manifest::Caixa::supervisor_view`] fold arm — cannot
3671 // silently split on any future default rebrand). Peer of the
3672 // sibling
3673 // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
3674 // + [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
3675 // byte-parity pins on the paired `MaxIntensity` + `Period` halves
3676 // of the same `SupervisorSpec::default()` composed altitude.
3677 assert_eq!(
3678 SupervisorSpec::default().estrategia(),
3679 SUPERVISOR_ESTRATEGIA_DEFAULT,
3680 );
3681 }
3682
3683 #[test]
3684 fn supervisor_spec_default_routes_through_otp_canonical_ctor() {
3685 // Composition pin: the [`Default for SupervisorSpec`] impl must
3686 // route through the substrate-canonical
3687 // [`SupervisorSpec::otp_canonical`] `pub const fn` constructor
3688 // rather than a re-hand-authored struct-literal cascade. Sharpens
3689 // the sibling per-arm
3690 // `supervisor_spec_default_*_routes_through_lifted_default` pins
3691 // from a per-field lift into a whole-struct one-source-of-truth
3692 // pin — the derived-until-now [`Default::default`] and the
3693 // [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
3694 // construction, not by coincidence.
3695 //
3696 // A future extension of the OTP-canonical baseline (a fifth
3697 // `restart_intensity` field the Erlang/OTP `#supervisor` record
3698 // grows, a per-child-cohort split of the `restart_window` /
3699 // `max_restarts` pair, an M4 `mesh.pleme.io/v1alpha1/Supervisor`
3700 // CR materializer's admission-time overlay pass) reaches both
3701 // paths through exactly one edit on
3702 // [`SupervisorSpec::otp_canonical`] — the derived path could
3703 // silently disagree with the constructor's shape on any new
3704 // field whose [`Default::default`] resolves to a different arm
3705 // than the OTP-canonical baseline the constructor names, while
3706 // this delegated impl reaches the constructor directly and
3707 // picks up every future extension by construction.
3708 //
3709 // Fourth peer on the M2 / M3 typed-slot-spec
3710 // [`Default`]-through-const-ctor fold family — sibling of the
3711 // [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
3712 // (abd52c2), [`crate::aplicacao::MeshPolicy`]
3713 // [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`]
3714 // (91641a4), and [`crate::BehaviorSpec`]
3715 // [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c)
3716 // per-`Option`-only-typed-slot folds — extended here onto the
3717 // M2 supervisor-slot [`SupervisorSpec`] whose canonical baseline
3718 // is not "everything `None`" but the Erlang/OTP-canonical
3719 // `{one_for_one, 5, 60}` worker-supervisor triple.
3720 assert_eq!(SupervisorSpec::default(), SupervisorSpec::otp_canonical());
3721 }
3722
3723 #[test]
3724 fn supervisor_spec_otp_canonical_byte_equals_default() {
3725 // Value pin: [`SupervisorSpec::otp_canonical`] must byte-equal
3726 // the hand-authored `{one_for_one, 5, 60, []}` OTP-canonical
3727 // baseline the sibling `default_has_one_for_one_and_5_restarts_in_60s`
3728 // pin already asserts against the [`Default::default`] path.
3729 // Sharpens the pair-invariant into a per-constructor pin so a
3730 // future extension of [`SupervisorSpec`] with a fifth field
3731 // whose OTP-canonical shape is non-`Default::default`-equivalent
3732 // trips at caixa-core test time rather than at a downstream
3733 // consumer that composed [`SupervisorSpec::otp_canonical`] with
3734 // [`SupervisorSpec::validate`] as its "canonical baseline
3735 // seed".
3736 let canonical = SupervisorSpec::otp_canonical();
3737 assert_eq!(canonical.estrategia, RestartStrategy::OneForOne);
3738 assert_eq!(canonical.max_restarts, 5);
3739 assert_eq!(canonical.restart_window, Some(Duration::from_secs(60)));
3740 assert!(canonical.children.is_empty());
3741 }
3742
3743 #[test]
3744 fn supervisor_spec_otp_canonical_is_usable_in_const_context() {
3745 // Const-context pin: [`SupervisorSpec::otp_canonical`] must
3746 // remain callable from a `const`-bound position so downstream
3747 // `const`-context callers wanting a canonical OTP-baseline seed
3748 // can construct one at compile time without runtime dispatch on
3749 // the derived [`Default::default`]. Peer of the sibling
3750 // `pub const fn` [`crate::LimitsSpec::empty`] /
3751 // [`crate::aplicacao::MeshPolicy::empty`] /
3752 // [`crate::BehaviorSpec::empty`] constructors on the sibling
3753 // typed-slot-spec `pub const fn` axis. If a future edit breaks
3754 // the `const`-eligibility of [`SupervisorSpec::otp_canonical`]
3755 // (a non-`const` field-default helper, a non-`const`-stable
3756 // container type promotion), this evaluation fails at
3757 // build time on this file rather than at a downstream
3758 // `const`-context call site.
3759 const CANONICAL: SupervisorSpec = SupervisorSpec::otp_canonical();
3760 assert_eq!(CANONICAL.estrategia, SUPERVISOR_ESTRATEGIA_DEFAULT);
3761 assert_eq!(CANONICAL.max_restarts, SUPERVISOR_MAX_RESTARTS_DEFAULT);
3762 assert_eq!(
3763 CANONICAL.restart_window,
3764 Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3765 );
3766 assert!(CANONICAL.children.is_empty());
3767 }
3768
3769 #[test]
3770 fn supervisor_child_restart_default_pins_otp_canonical_value() {
3771 // Pin [`SUPERVISOR_CHILD_RESTART_DEFAULT`] at
3772 // [`RestartPolicy::Permanent`] — Erlang/OTP's `permanent`
3773 // worker-child restart type (`{ChildId, StartFunc, permanent, …}`
3774 // in a `supervisor`'s `init/1` child-spec tuple), the per-child
3775 // half of the same OTP-shape supervisor-tree default set whose
3776 // per-`:supervisor` halves the sibling
3777 // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
3778 // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] /
3779 // [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] constants pin. Pinning the
3780 // arm here surfaces a future rebrand of the per-child default (an
3781 // OTP-`transient` widening once the substrate discovers clean-
3782 // completion-aware children as the more common child shape, a
3783 // per-cluster overlay the operator pins through a future
3784 // `:restart-overrides` slot the MESH-COMPOSITION §III.2
3785 // supervision-canary roadmap acknowledges) as a deliberate test
3786 // edit, not a silent contract migration. Peer of the sibling
3787 // [`supervisor_estrategia_default_pins_otp_canonical_value`] /
3788 // [`supervisor_max_restarts_default_pins_otp_canonical_value`] /
3789 // [`supervisor_restart_window_default_pins_otp_canonical_value`]
3790 // value pins on the per-`:supervisor` halves.
3791 assert_eq!(SUPERVISOR_CHILD_RESTART_DEFAULT, RestartPolicy::Permanent);
3792 }
3793
3794 #[test]
3795 fn restart_policy_default_routes_through_lifted_default() {
3796 // Composition pin: the [`Default for RestartPolicy`] impl's return
3797 // arm must route through the substrate-canonical
3798 // [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const` rather
3799 // than a raw `Self::Permanent` arm. Prior to the lift the impl
3800 // carried an inline `Self::Permanent` with no compile-time link
3801 // back to the OTP-shape supervisor-tree default set whose three
3802 // per-`:supervisor` halves already rode through lifted constants
3803 // — so a future coherent rebrand of the set would have had to
3804 // migrate three halves through typed constants and this fourth
3805 // through a raw enum arm in lockstep or the supervisor-level and
3806 // child-level defaults would silently drift apart. Byte-parity
3807 // against the lifted constant closes the split. Peer of the
3808 // sibling
3809 // [`restart_strategy_default_routes_through_lifted_default`]
3810 // composition pin on the per-`:supervisor` `:estrategia` axis.
3811 assert_eq!(RestartPolicy::default(), SUPERVISOR_CHILD_RESTART_DEFAULT);
3812 }
3813
3814 #[test]
3815 fn child_spec_serde_default_restart_routes_through_lifted_default() {
3816 // Composition pin: the serde-side `#[serde(default)]` on
3817 // [`ChildSpec::restart`] — the wire-format author-omitted
3818 // `:children :restart` arm — must resolve onto the substrate-
3819 // canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const`
3820 // (via the [`Default for RestartPolicy`] impl the sibling
3821 // `restart_policy_default_routes_through_lifted_default` pin
3822 // already routes onto the constant). Structurally: a `ChildSpec`
3823 // deserialized from a payload that omits the `restart` key must
3824 // yield a `restart` field byte-equal to the lifted constant, so
3825 // the wire-format author-omitted arm and the
3826 // [`RestartPolicy::default`] impl arm cannot silently split on any
3827 // future default rebrand. Peer of the sibling
3828 // [`supervisor_spec_default_estrategia_routes_through_lifted_default`]
3829 // / [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
3830 // / [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
3831 // byte-parity pins on the per-`:supervisor` halves of the same
3832 // author-omitted-slot resolution surface.
3833 let omitted: ChildSpec = serde_json::from_str(r#"{"caixa":"worker","versao":"^0.1"}"#)
3834 .expect("ChildSpec must deserialize with the restart key omitted");
3835 assert_eq!(
3836 omitted.restart(),
3837 SUPERVISOR_CHILD_RESTART_DEFAULT,
3838 "an author-omitted :children :restart slot must degrade onto \
3839 the SUPERVISOR_CHILD_RESTART_DEFAULT typed pub const (got \
3840 {:?}, expected {:?})",
3841 omitted.restart(),
3842 SUPERVISOR_CHILD_RESTART_DEFAULT,
3843 );
3844 }
3845
3846 #[test]
3847 fn supervisor_max_restarts_cap_pins_canonical_value() {
3848 // The SUPERVISOR_MAX_RESTARTS_MAX constant pins the value at
3849 // 1000 — the same ceiling the peer
3850 // POLICY_BREAKER_MAX_FAILURES_MAX cap carries on the
3851 // `:politicas :circuit-breaker :max-failures` axis (both are
3852 // "trip the next-higher protection layer after N events in a
3853 // rolling window" counters with identical
3854 // degenerate-at-the-high-end shape; uniform top edge so the
3855 // M4 CR materializers and the wasm-operator reconciler reach
3856 // for either field knowing the value is in `1..=1000`). Two
3857 // orders of magnitude above every documented Erlang/OTP /
3858 // Elixir / Riak Core / RabbitMQ production-playbook
3859 // recommendation band and below the clearly-pathological
3860 // "effectively no escalation" floor (10_000, 100_000,
3861 // u32::MAX). Pinning the literal value here surfaces a future
3862 // drift (a relaxation to 10_000, a tightening to 100) as a
3863 // deliberate test edit, not a silent contract narrowing.
3864 assert_eq!(SUPERVISOR_MAX_RESTARTS_MAX, 1000);
3865 }
3866
3867 #[test]
3868 fn validate_rejects_empty_child_name() {
3869 let s = SupervisorSpec {
3870 children: vec![child("", "^0.1", RestartPolicy::Permanent)],
3871 ..SupervisorSpec::default()
3872 };
3873 assert_eq!(s.validate().unwrap_err(), SupervisorError::EmptyChildName);
3874 }
3875
3876 #[test]
3877 fn validate_rejects_empty_child_version() {
3878 let s = SupervisorSpec {
3879 children: vec![child("w", "", RestartPolicy::Permanent)],
3880 ..SupervisorSpec::default()
3881 };
3882 assert!(matches!(
3883 s.validate().unwrap_err(),
3884 SupervisorError::EmptyChildVersion { .. }
3885 ));
3886 }
3887
3888 // ── value-shape: parse-as-VersionReq on :children :versao ─────────────
3889
3890 #[test]
3891 fn validate_rejects_invalid_child_versao_requirement() {
3892 // The fail-before-pass-after pin: a non-empty but malformed
3893 // semver requirement (`"^bad-version"`) silently passed
3894 // `validate()` on every pre-gate codebase because the prior
3895 // shape only refused the empty string. The parse failure
3896 // surfaced far downstream at lacre-resolve time with a
3897 // `semver::Error` that didn't name which `:children` entry
3898 // carried the typo. The new gate moves the check to caixa-build
3899 // time at the source caixa.lisp — the third `:versao` typed
3900 // axis (`:children`) joins `:deps` and `:membros` (9888b13) at
3901 // structural parity.
3902 let s = SupervisorSpec {
3903 children: vec![
3904 child("worker", "^0.1", RestartPolicy::Permanent),
3905 child("cache", "^bad-version", RestartPolicy::Transient),
3906 ],
3907 ..SupervisorSpec::default()
3908 };
3909 let err = s.validate().unwrap_err();
3910 assert!(
3911 matches!(
3912 err,
3913 SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
3914 if caixa == "cache" && versao == "^bad-version"
3915 ),
3916 "got {err:?}"
3917 );
3918 }
3919
3920 #[test]
3921 fn validate_rejects_child_versao_with_double_caret_typo() {
3922 // `"^^0.1"` is the canonical doubled-caret typo — looks
3923 // Cargo-shaped on first glance but fails the parser because
3924 // semver doesn't accept stacked operators. Pin this
3925 // adjacent-shape footgun explicitly so a future relaxation that
3926 // accepts "looks-canonical-but-isn't" forms surfaces here.
3927 let s = SupervisorSpec {
3928 children: vec![child("worker", "^^0.1", RestartPolicy::Permanent)],
3929 ..SupervisorSpec::default()
3930 };
3931 let err = s.validate().unwrap_err();
3932 assert!(
3933 matches!(
3934 err,
3935 SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
3936 if caixa == "worker" && versao == "^^0.1"
3937 ),
3938 "got {err:?}"
3939 );
3940 }
3941
3942 #[test]
3943 fn validate_rejects_child_versao_with_v_prefixed_tag() {
3944 // `"v0.1"` is the canonical "git-tag-shape leaking into the
3945 // semver requirement slot" typo — an author copies the
3946 // publish-side git-tag string verbatim into `:versao`, but
3947 // Cargo's semver parser rejects the leading `v`. Same
3948 // adjacent-shape footgun pinned for `:membros :versao`
3949 // (9888b13).
3950 let s = SupervisorSpec {
3951 children: vec![child("worker", "v0.1", RestartPolicy::Permanent)],
3952 ..SupervisorSpec::default()
3953 };
3954 let err = s.validate().unwrap_err();
3955 assert!(
3956 matches!(
3957 err,
3958 SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
3959 if caixa == "worker" && versao == "v0.1"
3960 ),
3961 "got {err:?}"
3962 );
3963 }
3964
3965 #[test]
3966 fn validate_accepts_canonical_child_versao_forms() {
3967 // The Cargo-shaped requirement forms `:deps :versao` and
3968 // `:membros :versao` already accept via
3969 // `crate::parse_requirement` must pass the children gate
3970 // without re-validating at the resolver layer. Pin every leg so
3971 // a future tightening of the canonical set surfaces here as a
3972 // test failure.
3973 for form in [
3974 "^0.1", // caret — minor-range pin (the most common shape)
3975 "~0.1.2", // tilde — patch-range pin
3976 "0.1.0", // exact — single-version pin
3977 "*", // wildcard — any version (semver::VersionReq::STAR)
3978 ">=0.1, <2", // multi-range — comma-separated comparators
3979 ] {
3980 let s = SupervisorSpec {
3981 children: vec![child("worker", form, RestartPolicy::Permanent)],
3982 ..SupervisorSpec::default()
3983 };
3984 s.validate()
3985 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
3986 }
3987 }
3988
3989 #[test]
3990 fn child_versao_empty_takes_precedence_over_invalid() {
3991 // Order pin: the existing `EmptyChildVersion` diagnostic (which
3992 // doesn't try to parse) fires before the new
3993 // `ChildVersaoInvalid` parse-side diagnostic, so an empty
3994 // `:versao` keeps its narrower error message —
3995 // `parse_requirement` would also reject `""`, but the
3996 // empty-string arm is the more self-locating diagnostic for the
3997 // author. Same ordering discipline as
3998 // `membro_versao_empty_takes_precedence_over_invalid` in
3999 // aplicacao.rs.
4000 let s = SupervisorSpec {
4001 children: vec![child("worker", "", RestartPolicy::Permanent)],
4002 ..SupervisorSpec::default()
4003 };
4004 let err = s.validate().unwrap_err();
4005 assert!(
4006 matches!(err, SupervisorError::EmptyChildVersion { ref caixa } if caixa == "worker"),
4007 "got {err:?}"
4008 );
4009 }
4010
4011 #[test]
4012 fn child_versao_invalid_fires_before_duplicate_check() {
4013 // Order pin: a malformed requirement on a non-duplicate entry
4014 // surfaces *its own* diagnostic (which names the offending
4015 // `:versao` string), even when a later entry would otherwise
4016 // collapse onto an earlier name. The per-entry shape gate runs
4017 // inline before the duplicate-key insert — parallel to
4018 // `membro_versao_invalid_fires_before_duplicate_check` in
4019 // aplicacao.rs and the b0c8389 / c4213a4 ordering discipline.
4020 let s = SupervisorSpec {
4021 children: vec![
4022 child("worker", "^bad", RestartPolicy::Permanent),
4023 child("cache", "^0.1", RestartPolicy::Transient),
4024 child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
4025 ],
4026 ..SupervisorSpec::default()
4027 };
4028 let err = s.validate().unwrap_err();
4029 assert!(
4030 matches!(
4031 err,
4032 SupervisorError::ChildVersaoInvalid { ref caixa, .. } if caixa == "worker"
4033 ),
4034 "got {err:?}"
4035 );
4036 }
4037
4038 #[test]
4039 fn child_versao_invalid_diagnostic_carries_offending_versao() {
4040 // The diagnostic-shape pin: the error names the offending
4041 // `:versao` value verbatim so the author can grep their
4042 // caixa.lisp without re-running the build, and carries a
4043 // non-empty `reason` from `semver::VersionReq::parse` so the
4044 // parser's own wording flows through to the diagnostic.
4045 let s = SupervisorSpec {
4046 children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
4047 ..SupervisorSpec::default()
4048 };
4049 let err = s.validate().unwrap_err();
4050 let SupervisorError::ChildVersaoInvalid {
4051 caixa,
4052 versao,
4053 reason,
4054 } = err
4055 else {
4056 panic!("expected ChildVersaoInvalid, got other variant");
4057 };
4058 assert_eq!(caixa, "worker");
4059 assert_eq!(versao, "not-a-req");
4060 assert!(
4061 !reason.is_empty(),
4062 "ChildVersaoInvalid `reason` must carry the parser's wording verbatim"
4063 );
4064 }
4065
4066 // ── value-shape: DNS-1123 label rule on :children :caixa ──────────────
4067
4068 #[test]
4069 fn validate_rejects_child_caixa_with_uppercase() {
4070 // The canonical "I copied the Servico's display name verbatim"
4071 // typo — child caixa names are lowercase per K8s DNS-1123 label
4072 // rule. The diagnostic names the offending name and suggests the
4073 // lower-cased fix in one edit, mirroring the
4074 // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0).
4075 let s = SupervisorSpec {
4076 children: vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
4077 ..SupervisorSpec::default()
4078 };
4079 let err = s.validate().unwrap_err();
4080 let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
4081 panic!("expected ChildCaixaInvalid, got other variant");
4082 };
4083 assert_eq!(caixa, "Worker");
4084 assert!(
4085 reason.contains("uppercase"),
4086 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
4087 );
4088 assert!(
4089 reason.contains("\"worker\""),
4090 "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
4091 );
4092 }
4093
4094 #[test]
4095 fn validate_rejects_child_caixa_with_underscore() {
4096 // The canonical "I'm thinking of a Python module / Postgres
4097 // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
4098 // label schema. K8s rejects `metadata.name: my_worker` at
4099 // admission time with an opaque `field is invalid` (no source-
4100 // citing diagnostic). The gate moves it to caixa-build time.
4101 let s = SupervisorSpec {
4102 children: vec![child("my_worker", "^0.1", RestartPolicy::Permanent)],
4103 ..SupervisorSpec::default()
4104 };
4105 let err = s.validate().unwrap_err();
4106 assert!(
4107 matches!(
4108 err,
4109 SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
4110 if caixa == "my_worker" && reason.contains('_')
4111 ),
4112 "got {err:?}"
4113 );
4114 }
4115
4116 #[test]
4117 fn validate_rejects_child_caixa_with_dot() {
4118 // A `:children :caixa` entry is a single DNS-1123 label, not a
4119 // subdomain. The K8s Service / ComputeUnit `metadata.name` rules
4120 // forbid dots. Same shape as `rejects_membro_caixa_with_dot`
4121 // (3f9d7a0) on the peer name axis.
4122 let s = SupervisorSpec {
4123 children: vec![child("team.worker", "^0.1", RestartPolicy::Permanent)],
4124 ..SupervisorSpec::default()
4125 };
4126 let err = s.validate().unwrap_err();
4127 assert!(
4128 matches!(
4129 err,
4130 SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
4131 if caixa == "team.worker" && reason.contains('.')
4132 ),
4133 "got {err:?}"
4134 );
4135 }
4136
4137 #[test]
4138 fn validate_rejects_child_caixa_with_leading_hyphen() {
4139 // DNS-1123 / DNS-1035 boundary rule: labels must start and end
4140 // with an alphanumeric. The K8s apiserver rejects `-worker`
4141 // outright; the renderer would emit a `metadata.name: "-worker"`
4142 // that fails admission far from the source caixa.lisp.
4143 let s = SupervisorSpec {
4144 children: vec![child("-worker", "^0.1", RestartPolicy::Permanent)],
4145 ..SupervisorSpec::default()
4146 };
4147 let err = s.validate().unwrap_err();
4148 assert!(
4149 matches!(
4150 err,
4151 SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
4152 if caixa == "-worker" && reason.contains("start and end")
4153 ),
4154 "got {err:?}"
4155 );
4156 }
4157
4158 #[test]
4159 fn validate_rejects_child_caixa_with_trailing_hyphen() {
4160 // The symmetric arm of the boundary rule. Pin separately so
4161 // both ends of the label are covered against a future relaxation
4162 // that only checks one boundary.
4163 let s = SupervisorSpec {
4164 children: vec![child("worker-", "^0.1", RestartPolicy::Permanent)],
4165 ..SupervisorSpec::default()
4166 };
4167 let err = s.validate().unwrap_err();
4168 assert!(
4169 matches!(
4170 err,
4171 SupervisorError::ChildCaixaInvalid { ref caixa, .. }
4172 if caixa == "worker-"
4173 ),
4174 "got {err:?}"
4175 );
4176 }
4177
4178 #[test]
4179 fn validate_rejects_child_caixa_with_unicode() {
4180 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
4181 // (`xn--…`) by the author before it reaches K8s. The byte-by-
4182 // byte ASCII validity check rejects multi-byte UTF-8 sequences
4183 // by the first byte that fails the `[a-z0-9-]` predicate.
4184 let s = SupervisorSpec {
4185 children: vec![child("café", "^0.1", RestartPolicy::Permanent)],
4186 ..SupervisorSpec::default()
4187 };
4188 let err = s.validate().unwrap_err();
4189 assert!(
4190 matches!(
4191 err,
4192 SupervisorError::ChildCaixaInvalid { ref caixa, .. }
4193 if caixa == "café"
4194 ),
4195 "got {err:?}"
4196 );
4197 }
4198
4199 #[test]
4200 fn validate_rejects_child_caixa_with_whitespace() {
4201 // Whitespace is the canonical "I pasted from a sketch / doc"
4202 // footgun. The apiserver rejects every `metadata.name` value
4203 // carrying whitespace; pin the gate fires at the right boundary.
4204 let s = SupervisorSpec {
4205 children: vec![child("my worker", "^0.1", RestartPolicy::Permanent)],
4206 ..SupervisorSpec::default()
4207 };
4208 let err = s.validate().unwrap_err();
4209 assert!(
4210 matches!(
4211 err,
4212 SupervisorError::ChildCaixaInvalid { ref caixa, .. }
4213 if caixa == "my worker"
4214 ),
4215 "got {err:?}"
4216 );
4217 }
4218
4219 #[test]
4220 fn validate_rejects_child_caixa_too_long() {
4221 // The 64-byte boundary pin. DNS-1123 / DNS-1035 cap labels at
4222 // 63 bytes; the K8s apiserver rejects every `metadata.name`
4223 // axis over the limit at admission time. The diagnostic names
4224 // both the cap and the actual length so the author can shorten
4225 // in one edit, mirroring `rejects_membro_caixa_too_long`
4226 // (3f9d7a0) and `rejects_placement_cluster_too_long` (6cbb900).
4227 let too_long = "a".repeat(64);
4228 let s = SupervisorSpec {
4229 children: vec![child(&too_long, "^0.1", RestartPolicy::Permanent)],
4230 ..SupervisorSpec::default()
4231 };
4232 let err = s.validate().unwrap_err();
4233 let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
4234 panic!("expected ChildCaixaInvalid, got other variant");
4235 };
4236 assert_eq!(caixa, too_long);
4237 assert!(
4238 reason.contains("63"),
4239 "diagnostic must name the 63-byte cap (got: {reason:?})"
4240 );
4241 assert!(
4242 reason.contains("64"),
4243 "diagnostic must name the actual length (got: {reason:?})"
4244 );
4245 }
4246
4247 #[test]
4248 fn child_caixa_max_length_validates() {
4249 // The 63-byte boundary control pin — exactly-at-the-cap is
4250 // accepted, mirroring `membro_caixa_max_length_validates`
4251 // (3f9d7a0) and `placement_cluster_max_length_validates`
4252 // (6cbb900). Pinned separately so a future off-by-one tightening
4253 // surfaces here.
4254 let max_label = "a".repeat(63);
4255 let s = SupervisorSpec {
4256 children: vec![child(&max_label, "^0.1", RestartPolicy::Permanent)],
4257 ..SupervisorSpec::default()
4258 };
4259 s.validate().unwrap();
4260 }
4261
4262 #[test]
4263 fn validate_accepts_canonical_child_caixa_forms() {
4264 // The realistic shapes a supervised child's `:caixa` carries —
4265 // single-word `worker`, version-suffixed `cache-v2`, single-char
4266 // `a`, two-char `db`, digit-start `2-pool`, longer hyphen-joined
4267 // `payment-retry`, all-digit `0`. Pin every leg so a future
4268 // tightening (e.g. requiring a leading lowercase letter) surfaces
4269 // here as a test failure. Mirrors `accepts_canonical_membro_caixa_forms`
4270 // (3f9d7a0) and `accepts_canonical_placement_cluster_forms`
4271 // (6cbb900).
4272 for form in [
4273 "worker",
4274 "cache-v2",
4275 "a",
4276 "db",
4277 "2-pool",
4278 "payment-retry",
4279 "0",
4280 ] {
4281 let s = SupervisorSpec {
4282 children: vec![child(form, "^0.1", RestartPolicy::Permanent)],
4283 ..SupervisorSpec::default()
4284 };
4285 s.validate()
4286 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
4287 }
4288 }
4289
4290 #[test]
4291 fn child_caixa_empty_takes_precedence_over_invalid() {
4292 // Order pin: the existing `EmptyChildName` diagnostic (which
4293 // doesn't try to parse the DNS-1123 shape) fires before the new
4294 // `ChildCaixaInvalid` per-axis gate, so an empty `:caixa` keeps
4295 // its narrower error message — `is_dns_1123_label` would reject
4296 // the empty string too (boundary check on the first byte), but
4297 // the empty-string arm is the more self-locating diagnostic for
4298 // the author. Same ordering discipline as
4299 // `membro_caixa_empty_takes_precedence_over_invalid` in
4300 // aplicacao.rs.
4301 let s = SupervisorSpec {
4302 children: vec![child("", "^0.1", RestartPolicy::Permanent)],
4303 ..SupervisorSpec::default()
4304 };
4305 let err = s.validate().unwrap_err();
4306 assert_eq!(err, SupervisorError::EmptyChildName);
4307 }
4308
4309 #[test]
4310 fn child_caixa_invalid_fires_before_versao_check() {
4311 // Order pin: the per-axis shape gate runs inline before the
4312 // per-entry versao check, so a malformed `:caixa` on an entry
4313 // whose `:versao` would also fail surfaces the more self-
4314 // locating name-axis diagnostic first. Parallel to
4315 // `membro_versao_invalid_fires_before_duplicate_check` (9888b13)
4316 // and `placement_cluster_invalid_fires_before_duplicate_check`
4317 // (6cbb900).
4318 let s = SupervisorSpec {
4319 children: vec![child("My_Worker", "", RestartPolicy::Permanent)],
4320 ..SupervisorSpec::default()
4321 };
4322 let err = s.validate().unwrap_err();
4323 assert!(
4324 matches!(
4325 err,
4326 SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "My_Worker"
4327 ),
4328 "got {err:?}"
4329 );
4330 }
4331
4332 #[test]
4333 fn child_caixa_invalid_fires_before_duplicate_check() {
4334 // Order pin: a malformed name on a non-duplicate entry surfaces
4335 // its own diagnostic, even when a later entry would otherwise
4336 // collapse onto an earlier name. The per-entry shape gate runs
4337 // inline before the duplicate-key HashSet insert, mirroring
4338 // `placement_cluster_invalid_fires_before_duplicate_check`
4339 // (6cbb900).
4340 let s = SupervisorSpec {
4341 children: vec![
4342 child("Worker", "^0.1", RestartPolicy::Permanent),
4343 child("cache", "^0.1", RestartPolicy::Transient),
4344 child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
4345 ],
4346 ..SupervisorSpec::default()
4347 };
4348 let err = s.validate().unwrap_err();
4349 assert!(
4350 matches!(
4351 err,
4352 SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "Worker"
4353 ),
4354 "got {err:?}"
4355 );
4356 }
4357
4358 #[test]
4359 fn child_caixa_invalid_diagnostic_carries_offending_caixa() {
4360 // The diagnostic-shape pin: the error names the offending
4361 // `:caixa` verbatim plus a non-empty parser-shaped `reason` so
4362 // the author can grep their caixa.lisp without re-running the
4363 // build. Mirrors the diagnostic-shape sweep on every prior
4364 // value-shape gate (3f9d7a0, 6cbb900, c7d05ec).
4365 let s = SupervisorSpec {
4366 children: vec![child("My_Worker", "^0.1", RestartPolicy::Permanent)],
4367 ..SupervisorSpec::default()
4368 };
4369 let err = s.validate().unwrap_err();
4370 let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
4371 panic!("expected ChildCaixaInvalid, got other variant");
4372 };
4373 assert_eq!(caixa, "My_Worker");
4374 assert!(
4375 !reason.is_empty(),
4376 "ChildCaixaInvalid `reason` must carry the parser's wording verbatim"
4377 );
4378 }
4379
4380 // ── value-shape: zero restart_window + duplicate child names ──────────
4381
4382 #[test]
4383 fn validate_accepts_none_restart_window() {
4384 // Omitted `:restart-window` is the "never reset" sentinel —
4385 // valid by design. Mirrors :limits axes where None = unbounded.
4386 let s = SupervisorSpec {
4387 restart_window: None,
4388 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4389 ..SupervisorSpec::default()
4390 };
4391 s.validate().unwrap();
4392 }
4393
4394 #[test]
4395 fn validate_rejects_zero_restart_window() {
4396 // Same "0 means the opposite of what you think" footgun closed
4397 // for :politicas :timeout (Envoy treats 0s as infinite) and
4398 // :limits :wall-clock (wasmtime traps before the call starts).
4399 // Erlang/OTP's MaxIntensity/Period requires Period > 0.
4400 let s = SupervisorSpec {
4401 restart_window: Some(Duration::ZERO),
4402 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4403 ..SupervisorSpec::default()
4404 };
4405 assert_eq!(
4406 s.validate().unwrap_err(),
4407 SupervisorError::RestartWindowZero
4408 );
4409 }
4410
4411 // ── value-shape: integer-ms canonical-form on :restart-window ─────────
4412 //
4413 // The fourth (and last) typed-`Duration` axis in caixa-core to get
4414 // the integer-millisecond canonical-form gate — peer with
4415 // `:limits :wall-clock` (82fc3ef), `:politicas :timeout` (a4ae535),
4416 // and `:politicas :circuit-breaker :window` (a4ae535). The serde
4417 // path is already gated at the shared codec layer (see
4418 // `restart_window_serde_rejects_fractional_seconds`); this arm
4419 // closes the programmatic-struct-literal path the codec gate can't
4420 // see.
4421
4422 #[test]
4423 fn validate_rejects_sub_millisecond_restart_window() {
4424 // The fail-before-pass-after pin: a programmatic
4425 // `Duration::from_micros(1500)` (= 1_500_000 ns) silently passed
4426 // `validate` on every pre-gate codebase, then truncated to
4427 // `as_millis() == 1` on first serialize — the shared codec
4428 // emits `"1ms"`, parses it back to `Duration::from_millis(1)` =
4429 // 1_000_000 ns, the typed `restart_window` no longer matches
4430 // its rendered form.
4431 let s = SupervisorSpec {
4432 restart_window: Some(Duration::from_micros(1500)),
4433 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4434 ..SupervisorSpec::default()
4435 };
4436 match s.validate().unwrap_err() {
4437 SupervisorError::RestartWindowNotCanonical { window } => {
4438 assert_eq!(window, Duration::from_micros(1500));
4439 }
4440 other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
4441 }
4442 }
4443
4444 #[test]
4445 fn validate_rejects_one_nanosecond_restart_window() {
4446 // The far-sub-ms case: `Duration::from_nanos(1)` is non-zero
4447 // (so `RestartWindowZero` doesn't fire) but `as_millis() == 0`,
4448 // so the shared codec emits the literal `"0s"` — the next
4449 // serde round-trip would parse back to `Duration::ZERO`, which
4450 // the `RestartWindowZero` arm then rejects on re-validate. The
4451 // canonical-form gate at this layer surfaces a self-locating
4452 // diagnostic naming the offending Duration verbatim rather
4453 // than a downstream `RestartWindowZero` whose remediation
4454 // points at omitting the slot.
4455 let s = SupervisorSpec {
4456 restart_window: Some(Duration::from_nanos(1)),
4457 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4458 ..SupervisorSpec::default()
4459 };
4460 match s.validate().unwrap_err() {
4461 SupervisorError::RestartWindowNotCanonical { window } => {
4462 assert_eq!(window, Duration::from_nanos(1));
4463 }
4464 other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
4465 }
4466 }
4467
4468 #[test]
4469 fn validate_rejects_nanosecond_past_canonical_boundary_restart_window() {
4470 // The 1-ns-past-1ms boundary case: a `Duration` carrying
4471 // 1_000_001 ns is structurally past the integer-ms granularity
4472 // floor — `subsec_nanos() % 1_000_000 == 1`. The codec round-
4473 // trip would truncate to `1ms` and the consumer would observe
4474 // a 1-ns drift on every emit. Same boundary the peer
4475 // `validate_rejects_nanosecond_past_canonical_boundary` test
4476 // in limits.rs pins for the `:limits :wall-clock` axis.
4477 let w = Duration::from_nanos(1_000_001);
4478 let s = SupervisorSpec {
4479 restart_window: Some(w),
4480 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4481 ..SupervisorSpec::default()
4482 };
4483 assert_eq!(
4484 s.validate().unwrap_err(),
4485 SupervisorError::RestartWindowNotCanonical { window: w }
4486 );
4487 }
4488
4489 #[test]
4490 fn validate_accepts_integer_millisecond_restart_window_values() {
4491 // The positive-control sweep: every `Duration` the shared
4492 // codec can round-trip losslessly — the canonical
4493 // `<integer>{ms,s,m,h}` set the codec's `render` / `parse`
4494 // pair emits and accepts — passes `validate` without
4495 // surfacing the new canonical-form arm. Mirrors
4496 // `validate_accepts_integer_millisecond_wall_clock_values` on
4497 // the sibling `:limits :wall-clock` axis.
4498 for w in [
4499 Duration::from_millis(1),
4500 Duration::from_millis(500),
4501 Duration::from_millis(1500),
4502 Duration::from_secs(1),
4503 Duration::from_secs(30),
4504 Duration::from_secs(60),
4505 Duration::from_secs(120),
4506 Duration::from_secs(3600),
4507 ] {
4508 let s = SupervisorSpec {
4509 restart_window: Some(w),
4510 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4511 ..SupervisorSpec::default()
4512 };
4513 s.validate()
4514 .unwrap_or_else(|e| panic!("integer-ms {w:?} must validate, got {e:?}"));
4515 }
4516 }
4517
4518 #[test]
4519 fn validate_restart_window_zero_takes_precedence_over_canonical_gate() {
4520 // Cross-arm ordering pin: `Duration::ZERO` has
4521 // `subsec_nanos() == 0` and would otherwise pass the
4522 // canonical-form arm — the zero-floor arm must fire first so
4523 // the more self-locating `RestartWindowZero` diagnostic (with
4524 // its omit-axis remediation directly named) leads. Same
4525 // posture every peer zero-then-shape gate uses
4526 // (`WallClockZero` → `WallClockNotCanonical`,
4527 // `PolicyTimeoutZero` → `PolicyTimeoutNotCanonical`,
4528 // `PolicyBreakerZeroWindow` → `PolicyBreakerWindowNotCanonical`).
4529 let s = SupervisorSpec {
4530 restart_window: Some(Duration::ZERO),
4531 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4532 ..SupervisorSpec::default()
4533 };
4534 assert_eq!(
4535 s.validate().unwrap_err(),
4536 SupervisorError::RestartWindowZero
4537 );
4538 }
4539
4540 #[test]
4541 fn restart_window_canonical_diagnostic_carries_offending_duration() {
4542 // Diagnostic-shape pin: the canonical-form arm names the
4543 // offending `Duration` verbatim so the author's grep lands on
4544 // the field's value, not a generic "duration not canonical"
4545 // message. Same shape every other typed-canonical-form arm
4546 // on this surface carries (`WallClockNotCanonical` carries
4547 // the offending `Duration` verbatim,
4548 // `PolicyTimeoutNotCanonical` carries the offending
4549 // `Duration` verbatim).
4550 let w = Duration::from_micros(500);
4551 let s = SupervisorSpec {
4552 restart_window: Some(w),
4553 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4554 ..SupervisorSpec::default()
4555 };
4556 let err = s.validate().unwrap_err();
4557 let msg = err.to_string();
4558 assert!(
4559 msg.contains("500"),
4560 "diagnostic must carry the offending magnitude verbatim (got {msg:?})"
4561 );
4562 assert!(
4563 msg.contains("sub-millisecond"),
4564 "diagnostic must name the sub-millisecond residue class (got {msg:?})"
4565 );
4566 }
4567
4568 #[test]
4569 fn restart_window_validated_value_round_trips_through_codec() {
4570 // The structural property the canonical-ms gate enforces:
4571 // every `SupervisorSpec::restart_window` past
4572 // `SupervisorSpec::validate` round-trips losslessly through
4573 // the shared duration codec (serialize → string →
4574 // deserialize → equal value). Pin this end-to-end so a future
4575 // change to either side (the validate gate's accepted
4576 // granularity, the codec's parse/render unit set) that breaks
4577 // the alignment surfaces here. Peer of
4578 // `wall_clock_validated_value_round_trips_through_codec` on
4579 // the sibling `:limits :wall-clock` axis.
4580 for w in [
4581 Duration::from_millis(1),
4582 Duration::from_millis(1500),
4583 Duration::from_secs(30),
4584 Duration::from_secs(3600),
4585 ] {
4586 let s = SupervisorSpec {
4587 restart_window: Some(w),
4588 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4589 ..SupervisorSpec::default()
4590 };
4591 s.validate().unwrap();
4592 let json = serde_json::to_string(&s).unwrap();
4593 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
4594 assert_eq!(back.restart_window, Some(w));
4595 }
4596 }
4597
4598 // ── value-shape: upper cap on :restart-window ─────────────────────────
4599 //
4600 // The fourth (and last) typed-`Duration` axis in caixa-core to get
4601 // the 1h upper cap — peer with `:limits :wall-clock` (51e0dbd),
4602 // `:politicas :timeout` (2e8ee7e), and `:politicas
4603 // :circuit-breaker :window` (379a814). Brackets the typed
4604 // `:restart-window` axis structurally: every validated value lies
4605 // in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`, integer-millisecond
4606 // granularity, closing the
4607 // rolling-window-degenerates-to-lifetime-counter footgun the prior
4608 // zero-floor-and-canonical-form-only checks left open.
4609
4610 #[test]
4611 fn validate_rejects_restart_window_above_cap() {
4612 // The fail-before-pass-after pin: 3601s = 1h + 1s is
4613 // structurally one canonical-tick past the
4614 // [`SUPERVISOR_RESTART_WINDOW_MAX`] ceiling (1h = 3600s) — an
4615 // integer-millisecond magnitude the canonical-form arm above
4616 // accepts cleanly, that the shared duration codec round-trips
4617 // losslessly as `"3601s"`, and that silently passed validate on
4618 // every pre-gate codebase because the typed slot's only checks
4619 // were the zero-floor and canonical-form arms. The runtime
4620 // substrate consuming the value (Erlang/OTP's MaxIntensity/
4621 // Period reconciler, the future wasm-operator's per-supervisor
4622 // restart-intensity counter) reaches for a `Duration` so long
4623 // no realistic restart-recovery pattern resets the counter,
4624 // far from the source caixa.lisp.
4625 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
4626 let s = SupervisorSpec {
4627 restart_window: Some(w),
4628 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4629 ..SupervisorSpec::default()
4630 };
4631 assert_eq!(
4632 s.validate().unwrap_err(),
4633 SupervisorError::RestartWindowExceedsCap { window: w }
4634 );
4635 }
4636
4637 #[test]
4638 fn validate_rejects_restart_window_one_millisecond_above_cap() {
4639 // Boundary case: exactly 1ms past the cap (the granularity the
4640 // canonical-form gate enforces). Catches a future "strictly
4641 // less than" half-measure and pins the diagnostic to name the
4642 // offending `Duration` verbatim. Peer of
4643 // `validate_rejects_wall_clock_one_millisecond_above_cap` /
4644 // `rejects_policy_timeout_one_millisecond_above_cap` /
4645 // `rejects_circuit_breaker_window_one_millisecond_above_cap`
4646 // on the sibling typed-`Duration` axes' top edges.
4647 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
4648 let s = SupervisorSpec {
4649 restart_window: Some(w),
4650 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4651 ..SupervisorSpec::default()
4652 };
4653 assert_eq!(
4654 s.validate().unwrap_err(),
4655 SupervisorError::RestartWindowExceedsCap { window: w }
4656 );
4657 }
4658
4659 #[test]
4660 fn validate_rejects_restart_window_far_above_cap() {
4661 // The "obvious authoring footgun" case: a `(:restart-window "24h")`,
4662 // `(:restart-window "7d")`, or any "I want a lifetime counter
4663 // but wrote a `<integer>h` magnitude anyway" typo — values the
4664 // canonical-form arm accepts as integer-millisecond magnitudes,
4665 // the codec round-trips losslessly through serde, but the
4666 // operator's `MaxIntensity / Period` reconciler cannot honor
4667 // as a meaningful rolling window. Until this gate landed
4668 // validate accepted them. Pin the common above-cap values (24h,
4669 // 7d, ~11.5d) so a future relaxation that drops the upper bound
4670 // surfaces here.
4671 for w in [
4672 Duration::from_secs(86_400), // 24h
4673 Duration::from_secs(604_800), // 7d
4674 Duration::from_secs(1_000_000), // ~11.5 days
4675 ] {
4676 let s = SupervisorSpec {
4677 restart_window: Some(w),
4678 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4679 ..SupervisorSpec::default()
4680 };
4681 assert_eq!(
4682 s.validate().unwrap_err(),
4683 SupervisorError::RestartWindowExceedsCap { window: w }
4684 );
4685 }
4686 }
4687
4688 #[test]
4689 fn validate_accepts_restart_window_at_cap() {
4690 // The boundary value — exactly [`SUPERVISOR_RESTART_WINDOW_MAX`]
4691 // (1h) — must validate. The cap is inclusive on the top edge,
4692 // matching the [`crate::LIMITS_WALL_CLOCK_MAX`] /
4693 // [`crate::POLICY_TIMEOUT_MAX`] /
4694 // [`crate::POLICY_BREAKER_WINDOW_MAX`] discipline on the sibling
4695 // capped axes. Pin the boundary explicitly so a future
4696 // off-by-one tightening (`>= SUPERVISOR_RESTART_WINDOW_MAX`
4697 // instead of `>`) surfaces here as a test failure rather than a
4698 // silent contract narrowing.
4699 let s = SupervisorSpec {
4700 restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
4701 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4702 ..SupervisorSpec::default()
4703 };
4704 s.validate()
4705 .expect("restart_window == SUPERVISOR_RESTART_WINDOW_MAX must validate");
4706 }
4707
4708 #[test]
4709 fn validate_accepts_restart_window_typical_values() {
4710 // The documented Erlang/OTP / Elixir / Riak Core / RabbitMQ
4711 // per-supervisor production-playbook band positive-control
4712 // sweep — every value Learn You Some Erlang's `{intensity, 5,
4713 // 60}` worker-supervisor `Period = 60s` default, Elixir's
4714 // `Supervisor` `max_seconds: 5` default, OTP's `supervisor`
4715 // callback module `MaxT = 5..=60` typical, Riak Core's `MaxT ∈
4716 // 10s..=300s`, and RabbitMQ broker-supervisor `MaxT = 5s`
4717 // default recommend (5s..=300s) must pass, plus a sweep
4718 // through the long-tail-flaky-pool band (5m, 15m, 30m, 1h) the
4719 // cap accepts. Mirrors `validate_accepts_wall_clock_typical_values`
4720 // on the sibling `:limits :wall-clock` axis.
4721 for w in [
4722 Duration::from_millis(1),
4723 Duration::from_millis(500),
4724 Duration::from_secs(1),
4725 Duration::from_secs(5), // RabbitMQ broker-supervisor default
4726 Duration::from_secs(10), // Riak Core lower
4727 Duration::from_secs(30),
4728 Duration::from_secs(60), // Learn You Some Erlang default
4729 Duration::from_secs(120), // OTP supervisor MaxT typical
4730 Duration::from_secs(300), // Riak Core upper
4731 Duration::from_secs(900), // 15m
4732 Duration::from_secs(1800),
4733 Duration::from_secs(3600), // exactly 1h, the cap
4734 ] {
4735 let s = SupervisorSpec {
4736 restart_window: Some(w),
4737 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4738 ..SupervisorSpec::default()
4739 };
4740 s.validate()
4741 .unwrap_or_else(|e| panic!("restart_window={w:?} must validate; got {e:?}"));
4742 }
4743 }
4744
4745 #[test]
4746 fn restart_window_zero_takes_precedence_over_cap() {
4747 // The cross-arm ordering pin: `Duration::ZERO` is structurally
4748 // outside both `>= 1ms` (zero-floor) and `<=
4749 // SUPERVISOR_RESTART_WINDOW_MAX` (cap), but the zero-floor
4750 // diagnostic is the more self-locating one (it directly names
4751 // the omit-axis remediation), so the validate gate must fire
4752 // on zero first. Same shape every other zero-then-cap ordering
4753 // on this surface uses (`WallClockZero` then
4754 // `WallClockExceedsCap`, `PolicyTimeoutZero` then
4755 // `PolicyTimeoutExceedsCap`, `PolicyBreakerZeroWindow` then
4756 // `PolicyBreakerWindowExceedsCap`).
4757 let s = SupervisorSpec {
4758 restart_window: Some(Duration::ZERO),
4759 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4760 ..SupervisorSpec::default()
4761 };
4762 assert_eq!(
4763 s.validate().unwrap_err(),
4764 SupervisorError::RestartWindowZero,
4765 "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
4766 );
4767 }
4768
4769 #[test]
4770 fn restart_window_canonical_takes_precedence_over_cap() {
4771 // The cross-arm ordering pin: a `Duration` that is *both*
4772 // sub-millisecond (non-canonical-form) and structurally above
4773 // the cap surfaces the canonical-form diagnostic first,
4774 // because the round-trip-shape break is the more fundamental
4775 // issue (the value can't even round-trip through the codec,
4776 // so the cap diagnostic naming `1ms..=1h` would be misleading
4777 // — there's no integer-ms form of the offending value). Pin
4778 // the order so a future refactor that reorders the arms
4779 // surfaces here as a test failure rather than a silent
4780 // diagnostic regression. Peer of
4781 // `wall_clock_canonical_takes_precedence_over_cap` /
4782 // `policy_timeout_canonical_takes_precedence_over_cap`.
4783 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_nanos(1);
4784 let s = SupervisorSpec {
4785 restart_window: Some(w),
4786 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4787 ..SupervisorSpec::default()
4788 };
4789 assert_eq!(
4790 s.validate().unwrap_err(),
4791 SupervisorError::RestartWindowNotCanonical { window: w },
4792 "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
4793 );
4794 }
4795
4796 #[test]
4797 fn max_restarts_cap_takes_precedence_over_restart_window_cap() {
4798 // The cross-arm ordering pin between the `:max-restarts` cap
4799 // and the sibling `:restart-window` cap. A supervisor carrying
4800 // both an over-cap `max_restarts` AND an over-cap window must
4801 // surface the `MaxRestartsExceedsCap` diagnostic first — the
4802 // cap arm is wired immediately after the zero-restart arm and
4803 // strictly before every window-axis arm (zero / canonical /
4804 // cap), so the offending value the diagnostic names matches
4805 // the order the author would discover the gates by reading
4806 // top-to-bottom through `SupervisorSpec::validate`. Pin the
4807 // order so a future refactor that reorders the arms surfaces
4808 // here as a test failure rather than a silent diagnostic
4809 // regression. Peer of
4810 // `max_restarts_cap_takes_precedence_over_restart_window_gates`
4811 // on the sibling zero / canonical window arms.
4812 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
4813 let s = SupervisorSpec {
4814 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4815 restart_window: Some(w),
4816 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4817 ..SupervisorSpec::default()
4818 };
4819 assert_eq!(
4820 s.validate().unwrap_err(),
4821 SupervisorError::MaxRestartsExceedsCap {
4822 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
4823 },
4824 "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
4825 );
4826 }
4827
4828 #[test]
4829 fn restart_window_cap_diagnostic_carries_offending_value() {
4830 // The diagnostic-shape pin: the offending `Duration` is
4831 // carried verbatim into the
4832 // [`SupervisorError::RestartWindowExceedsCap`] variant so the
4833 // surfaced error message names the value the author wrote,
4834 // not just the cap. Same self-locating diagnostic shape every
4835 // other typed-cap arm on this surface carries
4836 // (`WallClockExceedsCap` carries the offending `Duration`
4837 // verbatim, `PolicyTimeoutExceedsCap` carries the offending
4838 // `Duration` verbatim, `PolicyBreakerWindowExceedsCap` carries
4839 // the offending `Duration` verbatim).
4840 let w = Duration::from_secs(7200); // 2h
4841 let s = SupervisorSpec {
4842 restart_window: Some(w),
4843 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4844 ..SupervisorSpec::default()
4845 };
4846 let err = s.validate().unwrap_err();
4847 assert!(
4848 matches!(err, SupervisorError::RestartWindowExceedsCap { window } if window == w),
4849 "got {err:?}"
4850 );
4851 let msg = err.to_string();
4852 assert!(
4853 msg.contains("7200"),
4854 ":supervisor :restart-window cap diagnostic must carry the offending value verbatim (got: {msg})"
4855 );
4856 }
4857
4858 #[test]
4859 fn supervisor_restart_window_cap_pins_canonical_value() {
4860 // The SUPERVISOR_RESTART_WINDOW_MAX constant pins the value at
4861 // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
4862 // shared duration codec emits as a clean canonical string
4863 // (`"<n>h"`). Pinning the literal value here surfaces a future
4864 // drift (a relaxation to 24h, a tightening to 5m) as a
4865 // deliberate test edit, not a silent contract narrowing.
4866 //
4867 // The four typed-`Duration` caps on the validation surface
4868 // (`LIMITS_WALL_CLOCK_MAX` per-process, `POLICY_TIMEOUT_MAX`
4869 // per-edge, `POLICY_BREAKER_WINDOW_MAX` per-breaker,
4870 // `SUPERVISOR_RESTART_WINDOW_MAX` per-supervisor) share a
4871 // single uniform top edge at the codec's largest emitted unit
4872 // — a structural-property invariant the equality assertions
4873 // here enshrine, so a future drift on any of the four
4874 // surfaces as a deliberate test edit. Same shape every other
4875 // typed-cap value pin uses
4876 // (`wall_clock_cap_pins_canonical_value`,
4877 // `policy_timeout_cap_pins_canonical_value`,
4878 // `circuit_breaker_window_cap_pins_canonical_value`).
4879 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, Duration::from_secs(3600));
4880 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX.as_millis(), 3_600_000);
4881 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::LIMITS_WALL_CLOCK_MAX);
4882 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::POLICY_TIMEOUT_MAX);
4883 assert_eq!(
4884 SUPERVISOR_RESTART_WINDOW_MAX,
4885 crate::POLICY_BREAKER_WINDOW_MAX
4886 );
4887 }
4888
4889 #[test]
4890 fn restart_window_cap_value_round_trips_through_codec() {
4891 // The codec round-trip property the cap arm preserves: the
4892 // [`SUPERVISOR_RESTART_WINDOW_MAX`] constant itself round-trips
4893 // through the shared duration codec — every value at the cap
4894 // serializes to the canonical `"1h"` form and parses back
4895 // identically. Pin the round-trip so a future change to the
4896 // codec's unit set or to the cap's magnitude that breaks the
4897 // round-trip property surfaces here. Peer of
4898 // `wall_clock_cap_value_round_trips_through_codec` on the
4899 // sibling `:limits :wall-clock` axis.
4900 let s = SupervisorSpec {
4901 restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
4902 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
4903 ..SupervisorSpec::default()
4904 };
4905 s.validate().unwrap();
4906 let json = serde_json::to_string(&s).unwrap();
4907 assert!(
4908 json.contains("\"1h\""),
4909 "SUPERVISOR_RESTART_WINDOW_MAX must serialize to the canonical `\"1h\"` form (got {json})"
4910 );
4911 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
4912 assert_eq!(back.restart_window, Some(SUPERVISOR_RESTART_WINDOW_MAX));
4913 }
4914
4915 #[test]
4916 fn validate_rejects_duplicate_child_caixa() {
4917 // Two children with the same :caixa render to two ComputeUnits
4918 // with the same name in the cluster's HelmRelease values —
4919 // one silently overwrites the other. Erlang/OTP's child_spec.id
4920 // is required-unique per supervisor; same set-not-multiset
4921 // discipline applied here as for :membros / :placement
4922 // :clusters / :entrada :paths.
4923 let s = SupervisorSpec {
4924 children: vec![
4925 child("worker", "^0.1", RestartPolicy::Permanent),
4926 child("cache", "^0.1", RestartPolicy::Transient),
4927 child("worker", "^0.2", RestartPolicy::Permanent),
4928 ],
4929 ..SupervisorSpec::default()
4930 };
4931 let err = s.validate().unwrap_err();
4932 assert!(
4933 matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "worker"),
4934 "got {err:?}"
4935 );
4936 }
4937
4938 #[test]
4939 fn validate_duplicate_child_diagnostic_names_first_collision() {
4940 // Iteration walks the :children list in declaration order —
4941 // the diagnostic names the first repeat, deterministically,
4942 // even when multiple names duplicate.
4943 let s = SupervisorSpec {
4944 children: vec![
4945 child("a", "^0.1", RestartPolicy::Permanent),
4946 child("b", "^0.1", RestartPolicy::Permanent),
4947 child("a", "^0.1", RestartPolicy::Permanent),
4948 child("b", "^0.1", RestartPolicy::Permanent),
4949 ],
4950 ..SupervisorSpec::default()
4951 };
4952 let err = s.validate().unwrap_err();
4953 assert!(
4954 matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "a"),
4955 "got {err:?}"
4956 );
4957 }
4958
4959 // ── self-supervision cross-slot gate ──────────────────────────
4960
4961 #[test]
4962 fn validate_no_self_supervision_rejects_self_referential_child() {
4963 // A supervisor whose `:children` lists its own `:nome` is a
4964 // one-node reconciliation cycle — rejected, naming the parent.
4965 let children = vec![
4966 child("worker", "^0.1", RestartPolicy::Permanent),
4967 child("orquestra", "^0.1", RestartPolicy::Permanent),
4968 ];
4969 let err = validate_no_self_supervision(&children, "orquestra").unwrap_err();
4970 assert!(
4971 matches!(err, SupervisorError::ChildSupervisesSelf { ref caixa } if caixa == "orquestra"),
4972 "got {err:?}"
4973 );
4974 }
4975
4976 #[test]
4977 fn validate_no_self_supervision_accepts_distinct_children() {
4978 // Positive control: distinct child names (including a child that
4979 // is itself a supervisor — nested trees are valid OTP) pass.
4980 let children = vec![
4981 child("worker", "^0.1", RestartPolicy::Permanent),
4982 child("sub-tree", "^0.1", RestartPolicy::Permanent),
4983 ];
4984 validate_no_self_supervision(&children, "orquestra").unwrap();
4985 }
4986
4987 #[test]
4988 fn validate_no_self_supervision_empty_children_is_ok() {
4989 // SimpleOneForOne / no-static-children supervisors have nothing
4990 // to self-reference — the gate is vacuously satisfied.
4991 validate_no_self_supervision(&[], "orquestra").unwrap();
4992 }
4993
4994 #[test]
4995 fn validate_simple_one_for_one_skips_uniqueness_check() {
4996 // SimpleOneForOne supervisors carry no static children — the
4997 // duplicate-child loop never runs. A zero-window declaration
4998 // on a SimpleOneForOne supervisor still trips the window check
4999 // (window applies to dynamic children too).
5000 let s = SupervisorSpec {
5001 estrategia: RestartStrategy::SimpleOneForOne,
5002 restart_window: None,
5003 children: vec![],
5004 ..SupervisorSpec::default()
5005 };
5006 s.validate().unwrap();
5007 let s_zero = SupervisorSpec {
5008 estrategia: RestartStrategy::SimpleOneForOne,
5009 restart_window: Some(Duration::ZERO),
5010 children: vec![],
5011 ..SupervisorSpec::default()
5012 };
5013 assert_eq!(
5014 s_zero.validate().unwrap_err(),
5015 SupervisorError::RestartWindowZero
5016 );
5017 }
5018
5019 #[test]
5020 fn validate_zero_window_runs_after_max_restarts_check() {
5021 // Pin the order: max_restarts == 0 fires before
5022 // restart_window == 0s, so an author with both wrong sees the
5023 // counter-axis diagnostic first (matches the order in the
5024 // struct and in the doc comment).
5025 let s = SupervisorSpec {
5026 max_restarts: 0,
5027 restart_window: Some(Duration::ZERO),
5028 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5029 ..SupervisorSpec::default()
5030 };
5031 assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
5032 }
5033
5034 #[test]
5035 fn round_trip_all_strategies() {
5036 for &strat in RestartStrategy::ALL {
5037 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
5038 // shape partition through the [`gen_platform::IsVariant`]
5039 // derive-generated [`RestartStrategy::is_simple_one_for_one`]
5040 // predicate rather than the raw
5041 // `matches!(strat, RestartStrategy::SimpleOneForOne)`
5042 // open-coded pattern-match — same closed-set-typed-enum
5043 // arm-discriminator dispatch discipline the sibling
5044 // [`crate::upgrade::UpgradeInstruction::is_restart`] convergence
5045 // (915a934) extended onto its two paired positive / negated
5046 // `matches!` filter sites, and the sibling
5047 // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
5048 // predicate convergence (766ec63) extended onto the M3 mesh-
5049 // slot per-`:placement` distribution-strategy `matches!`
5050 // discriminator axis. See the sibling
5051 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
5052 // fixture and the peer `manifest::tests::
5053 // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
5054 // fixture — all three sites (the last unlifted
5055 // `matches!`-based arm-discriminator axis on the OTP-shape
5056 // supervisor sibling-restart-strategy closed-set typed enum,
5057 // acknowledged in 915a934's Prior-commits footnote as the
5058 // outstanding follow-up) now consult one typed dispatch on
5059 // the substrate primitive.
5060 let s = SupervisorSpec {
5061 estrategia: strat,
5062 children: if strat.is_simple_one_for_one() {
5063 vec![]
5064 } else {
5065 vec![child("w", "^0.1", RestartPolicy::Permanent)]
5066 },
5067 ..SupervisorSpec::default()
5068 };
5069 let json = serde_json::to_string(&s).unwrap();
5070 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5071 assert_eq!(s, back);
5072 }
5073 }
5074
5075 #[test]
5076 fn round_trip_all_restart_policies() {
5077 for policy in [
5078 RestartPolicy::Permanent,
5079 RestartPolicy::Temporary,
5080 RestartPolicy::Transient,
5081 ] {
5082 let c = child("w", "^0.1", policy);
5083 let json = serde_json::to_string(&c).unwrap();
5084 let back: ChildSpec = serde_json::from_str(&json).unwrap();
5085 assert_eq!(c, back);
5086 }
5087 }
5088
5089 #[test]
5090 fn restart_strategy_is_simple_one_for_one_predicate_partitions_the_arm_set() {
5091 // The fail-before-pass-after pin on the `gen_platform::IsVariant`
5092 // derive's [`RestartStrategy::is_simple_one_for_one`] arm-
5093 // discriminator predicate: [`RestartStrategy::SimpleOneForOne`]
5094 // is the only variant that satisfies `.is_simple_one_for_one()`;
5095 // every static-children-bearing arm (`OneForOne` / `OneForAll`
5096 // / `RestForOne`) returns `false`. This pin makes the partition
5097 // invariant load-bearing at caixa-core test time so a future
5098 // derive regression (a hole that returns `false` for
5099 // `SimpleOneForOne` too, or a byte-collision that flips a second
5100 // variant to `true`) trips here rather than laundering the arm
5101 // at the three test-fixture builder sites (a hole flips the
5102 // `SimpleOneForOne` fixture to carry a non-empty children list
5103 // and the subsequent `SupervisorSpec::validate` would refuse the
5104 // fixture with [`SupervisorError::SimpleOneForOneWithStaticChildren`];
5105 // a collision flips a peer strategy's fixture to carry an empty
5106 // children list and the subsequent `validate` would refuse with
5107 // [`SupervisorError::NoChildren`] — either way, the pin fires
5108 // here, at the derive site, rather than at the fixture-refusal
5109 // site far away). Peer of the sibling
5110 // [`crate::upgrade::tests::upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
5111 // (915a934) pin on the M2 OTP-appup axis and the sibling
5112 // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
5113 // pin on the M0 `:kind` axis.
5114 let cases: &[(RestartStrategy, bool)] = &[
5115 (RestartStrategy::OneForOne, false),
5116 (RestartStrategy::OneForAll, false),
5117 (RestartStrategy::RestForOne, false),
5118 (RestartStrategy::SimpleOneForOne, true),
5119 ];
5120 for (variant, expected) in cases {
5121 assert_eq!(
5122 variant.is_simple_one_for_one(),
5123 *expected,
5124 "RestartStrategy::{variant:?}.is_simple_one_for_one() must \
5125 return {expected} (partition invariant on the \
5126 IsVariant-derived arm-discriminator predicate — every \
5127 test-fixture site that partitions the `:children` slot \
5128 shape on `SimpleOneForOne ↔ non-SimpleOneForOne` keys \
5129 off this typed dispatch, so a derive regression must \
5130 surface here rather than at the fixture-refusal site)"
5131 );
5132 }
5133 }
5134
5135 #[test]
5136 fn restart_strategy_fixture_partition_routes_through_is_simple_one_for_one_predicate() {
5137 // Byte-identity pin on the `SimpleOneForOne ↔ non-SimpleOneForOne`
5138 // fixture-shape partition against the pre-lift
5139 // `matches!(strat, RestartStrategy::SimpleOneForOne)` open-coded
5140 // pattern-match every test-fixture builder site previously
5141 // coupled to inline. Asserts the two projections agree byte-for-
5142 // byte on every arm of the enum, so a future derive regression
5143 // that flipped either predicate's arm-set would surface here at
5144 // caixa-core test time rather than at the three fixture-builder
5145 // sites (`supervisor::tests::round_trip_all_strategies`,
5146 // `supervisor::tests::supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`,
5147 // `manifest::tests::caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`)
5148 // far from the derive site. Same peer-shape byte-identity pin
5149 // every sibling `IsVariant`-derive-routed convergence carries on
5150 // the substrate's closed-set typed-enum surface (peer of
5151 // [`crate::upgrade::tests::validate_restart_exclusive_routes_through_is_restart_predicate`]
5152 // on the M2 OTP-appup axis).
5153 for &strat in RestartStrategy::ALL {
5154 let via_predicate = strat.is_simple_one_for_one();
5155 let via_matches = matches!(strat, RestartStrategy::SimpleOneForOne);
5156 assert_eq!(
5157 via_predicate, via_matches,
5158 "RestartStrategy::{strat:?}: is_simple_one_for_one() must \
5159 byte-equal matches!(_, RestartStrategy::SimpleOneForOne) — \
5160 the pre-lift open-coded pattern and the \
5161 IsVariant-derived predicate are the same axis, \
5162 one typed dispatch"
5163 );
5164 }
5165 }
5166
5167 #[test]
5168 fn duration_codec_round_trip_canonical_units() {
5169 // Note the canonical-form rule: durations serialize to the
5170 // *largest* unit that divides cleanly, so 60s ↔ "1m" and not
5171 // "60s" — but the round-trip preserves the underlying Duration.
5172 let cases = [
5173 ("30s", Duration::from_secs(30)),
5174 ("5m", Duration::from_secs(300)),
5175 ("1h", Duration::from_secs(3600)),
5176 ("500ms", Duration::from_millis(500)),
5177 ];
5178 for (lit, dur) in cases {
5179 let s = SupervisorSpec {
5180 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5181 restart_window: Some(dur),
5182 ..SupervisorSpec::default()
5183 };
5184 let json = serde_json::to_string(&s).unwrap();
5185 assert!(
5186 json.contains(&format!("\"{lit}\"")),
5187 "expected \"{lit}\" in {json}"
5188 );
5189 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5190 assert_eq!(back.restart_window, Some(dur));
5191 }
5192 }
5193
5194 #[test]
5195 fn duration_canonicalizes_to_largest_unit() {
5196 // 60 seconds → "1m" (largest cleanly-divisible unit), but the
5197 // typed Duration still equals 60s on the way back.
5198 let s = SupervisorSpec {
5199 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5200 restart_window: Some(Duration::from_secs(60)),
5201 ..SupervisorSpec::default()
5202 };
5203 let json = serde_json::to_string(&s).unwrap();
5204 assert!(json.contains("\"1m\""), "{json}");
5205 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
5206 assert_eq!(back.restart_window, Some(Duration::from_secs(60)));
5207 }
5208
5209 #[test]
5210 fn three_child_one_for_one_validates() {
5211 let s = SupervisorSpec {
5212 estrategia: RestartStrategy::OneForOne,
5213 max_restarts: 5,
5214 restart_window: Some(Duration::from_secs(60)),
5215 children: vec![
5216 child("worker", "^0.1", RestartPolicy::Permanent),
5217 child("cache", "^0.1", RestartPolicy::Transient),
5218 child("scratch", "^0.1", RestartPolicy::Temporary),
5219 ],
5220 };
5221 s.validate().unwrap();
5222 }
5223
5224 #[test]
5225 fn json_uses_pascal_case_for_strategy_and_policy() {
5226 // Variant names are PascalCase by default in serde, matching
5227 // tatara-lisp's enum convention (`:estrategia OneForOne`).
5228 let c = child("w", "^0.1", RestartPolicy::Permanent);
5229 let json = serde_json::to_string(&c).unwrap();
5230 assert!(json.contains("\"Permanent\""));
5231 assert!(!json.contains("\"permanent\""));
5232
5233 let s = SupervisorSpec {
5234 estrategia: RestartStrategy::OneForOne,
5235 children: vec![c],
5236 ..SupervisorSpec::default()
5237 };
5238 let json = serde_json::to_string(&s).unwrap();
5239 assert!(json.contains("\"estrategia\":\"OneForOne\""));
5240 }
5241
5242 // ── shared duration codec: integer-magnitude canonical-form gate ──
5243 //
5244 // The gate lifts the discipline `crate::limits::parse_duration`
5245 // (818dd38) carries on the peer `:limits :wall-clock` codec onto
5246 // the shared codec backing the remaining three typed-duration
5247 // slots: `:supervisor :restart-window`, `:politicas :timeout`, and
5248 // `:politicas :circuit-breaker :window`. Every magnitude `render`
5249 // emits is a non-negative integer with no decimal point and no
5250 // leading sign, so the codec's accepted set must match for
5251 // serialize/deserialize to round-trip without canonical-form
5252 // drift.
5253
5254 #[test]
5255 fn parse_accepts_integer_canonical_units() {
5256 // Pin the happy-path: every canonical author shape `render`
5257 // ever emits parses to the same `Duration` value, so the
5258 // codec's accepted set is at least a superset of its emitted
5259 // set on the canonical-unit axis.
5260 for (lit, dur) in [
5261 ("30s", Duration::from_secs(30)),
5262 ("500ms", Duration::from_millis(500)),
5263 ("2m", Duration::from_secs(120)),
5264 ("1h", Duration::from_secs(3600)),
5265 ("0s", Duration::ZERO),
5266 ] {
5267 assert_eq!(
5268 duration_codec::parse(lit).unwrap(),
5269 dur,
5270 "parse({lit:?}) should be {dur:?}"
5271 );
5272 }
5273 }
5274
5275 #[test]
5276 fn parse_accepts_bare_integer_as_seconds() {
5277 // The `"s" | ""` arm: a bare integer with no unit is read as
5278 // seconds. Pin this so the unit-empty form keeps parsing (it
5279 // renders to `"<n>s"` on serialize — that's a unit-choice
5280 // drift the integer-magnitude gate does NOT close, matching
5281 // the `parse_byte_size` `"1024"` → `"1KiB"` scope decision in
5282 // the peer `:limits :memory` codec).
5283 assert_eq!(
5284 duration_codec::parse("30").unwrap(),
5285 Duration::from_secs(30)
5286 );
5287 }
5288
5289 #[test]
5290 fn parse_rejects_fractional_seconds_with_canonical_form_diagnostic() {
5291 // `"1.5s"` parses as f64 to 1.5 → renders back as `"1500ms"`
5292 // on first serialize — DRIFT. The integer-magnitude gate names
5293 // the offending `"1.5"` verbatim and points at the canonical
5294 // remediation `"1500ms"`.
5295 let err = duration_codec::parse("1.5s").unwrap_err();
5296 assert!(err.contains("\"1.5\""), "missing magnitude in {err:?}");
5297 assert!(
5298 err.contains("not a non-negative integer"),
5299 "missing canonical-form reason in {err:?}"
5300 );
5301 assert!(
5302 err.contains("\"1500ms\""),
5303 "missing canonical-form remediation in {err:?}"
5304 );
5305 }
5306
5307 #[test]
5308 fn parse_rejects_decimal_shaped_integer_seconds() {
5309 // `"1.0s"` is the trickiest drift class: numerically `1.0s` is
5310 // `1s` exactly, so the round-trip looks correct — but the
5311 // emitted canonical form is `"1s"`, not `"1.0s"`. Gate the
5312 // decimal-shape-with-integer-value form so author intent is
5313 // never silently rewritten.
5314 let err = duration_codec::parse("1.0s").unwrap_err();
5315 assert!(err.contains("\"1.0\""), "missing magnitude in {err:?}");
5316 assert!(
5317 err.contains("not a non-negative integer"),
5318 "missing canonical-form reason in {err:?}"
5319 );
5320 }
5321
5322 #[test]
5323 fn parse_rejects_half_unit_minute() {
5324 // `"0.5m"` is the unit-fraction footgun — author writes a
5325 // human-readable half-minute, serde silently rewrites to
5326 // `"30s"` on next emit. The gate names the offending
5327 // magnitude `"0.5"` and points at the integer-in-smaller-unit
5328 // form.
5329 let err = duration_codec::parse("0.5m").unwrap_err();
5330 assert!(err.contains("\"0.5\""), "missing magnitude in {err:?}");
5331 assert!(
5332 err.contains("\"30s\""),
5333 "missing canonical-form remediation in {err:?}"
5334 );
5335 }
5336
5337 #[test]
5338 fn parse_rejects_leading_plus_sign() {
5339 // `u64::from_str` rejects `"+30"` but `f64::from_str` accepts
5340 // it as `30.0` — the prior parser used f64 so `"+30s"` parsed
5341 // cleanly to 30s and round-tripped to `"30s"` on next emit
5342 // (DRIFT). The digit-only gate closes the leading-sign class
5343 // first; the diagnostic names `"+30"` verbatim.
5344 let err = duration_codec::parse("+30s").unwrap_err();
5345 assert!(err.contains("\"+30\""), "missing magnitude in {err:?}");
5346 assert!(
5347 err.contains("not a non-negative integer"),
5348 "missing canonical-form reason in {err:?}"
5349 );
5350 }
5351
5352 #[test]
5353 fn parse_rejects_leading_minus_sign() {
5354 // The former `num < 0.0` arm: `"-30s"` parsed as f64 to -30,
5355 // rejected with `"negative duration in \"-30s\""`. Under the
5356 // integer-magnitude gate the diagnostic is unified — `-30` is
5357 // non-digit-only, f64-numeric, and surfaces with the canonical-
5358 // form reason (no leading `+` / `-` sign) naming the offending
5359 // `"-30"` verbatim. Same diagnostic shape as every other
5360 // rejected non-integer magnitude.
5361 let err = duration_codec::parse("-30s").unwrap_err();
5362 assert!(err.contains("\"-30\""), "missing magnitude in {err:?}");
5363 assert!(
5364 err.contains("not a non-negative integer"),
5365 "missing canonical-form reason in {err:?}"
5366 );
5367 }
5368
5369 #[test]
5370 fn parse_garbage_still_falls_through_to_bad_magnitude() {
5371 // Non-digit-only AND non-numeric (`"--1s"`, `"abc"`) falls
5372 // through to the narrower "bad duration magnitude" arm — the
5373 // canonical-form diagnostic is reserved for the parser-shape
5374 // footgun case, not the "not a number at all" case. Same
5375 // shape `parse_byte_size`'s `BadByteMagnitude` arm carries on
5376 // the peer `:limits :memory` codec.
5377 let err = duration_codec::parse("--1s").unwrap_err();
5378 assert!(
5379 err.contains("bad duration magnitude"),
5380 "expected bad-magnitude wording in {err:?}"
5381 );
5382 }
5383
5384 #[test]
5385 fn parse_digit_only_magnitude_carries_zero_f64_drift() {
5386 // The accepted set is now closed under `u64`-exact integer
5387 // arithmetic: `"500ms"` → `Duration::from_millis(500)` exactly,
5388 // `"3600s"` → `Duration::from_secs(3600)` exactly, `"1h"` →
5389 // `Duration::from_secs(3600)` exactly, no f64 mantissa drift
5390 // possible. Pin the integer-exact arms across the four unit
5391 // suffixes so a future refactor that reaches back for f64
5392 // (`from_secs_f64`, `mul_f64`) surfaces here.
5393 assert_eq!(
5394 duration_codec::parse("3600s").unwrap(),
5395 Duration::from_secs(3600)
5396 );
5397 assert_eq!(
5398 duration_codec::parse("60m").unwrap(),
5399 Duration::from_secs(3600)
5400 );
5401 assert_eq!(
5402 duration_codec::parse("1h").unwrap(),
5403 Duration::from_secs(3600)
5404 );
5405 assert_eq!(
5406 duration_codec::parse("999ms").unwrap(),
5407 Duration::from_millis(999)
5408 );
5409 }
5410
5411 #[test]
5412 fn restart_window_serde_rejects_fractional_seconds() {
5413 // The shared codec backs `SupervisorSpec::restart_window`
5414 // (`with = "duration_codec"`) — so the gate applies on serde
5415 // deserialize for the typed Supervisor slot. A
5416 // `{"restartWindow":"1.5s"}` payload that previously round-
5417 // tripped to a different canonical string on next serialize
5418 // is now refused at deserialize with the integer-magnitude
5419 // diagnostic.
5420 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
5421 "restartWindow":"1.5s",
5422 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
5423 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5424 let msg = err.to_string();
5425 assert!(
5426 msg.contains("not a non-negative integer"),
5427 "expected integer-magnitude diagnostic in {msg:?}"
5428 );
5429 assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
5430 }
5431
5432 #[test]
5433 fn restart_window_serde_rejects_leading_plus() {
5434 // The `u64::from_str` leading-`+` permissiveness gap that
5435 // motivated the digit-only gate (the `f64`-side accepted
5436 // `"+30"`, the prior parser silently round-tripped to `"30s"`)
5437 // is now closed on the shared codec — surfaces as a structured
5438 // diagnostic at the serde layer for every typed-duration slot.
5439 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
5440 "restartWindow":"+30s",
5441 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
5442 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5443 let msg = err.to_string();
5444 assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
5445 assert!(
5446 msg.contains("not a non-negative integer"),
5447 "missing canonical-form reason in {msg:?}"
5448 );
5449 }
5450
5451 #[test]
5452 fn parse_rejects_leading_zero_magnitude() {
5453 // `"030s"` is digit-only, so the existing non-digit-only / sign
5454 // / fractional arm doesn't catch it — `u64::from_str("030")`
5455 // returns `Ok(30)`, so before this gate `"030s"` parsed to
5456 // `Duration::from_secs(30)` and round-tripped through `render`
5457 // to `"30s"` — a *different* canonical string on the next emit,
5458 // breaking the THEORY.md Part V render-determinism contract
5459 // exactly the way `"+30s"` did before the leading-`+` arm
5460 // landed. Peer with the `rate_limit_codec` leading-zero arm
5461 // (4f46830) on the same canonical-form-drift axis.
5462 let err = duration_codec::parse("030s").unwrap_err();
5463 assert!(
5464 err.contains("non-canonical leading zero"),
5465 "expected leading-zero diagnostic in {err:?}"
5466 );
5467 assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
5468 assert!(
5469 err.contains("\"30s\""),
5470 "missing canonical-form remediation in {err:?}"
5471 );
5472 assert!(
5473 err.contains("THEORY.md"),
5474 "missing render-determinism citation in {err:?}"
5475 );
5476 }
5477
5478 #[test]
5479 fn parse_rejects_multi_digit_zero_magnitude() {
5480 // `"00s"` and `"00ms"` are the all-zero leading-zero footgun —
5481 // digit-only, parse losslessly to `Duration::ZERO`, but render
5482 // back to `"0s"` (the single-byte canonical form) on the next
5483 // emit. The leading-zero arm refuses the drift class at the
5484 // codec layer; the semantic-zero gate downstream
5485 // (`SupervisorError::ZeroRestartWindow`, etc.) would refuse
5486 // the single-byte canonical form `"0s"` separately on the
5487 // typed-validate layer.
5488 let err = duration_codec::parse("00s").unwrap_err();
5489 assert!(
5490 err.contains("non-canonical leading zero"),
5491 "expected leading-zero diagnostic in {err:?}"
5492 );
5493 assert!(err.contains("\"00\""), "missing magnitude in {err:?}");
5494 }
5495
5496 #[test]
5497 fn parse_rejects_leading_zero_per_hour_window() {
5498 // `"01h"` is the per-hour-window footgun — multi-byte magnitude
5499 // starting with `0`, parses losslessly to `Duration::from_secs(3600)`,
5500 // renders to `"1h"` (DRIFT). The arm is unit-agnostic: every
5501 // canonical unit suffix the codec accepts (`ms` / `s` / `m` /
5502 // `h` / bare-integer-as-seconds) inherits the same gate.
5503 let err = duration_codec::parse("01h").unwrap_err();
5504 assert!(
5505 err.contains("non-canonical leading zero"),
5506 "expected leading-zero diagnostic in {err:?}"
5507 );
5508 assert!(err.contains("\"01\""), "missing magnitude in {err:?}");
5509 }
5510
5511 #[test]
5512 fn parse_rejects_leading_zero_bare_integer_as_seconds() {
5513 // The `parse_accepts_bare_integer_as_seconds` happy-path
5514 // (`"30"` → 30s) inherits the leading-zero arm: `"030"` is
5515 // multi-byte starts-with-`0`, parses losslessly to
5516 // `Duration::from_secs(30)`, renders to `"30s"` (DRIFT). The
5517 // bare-integer surface accepts permissive unit-empty
5518 // shorthand but still must reject leading-zero padding.
5519 let err = duration_codec::parse("030").unwrap_err();
5520 assert!(
5521 err.contains("non-canonical leading zero"),
5522 "expected leading-zero diagnostic in {err:?}"
5523 );
5524 assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
5525 }
5526
5527 #[test]
5528 fn parse_accepts_single_zero_magnitude_at_codec_layer() {
5529 // The codec-layer / typed-validate-layer boundary: `"0s"` /
5530 // `"0ms"` / `"0"` are the single-byte canonical-zero forms —
5531 // each round-trips losslessly through `render`
5532 // (`render(Duration::ZERO)` → `"0s"`), so the codec layer
5533 // accepts them. The downstream semantic-zero gates
5534 // (`SupervisorError::ZeroRestartWindow`,
5535 // `AplicacaoError::PolicyTimeoutZero`,
5536 // `AplicacaoError::PolicyCircuitBreakerWindowZero`) refuse
5537 // zero-magnitude authoring at the typed-validate layer above,
5538 // peer with the `rate_limit_codec` codec-layer / typed-
5539 // validate-layer partition for `"0/s"`.
5540 assert_eq!(duration_codec::parse("0s").unwrap(), Duration::ZERO);
5541 assert_eq!(duration_codec::parse("0ms").unwrap(), Duration::ZERO);
5542 assert_eq!(duration_codec::parse("0").unwrap(), Duration::ZERO);
5543 }
5544
5545 #[test]
5546 fn parse_accepts_canonical_magnitude_with_leading_one() {
5547 // The complementary boundary: a future tightening cannot
5548 // drift into rejecting valid canonical magnitudes that
5549 // happen to start with `1` (or any digit `[1-9]`). Pin
5550 // every canonical-unit suffix so the leading-zero arm
5551 // remains strictly narrower than the digit-only arm.
5552 assert_eq!(
5553 duration_codec::parse("100ms").unwrap(),
5554 Duration::from_millis(100)
5555 );
5556 assert_eq!(
5557 duration_codec::parse("100s").unwrap(),
5558 Duration::from_secs(100)
5559 );
5560 assert_eq!(
5561 duration_codec::parse("10m").unwrap(),
5562 Duration::from_secs(600)
5563 );
5564 assert_eq!(
5565 duration_codec::parse("10h").unwrap(),
5566 Duration::from_secs(36_000)
5567 );
5568 }
5569
5570 #[test]
5571 fn restart_window_serde_rejects_leading_zero() {
5572 // The shared codec backs `SupervisorSpec::restart_window`
5573 // (`with = "duration_codec"`) — so the leading-zero arm
5574 // applies on serde deserialize for the typed Supervisor slot.
5575 // A `{"restartWindow":"030s"}` payload that previously round-
5576 // tripped to a different canonical string on next serialize
5577 // is now refused at deserialize with the leading-zero
5578 // diagnostic. Peer with `restart_window_serde_rejects_leading_plus`
5579 // / `restart_window_serde_rejects_fractional_seconds` on the
5580 // same canonical-form-drift axis.
5581 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
5582 "restartWindow":"030s",
5583 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
5584 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5585 let msg = err.to_string();
5586 assert!(
5587 msg.contains("non-canonical leading zero"),
5588 "expected leading-zero diagnostic in {msg:?}"
5589 );
5590 assert!(msg.contains("\"030\""), "missing magnitude in {msg:?}");
5591 }
5592
5593 #[test]
5594 fn parse_rejects_leading_whitespace() {
5595 // `" 30s"` — the canonical paste-from-aligned-doc /
5596 // paste-from-YAML-quoted-plain-scalar footgun. Before this
5597 // gate the top-level `s.trim()` at parse entry silently ate
5598 // the leading space and parsed the value to
5599 // `Duration::from_secs(30)`, which then round-tripped through
5600 // `render` to `"30s"` (a *different* canonical string on the
5601 // next emit) — the exact canonical-form-drift class the
5602 // leading-`+` / leading-zero arms already close, extended
5603 // to the whitespace-byte class. Peer with the sibling
5604 // `rate_limit_codec` whitespace-rejection arm (1ad7755) on
5605 // the M3 `:politicas` axis.
5606 let err = duration_codec::parse(" 30s").unwrap_err();
5607 assert!(
5608 err.contains("contains whitespace byte"),
5609 "expected whitespace diagnostic in {err:?}"
5610 );
5611 assert!(err.contains("0x20"), "missing offending byte in {err:?}");
5612 assert!(
5613 err.contains("THEORY.md"),
5614 "missing render-determinism contract citation in {err:?}"
5615 );
5616 }
5617
5618 #[test]
5619 fn parse_rejects_trailing_whitespace() {
5620 // `"30s "` — the canonical shell-history / trailing-space
5621 // paste footgun. Before this gate the top-level `s.trim()`
5622 // silently ate the trailing space and parsed to
5623 // `Duration::from_secs(30)`, round-tripping to `"30s"` on the
5624 // next emit — same canonical-form drift as the leading-space
5625 // sibling, closed on the same whitespace-byte arm.
5626 let err = duration_codec::parse("30s ").unwrap_err();
5627 assert!(
5628 err.contains("contains whitespace byte"),
5629 "expected whitespace diagnostic in {err:?}"
5630 );
5631 assert!(err.contains("0x20"), "missing offending byte in {err:?}");
5632 }
5633
5634 #[test]
5635 fn parse_rejects_internal_whitespace_between_magnitude_and_unit() {
5636 // `"30 s"` — the canonical typographically-spaced author
5637 // shape (the same idiom every prose reference to a duration
5638 // renders as, mistakenly retained when the value is pasted
5639 // into a codec-shaped slot). Before this gate the per-part
5640 // `num_part.trim()` / `unit.trim()` calls silently ate the
5641 // whitespace between the magnitude and the unit and parsed
5642 // the value to `Duration::from_secs(30)`, round-tripping to
5643 // `"30s"` — the codec's *internal* whitespace-tolerance
5644 // vector, orthogonal to the leading / trailing surface but
5645 // the same canonical-form-drift class. Pins the arm as
5646 // strictly stronger than the pre-existing top-level
5647 // `s.trim()` behavior: it fires on whitespace anywhere in
5648 // the value, not just at the string boundary.
5649 let err = duration_codec::parse("30 s").unwrap_err();
5650 assert!(
5651 err.contains("contains whitespace byte"),
5652 "expected whitespace diagnostic in {err:?}"
5653 );
5654 assert!(err.contains("0x20"), "missing offending byte in {err:?}");
5655 }
5656
5657 #[test]
5658 fn parse_rejects_tab_byte() {
5659 // `"\t30s"` — the canonical paste-from-indented-doc /
5660 // paste-from-YAML-block-scalar footgun where a tab byte leads
5661 // the magnitude. Pins that the gate covers tab (`0x09`) as
5662 // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
5663 // members and both would be silently swallowed by `s.trim()`
5664 // pre-gate. The `is_ascii_whitespace` coverage extends beyond
5665 // space alone to the full ASCII-whitespace set (space `0x20`,
5666 // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
5667 // the tab arm as a representative of the non-space members.
5668 let err = duration_codec::parse("\t30s").unwrap_err();
5669 assert!(
5670 err.contains("contains whitespace byte"),
5671 "expected whitespace diagnostic in {err:?}"
5672 );
5673 assert!(
5674 err.contains("0x09"),
5675 "missing offending tab byte in {err:?}"
5676 );
5677 }
5678
5679 #[test]
5680 fn restart_window_serde_rejects_whitespace() {
5681 // The shared codec backs `SupervisorSpec::restart_window`
5682 // (`with = "duration_codec"`) — so the whitespace arm
5683 // applies on serde deserialize for the typed Supervisor slot.
5684 // A `{"restartWindow":" 30s"}` payload that previously round-
5685 // tripped to a different canonical string on next serialize
5686 // is now refused at deserialize with the whitespace-byte
5687 // diagnostic. Peer with `restart_window_serde_rejects_leading_zero`
5688 // / `restart_window_serde_rejects_leading_plus` /
5689 // `restart_window_serde_rejects_fractional_seconds` on the
5690 // same canonical-form-drift axis.
5691 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
5692 "restartWindow":" 30s",
5693 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
5694 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
5695 let msg = err.to_string();
5696 assert!(
5697 msg.contains("contains whitespace byte"),
5698 "expected whitespace diagnostic in {msg:?}"
5699 );
5700 assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
5701 }
5702
5703 // ── canonical-form: non-ASCII Unicode `White_Space` duration gate ─────
5704 //
5705 // Successor to the ASCII-whitespace arm (a7ae622) on the shared
5706 // duration codec — closes the strictly-complementary class the
5707 // byte-scan cannot see, through the lifted
5708 // [`crate::render::find_non_ascii_whitespace_char`] predicate.
5709 // Applies to `:supervisor :restart-window`, `:politicas :timeout`,
5710 // and `:politicas :circuit-breaker :window` simultaneously via
5711 // this shared codec.
5712
5713 #[test]
5714 fn duration_codec_parse_rejects_leading_nbsp() {
5715 // NBSP prefix — the strictly-complementary drift class the
5716 // ASCII byte-scan cannot see. `str::trim` strips it silently
5717 // and the value drifts to `"30s"` on next serialize.
5718 let err = duration_codec::parse("\u{00A0}30s").unwrap_err();
5719 assert!(
5720 err.contains("non-ASCII Unicode whitespace character"),
5721 "expected non-ASCII whitespace diagnostic in {err:?}"
5722 );
5723 assert!(err.contains("U+00A0"), "missing codepoint in {err:?}");
5724 }
5725
5726 #[test]
5727 fn duration_codec_parse_rejects_trailing_line_separator() {
5728 // LINE SEPARATOR (`\u{2028}`) trailing — paste-from-web-doc
5729 // footgun.
5730 let err = duration_codec::parse("30s\u{2028}").unwrap_err();
5731 assert!(
5732 err.contains("non-ASCII Unicode whitespace character"),
5733 "expected non-ASCII whitespace diagnostic in {err:?}"
5734 );
5735 assert!(err.contains("U+2028"), "missing codepoint in {err:?}");
5736 }
5737
5738 #[test]
5739 fn duration_codec_parse_accepts_ascii_only_forms_after_unicode_arm() {
5740 // Positive-control pin: every ASCII-only canonical form the
5741 // renderer emits stays accepted through the new arm.
5742 assert_eq!(
5743 duration_codec::parse("30s").unwrap(),
5744 Duration::from_secs(30)
5745 );
5746 assert_eq!(
5747 duration_codec::parse("500ms").unwrap(),
5748 Duration::from_millis(500)
5749 );
5750 assert_eq!(
5751 duration_codec::parse("1h").unwrap(),
5752 Duration::from_secs(3600)
5753 );
5754 }
5755
5756 #[test]
5757 fn restart_window_serde_rejects_non_ascii_whitespace() {
5758 // The shared codec backs `SupervisorSpec::restart_window` — so
5759 // the new non-ASCII Unicode whitespace arm applies on serde
5760 // deserialize for the typed Supervisor slot. A
5761 // `{"restartWindow":" 30s"}` payload that previously
5762 // survived the ASCII byte-scan (only ASCII whitespace was
5763 // refused) is now refused at deserialize with the
5764 // non-ASCII-whitespace-and-codepoint diagnostic.
5765 let payload = "{\"estrategia\":\"OneForOne\",\"maxRestarts\":5,\
5766 \"restartWindow\":\"\u{00A0}30s\",\
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("non-ASCII Unicode whitespace character"),
5772 "expected non-ASCII whitespace diagnostic in {msg:?}"
5773 );
5774 assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
5775 }
5776
5777 // ── drift-detection: serde-derive-to-SUPERVISOR_KEY_* identity ────────
5778
5779 #[test]
5780 fn supervisor_spec_serde_keys_match_lifted_supervisor_key_consts() {
5781 // Load-bearing invariant: the four `SUPERVISOR_KEY_*` consts
5782 // (`SUPERVISOR_KEY_ESTRATEGIA` / `SUPERVISOR_KEY_MAX_RESTARTS` /
5783 // `SUPERVISOR_KEY_RESTART_WINDOW` / `SUPERVISOR_KEY_CHILDREN`)
5784 // name the exact camelCase JSON keys the
5785 // `#[serde(rename_all = "camelCase")]` attribute on
5786 // `SupervisorSpec` emits. Serialize a fully-populated spec (each
5787 // field carries `Some(_)` / non-empty) and pin that each canonical
5788 // byte-sequence appears verbatim in the JSON — a future accidental
5789 // `rename_all = "snake_case"` / `"kebab-case"` / verbatim-field-
5790 // name flip at the derive attribute (any of which would silently
5791 // break every downstream JSON consumer that reaches for one of the
5792 // four consts via `Value::get(...)`) surfaces here as a build-time
5793 // test failure at `supervisor.rs`, not as an apply-time
5794 // `.get(<stale-canonical-const>)` returning `None` far from the
5795 // derive-attr drift's commit. Peer with the sibling
5796 // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
5797 // (d8b8b4f) pin on the M2 `:limits` axis — same discipline the
5798 // M2 typed-slot family established, extended here to close the
5799 // top-level Supervisor axis.
5800 let spec = SupervisorSpec {
5801 estrategia: RestartStrategy::OneForOne,
5802 max_restarts: 5,
5803 restart_window: Some(Duration::from_secs(60)),
5804 children: vec![ChildSpec {
5805 caixa: "w".into(),
5806 versao: "^0.1".into(),
5807 restart: RestartPolicy::Permanent,
5808 }],
5809 };
5810 let json = serde_json::to_string(&spec).unwrap();
5811 for key in [
5812 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
5813 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
5814 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
5815 crate::render::SUPERVISOR_KEY_CHILDREN,
5816 ] {
5817 let quoted = format!("\"{key}\"");
5818 assert!(
5819 json.contains("ed),
5820 "serialized SupervisorSpec must carry the lifted \
5821 SUPERVISOR_KEY_* byte-sequence {quoted} verbatim in \
5822 the JSON emission (got: {json})",
5823 );
5824 }
5825 }
5826
5827 #[test]
5828 fn supervisor_key_consts_are_pairwise_distinct() {
5829 // Cross-axis drift-detection pin: a future collapse of two
5830 // canonical top-level byte-strings onto the same value (e.g. an
5831 // accidental copy-paste flip of `SUPERVISOR_KEY_CHILDREN` to
5832 // also read `"estrategia"`) would silently reroute every
5833 // downstream probe on one axis onto the sibling axis's overlay
5834 // entry and pass every propagation-probe test that expected only
5835 // the stale axis's value. Peer of the sibling four-way distinct
5836 // pin on the `M2_LIMITS_KEY_*` tetrad (d8b8b4f).
5837 let all = [
5838 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
5839 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
5840 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
5841 crate::render::SUPERVISOR_KEY_CHILDREN,
5842 ];
5843 for (i, a) in all.iter().enumerate() {
5844 for b in all.iter().skip(i + 1) {
5845 assert_ne!(
5846 a, b,
5847 "SUPERVISOR_KEY_* consts must be pairwise-distinct \
5848 canonical byte-sequences — got `{a}` == `{b}`",
5849 );
5850 }
5851 }
5852 }
5853
5854 #[test]
5855 fn supervisor_key_consts_are_lower_camel_case_shape() {
5856 // Shape-pin: every `SUPERVISOR_KEY_*` const must be a
5857 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
5858 // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
5859 // capital, no whitespace / dots) — the canonical shape the
5860 // `#[serde(rename_all = "camelCase")]` derive produces on
5861 // `SupervisorSpec`. A future flip to a non-camelCase attribute
5862 // at the derive surfaces both here (this test fails on the
5863 // stale-constant shape) and at
5864 // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
5865 // (that test fails on the mismatch between const and derive).
5866 // Peer with `m2_limits_key_consts_are_lower_camel_case_shape`
5867 // (d8b8b4f) on the sibling M2 `:limits` axis.
5868 for key in [
5869 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
5870 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
5871 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
5872 crate::render::SUPERVISOR_KEY_CHILDREN,
5873 ] {
5874 assert!(
5875 !key.is_empty(),
5876 "SUPERVISOR_KEY_* must be non-empty (got {key:?})"
5877 );
5878 let first = key.chars().next().unwrap();
5879 assert!(
5880 first.is_ascii_lowercase(),
5881 "SUPERVISOR_KEY_* must lead with an ASCII-lowercase byte \
5882 (got {key:?}, leads with {first:?})",
5883 );
5884 assert!(
5885 key.chars().all(|c| c.is_ascii_alphanumeric()),
5886 "SUPERVISOR_KEY_* must be ASCII-alphanumeric only \
5887 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
5888 );
5889 }
5890 }
5891
5892 #[test]
5893 fn supervisor_key_consts_are_byte_distinct_from_supervisor_author_key_peers() {
5894 // Cross-axis drift pin: the four `SUPERVISOR_KEY_*` consts
5895 // (camelCase JSON keys, no leading colon) must never collide
5896 // byte-for-byte with the four peer `SUPERVISOR_AUTHOR_KEY_*`
5897 // consts (kebab-case author-facing labels with leading colon)
5898 // that sit next to them at `caixa_core::render`. Both families
5899 // cover the same four typed Supervisor slots on two distinct
5900 // axes (author-side kebab vs renderer-side camelCase);
5901 // collapsing either family onto the other's byte-shape would
5902 // silently reroute the render-side probe onto the author-facing
5903 // surface, or vice versa. Peer of the byte-distinctness
5904 // discipline the `M3_PLACEMENT_KEY_ESTRATEGIA` docstring names
5905 // against the peer `M3_AUTHOR_KEY_PLACEMENT`.
5906 let pairs = [
5907 (
5908 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
5909 crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA,
5910 ),
5911 (
5912 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
5913 crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS,
5914 ),
5915 (
5916 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
5917 crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW,
5918 ),
5919 (
5920 crate::render::SUPERVISOR_KEY_CHILDREN,
5921 crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN,
5922 ),
5923 ];
5924 for (json_key, author_key) in pairs {
5925 assert_ne!(
5926 json_key, author_key,
5927 "SUPERVISOR_KEY_* (JSON side) must differ byte-for-byte \
5928 from the peer SUPERVISOR_AUTHOR_KEY_* (author side); \
5929 got JSON `{json_key}` == author `{author_key}`",
5930 );
5931 }
5932 }
5933
5934 // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_KEY_* identity ──
5935
5936 #[test]
5937 fn child_spec_serde_keys_match_lifted_supervisor_child_key_consts() {
5938 // Load-bearing invariant: the three `SUPERVISOR_CHILD_KEY_*` consts
5939 // (`SUPERVISOR_CHILD_KEY_CAIXA` / `SUPERVISOR_CHILD_KEY_VERSAO` /
5940 // `SUPERVISOR_CHILD_KEY_RESTART`) name the exact camelCase JSON
5941 // keys the `#[serde(rename_all = "camelCase")]` attribute on
5942 // `ChildSpec` emits. Serialize a fully-populated `ChildSpec` and
5943 // pin that each canonical byte-sequence appears verbatim in the
5944 // JSON — a future accidental `rename_all = "snake_case"` /
5945 // `"kebab-case"` / verbatim-field-name flip at the derive
5946 // attribute (any of which would silently break every downstream
5947 // JSON consumer that reaches for one of the three consts via
5948 // `Value::get(...)`) surfaces here as a build-time test failure at
5949 // `supervisor.rs`, not as an apply-time
5950 // `.get(<stale-canonical-const>)` returning `None` far from the
5951 // derive-attr drift's commit. Peer with the enclosing
5952 // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
5953 // (40cc4e5) pin on the M2 supervision-tree top-level axis — same
5954 // discipline the SupervisorSpec top-level lift established,
5955 // extended here to the sibling per-`:children` entry `ChildSpec`
5956 // derive so the last M2 typed-struct sub-block
5957 // `#[serde(rename_all = "camelCase")]` axis on the Supervisor
5958 // surface without a lifted serde-key peer joins the substrate's
5959 // "one canonical byte-string per typed serialized-key axis"
5960 // discipline.
5961 let c = ChildSpec {
5962 caixa: "worker".into(),
5963 versao: "^0.1".into(),
5964 restart: RestartPolicy::Permanent,
5965 };
5966 let json = serde_json::to_string(&c).unwrap();
5967 for key in [
5968 crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
5969 crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
5970 crate::render::SUPERVISOR_CHILD_KEY_RESTART,
5971 ] {
5972 let quoted = format!("\"{key}\"");
5973 assert!(
5974 json.contains("ed),
5975 "serialized ChildSpec must carry the lifted \
5976 SUPERVISOR_CHILD_KEY_* byte-sequence {quoted} verbatim \
5977 in the JSON emission (got: {json})",
5978 );
5979 }
5980 }
5981
5982 #[test]
5983 fn supervisor_child_key_consts_are_pairwise_distinct() {
5984 // Cross-axis drift-detection pin: a future collapse of two
5985 // canonical `ChildSpec` per-entry byte-strings onto the same
5986 // value (e.g. an accidental copy-paste flip of
5987 // `SUPERVISOR_CHILD_KEY_RESTART` to also read `"caixa"`) would
5988 // silently reroute every downstream probe on one axis onto the
5989 // sibling axis's overlay entry and pass every propagation-probe
5990 // test that expected only the stale axis's value. Peer of the
5991 // sibling three-way distinct pin on the `CONTRATO_KEY_*` triad
5992 // (ca463a4) and the two-way distinct pin on the `MEMBRO_KEY_*`
5993 // pair (ce80ca0).
5994 let all = [
5995 crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
5996 crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
5997 crate::render::SUPERVISOR_CHILD_KEY_RESTART,
5998 ];
5999 for (i, a) in all.iter().enumerate() {
6000 for b in all.iter().skip(i + 1) {
6001 assert_ne!(
6002 a, b,
6003 "SUPERVISOR_CHILD_KEY_* consts must be pairwise-\
6004 distinct canonical byte-sequences — got `{a}` == `{b}`",
6005 );
6006 }
6007 }
6008 }
6009
6010 #[test]
6011 fn supervisor_child_key_consts_are_lower_camel_case_shape() {
6012 // Shape-pin: every `SUPERVISOR_CHILD_KEY_*` const must be a
6013 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
6014 // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
6015 // capital, no whitespace / dots) — the canonical shape the
6016 // `#[serde(rename_all = "camelCase")]` derive produces on
6017 // `ChildSpec`. A future flip to a non-camelCase attribute at the
6018 // derive surfaces both here (this test fails on the
6019 // stale-constant shape) and at
6020 // `child_spec_serde_keys_match_lifted_supervisor_child_key_consts`
6021 // (that test fails on the mismatch between const and derive).
6022 // Peer with `supervisor_key_consts_are_lower_camel_case_shape`
6023 // (40cc4e5) on the sibling `SupervisorSpec` top-level axis.
6024 for key in [
6025 crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
6026 crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
6027 crate::render::SUPERVISOR_CHILD_KEY_RESTART,
6028 ] {
6029 assert!(
6030 !key.is_empty(),
6031 "SUPERVISOR_CHILD_KEY_* must be non-empty (got {key:?})"
6032 );
6033 let first = key.chars().next().unwrap();
6034 assert!(
6035 first.is_ascii_lowercase(),
6036 "SUPERVISOR_CHILD_KEY_* must lead with an ASCII-lowercase \
6037 byte (got {key:?}, leads with {first:?})",
6038 );
6039 assert!(
6040 key.chars().all(|c| c.is_ascii_alphanumeric()),
6041 "SUPERVISOR_CHILD_KEY_* must be ASCII-alphanumeric only \
6042 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
6043 );
6044 }
6045 }
6046
6047 // ── drift-detection: serde-derive-to-SUPERVISOR_ESTRATEGIA_* identity ────
6048
6049 #[test]
6050 fn restart_strategy_variants_serialize_to_lifted_scalar_values() {
6051 // The fail-before-pass-after pin: pre-lift there was no
6052 // single-source binding between the [`RestartStrategy`] variant
6053 // name the un-`rename`d `Serialize` derive emits under
6054 // [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the byte-string
6055 // every downstream cluster-side dispatcher (the future
6056 // wasm-operator's per-supervisor sibling-restart branch, the
6057 // future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
6058 // admission-time enum-arm bind, the `caixa-operator`'s
6059 // hierarchical reconciliation scheduler's per-strategy fan-out)
6060 // probes verbatim. A future `#[serde(rename_all = "kebab-case")]`
6061 // attribute on the enum — or a per-variant `#[serde(rename = "…")]`
6062 // override, or a variant rename in the source — would silently
6063 // rebrand the emitted scalar under one spelling while every
6064 // downstream dispatcher still probed the other, with the failure
6065 // surfacing at the operator's reconcile posture (subtrees coming
6066 // up under the `default()` `OneForOne` arm rather than the typed
6067 // slot's declared strategy — a bad child would then only take
6068 // itself down instead of the sibling set the author intended, so
6069 // shared-state children fall out of sync) far from the source
6070 // rebrand commit and with no field naming the drift. Pinning the
6071 // two paths (the `Serialize` derive's serialized string AND the
6072 // [`RestartStrategy::as_str`] helper) to the same four lifted
6073 // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
6074 // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
6075 // [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
6076 // [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
6077 // byte-strings makes any future drift on either endpoint fail
6078 // here at caixa-core build time. Peer of the M3
6079 // `placement_strategy_variants_serialize_to_lifted_scalar_values`
6080 // (3f0e21c) on the sibling `PlacementStrategy` axis — same
6081 // three-path-convergence discipline, extended to close the
6082 // OTP-shaped per-supervisor sibling-restart axis.
6083 for (variant, expected) in [
6084 (
6085 RestartStrategy::OneForOne,
6086 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
6087 ),
6088 (
6089 RestartStrategy::OneForAll,
6090 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
6091 ),
6092 (
6093 RestartStrategy::RestForOne,
6094 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
6095 ),
6096 (
6097 RestartStrategy::SimpleOneForOne,
6098 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
6099 ),
6100 ] {
6101 let json = serde_json::to_string(&variant).unwrap();
6102 assert_eq!(
6103 json,
6104 format!("\"{expected}\""),
6105 "RestartStrategy::{variant:?} must serialize to {expected:?}"
6106 );
6107 assert_eq!(
6108 variant.as_str(),
6109 expected,
6110 "RestartStrategy::{variant:?}.as_str() must return the lifted \
6111 SUPERVISOR_ESTRATEGIA_* constant"
6112 );
6113 }
6114 }
6115
6116 #[test]
6117 fn supervisor_estrategia_consts_are_pairwise_distinct() {
6118 // Cross-arm drift-detection pin: a future collapse of two
6119 // canonical variant byte-strings onto the same value (e.g. an
6120 // accidental copy-paste flip of `SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`
6121 // to also read `"OneForOne"`) would silently reroute every
6122 // downstream operator's per-strategy dispatch onto the sibling
6123 // arm's reconcile branch and pass every propagation-probe test
6124 // that expected only the stale arm's value — the mis-strategied
6125 // subtree would come up with the wrong sibling-restart posture
6126 // on every subsequent failure. Peer of the sibling four-way
6127 // distinct pin `supervisor_key_consts_are_pairwise_distinct`
6128 // (40cc4e5) on the top-level `SUPERVISOR_KEY_*` axis.
6129 let all = [
6130 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
6131 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
6132 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
6133 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
6134 ];
6135 for (i, a) in all.iter().enumerate() {
6136 for (j, b) in all.iter().enumerate() {
6137 if i != j {
6138 assert_ne!(
6139 a, b,
6140 "SUPERVISOR_ESTRATEGIA_* consts must be pairwise distinct \
6141 — got duplicate {a:?} at indices {i} and {j}",
6142 );
6143 }
6144 }
6145 }
6146 }
6147
6148 #[test]
6149 fn restart_strategy_display_routes_through_as_str_helper() {
6150 // The fail-before-pass-after pin on the first half of the
6151 // three-path convergence: pre-convergence the sibling
6152 // OTP-shape typed enum [`RestartStrategy`] carried a
6153 // [`std::fmt::Display`] surface via its
6154 // `#[discriminant(also_display)]` gen-platform derive route,
6155 // which arrived kebab-case as `"one-for-one"` /
6156 // `"one-for-all"` / `"rest-for-one"` /
6157 // `"simple-one-for-one"` while the wire format ran as
6158 // PascalCase `"OneForOne"` / `"OneForAll"` / `"RestForOne"` /
6159 // `"SimpleOneForOne"` through the un-`rename`d serde derive.
6160 // Every consumer reaching for a strategy byte-string past the
6161 // wire format had to pick between three paths
6162 // ([`RestartStrategy::as_str`], the `Serialize` derive's
6163 // serialized string, or `format!("{v}")` on the
6164 // discriminant-Display route), any two of which a future
6165 // variant rename or `#[serde(rename_all = "kebab-case")]`
6166 // attribute would silently desynchronize. Wiring
6167 // [`std::fmt::Display`] through [`RestartStrategy::as_str`]
6168 // closes the third path: every `format!("{v}")` call reaches
6169 // the same lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
6170 // const the wire format and the [`RestartStrategy::as_str`]
6171 // helper already route through, so a future variant rename
6172 // lands at exactly one place. Pin the routing here so a future
6173 // `impl std::fmt::Display for RestartStrategy`
6174 // reimplementation that hand-rolls the arms instead of
6175 // delegating to [`RestartStrategy::as_str`] fails at
6176 // caixa-core build time. Peer of the M3
6177 // `placement_strategy_display_routes_through_as_str_helper`
6178 // (cc8f749) which the M3 axis converged first.
6179 for &variant in RestartStrategy::ALL {
6180 assert_eq!(
6181 variant.to_string(),
6182 variant.as_str(),
6183 "RestartStrategy::{variant:?} Display must route through \
6184 RestartStrategy::as_str (single source of truth: the lifted \
6185 SUPERVISOR_ESTRATEGIA_* const the wire format also emits)"
6186 );
6187 }
6188 }
6189
6190 #[test]
6191 fn restart_strategy_display_matches_serialized_wire_byte_string() {
6192 // The fail-before-pass-after pin on the second half of the
6193 // three-path convergence: `Display` (user-facing text) agrees
6194 // byte-for-byte with the `Serialize` derive's wire format
6195 // (canonical camelCase-schema `SUPERVISOR_KEY_ESTRATEGIA`
6196 // scalar) on every variant. Pre-convergence the two paths
6197 // were structurally independent — a future
6198 // `#[serde(rename_all = "kebab-case")]` attribute on the
6199 // enum would silently rebrand the emitted wire scalar
6200 // (`one-for-one`, `one-for-all`, `rest-for-one`,
6201 // `simple-one-for-one`) while every consumer that
6202 // pretty-prints the strategy (the future wasm-operator's
6203 // per-supervisor sibling-restart-strategy diagnostic line,
6204 // the future `feira app graph` per-supervisor strategy line,
6205 // the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
6206 // materializer's admission-webhook rejection body) would
6207 // still emit the PascalCase form the `as_str` / `Display`
6208 // route returns, with the mismatch surfacing at consumer
6209 // parse time / operator dispatch time far from the source
6210 // rebrand commit. Pin the two paths byte-for-byte here so any
6211 // future serde-attribute or variant-rename drift is a
6212 // caixa-core-build-time test failure at this call, not a
6213 // silent per-consumer dispatch miss. Peer of the M3
6214 // `placement_strategy_display_matches_serialized_wire_byte_string`
6215 // (cc8f749) which the M3 axis converged first.
6216 for &variant in RestartStrategy::ALL {
6217 let wire = serde_json::to_string(&variant).unwrap();
6218 let unquoted = wire
6219 .strip_prefix('"')
6220 .and_then(|s| s.strip_suffix('"'))
6221 .expect("serialized RestartStrategy is a JSON string");
6222 assert_eq!(
6223 variant.to_string(),
6224 unquoted,
6225 "RestartStrategy::{variant:?} Display byte-string must match the \
6226 Serialize derive's wire byte-string (three-path convergence: \
6227 Display + as_str + Serialize all resolve to the same \
6228 SUPERVISOR_ESTRATEGIA_* const)"
6229 );
6230 }
6231 }
6232
6233 #[test]
6234 fn restart_strategy_as_ref_str_routes_through_as_str_accessor() {
6235 // Fail-before-pass-after byte-parity pin on the lifted
6236 // `impl AsRef<str> for RestartStrategy` — asserts the
6237 // standard-library trait impl and the substrate-primitive
6238 // [`RestartStrategy::as_str`] `pub const fn` accessor resolve
6239 // to the same `&str` per instance across the four-arm
6240 // closed set, so any future silent detour that routes the
6241 // impl through a divergent projection (a per-arm inline
6242 // `match self { RestartStrategy::OneForOne => "OneForOne", … }`
6243 // re-inlining that opens a compile-time link to the un-lifted
6244 // arm-literal, a swap onto the kebab-case
6245 // [`gen_platform::Discriminant`] catalog identity that would
6246 // collide the wire axis with the dispatcher-catalog axis) trips
6247 // at caixa-core test time under `PartialEq` rather than at a
6248 // downstream `impl AsRef<str>`-bound consumer's silent split.
6249 // Sweeps every one of the four arms
6250 // [`RestartStrategy::ALL`] carries so no arm's projection is
6251 // covered only by the sibling wire-format `Serialize` derive
6252 // path. Peer of the sibling
6253 // [`crate::version::tests::caixa_version_as_ref_str_routes_through_as_str_accessor`]
6254 // (16d5c7e) `AsRef<str>`-byte-parity pin on the paired
6255 // top-level `:versao` typed newtype — the two pins together
6256 // cover the substrate primitive's `AsRef<str>` projection axis
6257 // on the paired newtype + closed-set-typed-enum surface.
6258 for &variant in RestartStrategy::ALL {
6259 assert_eq!(
6260 <RestartStrategy as AsRef<str>>::as_ref(&variant),
6261 variant.as_str(),
6262 "AsRef<str> impl on RestartStrategy::{variant:?} must \
6263 byte-equal RestartStrategy::as_str on the same instance \
6264 — divergence signals a silent detour off the substrate-\
6265 primitive accessor"
6266 );
6267 }
6268 }
6269
6270 #[test]
6271 fn restart_strategy_as_ref_str_routes_through_display_via_shared_accessor() {
6272 // Fail-before-pass-after byte-parity pin on the three-path
6273 // convergence discipline the M2 sibling-restart primitive now
6274 // carries on the `&str`-projection axis:
6275 // `<RestartStrategy as AsRef<str>>::as_ref(&s)` (the newly
6276 // lifted impl), `format!("{s}")` (the pre-existing
6277 // [`fmt::Display`] impl), and `s.as_str()` (the substrate-
6278 // primitive `pub const fn` accessor both trait impls delegate
6279 // through) must resolve to the same byte-string on every
6280 // instance across the four-arm closed set. Refuses any future
6281 // divergence between the two trait impls (a stray
6282 // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
6283 // rather than delegating through the shared accessor; a
6284 // hypothetical `AsRef<str>` rewrite that inlines a per-arm
6285 // literal cascade) that would silently split the two
6286 // projection paths of the same closed-set typed enum. Mirrors
6287 // the sibling three-path-convergence discipline the peer
6288 // [`crate::CaixaVersion`] typed newtype carries on its
6289 // `AsRef<str>` / `Display` / `as_str` triple
6290 // (version.rs pin
6291 // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
6292 // 16d5c7e).
6293 for &variant in RestartStrategy::ALL {
6294 let via_as_ref: &str = <RestartStrategy as AsRef<str>>::as_ref(&variant);
6295 let via_display: String = format!("{variant}");
6296 let via_accessor: &str = variant.as_str();
6297 assert_eq!(via_as_ref, via_accessor);
6298 assert_eq!(via_display, via_accessor);
6299 assert_eq!(via_as_ref, via_display.as_str());
6300 }
6301 }
6302
6303 #[test]
6304 fn restart_strategy_all_enumerates_every_variant_exactly_once() {
6305 // Fail-before-pass-after pin on the [`RestartStrategy::ALL`]
6306 // exhaustive-iteration surface: every variant appears exactly
6307 // once, and the slice length matches the arm count of the
6308 // closed set. Every consumer that walks the accepted-strategy
6309 // set (a future `feira supervisor --estrategia …` CLI-side
6310 // arg-parse's "did you mean" hint, a future M4 admission-
6311 // webhook's rejection body naming the accepted-`:estrategia`
6312 // list, the [`RestartStrategy::from_wire`] reverse-projection
6313 // consumers that iterate the accept-set for diagnostic
6314 // rendering) reads through this slice, so a future arm addition
6315 // that grows the enum but forgets to grow [`Self::ALL`]
6316 // silently truncates every downstream consumer's accept-set at
6317 // the same pre-addition boundary — this pin fails at caixa-core
6318 // build time on the pairwise-distinct + arm-count invariants.
6319 //
6320 // Peer of the sibling [`crate::CaixaKind::ALL`] (6b1f4fb) /
6321 // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
6322 // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
6323 // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
6324 // pins on the peer closed-set typed-enum axes.
6325 let all: &[RestartStrategy] = RestartStrategy::ALL;
6326 assert_eq!(
6327 all.len(),
6328 4,
6329 "RestartStrategy::ALL must enumerate every variant of the \
6330 four-arm closed set (OneForOne, OneForAll, RestForOne, \
6331 SimpleOneForOne); got {all:?}"
6332 );
6333 for (i, a) in all.iter().enumerate() {
6334 for (j, b) in all.iter().enumerate() {
6335 if i != j {
6336 assert_ne!(
6337 a, b,
6338 "RestartStrategy::ALL must carry every variant exactly \
6339 once — got duplicate {a:?} at indices {i} and {j}"
6340 );
6341 }
6342 }
6343 }
6344 for variant in [
6345 RestartStrategy::OneForOne,
6346 RestartStrategy::OneForAll,
6347 RestartStrategy::RestForOne,
6348 RestartStrategy::SimpleOneForOne,
6349 ] {
6350 assert!(
6351 all.contains(&variant),
6352 "RestartStrategy::ALL must contain {variant:?} — a future arm \
6353 addition that grows the enum but forgets to grow the ALL slice \
6354 silently truncates every downstream consumer's accept-set at \
6355 the pre-addition boundary"
6356 );
6357 }
6358 }
6359
6360 #[test]
6361 fn restart_strategy_from_wire_accepts_every_lifted_constant() {
6362 // Fail-before-pass-after pin on the forward accept-set of the
6363 // [`RestartStrategy::from_wire`] reverse projection: every
6364 // canonical [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
6365 // constant the [`RestartStrategy::as_str`] emitter walks parses
6366 // back to its paired variant. Any future arm addition that
6367 // grows the emitter's `as_str` match but forgets to grow the
6368 // parser's `from_wire` match silently splits the two halves of
6369 // the round-trip — the wire byte-string one non-serde consumer
6370 // parses from the one the emitter wrote — with the failure
6371 // surfacing at parse time far from the rebrand commit. Pinning
6372 // the four-arm accept-set here catches the drift at caixa-core
6373 // build time.
6374 //
6375 // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
6376 // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
6377 // accept-set pins on the peer closed-set typed-enum `str → Self`
6378 // axes.
6379 for (wire, expected) in [
6380 (
6381 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
6382 RestartStrategy::OneForOne,
6383 ),
6384 (
6385 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
6386 RestartStrategy::OneForAll,
6387 ),
6388 (
6389 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
6390 RestartStrategy::RestForOne,
6391 ),
6392 (
6393 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
6394 RestartStrategy::SimpleOneForOne,
6395 ),
6396 ] {
6397 let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
6398 panic!(
6399 "RestartStrategy::from_wire({wire:?}) must accept every \
6400 SUPERVISOR_ESTRATEGIA_* constant — got None for the \
6401 lifted canonical byte-string that RestartStrategy::{expected:?} \
6402 serializes as under SUPERVISOR_KEY_ESTRATEGIA"
6403 )
6404 });
6405 assert_eq!(
6406 parsed, expected,
6407 "RestartStrategy::from_wire({wire:?}) must return \
6408 RestartStrategy::{expected:?}; got RestartStrategy::{parsed:?}"
6409 );
6410 }
6411 }
6412
6413 #[test]
6414 fn restart_strategy_from_wire_round_trips_through_as_str() {
6415 // Fail-before-pass-after pin on the closed round-trip between
6416 // the forward [`RestartStrategy::as_str`] emitter and the
6417 // reverse [`RestartStrategy::from_wire`] parser: for every
6418 // variant in [`RestartStrategy::ALL`], parsing the emitter's
6419 // output must return exactly the same variant. Any per-arm
6420 // divergence — a future arm added to `as_str` but not
6421 // `from_wire`, an accidental copy-paste flip in one but not
6422 // the other — silently splits the emit and parse halves and
6423 // the failure surfaces at consumer parse time far from the
6424 // drift site. The `ALL`-iterating shape means a future arm
6425 // addition picks up the coverage by construction.
6426 //
6427 // Peer of the sibling
6428 // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
6429 // (18c7342) round-trip pin on
6430 // [`crate::aplicacao::PlacementStrategy::from_wire`] and
6431 // [`crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`]
6432 // (6b1f4fb) round-trip pin on [`crate::CaixaKind::from_wire`].
6433 for &variant in RestartStrategy::ALL {
6434 let wire = variant.as_str();
6435 let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
6436 panic!(
6437 "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
6438 must be Some({variant:?}) — the two halves of the round-trip \
6439 dispatch on the same lifted SUPERVISOR_ESTRATEGIA_* consts; \
6440 got None on wire byte-string {wire:?}"
6441 )
6442 });
6443 assert_eq!(
6444 parsed, variant,
6445 "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
6446 must round-trip to the same variant; got {parsed:?}"
6447 );
6448 }
6449 }
6450
6451 #[test]
6452 fn restart_strategy_from_wire_rejects_unknown_byte_strings() {
6453 // Fail-before-pass-after pin on the closed-set refusal
6454 // discipline of [`RestartStrategy::from_wire`]: every
6455 // byte-string outside the four-arm accept-set returns `None`
6456 // rather than silently collapsing onto the [`Default`]
6457 // (`OneForOne`) arm or an arbitrary neighbor. The refusal set
6458 // exercised here sweeps the load-bearing drift shapes: the
6459 // empty string (a stripped serde-attribute drift), all-
6460 // whitespace strings (the canonical text-editor accidental
6461 // padding shape), the kebab-case dispatcher-catalog identities
6462 // (`"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
6463 // `"simple-one-for-one"` — the [`gen_platform::FromStrKind`]-
6464 // derived [`std::str::FromStr`] accept-set, which parses the
6465 // *other* axis of this enum's two-axis split and must not leak
6466 // into the `from_wire` PascalCase-wire accept-set), the
6467 // lowercased single-word forms (`"oneforone"`), the padded
6468 // canonical scalar (`" OneForOne "`), the trailing-newline
6469 // shapes (`"OneForOne\n"`), and neighboring-but-unknown arms
6470 // (`"AllForOne"` — the canonical typo direction).
6471 //
6472 // Peer of the sibling
6473 // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
6474 // (2aa6d23) +
6475 // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
6476 // (18c7342) refusal pins on the peer closed-set typed-enum
6477 // axes.
6478 for bad in [
6479 "",
6480 " ",
6481 "\n",
6482 "\t",
6483 "one-for-one",
6484 "one-for-all",
6485 "rest-for-one",
6486 "simple-one-for-one",
6487 "oneforone",
6488 "OneForOnes",
6489 "one_for_one",
6490 "one for one",
6491 "ONEFORONE",
6492 "OneForOne ",
6493 " OneForOne",
6494 " SimpleOneForOne ",
6495 "OneForOne\n",
6496 "restforone",
6497 "REST_FOR_ONE",
6498 "AllForOne",
6499 "Simple",
6500 "?",
6501 ] {
6502 assert!(
6503 RestartStrategy::from_wire(bad).is_none(),
6504 "RestartStrategy::from_wire({bad:?}) must return None — the \
6505 parser's accept-set is exactly the four RestartStrategy::as_str \
6506 outputs (OneForOne, OneForAll, RestForOne, SimpleOneForOne), \
6507 and this byte-string is outside that closed set"
6508 );
6509 }
6510 }
6511
6512 #[test]
6513 fn restart_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
6514 // Fail-before-pass-after pin on the fourth path of the four-path
6515 // convergence: `from_wire` (the reverse projection) inverts the
6516 // `Serialize` derive's wire byte-string on every variant.
6517 // Together with the pre-existing three-path convergence
6518 // (`Display` + `as_str` + `Serialize` all resolve to the same
6519 // lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const,
6520 // pinned by
6521 // [`restart_strategy_display_matches_serialized_wire_byte_string`])
6522 // this closes the round-trip: the wire byte-string the
6523 // `Serialize` derive emits parses back to the same variant
6524 // through `from_wire`, so any future serde-attribute or variant-
6525 // rename drift on the emit half now surfaces as a matched drift
6526 // on the parse half at caixa-core build time — the two halves
6527 // migrate as a unit through the lifted consts on any future
6528 // rename, and the round-trip cannot silently split.
6529 //
6530 // Peer of the sibling
6531 // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
6532 // (18c7342) wire-format pin on
6533 // [`crate::aplicacao::PlacementStrategy::from_wire`].
6534 for &variant in RestartStrategy::ALL {
6535 let wire = serde_json::to_string(&variant).unwrap();
6536 let unquoted = wire
6537 .strip_prefix('"')
6538 .and_then(|s| s.strip_suffix('"'))
6539 .expect("serialized RestartStrategy is a JSON string");
6540 let parsed = RestartStrategy::from_wire(unquoted).unwrap_or_else(|| {
6541 panic!(
6542 "RestartStrategy::from_wire({unquoted:?}) must accept the \
6543 Serialize derive's wire byte-string for \
6544 RestartStrategy::{variant:?} — the four-path convergence \
6545 (Display + as_str + Serialize + from_wire) resolves through \
6546 the same lifted SUPERVISOR_ESTRATEGIA_* const; got None"
6547 )
6548 });
6549 assert_eq!(
6550 parsed, variant,
6551 "RestartStrategy::from_wire of the Serialize derive's wire \
6552 byte-string for RestartStrategy::{variant:?} must round-trip \
6553 to the same variant; got {parsed:?}"
6554 );
6555 }
6556 }
6557
6558 #[test]
6559 fn restart_strategy_try_from_str_routes_through_from_wire_accessor() {
6560 // Fail-before-pass-after byte-parity pin on the newly lifted
6561 // `impl TryFrom<&str> for RestartStrategy` — asserts the standard-
6562 // library trait impl and the substrate-primitive
6563 // [`RestartStrategy::from_wire`] `Option<Self>` accessor resolve to
6564 // the same four-arm accept-set across every arm the exhaustive
6565 // [`RestartStrategy::ALL`] slice enumerates. Any future silent
6566 // detour that routes the trait impl through a divergent projection
6567 // (a per-arm inline `match s { "OneForOne" => Ok(Self::OneForOne),
6568 // … }` re-inlining that opens a compile-time link to the un-
6569 // lifted arm-literal, a hypothetical `#[serde(rename_all = "…")]`
6570 // attribute drift that silently splits the wire byte-string from
6571 // every consumer that reaches for this typed dispatch, an
6572 // accidental swap onto the kebab-case dispatcher-catalog axis the
6573 // pre-existing [`std::str::FromStr`] impl parses through and which
6574 // would collide the two-axis wire/catalog split the sibling
6575 // [`RestartStrategy::from_wire`] doc block makes load-bearing)
6576 // trips at caixa-core test time under `assert_eq!` rather than at
6577 // a downstream `impl TryFrom<&str>`-bound consumer's silent split.
6578 // Sweeps every one of the four arms [`RestartStrategy::ALL`]
6579 // carries so no arm's projection is covered only by the sibling
6580 // method-named `from_wire` path. Peer of the sibling
6581 // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
6582 // (3c83606),
6583 // [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
6584 // (bf33136), and the M3
6585 // [`crate::aplicacao::tests::placement_strategy_try_from_str_routes_through_from_wire_accessor`]
6586 // (6fd00cd) — extends the trait-idiomatic reverse-projection axis
6587 // onto the first M2-OTP-shape closed-set typed enum on the caixa
6588 // surface.
6589 for &variant in RestartStrategy::ALL {
6590 let wire = variant.as_str();
6591 assert_eq!(
6592 <RestartStrategy as TryFrom<&str>>::try_from(wire),
6593 Ok(variant),
6594 "TryFrom<&str> impl on RestartStrategy must round-trip \
6595 RestartStrategy::{variant:?}.as_str() = {wire:?} back to \
6596 Ok(RestartStrategy::{variant:?}) — divergence from \
6597 RestartStrategy::from_wire signals a silent detour off \
6598 the substrate-primitive accessor"
6599 );
6600 assert_eq!(
6601 <RestartStrategy as TryFrom<&str>>::try_from(wire).ok(),
6602 RestartStrategy::from_wire(wire),
6603 "TryFrom<&str> ok()-projection on {wire:?} must byte-equal \
6604 RestartStrategy::from_wire on the same input"
6605 );
6606 }
6607 }
6608
6609 #[test]
6610 fn restart_strategy_try_from_str_rejects_unknown_byte_strings() {
6611 // Rejection witness on the `impl TryFrom<&str> for
6612 // RestartStrategy` — sweeps a candidate set of byte-strings
6613 // outside the four-arm PascalCase wire accept-set the sibling
6614 // [`RestartStrategy::as_str`] emits and asserts every one lands on
6615 // `Err(())`, so a future accidental widening of the trait impl's
6616 // accept-set (a stray additional
6617 // `_ if s.eq_ignore_ascii_case("OneForOne") => Ok(…)` case-fold
6618 // path, a silent inclusion of the kebab-case dispatcher-catalog
6619 // byte-string the pre-existing [`std::str::FromStr`] impl the
6620 // [`gen_platform::FromStrKind`] derive installs parses onto the
6621 // wire axis — which would collide the two-axis
6622 // wire/dispatcher-catalog split the sibling
6623 // [`RestartStrategy::from_wire`] doc block makes load-bearing —
6624 // an English-rebrand or plural-arm silent alias that would
6625 // widen the wire accept-set past the OTP-canonical four) trips at
6626 // caixa-core test time. The candidate set includes the empty
6627 // string, whitespace-only padding, the kebab-case dispatcher-
6628 // catalog byte-strings on the sibling axis (a caller who confuses
6629 // the two axes trips here rather than at a downstream consumer's
6630 // silent reject), a lowercase / uppercase / mixed-case fold of
6631 // each PascalCase arm (a caller who assumes case-fold acceptance
6632 // trips here), leading/trailing whitespace padding, the trailing-
6633 // newline shape, quote-wrapped candidates, and a residual set of
6634 // plausible-but-wrong English rebrand candidates. Peer of the
6635 // sibling
6636 // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
6637 // (3c83606) and
6638 // [`crate::aplicacao::tests::placement_strategy_try_from_str_rejects_unknown_byte_strings`]
6639 // (6fd00cd) rejection witnesses.
6640 let rejected: &[&str] = &[
6641 "",
6642 " ",
6643 "\n",
6644 "\t",
6645 "one-for-one",
6646 "one-for-all",
6647 "rest-for-one",
6648 "simple-one-for-one",
6649 "oneforone",
6650 "one_for_one",
6651 "OneForOnes",
6652 "ONEFORONE",
6653 "oneforall",
6654 "restforone",
6655 "simpleoneforone",
6656 "OneForOne ",
6657 " OneForOne",
6658 " OneForAll ",
6659 "OneForOne\n",
6660 "RestForOne\t",
6661 "OneForEach",
6662 "AllForOne",
6663 "one for one",
6664 "\"OneForOne\"",
6665 "?",
6666 ];
6667 for &input in rejected {
6668 assert_eq!(
6669 <RestartStrategy as TryFrom<&str>>::try_from(input),
6670 Err(()),
6671 "TryFrom<&str> impl on RestartStrategy must reject the \
6672 non-wire byte-string {input:?} — silent acceptance signals \
6673 an accept-set widening off the paired \
6674 RestartStrategy::from_wire resolver"
6675 );
6676 }
6677 }
6678
6679 #[test]
6680 fn restart_strategy_try_from_str_and_from_wire_partition_the_accept_set() {
6681 // Cross-axis partition pin: the paired `TryFrom<&str>` and
6682 // `from_wire` reverse projections must resolve identically on
6683 // *every* input, not just the ones [`RestartStrategy::ALL`]
6684 // enumerates. Sweeps a mixed candidate set spanning accepted
6685 // (four-arm PascalCase wire byte-strings) and rejected (kebab-case
6686 // dispatcher-catalog byte-strings, empty, whitespace-padded,
6687 // quoted, English-rebrand candidates) inputs and asserts the
6688 // trait's `Result::ok()` projection byte-equals the method-named
6689 // resolver's `Option<Self>` return-shape on each, locking the two
6690 // paths together by construction so any future detour (a stray
6691 // `try_from` special-case that widens or narrows the accept-set
6692 // outside the paired `from_wire` resolver, an accidental swap
6693 // onto the kebab-case [`std::str::FromStr`] impl the
6694 // [`gen_platform::FromStrKind`] derive installs on the sibling
6695 // dispatcher-catalog axis) trips at caixa-core test time. Peer of
6696 // the sibling
6697 // [`crate::kind::tests::caixa_kind_try_from_str_and_from_wire_partition_the_accept_set`]
6698 // pin — extends the round-trip discipline onto the M2-OTP-shape
6699 // sibling-restart axis.
6700 let candidates: &[&str] = &[
6701 "OneForOne",
6702 "OneForAll",
6703 "RestForOne",
6704 "SimpleOneForOne",
6705 "",
6706 "one-for-one",
6707 "one-for-all",
6708 "rest-for-one",
6709 "simple-one-for-one",
6710 "oneforone",
6711 "unknown",
6712 "OneForOne ",
6713 " OneForOne",
6714 "\"OneForOne\"",
6715 "OneForEach",
6716 "?",
6717 ];
6718 for &input in candidates {
6719 let via_trait: Option<RestartStrategy> =
6720 <RestartStrategy as TryFrom<&str>>::try_from(input).ok();
6721 let via_method: Option<RestartStrategy> = RestartStrategy::from_wire(input);
6722 assert_eq!(
6723 via_trait, via_method,
6724 "TryFrom<&str> and from_wire must resolve identically on \
6725 input {input:?} — divergence signals the two reverse-\
6726 projection paths have drifted onto different accept-sets"
6727 );
6728 }
6729 }
6730
6731 // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_RESTART_* identity ─
6732
6733 #[test]
6734 fn restart_policy_variants_serialize_to_lifted_scalar_values() {
6735 // The fail-before-pass-after pin: pre-lift there was no
6736 // single-source binding between the [`RestartPolicy`] variant
6737 // name the un-`rename`d `Serialize` derive emits under
6738 // [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
6739 // byte-string every downstream cluster-side dispatcher (the
6740 // future wasm-operator's per-child post-exit restart-decision
6741 // branch, the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
6742 // materializer's admission-time enum-arm bind, the
6743 // `caixa-operator`'s hierarchical reconciliation scheduler's
6744 // per-child-policy fan-out) probes verbatim. A future
6745 // `#[serde(rename_all = "kebab-case")]` attribute on the enum —
6746 // or a per-variant `#[serde(rename = "…")]` override, or a
6747 // variant rename in the source — would silently rebrand the
6748 // emitted scalar under one spelling while every downstream
6749 // dispatcher still probed the other, with the failure surfacing
6750 // at the operator's reconcile posture (children coming up under
6751 // the `default()` `Permanent` arm rather than the typed slot's
6752 // declared policy — a `:temporary` `oneShot` child would be
6753 // restarted on clean exit, treating the successful-completion
6754 // signal as failure and re-running the completion-terminal
6755 // one-shot indefinitely; a `:transient` child that clean-exited
6756 // would be restarted, masking the clean-completion contract)
6757 // far from the source rebrand commit and with no field naming
6758 // the drift. Pinning the two paths (the `Serialize` derive's
6759 // serialized string AND the [`RestartPolicy::as_str`] helper)
6760 // to the same three lifted
6761 // [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
6762 // [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
6763 // [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
6764 // byte-strings makes any future drift on either endpoint fail
6765 // here at caixa-core build time. Peer of the sibling
6766 // [`restart_strategy_variants_serialize_to_lifted_scalar_values`]
6767 // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
6768 // and the M3
6769 // `placement_strategy_variants_serialize_to_lifted_scalar_values`
6770 // (3f0e21c) on the per-Aplicacao distribution-strategy axis —
6771 // same three-path-convergence discipline, extended to close the
6772 // third OTP-shaped closed-enum discriminator axis on the caixa
6773 // typed surface (per-child restart-decision policy).
6774 for (variant, expected) in [
6775 (
6776 RestartPolicy::Permanent,
6777 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
6778 ),
6779 (
6780 RestartPolicy::Temporary,
6781 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
6782 ),
6783 (
6784 RestartPolicy::Transient,
6785 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
6786 ),
6787 ] {
6788 let json = serde_json::to_string(&variant).unwrap();
6789 assert_eq!(
6790 json,
6791 format!("\"{expected}\""),
6792 "RestartPolicy::{variant:?} must serialize to {expected:?}"
6793 );
6794 assert_eq!(
6795 variant.as_str(),
6796 expected,
6797 "RestartPolicy::{variant:?}.as_str() must return the lifted \
6798 SUPERVISOR_CHILD_RESTART_* constant"
6799 );
6800 }
6801 }
6802
6803 #[test]
6804 fn supervisor_child_restart_consts_are_pairwise_distinct() {
6805 // Cross-arm drift-detection pin: a future collapse of two
6806 // canonical variant byte-strings onto the same value (e.g. an
6807 // accidental copy-paste flip of `SUPERVISOR_CHILD_RESTART_TRANSIENT`
6808 // to also read `"Permanent"`) would silently reroute every
6809 // downstream operator's per-child-policy dispatch onto the
6810 // sibling arm's reconcile branch and pass every propagation-probe
6811 // test that expected only the stale arm's value — a `:transient`
6812 // child would come up under the `:permanent` restart-decision
6813 // posture on every subsequent clean exit, so a completion-terminal
6814 // child would be restarted indefinitely against its declared
6815 // policy. Peer of the sibling
6816 // [`supervisor_estrategia_consts_are_pairwise_distinct`]
6817 // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
6818 // and the four-way distinct pin
6819 // `supervisor_key_consts_are_pairwise_distinct` (40cc4e5) on the
6820 // top-level `SUPERVISOR_KEY_*` axis.
6821 let all = [
6822 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
6823 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
6824 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
6825 ];
6826 for (i, a) in all.iter().enumerate() {
6827 for (j, b) in all.iter().enumerate() {
6828 if i != j {
6829 assert_ne!(
6830 a, b,
6831 "SUPERVISOR_CHILD_RESTART_* consts must be pairwise distinct \
6832 — got duplicate {a:?} at indices {i} and {j}",
6833 );
6834 }
6835 }
6836 }
6837 }
6838
6839 #[test]
6840 fn restart_policy_display_routes_through_as_str_helper() {
6841 // The fail-before-pass-after pin on the first half of the
6842 // three-path convergence: pre-convergence [`RestartPolicy`]
6843 // carried a [`std::fmt::Display`] surface via its
6844 // `#[discriminant(also_display)]` gen-platform derive route,
6845 // which arrived kebab-case as `"permanent"` / `"temporary"`
6846 // / `"transient"` on this three-arm enum (whose variant
6847 // names each collapse to their own lowercase form under the
6848 // kebab-case transform) while the wire format ran as
6849 // PascalCase `"Permanent"` / `"Temporary"` / `"Transient"`
6850 // through the un-`rename`d serde derive. Every consumer
6851 // reaching for a policy byte-string past the wire format had
6852 // to pick between three paths ([`RestartPolicy::as_str`],
6853 // the `Serialize` derive's serialized string, or
6854 // `format!("{v}")` on the discriminant-Display route), any
6855 // two of which a future variant rename or
6856 // `#[serde(rename_all = "kebab-case")]` attribute would
6857 // silently desynchronize. Wiring [`std::fmt::Display`]
6858 // through [`RestartPolicy::as_str`] closes the third path:
6859 // every `format!("{v}")` call reaches the same lifted
6860 // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the
6861 // wire format and the [`RestartPolicy::as_str`] helper
6862 // already route through, so a future variant rename lands at
6863 // exactly one place. Pin the routing here so a future
6864 // `impl std::fmt::Display for RestartPolicy`
6865 // reimplementation that hand-rolls the arms instead of
6866 // delegating to [`RestartPolicy::as_str`] fails at
6867 // caixa-core build time. Peer of the sibling
6868 // [`restart_strategy_display_routes_through_as_str_helper`]
6869 // on the per-supervisor sibling-restart-strategy axis and
6870 // the M3
6871 // `placement_strategy_display_routes_through_as_str_helper`
6872 // (cc8f749) — the third of three OTP-shape closed-enum
6873 // discriminator axes on the caixa typed surface now
6874 // converged onto the same three-path
6875 // (Display → as_str → lifted const) discipline.
6876 for variant in [
6877 RestartPolicy::Permanent,
6878 RestartPolicy::Temporary,
6879 RestartPolicy::Transient,
6880 ] {
6881 assert_eq!(
6882 variant.to_string(),
6883 variant.as_str(),
6884 "RestartPolicy::{variant:?} Display must route through \
6885 RestartPolicy::as_str (single source of truth: the lifted \
6886 SUPERVISOR_CHILD_RESTART_* const the wire format also emits)"
6887 );
6888 }
6889 }
6890
6891 #[test]
6892 fn restart_policy_display_matches_serialized_wire_byte_string() {
6893 // The fail-before-pass-after pin on the second half of the
6894 // three-path convergence: `Display` (user-facing text) agrees
6895 // byte-for-byte with the `Serialize` derive's wire format
6896 // (canonical camelCase-schema `SUPERVISOR_CHILD_KEY_RESTART`
6897 // scalar) on every variant. Pre-convergence the two paths
6898 // were structurally independent — a future
6899 // `#[serde(rename_all = "kebab-case")]` attribute on the
6900 // enum would silently rebrand the emitted wire scalar
6901 // (`permanent`, `temporary`, `transient`) while every
6902 // consumer that pretty-prints the policy (the future
6903 // wasm-operator's per-child post-exit restart-decision
6904 // diagnostic line, the future `feira app graph` per-child
6905 // restart column, the future M4
6906 // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
6907 // per-child admission-webhook rejection body) would still
6908 // emit the PascalCase form the `as_str` / `Display` route
6909 // returns, with the mismatch surfacing at consumer parse
6910 // time / operator dispatch time far from the source rebrand
6911 // commit. Pin the two paths byte-for-byte here so any future
6912 // serde-attribute or variant-rename drift is a
6913 // caixa-core-build-time test failure at this call, not a
6914 // silent per-consumer dispatch miss. Peer of the sibling
6915 // [`restart_strategy_display_matches_serialized_wire_byte_string`]
6916 // on the per-supervisor sibling-restart-strategy axis and
6917 // the M3
6918 // `placement_strategy_display_matches_serialized_wire_byte_string`
6919 // (cc8f749).
6920 for variant in [
6921 RestartPolicy::Permanent,
6922 RestartPolicy::Temporary,
6923 RestartPolicy::Transient,
6924 ] {
6925 let wire = serde_json::to_string(&variant).unwrap();
6926 let unquoted = wire
6927 .strip_prefix('"')
6928 .and_then(|s| s.strip_suffix('"'))
6929 .expect("serialized RestartPolicy is a JSON string");
6930 assert_eq!(
6931 variant.to_string(),
6932 unquoted,
6933 "RestartPolicy::{variant:?} Display byte-string must match the \
6934 Serialize derive's wire byte-string (three-path convergence: \
6935 Display + as_str + Serialize all resolve to the same \
6936 SUPERVISOR_CHILD_RESTART_* const)"
6937 );
6938 }
6939 }
6940
6941 #[test]
6942 fn restart_policy_as_ref_str_routes_through_as_str_accessor() {
6943 // Fail-before-pass-after byte-parity pin on the lifted
6944 // `impl AsRef<str> for RestartPolicy` — asserts the
6945 // standard-library trait impl and the substrate-primitive
6946 // [`RestartPolicy::as_str`] `pub const fn` accessor resolve
6947 // to the same `&str` per instance across the three-arm
6948 // closed set, so any future silent detour that routes the
6949 // impl through a divergent projection (a per-arm inline
6950 // `match self { RestartPolicy::Permanent => "Permanent", … }`
6951 // re-inlining that opens a compile-time link to the un-lifted
6952 // arm-literal, a swap onto the kebab-case
6953 // [`gen_platform::Discriminant`] catalog identity that would
6954 // collide the wire axis with the dispatcher-catalog axis) trips
6955 // at caixa-core test time under `PartialEq` rather than at a
6956 // downstream `impl AsRef<str>`-bound consumer's silent split.
6957 // Sweeps every one of the three arms
6958 // [`RestartPolicy::ALL`] carries so no arm's projection is
6959 // covered only by the sibling wire-format `Serialize` derive
6960 // path. Peer of the sibling
6961 // [`restart_strategy_as_ref_str_routes_through_as_str_accessor`]
6962 // (63eb1a4) on the paired per-supervisor sibling-restart-
6963 // strategy axis and the [`crate::CaixaVersion`]
6964 // `AsRef<str>`-byte-parity pin (16d5c7e) on the paired
6965 // top-level `:versao` typed newtype — the three pins together
6966 // cover the substrate primitive's `AsRef<str>` projection axis
6967 // on the paired newtype + M2 closed-set-typed-enum surface.
6968 for &variant in RestartPolicy::ALL {
6969 assert_eq!(
6970 <RestartPolicy as AsRef<str>>::as_ref(&variant),
6971 variant.as_str(),
6972 "AsRef<str> impl on RestartPolicy::{variant:?} must \
6973 byte-equal RestartPolicy::as_str on the same instance \
6974 — divergence signals a silent detour off the substrate-\
6975 primitive accessor"
6976 );
6977 }
6978 }
6979
6980 #[test]
6981 fn restart_policy_as_ref_str_routes_through_display_via_shared_accessor() {
6982 // Fail-before-pass-after byte-parity pin on the three-path
6983 // convergence discipline the M2 per-child-restart-policy
6984 // primitive now carries on the `&str`-projection axis:
6985 // `<RestartPolicy as AsRef<str>>::as_ref(&v)` (the newly
6986 // lifted impl), `format!("{v}")` (the pre-existing
6987 // [`fmt::Display`] impl), and `v.as_str()` (the substrate-
6988 // primitive `pub const fn` accessor both trait impls delegate
6989 // through) must resolve to the same byte-string on every
6990 // instance across the three-arm closed set. Refuses any future
6991 // divergence between the two trait impls (a stray
6992 // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
6993 // rather than delegating through the shared accessor; a
6994 // hypothetical `AsRef<str>` rewrite that inlines a per-arm
6995 // literal cascade) that would silently split the two
6996 // projection paths of the same closed-set typed enum. Mirrors
6997 // the sibling three-path-convergence discipline the peer
6998 // [`RestartStrategy`] typed enum carries on its
6999 // `AsRef<str>` / `Display` / `as_str` triple
7000 // (supervisor.rs pin
7001 // `restart_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
7002 // 63eb1a4) and the [`crate::CaixaVersion`] typed newtype
7003 // carries on the same triple (version.rs pin
7004 // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
7005 // 16d5c7e).
7006 for &variant in RestartPolicy::ALL {
7007 let via_as_ref: &str = <RestartPolicy as AsRef<str>>::as_ref(&variant);
7008 let via_display: String = format!("{variant}");
7009 let via_accessor: &str = variant.as_str();
7010 assert_eq!(via_as_ref, via_accessor);
7011 assert_eq!(via_display, via_accessor);
7012 assert_eq!(via_as_ref, via_display.as_str());
7013 }
7014 }
7015
7016 #[test]
7017 fn restart_policy_all_enumerates_every_variant_exactly_once() {
7018 // Fail-before-pass-after pin on the [`RestartPolicy::ALL`]
7019 // exhaustive-iteration surface: every variant appears exactly
7020 // once, and the slice length matches the arm count of the
7021 // closed set. Every consumer that walks the accepted-policy
7022 // set (a future `feira supervisor --restart …` CLI-side
7023 // arg-parse's "did you mean" hint, a future M4 admission-
7024 // webhook's per-child rejection body naming the accepted-
7025 // `:restart` list, the [`RestartPolicy::from_wire`] reverse-
7026 // projection consumers that iterate the accept-set for
7027 // diagnostic rendering) reads through this slice, so a future
7028 // arm addition that grows the enum but forgets to grow
7029 // [`Self::ALL`] silently truncates every downstream consumer's
7030 // accept-set at the same pre-addition boundary — this pin
7031 // fails at caixa-core build time on the pairwise-distinct +
7032 // arm-count invariants.
7033 //
7034 // Peer of the sibling [`RestartStrategy::ALL`] (4eec29c) /
7035 // [`crate::CaixaKind::ALL`] (6b1f4fb) /
7036 // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
7037 // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
7038 // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
7039 // pins on the peer closed-set typed-enum axes.
7040 let all: &[RestartPolicy] = RestartPolicy::ALL;
7041 assert_eq!(
7042 all.len(),
7043 3,
7044 "RestartPolicy::ALL must enumerate every variant of the \
7045 three-arm closed set (Permanent, Temporary, Transient); \
7046 got {all:?}"
7047 );
7048 for (i, a) in all.iter().enumerate() {
7049 for (j, b) in all.iter().enumerate() {
7050 if i != j {
7051 assert_ne!(
7052 a, b,
7053 "RestartPolicy::ALL must carry every variant exactly \
7054 once — got duplicate {a:?} at indices {i} and {j}"
7055 );
7056 }
7057 }
7058 }
7059 for variant in [
7060 RestartPolicy::Permanent,
7061 RestartPolicy::Temporary,
7062 RestartPolicy::Transient,
7063 ] {
7064 assert!(
7065 all.contains(&variant),
7066 "RestartPolicy::ALL must contain {variant:?} — a future arm \
7067 addition that grows the enum but forgets to grow the ALL slice \
7068 silently truncates every downstream consumer's accept-set at \
7069 the pre-addition boundary"
7070 );
7071 }
7072 }
7073
7074 #[test]
7075 fn restart_policy_from_wire_accepts_every_lifted_constant() {
7076 // Fail-before-pass-after pin on the forward accept-set of the
7077 // [`RestartPolicy::from_wire`] reverse projection: every
7078 // canonical [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
7079 // constant the [`RestartPolicy::as_str`] emitter walks parses
7080 // back to its paired variant. Any future arm addition that
7081 // grows the emitter's `as_str` match but forgets to grow the
7082 // parser's `from_wire` match silently splits the two halves of
7083 // the round-trip — the wire byte-string one non-serde consumer
7084 // parses from the one the emitter wrote — with the failure
7085 // surfacing at the operator's reconcile posture (a `:temporary`
7086 // `oneShot` child restarted on clean exit, a `:transient` child
7087 // restarted after clean completion) far from the rebrand
7088 // commit. Pinning the three-arm accept-set here catches the
7089 // drift at caixa-core build time.
7090 //
7091 // Peer of the sibling [`RestartStrategy::from_wire`] (4eec29c)
7092 // + [`crate::CaixaKind::from_wire`] (2aa6d23)
7093 // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
7094 // accept-set pins on the peer closed-set typed-enum `str → Self`
7095 // axes.
7096 for (wire, expected) in [
7097 (
7098 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
7099 RestartPolicy::Permanent,
7100 ),
7101 (
7102 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
7103 RestartPolicy::Temporary,
7104 ),
7105 (
7106 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
7107 RestartPolicy::Transient,
7108 ),
7109 ] {
7110 let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
7111 panic!(
7112 "RestartPolicy::from_wire({wire:?}) must accept every \
7113 SUPERVISOR_CHILD_RESTART_* constant — got None for the \
7114 lifted canonical byte-string that RestartPolicy::{expected:?} \
7115 serializes as under SUPERVISOR_CHILD_KEY_RESTART"
7116 )
7117 });
7118 assert_eq!(
7119 parsed, expected,
7120 "RestartPolicy::from_wire({wire:?}) must return \
7121 RestartPolicy::{expected:?}; got RestartPolicy::{parsed:?}"
7122 );
7123 }
7124 }
7125
7126 #[test]
7127 fn restart_policy_from_wire_round_trips_through_as_str() {
7128 // Fail-before-pass-after pin on the closed round-trip between
7129 // the forward [`RestartPolicy::as_str`] emitter and the
7130 // reverse [`RestartPolicy::from_wire`] parser: for every
7131 // variant in [`RestartPolicy::ALL`], parsing the emitter's
7132 // output must return exactly the same variant. Any per-arm
7133 // divergence — a future arm added to `as_str` but not
7134 // `from_wire`, an accidental copy-paste flip in one but not
7135 // the other — silently splits the emit and parse halves and
7136 // the failure surfaces at consumer parse time far from the
7137 // drift site. The `ALL`-iterating shape means a future arm
7138 // addition picks up the coverage by construction.
7139 //
7140 // Peer of the sibling
7141 // [`restart_strategy_from_wire_round_trips_through_as_str`]
7142 // (4eec29c) round-trip pin on
7143 // [`RestartStrategy::from_wire`] and the M3
7144 // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
7145 // (18c7342) round-trip pin on
7146 // [`crate::aplicacao::PlacementStrategy::from_wire`].
7147 for &variant in RestartPolicy::ALL {
7148 let wire = variant.as_str();
7149 let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
7150 panic!(
7151 "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
7152 must be Some({variant:?}) — the two halves of the round-trip \
7153 dispatch on the same lifted SUPERVISOR_CHILD_RESTART_* consts; \
7154 got None on wire byte-string {wire:?}"
7155 )
7156 });
7157 assert_eq!(
7158 parsed, variant,
7159 "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
7160 must round-trip to the same variant; got {parsed:?}"
7161 );
7162 }
7163 }
7164
7165 #[test]
7166 fn restart_policy_from_wire_rejects_unknown_byte_strings() {
7167 // Fail-before-pass-after pin on the closed-set refusal
7168 // discipline of [`RestartPolicy::from_wire`]: every
7169 // byte-string outside the three-arm accept-set returns `None`
7170 // rather than silently collapsing onto the [`Default`]
7171 // (`Permanent`) arm or an arbitrary neighbor. The refusal set
7172 // exercised here sweeps the load-bearing drift shapes: the
7173 // empty string (a stripped serde-attribute drift), all-
7174 // whitespace strings (the canonical text-editor accidental
7175 // padding shape), the kebab-case dispatcher-catalog identities
7176 // (`"permanent"` / `"temporary"` / `"transient"` — the
7177 // [`gen_platform::FromStrKind`]-derived [`std::str::FromStr`]
7178 // accept-set, which parses the *other* axis of this enum's
7179 // two-axis split and must not leak into the `from_wire`
7180 // PascalCase-wire accept-set — a lowercase leak here would
7181 // silently accept the operator's kebab-case
7182 // dispatcher-catalog probe under the wire-axis parser and mis-
7183 // route a `:permanent` intent), the padded canonical scalar
7184 // (`" Permanent "`), the trailing-newline shapes
7185 // (`"Permanent\n"`), the uppercase-single-word forms
7186 // (`"PERMANENT"`), and neighboring-but-unknown arms
7187 // (`"Restart"` — the canonical typo direction toward the
7188 // sibling [`RestartStrategy`] enum's own wire-arm namespace).
7189 //
7190 // Peer of the sibling
7191 // [`restart_strategy_from_wire_rejects_unknown_byte_strings`]
7192 // (4eec29c) +
7193 // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
7194 // (2aa6d23) +
7195 // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
7196 // (18c7342) refusal pins on the peer closed-set typed-enum
7197 // axes.
7198 for bad in [
7199 "",
7200 " ",
7201 "\n",
7202 "\t",
7203 "permanent",
7204 "temporary",
7205 "transient",
7206 "PERMANENT",
7207 "TEMPORARY",
7208 "TRANSIENT",
7209 "Permanents",
7210 "Permanent ",
7211 " Permanent",
7212 " Transient ",
7213 "Permanent\n",
7214 "perma",
7215 "Trans",
7216 "OneForOne",
7217 "Restart",
7218 "?",
7219 ] {
7220 assert!(
7221 RestartPolicy::from_wire(bad).is_none(),
7222 "RestartPolicy::from_wire({bad:?}) must return None — the \
7223 parser's accept-set is exactly the three RestartPolicy::as_str \
7224 outputs (Permanent, Temporary, Transient), and this \
7225 byte-string is outside that closed set"
7226 );
7227 }
7228 }
7229
7230 #[test]
7231 fn restart_policy_from_wire_matches_serialize_derive_wire_byte_string() {
7232 // Fail-before-pass-after pin on the fourth path of the four-path
7233 // convergence: `from_wire` (the reverse projection) inverts the
7234 // `Serialize` derive's wire byte-string on every variant.
7235 // Together with the pre-existing three-path convergence
7236 // (`Display` + `as_str` + `Serialize` all resolve to the same
7237 // lifted [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const,
7238 // pinned by
7239 // [`restart_policy_display_matches_serialized_wire_byte_string`])
7240 // this closes the round-trip: the wire byte-string the
7241 // `Serialize` derive emits parses back to the same variant
7242 // through `from_wire`, so any future serde-attribute or variant-
7243 // rename drift on the emit half now surfaces as a matched drift
7244 // on the parse half at caixa-core build time — the two halves
7245 // migrate as a unit through the lifted consts on any future
7246 // rename, and the round-trip cannot silently split.
7247 //
7248 // Peer of the sibling
7249 // [`restart_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
7250 // (4eec29c) wire-format pin on
7251 // [`RestartStrategy::from_wire`] and the M3
7252 // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
7253 // (18c7342) wire-format pin on
7254 // [`crate::aplicacao::PlacementStrategy::from_wire`].
7255 for &variant in RestartPolicy::ALL {
7256 let wire = serde_json::to_string(&variant).unwrap();
7257 let unquoted = wire
7258 .strip_prefix('"')
7259 .and_then(|s| s.strip_suffix('"'))
7260 .expect("serialized RestartPolicy is a JSON string");
7261 let parsed = RestartPolicy::from_wire(unquoted).unwrap_or_else(|| {
7262 panic!(
7263 "RestartPolicy::from_wire({unquoted:?}) must accept the \
7264 Serialize derive's wire byte-string for \
7265 RestartPolicy::{variant:?} — the four-path convergence \
7266 (Display + as_str + Serialize + from_wire) resolves through \
7267 the same lifted SUPERVISOR_CHILD_RESTART_* const; got None"
7268 )
7269 });
7270 assert_eq!(
7271 parsed, variant,
7272 "RestartPolicy::from_wire of the Serialize derive's wire \
7273 byte-string for RestartPolicy::{variant:?} must round-trip \
7274 to the same variant; got {parsed:?}"
7275 );
7276 }
7277 }
7278
7279 // ── drift-detection: ChildSpec::nome accessor pins ────────────────────
7280 //
7281 // The M2 supervisor-tree sibling of the M3 `Membro::nome` (4a32abf) pin
7282 // pair (`membro_nome_returns_caixa_byte_equal_across_permutations` +
7283 // `membro_nome_borrows_from_caixa_storage`) — extended here to the M2
7284 // per-`:children` child-caixa `:nome` axis, sibling to the first M2
7285 // slot scalar accessor `UpgradeFromEntry::prior_versao` (75d27a8) on
7286 // the peer per-`:upgrade-from :from` axis. The three pins jointly
7287 // brace the accessor against every future silent detour that would
7288 // desynchronize it from the raw `.caixa` field access every consumer
7289 // previously open-coded.
7290
7291 #[test]
7292 fn child_spec_nome_returns_caixa_byte_equal_across_permutations() {
7293 // The canonical per-`:children` child-caixa `:nome`-scalar pin:
7294 // [`ChildSpec::nome`] must return the `:children :caixa` field
7295 // byte-for-byte across every DNS-1123-label value the upstream
7296 // [`crate::render::require_valid_dns_1123_label`] gate at
7297 // `SupervisorSpec::validate` admits. Peer of the sibling
7298 // `membro_nome_returns_caixa_byte_equal_across_permutations`
7299 // (4a32abf) pin on the M3 per-`:membros` axis — same "the
7300 // substrate-primitive accessor must byte-equal the raw field
7301 // access verbatim across every author-declared value" discipline
7302 // extended to the M2 supervisor-tree per-`:children` arm. Pins
7303 // against a future silent detour that re-normalized the child
7304 // identity (an accidental `.to_lowercase()` — every `:children
7305 // :caixa` is validated as a DNS-1123 label upstream, so any
7306 // re-normalization is redundant + a drift surface between the
7307 // validator and the accessor), a namespace-prefix rewrite (an
7308 // accidental `format!("{namespace}/{caixa}")` per-CR
7309 // fully-qualified rewrite that didn't land on the peer axes), or
7310 // a per-cluster alias stamp the future wasm-operator's
7311 // hierarchical reconciliation scheduler authors on one consumer
7312 // without the others. Five values sweep the accept-set the
7313 // DNS-1123 gate upstream admits (short single-word / dashed /
7314 // v-suffixed / mixed-digit child names).
7315 for name in [
7316 "worker",
7317 "cache-server",
7318 "scratch-job",
7319 "orders-v2",
7320 "session-8080",
7321 ] {
7322 let c = ChildSpec {
7323 caixa: name.into(),
7324 versao: "^0.1".into(),
7325 restart: RestartPolicy::Permanent,
7326 };
7327 assert_eq!(
7328 c.nome(),
7329 name,
7330 "ChildSpec::nome must return :children :caixa verbatim \
7331 (got {:?}, expected {name:?})",
7332 c.nome(),
7333 );
7334 assert_eq!(
7335 c.nome(),
7336 c.caixa.as_str(),
7337 "ChildSpec::nome must byte-equal the .caixa field access",
7338 );
7339 }
7340 }
7341
7342 #[test]
7343 fn child_spec_nome_borrows_from_caixa_storage() {
7344 // The borrow-not-copy pin: [`ChildSpec::nome`] must return a
7345 // `&str` slice that borrows from the typed slot's own [`String`]
7346 // storage — same-address invariant with `c.caixa.as_str()`. Pins
7347 // against a future silent detour that allocated a fresh `String`
7348 // (`self.caixa.clone()` in the body would type-check but silently
7349 // drop the borrow, and every downstream consumer that assumed
7350 // the returned slice outlives `&self` would break on a stale-
7351 // reference use-after-free — the [`crate::render::insert_first_seen`]
7352 // dedup key at [`SupervisorSpec::validate`], the
7353 // [`validate_no_self_supervision`] equality check against the
7354 // parent's `:nome` string slice, the DNS-1123 gate's `&str`
7355 // borrow — each would silently misbehave if this accessor
7356 // produced a detached copy). Peer of the sibling
7357 // `membro_nome_borrows_from_caixa_storage` (4a32abf) pin on the
7358 // M3 per-`:membros` axis and the
7359 // `prior_versao_borrows_from_from_storage` (75d27a8) pin on the
7360 // first M2 slot scalar accessor.
7361 let c = ChildSpec {
7362 caixa: "worker".into(),
7363 versao: "^0.1".into(),
7364 restart: RestartPolicy::Permanent,
7365 };
7366 let name = c.nome();
7367 let caixa_slice = c.caixa.as_str();
7368 assert_eq!(
7369 name.as_ptr(),
7370 caixa_slice.as_ptr(),
7371 "ChildSpec::nome must borrow from the .caixa String's backing \
7372 storage — a fresh allocation here means the accessor no \
7373 longer names the substrate-primitive typed dispatch and \
7374 every downstream consumer would silently carry a detached \
7375 copy",
7376 );
7377 assert_eq!(
7378 name.len(),
7379 caixa_slice.len(),
7380 "ChildSpec::nome and .caixa.as_str() must byte-equal in length \
7381 as well as in address",
7382 );
7383 }
7384
7385 #[test]
7386 fn validate_gates_child_nome_through_lifted_accessor() {
7387 // Bilateral coherence pin: every `:children :caixa` that
7388 // [`SupervisorSpec::validate`] accepts is one
7389 // [`crate::render::require_valid_dns_1123_label`] accepts on the
7390 // accessor-projected value, and vice versa on the reject side.
7391 // This closes the "the validator reads through the accessor"
7392 // contract structurally — a future silent detour that made the
7393 // accessor return a different byte-string than the validator
7394 // gates against would surface here as a coverage mismatch, not
7395 // as an apply-time DNS-1123 rejection at
7396 // `metadata.name: Invalid value` far from the caixa.lisp source.
7397 // Peer of the M2 sibling
7398 // `validate_parses_prior_versao_through_lifted_accessor`
7399 // (75d27a8) on the per-`:upgrade-from :from` axis and the M3
7400 // `validate_membros` peer discipline.
7401 //
7402 // Accept-set sweep: five DNS-1123-label values the upstream gate
7403 // admits.
7404 for ok_name in ["a", "worker", "cache-server", "orders-v2", "svc-8080"] {
7405 let s = SupervisorSpec {
7406 children: vec![ChildSpec {
7407 caixa: ok_name.into(),
7408 versao: "^0.1".into(),
7409 restart: RestartPolicy::Permanent,
7410 }],
7411 ..SupervisorSpec::default()
7412 };
7413 s.validate().unwrap_or_else(|e| {
7414 panic!(
7415 "SupervisorSpec::validate must accept :children :caixa {ok_name:?} \
7416 (upstream DNS-1123 gate accepts it): got {e:?}",
7417 );
7418 });
7419 let c = ChildSpec {
7420 caixa: ok_name.into(),
7421 versao: "^0.1".into(),
7422 restart: RestartPolicy::Permanent,
7423 };
7424 crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| ())
7425 .unwrap_or_else(|()| {
7426 panic!(
7427 "require_valid_dns_1123_label must accept the accessor-projected \
7428 :children :caixa {ok_name:?}",
7429 );
7430 });
7431 }
7432 // Reject-set sweep: five DNS-1123-label-violating shapes the
7433 // upstream gate refuses (empty / uppercase / underscore / dot /
7434 // leading-hyphen). Every rejection at the validator must
7435 // correspond to a rejection when the accessor's projected value
7436 // is fed back through the shared gate.
7437 for bad_name in ["", "Worker", "my_worker", "team.worker", "-worker"] {
7438 let s = SupervisorSpec {
7439 children: vec![ChildSpec {
7440 caixa: bad_name.into(),
7441 versao: "^0.1".into(),
7442 restart: RestartPolicy::Permanent,
7443 }],
7444 ..SupervisorSpec::default()
7445 };
7446 let err = s.validate().unwrap_err();
7447 assert!(
7448 matches!(
7449 err,
7450 SupervisorError::EmptyChildName | SupervisorError::ChildCaixaInvalid { .. }
7451 ),
7452 "SupervisorSpec::validate must reject :children :caixa {bad_name:?} \
7453 via the DNS-1123 gate: got {err:?}",
7454 );
7455 let c = ChildSpec {
7456 caixa: bad_name.into(),
7457 versao: "^0.1".into(),
7458 restart: RestartPolicy::Permanent,
7459 };
7460 assert!(
7461 crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| (),)
7462 .is_err(),
7463 "require_valid_dns_1123_label must reject the accessor-projected \
7464 :children :caixa {bad_name:?}",
7465 );
7466 }
7467 }
7468
7469 // ── drift-detection: ChildSpec::versao_requirement accessor pins ──────
7470 //
7471 // Sibling of the peer per-`:membros` `membro_versao_requirement_*`
7472 // (a40b0e3) pin pair on the M3 mesh-slot surface — extended here to the
7473 // M2 supervisor-tree per-`:children` child-`:versao` axis, sibling to
7474 // the just-landed [`ChildSpec::nome`] (57c61d0) child-`:nome` pin
7475 // trio on the peer per-`:children` `String`-carry axis. The three pins
7476 // jointly brace the accessor against every future silent detour that
7477 // would desynchronize it from the raw `.versao` field access the
7478 // requirement gate + error carrier previously open-coded.
7479 //
7480 // Closes the last unlifted per-`:children` `String`-carry axis: the
7481 // pair (`nome`, `versao_requirement`) now jointly projects the
7482 // (`.caixa`, `.versao`) field pair every OTP-shape supervisor-tree
7483 // consumer that fans on per-child identity + version pin reads,
7484 // matching the peer M3 (`Membro::nome`, `Membro::versao_requirement`)
7485 // pair discipline verbatim.
7486 #[test]
7487 fn child_spec_versao_requirement_returns_versao_byte_equal_across_permutations() {
7488 // The canonical per-`:children` child-`:versao`-scalar pin:
7489 // [`ChildSpec::versao_requirement`] must return the `:children
7490 // :versao` field byte-for-byte across every Cargo-shaped semver
7491 // requirement value the upstream
7492 // [`crate::render::require_valid_versao_requirement`] gate admits.
7493 // Peer of the sibling
7494 // `membro_versao_requirement_returns_versao_byte_equal_across_permutations`
7495 // (a40b0e3) pin on the M3 per-`:membros` axis — same "the
7496 // substrate-primitive accessor must byte-equal the raw field
7497 // access verbatim across every author-declared value" discipline
7498 // extended to the M2 supervisor-tree per-`:children` arm. Pins
7499 // against a future silent detour that re-canonicalized the
7500 // requirement (an accidental `.to_string()` via
7501 // [`crate::version::parse_requirement`] → [`std::fmt::Display`]
7502 // round-trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and
7503 // silently drifted the error carrier's quoted requirement away
7504 // from the source `caixa.lisp`, an accidental whitespace trim on
7505 // `"^ 0.1"` that no consumer ever produced from the field-access
7506 // side, an accidental per-cluster lacre-projected concrete-version
7507 // rewrite that didn't land on the peer requirement-gate call).
7508 // Five values sweep the accept-set the shared
7509 // [`crate::render::require_valid_versao_requirement`] gate admits
7510 // (caret / tilde / exact / wildcard / bare-major).
7511 for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
7512 let c = ChildSpec {
7513 caixa: "worker".into(),
7514 versao: req.into(),
7515 restart: RestartPolicy::Permanent,
7516 };
7517 assert_eq!(
7518 c.versao_requirement(),
7519 req,
7520 "ChildSpec::versao_requirement must return :children :versao \
7521 verbatim (got {:?}, expected {req:?})",
7522 c.versao_requirement(),
7523 );
7524 assert_eq!(
7525 c.versao_requirement(),
7526 c.versao.as_str(),
7527 "ChildSpec::versao_requirement must byte-equal the .versao \
7528 field access",
7529 );
7530 }
7531 }
7532
7533 #[test]
7534 fn child_spec_versao_requirement_borrows_from_versao_storage() {
7535 // The borrow-not-copy pin: [`ChildSpec::versao_requirement`] must
7536 // return a `&str` slice that borrows from the typed slot's own
7537 // [`String`] storage — same-address invariant with
7538 // `c.versao.as_str()`. Pins against a future silent detour that
7539 // allocated a fresh `String` (`self.versao.clone()` in the body
7540 // would type-check but silently drop the borrow, and every
7541 // downstream consumer that assumed the returned slice outlives
7542 // `&self` — the [`crate::render::require_valid_versao_requirement`]
7543 // gate's `&str` borrow, the [`SupervisorError::ChildVersaoInvalid`]
7544 // `.to_string()` carrier's byte-length assumption — would silently
7545 // misbehave if this accessor produced a detached copy). Peer of
7546 // the sibling `child_spec_nome_borrows_from_caixa_storage`
7547 // (57c61d0) pin on the per-`:children` `:nome` axis and the M3
7548 // `membro_versao_requirement_borrows_from_versao_storage` (a40b0e3)
7549 // pin on the peer per-`:membros` `:versao` axis.
7550 let c = ChildSpec {
7551 caixa: "worker".into(),
7552 versao: "^0.1".into(),
7553 restart: RestartPolicy::Permanent,
7554 };
7555 let req = c.versao_requirement();
7556 let versao_slice = c.versao.as_str();
7557 assert_eq!(
7558 req.as_ptr(),
7559 versao_slice.as_ptr(),
7560 "ChildSpec::versao_requirement must borrow from the .versao \
7561 String's backing storage — a fresh allocation here means the \
7562 accessor no longer names the substrate-primitive typed \
7563 dispatch and every downstream consumer would silently carry \
7564 a detached copy",
7565 );
7566 assert_eq!(
7567 req.len(),
7568 versao_slice.len(),
7569 "ChildSpec::versao_requirement and .versao.as_str() must \
7570 byte-equal in length as well as in address",
7571 );
7572 }
7573
7574 #[test]
7575 fn validate_gates_child_versao_through_lifted_accessor() {
7576 // Bilateral coherence pin: every `:children :versao` that
7577 // [`SupervisorSpec::validate`] accepts is one
7578 // [`crate::render::require_valid_versao_requirement`] accepts on
7579 // the accessor-projected value, and vice versa on the reject side.
7580 // This closes the "the validator reads through the accessor"
7581 // contract structurally — a future silent detour that made the
7582 // accessor return a different byte-string than the validator gates
7583 // against would surface here as a coverage mismatch, not as a
7584 // resolver-time semver-parse rejection at lacre-closure time far
7585 // from the caixa.lisp source. Peer of the sibling
7586 // `validate_gates_child_nome_through_lifted_accessor` (57c61d0) on
7587 // the per-`:children :caixa` axis and the M2
7588 // `validate_parses_prior_versao_through_lifted_accessor` (75d27a8)
7589 // on the peer per-`:upgrade-from :from` axis.
7590 //
7591 // Accept-set sweep: five Cargo-shaped semver requirement values
7592 // the upstream gate admits (caret / tilde / exact / wildcard /
7593 // bare-major).
7594 for ok_req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
7595 let s = SupervisorSpec {
7596 children: vec![ChildSpec {
7597 caixa: "worker".into(),
7598 versao: ok_req.into(),
7599 restart: RestartPolicy::Permanent,
7600 }],
7601 ..SupervisorSpec::default()
7602 };
7603 s.validate().unwrap_or_else(|e| {
7604 panic!(
7605 "SupervisorSpec::validate must accept :children :versao {ok_req:?} \
7606 (upstream versao-requirement gate accepts it): got {e:?}",
7607 );
7608 });
7609 let c = ChildSpec {
7610 caixa: "worker".into(),
7611 versao: ok_req.into(),
7612 restart: RestartPolicy::Permanent,
7613 };
7614 crate::render::require_valid_versao_requirement(
7615 c.versao_requirement(),
7616 || (),
7617 |_reason| (),
7618 )
7619 .unwrap_or_else(|()| {
7620 panic!(
7621 "require_valid_versao_requirement must accept the accessor-projected \
7622 :children :versao {ok_req:?}",
7623 );
7624 });
7625 }
7626 // Reject-set sweep: five requirement-violating shapes the upstream
7627 // gate refuses. The empty string closes the empty-first arm of the
7628 // shared [`crate::render::require_valid_versao_requirement`]
7629 // cascade; the four non-empty arms exercise distinct semver-parse
7630 // failure modes the M3 peer per-`:membros` reject-set already pins
7631 // (`rejects_invalid_membro_versao_requirement` on `^bad-version`,
7632 // `rejects_membro_versao_with_double_caret_typo` on `^^0.1`,
7633 // `rejects_membro_versao_with_v_prefixed_tag` on `v0.1`) — the
7634 // shared parser routing means the same reject-set must fail
7635 // identically at the M2 supervisor-tree per-`:children` accessor
7636 // arm here. Every rejection at the validator must correspond to a
7637 // rejection when the accessor's projected value is fed back
7638 // through the shared gate.
7639 //
7640 // (Bare partial magnitudes like `"0.1"` and bare identifiers like
7641 // `"not-a-semver"` are intentionally *not* in the reject-set: the
7642 // semver crate accepts `"0.1"` as an implicit `^0.1` requirement,
7643 // and the identifier-tail arm's grammar admits some non-canonical
7644 // shapes — matching what the M3 peer test suite already documents
7645 // as the shared parser's accept-set edges.)
7646 for bad_req in ["", "v0.1.0", "^bad-version", "^^0.1", "v0.1"] {
7647 let s = SupervisorSpec {
7648 children: vec![ChildSpec {
7649 caixa: "worker".into(),
7650 versao: bad_req.into(),
7651 restart: RestartPolicy::Permanent,
7652 }],
7653 ..SupervisorSpec::default()
7654 };
7655 let err = s.validate().unwrap_err();
7656 assert!(
7657 matches!(
7658 err,
7659 SupervisorError::EmptyChildVersion { .. }
7660 | SupervisorError::ChildVersaoInvalid { .. }
7661 ),
7662 "SupervisorSpec::validate must reject :children :versao {bad_req:?} \
7663 via the versao-requirement gate: got {err:?}",
7664 );
7665 let c = ChildSpec {
7666 caixa: "worker".into(),
7667 versao: bad_req.into(),
7668 restart: RestartPolicy::Permanent,
7669 };
7670 assert!(
7671 crate::render::require_valid_versao_requirement(
7672 c.versao_requirement(),
7673 || (),
7674 |_reason| (),
7675 )
7676 .is_err(),
7677 "require_valid_versao_requirement must reject the accessor-projected \
7678 :children :versao {bad_req:?}",
7679 );
7680 }
7681 }
7682
7683 // ── per-`:children` `:restart` typed-accessor coherence pins ──────────
7684 //
7685 // The [`ChildSpec::restart`] accessor lift closes the last unlifted
7686 // per-`:children` axis (the pair `nome()` + `versao_requirement()`
7687 // already project the `String`-carry `(caixa, versao)` fields; the
7688 // `Copy`-composite-enum `restart` field is the third and final axis).
7689 // Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
7690 // (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
7691 // scalar accessor and the M3 mesh-slot [`crate::Placement::estrategia`]
7692 // (921fe1b) `Copy`-return [`crate::PlacementStrategy`] distribution-
7693 // strategy scalar accessor — same "one typed dispatch on the substrate
7694 // primitive, `Copy`-projected closed-set enum-arm discriminator" shape
7695 // extended onto the M2 supervisor-slot per-`:children` restart-decision
7696 // axis. The pin below covers the accessor's byte-equal projection
7697 // against the raw field access across every variant in the closed
7698 // accept-set (`Permanent`, `Transient`, `Temporary`).
7699
7700 #[test]
7701 fn child_spec_restart_returns_restart_verbatim_across_permutations() {
7702 // The canonical per-`:children` restart-decision-policy-scalar
7703 // pin: [`ChildSpec::restart`] must return the `:children :restart`
7704 // field verbatim as a [`RestartPolicy`], `Copy`-projected from the
7705 // typed slot's own [`RestartPolicy`] storage across every variant
7706 // in the closed accept-set (`Permanent`, `Transient`, `Temporary`).
7707 // Pins against a future silent detour that re-derived the policy
7708 // from a peer axis (an accidental fallback to
7709 // `if is_supervisor_child { Permanent } else { Temporary }` that
7710 // collapsed the child's kind axis into the restart discriminator),
7711 // a variant remap the operator authors on one consumer without the
7712 // other, or a stale-derive detour that substituted
7713 // [`RestartPolicy::default`] when the field held any explicit
7714 // variant (which would silently collapse the distinction between
7715 // "author explicitly declared `:restart Permanent`" and "author
7716 // omitted the slot and inherited the default" the future
7717 // per-cluster restart-decision override slot depends on).
7718 //
7719 // Peer of the sibling per-`:supervisor`
7720 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
7721 // (eafb619) pin on the M2 supervisor-slot sibling-restart-strategy
7722 // axis and the M3
7723 // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
7724 // (921fe1b) pin on the per-`:placement` distribution-strategy axis
7725 // — same "the substrate-primitive accessor must byte-equal the raw
7726 // field access verbatim across every author-declared value"
7727 // discipline extended onto the M2 supervisor-slot per-`:children`
7728 // restart-decision-policy axis, closing the last unlifted axis on
7729 // the per-`:children` [`ChildSpec`] type.
7730 for restart in [
7731 RestartPolicy::Permanent,
7732 RestartPolicy::Transient,
7733 RestartPolicy::Temporary,
7734 ] {
7735 let c = ChildSpec {
7736 caixa: "worker".into(),
7737 versao: "^0.1".into(),
7738 restart,
7739 };
7740 assert_eq!(
7741 c.restart(),
7742 restart,
7743 "ChildSpec::restart must return :children :restart \
7744 verbatim (got {:?}, expected {restart:?})",
7745 c.restart(),
7746 );
7747 assert_eq!(
7748 c.restart(),
7749 c.restart,
7750 "ChildSpec::restart accessor and .restart field access \
7751 must byte-equal — the accessor is the substrate-primitive \
7752 typed dispatch every downstream per-child restart-\
7753 decision consumer must route through",
7754 );
7755 }
7756 }
7757
7758 // ── per-`:supervisor` `:estrategia` typed-accessor coherence pins ─────
7759 //
7760 // The [`SupervisorSpec::estrategia`] accessor lift extends the peer M3
7761 // [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
7762 // distribution-strategy accessor discipline onto the M2 supervisor-slot
7763 // per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
7764 // scalar axis. The two pins below cover (1) the accessor's byte-equal
7765 // projection against the raw field access across every variant in the
7766 // closed accept-set, and (2) the two-consumer coherence between the
7767 // [`SupervisorSpec::validate`] partition-dispatch `match` arm and the
7768 // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
7769 // carrier's `estrategia:` field — peer of the sibling M3
7770 // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
7771 // / `validate_placement_reads_through_lifted_estrategia_accessor` pin
7772 // pair on the per-`:placement` distribution-strategy axis.
7773
7774 #[test]
7775 fn supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations() {
7776 // The canonical per-`:supervisor` sibling-restart-strategy-scalar
7777 // pin: [`SupervisorSpec::estrategia`] must return the
7778 // `:supervisor :estrategia` field verbatim as a
7779 // [`RestartStrategy`], `Copy`-projected from the typed slot's own
7780 // [`RestartStrategy`] storage across every variant in the closed
7781 // accept-set (`OneForOne`, `OneForAll`, `RestForOne`,
7782 // `SimpleOneForOne`). Pins against a future silent detour that
7783 // re-derived the strategy from a peer axis (an accidental
7784 // fallback to `if children.is_empty() { SimpleOneForOne } else {
7785 // OneForOne }` collapse that read the children-count axis into
7786 // the strategy discriminator), a variant remap the operator
7787 // authors on one consumer without the other, or a stale-derive
7788 // detour that substituted [`RestartStrategy::default`] when the
7789 // field held any explicit variant (which would silently collapse
7790 // the distinction between "author explicitly declared
7791 // `:estrategia OneForOne`" and "author omitted the slot and
7792 // inherited the default" the future per-cluster strategy override
7793 // slot depends on). Peer of the sibling M3
7794 // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
7795 // (921fe1b) pin on the M3 mesh-slot `Copy`-composite-enum scalar
7796 // axis — same "the substrate-primitive accessor must byte-equal
7797 // the raw field access verbatim across every author-declared
7798 // value" discipline extended onto the M2 supervisor-slot
7799 // per-`:supervisor` sibling-restart-strategy axis.
7800 for &estrategia in RestartStrategy::ALL {
7801 // `SimpleOneForOne` requires `children.is_empty()`; the peer
7802 // three strategies require a non-empty static children list.
7803 // Build each shape coherently so the pin's fixture would
7804 // itself pass [`SupervisorSpec::validate`] once fed through
7805 // the sibling coherence pin below — the byte-equal projection
7806 // asserted here is a strictly weaker property (a `Copy` field
7807 // read) that does not depend on `validate` running, but
7808 // keeping the fixture validate-clean means a future extension
7809 // of the pin to exercise `validate` end-to-end does not have
7810 // to re-author the children shape.
7811 //
7812 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
7813 // shape partition through the [`gen_platform::IsVariant`]
7814 // derive-generated
7815 // [`RestartStrategy::is_simple_one_for_one`] predicate rather
7816 // than the raw `matches!(estrategia, RestartStrategy::
7817 // SimpleOneForOne)` open-coded pattern-match — same closed-
7818 // set-typed-enum arm-discriminator dispatch discipline the
7819 // sibling [`crate::upgrade::UpgradeInstruction::is_restart`]
7820 // convergence (915a934) extended onto its two paired positive
7821 // / negated `matches!` sites and the peer
7822 // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
7823 // predicate convergence (766ec63) extended onto the M3 mesh-
7824 // slot per-`:placement` distribution-strategy discriminator
7825 // axis. See the sibling `round_trip_all_strategies` and the
7826 // peer `manifest::tests::
7827 // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
7828 // fixture for the two peer sites the same lift closes on.
7829 let children = if estrategia.is_simple_one_for_one() {
7830 Vec::new()
7831 } else {
7832 vec![ChildSpec {
7833 caixa: "worker".into(),
7834 versao: "^0.1".into(),
7835 restart: RestartPolicy::Permanent,
7836 }]
7837 };
7838 let s = SupervisorSpec {
7839 estrategia,
7840 children,
7841 ..SupervisorSpec::default()
7842 };
7843 assert_eq!(
7844 s.estrategia(),
7845 estrategia,
7846 "SupervisorSpec::estrategia must return :supervisor :estrategia \
7847 verbatim (got {:?}, expected {estrategia:?})",
7848 s.estrategia(),
7849 );
7850 assert_eq!(
7851 s.estrategia(),
7852 s.estrategia,
7853 "SupervisorSpec::estrategia accessor and .estrategia field \
7854 access must byte-equal — the accessor is the substrate-\
7855 primitive typed dispatch every downstream sibling-restart-\
7856 strategy consumer must route through",
7857 );
7858 }
7859 }
7860
7861 #[test]
7862 fn validate_reads_through_lifted_estrategia_accessor() {
7863 // Two-consumer coherence pin: the [`SupervisorSpec::validate`]
7864 // `SimpleOneForOne ↔ non-SimpleOneForOne` `match` partition
7865 // dispatch (which reads through [`SupervisorSpec::estrategia`]
7866 // to fan across the strategy-arm shape-gate cascades) and the
7867 // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
7868 // error carrier's `estrategia:` field (which reads through
7869 // [`SupervisorSpec::estrategia`] to name the strategy the empty
7870 // `:children` list was declared against) must both key off the
7871 // lifted accessor, so any future rebrand on the typed slot's
7872 // reader shape lands at exactly one place. Pins the two-site
7873 // coherence by exercising the `NoChildren` error surface end-to-
7874 // end across every non-`SimpleOneForOne` variant and asserting
7875 // the surfaced `estrategia:` field byte-equals the accessor's
7876 // return. Peer of the sibling M3
7877 // `validate_placement_reads_through_lifted_estrategia_accessor`
7878 // (921fe1b) three-consumer coherence pin on the per-`:placement`
7879 // distribution-strategy axis.
7880 for estrategia in [
7881 RestartStrategy::OneForOne,
7882 RestartStrategy::OneForAll,
7883 RestartStrategy::RestForOne,
7884 ] {
7885 let s = SupervisorSpec {
7886 estrategia,
7887 children: Vec::new(),
7888 ..SupervisorSpec::default()
7889 };
7890 let err = s.validate().unwrap_err();
7891 match err {
7892 SupervisorError::NoChildren { estrategia: e } => {
7893 assert_eq!(
7894 e,
7895 s.estrategia(),
7896 "NoChildren.estrategia must byte-equal \
7897 SupervisorSpec::estrategia() — the empty-`:children` \
7898 refusal reads through the lifted accessor",
7899 );
7900 assert_eq!(
7901 e, estrategia,
7902 "NoChildren.estrategia must carry the author-declared \
7903 :supervisor :estrategia variant verbatim (got {e:?}, \
7904 expected {estrategia:?})",
7905 );
7906 }
7907 other => panic!("expected NoChildren, got {other:?} for estrategia={estrategia:?}"),
7908 }
7909 }
7910 }
7911
7912 // ── per-`:supervisor` `:max-restarts` typed-accessor coherence pins ────
7913 //
7914 // The [`SupervisorSpec::max_restarts`] accessor lift extends the peer M3
7915 // [`crate::CircuitBreaker::max_failures`] (3a74062) `Copy`-return
7916 // required-`u32` scalar accessor discipline onto the M2 supervisor-slot
7917 // per-`:supervisor` restart-budget-count `Copy`-`u32` scalar axis.
7918 // The two pins below cover (1) the accessor's byte-equal projection
7919 // against the raw field access across every representative value in
7920 // the `u32` accept-set (`1` lower boundary, `SUPERVISOR_MAX_RESTARTS_MAX`
7921 // upper boundary, `0` past-the-guard zero sentinel, `u32::MAX`
7922 // past-the-guard cap sentinel), and (2) the [`SupervisorSpec::validate`]
7923 // zero-floor / cap composition — the validate gate and the accessor
7924 // must route through the same substrate-primitive typed dispatch, so
7925 // any future silent detour that had the accessor perform a
7926 // bounds-collapsing clamp would fail here at caixa-core build time.
7927 // Peer of the sibling M3
7928 // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
7929 // (3a74062) pin on the per-`CircuitBreaker :max-failures` axis.
7930
7931 #[test]
7932 fn supervisor_spec_max_restarts_returns_max_restarts_u32_byte_equal_across_permutations() {
7933 // The canonical per-`:supervisor` restart-budget-count scalar pin:
7934 // [`SupervisorSpec::max_restarts`] must return the `:supervisor
7935 // :max-restarts` typed `u32` verbatim, `Copy`-projected from the
7936 // typed slot's own `u32` storage, byte-equal to the raw field
7937 // access across every representative value in the accept-set —
7938 // `1` (the lower boundary of the `1..=SUPERVISOR_MAX_RESTARTS_MAX`
7939 // accept-set the surrounding [`SupervisorSpec::validate`] gate
7940 // carves out on the sibling `ZeroMaxRestarts` refusal),
7941 // `SUPERVISOR_MAX_RESTARTS_MAX` (the upper boundary the same gate
7942 // carves out on the sibling `MaxRestartsExceedsCap` refusal), `0`
7943 // (a past-the-guard sentinel that pins the accessor doesn't
7944 // perform a silent bounds-collapse into `1` on the zero arm —
7945 // validate rejects zero but the accessor must ship the raw slot
7946 // verbatim so a validate-time gate regression surfaces at the
7947 // emit boundary rather than being silently absorbed), `u32::MAX`
7948 // (a past-the-guard sentinel that pins the accessor doesn't
7949 // perform a silent bounds-collapse through
7950 // `SUPERVISOR_MAX_RESTARTS_MAX` at the return path).
7951 //
7952 // Peer of the sibling M3
7953 // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
7954 // (3a74062) pin on the M3 mesh-slot `Copy`-`u32` sub-struct
7955 // required-scalar axis — same "the substrate-primitive accessor
7956 // must byte-equal the raw field access verbatim across every
7957 // value in the `u32` accept-set" discipline extended onto the M2
7958 // supervisor-slot per-`:supervisor` restart-budget-count axis.
7959 for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX, 0, u32::MAX] {
7960 let s = SupervisorSpec {
7961 max_restarts,
7962 ..SupervisorSpec::default()
7963 };
7964 assert_eq!(
7965 s.max_restarts(),
7966 max_restarts,
7967 "SupervisorSpec::max_restarts must return :supervisor \
7968 :max-restarts verbatim (got {}, expected {max_restarts})",
7969 s.max_restarts(),
7970 );
7971 assert_eq!(
7972 s.max_restarts(),
7973 s.max_restarts,
7974 "SupervisorSpec::max_restarts accessor and .max_restarts \
7975 field access must byte-equal — the accessor is the \
7976 substrate-primitive typed dispatch every downstream \
7977 restart-budget-count consumer must route through",
7978 );
7979 }
7980 }
7981
7982 #[test]
7983 fn validate_max_restarts_zero_floor_and_cap_arms_route_through_accessor() {
7984 // Composition pin: [`SupervisorSpec::validate`]'s `:max-restarts`
7985 // zero-floor + upper-cap bracket must key off
7986 // [`SupervisorSpec::max_restarts`], not the raw `.max_restarts`
7987 // field access. Structurally: a `SupervisorSpec { max_restarts:
7988 // 0, .. }` must surface the `ZeroMaxRestarts` refusal exactly, a
7989 // `SupervisorSpec { max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
7990 // .. }` must surface the `MaxRestartsExceedsCap` refusal exactly
7991 // (with the offending count carried verbatim from the accessor
7992 // return), and a `SupervisorSpec { max_restarts: 1, .. }` (the
7993 // lower boundary of the accept-set) plus a `SupervisorSpec {
7994 // max_restarts: SUPERVISOR_MAX_RESTARTS_MAX, .. }` (the upper
7995 // boundary) must pass validate. The four together jointly pin the
7996 // accessor + validate-gate composition: any future silent detour
7997 // that had the accessor return a fresh `1` on the zero arm (a
7998 // `.max_restarts().max(1)` collapse) would silently absorb the
7999 // `ZeroMaxRestarts` refusal at the accessor boundary and the
8000 // validate gate would accept a struct-literal `SupervisorSpec {
8001 // max_restarts: 0, .. }` — the composition pin catches that at
8002 // caixa-core build time.
8003 //
8004 // Peer of the sibling M3
8005 // `validate_politicas_max_failures_zero_floor_arm_routes_through_accessor`
8006 // (3a74062) pin on the sibling per-`CircuitBreaker :max-failures`
8007 // composition axis — same "the validate / shape-gate predicate
8008 // must route through the substrate-primitive typed dispatch"
8009 // discipline extended onto the peer M2 supervisor-slot
8010 // required-`u32` composition axis.
8011 let child = ChildSpec {
8012 caixa: "worker".into(),
8013 versao: "^0.1".into(),
8014 restart: RestartPolicy::Permanent,
8015 };
8016 // Zero-floor arm.
8017 let s = SupervisorSpec {
8018 max_restarts: 0,
8019 children: vec![child.clone()],
8020 ..SupervisorSpec::default()
8021 };
8022 assert_eq!(
8023 s.validate().unwrap_err(),
8024 SupervisorError::ZeroMaxRestarts,
8025 "validate must reject max_restarts == 0 with ZeroMaxRestarts \
8026 — the accessor and the validate gate must route through the \
8027 same substrate-primitive typed dispatch on the zero-floor arm",
8028 );
8029 // Cap arm — the surfaced `max_restarts:` field must byte-equal
8030 // the accessor's return so a future rebrand on the accessor
8031 // lands in the diagnostic without a coordinated rewrite.
8032 let over_cap = SUPERVISOR_MAX_RESTARTS_MAX + 1;
8033 let s = SupervisorSpec {
8034 max_restarts: over_cap,
8035 children: vec![child.clone()],
8036 ..SupervisorSpec::default()
8037 };
8038 match s.validate().unwrap_err() {
8039 SupervisorError::MaxRestartsExceedsCap { max_restarts } => {
8040 assert_eq!(
8041 max_restarts,
8042 s.max_restarts(),
8043 "MaxRestartsExceedsCap.max_restarts must byte-equal \
8044 SupervisorSpec::max_restarts() — the cap-arm refusal \
8045 reads through the lifted accessor",
8046 );
8047 assert_eq!(
8048 max_restarts, over_cap,
8049 "MaxRestartsExceedsCap.max_restarts must carry the \
8050 author-declared :supervisor :max-restarts value \
8051 verbatim (got {max_restarts}, expected {over_cap})",
8052 );
8053 }
8054 other => panic!("expected MaxRestartsExceedsCap, got {other:?}"),
8055 }
8056 // Lower + upper accept-set boundaries.
8057 for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX] {
8058 let s = SupervisorSpec {
8059 max_restarts,
8060 children: vec![child.clone()],
8061 ..SupervisorSpec::default()
8062 };
8063 assert!(
8064 s.validate().is_ok(),
8065 "validate must accept max_restarts == {max_restarts} \
8066 (an accept-set boundary of \
8067 1..=SUPERVISOR_MAX_RESTARTS_MAX)",
8068 );
8069 }
8070 }
8071
8072 // ── per-`:supervisor` `:restart-window` typed-accessor coherence pins ─
8073 //
8074 // The [`SupervisorSpec::restart_window`] accessor lift extends the peer
8075 // M2 [`crate::LimitsSpec::wall_clock`] (8cb717b) `Option<Duration>`
8076 // accessor discipline and the peer M3 [`crate::MeshPolicy::timeout`]
8077 // (7073d0f) `Option<Duration>` accessor discipline onto the M2
8078 // supervisor-slot per-`:supervisor` restart-intensity-denominator
8079 // `Option<Duration>` scalar axis — third `Copy`-return accessor on the
8080 // M2 supervisor-slot `SupervisorSpec` type, closing the last unlifted
8081 // per-`:supervisor` scalar-value axis. The three pins below cover
8082 // (1) the accessor's byte-equal projection against the raw field
8083 // access across every representative value in the `Option<Duration>`
8084 // accept-set (`None` never-reset sentinel, `Some(Duration::from_millis(1))`
8085 // lower boundary, `Some(SUPERVISOR_RESTART_WINDOW_MAX)` upper boundary,
8086 // `Some(Duration::ZERO)` past-the-guard zero sentinel, `Some(Duration::MAX)`
8087 // past-the-guard above-cap sentinel), (2) the [`SupervisorSpec::validate`]
8088 // `if let Some(w) = self.restart_window() { … }` bracket-arm
8089 // composition — the validate gate and the accessor must route through
8090 // the same substrate-primitive typed dispatch, so any future silent
8091 // detour that had the accessor perform a bounds-collapsing clamp
8092 // would fail here at caixa-core build time, and (3) the accessor's
8093 // by-copy idempotence pin — the returned `Option<Duration>` must
8094 // outlive `&self` and two successive calls must return byte-equal
8095 // values. Peer of the sibling M2
8096 // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
8097 // (8cb717b) pin on the per-`:limits :wall-clock` axis and the sibling
8098 // M3 `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
8099 // (7073d0f) pin on the per-`:politicas :timeout` axis.
8100
8101 #[test]
8102 fn supervisor_spec_restart_window_returns_option_duration_byte_equal_across_permutations() {
8103 // The canonical per-`:supervisor` restart-intensity-denominator
8104 // scalar pin: [`SupervisorSpec::restart_window`] must return the
8105 // `:supervisor :restart-window` typed [`Duration`] verbatim as an
8106 // `Option<Duration>`, `Copy`-projected from the typed slot's own
8107 // `Option<Duration>` storage, byte-equal to the raw field access
8108 // across every representative value in the accept-set — `None`
8109 // (the "never reset — every restart across the supervisor's
8110 // lifetime counts against the sibling `:max-restarts` budget"
8111 // sentinel the field's own docstring names and the peer
8112 // `validate_accepts_none_restart_window` pin locks in on the
8113 // [`SupervisorSpec::validate`] entry-side),
8114 // `Some(Duration::from_millis(1))` (the structural minimum a
8115 // validated `:restart-window` may carry, the integer-millisecond
8116 // floor [`SupervisorError::RestartWindowNotCanonical`] rejects
8117 // everything sub-ms; `Duration::ZERO` is separately rejected by
8118 // [`SupervisorError::RestartWindowZero`]),
8119 // `Some(SUPERVISOR_RESTART_WINDOW_MAX)` (the upper boundary the
8120 // surrounding [`SupervisorSpec::validate`] gate carves out on the
8121 // sibling [`SupervisorError::RestartWindowExceedsCap`] refusal),
8122 // `Some(Duration::ZERO)` (a past-the-guard sentinel that pins the
8123 // accessor doesn't perform a silent bounds-collapse into `None` on
8124 // the zero-Duration arm — validate rejects zero but the accessor
8125 // must ship the raw slot verbatim so a validate-time gate
8126 // regression surfaces at the emit boundary rather than being
8127 // silently absorbed), and `Some(Duration::MAX)` (a past-the-guard
8128 // sentinel that pins the accessor doesn't perform a silent
8129 // bounds-collapse through [`SUPERVISOR_RESTART_WINDOW_MAX`] at the
8130 // return path).
8131 //
8132 // Peer of the sibling M2
8133 // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
8134 // (8cb717b) pin on the per-`:limits :wall-clock` axis and the
8135 // sibling M3
8136 // `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
8137 // (7073d0f) pin on the per-`:politicas :timeout` axis — same "the
8138 // substrate-primitive accessor must byte-equal the raw field
8139 // access verbatim across every value in the `Option<Duration>`
8140 // accept-set" discipline extended onto the M2 supervisor-slot
8141 // per-`:supervisor` `Option<Duration>` axis. Pins against a future
8142 // silent detour that re-derived the restart-window from a peer
8143 // axis (an accidental `.max_restarts.into()` collapse that read
8144 // the restart-budget-count as a duration — the two axes serve
8145 // different halves of the `MaxIntensity / Period` restart-
8146 // intensity ratio, and confusing them silently inverts the
8147 // ratio's numerator and denominator), a `None → Some(Duration::ZERO)`
8148 // "zero means never reset" collapse (the canonical
8149 // `Option<Duration>` → `Duration` collapse footgun the
8150 // [`SupervisorError::RestartWindowZero`] validate arm guards on
8151 // the peer zero-floor axis; a zero period either trips on the
8152 // first failure or never trips depending on operator
8153 // interpretation, neither of which is the author's "never reset"
8154 // intent that `None` expresses structurally), or a per-arm
8155 // variant swap that landed on one consumer without the other.
8156 for restart_window in [
8157 None,
8158 Some(Duration::from_millis(1)),
8159 Some(SUPERVISOR_RESTART_WINDOW_MAX),
8160 Some(Duration::ZERO),
8161 Some(Duration::MAX),
8162 ] {
8163 let s = SupervisorSpec {
8164 restart_window,
8165 ..SupervisorSpec::default()
8166 };
8167 assert_eq!(
8168 s.restart_window(),
8169 restart_window,
8170 "SupervisorSpec::restart_window must return :supervisor \
8171 :restart-window verbatim (got {:?}, expected {restart_window:?})",
8172 s.restart_window(),
8173 );
8174 assert_eq!(
8175 s.restart_window(),
8176 s.restart_window,
8177 "SupervisorSpec::restart_window accessor and \
8178 .restart_window field access must byte-equal — the \
8179 accessor is the substrate-primitive typed dispatch every \
8180 downstream restart-intensity-denominator consumer must \
8181 route through",
8182 );
8183 }
8184 }
8185
8186 #[test]
8187 fn validate_restart_window_bracket_arm_routes_through_accessor() {
8188 // Composition pin: [`SupervisorSpec::validate`]'s
8189 // `:restart-window` `if let Some(w) = self.restart_window() { … }`
8190 // zero-floor + integer-millisecond canonical-form + upper-cap
8191 // bracket-arm must key off [`SupervisorSpec::restart_window`], not
8192 // the raw `.restart_window` field access. Structurally: a
8193 // `SupervisorSpec { restart_window: None, .. }` must pass the
8194 // arm gate structurally (the `if let Some(_)` shape returns
8195 // early on the `None` arm — the accessor and the validate gate
8196 // must agree on `None → skip the bracket cascade` so an authored
8197 // `:restart-window ()` structurally routes through the "never
8198 // reset" sentinel path), a `SupervisorSpec { restart_window:
8199 // Some(Duration::ZERO), .. }` must surface the `RestartWindowZero`
8200 // refusal exactly, a `SupervisorSpec { restart_window:
8201 // Some(Duration::from_micros(1500)), .. }` must surface the
8202 // `RestartWindowNotCanonical` refusal exactly (with the offending
8203 // duration carried verbatim from the accessor return), a
8204 // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX
8205 // + Duration::from_millis(1)), .. }` must surface the
8206 // `RestartWindowExceedsCap` refusal exactly (with the offending
8207 // duration carried verbatim from the accessor return), and a
8208 // `SupervisorSpec { restart_window: Some(Duration::from_millis(1)),
8209 // .. }` (the lower boundary of the accept-set) plus a
8210 // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
8211 // .. }` (the upper boundary) must pass validate. The six together
8212 // jointly pin the accessor + validate-gate composition: any future
8213 // silent detour that had the accessor return a fresh `None` on any
8214 // `Some` arm (a `.restart_window().filter(|w| !w.is_zero())`
8215 // collapse) would silently absorb the `RestartWindowZero` refusal
8216 // at the accessor boundary and the validate gate would accept a
8217 // struct-literal `SupervisorSpec { restart_window:
8218 // Some(Duration::ZERO), .. }` — the composition pin catches that
8219 // at caixa-core build time.
8220 //
8221 // Peer of the sibling M2 [`crate::LimitsSpec::wall_clock`]
8222 // (8cb717b) validate-arm-route pin on the per-`:limits :wall-clock`
8223 // axis and the peer M3 [`crate::MeshPolicy::timeout`] (7073d0f)
8224 // accessor-composition pin on the per-`:politicas :timeout` axis —
8225 // same "the validate / shape-gate predicate must route through
8226 // the substrate-primitive typed dispatch" discipline extended
8227 // onto the peer M2 supervisor-slot optional-`Duration` axis.
8228 let child = ChildSpec {
8229 caixa: "worker".into(),
8230 versao: "^0.1".into(),
8231 restart: RestartPolicy::Permanent,
8232 };
8233 // None arm — must not surface any :restart-window-shaped refusal;
8234 // the `if let Some(_)` bracket returns early on `None` structurally.
8235 let s = SupervisorSpec {
8236 restart_window: None,
8237 children: vec![child.clone()],
8238 ..SupervisorSpec::default()
8239 };
8240 assert!(
8241 s.validate().is_ok(),
8242 "validate must accept restart_window: None (the never-reset \
8243 sentinel) — the `if let Some(_)` bracket returns early on \
8244 the None arm and the accessor must agree",
8245 );
8246 // Zero-floor arm.
8247 let s = SupervisorSpec {
8248 restart_window: Some(Duration::ZERO),
8249 children: vec![child.clone()],
8250 ..SupervisorSpec::default()
8251 };
8252 assert_eq!(
8253 s.validate().unwrap_err(),
8254 SupervisorError::RestartWindowZero,
8255 "validate must reject restart_window == Some(Duration::ZERO) \
8256 with RestartWindowZero — the accessor and the validate gate \
8257 must route through the same substrate-primitive typed \
8258 dispatch on the zero-floor arm",
8259 );
8260 // Non-canonical (sub-ms) arm — the surfaced `window:` field must
8261 // byte-equal the accessor's return so a future rebrand on the
8262 // accessor lands in the diagnostic without a coordinated rewrite.
8263 let sub_ms = Duration::from_micros(1500);
8264 let s = SupervisorSpec {
8265 restart_window: Some(sub_ms),
8266 children: vec![child.clone()],
8267 ..SupervisorSpec::default()
8268 };
8269 match s.validate().unwrap_err() {
8270 SupervisorError::RestartWindowNotCanonical { window } => {
8271 assert_eq!(
8272 Some(window),
8273 s.restart_window(),
8274 "RestartWindowNotCanonical.window must byte-equal \
8275 SupervisorSpec::restart_window().unwrap() — the \
8276 non-canonical-arm refusal reads through the lifted \
8277 accessor",
8278 );
8279 assert_eq!(
8280 window, sub_ms,
8281 "RestartWindowNotCanonical.window must carry the \
8282 author-declared :supervisor :restart-window value \
8283 verbatim (got {window:?}, expected {sub_ms:?})",
8284 );
8285 }
8286 other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
8287 }
8288 // Cap arm — the surfaced `window:` field must byte-equal the
8289 // accessor's return.
8290 let over_cap = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
8291 let s = SupervisorSpec {
8292 restart_window: Some(over_cap),
8293 children: vec![child.clone()],
8294 ..SupervisorSpec::default()
8295 };
8296 match s.validate().unwrap_err() {
8297 SupervisorError::RestartWindowExceedsCap { window } => {
8298 assert_eq!(
8299 Some(window),
8300 s.restart_window(),
8301 "RestartWindowExceedsCap.window must byte-equal \
8302 SupervisorSpec::restart_window().unwrap() — the \
8303 cap-arm refusal reads through the lifted accessor",
8304 );
8305 assert_eq!(
8306 window, over_cap,
8307 "RestartWindowExceedsCap.window must carry the \
8308 author-declared :supervisor :restart-window value \
8309 verbatim (got {window:?}, expected {over_cap:?})",
8310 );
8311 }
8312 other => panic!("expected RestartWindowExceedsCap, got {other:?}"),
8313 }
8314 // Lower + upper accept-set boundaries.
8315 for restart_window in [Duration::from_millis(1), SUPERVISOR_RESTART_WINDOW_MAX] {
8316 let s = SupervisorSpec {
8317 restart_window: Some(restart_window),
8318 children: vec![child.clone()],
8319 ..SupervisorSpec::default()
8320 };
8321 assert!(
8322 s.validate().is_ok(),
8323 "validate must accept restart_window == Some({restart_window:?}) \
8324 (an accept-set boundary of \
8325 1ms..=SUPERVISOR_RESTART_WINDOW_MAX)",
8326 );
8327 }
8328 }
8329
8330 #[test]
8331 fn supervisor_spec_restart_window_projects_option_duration_by_copy() {
8332 // The by-copy pin: [`SupervisorSpec::restart_window`] returns
8333 // `Option<Duration>` by copy — `Duration` is `Copy` (so
8334 // `Option<Duration>` is `Copy`) and the accessor must return by
8335 // value, not by reference. Peer of the sibling M2
8336 // [`crate::LimitsSpec::wall_clock`] (8cb717b) by-copy pin on the
8337 // per-`:limits :wall-clock` axis and the sibling M3
8338 // [`crate::MeshPolicy::timeout`] (7073d0f) by-copy pin on the
8339 // per-`:politicas :timeout` axis, extended onto the peer M2
8340 // supervisor-slot `Option<Duration>` copy-invariant shape — the
8341 // accessor's returned `Option<Duration>` must outlive `&self`
8342 // (multiple calls must return equal values from a dropped-`&self`
8343 // copy, since the returned Option carries no borrow), and calling
8344 // the accessor twice on the same SupervisorSpec must yield the
8345 // same `Option<Duration>` verbatim (idempotent, no side effects
8346 // on `&self`).
8347 //
8348 // Pins against a future silent detour that returned
8349 // `Option<&Duration>` (which would type-check but silently break
8350 // every downstream caller — the future wasm-operator's
8351 // per-supervisor restart-intensity counter consumes `Duration` by
8352 // value and `&Duration` would fold to a detached copy at the call
8353 // site), an accidental `Option::as_ref()` projection
8354 // (`self.restart_window.as_ref()` would also type-check but
8355 // return `Option<&Duration>`), or a one-arm-only accessor that
8356 // reads `Some(*w)` in the Some arm but reads a fresh
8357 // `Default::default()` (which would collapse to `Duration::ZERO`,
8358 // not `None`) in the None arm — a footgun the
8359 // [`SupervisorError::RestartWindowZero`] validate arm explicitly
8360 // closes since Erlang/OTP's `MaxIntensity / Period` invariant
8361 // requires `Period > 0` and `None` structurally expresses "never
8362 // reset" instead.
8363 for restart_window in [
8364 None,
8365 Some(Duration::from_millis(1)),
8366 Some(Duration::from_secs(60)),
8367 Some(SUPERVISOR_RESTART_WINDOW_MAX),
8368 ] {
8369 let s = SupervisorSpec {
8370 restart_window,
8371 ..SupervisorSpec::default()
8372 };
8373 let first = s.restart_window();
8374 let second = s.restart_window();
8375 assert_eq!(
8376 first, second,
8377 "SupervisorSpec::restart_window must be idempotent — two \
8378 successive calls on the same &self must return the \
8379 same Option<Duration>",
8380 );
8381 assert_eq!(
8382 first, restart_window,
8383 "SupervisorSpec::restart_window must return :supervisor \
8384 :restart-window verbatim by copy — got {first:?}, \
8385 expected {restart_window:?}",
8386 );
8387 }
8388 }
8389
8390 // ── per-`:supervisor` `:children` typed-accessor coherence pins ─────────
8391 //
8392 // The [`SupervisorSpec::children`] accessor lift is the seed of the
8393 // slice-return (`&[T]`) accessor discipline on the substrate — the four
8394 // peer `Vec`-carry axes ([`crate::Placement::clusters`],
8395 // [`crate::AplicacaoSpec::membros`], [`crate::AplicacaoSpec::contratos`],
8396 // [`crate::UpgradeFromEntry::instructions`]) still key off the raw field
8397 // access at the time of this seed, and inherit this pin family's
8398 // discipline as future compounding runs migrate their consumers. The
8399 // three pins below cover (1) the accessor's byte-equal projection
8400 // against the raw field access across the empty / singleton / cohort
8401 // fixtures the [`SupervisorSpec::validate`] partition-dispatch fans
8402 // between, (2) the [`SupervisorSpec::validate`] `SimpleOneForOne ↔
8403 // non-SimpleOneForOne` partition dispatch's paired `.is_empty()`
8404 // consumer routing through the accessor on both arms, and (3) the
8405 // per-child validate loop's traversal reading the same slice-view the
8406 // accessor projects. Peer of the sibling M2
8407 // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
8408 // two-consumer coherence pin on the per-`:supervisor`
8409 // sibling-restart-strategy `Copy`-composite-enum scalar axis, extended
8410 // onto the per-`:supervisor` static-child-list `Vec`-carry axis.
8411
8412 #[test]
8413 fn supervisor_spec_children_returns_children_slice_byte_equal_across_permutations() {
8414 // The canonical per-`:supervisor` static-child-list scalar-shape
8415 // pin: [`SupervisorSpec::children`] must return the `:supervisor
8416 // :children` typed `Vec<ChildSpec>` verbatim as a `&[ChildSpec]`
8417 // slice-view over the same backing buffer the raw
8418 // `self.children.as_slice()` field access borrows from, byte-
8419 // equal across every representative fixture in the accept-set —
8420 // the empty slice (the `SimpleOneForOne`-arm sentinel),
8421 // the singleton slice (the minimal non-`SimpleOneForOne` shape),
8422 // and a two-child cohort (a peer non-`SimpleOneForOne` shape
8423 // with the peer three restart-policy variants in play).
8424 //
8425 // Pins against a future silent detour that returned
8426 // `&Vec<ChildSpec>` (which would type-check but leak the
8427 // storage-side `Vec`'s grow/push/reserve surface no consumer of
8428 // the typed view reaches for), a fresh-allocated
8429 // `Vec<ChildSpec>` copy (which would type-check via a coercion
8430 // but silently break every downstream caller that relied on the
8431 // slice sharing the backing buffer's identity), or an
8432 // out-of-order or length-drifted projection (which would silently
8433 // split the per-child validate loop's traversal input from the
8434 // paired partition-dispatch `.is_empty()` probe's input).
8435 //
8436 // Peer of the sibling
8437 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
8438 // (eafb619) `Copy`-composite-enum byte-equal pin on the
8439 // per-`:supervisor` sibling-restart-strategy axis, extended onto
8440 // the per-`:supervisor` static-child-list `Vec`-carry axis.
8441 let fixtures: Vec<Vec<ChildSpec>> = vec![
8442 Vec::new(),
8443 vec![child("worker", "^0.1", RestartPolicy::Permanent)],
8444 vec![
8445 child("worker", "^0.1", RestartPolicy::Permanent),
8446 child("cache-server", "^0.1", RestartPolicy::Transient),
8447 ],
8448 vec![
8449 child("worker", "^0.1", RestartPolicy::Permanent),
8450 child("cache-server", "^0.1", RestartPolicy::Transient),
8451 child("scratch-job", "^0.1", RestartPolicy::Temporary),
8452 ],
8453 ];
8454 for children in fixtures {
8455 let s = SupervisorSpec {
8456 children: children.clone(),
8457 ..SupervisorSpec::default()
8458 };
8459 assert_eq!(
8460 s.children(),
8461 children.as_slice(),
8462 "SupervisorSpec::children must return :supervisor \
8463 :children verbatim (got {:?}, expected {:?})",
8464 s.children(),
8465 children.as_slice(),
8466 );
8467 assert_eq!(
8468 s.children(),
8469 s.children.as_slice(),
8470 "SupervisorSpec::children accessor and \
8471 .children.as_slice() field access must byte-equal — \
8472 the accessor is the substrate-primitive typed \
8473 dispatch every downstream static-child-list consumer \
8474 must route through",
8475 );
8476 assert_eq!(
8477 s.children().len(),
8478 s.children.len(),
8479 "SupervisorSpec::children().len() must byte-equal \
8480 self.children.len() — a length-drift would silently \
8481 split the paired partition-dispatch `.is_empty()` \
8482 probe input from the per-child validate loop's \
8483 traversal input",
8484 );
8485 }
8486 }
8487
8488 #[test]
8489 fn validate_reads_through_lifted_children_accessor() {
8490 // Three-consumer coherence pin: the [`SupervisorSpec::validate`]
8491 // `SimpleOneForOne`-arm `!self.children().is_empty()` refusal
8492 // probe (which must trip [`SupervisorError::SimpleOneForOneWithStaticChildren`]
8493 // when the accessor projects a non-empty slice under a
8494 // `SimpleOneForOne` estrategia), the peer non-`SimpleOneForOne`-arm
8495 // `self.children().is_empty()` refusal probe (which must trip
8496 // [`SupervisorError::NoChildren`] when the accessor projects the
8497 // empty slice under any peer estrategia), and the per-child
8498 // validate loop's `for child in self.children()` traversal
8499 // (which must reach every entry in the same order the accessor
8500 // projects) must all key off the lifted accessor, so any future
8501 // rebrand on the typed slot's reader shape lands at exactly one
8502 // place. Pins the three-site coherence by exercising each
8503 // production consumer end-to-end: (1) the
8504 // `SimpleOneForOneWithStaticChildren` refusal under a non-empty
8505 // slice + `SimpleOneForOne` estrategia, (2) the `NoChildren`
8506 // refusal under the empty slice + non-`SimpleOneForOne`
8507 // estrategia across every peer variant, and (3) the per-child
8508 // duplicate-detection surface fires on the second entry of a
8509 // two-child cohort that shares a `:caixa` name (which requires
8510 // the loop to reach both entries — a first-entry-only projection
8511 // would silently pass since the dedup HashSet has room for the
8512 // first insert).
8513 //
8514 // Peer of the sibling M2
8515 // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
8516 // two-consumer coherence pin on the per-`:supervisor`
8517 // sibling-restart-strategy axis, extended onto the
8518 // per-`:supervisor` static-child-list `Vec`-carry axis.
8519
8520 // (1) `SimpleOneForOne`-arm probe: a non-empty slice under a
8521 // `SimpleOneForOne` estrategia must trip
8522 // `SimpleOneForOneWithStaticChildren`.
8523 let s = SupervisorSpec {
8524 estrategia: RestartStrategy::SimpleOneForOne,
8525 children: vec![child("worker", "^0.1", RestartPolicy::Permanent)],
8526 ..SupervisorSpec::default()
8527 };
8528 assert_eq!(
8529 s.validate().unwrap_err(),
8530 SupervisorError::SimpleOneForOneWithStaticChildren,
8531 "SimpleOneForOne + non-empty children must trip \
8532 SimpleOneForOneWithStaticChildren — the accessor projects \
8533 a non-empty slice, and the SimpleOneForOne-arm refusal \
8534 probe reads through the lifted accessor",
8535 );
8536 assert!(
8537 !s.children().is_empty(),
8538 "the SimpleOneForOne-arm refusal input must be a non-empty \
8539 slice per the accessor's projection",
8540 );
8541
8542 // (2) Peer non-`SimpleOneForOne`-arm probe: the empty slice
8543 // under any peer estrategia must trip `NoChildren`.
8544 for estrategia in [
8545 RestartStrategy::OneForOne,
8546 RestartStrategy::OneForAll,
8547 RestartStrategy::RestForOne,
8548 ] {
8549 let s = SupervisorSpec {
8550 estrategia,
8551 children: Vec::new(),
8552 ..SupervisorSpec::default()
8553 };
8554 match s.validate().unwrap_err() {
8555 SupervisorError::NoChildren { estrategia: e } => {
8556 assert_eq!(
8557 e, estrategia,
8558 "NoChildren.estrategia must carry the author-\
8559 declared :supervisor :estrategia variant \
8560 verbatim (got {e:?}, expected {estrategia:?})",
8561 );
8562 }
8563 other => panic!(
8564 "expected NoChildren, got {other:?} for \
8565 estrategia={estrategia:?}"
8566 ),
8567 }
8568 assert!(
8569 s.children().is_empty(),
8570 "the non-SimpleOneForOne-arm refusal input must be the \
8571 empty slice per the accessor's projection",
8572 );
8573 }
8574
8575 // (3) Per-child validate loop: a two-child cohort that shares a
8576 // `:caixa` name must trip `DuplicateChildCaixa` — the loop must
8577 // reach both entries through the accessor.
8578 let s = SupervisorSpec {
8579 estrategia: RestartStrategy::OneForOne,
8580 children: vec![
8581 child("worker", "^0.1", RestartPolicy::Permanent),
8582 child("worker", "^0.2", RestartPolicy::Transient),
8583 ],
8584 ..SupervisorSpec::default()
8585 };
8586 match s.validate().unwrap_err() {
8587 SupervisorError::DuplicateChildCaixa { caixa } => {
8588 assert_eq!(
8589 caixa, "worker",
8590 "DuplicateChildCaixa.caixa must carry the shared \
8591 child `:caixa` name verbatim",
8592 );
8593 }
8594 other => panic!("expected DuplicateChildCaixa, got {other:?}"),
8595 }
8596 assert_eq!(
8597 s.children().len(),
8598 2,
8599 "the per-child validate loop's traversal input must be a \
8600 two-element slice per the accessor's projection",
8601 );
8602 }
8603
8604 // Shared helper for the M2 per-`:children` per-slot-gate ≡
8605 // `validate` equivalence pins: builds an `OneForOne`-estrategia
8606 // one-cohort spec whose peer `:estrategia`↔`:children.is_empty()`
8607 // partition, `:max-restarts` zero-floor/cap, and `:restart-window`
8608 // bracket all pass cleanly so the sole failing surface is the
8609 // per-child cascade [`SupervisorSpec::validate_children`] owns, and
8610 // pins the two-altitude equivalence on the paired probe.
8611 fn assert_validate_children_matches_gate(children: Vec<ChildSpec>, expected: &SupervisorError) {
8612 let s = SupervisorSpec {
8613 estrategia: RestartStrategy::OneForOne,
8614 children,
8615 ..SupervisorSpec::default()
8616 };
8617 let via_gate = s.validate_children().unwrap_err();
8618 let via_validate = s.validate().unwrap_err();
8619 assert_eq!(&via_gate, expected, "validate_children direct dispatch",);
8620 assert_eq!(&via_validate, expected, "validate() end-to-end dispatch",);
8621 assert_eq!(
8622 via_gate, via_validate,
8623 "per-slot gate ≡ validate() must discriminate the same \
8624 refusal shape",
8625 );
8626 }
8627
8628 #[test]
8629 fn validate_children_matches_gate_on_per_axis_refusal_shapes() {
8630 // Fail-before-pass-after equivalence pin on the M2
8631 // per-`:children` per-slot gate ≡ [`SupervisorSpec::validate`]
8632 // convergence — sibling of the M3 mesh-slot
8633 // `validate_membros_*` / `validate_contratos_*` /
8634 // `validate_entrada_*` per-slot-gate ≡ `validate` pins on the
8635 // peer per-entry axes. Sweeps four of the five refusal shapes
8636 // the per-slot gate owns: (1) `EmptyChildName` on an empty-
8637 // `:caixa` child, (2) `ChildCaixaInvalid` on a structurally
8638 // invalid `:caixa` DNS-1123 label, (3) `EmptyChildVersion` on
8639 // an empty-`:versao` child, (4) `DuplicateChildCaixa` on a
8640 // duplicate-`:caixa` fan-out. Companion pin
8641 // `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
8642 // covers `ChildVersaoInvalid` (whose parser-owned reason string
8643 // needs pattern-matching, not equality) and the clean-pass
8644 // canonical fixture; together the two pins guarantee the
8645 // per-slot gate and `validate` discriminate the same set on
8646 // every per-child-covered input.
8647 assert_validate_children_matches_gate(
8648 vec![child("", "^0.1", RestartPolicy::Permanent)],
8649 &SupervisorError::EmptyChildName,
8650 );
8651 assert_validate_children_matches_gate(
8652 vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
8653 &SupervisorError::ChildCaixaInvalid {
8654 caixa: "Worker".into(),
8655 reason: "contains uppercase character 'W' (K8s DNS-1123 label names are lowercase-only; use \"worker\")".into(),
8656 },
8657 );
8658 assert_validate_children_matches_gate(
8659 vec![child("worker", "", RestartPolicy::Permanent)],
8660 &SupervisorError::EmptyChildVersion {
8661 caixa: "worker".into(),
8662 },
8663 );
8664 assert_validate_children_matches_gate(
8665 vec![
8666 child("worker", "^0.1", RestartPolicy::Permanent),
8667 child("worker", "^0.2", RestartPolicy::Transient),
8668 ],
8669 &SupervisorError::DuplicateChildCaixa {
8670 caixa: "worker".into(),
8671 },
8672 );
8673 }
8674
8675 #[test]
8676 fn validate_children_matches_gate_on_versao_invalid_and_clean_pass() {
8677 // Second half of the two-altitude equivalence pin — covers the
8678 // one refusal shape whose reason string is parser-owned
8679 // (`ChildVersaoInvalid`, whose reason comes from the shared
8680 // [`crate::version::parse_requirement`] impl and may drift) and
8681 // the clean-pass canonical fixture. Sibling pin
8682 // `validate_children_matches_gate_on_per_axis_refusal_shapes`
8683 // covers the four equality-comparable refusal shapes.
8684 let s_bad_versao = SupervisorSpec {
8685 estrategia: RestartStrategy::OneForOne,
8686 children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
8687 ..SupervisorSpec::default()
8688 };
8689 let via_gate = s_bad_versao.validate_children().unwrap_err();
8690 let via_validate = s_bad_versao.validate().unwrap_err();
8691 match (&via_gate, &via_validate) {
8692 (
8693 SupervisorError::ChildVersaoInvalid {
8694 caixa: cg,
8695 versao: vg,
8696 ..
8697 },
8698 SupervisorError::ChildVersaoInvalid {
8699 caixa: cv,
8700 versao: vv,
8701 ..
8702 },
8703 ) => {
8704 assert_eq!(cg, "worker", "per-slot gate :caixa carrier");
8705 assert_eq!(vg, "not-a-req", "per-slot gate :versao carrier");
8706 assert_eq!(cv, "worker", "validate() :caixa carrier");
8707 assert_eq!(vv, "not-a-req", "validate() :versao carrier");
8708 }
8709 other => panic!("expected ChildVersaoInvalid on both altitudes, got {other:?}"),
8710 }
8711 assert_eq!(
8712 via_gate, via_validate,
8713 "per-slot gate ≡ validate() on ChildVersaoInvalid full envelope",
8714 );
8715
8716 let s_ok = SupervisorSpec {
8717 estrategia: RestartStrategy::OneForOne,
8718 children: vec![
8719 child("worker-a", "^0.1", RestartPolicy::Permanent),
8720 child("worker-b", "~0.2.3", RestartPolicy::Transient),
8721 child("collector", "*", RestartPolicy::Temporary),
8722 ],
8723 ..SupervisorSpec::default()
8724 };
8725 s_ok.validate_children()
8726 .expect("per-slot gate must accept the clean-pass fixture");
8727 s_ok.validate()
8728 .expect("validate() must accept the clean-pass fixture");
8729 }
8730
8731 #[test]
8732 fn validate_children_is_self_contained_on_children_slot() {
8733 // Self-containment pin: [`SupervisorSpec::validate_children`]
8734 // resolves the per-child cascade against `&self` alone, without
8735 // depending on the peer `:estrategia`/`:max-restarts`/
8736 // `:restart-window` gates having run first — same posture the M3
8737 // peer per-slot gates carry (`validate_membros`,
8738 // `validate_contratos`, `validate_entrada`, `validate_placement`,
8739 // routing through their own oracles rather than borrowing state
8740 // threaded down from `validate`). A future consumer that reaches
8741 // the per-slot gate directly on a spec whose peer slots would
8742 // fail `validate` still surfaces the per-child refusal, not the
8743 // peer refusal.
8744 //
8745 // Construct a spec whose `:max-restarts` is `0` (which would
8746 // trip [`SupervisorError::ZeroMaxRestarts`] at `validate` after
8747 // the partition-dispatch) and whose `:children` carries a
8748 // `DuplicateChildCaixa` shape: the per-slot gate called directly
8749 // must surface `DuplicateChildCaixa`, proving it does not depend
8750 // on the peer `:max-restarts` gate running first.
8751 let s = SupervisorSpec {
8752 estrategia: RestartStrategy::OneForOne,
8753 max_restarts: 0,
8754 restart_window: Some(Duration::from_secs(60)),
8755 children: vec![
8756 child("worker", "^0.1", RestartPolicy::Permanent),
8757 child("worker", "^0.2", RestartPolicy::Transient),
8758 ],
8759 };
8760 assert_eq!(
8761 s.validate_children().unwrap_err(),
8762 SupervisorError::DuplicateChildCaixa {
8763 caixa: "worker".into(),
8764 },
8765 "per-slot gate must resolve per-child refusal directly against \
8766 `&self` — a dependency on the peer `:max-restarts` gate \
8767 running first would surface ZeroMaxRestarts here instead",
8768 );
8769 // The peer gate is still the surface `validate` reaches — pin
8770 // the ordering to establish that `validate_children` truly runs
8771 // last in `validate`'s dispatch, so a direct call bypasses the
8772 // peer gates on any spec whose per-child cascade would fail.
8773 assert_eq!(
8774 s.validate().unwrap_err(),
8775 SupervisorError::ZeroMaxRestarts,
8776 "validate() must surface the peer `:max-restarts` gate before \
8777 reaching the per-child cascade — this pins the dispatch \
8778 ordering the per-slot gate's self-containment complements",
8779 );
8780 }
8781
8782 #[test]
8783 fn child_spec_restart_accessor_is_const_fn() {
8784 // The [`ChildSpec::restart`] per-`:children` restart-decision-
8785 // policy `Copy`-return scalar accessor is declared
8786 // `#[must_use] pub const fn` — matching the sibling M2
8787 // per-`:supervisor` [`SupervisorSpec::estrategia`] (pinned by
8788 // [`supervisor_spec_estrategia_accessor_is_const_fn`] below,
8789 // both converted in this commit), the sibling M2
8790 // per-`:supervisor` [`SupervisorSpec::max_restarts`] (b698ec0)
8791 // `Copy`-`u32` accessor already `pub const fn`, and the peer M3
8792 // mesh-slot per-`:entrada` [`crate::Entrada::port`] (bafa004) /
8793 // per-`:placement` [`crate::Placement::estrategia`] (bafa004)
8794 // `Copy`-return `pub const fn` scalar accessors on the sibling
8795 // M3 surface. Pin the `const`-eval posture here so a future
8796 // accidental downgrade to non-`const` (an added runtime helper
8797 // reachable only from a non-`const` context, an
8798 // `Option<RestartPolicy>`-shape migration on the per-child
8799 // restart-decision axis once heterogeneous per-cluster
8800 // restart-policy overlays land that would silently drop the
8801 // `const` qualifier, a manual hand-rolled shadow) trips at
8802 // caixa-core build time rather than surfacing as a downstream
8803 // `const`-context regression far from the declaration.
8804 //
8805 // Same shape as the sibling M3
8806 // [`crate::aplicacao::tests::placement_estrategia_accessor_is_const_fn`]
8807 // and [`crate::aplicacao::tests::entrada_port_accessor_is_const_fn`]
8808 // (bafa004) pins on the peer M3 mesh-slot `Copy`-return scalar
8809 // accessor axis — the load-bearing witness lives in the
8810 // module-scope `const fn` wrapper `restart_via_const_fn` below:
8811 // a body that calls [`ChildSpec::restart`] under a `const fn`
8812 // signature is well-formed only when the callee is itself
8813 // `const fn`, so any future accidental downgrade of
8814 // [`ChildSpec::restart`] to non-`const` fails at caixa-core
8815 // build time (const-eval E0015 `cannot call non-const method`),
8816 // strictly stronger than a runtime `assert!(CONST)` and
8817 // side-stepping the destructor-in-const restriction that
8818 // blocks direct `const _: RestartPolicy = FIXTURE.restart()`
8819 // items on `ChildSpec`'s `String` carriers.
8820 //
8821 // The runtime body sweeps every closed-set [`RestartPolicy`]
8822 // arm and asserts the wrapped and direct dispatches agree.
8823 const fn restart_via_const_fn(c: &ChildSpec) -> RestartPolicy {
8824 c.restart()
8825 }
8826 for restart in [
8827 RestartPolicy::Permanent,
8828 RestartPolicy::Transient,
8829 RestartPolicy::Temporary,
8830 ] {
8831 let c = ChildSpec {
8832 caixa: "worker".into(),
8833 versao: "^0.1".into(),
8834 restart,
8835 };
8836 assert_eq!(
8837 restart_via_const_fn(&c),
8838 c.restart(),
8839 "const-fn-wrapped and direct dispatch on \
8840 ChildSpec::restart must agree for {restart:?}",
8841 );
8842 assert_eq!(
8843 c.restart(),
8844 restart,
8845 "ChildSpec::restart must return the storage-side \
8846 RestartPolicy verbatim for {restart:?} (a violation \
8847 means the accessor stopped being a raw field-return \
8848 copy)",
8849 );
8850 }
8851 }
8852
8853 #[test]
8854 fn supervisor_spec_estrategia_accessor_is_const_fn() {
8855 // The [`SupervisorSpec::estrategia`] per-`:supervisor`
8856 // sibling-restart-strategy `Copy`-return scalar accessor is
8857 // declared `#[must_use] pub const fn` — matching the sibling M2
8858 // per-`:children` [`ChildSpec::restart`] (pinned by
8859 // [`child_spec_restart_accessor_is_const_fn`] above, both
8860 // converted in this commit), the sibling M2 per-`:supervisor`
8861 // [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32`
8862 // accessor already `pub const fn`, and mirroring the peer M3
8863 // mesh-slot per-`:placement`
8864 // [`crate::Placement::estrategia`] (bafa004) `Copy`-return
8865 // `pub const fn` scalar accessor whose method-name discipline
8866 // the [`SupervisorSpec::estrategia`] method was authored to
8867 // match. Pin the `const`-eval posture here so a future
8868 // accidental downgrade to non-`const` (an added runtime helper
8869 // reachable only from a non-`const` context, an
8870 // `Option<RestartStrategy>`-shape migration once the substrate
8871 // grows per-cluster strategy overlays that would silently drop
8872 // the `const` qualifier, a manual hand-rolled shadow) trips at
8873 // caixa-core build time rather than surfacing as a downstream
8874 // `const`-context regression far from the declaration.
8875 //
8876 // Same shape as the sibling
8877 // [`child_spec_restart_accessor_is_const_fn`] pin above — the
8878 // load-bearing witness lives in the module-scope `const fn`
8879 // wrapper `estrategia_via_const_fn` below: a body that calls
8880 // [`SupervisorSpec::estrategia`] under a `const fn` signature
8881 // is well-formed only when the callee is itself `const fn`,
8882 // side-stepping the destructor-in-const restriction that would
8883 // otherwise block a direct
8884 // `const _: RestartStrategy = FIXTURE.estrategia()` item on
8885 // `SupervisorSpec`'s `Vec<ChildSpec>` / `Option<Duration>`
8886 // carriers.
8887 //
8888 // The runtime body sweeps every closed-set [`RestartStrategy`]
8889 // arm via [`RestartStrategy::ALL`] and asserts the wrapped and
8890 // direct dispatches agree.
8891 const fn estrategia_via_const_fn(s: &SupervisorSpec) -> RestartStrategy {
8892 s.estrategia()
8893 }
8894 for &estrategia in RestartStrategy::ALL {
8895 let s = SupervisorSpec {
8896 estrategia,
8897 max_restarts: 5,
8898 restart_window: Some(Duration::from_secs(60)),
8899 children: Vec::new(),
8900 };
8901 assert_eq!(
8902 estrategia_via_const_fn(&s),
8903 s.estrategia(),
8904 "const-fn-wrapped and direct dispatch on \
8905 SupervisorSpec::estrategia must agree for {estrategia:?}",
8906 );
8907 assert_eq!(
8908 s.estrategia(),
8909 estrategia,
8910 "SupervisorSpec::estrategia must return the storage-side \
8911 RestartStrategy verbatim for {estrategia:?} (a violation \
8912 means the accessor stopped being a raw field-return \
8913 copy)",
8914 );
8915 }
8916 }
8917
8918 // Per-variant equivalence pins for the [`supervisor_caixa_only_ctors!`]
8919 // macro definition (see the paired doc-block above the macro
8920 // definition) — every generated `<ctor>(caixa: &str) -> Self`
8921 // constructor folds the uniform `Self::<Variant> { caixa:
8922 // caixa.to_string() }` one-field struct-literal onto one substrate
8923 // primitive. The three per-variant equivalence pins below
8924 // (fail-before-pass-after by construction — a byte-mismatched macro
8925 // arm would trip its equivalence pin first) lock each generated
8926 // constructor to its struct-literal peer under `PartialEq`, so
8927 // every wire-up in [`SupervisorSpec::validate_children`] and
8928 // [`validate_no_self_supervision`] on that variant produces a
8929 // byte-equal `SupervisorError` to the pre-lift open-coded
8930 // struct-literal. The cross-axis pin that follows (non-default
8931 // caixa name) routes the sole constructor input axis through
8932 // `.to_string()`, so the fold does not silently collapse onto a
8933 // fixed name.
8934 //
8935 // Peer of the sibling `<slot>_ctor_matches_tuple_literal_wrap` /
8936 // `<slot>_violation_ctor_matches_struct_literal_wrap` /
8937 // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
8938 // `missing_entry_ctor_matches_struct_literal_wrap` /
8939 // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
8940 // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
8941 // `contrato_missing_target_ctor_matches_struct_literal_wrap` /
8942 // `<variant>_ctor_matches_struct_literal_wrap` equivalence pins
8943 // on the six sibling ctor families the recent trajectory closed
8944 // on the peer `LayoutError` / `AplicacaoError` envelopes.
8945
8946 #[test]
8947 fn empty_child_version_ctor_matches_struct_literal_wrap() {
8948 assert_eq!(
8949 SupervisorError::empty_child_version("worker"),
8950 SupervisorError::EmptyChildVersion {
8951 caixa: "worker".to_string(),
8952 },
8953 "generated empty_child_version ctor must produce byte-equal \
8954 SupervisorError to the open-coded struct-literal wrap on the \
8955 same &str fixture",
8956 );
8957 }
8958
8959 #[test]
8960 fn duplicate_child_caixa_ctor_matches_struct_literal_wrap() {
8961 assert_eq!(
8962 SupervisorError::duplicate_child_caixa("worker"),
8963 SupervisorError::DuplicateChildCaixa {
8964 caixa: "worker".to_string(),
8965 },
8966 "generated duplicate_child_caixa ctor must produce byte-equal \
8967 SupervisorError to the open-coded struct-literal wrap on the \
8968 same &str fixture",
8969 );
8970 }
8971
8972 #[test]
8973 fn child_supervises_self_ctor_matches_struct_literal_wrap() {
8974 assert_eq!(
8975 SupervisorError::child_supervises_self("orquestra"),
8976 SupervisorError::ChildSupervisesSelf {
8977 caixa: "orquestra".to_string(),
8978 },
8979 "generated child_supervises_self ctor must produce byte-equal \
8980 SupervisorError to the open-coded struct-literal wrap on the \
8981 same &str fixture",
8982 );
8983 }
8984
8985 // Per-variant equivalence pins for the two lifted
8986 // [`SupervisorError::child_caixa_invalid`] /
8987 // [`SupervisorError::child_versao_invalid`] inherent constructors
8988 // (fail-before-pass-after by construction — a byte-mismatched ctor body
8989 // would trip its equivalence pin first). Each pins the ctor output to
8990 // its pre-lift struct-literal peer under `PartialEq`, so every wire-up
8991 // in [`SupervisorSpec::validate_children`] on the two variants
8992 // produces a byte-equal `SupervisorError` to the pre-lift open-coded
8993 // struct-literal on the same scalar fixtures. Peers of the sibling
8994 // `membro_caixa_invalid_ctor_matches_struct_literal_wrap` /
8995 // `entrada_para_invalid_ctor_matches_struct_literal_wrap` / … pins on
8996 // the peer `AplicacaoError` envelope's
8997 // [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold.
8998
8999 #[test]
9000 fn child_caixa_invalid_ctor_matches_struct_literal_wrap() {
9001 let caixa = "Worker";
9002 let reason = "sample reason text";
9003 assert_eq!(
9004 SupervisorError::child_caixa_invalid(caixa, reason),
9005 SupervisorError::ChildCaixaInvalid {
9006 caixa: caixa.to_string(),
9007 reason: reason.to_string(),
9008 },
9009 "lifted child_caixa_invalid ctor must produce byte-equal \
9010 SupervisorError to the open-coded struct-literal wrap on the \
9011 same (&str, reason) fixture",
9012 );
9013 }
9014
9015 #[test]
9016 fn child_versao_invalid_ctor_matches_struct_literal_wrap() {
9017 let caixa = "worker";
9018 let versao = "not-a-req";
9019 let reason = "sample reason text";
9020 assert_eq!(
9021 SupervisorError::child_versao_invalid(caixa, versao, reason),
9022 SupervisorError::ChildVersaoInvalid {
9023 caixa: caixa.to_string(),
9024 versao: versao.to_string(),
9025 reason: reason.to_string(),
9026 },
9027 "lifted child_versao_invalid ctor must produce byte-equal \
9028 SupervisorError to the open-coded struct-literal wrap on the \
9029 same (&str, &str, reason) fixture",
9030 );
9031 }
9032
9033 #[test]
9034 fn supervisor_child_reason_ctors_route_reason_through_into_uniformly() {
9035 // Cross-axis pin: sweep the two lifted `{ …, reason }` ctors
9036 // against a `&str`-literal vs. `format!(…)` reason input to pin
9037 // both constructors accept the `impl Into<String>` bound
9038 // uniformly, so neither wire-up site drifts under a per-arm
9039 // wrapper transformation on the caller-side `reason` axis. Peer
9040 // of the sibling
9041 // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
9042 // sweep on the peer `AplicacaoError` envelope.
9043 let via_literal = "literal reason text";
9044 let via_format = format!("{} reason text", "literal");
9045 assert_eq!(
9046 SupervisorError::child_caixa_invalid("Worker", via_literal),
9047 SupervisorError::child_caixa_invalid("Worker", via_format.clone()),
9048 );
9049 assert_eq!(
9050 SupervisorError::child_versao_invalid("worker", "not-a-req", via_literal),
9051 SupervisorError::child_versao_invalid("worker", "not-a-req", via_format),
9052 );
9053 }
9054
9055 #[test]
9056 fn supervisor_caixa_only_ctors_route_caixa_through_to_string() {
9057 // Cross-axis pin: sweep the sole constructor input axis (`caixa:
9058 // &str`) through a non-default fixture name against every
9059 // generated arm in the [`supervisor_caixa_only_ctors!`] macro,
9060 // so any wrapper-side lowercase / trim / truncate / re-order on
9061 // the `caixa.to_string()` sole-field construction surfaces
9062 // here rather than at a downstream diagnostic-shape mismatch.
9063 // Peer of the sibling `nome_only_ctor_routes_caixa_through_
9064 // nome_accessor` / `entrada_host_invalid_ctor_routes_host_
9065 // through_to_string` / `contrato_target_ctors_route_edge_
9066 // triple_through_verbatim` / `contrato_empty_pair_ctors_
9067 // route_edge_pair_through_verbatim` cross-axis routing pins on
9068 // the peer `LayoutError` / `AplicacaoError` envelopes; extended
9069 // here onto the `SupervisorError` `{ caixa: String }` envelope
9070 // so every substrate-primitive ctor family in caixa-core
9071 // guarantees the sole-field construction routes the caller's
9072 // `&str` through `.to_string()` verbatim.
9073 let name = "cache-v2";
9074 assert_eq!(
9075 SupervisorError::empty_child_version(name),
9076 SupervisorError::EmptyChildVersion {
9077 caixa: name.to_string(),
9078 },
9079 );
9080 assert_eq!(
9081 SupervisorError::duplicate_child_caixa(name),
9082 SupervisorError::DuplicateChildCaixa {
9083 caixa: name.to_string(),
9084 },
9085 );
9086 assert_eq!(
9087 SupervisorError::child_supervises_self(name),
9088 SupervisorError::ChildSupervisesSelf {
9089 caixa: name.to_string(),
9090 },
9091 );
9092 }
9093
9094 // ── supervisor_scalar_ctors! per-variant + cross-axis pins ──────────────
9095 //
9096 // Per-variant byte-equality pins guaranteeing every generated ctor arm in
9097 // the [`supervisor_scalar_ctors!`] macro produces a `SupervisorError`
9098 // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
9099 // one-line struct-literal on the same `Copy`-`RestartStrategy | u32 |
9100 // Duration` fixture, plus one cross-axis sweep that routes each per-variant
9101 // `<field>: <ty>` scalar through the sole `$field:ident: $ty:ty` axis the
9102 // macro exposes so any wrapper-side truncation / re-order / silent `.into()`
9103 // / silent constant-substitution on any one variant surfaces here rather
9104 // than at a downstream per-`:supervisor` diagnostic-shape drift. Peer of the
9105 // sibling per-variant pins on `aplicacao_policy_scalar_ctors!` (7ef425e,
9106 // the 8-variant `AplicacaoError` `{ <field>: Duration | u32 }` fold on the
9107 // per-`:politicas` per-axis cap / canonical-form arms), plus the sibling
9108 // `supervisor_caixa_only_ctors!` (db09650), `SupervisorError::
9109 // {child_caixa_invalid,child_versao_invalid}` (d2ef2ec), and the peer
9110 // `DepError` / `AplicacaoError` / `LayoutError` / `LimitsError` /
9111 // `BehaviorError` / `UpgradeError` per-envelope ctor-macro pins.
9112 #[test]
9113 fn no_children_ctor_matches_struct_literal_wrap() {
9114 let estrategia = RestartStrategy::OneForAll;
9115 assert_eq!(
9116 SupervisorError::no_children(estrategia),
9117 SupervisorError::NoChildren { estrategia },
9118 "generated no_children ctor must produce byte-equal \
9119 `SupervisorError::NoChildren` to the pre-lift struct-literal wrap \
9120 on the same `Copy`-`RestartStrategy` fixture",
9121 );
9122 }
9123
9124 #[test]
9125 fn max_restarts_exceeds_cap_ctor_matches_struct_literal_wrap() {
9126 let max_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 1;
9127 assert_eq!(
9128 SupervisorError::max_restarts_exceeds_cap(max_restarts),
9129 SupervisorError::MaxRestartsExceedsCap { max_restarts },
9130 "generated max_restarts_exceeds_cap ctor must produce byte-equal \
9131 `SupervisorError::MaxRestartsExceedsCap` to the pre-lift \
9132 struct-literal wrap on the same `Copy`-`u32` fixture",
9133 );
9134 }
9135
9136 #[test]
9137 fn restart_window_not_canonical_ctor_matches_struct_literal_wrap() {
9138 let window = Duration::from_micros(1_500);
9139 assert_eq!(
9140 SupervisorError::restart_window_not_canonical(window),
9141 SupervisorError::RestartWindowNotCanonical { window },
9142 "generated restart_window_not_canonical ctor must produce \
9143 byte-equal `SupervisorError::RestartWindowNotCanonical` to the \
9144 pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
9145 );
9146 }
9147
9148 #[test]
9149 fn restart_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
9150 let window = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
9151 assert_eq!(
9152 SupervisorError::restart_window_exceeds_cap(window),
9153 SupervisorError::RestartWindowExceedsCap { window },
9154 "generated restart_window_exceeds_cap ctor must produce \
9155 byte-equal `SupervisorError::RestartWindowExceedsCap` to the \
9156 pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
9157 );
9158 }
9159
9160 #[test]
9161 fn supervisor_scalar_ctors_route_field_through_copy_uniformly() {
9162 // Cross-axis routing pin: sweep each generated `<field>: <ty>`
9163 // constructor input axis through a non-default `Copy` fixture against
9164 // every arm in the [`supervisor_scalar_ctors!`] macro, so any wrapper-
9165 // side silent `.into()` / silent constant-substitution / silent field
9166 // re-name away from the canonical `estrategia | max_restarts | window`
9167 // axes on any one variant, or a `RestartStrategy | u32 | Duration`
9168 // axis silently rerouted through some other `Copy` coercion, surfaces
9169 // here rather than at a downstream per-`:supervisor` diagnostic-shape
9170 // drift. Peer of the sibling
9171 // `aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly`
9172 // (7ef425e) cross-axis routing pin on the peer `AplicacaoError`
9173 // envelope's per-`:politicas` per-axis ctor family, extended here onto
9174 // the last M2 per-`:supervisor` `Copy`-scalar `SupervisorError`
9175 // variant family folded onto a substrate primitive.
9176 //
9177 // Fixtures picked out of each variant's accept-set boundary rather
9178 // than the default value so a silent constant-substitution to a per-
9179 // variant sentinel surfaces here on the structural-equality assertion.
9180 // The `RestartStrategy` fixture picks `RestForOne` (a non-default arm
9181 // that isn't the `OneForOne` [`SUPERVISOR_ESTRATEGIA_DEFAULT`] and
9182 // isn't the `SimpleOneForOne` arm the sibling
9183 // `SimpleOneForOneWithStaticChildren` unit variant intercepts). The
9184 // `max_restarts` fixture picks an above-cap magnitude the cap arm
9185 // rejects; the two `Duration` fixtures pick the sub-millisecond and
9186 // above-cap ends of the `:restart-window` canonical-form + cap
9187 // bracket respectively.
9188 let estrategia = RestartStrategy::RestForOne;
9189 let above_cap_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 137;
9190 let sub_ms = Duration::from_micros(1_500);
9191 let above_hour = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
9192 assert_eq!(
9193 SupervisorError::no_children(estrategia),
9194 SupervisorError::NoChildren { estrategia },
9195 );
9196 assert_eq!(
9197 SupervisorError::max_restarts_exceeds_cap(above_cap_restarts),
9198 SupervisorError::MaxRestartsExceedsCap {
9199 max_restarts: above_cap_restarts,
9200 },
9201 );
9202 assert_eq!(
9203 SupervisorError::restart_window_not_canonical(sub_ms),
9204 SupervisorError::RestartWindowNotCanonical { window: sub_ms },
9205 );
9206 assert_eq!(
9207 SupervisorError::restart_window_exceeds_cap(above_hour),
9208 SupervisorError::RestartWindowExceedsCap { window: above_hour },
9209 );
9210 }
9211
9212 #[test]
9213 fn supervisor_scalar_ctors_are_const_zero_runtime_work() {
9214 // Const-eval pin: the [`supervisor_scalar_ctors!`] macro spells every
9215 // generated ctor `const fn` so a caller can pin a `SupervisorError`
9216 // at compile time — the same zero-runtime-work property the pre-lift
9217 // `|<slot>| SupervisorError::<Variant> { <slot> }` closure carried on
9218 // its `Copy`-pass-through construction path (no `.to_string()` /
9219 // `.into()` allocation, no branching). If any future edit silently
9220 // drops the `const` qualifier from the macro body the per-arm `const`
9221 // bindings below fail to compile, which surfaces the regression at
9222 // the substrate-primitive definition rather than at some downstream
9223 // consumer that had come to rely on the `const`-constructibility.
9224 // Peer of the sibling
9225 // `aplicacao_policy_scalar_ctors_are_const_zero_runtime_work`
9226 // (7ef425e) const-eval pin on the peer `AplicacaoError` envelope's
9227 // per-`:politicas` per-axis ctor family.
9228 const NO_CHILDREN: SupervisorError =
9229 SupervisorError::no_children(RestartStrategy::OneForAll);
9230 const MAX_RESTARTS_CAP: SupervisorError = SupervisorError::max_restarts_exceeds_cap(1_337);
9231 const WINDOW_NC: SupervisorError =
9232 SupervisorError::restart_window_not_canonical(Duration::from_micros(1));
9233 const WINDOW_CAP: SupervisorError =
9234 SupervisorError::restart_window_exceeds_cap(Duration::from_secs(3_601));
9235 assert!(matches!(NO_CHILDREN, SupervisorError::NoChildren { .. }));
9236 assert!(matches!(
9237 MAX_RESTARTS_CAP,
9238 SupervisorError::MaxRestartsExceedsCap { .. }
9239 ));
9240 assert!(matches!(
9241 WINDOW_NC,
9242 SupervisorError::RestartWindowNotCanonical { .. }
9243 ));
9244 assert!(matches!(
9245 WINDOW_CAP,
9246 SupervisorError::RestartWindowExceedsCap { .. }
9247 ));
9248 }
9249}