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 /// Substrate-canonical exhaustive accept-set on the
113 /// [`RestartStrategy`] `PascalCase` wire byte-string axis — the
114 /// closed four-arm roster of every byte-string [`Self::as_str`]
115 /// returns, routed byte-for-byte through the paired
116 /// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
117 /// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
118 /// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
119 /// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
120 /// lifted `pub const` roster the [`Self::as_str`] emitter (and the
121 /// [`std::fmt::Display`] / [`AsRef<str>`] /
122 /// `From<{Self,&Self}> for {&'static str, String, Cow<'static, str>,
123 /// Box<str>, Arc<str>}` trait triple + quintuple routed through it)
124 /// walks — and byte-for-byte the same four strings the un-`rename`d
125 /// `Serialize` derive emits under the paired
126 /// [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] tag key on every
127 /// JSON / YAML CR round-trip.
128 ///
129 /// Peer of the sibling [`crate::CaixaKind::WIRE_NAMES`] (bd708bd)
130 /// roster on the top-level typed-kind discriminator's `PascalCase`
131 /// wire byte-string axis, and of the sibling
132 /// [`crate::upgrade::UpgradeInstruction::WIRE_FORMS`] (cc42c0e) /
133 /// [`crate::upgrade::UpgradeInstruction::LISP_FORMS`] (1898d77)
134 /// rosters on the OTP-appup discriminator's two-axis roster split —
135 /// the same closed-set exhaustive-accept-set roster discipline
136 /// extended here onto the first M2 OTP-shape sibling-restart
137 /// closed-set typed enum. The sibling
138 /// [`crate::aplicacao::PlacementStrategy`] M3 mesh-shape distribution
139 /// strategy enum is the next natural peer on the same axis, still
140 /// carrying only [`crate::aplicacao::PlacementStrategy::ALL`].
141 ///
142 /// Downstream consumers of the closed accepted-wire-form set — a
143 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook
144 /// rejection body enumerating the accepted JSON `:estrategia` values
145 /// verbatim (as distinct from the kebab-case dispatcher-catalog
146 /// enumeration [`Self::discriminant`] serves, whose per-arm form
147 /// `"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
148 /// `"simple-one-for-one"` structurally disagrees with the wire byte-
149 /// string these `PascalCase` entries carry), a future `feira
150 /// supervisor --estrategia …` CLI-side "did you mean" hint whose
151 /// candidate-list must byte-match the wire form the operator's
152 /// per-strategy dispatch keys off (rather than the kebab
153 /// dispatcher-catalog identity), a future `feira app graph`
154 /// per-supervisor `:estrategia`-histogram column that renders
155 /// zero-count arms, a future wasm-operator per-reconcile-step
156 /// diagnostic log line enumerating accepted wire forms on an
157 /// unknown-strategy rejection, a future
158 /// `tracing::field::valuable::Value::List` structured-log accepted-
159 /// wire-form emit — now reach for one lifted substrate-primitive
160 /// roster rather than open-coding a four-string array-literal
161 /// (`["OneForOne", "OneForAll", "RestForOne", "SimpleOneForOne"]`)
162 /// whose arm-set has no compile-time link back to the typed
163 /// [`RestartStrategy`] enum. A future arm addition (an OTP-`rest_for_all`
164 /// arm the theory
165 /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
166 /// might reach for once the four canonical OTP strategies stop
167 /// covering the substrate's discovered load-shape) extends this
168 /// roster as a single edit — paired with the [`Self::as_str`]
169 /// match's compiler-checked exhaustiveness on the new arm — and
170 /// every consumer picks up the new wire form by construction rather
171 /// than a coordinated array-literal rewrite across every downstream
172 /// site.
173 ///
174 /// Length is pinned load-bearing at `RestartStrategy::ALL.len()`
175 /// (four) by
176 /// [`tests::restart_strategy_wire_names_covers_every_arm`], every
177 /// variant's [`Self::as_str`] projection is pinned to a member of
178 /// the roster so a silent skew between the emitter's arm-set and
179 /// this const's arm-set trips at caixa-core test time rather than
180 /// at a downstream consumer's accepted-set enumeration miss, and
181 /// every entry is further pinned to open with an ASCII uppercase
182 /// byte so a silent collapse of the wire-form axis with the peer
183 /// kebab-case dispatcher-catalog axis (an entry byte-identical to a
184 /// sibling [`Self::discriminant`] kebab byte-string that would let
185 /// a wire-axis consumer accept the dispatcher-catalog vocabulary)
186 /// trips here rather than at a downstream K8s-CR round-trip miss.
187 pub const WIRE_NAMES: &'static [&'static str] = &[
188 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
189 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
190 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
191 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
192 ];
193
194 /// Canonical PascalCase discriminator scalar this variant serializes
195 /// as under [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`]. The four arms
196 /// return the paired [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`]
197 /// / [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
198 /// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
199 /// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] lifted
200 /// constants so every substrate consumer that dispatches on the
201 /// per-supervisor sibling-restart strategy (the future
202 /// wasm-operator's per-supervisor sibling-restart branch, the future
203 /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
204 /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
205 /// reconciliation scheduler's per-strategy fan-out) reads the same
206 /// byte-string the `Serialize` derive emits — the pin test in
207 /// [`tests::restart_strategy_variants_serialize_to_lifted_scalar_values`]
208 /// asserts the two paths agree, peer of the M3
209 /// `PlacementStrategy::as_str` (cc8f749) on the sibling per-Aplicacao
210 /// distribution-strategy axis.
211 #[must_use]
212 pub const fn as_str(self) -> &'static str {
213 match self {
214 Self::OneForOne => crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
215 Self::OneForAll => crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
216 Self::RestForOne => crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
217 Self::SimpleOneForOne => crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
218 }
219 }
220
221 /// Substrate-canonical reverse projection on the `:supervisor
222 /// :estrategia` closed-set axis — parses the `PascalCase`
223 /// discriminator scalar back to the typed variant, or `None` when
224 /// `s` is outside
225 /// the closed-set arm-string set [`Self::as_str`] emits. Dispatches
226 /// on the same lifted
227 /// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
228 /// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
229 /// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
230 /// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
231 /// constants the [`Self::as_str`] emitter walks, so the parse and
232 /// emit halves of the round-trip migrate through one caixa-core
233 /// edit on any future arm addition.
234 ///
235 /// Prior to this lift the substrate carried only the forward
236 /// `Self → &str` projection on the OTP sibling-restart axis (the
237 /// [`Self::as_str`] emitter, the [`std::fmt::Display`] impl routed
238 /// through it, the `Serialize` derive that emits the same
239 /// byte-string under [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`])
240 /// plus the kebab-case dispatcher-catalog identity via
241 /// [`Self::discriminant`] — every non-serde consumer that wanted to
242 /// parse a wire-form `PascalCase` strategy scalar had to re-inline
243 /// a four-arm `match s { "OneForOne" => …, "OneForAll" => …,
244 /// "RestForOne" => …, "SimpleOneForOne" => …, _ => … }` cascade
245 /// that expressed no compile-time link back to the typed variant's
246 /// canonical lifted constant. A future variant rename or per-arm
247 /// serde-attribute drift would silently split the wire byte-string
248 /// one non-serde consumer parsed from the one the emitter wrote,
249 /// with the failure surfacing at parse time far from the rebrand
250 /// commit.
251 ///
252 /// Distinct axis from the [`std::str::FromStr`] impl the
253 /// [`gen_platform::FromStrKind`] derive already installs on this
254 /// enum by design, not by drift: `FromStr` parses the *kebab-case*
255 /// dispatcher-catalog identity (`"one-for-one"` / `"one-for-all"` /
256 /// `"rest-for-one"` / `"simple-one-for-one"` — the inverse of
257 /// [`Self::discriminant`]), while this method inverts the
258 /// `PascalCase` wire byte-string [`Self::as_str`] emits. The
259 /// two-axis split lets the dispatcher-catalog identity live in
260 /// kebab-case
261 /// (where every peer catalog identifier already lives) without
262 /// forcing a wire-format rename on the tatara-lisp author surface
263 /// (`:estrategia OneForOne`, `PascalCase`) — the same two-axis
264 /// distinction the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
265 /// / [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
266 /// carry on their peer closed-set typed-enum wire round-trips.
267 ///
268 /// Same closed-set-reverse-projection discipline the sibling
269 /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
270 /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
271 /// [`crate::aplicacao::RateLimitUnit::from_suffix`] typed enums
272 /// carry on the peer wire-side `str → Self` axes — extended onto
273 /// the M2 OTP-shape sibling-restart-strategy closed-set axis, the
274 /// fifth substrate-side closed-set typed enum to converge on the
275 /// two-way `str ↔ Self` round-trip. Method-named `from_wire` (not
276 /// `from_str`) to match the peer [`crate::CaixaKind::from_wire`]
277 /// shape verbatim and side-step the [`std::str::FromStr`] impl the
278 /// derive already installs on the sibling kebab-case axis. Returns
279 /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
280 /// shapes: the caller picks the diagnostic form appropriate for
281 /// its use site.
282 #[must_use]
283 pub fn from_wire(s: &str) -> Option<Self> {
284 match s {
285 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE => Some(Self::OneForOne),
286 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL => Some(Self::OneForAll),
287 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE => Some(Self::RestForOne),
288 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE => Some(Self::SimpleOneForOne),
289 _ => None,
290 }
291 }
292}
293
294/// [`std::fmt::Display`] routed through [`RestartStrategy::as_str`], so the
295/// pretty-printed byte-string every consumer that formats the strategy as
296/// user-facing text lands on (the future wasm-operator's per-supervisor
297/// sibling-restart-strategy diagnostic line, the future `feira app graph`
298/// per-supervisor strategy line, the future M4
299/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission-webhook
300/// rejection body) reaches for the same lifted
301/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
302/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
303/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
304/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const the
305/// wire-format `Serialize` derive already emits under
306/// [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the
307/// [`RestartStrategy::as_str`] helper already returns.
308///
309/// Pre-convergence the two paths structurally disagreed — the
310/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
311/// route (now retired here) sent [`std::fmt::Display`] through the
312/// gen-platform discriminant catalog string, which arrives kebab-case as
313/// `"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
314/// `"simple-one-for-one"`, while the wire format ran as `PascalCase`
315/// `"OneForOne"` / `"OneForAll"` / `"RestForOne"` / `"SimpleOneForOne"`
316/// through the un-`rename`d serde derive. Every consumer that formatted
317/// the strategy for a diagnostic line, a graph, or a rejection body under
318/// `format!("{v}")` therefore landed under a different byte-string than
319/// the wire format the operator's per-strategy dispatch keyed off — a
320/// silent split whose apply-time symptom (a `format!("{v}")`-carrying
321/// diagnostic quoting `"one-for-one"` while the wire scalar the operator
322/// probed was `"OneForOne"`) surfaced as a confused correlate at
323/// operator-log time far from the two-declaration site.
324///
325/// Routing `Display` through [`RestartStrategy::as_str`] closes the third
326/// path: every `format!("{v}")` call reaches the same lifted
327/// [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const the wire format and
328/// the [`RestartStrategy::as_str`] helper route through — `Debug` (the
329/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
330/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
331/// byte-string per variant. A future variant rename or
332/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
333/// exactly one place, structurally.
334///
335/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
336/// (from `#[derive(gen_platform::Discriminant)]`) still returns
337/// `"one-for-one"` / etc., and the fleet-wide
338/// [`gen_platform::register_dispatcher!("caixa.restart-strategy", …)`]
339/// registration keys the catalog off the same kebab identity. The two
340/// naming worlds now live on separate typed methods (`Display` /
341/// `as_str` for the wire byte-string, `discriminant` for the catalog
342/// identity) rather than sharing one `Display` route that structurally
343/// disagrees with the wire format.
344///
345/// Pin tests
346/// [`tests::restart_strategy_display_routes_through_as_str_helper`]
347/// and
348/// [`tests::restart_strategy_display_matches_serialized_wire_byte_string`]
349/// assert the three paths agree byte-for-byte on every variant, so a
350/// future variant rename or per-arm serde attribute drift is a build
351/// error visible at caixa-core test time, not a silent per-consumer
352/// dispatch miss at apply / reconcile time.
353///
354/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
355/// (aplicacao.rs:2306) on the sibling per-Aplicacao distribution-strategy
356/// axis — same three-path-convergence discipline, extended to close the
357/// second of three OTP-shaped closed-enum discriminator axes on the
358/// caixa typed surface.
359impl std::fmt::Display for RestartStrategy {
360 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
361 f.write_str(self.as_str())
362 }
363}
364
365/// Substrate-canonical [`AsRef<str>`] projection on the M2
366/// per-supervisor sibling-restart [`RestartStrategy`] closed-set typed
367/// enum — routes through the same [`RestartStrategy::as_str`]
368/// `pub const fn` scalar accessor the paired [`std::fmt::Display`]
369/// impl and the un-`rename`d [`serde::Serialize`] derive already key
370/// off, so any future consumer that binds a [`RestartStrategy`]
371/// through the standard-library `impl AsRef<str>` bound (a future
372/// [`caixa-feira`] `feira supervisor --estrategia <arm>` verb that
373/// composes the emitted `PascalCase` wire scalar into a
374/// [`std::process::Command::arg`] shell-out of the future
375/// wasm-operator's admission gate, a per-supervisor structured-log
376/// recorder on the future `caixa-operator`'s hierarchical
377/// reconciliation surface that accepts `impl AsRef<str>` at the
378/// `tracing::field::Value` `Str`-arm, a [`std::collections::HashMap`]
379/// lookup keyed on the estrategia wire byte through
380/// `map.get::<str>(strategy.as_ref())` on a future per-strategy
381/// dispatch table) reaches the paired [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`]
382/// / [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
383/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
384/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
385/// lifted-const through one substrate-primitive dispatch rather
386/// than an open-coded `.as_str()` projection at every wire-up.
387///
388/// Peer of the sibling [`std::fmt::Display`] impl on the same
389/// primitive — both delegate to the shared
390/// [`RestartStrategy::as_str`] `pub const fn` accessor, so
391/// [`format!("{s}")`], `s.as_str()`, and
392/// `<RestartStrategy as AsRef<str>>::as_ref(&s)` resolve to the same
393/// byte-string per instance by construction. A future variant rename
394/// or `#[serde(rename_all = "kebab-case")]` attribute-drift on the
395/// enum reaches every one of the three paths (plus the wire-format
396/// `Serialize` derive that already routes through the same lifted
397/// const) through exactly one caixa-core edit.
398///
399/// Same "route the trait impl through the substrate-primitive
400/// accessor" discipline the sibling [`crate::CaixaVersion`]
401/// [`AsRef<str>`] impl (16d5c7e) carries on the paired top-level
402/// `:versao` typed newtype — extends it onto the second `AsRef<str>`
403/// axis on the caixa typed surface (the first M2 OTP-shape
404/// closed-set typed enum to converge onto the standard-library
405/// [`AsRef<str>`] projection). Rust-side newtype/typed-enum
406/// convention pairs [`AsRef<str>`] and [`fmt::Display`] on the same
407/// primitive so a caller who has one has both; before this lift,
408/// [`RestartStrategy`] carried [`fmt::Display`] but not the paired
409/// [`AsRef<str>`] impl the convention names.
410///
411/// Pinned load-bearing by
412/// [`tests::restart_strategy_as_ref_str_routes_through_as_str_accessor`]
413/// (byte-parity pin against [`RestartStrategy::as_str`] across the
414/// four-arm closed set) — any future silent detour that routes the
415/// impl through a divergent projection (a per-arm inline
416/// `match self { … }` re-inlining that opens a compile-time link to
417/// the un-lifted arm-literal, a swap onto the kebab-case
418/// [`gen_platform::Discriminant`] catalog identity that would collide
419/// the wire axis with the dispatcher-catalog axis) trips at
420/// caixa-core test time under `assert_eq!` rather than at a
421/// downstream `impl AsRef<str>`-bound consumer's silent split.
422impl AsRef<str> for RestartStrategy {
423 fn as_ref(&self) -> &str {
424 self.as_str()
425 }
426}
427
428/// Trait-idiomatic reverse projection on the M2-OTP-shape sibling-restart
429/// [`RestartStrategy`] closed-set typed enum — routes byte-for-byte through
430/// the paired substrate-primitive [`RestartStrategy::from_wire`]
431/// `Option<Self>` accessor so every future consumer that binds a
432/// `PascalCase` `:supervisor :estrategia` wire byte-string through the
433/// standard-library `.try_into()` / [`TryFrom`] axis (a future
434/// [`caixa-feira`] `feira supervisor --estrategia <OneForOne|OneForAll|
435/// RestForOne|SimpleOneForOne>` CLI arg-parse that composes into
436/// `let estrategia: RestartStrategy = s.try_into()?`, a future
437/// `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook that folds a
438/// `spec.estrategia: String` field through
439/// `RestartStrategy::try_from(&s)?`, a generic
440/// `<T: TryFrom<&str>>`-bound loader over any of the substrate's closed-
441/// set typed enums) reaches the same four-arm accept-set the sibling
442/// [`RestartStrategy::from_wire`] resolver parses through and the sibling
443/// [`RestartStrategy::as_str`] emits, rather than an open-coded per-arm
444/// `match s { "OneForOne" => …, "OneForAll" => …, "RestForOne" => …,
445/// "SimpleOneForOne" => …, _ => … }` cascade whose arm-set has no
446/// compile-time link back to the substrate primitive.
447///
448/// Complements the pre-existing forward-projection triple
449/// ([`std::fmt::Display`], [`AsRef<str>`], [`RestartStrategy::as_str`])
450/// with the paired trait-idiomatic reverse-projection axis: Rust-side
451/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
452/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so a
453/// caller who can project *out to* a `&str` can also project *in from*
454/// one. The [`TryFrom<&str>`] axis is deliberately chosen over
455/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
456/// lint the sibling method-named [`RestartStrategy::from_wire`] would
457/// trigger under a `FromStr` impl and to avoid colliding with the
458/// [`std::str::FromStr`] impl the [`gen_platform::FromStrKind`] derive
459/// already installs on the paired *kebab-case dispatcher-catalog* axis
460/// (which parses `"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
461/// `"simple-one-for-one"`, the inverse of [`Self::discriminant`]) — this
462/// impl closes the trait-idiomatic reverse axis on the *`PascalCase` wire*
463/// half without disturbing either the method-named `from_wire` shape every
464/// sibling closed-set typed enum on the substrate already carries or the
465/// pre-existing `FromStr` on the dispatcher-catalog half, keeping the
466/// two-axis split the sibling [`Self::from_wire`] doc block motivates.
467///
468/// `type Error = ()` matches the sibling [`RestartStrategy::from_wire`]'s
469/// `Option<Self>` return-shape's deliberate deferral of error typing: the
470/// caller picks the diagnostic form appropriate for its use site (a future
471/// `feira supervisor --estrategia` arg-parse composes its own per-verb
472/// "unknown strategy: <arg> — accepted: {…}" message enumerating
473/// [`RestartStrategy::ALL`], a future M4 admission-webhook rejection body
474/// wraps the `Err(())` outcome with the accepted-set enumeration for
475/// operator diagnostics, a `Result::map_err` at the call site lifts the
476/// unit-error to a per-verb error type). Same shape the peer
477/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136),
478/// [`crate::aplicacao::PlacementStrategy`] (6fd00cd), and
479/// [`crate::provedor::ferrite::FerriteRuntime::from_wire`] blocks motivate
480/// on their peer closed-set typed enums' reverse projections.
481///
482/// The paired [`TryFrom<&str>`] impl reaches the same four-arm accept-set
483/// the [`RestartStrategy::from_wire`] resolver dispatches through, so any
484/// future arm addition (an OTP-`rest_for_all` fifth arm the theory
485/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
486/// might reach for once the four canonical OTP strategies stop covering
487/// the substrate's discovered load-shape) grows the trait-idiomatic axis
488/// by construction — one caixa-core edit on
489/// [`RestartStrategy::from_wire`] extends both the method-named reverse
490/// projection every existing consumer keys off and the trait-idiomatic
491/// reverse projection this impl exposes, without a coordinated rewrite
492/// across every future `TryFrom<&str>`-bound consumer's arm-set.
493///
494/// Extends the substrate-wide closed-set-enum reverse-projection family
495/// ([`crate::CaixaKind`] via 3c83606, [`crate::CaixaDialeto`] via bf33136,
496/// [`crate::aplicacao::PlacementStrategy`] via 6fd00cd) onto the first
497/// M2-OTP-shape closed-set typed enum on the caixa surface — the
498/// `:supervisor :estrategia` closed set the future wasm-operator's
499/// hierarchical reconciliation scheduler keys off end-to-end.
500///
501/// Pinned load-bearing by
502/// [`tests::restart_strategy_try_from_str_routes_through_from_wire_accessor`]
503/// (byte-parity pin against [`RestartStrategy::from_wire`] across the
504/// four-arm accept-set) and
505/// [`tests::restart_strategy_try_from_str_rejects_unknown_byte_strings`]
506/// (rejection witness against silent accept-set widening).
507impl TryFrom<&str> for RestartStrategy {
508 type Error = ();
509
510 fn try_from(s: &str) -> Result<Self, Self::Error> {
511 Self::from_wire(s).ok_or(())
512 }
513}
514
515/// Trait-idiomatic *forward* projection on the M2-OTP-shape sibling-restart
516/// [`RestartStrategy`] closed-set typed enum onto the `&'static str` axis —
517/// routes byte-for-byte through the paired substrate-primitive
518/// [`RestartStrategy::as_str`] `pub const fn` accessor so every future
519/// consumer that binds a [`RestartStrategy`] through the standard-library
520/// `.into()` / [`From<Self> for &'static str`] (equivalently
521/// [`Into<&'static str>`]) axis (a future
522/// `tracing::field::valuable::Value::Str(strategy.into())` structured-log
523/// recorder where the `Str` arm typing demands `&'static str` and the
524/// sibling [`AsRef<str>`] impl's borrowed `&str` return-type does not
525/// satisfy the bound, a future `Cow::Borrowed::<'static, str>(strategy.into())`
526/// composer on the future M4 admission-webhook rejection body where the
527/// `Cow<'static, str>` typing rules out the sibling [`AsRef<str>`] borrowed
528/// return, a generic `<T: Into<&'static str>>`-bound serializer on a
529/// per-strategy diagnostic column) reaches the same lifted
530/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
531/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
532/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
533/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const the
534/// paired [`std::fmt::Display`], [`AsRef<str>`], and
535/// [`RestartStrategy::as_str`] surfaces already return, rather than an
536/// open-coded per-arm `match s { OneForOne => "OneForOne", … }` cascade
537/// whose arm-set has no compile-time link back to the substrate primitive.
538///
539/// Complements the pre-existing quadruple
540/// ([`std::fmt::Display`], [`AsRef<str>`], [`RestartStrategy::as_str`],
541/// [`TryFrom<&str>`] via 5b828ed) with the paired trait-idiomatic
542/// forward-projection axis: Rust-side newtype/typed-enum convention pairs
543/// [`TryFrom<&str>`] (trait-idiomatic reverse) with [`From<Self> for
544/// &'static str`] (trait-idiomatic forward) on the same primitive so a
545/// caller who can project *in from* a `&str` via the trait axis can also
546/// project *out to* one — mirroring the `strum::IntoStaticStr` /
547/// `serde::Serialize`-shape idiom where both projection halves share one
548/// trait-driven vocabulary. Before this lift the substrate carried a
549/// `&str`-returning [`AsRef<str>`] but not the paired `&'static str`-
550/// returning [`From<Self> for &'static str`] axis every downstream
551/// generic that specifically needs `'static` byte-string bytes reaches for.
552///
553/// The paired [`RestartStrategy::as_str`] returns `&'static str` by
554/// construction (each `match` arm resolves to a
555/// [`crate::render::SUPERVISOR_ESTRATEGIA_*`] `pub const &str` with static
556/// lifetime), so the trait's return-type promise is upheld structurally.
557/// Any future silent detour that routes the impl through a non-static
558/// projection (a per-arm inline `String::from("OneForOne")`-shaped
559/// re-inlining that would `.leak()`-cast for the `'static` bound, a
560/// hypothetical rebrand of one arm's [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
561/// const to a non-`const &str`) is a caixa-core-build-time failure through
562/// the `pub const fn as_str` signature the trait routes through.
563///
564/// The paired impl reaches the same four-arm emit-set the
565/// [`RestartStrategy::as_str`] accessor dispatches through, so any future
566/// arm addition (an OTP-`rest_for_all` fifth arm the theory
567/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
568/// might reach for once the four canonical OTP strategies stop covering
569/// the substrate's discovered load-shape) grows the trait-idiomatic
570/// forward axis by construction — one caixa-core edit on
571/// [`RestartStrategy::as_str`] extends every one of the five sibling
572/// forward-projection paths ([`std::fmt::Display`], [`AsRef<str>`],
573/// [`RestartStrategy::as_str`] itself, this [`From<Self> for &'static str`],
574/// and the un-`rename`d [`serde::Serialize`] derive that also emits
575/// [`Self::as_str`]'s bytes) without a coordinated rewrite across every
576/// future `Into<&'static str>`-bound consumer's arm-set.
577///
578/// Opens the substrate-wide trait-idiomatic *forward*-projection family on
579/// closed-set fieldless typed enums — the mirror of the recently-closed
580/// trait-idiomatic *reverse*-projection family ([`crate::CaixaKind`] via
581/// 3c83606, [`crate::CaixaDialeto`] via bf33136,
582/// [`crate::aplicacao::PlacementStrategy`] via 6fd00cd, this enum via
583/// 5b828ed, [`crate::supervisor::RestartPolicy`] via 6fdd0d9,
584/// [`crate::aplicacao::WitShape`] via 5472902,
585/// [`crate::aplicacao::RateLimitUnit`] via bf78400,
586/// [`crate::render::PathShapeViolation`] via e67e48a, and the four
587/// downstream-crate peers — [`caixa_arch::InvariantKind`] via e21a857,
588/// [`caixa_arch::ArchVerdict`] via 0a4cc45, [`caixa_lint::Severity`] via
589/// a7bf74c, [`caixa_lint::FixSafety`] via df86c94,
590/// [`caixa_theme::Semantic`] via bd7da69, and
591/// [`caixa_provedor::ferrite::FerriteRuntime`] via 42ab951). This lift
592/// picks [`RestartStrategy`] as the first-mover on the forward-projection
593/// family because its wire byte-string (`PascalCase`) and diagnostic
594/// byte-string ([`as_str`] return) coincide by construction — the sibling
595/// [`crate::CaixaKind`] two-axis split (lowercase Portuguese diagnostic
596/// vs `PascalCase` wire) would leave a first-mover peer arbitrarily
597/// picking one axis; on [`RestartStrategy`] the choice is unambiguous.
598///
599/// Pinned load-bearing by
600/// [`tests::restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
601/// (byte-parity pin against [`RestartStrategy::as_str`] across the
602/// four-arm emit-set, plus a `const`-context materialization witness for
603/// the `&'static str` lifetime promise) and
604/// [`tests::restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
605/// (partition pin asserting `<&'static str as From<RestartStrategy>>::from`
606/// and [`RestartStrategy::as_str`] agree on every arm, so no future
607/// silent bifurcation of the two forward-projection paths can land
608/// silently).
609impl From<RestartStrategy> for &'static str {
610 fn from(strategy: RestartStrategy) -> &'static str {
611 strategy.as_str()
612 }
613}
614
615/// Trait-idiomatic *forward* projection on [`RestartStrategy`] from a
616/// *borrowed* input onto the `&'static str` axis — the borrowed-input
617/// companion to the paired owned-input [`From<RestartStrategy> for
618/// &'static str`] impl immediately above. Routes byte-for-byte through
619/// the same substrate-primitive [`RestartStrategy::as_str`] `pub const
620/// fn` accessor so every consumer that binds a `&RestartStrategy`
621/// through the standard-library `.into()` / [`From<&Self> for &'static
622/// str`] axis (a `RestartStrategy::ALL.iter().map(<&'static
623/// str>::from).collect::<Vec<_>>()` per-arm accept-set materializer —
624/// whose iterator over `&'static [RestartStrategy]` yields
625/// `&RestartStrategy`, not `RestartStrategy`, so the owned-input
626/// [`From<RestartStrategy>`] axis alone forces every call site through
627/// an explicit `.copied()` / dereference / [`Copy`]-bound restatement
628/// rather than the direct trait-idiomatic projection; a future generic
629/// `<T: Copy + for<'a> Into<&'static str>>`-bound diagnostic column
630/// that walks the `iter().map(Into::into)` shape verbatim across every
631/// substrate-wide closed-set typed enum; the future wasm-operator's
632/// per-supervisor sibling-restart-strategy diagnostic line that
633/// composes the accepted-set enumeration from an iterated
634/// `RestartStrategy::ALL.iter().map(|s| s.into())` pipe rather than a
635/// per-arm `match s { … }` cascade; a future
636/// `HashMap::<&'static str, RestartStrategy>::from_iter(
637/// RestartStrategy::ALL.iter().map(|s| (s.into(), *s)))`-style
638/// per-strategy reverse-lookup table the sibling [`TryFrom<&str>`]
639/// impl cannot compose without this borrowed-input axis in place)
640/// reaches the same four-arm lifted
641/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
642/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
643/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
644/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
645/// the paired owned-input [`From<RestartStrategy> for &'static str`],
646/// the sibling [`std::fmt::Display`], [`AsRef<str>`], and
647/// [`RestartStrategy::as_str`] surfaces already return.
648///
649/// Fourth peer on the substrate-wide trait-idiomatic *borrowed-input*
650/// forward-projection family opened on [`crate::dep::DepList`]
651/// (64aa742) and extended onto [`crate::CaixaKind`] (5ab993a) and
652/// [`crate::CaixaDialeto`] (807b0b5). Rust's `From` trait does not
653/// auto-derive the `From<&Self>` sibling from a `From<Self>` impl (the
654/// blanket `impl<T, U> From<&T> for U where T: Copy, U: From<T>` does
655/// not exist in `core`), so every closed-set typed enum that carries
656/// the owned-input axis but not the borrowed-input axis forces every
657/// borrowed-input call site through a `.copied()` /
658/// `<&'static str>::from(*strategy)` / `strategy.as_str()` detour whose
659/// type bounds have no compile-time link to the substrate primitive.
660/// [`RestartStrategy`] is the first M2 OTP-shape peer to converge onto
661/// this campaign (mirroring the first-mover role it played on the
662/// owned-input axis in 523157d); the remaining eleven substrate-wide
663/// closed-set fieldless typed enum peers (`RestartPolicy`, `WitShape`,
664/// `RateLimitUnit`, `PlacementStrategy`, `PathShapeViolation`,
665/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
666/// `FerriteRuntime`) are the future targets of this campaign.
667///
668/// Unlike the peer [`crate::CaixaKind`] axis pair (whose forward
669/// [`From<Self> for &'static str`] emits the lowercase Portuguese
670/// [`Self::as_str`] diagnostic vocabulary while the reverse
671/// [`TryFrom<&str>`] parses the `PascalCase` [`Self::wire_name`]
672/// author-surface vocabulary, forcing the round-trip through an
673/// intermediate wire-vocab hop), [`RestartStrategy`]'s
674/// [`Self::as_str`] emit and [`Self::from_wire`] parse share the same
675/// `PascalCase` vocabulary by construction, so the borrowed-input
676/// forward axis and the reverse axis compose directly — the round-trip
677/// witness pin below locks this direct composition without the
678/// intermediate hop the peer axis requires.
679///
680/// Pinned load-bearing by
681/// [`tests::restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
682/// (byte-parity pin against [`RestartStrategy::as_str`] across the
683/// four-arm emit-set via a borrowed input, plus a `const`-context
684/// materialization witness for the `&'static str` lifetime promise,
685/// plus a blanket `.into()` shape) and
686/// [`tests::restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
687/// (cross-axis partition pin against the paired owned-input
688/// [`From<RestartStrategy> for &'static str`] impl, plus a
689/// `.iter().map(Into::into)` pipe witness over
690/// [`RestartStrategy::ALL`], plus a direct round-trip witness through
691/// [`TryFrom<&str>`] that closes the two-way `&Self → &'static str →
692/// Self` round-trip without the wire-vocab intermediate the peer
693/// [`crate::CaixaKind`] axis pair requires).
694impl From<&RestartStrategy> for &'static str {
695 fn from(strategy: &RestartStrategy) -> &'static str {
696 strategy.as_str()
697 }
698}
699
700/// Trait-idiomatic *owned-`String`* forward projection on the M2
701/// OTP-shape sibling-restart-strategy closed-set typed enum — the
702/// owned-heap-string companion to the paired `&'static str`-returning
703/// [`From<RestartStrategy> for &'static str`] / [`From<&RestartStrategy>
704/// for &'static str`] impls immediately above. Routes byte-for-byte
705/// through the substrate-primitive [`RestartStrategy::as_str`]
706/// `pub const fn` accessor (via [`str::to_owned`]) so every consumer
707/// that binds a [`RestartStrategy`] through the standard-library
708/// `.into()` / [`From<Self> for String`] (equivalently
709/// [`Into<String>`]) axis — a future
710/// `serde_json::Value::String(strategy.into())` structured-payload
711/// composer where the `Value::String` arm typing demands an owned
712/// [`String`] and the sibling [`&'static str`]-returning axis forces an
713/// explicit `.to_owned()` / `String::from` restatement at every call
714/// site, a future
715/// `HashMap::<String, RestartStrategy>::from_iter(RestartStrategy::ALL
716/// .iter().map(|s| (s.into(), *s)))` per-strategy lookup where the
717/// map's key type is owned [`String`] rather than [`&'static str`], a
718/// future `Cow::<'static, str>::Owned(strategy.into())` composer on
719/// the future M4 admission-webhook rejection body's owned-arm, the
720/// future wasm-operator's per-supervisor `serde_json::json!({
721/// "estrategia": strategy })` diagnostic emit where the JSON
722/// serializer's `Serialize` impl on [`String`] owns the emit-path — reaches
723/// the same four-arm lifted
724/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
725/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
726/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
727/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const the
728/// paired [`std::fmt::Display`], [`AsRef<str>`],
729/// [`RestartStrategy::as_str`], and the two `&'static str`-returning
730/// forward-projection impls already return.
731///
732/// Opens the trait-idiomatic *owned-`String`* forward-projection axis
733/// on the closed-set fieldless typed enum surface — first-mover on the
734/// M2 OTP-shape sibling-restart-strategy axis, mirror of the
735/// [`crate::supervisor::RestartStrategy`] first-mover position that
736/// opened the paired owned-`&'static str` axis (523157d) and the
737/// borrowed-input `&'static str` axis on
738/// [`crate::dep::DepList`] (64aa742). Rust's standard library does not
739/// carry a blanket `impl<T: AsRef<str>> From<T> for String` (nor an
740/// `impl<T: fmt::Display> From<T> for String`), so every closed-set
741/// typed enum that carries the paired `AsRef<str>` / `Display` /
742/// `From<Self> for &'static str` triple but not the owned-[`String`]
743/// axis forces every owned-string call site through a `.to_string()` /
744/// `.as_str().to_owned()` / `String::from(strategy.as_str())` detour
745/// whose type bounds have no compile-time link to the substrate
746/// primitive.
747///
748/// Deliberately routes through the human-readable
749/// [`RestartStrategy::as_str`] axis — for this enum the wire format
750/// (`PascalCase`, tatara-lisp author surface `:estrategia OneForOne`)
751/// and the diagnostic byte-string share the same vocabulary by
752/// construction (unlike the sibling [`crate::CaixaKind`] enum whose two
753/// axes diverge), so the owned-[`String`] projection lands
754/// byte-identically on both the wire vocabulary the paired
755/// [`serde::Serialize`] derive emits and the diagnostic vocabulary the
756/// [`RestartStrategy::as_str`] helper returns.
757///
758/// The remaining fourteen closed-set typed enums on the caixa
759/// substrate surface (`RestartPolicy`, `CaixaKind`, `CaixaDialeto`,
760/// `DepList`, `PlacementStrategy`, `WitShape`, `RateLimitUnit`,
761/// `PathShapeViolation`, `InvariantKind`, `ArchVerdict`, `Severity`,
762/// `FixSafety`, `Semantic`, `FerriteRuntime`) are the future targets of
763/// this campaign — each carries the same paired `AsRef<str>` /
764/// `Display` / `From<Self> for &'static str` / `From<&Self> for
765/// &'static str` quadruple that this owned-[`String`] axis extends onto.
766///
767/// Pinned load-bearing by
768/// [`tests::restart_strategy_from_into_owned_string_routes_through_as_str_accessor`]
769/// (byte-parity pin against [`RestartStrategy::as_str`] across the
770/// four-arm emit-set, plus a blanket `.into::<String>()` shape witness)
771/// and
772/// [`tests::restart_strategy_from_into_owned_string_and_static_str_agree_on_every_arm`]
773/// (cross-axis partition pin against the paired owned-input
774/// [`From<RestartStrategy> for &'static str`] impl and the sibling
775/// [`ToString::to_string`] surface routed through [`std::fmt::Display`],
776/// plus a direct round-trip witness through [`TryFrom<&str>`] on the
777/// owned-[`String`]'s [`String::as_str`] borrow that closes the two-way
778/// `Self → String → Self` round-trip on the trait-idiomatic
779/// owned-[`String`] forward + reverse axis pair).
780impl From<RestartStrategy> for String {
781 fn from(strategy: RestartStrategy) -> String {
782 strategy.as_str().to_owned()
783 }
784}
785
786/// Trait-idiomatic *borrowed-input, owned-`String` output* forward
787/// projection on the M2 OTP-shape sibling-restart-strategy closed-set
788/// typed enum — the fourth (and closing) corner of the
789/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
790/// projection family. Routes byte-for-byte through the
791/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
792/// accessor (via [`str::to_owned`]) so every consumer that holds a
793/// borrowed [`&RestartStrategy`] and needs an owned [`String`] — a
794/// future `serde_json::Value::String(String::from(&strategy))`
795/// structured-payload composer over a borrowed field, a future
796/// `Iterator::map` over `&[RestartStrategy]` that projects to owned
797/// keys through `.iter().map(String::from)`, a future
798/// `HashMap::<String, RestartStrategy>::from_iter` that keys off a
799/// borrowed-iteration axis where dereferencing the strategy would force
800/// an unnecessary `Copy` at every step, the future wasm-operator's
801/// per-supervisor `strategies.iter().map(String::from).collect()`
802/// diagnostic emit whose iteration axis is borrowed by construction —
803/// reaches the same four-arm lifted
804/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
805/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
806/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
807/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const the
808/// paired [`std::fmt::Display`], [`AsRef<str>`],
809/// [`RestartStrategy::as_str`], and the three other trait-idiomatic
810/// forward-projection impls
811/// ([`From<RestartStrategy> for &'static str`],
812/// [`From<&RestartStrategy> for &'static str`],
813/// [`From<RestartStrategy> for String`]) already return.
814///
815/// Opens the trait-idiomatic *borrowed-input, owned-`String` output*
816/// forward-projection axis on closed-set fieldless typed enums —
817/// first-mover on the 2×2 completion corner, mirror of the
818/// [`crate::supervisor::RestartStrategy`] first-mover position that
819/// opened the paired owned-input owned-`String` axis (7baa18a), the
820/// owned-input owned-`&'static str` axis (523157d), and the paired
821/// [`crate::dep::DepList`] first-mover position that opened the
822/// borrowed-input `&'static str` axis (64aa742). Rust's standard
823/// library does not carry a blanket `impl<T: AsRef<str>> From<&T> for
824/// String` (nor an `impl<T: fmt::Display> From<&T> for String`), so
825/// every closed-set typed enum that carries the paired `AsRef<str>` /
826/// `Display` / `From<Self> for &'static str` / `From<&Self> for
827/// &'static str` / `From<Self> for String` quintuple but not the
828/// borrowed-input owned-[`String`] axis forces every borrowed-input
829/// owned-string call site through a `strategy.as_str().to_owned()` /
830/// `String::from(*strategy)` (with a spurious `Copy`) /
831/// `strategy.to_string()` (through `Display`) detour whose type bounds
832/// have no compile-time link to the substrate primitive.
833///
834/// Deliberately routes through the human-readable
835/// [`RestartStrategy::as_str`] axis — for this enum the wire format
836/// (`PascalCase`, tatara-lisp author surface `:estrategia OneForOne`)
837/// and the diagnostic byte-string share the same vocabulary by
838/// construction (unlike the sibling [`crate::CaixaKind`] enum whose two
839/// axes diverge), so the borrowed-input owned-[`String`] projection
840/// lands byte-identically on both the wire vocabulary the paired
841/// [`serde::Serialize`] derive emits and the diagnostic vocabulary the
842/// [`RestartStrategy::as_str`] helper returns.
843///
844/// The remaining fourteen closed-set typed enums on the caixa
845/// substrate surface (`RestartPolicy`, `CaixaKind`, `CaixaDialeto`,
846/// `DepList`, `PlacementStrategy`, `WitShape`, `RateLimitUnit`,
847/// `PathShapeViolation`, `InvariantKind`, `ArchVerdict`, `Severity`,
848/// `FixSafety`, `Semantic`, `FerriteRuntime`) are the future targets of
849/// this 2×2-completion campaign — each carries the same paired
850/// quintuple that this borrowed-input owned-[`String`] axis extends onto.
851///
852/// Pinned load-bearing by
853/// [`tests::restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
854/// (byte-parity pin against [`RestartStrategy::as_str`] across the
855/// four-arm emit-set through the borrowed-input surface) and
856/// [`tests::restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
857/// (cross-axis partition pin against the paired owned-input owned-
858/// [`String`] [`From<RestartStrategy> for String`] impl, the paired
859/// borrowed-input owned-[`&'static str`] [`From<&RestartStrategy> for
860/// &'static str`] impl, and the sibling [`ToString::to_string`] surface
861/// routed through [`std::fmt::Display`], plus a direct round-trip
862/// witness through [`TryFrom<&str>`] on the owned-[`String`]'s
863/// [`String::as_str`] borrow that closes the two-way
864/// `&Self → String → Self` round-trip on the trait-idiomatic
865/// borrowed-input owned-[`String`] forward + reverse axis pair).
866impl From<&RestartStrategy> for String {
867 fn from(strategy: &RestartStrategy) -> String {
868 strategy.as_str().to_owned()
869 }
870}
871
872/// Trait-idiomatic *owned-input, [`std::borrow::Cow<'static, str>`]
873/// output* forward projection on the M2 OTP-shape sibling-restart
874/// [`RestartStrategy`] closed-set typed enum — extends the substrate-
875/// wide [`std::borrow::Cow<'static, str>`] forward-projection family
876/// opened on [`crate::CaixaKind`] (99c1735) onto the first M2 OTP-
877/// shape closed-set fieldless typed enum peer on the caixa surface
878/// (`:supervisor :estrategia`). Routes byte-for-byte through the
879/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
880/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
881/// that binds a [`RestartStrategy`] through the trait-idiomatic
882/// [`std::borrow::Cow<'static, str>`] axis — a future
883/// `axum::response::IntoResponse` composer whose per-strategy
884/// diagnostic-body typing rules out the sibling [`AsRef<str>`]
885/// borrowed return, a future M4 admission-webhook rejection body
886/// that composes the accepted-strategy enumeration through the same
887/// `RestartStrategy::ALL.iter().map(Cow::from)` shape [`CaixaKind`]
888/// already routes through, a generic `<T: for<'a>
889/// Into<std::borrow::Cow<'static, str>>>`-bound structured-log
890/// emitter on a per-supervisor diagnostic column — reaches the same
891/// four-arm lifted [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`]
892/// / [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
893/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
894/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
895/// the paired [`std::fmt::Display`], [`AsRef<str>`],
896/// [`RestartStrategy::as_str`], and the four
897/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
898/// forward-projection corners already return.
899///
900/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
901/// [`std::borrow::Cow::Owned`] — the substrate-primitive
902/// [`RestartStrategy::as_str`] accessor's return carries the
903/// `&'static str` lifetime by construction (each `match` arm resolves
904/// to a [`crate::render::SUPERVISOR_ESTRATEGIA_*`] `pub const &str`
905/// with static lifetime), so the zero-alloc borrowed arm is the
906/// type-correct projection with no runtime allocation.
907///
908/// Rust's standard library carries no blanket `impl<T: AsRef<str>>
909/// From<T> for Cow<'static, str>` (nor an `impl<T: fmt::Display>
910/// From<T> for Cow<'static, str>`), so the paired sibling
911/// [`From<RestartStrategy> for &'static str`],
912/// [`From<RestartStrategy> for String`], [`AsRef<str>`], and
913/// [`std::fmt::Display`] surfaces do not implicitly extend to a
914/// [`Cow<'static, str>`]-bound call site — every such site is forced
915/// through a `Cow::Borrowed(strategy.as_str())` /
916/// `Cow::Owned(strategy.to_string())` open-code whose type bounds
917/// have no compile-time link back to the substrate primitive until
918/// this lift.
919///
920/// First peer to extend the substrate-wide trait-idiomatic
921/// [`std::borrow::Cow<'static, str>`] forward-projection axis off the
922/// top-level [`crate::CaixaKind`] enum (99c1735 owned-input,
923/// d45c409 borrowed-input) onto the wider substrate — the remaining
924/// twelve peers (`RestartPolicy`, `PlacementStrategy`, `RateLimitUnit`,
925/// `DepList`, `CaixaDialeto`, and the outside-`caixa-core` peers
926/// `WitShape`, `PathShapeViolation`, `InvariantKind`, `ArchVerdict`,
927/// `Severity`, `FixSafety`, `Semantic`, `FerriteRuntime`) are the
928/// future targets of this campaign.
929///
930/// Pinned load-bearing by
931/// [`tests::restart_strategy_from_into_static_cow_str_routes_through_as_str_accessor`]
932/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
933/// against [`RestartStrategy::as_str`] across the four-arm
934/// [`RestartStrategy::ALL`]) and
935/// [`tests::restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
936/// (cross-axis partition pin against the paired [`From<RestartStrategy>
937/// for &'static str`], [`From<RestartStrategy> for String`], and
938/// [`ToString`]-through-[`std::fmt::Display`] axes, plus a
939/// `.iter().copied().map(Cow::from)` pipe witness over
940/// [`RestartStrategy::ALL`] that materializes the four-arm accept-set
941/// through the [`Cow<'static, str>`] axis alone and pins the
942/// zero-alloc discipline on every element).
943impl From<RestartStrategy> for std::borrow::Cow<'static, str> {
944 fn from(strategy: RestartStrategy) -> std::borrow::Cow<'static, str> {
945 std::borrow::Cow::Borrowed(strategy.as_str())
946 }
947}
948
949/// Trait-idiomatic *borrowed-input, [`std::borrow::Cow<'static, str>`]
950/// output* forward projection on the M2 OTP-shape sibling-restart
951/// [`RestartStrategy`] closed-set typed enum — the borrowed-input
952/// companion to the paired owned-input
953/// [`From<RestartStrategy> for std::borrow::Cow<'static, str>`] impl
954/// immediately above (7dd28b3). Routes byte-for-byte through the same
955/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
956/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
957/// that holds a `&RestartStrategy` and needs a
958/// [`std::borrow::Cow<'static, str>`] — a
959/// `RestartStrategy::ALL.iter().map(std::borrow::Cow::from).collect::<Vec<_>>()`
960/// per-arm accept-set materializer (whose iterator over
961/// `&'static [RestartStrategy]` yields `&RestartStrategy`, not
962/// `RestartStrategy`, so the paired owned-input
963/// [`From<RestartStrategy> for std::borrow::Cow<'static, str>`] axis
964/// alone forces every call site through an explicit `.copied()` /
965/// dereference / [`Copy`]-bound restatement rather than the direct
966/// trait-idiomatic projection), a future generic
967/// `<T: for<'a> Into<std::borrow::Cow<'static, str>>>`-bound emitter
968/// on a per-strategy diagnostic column that walks the
969/// `iter().map(Into::into)` shape verbatim, the future M4 admission-
970/// webhook rejection body that composes the accepted-strategy
971/// enumeration from an iterated
972/// `RestartStrategy::ALL.iter().map(|s| s.into())` pipe rather than a
973/// per-arm `match s { … }` cascade — reaches the same four-arm lifted
974/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
975/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
976/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
977/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
978/// the paired [`std::fmt::Display`], [`AsRef<str>`],
979/// [`RestartStrategy::as_str`], the four
980/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
981/// forward-projection corners, and the paired owned-input
982/// [`From<RestartStrategy> for std::borrow::Cow<'static, str>`] impl
983/// already return.
984///
985/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
986/// [`std::borrow::Cow::Owned`] — the substrate-primitive
987/// [`RestartStrategy::as_str`] accessor's return carries the
988/// `&'static str` lifetime by construction (each `match` arm resolves
989/// to a [`crate::render::SUPERVISOR_ESTRATEGIA_*`] `pub const &str`
990/// with static lifetime), so the zero-alloc borrowed arm is the
991/// type-correct projection with no runtime allocation.
992///
993/// Second peer on the substrate-wide trait-idiomatic
994/// [`std::borrow::Cow<'static, str>`] forward-projection family
995/// opened one commit prior (7dd28b3) on the paired owned-input
996/// [`From<RestartStrategy> for std::borrow::Cow<'static, str>`] impl
997/// — closes the `{Self, &Self}` input-shape corner of the
998/// [`Cow<'static, str>`] axis on the first M2 OTP-shape closed-set
999/// fieldless typed enum peer on the caixa surface, exactly as
1000/// d45c409 closed it on the top-level [`crate::CaixaKind`] one commit
1001/// after the owning half (99c1735) landed. Rust's standard library
1002/// does not carry a blanket `impl<T: AsRef<str>> From<&T> for
1003/// Cow<'static, str>` (nor an `impl<T: fmt::Display> From<&T> for
1004/// Cow<'static, str>`), so every closed-set fieldless typed enum peer
1005/// on the substrate that carries the paired owned-input
1006/// [`Cow<'static, str>`] axis but not the borrowed-input axis forces
1007/// every borrowed-input [`Cow<'static, str>`]-parameterized call site
1008/// through a spurious [`Copy`] deref
1009/// (`std::borrow::Cow::from(*strategy)`) or a
1010/// `std::borrow::Cow::Borrowed(strategy.as_str())` open-code whose
1011/// type bounds have no compile-time link to the substrate primitive.
1012///
1013/// Pinned load-bearing by
1014/// [`tests::restart_strategy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor`]
1015/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
1016/// against [`RestartStrategy::as_str`] across the four-arm
1017/// [`RestartStrategy::ALL`] through the borrowed-input surface) and
1018/// [`tests::restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
1019/// (cross-axis partition pin against the paired owned-input
1020/// [`From<RestartStrategy> for std::borrow::Cow<'static, str>`], the
1021/// paired borrowed-input owned-`&'static str`
1022/// [`From<&RestartStrategy> for &'static str`], and the paired
1023/// borrowed-input owned-`String` [`From<&RestartStrategy> for String`]
1024/// impls, plus a `.iter().map(std::borrow::Cow::from)` pipe witness
1025/// over [`RestartStrategy::ALL`] — whose iterator yields
1026/// `&RestartStrategy` by construction, so the borrowed-input
1027/// [`Cow<'static, str>`] axis is what routes the pipe through the
1028/// substrate-primitive [`RestartStrategy::as_str`] accessor with the
1029/// zero-alloc [`Cow::Borrowed`] arm by construction and without a
1030/// spurious [`Copy`] deref).
1031impl From<&RestartStrategy> for std::borrow::Cow<'static, str> {
1032 fn from(strategy: &RestartStrategy) -> std::borrow::Cow<'static, str> {
1033 std::borrow::Cow::Borrowed(strategy.as_str())
1034 }
1035}
1036
1037/// Trait-idiomatic *owned-input, [`Box<str>`] output* forward
1038/// projection on the M2 OTP-shape sibling-restart [`RestartStrategy`]
1039/// closed-set fieldless typed enum — opens a fresh
1040/// substrate-wide `Box<str>` forward-projection campaign tier on the
1041/// first M2 OTP-shape closed-set fieldless typed enum peer on the
1042/// caixa surface, immediately after the paired `Cow<'static, str>`
1043/// axis (7dd28b3 / ee577fd) closed the
1044/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}` 2×3
1045/// corner on this enum. Routes byte-for-byte through the
1046/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
1047/// accessor via [`Box::<str>::from`] on the returned `&'static str`,
1048/// so every consumer that binds a
1049/// `let key: Box<str> = strategy.into();`-shaped call site — a
1050/// per-supervisor metric-key materializer that stashes the strategy
1051/// discriminator in a `Box<str>`-typed heap-owned scalar for cheap
1052/// clone (a shared-nothing per-strategy accept-set the
1053/// `caixa-operator` reconciliation scheduler carries), a future
1054/// admission-webhook rejection body whose per-arm `Box<str>` field
1055/// composes from an owned `RestartStrategy` handle — reaches the
1056/// same four-arm lifted
1057/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
1058/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
1059/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
1060/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
1061/// the sibling
1062/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
1063/// forward-projection corner already returns. Rust's standard
1064/// library carries `impl From<&str> for Box<str>` and
1065/// `impl From<String> for Box<str>` but no blanket
1066/// `impl<T: AsRef<str>> From<T> for Box<str>`, so this axis is a
1067/// distinct trait-idiomatic surface that a downstream
1068/// `RestartStrategy → Box<str>` `.into()` reaches through this impl
1069/// and no other — without a
1070/// `Box::from(strategy.as_str())` open-code whose type bounds have
1071/// no compile-time link back to the substrate primitive.
1072///
1073/// Pinned load-bearing by
1074/// [`tests::restart_strategy_from_into_box_str_routes_through_as_str_accessor`]
1075/// (byte-parity pin against [`RestartStrategy::as_str`] across the
1076/// four-arm [`RestartStrategy::ALL`] emit-set on the owned-input
1077/// surface, plus a blanket-derived [`Into`] shape witness).
1078impl From<RestartStrategy> for Box<str> {
1079 fn from(strategy: RestartStrategy) -> Box<str> {
1080 Box::<str>::from(strategy.as_str())
1081 }
1082}
1083
1084/// Trait-idiomatic *borrowed-input, [`Box<str>`] output* forward
1085/// projection on the M2 OTP-shape sibling-restart [`RestartStrategy`]
1086/// closed-set fieldless typed enum — closes the `{Self, &Self}`
1087/// input-shape corner of the substrate-wide `Box<str>`
1088/// forward-projection axis opened one commit prior (69ef45c) on the
1089/// paired owned-input [`From<RestartStrategy> for Box<str>`] impl.
1090/// Routes byte-for-byte through the same substrate-primitive
1091/// [`RestartStrategy::as_str`] `pub const fn` accessor via
1092/// [`Box::<str>::from`] on the returned `&'static str`, so every
1093/// consumer that holds a `&RestartStrategy` and needs a
1094/// [`Box<str>`] — a
1095/// `RestartStrategy::ALL.iter().map(Box::<str>::from).collect::<Vec<_>>()`
1096/// per-arm accept-set materializer (whose iterator over
1097/// `&'static [RestartStrategy]` yields `&RestartStrategy`, not
1098/// `RestartStrategy`, so the paired owned-input
1099/// [`From<RestartStrategy> for Box<str>`] axis alone forces every
1100/// call site through an explicit `.copied()` / dereference /
1101/// [`Copy`]-bound restatement rather than the direct trait-idiomatic
1102/// projection), a per-supervisor metric-key materializer holding
1103/// `&RestartStrategy` through a `caixa-operator` reconciliation
1104/// scheduler's borrow lifetime, a future admission-webhook rejection
1105/// body whose per-arm `Box<str>` field composes from a borrowed
1106/// `&RestartStrategy` handle without a spurious [`Copy`] deref —
1107/// reaches the same four-arm lifted
1108/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
1109/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
1110/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
1111/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
1112/// the paired owned-input [`From<RestartStrategy> for Box<str>`] and
1113/// the sibling
1114/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
1115/// forward-projection corner already return.
1116///
1117/// Second peer on the substrate-wide trait-idiomatic
1118/// [`Box<str>`] forward-projection family opened one commit prior
1119/// (69ef45c) on the paired owned-input
1120/// [`From<RestartStrategy> for Box<str>`] impl — closes the
1121/// `{Self, &Self}` input-shape corner of the [`Box<str>`] axis on
1122/// the first M2 OTP-shape closed-set fieldless typed enum peer on
1123/// the caixa surface (`:supervisor :estrategia`), exactly as
1124/// ee577fd closed the paired [`Cow<'static, str>`] axis one commit
1125/// after its owning half (7dd28b3) landed. Rust's standard library
1126/// carries `impl From<&str> for Box<str>` and
1127/// `impl From<String> for Box<str>` but no blanket
1128/// `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
1129/// `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
1130/// every closed-set fieldless typed enum peer on the substrate that
1131/// carries the paired owned-input `Box<str>` axis but not the
1132/// borrowed-input axis forces every borrowed-input
1133/// `Box<str>`-parameterized call site through a spurious [`Copy`]
1134/// deref (`Box::<str>::from((*strategy).as_str())`) or a
1135/// `Box::<str>::from(strategy.as_str())` open-code whose type bounds
1136/// have no compile-time link back to the substrate primitive.
1137///
1138/// Pinned load-bearing by
1139/// [`tests::restart_strategy_from_borrowed_into_box_str_routes_through_as_str_accessor`]
1140/// (byte-parity pin against [`RestartStrategy::as_str`] across the
1141/// four-arm [`RestartStrategy::ALL`] emit-set on the borrowed-input
1142/// surface, plus a blanket-derived [`Into`] shape witness and a
1143/// cross-axis pin against the paired owned-input
1144/// [`From<RestartStrategy> for Box<str>`] and the sibling
1145/// borrowed-input `{&'static str, String, Cow<'static, str>}`
1146/// return-shape axes).
1147impl From<&RestartStrategy> for Box<str> {
1148 fn from(strategy: &RestartStrategy) -> Box<str> {
1149 Box::<str>::from(strategy.as_str())
1150 }
1151}
1152
1153/// Trait-idiomatic *owned-input, [`std::sync::Arc<str>`] output*
1154/// forward projection on the M2 OTP-shape sibling-restart
1155/// [`RestartStrategy`] closed-set fieldless typed enum — opens the
1156/// substrate-wide [`std::sync::Arc<str>`] forward-projection campaign
1157/// tier on the first M2 OTP-shape closed-set fieldless typed enum peer
1158/// on the caixa surface (`:supervisor :estrategia`), immediately after
1159/// the paired [`Box<str>`] axis (69ef45c / 59ae5dc) closed the
1160/// `{Self, &Self} × {&'static str, String, Cow<'static, str>, Box<str>}`
1161/// 2×4 corner on this enum. Routes byte-for-byte through the
1162/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
1163/// accessor (via [`std::sync::Arc::<str>::from`] on the returned
1164/// `&'static str`), so every consumer that binds a
1165/// [`RestartStrategy`] through the standard-library `.into()` /
1166/// [`From<Self> for std::sync::Arc<str>`] (equivalently
1167/// [`Into<std::sync::Arc<str>>`]) axis — a future admission-webhook
1168/// running under `axum` + `tokio` whose per-arm structured-log field
1169/// crosses an `.await` boundary and demands the [`Sync`] +
1170/// [`Send`]-safe shared-ownership envelope [`std::sync::Arc<str>`]
1171/// provides (the sibling [`Box<str>`] axis's owned-move return-shape
1172/// forces every downstream `.clone()` through a heap allocation, while
1173/// [`std::sync::Arc<str>`]'s reference-counted shared-ownership
1174/// resolves the same `.clone()` through a refcount bump), a future
1175/// wasm-operator's per-supervisor reconciliation scheduler that
1176/// dispatches the same per-strategy diagnostic key onto multiple
1177/// concurrent reconcile-loop tasks holding shared-ownership through
1178/// [`std::sync::Arc<str>`], a future
1179/// `tracing::field::valuable::Value::Str(strategy.into())` structured-
1180/// log recorder whose typing folds a shared-ownership envelope onto
1181/// the span-context axis, a generic
1182/// `<T: Into<std::sync::Arc<str>>>`-bound diagnostic column on a
1183/// shared-ownership per-strategy cache — reaches the same four-arm
1184/// lifted [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
1185/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
1186/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
1187/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
1188/// the sibling
1189/// `{Self, &Self} × {&'static str, String, Cow<'static, str>, Box<str>}`
1190/// forward-projection corner already returns.
1191///
1192/// First-mover on the substrate-wide trait-idiomatic
1193/// [`std::sync::Arc<str>`] forward-projection family — Rust's
1194/// standard library carries `impl From<&str> for std::sync::Arc<str>`
1195/// and `impl From<String> for std::sync::Arc<str>` but no blanket
1196/// `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor an
1197/// `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`), so every
1198/// closed-set fieldless typed enum on the substrate that carries the
1199/// paired [`AsRef<str>`] / [`std::fmt::Display`] /
1200/// [`From<Self> for &'static str`] / [`From<&Self> for &'static str`] /
1201/// [`From<Self> for String`] / [`From<&Self> for String`] /
1202/// [`From<Self> for Cow<'static, str>`] /
1203/// [`From<&Self> for Cow<'static, str>`] /
1204/// [`From<Self> for Box<str>`] / [`From<&Self> for Box<str>`] decet
1205/// but not the [`std::sync::Arc<str>`] axis forces every
1206/// `std::sync::Arc<str>`-parameterized call site through a
1207/// `std::sync::Arc::<str>::from(strategy.as_str())` open-code (or a
1208/// `std::sync::Arc::<str>::from(String::from(strategy))` two-step
1209/// composition through the owned-`String` axis that allocates
1210/// twice — once into the intermediate `String`, once into the
1211/// [`Arc<str>`] on the `From<String>` conversion) whose type bounds
1212/// have no compile-time link back to the substrate primitive. Opening
1213/// the axis on the first M2 OTP-shape closed-set fieldless typed enum
1214/// peer on the caixa substrate surface establishes the "route through
1215/// `as_str` via [`std::sync::Arc::<str>::from`] on the returned
1216/// `&'static str`" discipline; every future closed-set fieldless
1217/// typed enum peer on the substrate ([`RestartPolicy`],
1218/// [`crate::aplicacao::PlacementStrategy`],
1219/// [`crate::aplicacao::RateLimitUnit`], [`crate::aplicacao::WitShape`],
1220/// [`crate::dep::DepList`], [`crate::dialeto::CaixaDialeto`],
1221/// [`crate::kind::CaixaKind`],
1222/// [`crate::render::PathShapeViolation`], and the outside-`caixa-core`
1223/// peers `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`,
1224/// `Semantic`, `FerriteRuntime`) is a future target of the campaign,
1225/// tracking the same 14-peer emit-set every prior projection tier
1226/// ([`&'static str`], [`String`], [`Cow<'static, str>`], [`Box<str>`])
1227/// converged onto.
1228///
1229/// Peer of the sibling [`Box<str>`] forward-projection first-mover
1230/// (69ef45c) — same "opens a new substrate-wide projection tier"
1231/// discipline, extended onto the [`std::sync::Arc<str>`] axis whose
1232/// shared-ownership + [`Sync`] + [`Send`] contract is the distinct
1233/// value the [`Box<str>`] axis's owned-move return-shape cannot
1234/// provide.
1235///
1236/// Pinned load-bearing by
1237/// [`tests::restart_strategy_from_into_arc_str_routes_through_as_str_accessor`]
1238/// (byte-parity pin against [`RestartStrategy::as_str`] across the
1239/// four-arm [`RestartStrategy::ALL`] emit-set on the owned-input
1240/// surface, plus a blanket-derived [`Into`] shape witness and cross-
1241/// axis byte-parity pins against the sibling owned-input
1242/// `{&'static str, String, Cow<'static, str>, Box<str>}` return-shape
1243/// axes).
1244impl From<RestartStrategy> for std::sync::Arc<str> {
1245 fn from(strategy: RestartStrategy) -> std::sync::Arc<str> {
1246 std::sync::Arc::<str>::from(strategy.as_str())
1247 }
1248}
1249
1250/// Trait-idiomatic *borrowed-input, [`std::sync::Arc<str>`] output*
1251/// forward projection on the M2 OTP-shape sibling-restart
1252/// [`RestartStrategy`] closed-set fieldless typed enum — closes the
1253/// `{Self, &Self}` input-shape corner of the [`std::sync::Arc<str>`]
1254/// forward-projection axis on the first M2 OTP-shape closed-set
1255/// fieldless typed enum peer on the caixa surface
1256/// (`:supervisor :estrategia`), companion to the paired owned-input
1257/// [`From<RestartStrategy> for std::sync::Arc<str>`] impl one commit
1258/// prior (bca2ec8). Routes byte-for-byte through the
1259/// substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
1260/// accessor (via [`std::sync::Arc::<str>::from`] on the returned
1261/// `&'static str`), so every consumer that binds a
1262/// [`&RestartStrategy`] through the standard-library `.into()` /
1263/// [`From<&Self> for std::sync::Arc<str>`] (equivalently
1264/// [`Into<std::sync::Arc<str>>`]) axis — a future admission-webhook's
1265/// per-request borrowed-`&RestartStrategy` handle rendering a per-arm
1266/// `Sync` + `Send`-safe structured-log field across an `.await`
1267/// boundary through a `<T: Into<std::sync::Arc<str>>>`-bound
1268/// diagnostic-column dispatch, a future wasm-operator's per-
1269/// supervisor reconciliation pipeline whose
1270/// `.iter().map(std::sync::Arc::<str>::from)` collector reaches into
1271/// the shared-ownership per-strategy key without a spurious [`Copy`]
1272/// deref (which would only be reachable through the owned-input
1273/// [`From<RestartStrategy> for std::sync::Arc<str>`] axis by first
1274/// calling `.copied()` on the iterator), a future
1275/// `<T: Into<std::sync::Arc<str>>>`-bound `tracing`-span attributes
1276/// collector recording a borrowed-`&RestartStrategy` per-arm field
1277/// onto the parent span's shared-ownership context — reaches the
1278/// same four-arm lifted
1279/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
1280/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
1281/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
1282/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`] const
1283/// the paired owned-input
1284/// [`From<RestartStrategy> for std::sync::Arc<str>`] impl and the
1285/// sibling `{&'static str, String, Cow<'static, str>, Box<str>}`
1286/// forward-projection corner already return.
1287///
1288/// Second peer on the substrate-wide trait-idiomatic
1289/// [`std::sync::Arc<str>`] forward-projection family opened one
1290/// commit prior (bca2ec8) on the paired owned-input
1291/// [`From<RestartStrategy> for std::sync::Arc<str>`] impl — closes
1292/// the `{Self, &Self}` input-shape corner of the
1293/// [`std::sync::Arc<str>`] axis on the first M2 OTP-shape closed-set
1294/// fieldless typed enum peer on the caixa surface, exactly as
1295/// 59ae5dc closed the paired [`Box<str>`] axis one commit after its
1296/// owning half (69ef45c) landed. Rust's standard library carries
1297/// `impl From<&str> for std::sync::Arc<str>` and
1298/// `impl From<String> for std::sync::Arc<str>` but no blanket
1299/// `impl<T: AsRef<str>> From<&T> for std::sync::Arc<str>` (nor a
1300/// `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
1301/// every closed-set fieldless typed enum peer on the substrate that
1302/// carries the paired owned-input [`std::sync::Arc<str>`] axis but
1303/// not the borrowed-input axis forces every borrowed-input
1304/// [`std::sync::Arc<str>`]-parameterized call site through a
1305/// spurious [`Copy`] deref
1306/// (`std::sync::Arc::<str>::from((*strategy).as_str())`) or a
1307/// `std::sync::Arc::<str>::from(strategy.as_str())` open-code whose
1308/// type bounds have no compile-time link back to the substrate
1309/// primitive.
1310///
1311/// Pinned load-bearing by
1312/// [`tests::restart_strategy_from_borrowed_into_arc_str_routes_through_as_str_accessor`]
1313/// (byte-parity pin against [`RestartStrategy::as_str`] across the
1314/// four-arm [`RestartStrategy::ALL`] emit-set on the borrowed-input
1315/// surface, plus a blanket-derived [`Into`] shape witness and a
1316/// cross-axis pin against the paired owned-input
1317/// [`From<RestartStrategy> for std::sync::Arc<str>`] and the sibling
1318/// borrowed-input `{&'static str, String, Cow<'static, str>,
1319/// Box<str>}` return-shape axes).
1320impl From<&RestartStrategy> for std::sync::Arc<str> {
1321 fn from(strategy: &RestartStrategy) -> std::sync::Arc<str> {
1322 std::sync::Arc::<str>::from(strategy.as_str())
1323 }
1324}
1325
1326/// Per-child restart policy.
1327///
1328/// Permanent / Temporary / Transient match Erlang/OTP semantics 1:1.
1329#[derive(
1330 Serialize,
1331 Deserialize,
1332 Debug,
1333 Clone,
1334 Copy,
1335 PartialEq,
1336 Eq,
1337 Hash,
1338 gen_platform::TypedDispatcher,
1339 gen_platform::Discriminant,
1340 gen_platform::IsVariant,
1341 gen_platform::FromStrKind,
1342)]
1343pub enum RestartPolicy {
1344 /// Always restart the child, regardless of how it died. Used for
1345 /// long-running services that must always be up.
1346 Permanent,
1347 /// Never restart. Used for one-shot work whose completion is
1348 /// itself the success signal (`oneShot` triggers map here).
1349 Temporary,
1350 /// Restart only when the child died *abnormally* (non-zero exit
1351 /// or unhandled exception). A clean exit completes the child.
1352 Transient,
1353}
1354
1355impl Default for RestartPolicy {
1356 fn default() -> Self {
1357 // Route the [`Default for RestartPolicy`] impl's return arm through
1358 // the substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed
1359 // `pub const` rather than a raw `Self::Permanent` arm — one source
1360 // of truth for the Erlang/OTP-canonical `permanent` worker-child
1361 // default across the two production consumers that currently
1362 // dispatch on it (this impl at the [`RestartPolicy::default`] call
1363 // and the serde-side `#[serde(default)]` on
1364 // [`ChildSpec::restart`] that resolves an author-omitted
1365 // `:children :restart` slot through `RestartPolicy::default()`).
1366 // Peer of the sibling per-`:supervisor` axis
1367 // [`Default for RestartStrategy`] → [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
1368 // route (95ffacc) — the two impls now share one substrate-primitive
1369 // lift discipline, so any future coherent rebrand of the OTP-shape
1370 // supervisor+child default set migrates through typed constants in
1371 // lockstep instead of splitting a lifted supervisor half against
1372 // an open-coded child half. Pinned by
1373 // `restart_policy_default_routes_through_lifted_default` +
1374 // `child_spec_serde_default_restart_routes_through_lifted_default`
1375 // in the tests module.
1376 SUPERVISOR_CHILD_RESTART_DEFAULT
1377 }
1378}
1379
1380impl RestartPolicy {
1381 /// Exhaustive iteration surface for every consumer that walks the
1382 /// closed three-arm [`RestartPolicy`] discriminator set (the future
1383 /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1384 /// per-child admission-webhook rejection body naming the accepted-
1385 /// `:restart` list, a future `feira supervisor --restart …` CLI
1386 /// arg-parse's "did you mean" hint via a [`Self::from_wire`]-scan
1387 /// over the slice, the future `feira app graph` per-child restart
1388 /// column, any future round-trip fuzz harness that sweeps every
1389 /// arm). A future arm addition (an OTP-`intrinsic` fourth arm the
1390 /// theory
1391 /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1392 /// might reach for once the three canonical OTP restart policies
1393 /// stop covering the substrate's discovered load-shape) extends
1394 /// this slice as one edit and every consumer picks up the new entry
1395 /// by construction; the compiler-checked exhaustiveness on the
1396 /// sibling method `match` arms ([`Self::as_str`] / [`Self::from_wire`])
1397 /// is the build-time guarantee that no arm forgets to grow.
1398 ///
1399 /// Peer of the sibling closed-set typed enums'
1400 /// [`RestartStrategy::ALL`] (4eec29c) /
1401 /// [`crate::CaixaKind::ALL`] (6b1f4fb) /
1402 /// [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
1403 /// [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
1404 /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
1405 /// surfaces — the sixth (and the third and final M2 OTP-shape)
1406 /// closed-set typed enum on the caixa surface to converge onto the
1407 /// same one-canonical-arm-list-per-enum discipline. Sibling axis to
1408 /// the peer [`RestartStrategy::ALL`] on the per-supervisor
1409 /// sibling-restart-strategy axis; this closes the per-child
1410 /// restart-decision-policy axis on the same M2 `:supervisor` slot.
1411 pub const ALL: &'static [Self] = &[Self::Permanent, Self::Temporary, Self::Transient];
1412
1413 /// Substrate-canonical exhaustive accept-set on the [`RestartPolicy`]
1414 /// `PascalCase` wire byte-string axis — the closed three-arm roster
1415 /// of every byte-string [`Self::as_str`] returns, routed byte-for-byte
1416 /// through the paired
1417 /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1418 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1419 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] lifted
1420 /// `pub const` roster the [`Self::as_str`] emitter (and the
1421 /// [`std::fmt::Display`] impl / `Serialize` derive routed through it)
1422 /// walks — and byte-for-byte the same three strings the un-`rename`d
1423 /// `Serialize` derive emits under the paired
1424 /// [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] tag key on every
1425 /// JSON / YAML CR round-trip.
1426 ///
1427 /// Peer of the sibling [`crate::CaixaKind::WIRE_NAMES`] (bd708bd)
1428 /// roster on the top-level typed-kind discriminator's `PascalCase`
1429 /// wire byte-string axis, the sibling
1430 /// [`RestartStrategy::WIRE_NAMES`] (3033f45) roster on the per-
1431 /// supervisor sibling-restart-strategy axis (the first M2 OTP-shape
1432 /// closed-set typed enum to converge onto the paired-roster
1433 /// discipline), the sibling
1434 /// [`crate::aplicacao::PlacementStrategy::WIRE_NAMES`] (3e5b194)
1435 /// roster on the first M3 mesh-shape distribution-strategy closed-
1436 /// set typed enum, and the sibling
1437 /// [`crate::upgrade::UpgradeInstruction::WIRE_FORMS`] (cc42c0e) /
1438 /// [`crate::upgrade::UpgradeInstruction::LISP_FORMS`] (1898d77)
1439 /// rosters on the OTP-appup discriminator's two-axis roster split —
1440 /// the same closed-set exhaustive-accept-set roster discipline
1441 /// extended here onto the second and final M2 OTP-shape sibling-
1442 /// enum on the caixa surface, closing the per-child restart-decision-
1443 /// policy axis paired with the peer [`RestartStrategy::WIRE_NAMES`]
1444 /// per-supervisor sibling-restart-strategy axis on the same M2
1445 /// `:supervisor` slot.
1446 ///
1447 /// Downstream consumers of the closed accepted-wire-form set — a
1448 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR admission-
1449 /// webhook rejection body enumerating the accepted JSON `:restart`
1450 /// values verbatim (as distinct from the kebab-case dispatcher-
1451 /// catalog enumeration [`Self::discriminant`] serves, whose per-arm
1452 /// form `"permanent"` / `"temporary"` / `"transient"` structurally
1453 /// disagrees with the wire byte-string these `PascalCase` entries
1454 /// carry — the split the sibling
1455 /// [`tests::restart_policy_display_matches_serialized_wire_byte_string`]
1456 /// pin already makes load-bearing), a future `feira supervisor
1457 /// --restart …` CLI-side "did you mean" hint whose candidate-list
1458 /// must byte-match the wire form the operator's per-child dispatch
1459 /// keys off, a future `feira app graph` per-child `:restart`-
1460 /// histogram column that renders zero-count arms, a future
1461 /// `caixa-operator` per-reconcile-step diagnostic log line
1462 /// enumerating accepted wire forms on an unknown-policy rejection,
1463 /// a future
1464 /// `tracing::field::valuable::Value::List` structured-log accepted-
1465 /// wire-form emit — now reach for one lifted substrate-primitive
1466 /// roster rather than open-coding a three-string array-literal
1467 /// (`["Permanent", "Temporary", "Transient"]`) whose arm-set has no
1468 /// compile-time link back to the typed [`RestartPolicy`] enum. A
1469 /// future arm addition (an OTP-`intrinsic` fourth arm the theory
1470 /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1471 /// might reach for once the three canonical OTP restart policies
1472 /// stop covering the substrate's discovered load-shape) extends
1473 /// this roster as a single edit — paired with the [`Self::as_str`]
1474 /// match's compiler-checked exhaustiveness on the new arm — and
1475 /// every consumer picks up the new wire form by construction rather
1476 /// than a coordinated array-literal rewrite across every downstream
1477 /// site.
1478 ///
1479 /// Length is pinned load-bearing at `RestartPolicy::ALL.len()`
1480 /// (three) by
1481 /// [`tests::restart_policy_wire_names_covers_every_arm`], every
1482 /// variant's [`Self::as_str`] projection is pinned to a member of
1483 /// the roster so a silent skew between the emitter's arm-set and
1484 /// this const's arm-set trips at caixa-core test time rather than at
1485 /// a downstream consumer's accepted-set enumeration miss, and every
1486 /// entry is further pinned to open with an ASCII uppercase byte so
1487 /// a silent collapse of the `PascalCase` wire-form axis with the
1488 /// peer kebab-case dispatcher-catalog axis (an entry byte-identical
1489 /// to a sibling [`Self::discriminant`] kebab byte-string that would
1490 /// let a wire-axis consumer accept the dispatcher-catalog
1491 /// vocabulary) trips here rather than at a downstream K8s-CR round-
1492 /// trip miss.
1493 pub const WIRE_NAMES: &'static [&'static str] = &[
1494 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
1495 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
1496 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
1497 ];
1498
1499 /// Canonical PascalCase discriminator scalar this variant serializes
1500 /// as under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`]. The three
1501 /// arms return the paired
1502 /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1503 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1504 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] lifted
1505 /// constants so every substrate consumer that dispatches on the
1506 /// per-child restart-decision policy (the future wasm-operator's
1507 /// per-child post-exit restart-decision branch, the future M4
1508 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1509 /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
1510 /// reconciliation scheduler's per-child-policy fan-out) reads the
1511 /// same byte-string the `Serialize` derive emits — the pin test in
1512 /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
1513 /// asserts the two paths agree, peer of the M2
1514 /// [`RestartStrategy::as_str`] (09ffb2d) on the sibling per-supervisor
1515 /// sibling-restart-strategy axis and the M3
1516 /// [`crate::aplicacao::PlacementStrategy::as_str`] (cc8f749) on the
1517 /// per-Aplicacao distribution-strategy axis — the third of three
1518 /// OTP-shaped closed-enum discriminator axes on the caixa typed
1519 /// surface to converge onto the same three-path-convergence
1520 /// (`Serialize` derive → `as_str` helper → lifted constant)
1521 /// drift-detection posture.
1522 #[must_use]
1523 pub const fn as_str(self) -> &'static str {
1524 match self {
1525 Self::Permanent => crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
1526 Self::Temporary => crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
1527 Self::Transient => crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
1528 }
1529 }
1530
1531 /// Substrate-canonical reverse projection on the `:children :restart`
1532 /// closed-set axis — parses the `PascalCase` discriminator scalar
1533 /// back to the typed variant, or `None` when `s` is outside the
1534 /// closed-set arm-string set [`Self::as_str`] emits. Dispatches on
1535 /// the same lifted
1536 /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1537 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1538 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] constants
1539 /// the [`Self::as_str`] emitter walks, so the parse and emit halves
1540 /// of the round-trip migrate through one caixa-core edit on any
1541 /// future arm addition.
1542 ///
1543 /// Prior to this lift the substrate carried only the forward
1544 /// `Self → &str` projection on the OTP per-child restart-policy
1545 /// axis (the [`Self::as_str`] emitter, the [`std::fmt::Display`]
1546 /// impl routed through it, the `Serialize` derive that emits the
1547 /// same byte-string under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`])
1548 /// plus the kebab-case dispatcher-catalog identity via
1549 /// [`Self::discriminant`] — every non-serde consumer that wanted to
1550 /// parse a wire-form `PascalCase` policy scalar had to re-inline a
1551 /// three-arm `match s { "Permanent" => …, "Temporary" => …,
1552 /// "Transient" => …, _ => … }` cascade that expressed no
1553 /// compile-time link back to the typed variant's canonical lifted
1554 /// constant. A future variant rename or per-arm serde-attribute
1555 /// drift would silently split the wire byte-string one non-serde
1556 /// consumer parsed from the one the emitter wrote, with the failure
1557 /// surfacing at the operator's reconcile posture (a `:temporary`
1558 /// `oneShot` child being restarted on clean exit, treating the
1559 /// successful-completion signal as failure and re-running the
1560 /// completion-terminal one-shot indefinitely; a `:transient` child
1561 /// that clean-exited being restarted, masking the clean-completion
1562 /// contract) far from the rebrand commit and with no field naming
1563 /// the drift.
1564 ///
1565 /// Distinct axis from the [`std::str::FromStr`] impl the
1566 /// [`gen_platform::FromStrKind`] derive already installs on this
1567 /// enum by design, not by drift: `FromStr` parses the *kebab-case*
1568 /// dispatcher-catalog identity (`"permanent"` / `"temporary"` /
1569 /// `"transient"` — the inverse of [`Self::discriminant`]), while
1570 /// this method inverts the `PascalCase` wire byte-string
1571 /// [`Self::as_str`] emits. The two-axis split lets the dispatcher-
1572 /// catalog identity live in kebab-case (where every peer catalog
1573 /// identifier already lives) without forcing a wire-format rename
1574 /// on the tatara-lisp author surface (`:restart Permanent`,
1575 /// `PascalCase`) — the same two-axis distinction the sibling
1576 /// [`RestartStrategy::from_wire`] (4eec29c) /
1577 /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
1578 /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
1579 /// carry on their peer closed-set typed-enum wire round-trips.
1580 ///
1581 /// Same closed-set-reverse-projection discipline the sibling
1582 /// [`RestartStrategy::from_wire`] (4eec29c) /
1583 /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
1584 /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
1585 /// [`crate::aplicacao::RateLimitUnit::from_suffix`] typed enums
1586 /// carry on the peer wire-side `str → Self` axes — extended onto
1587 /// the M2 OTP-shape per-child restart-policy closed-set axis, the
1588 /// sixth substrate-side closed-set typed enum (and the third and
1589 /// final OTP-shape closed-enum discriminator axis) to converge on
1590 /// the two-way `str ↔ Self` round-trip. Method-named `from_wire`
1591 /// (not `from_str`) to match the peer [`RestartStrategy::from_wire`]
1592 /// shape verbatim and side-step the [`std::str::FromStr`] impl the
1593 /// derive already installs on the sibling kebab-case axis. Returns
1594 /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
1595 /// shapes: the caller picks the diagnostic form appropriate for
1596 /// its use site.
1597 #[must_use]
1598 pub fn from_wire(s: &str) -> Option<Self> {
1599 match s {
1600 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT => Some(Self::Permanent),
1601 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY => Some(Self::Temporary),
1602 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT => Some(Self::Transient),
1603 _ => None,
1604 }
1605 }
1606}
1607
1608/// [`std::fmt::Display`] routed through [`RestartPolicy::as_str`], so the
1609/// pretty-printed byte-string every consumer that formats the policy as
1610/// user-facing text lands on (the future wasm-operator's per-child
1611/// post-exit restart-decision diagnostic line, the future `feira app
1612/// graph` per-child restart column, the future M4
1613/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1614/// admission-webhook rejection body) reaches for the same lifted
1615/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1616/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1617/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1618/// wire-format `Serialize` derive already emits under
1619/// [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
1620/// [`RestartPolicy::as_str`] helper already returns.
1621///
1622/// Pre-convergence the two paths structurally disagreed — the
1623/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
1624/// route (now retired here) sent [`std::fmt::Display`] through the
1625/// gen-platform discriminant catalog string, which arrives kebab-case as
1626/// `"permanent"` / `"temporary"` / `"transient"` on this three-arm enum
1627/// (whose variant names each collapse to their own lowercase form under
1628/// the kebab-case transform), while the wire format ran as `PascalCase`
1629/// `"Permanent"` / `"Temporary"` / `"Transient"` through the un-`rename`d
1630/// serde derive. Every consumer that formatted the policy for a
1631/// diagnostic line, a graph column, or a rejection body under
1632/// `format!("{v}")` therefore landed under a different byte-string than
1633/// the wire format the operator's per-child-policy dispatch keyed off —
1634/// a silent split whose apply-time symptom (a `format!("{v}")`-carrying
1635/// diagnostic quoting `"permanent"` while the wire scalar the operator
1636/// probed was `"Permanent"`) surfaced as a confused correlate at
1637/// operator-log time far from the two-declaration site.
1638///
1639/// Routing `Display` through [`RestartPolicy::as_str`] closes the third
1640/// path: every `format!("{v}")` call reaches the same lifted
1641/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the wire format
1642/// and the [`RestartPolicy::as_str`] helper route through — `Debug` (the
1643/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
1644/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
1645/// byte-string per variant. A future variant rename or
1646/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
1647/// exactly one place, structurally.
1648///
1649/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
1650/// (from `#[derive(gen_platform::Discriminant)]`) still returns
1651/// `"permanent"` / `"temporary"` / `"transient"`, and the fleet-wide
1652/// [`gen_platform::register_dispatcher!("caixa.restart-policy", …)`]
1653/// registration keys the catalog off the same kebab identity. The two
1654/// naming worlds now live on separate typed methods (`Display` /
1655/// `as_str` for the wire byte-string, `discriminant` for the catalog
1656/// identity) rather than sharing one `Display` route that structurally
1657/// disagrees with the wire format.
1658///
1659/// Pin tests
1660/// [`tests::restart_policy_display_routes_through_as_str_helper`]
1661/// and
1662/// [`tests::restart_policy_display_matches_serialized_wire_byte_string`]
1663/// assert the three paths agree byte-for-byte on every variant, so a
1664/// future variant rename or per-arm serde attribute drift is a build
1665/// error visible at caixa-core test time, not a silent per-consumer
1666/// dispatch miss at apply / reconcile time.
1667///
1668/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
1669/// (aplicacao.rs:2306) on the per-Aplicacao distribution-strategy axis
1670/// and the sibling [`RestartStrategy`] `Display` impl on the
1671/// per-supervisor sibling-restart-strategy axis — same three-path-
1672/// convergence discipline, extended to close the third and final of
1673/// three OTP-shaped closed-enum discriminator axes on the caixa typed
1674/// surface.
1675impl std::fmt::Display for RestartPolicy {
1676 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1677 f.write_str(self.as_str())
1678 }
1679}
1680
1681/// Substrate-canonical [`AsRef<str>`] projection on the M2
1682/// per-child-restart-policy [`RestartPolicy`] closed-set typed enum —
1683/// routes through the same [`RestartPolicy::as_str`] `pub const fn`
1684/// scalar accessor the paired [`std::fmt::Display`] impl and the
1685/// un-`rename`d [`serde::Serialize`] derive already key off, so any
1686/// future consumer that binds a [`RestartPolicy`] through the
1687/// standard-library `impl AsRef<str>` bound (a future
1688/// [`caixa-feira`] `feira supervisor --restart <arm>` verb that
1689/// composes the emitted `PascalCase` wire scalar into a
1690/// [`std::process::Command::arg`] shell-out of the future
1691/// wasm-operator's per-child admission gate, a per-child structured-
1692/// log recorder on the future `caixa-operator`'s hierarchical
1693/// reconciliation surface that accepts `impl AsRef<str>` at the
1694/// `tracing::field::Value` `Str`-arm, a [`std::collections::HashMap`]
1695/// lookup keyed on the restart-policy wire byte through
1696/// `map.get::<str>(policy.as_ref())` on a future per-policy
1697/// dispatch table) reaches the paired
1698/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1699/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1700/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
1701/// lifted-const through one substrate-primitive dispatch rather
1702/// than an open-coded `.as_str()` projection at every wire-up.
1703///
1704/// Peer of the sibling [`std::fmt::Display`] impl on the same
1705/// primitive — both delegate to the shared [`RestartPolicy::as_str`]
1706/// `pub const fn` accessor, so [`format!("{v}")`], `v.as_str()`, and
1707/// `<RestartPolicy as AsRef<str>>::as_ref(&v)` resolve to the same
1708/// byte-string per instance by construction. A future variant rename
1709/// or `#[serde(rename_all = "kebab-case")]` attribute-drift on the
1710/// enum reaches every one of the three paths (plus the wire-format
1711/// `Serialize` derive that already routes through the same lifted
1712/// const) through exactly one caixa-core edit.
1713///
1714/// Same "route the trait impl through the substrate-primitive
1715/// accessor" discipline the sibling [`crate::CaixaVersion`]
1716/// [`AsRef<str>`] impl (16d5c7e) and the paired M2
1717/// [`RestartStrategy`] [`AsRef<str>`] impl (63eb1a4) carry — extends
1718/// the axis onto the paired per-child-restart-decision-policy
1719/// sibling on the same M2 `:supervisor` slot (the second M2
1720/// OTP-shape closed-set typed enum to converge onto the standard-
1721/// library [`AsRef<str>`] projection). Rust-side newtype/typed-enum
1722/// convention pairs [`AsRef<str>`] and [`fmt::Display`] on the same
1723/// primitive so a caller who has one has both; before this lift,
1724/// [`RestartPolicy`] carried [`fmt::Display`] but not the paired
1725/// [`AsRef<str>`] impl the convention names.
1726///
1727/// Pinned load-bearing by
1728/// [`tests::restart_policy_as_ref_str_routes_through_as_str_accessor`]
1729/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1730/// three-arm closed set) and
1731/// [`tests::restart_policy_as_ref_str_routes_through_display_via_shared_accessor`]
1732/// (three-path convergence: `AsRef<str>` + `Display` + `as_str` all
1733/// resolve to the same lifted `SUPERVISOR_CHILD_RESTART_*` const per
1734/// arm) — any future silent detour that routes the impl through a
1735/// divergent projection (a per-arm inline `match self { … }`
1736/// re-inlining that opens a compile-time link to the un-lifted
1737/// arm-literal, a swap onto the kebab-case
1738/// [`gen_platform::Discriminant`] catalog identity that would
1739/// collide the wire axis with the dispatcher-catalog axis) trips at
1740/// caixa-core test time under `assert_eq!` rather than at a
1741/// downstream `impl AsRef<str>`-bound consumer's silent split.
1742impl AsRef<str> for RestartPolicy {
1743 fn as_ref(&self) -> &str {
1744 self.as_str()
1745 }
1746}
1747
1748/// Trait-idiomatic reverse projection on the M2-OTP-shape per-child
1749/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
1750/// byte-for-byte through the paired substrate-primitive
1751/// [`RestartPolicy::from_wire`] `Option<Self>` accessor so every future
1752/// consumer that binds a `PascalCase` `:children :restart` wire
1753/// byte-string through the standard-library `.try_into()` / [`TryFrom`]
1754/// axis (a future [`caixa-feira`] `feira supervisor --restart
1755/// <Permanent|Temporary|Transient>` CLI arg-parse that composes into
1756/// `let restart: RestartPolicy = s.try_into()?`, a future
1757/// `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook that folds a
1758/// `spec.children[*].restart: String` field through
1759/// `RestartPolicy::try_from(&s)?`, a generic
1760/// `<T: TryFrom<&str>>`-bound loader over any of the substrate's closed-
1761/// set typed enums) reaches the same three-arm accept-set the sibling
1762/// [`RestartPolicy::from_wire`] resolver parses through and the sibling
1763/// [`RestartPolicy::as_str`] emits, rather than an open-coded per-arm
1764/// `match s { "Permanent" => …, "Temporary" => …, "Transient" => …, _ =>
1765/// … }` cascade whose arm-set has no compile-time link back to the
1766/// substrate primitive.
1767///
1768/// Complements the pre-existing forward-projection triple
1769/// ([`std::fmt::Display`], [`AsRef<str>`], [`RestartPolicy::as_str`])
1770/// with the paired trait-idiomatic reverse-projection axis: Rust-side
1771/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
1772/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so a
1773/// caller who can project *out to* a `&str` can also project *in from*
1774/// one. The [`TryFrom<&str>`] axis is deliberately chosen over
1775/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
1776/// lint the sibling method-named [`RestartPolicy::from_wire`] would
1777/// trigger under a `FromStr` impl and to avoid colliding with the
1778/// [`std::str::FromStr`] impl the [`gen_platform::FromStrKind`] derive
1779/// already installs on the paired *kebab-case dispatcher-catalog* axis
1780/// (which parses `"permanent"` / `"temporary"` / `"transient"`, the
1781/// inverse of [`Self::discriminant`]) — this impl closes the trait-
1782/// idiomatic reverse axis on the *`PascalCase` wire* half without
1783/// disturbing either the method-named `from_wire` shape every sibling
1784/// closed-set typed enum on the substrate already carries or the
1785/// pre-existing `FromStr` on the dispatcher-catalog half, keeping the
1786/// two-axis split the sibling [`Self::from_wire`] doc block motivates.
1787///
1788/// `type Error = ()` matches the sibling [`RestartPolicy::from_wire`]'s
1789/// `Option<Self>` return-shape's deliberate deferral of error typing: the
1790/// caller picks the diagnostic form appropriate for its use site (a
1791/// future `feira supervisor --restart` arg-parse composes its own
1792/// per-verb "unknown restart: <arg> — accepted: {…}" message enumerating
1793/// [`RestartPolicy::ALL`], a future M4 admission-webhook rejection body
1794/// wraps the `Err(())` outcome with the accepted-set enumeration for
1795/// operator diagnostics, a `Result::map_err` at the call site lifts the
1796/// unit-error to a per-verb error type). Same shape the peer
1797/// [`RestartStrategy`] (5b828ed) on the sibling per-supervisor axis,
1798/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136), and
1799/// [`crate::aplicacao::PlacementStrategy`] (6fd00cd) blocks motivate on
1800/// their peer closed-set typed enums' reverse projections.
1801///
1802/// The paired [`TryFrom<&str>`] impl reaches the same three-arm accept-
1803/// set the [`RestartPolicy::from_wire`] resolver dispatches through, so
1804/// any future arm addition (an OTP-`intrinsic` fourth arm the theory
1805/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1806/// might reach for once the three canonical OTP restart policies stop
1807/// covering the substrate's discovered load-shape) grows the trait-
1808/// idiomatic axis by construction — one caixa-core edit on
1809/// [`RestartPolicy::from_wire`] extends both the method-named reverse
1810/// projection every existing consumer keys off and the trait-idiomatic
1811/// reverse projection this impl exposes, without a coordinated rewrite
1812/// across every future `TryFrom<&str>`-bound consumer's arm-set.
1813///
1814/// Extends the substrate-wide closed-set-enum reverse-projection family
1815/// ([`crate::CaixaKind`] via 3c83606, [`crate::CaixaDialeto`] via
1816/// bf33136, [`crate::aplicacao::PlacementStrategy`] via 6fd00cd, and
1817/// [`RestartStrategy`] via 5b828ed) onto the third and final OTP-shape
1818/// closed-enum discriminator axis on the caixa surface — the paired
1819/// per-child `:children :restart` closed set the future wasm-operator's
1820/// hierarchical reconciliation scheduler's per-child post-exit
1821/// restart-decision branch keys off end-to-end.
1822///
1823/// Pinned load-bearing by
1824/// [`tests::restart_policy_try_from_str_routes_through_from_wire_accessor`]
1825/// (byte-parity pin against [`RestartPolicy::from_wire`] across the
1826/// three-arm accept-set),
1827/// [`tests::restart_policy_try_from_str_rejects_unknown_byte_strings`]
1828/// (rejection witness against silent accept-set widening), and
1829/// [`tests::restart_policy_try_from_str_and_from_wire_partition_the_accept_set`]
1830/// (cross-axis partition pin locking the trait and method-named
1831/// projections onto one accept-set).
1832impl TryFrom<&str> for RestartPolicy {
1833 type Error = ();
1834
1835 fn try_from(s: &str) -> Result<Self, Self::Error> {
1836 Self::from_wire(s).ok_or(())
1837 }
1838}
1839
1840/// Trait-idiomatic forward projection on the M2-OTP-shape per-child
1841/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
1842/// byte-for-byte through the paired substrate-primitive
1843/// [`RestartPolicy::as_str`] `pub const fn` accessor. Return type is
1844/// `&'static str` by construction — every [`RestartPolicy::as_str`] arm
1845/// resolves to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const
1846/// &str` with `'static` lifetime, so the trait's return-type promise is
1847/// upheld structurally without a [`String::leak`] cast or a per-arm inline
1848/// literal.
1849///
1850/// Every future consumer that specifically needs `&'static str` lifetime
1851/// bytes on the per-child restart-decision axis (a
1852/// [`tracing::field::valuable::Value::Str`] recording where the `Str`
1853/// arm's typing demands `&'static str`, a
1854/// [`std::borrow::Cow::Borrowed`]`::<'static, str>(policy.into())` composer
1855/// on the future M4 admission-webhook rejection body where the
1856/// `Cow<'static, str>` typing rules out the sibling [`AsRef<str>`]
1857/// borrowed return, a generic `<T: Into<&'static str>>`-bound serializer
1858/// or error formatter that requires the `'static` bound) reaches the same
1859/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1860/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1861/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] substrate-
1862/// primitive dispatch rather than an open-coded per-arm literal cascade
1863/// whose arm-set has no compile-time link back to the substrate primitive.
1864///
1865/// Peer of the sibling M2-OTP-shape [`RestartStrategy`] forward-projection
1866/// impl (523157d) on the per-supervisor sibling-restart-strategy axis —
1867/// the second (and second-of-two-in-M2) closed-set typed enum on the
1868/// caixa surface to converge onto the paired trait-idiomatic forward-
1869/// projection axis. With this lift the paired per-child
1870/// `:children :restart` closed-set typed enum carries the full sibling
1871/// quintet ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
1872/// [`TryFrom<&str>`] via 6fdd0d9, `From<Self> for &'static str` via this
1873/// lift) plus the round-trip witness through both the trait-idiomatic
1874/// (`From<Self> for &'static str` + `TryFrom<&str>`) and the method-named
1875/// (`as_str` + `from_wire`) axis pairs — mirrors the sibling
1876/// [`RestartStrategy`] surface arm-for-arm, so every future arm addition
1877/// (an OTP-`intrinsic` fourth arm the theory
1878/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1879/// might reach for once the three canonical OTP restart policies stop
1880/// covering the substrate's discovered load-shape) grows the trait-
1881/// idiomatic forward axis by construction: one caixa-core edit on
1882/// [`RestartPolicy::as_str`] extends every one of the five sibling
1883/// forward-projection paths ([`std::fmt::Display`], [`AsRef<str>`],
1884/// [`Self::as_str`] itself, this `From<Self> for &'static str`, and the
1885/// un-`rename`d [`serde::Serialize`] derive that also emits `as_str`'s
1886/// bytes) without a coordinated rewrite across every future
1887/// `Into<&'static str>`-bound consumer's arm-set.
1888///
1889/// Pinned load-bearing by
1890/// [`tests::restart_policy_from_into_static_str_routes_through_as_str_accessor`]
1891/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1892/// three-arm emit-set, plus a `const`-context materialization witness for
1893/// the `&'static str` lifetime promise) and
1894/// [`tests::restart_policy_from_into_static_str_and_as_str_partition_the_emit_set`]
1895/// (partition pin asserting `<&'static str as From<RestartPolicy>>::from`
1896/// and [`RestartPolicy::as_str`] agree on every arm, plus a two-way
1897/// round-trip witness through the paired trait-idiomatic reverse-
1898/// projection axis [`TryFrom<&str>`] (6fdd0d9): every
1899/// `policy.into::<&'static str>()` output re-parses back through
1900/// [`RestartPolicy::try_from`] to the original variant, closing the two-
1901/// way `Self ↔ &'static str` round-trip on the trait-idiomatic axis pair).
1902impl From<RestartPolicy> for &'static str {
1903 fn from(policy: RestartPolicy) -> &'static str {
1904 policy.as_str()
1905 }
1906}
1907
1908/// Trait-idiomatic *forward* projection on [`RestartPolicy`] from a
1909/// *borrowed* input onto the `&'static str` axis — the borrowed-input
1910/// companion to the paired owned-input [`From<RestartPolicy> for
1911/// &'static str`] impl immediately above. Routes byte-for-byte through
1912/// the same substrate-primitive [`RestartPolicy::as_str`] `pub const
1913/// fn` accessor so every consumer that binds a `&RestartPolicy`
1914/// through the standard-library `.into()` / [`From<&Self> for &'static
1915/// str`] axis (a `RestartPolicy::ALL.iter().map(<&'static
1916/// str>::from).collect::<Vec<_>>()` per-arm accept-set materializer —
1917/// whose iterator over `&'static [RestartPolicy]` yields
1918/// `&RestartPolicy`, not `RestartPolicy`, so the owned-input
1919/// [`From<RestartPolicy>`] axis alone forces every call site through
1920/// an explicit `.copied()` / dereference / [`Copy`]-bound restatement
1921/// rather than the direct trait-idiomatic projection; a future generic
1922/// `<T: Copy + for<'a> Into<&'static str>>`-bound diagnostic column
1923/// that walks the `iter().map(Into::into)` shape verbatim across every
1924/// substrate-wide closed-set typed enum; the future wasm-operator's
1925/// per-child post-exit restart-decision diagnostic line that composes
1926/// the accepted-set enumeration from an iterated
1927/// `RestartPolicy::ALL.iter().map(|p| p.into())` pipe rather than a
1928/// per-arm `match p { … }` cascade; a future
1929/// `HashMap::<&'static str, RestartPolicy>::from_iter(
1930/// RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
1931/// per-policy reverse-lookup table the sibling [`TryFrom<&str>`] impl
1932/// cannot compose without this borrowed-input axis in place) reaches
1933/// the same three-arm lifted
1934/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1935/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1936/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1937/// paired owned-input [`From<RestartPolicy> for &'static str`], the
1938/// sibling [`std::fmt::Display`], [`AsRef<str>`], and
1939/// [`RestartPolicy::as_str`] surfaces already return.
1940///
1941/// Fifth peer on the substrate-wide trait-idiomatic *borrowed-input*
1942/// forward-projection family opened on [`crate::dep::DepList`]
1943/// (64aa742) and extended onto [`crate::CaixaKind`] (5ab993a),
1944/// [`crate::CaixaDialeto`] (807b0b5), and the paired
1945/// per-supervisor sibling-restart-strategy [`RestartStrategy`]
1946/// (e941836). Rust's `From` trait does not auto-derive the
1947/// `From<&Self>` sibling from a `From<Self>` impl (the blanket
1948/// `impl<T, U> From<&T> for U where T: Copy, U: From<T>` does not
1949/// exist in `core`), so every closed-set typed enum that carries the
1950/// owned-input axis but not the borrowed-input axis forces every
1951/// borrowed-input call site through a `.copied()` /
1952/// `<&'static str>::from(*policy)` / `policy.as_str()` detour whose
1953/// type bounds have no compile-time link to the substrate primitive.
1954/// [`RestartPolicy`] is the second (and second-of-two-in-M2)
1955/// OTP-shape peer to converge onto this campaign — sibling of the
1956/// paired per-supervisor [`RestartStrategy`] borrowed-input axis, so
1957/// with this lift both closed-set typed enums on the M2 `:supervisor`
1958/// slot now carry the full sibling quintet ([`std::fmt::Display`],
1959/// [`AsRef<str>`], [`Self::as_str`], `From<Self> for &'static str`,
1960/// `From<&Self> for &'static str`) plus the paired trait-idiomatic
1961/// reverse projection [`TryFrom<&str>`], closing the borrowed-input
1962/// forward-projection axis on the M2 OTP-shape slot as a unit.
1963///
1964/// Same three-path convergence discipline as the paired owned-input
1965/// impl (this borrowed-input axis, the paired owned-input
1966/// [`From<RestartPolicy> for &'static str`], and
1967/// [`RestartPolicy::as_str`] all route through the same lifted
1968/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const), so a future
1969/// variant rename or per-arm serde-attribute drift reaches every one
1970/// of the six sibling forward-projection paths
1971/// ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
1972/// [`From<Self> for &'static str`], this [`From<&Self> for &'static
1973/// str`], and the un-`rename`d [`serde::Serialize`] derive that also
1974/// emits [`Self::as_str`]'s bytes) through exactly one caixa-core
1975/// edit.
1976///
1977/// The [`RestartPolicy::as_str`] emit and [`RestartPolicy::from_wire`]
1978/// parse share the same `PascalCase` vocabulary by construction, so
1979/// the borrowed-input forward axis and the reverse axis compose
1980/// directly — the round-trip witness pin below locks this direct
1981/// composition without the intermediate wire-vocab hop the peer
1982/// [`crate::CaixaKind`] axis pair requires.
1983///
1984/// Pinned load-bearing by
1985/// [`tests::restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
1986/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1987/// three-arm emit-set via a borrowed input, plus a `const`-context
1988/// materialization witness for the `&'static str` lifetime promise,
1989/// plus a blanket `.into()` shape) and
1990/// [`tests::restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
1991/// (cross-axis partition pin against the paired owned-input
1992/// [`From<RestartPolicy> for &'static str`] impl, plus a
1993/// `.iter().map(Into::into)` pipe witness over
1994/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
1995/// [`TryFrom<&str>`] that closes the two-way `&Self → &'static str →
1996/// Self` round-trip without the wire-vocab intermediate the peer
1997/// [`crate::CaixaKind`] axis pair requires).
1998impl From<&RestartPolicy> for &'static str {
1999 fn from(policy: &RestartPolicy) -> &'static str {
2000 policy.as_str()
2001 }
2002}
2003
2004/// Trait-idiomatic *owned-`String`* forward projection on the second
2005/// M2 OTP-shape closed-set typed enum ([`RestartPolicy`]) — the
2006/// owned-heap-string companion to the paired `&'static str`-returning
2007/// [`From<RestartPolicy> for &'static str`] / [`From<&RestartPolicy>
2008/// for &'static str`] impls immediately above. Routes byte-for-byte
2009/// through the substrate-primitive [`RestartPolicy::as_str`] `pub
2010/// const fn` accessor (via [`str::to_owned`]) so every consumer that
2011/// binds a [`RestartPolicy`] through the standard-library `.into()` /
2012/// [`From<Self> for String`] (equivalently [`Into<String>`]) axis — a
2013/// future `serde_json::Value::String(policy.into())` structured-payload
2014/// composer where the `Value::String` arm typing demands an owned
2015/// [`String`] and the sibling [`&'static str`]-returning axis forces
2016/// an explicit `.to_owned()` / `String::from` restatement at every
2017/// call site, a future `HashMap::<String, RestartPolicy>::from_iter(
2018/// RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))` per-policy
2019/// lookup where the map's key type is owned [`String`] rather than
2020/// [`&'static str`], a future `Cow::<'static, str>::Owned(policy.into())`
2021/// composer on the future M4 admission-webhook rejection body's
2022/// owned-arm, the future wasm-operator's per-child post-exit
2023/// diagnostic emit `serde_json::json!({ "restart": policy })` where the
2024/// JSON serializer's `Serialize` impl on [`String`] owns the emit-path
2025/// — reaches the same three-arm lifted
2026/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2027/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2028/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2029/// paired [`std::fmt::Display`], [`AsRef<str>`],
2030/// [`RestartPolicy::as_str`], and the two `&'static str`-returning
2031/// forward-projection impls already return.
2032///
2033/// Extends the trait-idiomatic *owned-`String`* forward-projection
2034/// axis onto the second-of-two M2 OTP-shape closed-set typed enums on
2035/// the caixa surface — mirror of the first-mover
2036/// [`From<RestartStrategy> for String`] (7baa18a) that opened this
2037/// axis on the sibling supervisor-level strategy enum. Rust's standard
2038/// library does not carry a blanket `impl<T: AsRef<str>> From<T> for
2039/// String` (nor an `impl<T: fmt::Display> From<T> for String`), so
2040/// every closed-set typed enum that carries the paired `AsRef<str>` /
2041/// `Display` / `From<Self> for &'static str` triple but not the
2042/// owned-[`String`] axis forces every owned-string call site through a
2043/// `.to_string()` / `.as_str().to_owned()` / `String::from(policy.as_str())`
2044/// detour whose type bounds have no compile-time link to the
2045/// substrate primitive.
2046///
2047/// Deliberately routes through the human-readable
2048/// [`RestartPolicy::as_str`] axis — for this enum the wire format
2049/// (`PascalCase`, tatara-lisp author surface `:restart Permanent`) and
2050/// the diagnostic byte-string share the same vocabulary by
2051/// construction (unlike the sibling [`crate::CaixaKind`] enum whose
2052/// two axes diverge), so the owned-[`String`] projection lands
2053/// byte-identically on both the wire vocabulary the paired
2054/// [`serde::Serialize`] derive emits and the diagnostic vocabulary the
2055/// [`RestartPolicy::as_str`] helper returns, and — because the paired
2056/// [`TryFrom<&str>`] / [`RestartPolicy::from_wire`] reverse-projection
2057/// axis parses the same `PascalCase` vocabulary — the direct two-way
2058/// `Self → String → Self` round-trip composes without the wire-vocab
2059/// intermediate hop the peer [`crate::CaixaKind`] owned-[`String`]
2060/// axis pair requires.
2061///
2062/// Pinned load-bearing by
2063/// [`tests::restart_policy_from_into_owned_string_routes_through_as_str_accessor`]
2064/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2065/// three-arm emit-set, plus a blanket `.into::<String>()` shape
2066/// witness) and
2067/// [`tests::restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm`]
2068/// (cross-axis partition pin against the paired owned-input
2069/// [`From<RestartPolicy> for &'static str`] impl and the sibling
2070/// [`ToString::to_string`] surface routed through [`std::fmt::Display`],
2071/// plus a `.iter().copied().map(String::from)` pipe witness over
2072/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
2073/// [`TryFrom<&str>`] on the owned-[`String`]'s [`String::as_str`]
2074/// borrow that closes the two-way `Self → String → Self` round-trip
2075/// on the trait-idiomatic owned-[`String`] forward + reverse axis
2076/// pair).
2077impl From<RestartPolicy> for String {
2078 fn from(policy: RestartPolicy) -> String {
2079 policy.as_str().to_owned()
2080 }
2081}
2082
2083/// Trait-idiomatic *borrowed-input, owned-`String` output* forward
2084/// projection on the second-of-two M2 OTP-shape closed-set typed enum
2085/// ([`RestartPolicy`]) — the fourth (and closing) corner of the
2086/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
2087/// projection family on this enum, mirror of the first-mover
2088/// [`From<&RestartStrategy> for String`] (579385f) that opened the
2089/// 2×2-completion corner on the sibling supervisor-level strategy
2090/// enum. Routes byte-for-byte through the substrate-primitive
2091/// [`RestartPolicy::as_str`] `pub const fn` accessor (via
2092/// [`str::to_owned`]) so every consumer that holds a borrowed
2093/// [`&RestartPolicy`] and needs an owned [`String`] — a future
2094/// `serde_json::Value::String(String::from(&policy))` structured-payload
2095/// composer over a borrowed field, a future `Iterator::map` over
2096/// `&[RestartPolicy]` that projects to owned keys through
2097/// `.iter().map(String::from)`, a future `HashMap::<String,
2098/// RestartPolicy>::from_iter` that keys off a borrowed-iteration axis
2099/// where dereferencing the policy would force an unnecessary `Copy` at
2100/// every step, the future wasm-operator's per-supervisor
2101/// `child_policies.iter().map(String::from).collect()` per-child post-
2102/// exit restart-decision diagnostic emit whose iteration axis is
2103/// borrowed by construction — reaches the same three-arm lifted
2104/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2105/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2106/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2107/// paired [`std::fmt::Display`], [`AsRef<str>`],
2108/// [`RestartPolicy::as_str`], and the three other trait-idiomatic
2109/// forward-projection impls
2110/// ([`From<RestartPolicy> for &'static str`],
2111/// [`From<&RestartPolicy> for &'static str`],
2112/// [`From<RestartPolicy> for String`]) already return.
2113///
2114/// Second peer on the substrate-wide trait-idiomatic *borrowed-input,
2115/// owned-`String` output* forward-projection family opened on
2116/// [`crate::supervisor::RestartStrategy`] (579385f) — closes the
2117/// `{Self, &Self} × {&'static str, String}` 2×2 projection corner on
2118/// both M2 OTP-shape sibling peers (the paired supervisor-level
2119/// sibling-restart-strategy axis and the per-child restart-decision-
2120/// policy axis), so the whole M2 OTP-shape axis pair now carries the
2121/// full four-corner family by construction. Rust's standard library
2122/// does not carry a blanket `impl<T: AsRef<str>> From<&T> for String`
2123/// (nor an `impl<T: fmt::Display> From<&T> for String`), so every
2124/// closed-set typed enum that carries the paired `AsRef<str>` /
2125/// `Display` / `From<Self> for &'static str` / `From<&Self> for
2126/// &'static str` / `From<Self> for String` quintuple but not the
2127/// borrowed-input owned-[`String`] axis forces every borrowed-input
2128/// owned-string call site through a `policy.as_str().to_owned()` /
2129/// `String::from(*policy)` (with a spurious `Copy`) /
2130/// `policy.to_string()` (through `Display`) detour whose type bounds
2131/// have no compile-time link to the substrate primitive.
2132///
2133/// Deliberately routes through the human-readable
2134/// [`RestartPolicy::as_str`] axis — for this enum the wire format
2135/// (`PascalCase`, tatara-lisp author surface `:restart Permanent`) and
2136/// the diagnostic byte-string share the same vocabulary by
2137/// construction (unlike the sibling [`crate::CaixaKind`] enum whose
2138/// two axes diverge), so the borrowed-input owned-[`String`]
2139/// projection lands byte-identically on both the wire vocabulary the
2140/// paired [`serde::Serialize`] derive emits and the diagnostic
2141/// vocabulary the [`RestartPolicy::as_str`] helper returns, and —
2142/// because the paired [`TryFrom<&str>`] / [`RestartPolicy::from_wire`]
2143/// reverse-projection axis parses the same `PascalCase` vocabulary —
2144/// the direct two-way `&Self → String → Self` round-trip composes
2145/// without the wire-vocab intermediate hop the peer
2146/// [`crate::CaixaKind`] axis pair requires.
2147///
2148/// The remaining thirteen closed-set typed enums on the caixa
2149/// substrate surface (`CaixaKind`, `CaixaDialeto`, `DepList`,
2150/// `PlacementStrategy`, `WitShape`, `RateLimitUnit`,
2151/// `PathShapeViolation`, `InvariantKind`, `ArchVerdict`, `Severity`,
2152/// `FixSafety`, `Semantic`, `FerriteRuntime`) are the future targets
2153/// of this 2×2-completion campaign — each carries the same paired
2154/// quintuple that this borrowed-input owned-[`String`] axis extends
2155/// onto.
2156///
2157/// Pinned load-bearing by
2158/// [`tests::restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
2159/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2160/// three-arm emit-set through the borrowed-input surface) and
2161/// [`tests::restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
2162/// (cross-axis partition pin against the paired owned-input owned-
2163/// [`String`] [`From<RestartPolicy> for String`] impl, the paired
2164/// borrowed-input owned-[`&'static str`] [`From<&RestartPolicy> for
2165/// &'static str`] impl, and the sibling [`ToString::to_string`]
2166/// surface routed through [`std::fmt::Display`], plus a direct round-
2167/// trip witness through [`TryFrom<&str>`] on the owned-[`String`]'s
2168/// [`String::as_str`] borrow that closes the two-way
2169/// `&Self → String → Self` round-trip on the trait-idiomatic
2170/// borrowed-input owned-[`String`] forward + reverse axis pair).
2171impl From<&RestartPolicy> for String {
2172 fn from(policy: &RestartPolicy) -> String {
2173 policy.as_str().to_owned()
2174 }
2175}
2176
2177/// Trait-idiomatic *owned-input, [`std::borrow::Cow<'static, str>`]
2178/// output* forward projection on the M2 OTP-shape per-child-restart
2179/// [`RestartPolicy`] closed-set typed enum — extends the substrate-
2180/// wide [`std::borrow::Cow<'static, str>`] forward-projection family
2181/// opened on [`crate::CaixaKind`] (99c1735 owned-input, d45c409
2182/// borrowed-input) and first extended off it onto the sibling M2
2183/// OTP-shape sibling-restart [`RestartStrategy`] (7dd28b3 owned-input,
2184/// 9b3e4b3 borrowed-input) onto the second (and second-of-two-in-M2)
2185/// M2 OTP-shape closed-set fieldless typed enum peer on the caixa
2186/// surface (`:children :restart`). Routes byte-for-byte through the
2187/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2188/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
2189/// that binds a [`RestartPolicy`] through the trait-idiomatic
2190/// [`std::borrow::Cow<'static, str>`] axis — a future
2191/// `axum::response::IntoResponse` composer whose per-policy
2192/// diagnostic-body typing rules out the sibling [`AsRef<str>`]
2193/// borrowed return, a future M4 admission-webhook rejection body
2194/// that composes the accepted-policy enumeration through the same
2195/// `RestartPolicy::ALL.iter().map(Cow::from)` shape [`crate::CaixaKind`]
2196/// and [`RestartStrategy`] already route through, a generic `<T: for<'a>
2197/// Into<std::borrow::Cow<'static, str>>>`-bound structured-log
2198/// emitter on a per-child-policy diagnostic column — reaches the same
2199/// three-arm lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`]
2200/// / [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2201/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2202/// paired [`std::fmt::Display`], [`AsRef<str>`],
2203/// [`RestartPolicy::as_str`], and the four
2204/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
2205/// forward-projection corners already return.
2206///
2207/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
2208/// [`std::borrow::Cow::Owned`] — the substrate-primitive
2209/// [`RestartPolicy::as_str`] accessor's return carries the `&'static
2210/// str` lifetime by construction (each `match` arm resolves to a
2211/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const &str`
2212/// with static lifetime), so the zero-alloc borrowed arm is the
2213/// type-correct projection with no runtime allocation.
2214///
2215/// Rust's standard library carries no blanket `impl<T: AsRef<str>>
2216/// From<T> for Cow<'static, str>` (nor an `impl<T: fmt::Display>
2217/// From<T> for Cow<'static, str>`), so the paired sibling
2218/// [`From<RestartPolicy> for &'static str`] (9fb37d0),
2219/// [`From<RestartPolicy> for String`] (7851725), [`AsRef<str>`], and
2220/// [`std::fmt::Display`] surfaces do not implicitly extend to a
2221/// [`Cow<'static, str>`]-bound call site — every such site is forced
2222/// through a `Cow::Borrowed(policy.as_str())` /
2223/// `Cow::Owned(policy.to_string())` open-code whose type bounds have
2224/// no compile-time link back to the substrate primitive until this
2225/// lift.
2226///
2227/// Second peer to extend the substrate-wide trait-idiomatic
2228/// [`std::borrow::Cow<'static, str>`] forward-projection axis off the
2229/// top-level [`crate::CaixaKind`] enum (99c1735 owned-input, d45c409
2230/// borrowed-input) onto the wider substrate — closes the M2 OTP-shape
2231/// tier of the campaign (both sibling peers, `RestartStrategy` and
2232/// `RestartPolicy`, now carry the owned-input Cow<'static, str>
2233/// forward projection) so the remaining eleven peers
2234/// (`PlacementStrategy`, `RateLimitUnit`, `DepList`, `CaixaDialeto`,
2235/// and the outside-`caixa-core` peers `WitShape`, `PathShapeViolation`,
2236/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
2237/// `FerriteRuntime`) are the future targets. Every future arm addition
2238/// (an OTP-`intrinsic` fourth restart policy the ABSORPTION-ROADMAP
2239/// might reach for once the three canonical OTP restart policies stop
2240/// covering the substrate's discovered load-shape) grows the
2241/// Cow<'static, str> axis by construction through one caixa-core edit
2242/// on [`RestartPolicy::as_str`] — rather than a coordinated rewrite
2243/// across every future Cow<'static, str>-bound consumer site.
2244///
2245/// Pinned load-bearing by
2246/// [`tests::restart_policy_from_into_static_cow_str_routes_through_as_str_accessor`]
2247/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
2248/// against [`RestartPolicy::as_str`] across the three-arm
2249/// [`RestartPolicy::ALL`]) and
2250/// [`tests::restart_policy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
2251/// (cross-axis partition pin against the paired [`From<RestartPolicy>
2252/// for &'static str`], [`From<RestartPolicy> for String`], and
2253/// [`ToString`]-through-[`std::fmt::Display`] axes, plus a
2254/// `.iter().copied().map(Cow::from)` pipe witness over
2255/// [`RestartPolicy::ALL`] that materializes the three-arm accept-set
2256/// through the [`Cow<'static, str>`] axis alone and pins the
2257/// zero-alloc discipline on every element).
2258impl From<RestartPolicy> for std::borrow::Cow<'static, str> {
2259 fn from(policy: RestartPolicy) -> std::borrow::Cow<'static, str> {
2260 std::borrow::Cow::Borrowed(policy.as_str())
2261 }
2262}
2263
2264/// Trait-idiomatic *borrowed-input, [`std::borrow::Cow<'static, str>`]
2265/// output* forward projection on the M2 OTP-shape per-child-restart
2266/// [`RestartPolicy`] closed-set typed enum — the borrowed-input
2267/// companion to the paired owned-input
2268/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl
2269/// immediately above (0612398). Routes byte-for-byte through the same
2270/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2271/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
2272/// that holds a `&RestartPolicy` and needs a
2273/// [`std::borrow::Cow<'static, str>`] — a
2274/// `RestartPolicy::ALL.iter().map(std::borrow::Cow::from).collect::<Vec<_>>()`
2275/// per-arm accept-set materializer (whose iterator over
2276/// `&'static [RestartPolicy]` yields `&RestartPolicy`, not
2277/// `RestartPolicy`, so the paired owned-input
2278/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] axis
2279/// alone forces every call site through an explicit `.copied()` /
2280/// dereference / [`Copy`]-bound restatement rather than the direct
2281/// trait-idiomatic projection), a future generic
2282/// `<T: for<'a> Into<std::borrow::Cow<'static, str>>>`-bound emitter
2283/// on a per-child-policy diagnostic column that walks the
2284/// `iter().map(Into::into)` shape verbatim, the future M4 admission-
2285/// webhook rejection body that composes the accepted-policy
2286/// enumeration from an iterated
2287/// `RestartPolicy::ALL.iter().map(|p| p.into())` pipe rather than a
2288/// per-arm `match p { … }` cascade — reaches the same three-arm
2289/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2290/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2291/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2292/// paired [`std::fmt::Display`], [`AsRef<str>`],
2293/// [`RestartPolicy::as_str`], the four
2294/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
2295/// forward-projection corners, and the paired owned-input
2296/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl
2297/// already return.
2298///
2299/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
2300/// [`std::borrow::Cow::Owned`] — the substrate-primitive
2301/// [`RestartPolicy::as_str`] accessor's return carries the
2302/// `&'static str` lifetime by construction (each `match` arm resolves
2303/// to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const &str`
2304/// with static lifetime), so the zero-alloc borrowed arm is the
2305/// type-correct projection with no runtime allocation.
2306///
2307/// Closes the `{Self, &Self}` input-shape corner on the M2 OTP-shape
2308/// per-child-restart [`std::borrow::Cow<'static, str>`] axis opened
2309/// one commit prior (0612398) on the paired owned-input
2310/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl —
2311/// second-of-two-in-M2 closed-set fieldless typed enum peer on the
2312/// caixa surface (paired with the sibling-restart [`RestartStrategy`]
2313/// which carries both {Self, &Self} × Cow<'static, str> corners since
2314/// 7dd28b3 owned-input, 9b3e4b3 borrowed-input), exactly as d45c409
2315/// closed it on the top-level [`crate::CaixaKind`] one commit after
2316/// the owning half (99c1735) landed. This lift closes the whole M2
2317/// OTP-shape tier of the substrate-wide [`Cow<'static, str>`]
2318/// forward-projection campaign on both input-shape corners
2319/// ({Self, &Self}) of both M2 OTP-shape sibling peers
2320/// ([`RestartStrategy`] and [`RestartPolicy`]), so the remaining
2321/// eleven substrate-wide peers (`PlacementStrategy`, `RateLimitUnit`,
2322/// `DepList`, `CaixaDialeto`, `WitShape`, `PathShapeViolation`,
2323/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
2324/// `FerriteRuntime`) become the future targets of the campaign. Rust's
2325/// standard library does not carry a blanket
2326/// `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor an
2327/// `impl<T: fmt::Display> From<&T> for Cow<'static, str>`), so every
2328/// closed-set fieldless typed enum peer on the substrate that carries
2329/// the paired owned-input [`Cow<'static, str>`] axis but not the
2330/// borrowed-input axis forces every borrowed-input
2331/// [`Cow<'static, str>`]-parameterized call site through a spurious
2332/// [`Copy`] deref (`std::borrow::Cow::from(*policy)`) or a
2333/// `std::borrow::Cow::Borrowed(policy.as_str())` open-code whose type
2334/// bounds have no compile-time link to the substrate primitive.
2335///
2336/// Pinned load-bearing by
2337/// [`tests::restart_policy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor`]
2338/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
2339/// against [`RestartPolicy::as_str`] across the three-arm
2340/// [`RestartPolicy::ALL`] through the borrowed-input surface) and
2341/// [`tests::restart_policy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
2342/// (cross-axis partition pin against the paired owned-input
2343/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`], the
2344/// paired borrowed-input owned-`&'static str`
2345/// [`From<&RestartPolicy> for &'static str`], and the paired
2346/// borrowed-input owned-`String` [`From<&RestartPolicy> for String`]
2347/// impls, plus a `.iter().map(std::borrow::Cow::from)` pipe witness
2348/// over [`RestartPolicy::ALL`] — whose iterator yields
2349/// `&RestartPolicy` by construction, so the borrowed-input
2350/// [`Cow<'static, str>`] axis is what routes the pipe through the
2351/// substrate-primitive [`RestartPolicy::as_str`] accessor with the
2352/// zero-alloc [`Cow::Borrowed`] arm by construction and without a
2353/// spurious [`Copy`] deref).
2354impl From<&RestartPolicy> for std::borrow::Cow<'static, str> {
2355 fn from(policy: &RestartPolicy) -> std::borrow::Cow<'static, str> {
2356 std::borrow::Cow::Borrowed(policy.as_str())
2357 }
2358}
2359
2360/// Trait-idiomatic *owned-input, [`Box<str>`] output* forward
2361/// projection on the M2 OTP-shape per-child-restart [`RestartPolicy`]
2362/// closed-set fieldless typed enum — extends the substrate-wide
2363/// `Box<str>` forward-projection campaign tier opened one commit prior
2364/// (69ef45c) on the paired sibling-restart [`RestartStrategy`] onto
2365/// the second (and third-and-final) M2 OTP-shape closed-set fieldless
2366/// typed enum peer on the caixa surface (`:children :restart`),
2367/// immediately after the paired `Cow<'static, str>` axis (0612398 /
2368/// b4dc55c) closed the
2369/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}` 2×3
2370/// corner on this enum. Routes byte-for-byte through the
2371/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2372/// accessor via [`Box::<str>::from`] on the returned `&'static str`,
2373/// so every consumer that binds a
2374/// `let key: Box<str> = policy.into();`-shaped call site — a
2375/// per-child metric-key materializer that stashes the policy
2376/// discriminator in a `Box<str>`-typed heap-owned scalar for cheap
2377/// clone (a shared-nothing per-policy accept-set the `caixa-operator`
2378/// hierarchical reconciliation scheduler's per-child restart-decision
2379/// fan-out carries), a future admission-webhook rejection body whose
2380/// per-arm `Box<str>` field composes from an owned `RestartPolicy`
2381/// handle — reaches the same three-arm lifted
2382/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2383/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2384/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2385/// sibling
2386/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
2387/// forward-projection corner already returns. Rust's standard library
2388/// carries `impl From<&str> for Box<str>` and
2389/// `impl From<String> for Box<str>` but no blanket
2390/// `impl<T: AsRef<str>> From<T> for Box<str>` (nor any
2391/// `impl<T: Copy, U: From<T>> From<T> for U` route from the enum), so
2392/// this axis is a distinct trait-idiomatic surface that a downstream
2393/// `RestartPolicy → Box<str>` `.into()` reaches through this impl and
2394/// no other — without a `Box::from(policy.as_str())` open-code whose
2395/// type bounds have no compile-time link back to the substrate
2396/// primitive.
2397///
2398/// Second peer on the substrate-wide trait-idiomatic [`Box<str>`]
2399/// forward-projection family opened on the sibling-restart
2400/// [`RestartStrategy`] (69ef45c / 59ae5dc) — closes the whole M2
2401/// OTP-shape tier of the substrate-wide [`Box<str>`] forward-
2402/// projection campaign's owned-input corner on both M2 OTP-shape
2403/// sibling peers ([`RestartStrategy`] and [`RestartPolicy`]), the
2404/// paired borrowed-input `From<&RestartPolicy> for Box<str>` closer
2405/// and the remaining fieldless-enum peers on the M3 mesh-shape /
2406/// outside-M3 caixa-core / render-side / outside-caixa-core tiers
2407/// are the future targets of the campaign.
2408///
2409/// Pinned load-bearing by
2410/// [`tests::restart_policy_from_into_box_str_routes_through_as_str_accessor`]
2411/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2412/// three-arm [`RestartPolicy::ALL`] emit-set on the owned-input
2413/// surface, plus a blanket-derived [`Into`] shape witness).
2414impl From<RestartPolicy> for Box<str> {
2415 fn from(policy: RestartPolicy) -> Box<str> {
2416 Box::<str>::from(policy.as_str())
2417 }
2418}
2419
2420/// Trait-idiomatic *borrowed-input, [`Box<str>`] output* forward
2421/// projection on the M2 OTP-shape per-child-restart [`RestartPolicy`]
2422/// closed-set fieldless typed enum — the borrowed-input companion to
2423/// the paired owned-input [`From<RestartPolicy> for Box<str>`] impl
2424/// (0a1b313, one commit prior) that closes the `{Self, &Self}`
2425/// input-shape corner of the substrate-wide [`Box<str>`] forward-
2426/// projection axis on the second (and third-and-final) M2 OTP-shape
2427/// closed-set fieldless typed enum peer on the caixa surface
2428/// (`:children :restart`), routing byte-for-byte through the
2429/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2430/// accessor via [`Box::<str>::from`] on the returned `&'static str`.
2431/// Every consumer that holds a `&RestartPolicy` and needs a
2432/// [`Box<str>`] — a
2433/// `RestartPolicy::ALL.iter().map(Box::<str>::from).collect::<Vec<_>>()`
2434/// per-arm accept-set materializer (whose iterator over
2435/// `&'static [RestartPolicy]` yields `&RestartPolicy`, not
2436/// `RestartPolicy`, so the paired owned-input
2437/// [`From<RestartPolicy> for Box<str>`] axis alone forces every
2438/// call site through an explicit [`Copy`] deref or a
2439/// `.copied()` restatement rather than the direct trait-idiomatic
2440/// projection), a per-child metric-key materializer holding
2441/// `&RestartPolicy` through a `caixa-operator` hierarchical
2442/// reconciliation scheduler's borrow lifetime, a future admission-
2443/// webhook rejection body whose per-arm `Box<str>` field composes
2444/// from a borrowed `&RestartPolicy` handle — reaches the
2445/// substrate-primitive [`RestartPolicy::as_str`] accessor through
2446/// this impl and no other, without a
2447/// `Box::<str>::from(policy.as_str())` open-code whose type bounds
2448/// have no compile-time link back to the substrate primitive.
2449///
2450/// Rust's standard library carries `impl From<&str> for Box<str>`
2451/// and `impl From<String> for Box<str>` but no blanket
2452/// `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
2453/// `Copy`-based `impl<T: Copy, U: From<&T> for U`), so every closed-
2454/// set fieldless typed enum peer on the substrate that carries the
2455/// paired owned-input `Box<str>` axis but not the borrowed-input
2456/// axis forces every borrowed-input `Box<str>`-parameterized call
2457/// site through a spurious [`Copy`] deref
2458/// (`Box::<str>::from((*policy).as_str())`) or a
2459/// `Box::<str>::from(policy.as_str())` open-code whose type bounds
2460/// have no compile-time link back to the substrate primitive.
2461///
2462/// Fourth (and closing) peer on the substrate-wide trait-idiomatic
2463/// [`Box<str>`] forward-projection family on the M2 OTP-shape tier
2464/// — closes the whole `{Self, &Self}` input-shape corner of the
2465/// [`Box<str>`] axis on both M2 OTP-shape sibling peers
2466/// ([`RestartStrategy`] and [`RestartPolicy`]), exactly as b4dc55c
2467/// closed the paired [`Cow<'static, str>`] axis one commit after
2468/// its owning half (0612398) landed on this enum. The remaining
2469/// fieldless-enum peers on the M3 mesh-shape / outside-M3 caixa-
2470/// core / render-side / outside-caixa-core tiers are the future
2471/// targets of the [`Box<str>`] campaign.
2472///
2473/// Pinned load-bearing by
2474/// [`tests::restart_policy_from_borrowed_into_box_str_routes_through_as_str_accessor`]
2475/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2476/// three-arm [`RestartPolicy::ALL`] emit-set on the borrowed-input
2477/// surface, plus a blanket-derived [`Into`] shape witness, a
2478/// cross-axis partition pin against the paired owned-input
2479/// [`From<RestartPolicy> for Box<str>`] and the sibling borrowed-
2480/// input `{&'static str, String, Cow<'static, str>}` return-shape
2481/// axes, and a `.iter().map(Box::<str>::from)` pipe witness over
2482/// [`RestartPolicy::ALL`] — whose iterator yields `&RestartPolicy`
2483/// by construction, so the borrowed-input [`Box<str>`] axis is
2484/// what routes the pipe through the substrate-primitive
2485/// [`RestartPolicy::as_str`] accessor without a spurious [`Copy`]
2486/// deref).
2487impl From<&RestartPolicy> for Box<str> {
2488 fn from(policy: &RestartPolicy) -> Box<str> {
2489 Box::<str>::from(policy.as_str())
2490 }
2491}
2492
2493/// Trait-idiomatic *owned-input, [`std::sync::Arc<str>`] output*
2494/// forward projection on the M2 OTP-shape per-child-restart
2495/// [`RestartPolicy`] closed-set fieldless typed enum — routes byte-
2496/// for-byte through the substrate-primitive [`RestartPolicy::as_str`]
2497/// `pub const fn` accessor via [`std::sync::Arc::<str>::from`] on the
2498/// returned `&'static str`, so every consumer that binds a
2499/// [`RestartPolicy`] through the standard-library `.into()` /
2500/// [`From<Self> for std::sync::Arc<str>`] (equivalently
2501/// [`Into<std::sync::Arc<str>>`]) axis — a future admission-webhook's
2502/// per-request `Sync` + `Send`-safe structured-log field composed
2503/// across an `.await` boundary through a
2504/// `<T: Into<std::sync::Arc<str>>>`-bound diagnostic-column dispatch,
2505/// a future wasm-operator's per-child post-exit restart-decision
2506/// pipeline holding a shared-ownership per-arm cache key, a
2507/// `<T: Into<std::sync::Arc<str>>>`-bound `tracing`-span attributes
2508/// collector recording a per-child-policy field onto the parent
2509/// span's shared-ownership context — reaches the same three-arm
2510/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2511/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2512/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2513/// sibling
2514/// `{Self, &Self} × {&'static str, String, Cow<'static, str>, Box<str>}`
2515/// forward-projection corner already returns.
2516///
2517/// Second peer on the substrate-wide trait-idiomatic
2518/// [`std::sync::Arc<str>`] forward-projection family opened one
2519/// projection tier prior (bca2ec8) on the paired sibling-restart
2520/// [`RestartStrategy`] owned-input first-mover — extends the tier
2521/// onto the second (and third-and-final) M2 OTP-shape closed-set
2522/// fieldless typed enum peer on the caixa surface
2523/// (`:children :restart`), immediately after the paired [`Box<str>`]
2524/// axis (0a1b313 / cb1d068) closed the whole
2525/// `{Self, &Self} × {&'static str, String, Cow<'static, str>, Box<str>}`
2526/// 2×4 corner on this enum. Rust's standard library carries
2527/// `impl From<&str> for std::sync::Arc<str>` and
2528/// `impl From<String> for std::sync::Arc<str>` but no blanket
2529/// `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor an
2530/// `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`), so this
2531/// axis is a distinct trait-idiomatic surface that a
2532/// `let key: std::sync::Arc<str> = policy.into();`-shaped call site
2533/// reaches through this impl and no other — a paired
2534/// `std::sync::Arc::<str>::from(policy.as_str())` open-code has no
2535/// compile-time link back to the substrate primitive, and a two-step
2536/// `std::sync::Arc::<str>::from(String::from(policy))` composition
2537/// through the owned-`String` axis allocates twice (once into the
2538/// intermediate `String`, once into the [`Arc<str>`] on the
2539/// `From<String>` conversion) where the single-step trait impl
2540/// allocates once.
2541///
2542/// Peer of the sibling [`Box<str>`] second-tier extender (0a1b313) —
2543/// same "extends the substrate-wide projection tier onto the next
2544/// M2 OTP-shape peer" discipline, extended onto the
2545/// [`std::sync::Arc<str>`] axis whose shared-ownership + [`Sync`] +
2546/// [`Send`] contract is the distinct value the [`Box<str>`] axis's
2547/// owned-move return-shape cannot provide.
2548///
2549/// Pinned load-bearing by
2550/// [`tests::restart_policy_from_into_arc_str_routes_through_as_str_accessor`]
2551/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2552/// three-arm [`RestartPolicy::ALL`] emit-set on the owned-input
2553/// surface, plus a blanket-derived [`Into`] shape witness and cross-
2554/// axis byte-parity pins against the sibling owned-input
2555/// `{&'static str, String, Cow<'static, str>, Box<str>}` return-shape
2556/// axes).
2557impl From<RestartPolicy> for std::sync::Arc<str> {
2558 fn from(policy: RestartPolicy) -> std::sync::Arc<str> {
2559 std::sync::Arc::<str>::from(policy.as_str())
2560 }
2561}
2562
2563/// Trait-idiomatic *borrowed-input, [`std::sync::Arc<str>`] output*
2564/// forward projection on the M2 OTP-shape per-child-restart
2565/// [`RestartPolicy`] closed-set fieldless typed enum — closes the
2566/// `{Self, &Self}` input-shape corner of the [`std::sync::Arc<str>`]
2567/// forward-projection axis on the second (and third-and-final) M2
2568/// OTP-shape closed-set fieldless typed enum peer on the caixa
2569/// surface (`:children :restart`), companion to the paired
2570/// owned-input [`From<RestartPolicy> for std::sync::Arc<str>`] impl
2571/// one commit prior (b05724e). Routes byte-for-byte through the
2572/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2573/// accessor (via [`std::sync::Arc::<str>::from`] on the returned
2574/// `&'static str`), so every consumer that binds a
2575/// [`&RestartPolicy`] through the standard-library `.into()` /
2576/// [`From<&Self> for std::sync::Arc<str>`] (equivalently
2577/// [`Into<std::sync::Arc<str>>`]) axis — a future admission-webhook's
2578/// per-request borrowed-`&RestartPolicy` handle rendering a per-arm
2579/// `Sync` + `Send`-safe structured-log field across an `.await`
2580/// boundary through a `<T: Into<std::sync::Arc<str>>>`-bound
2581/// diagnostic-column dispatch, a future wasm-operator's per-child
2582/// post-exit restart-decision pipeline whose
2583/// `.iter().map(std::sync::Arc::<str>::from)` collector reaches
2584/// into the shared-ownership per-arm key without a spurious [`Copy`]
2585/// deref (which would only be reachable through the owned-input
2586/// [`From<RestartPolicy> for std::sync::Arc<str>`] axis by first
2587/// calling `.copied()` on the iterator), a future
2588/// `<T: Into<std::sync::Arc<str>>>`-bound `tracing`-span attributes
2589/// collector recording a borrowed-`&RestartPolicy` per-arm field
2590/// onto the parent span's shared-ownership context — reaches the
2591/// same three-arm lifted
2592/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2593/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2594/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2595/// paired owned-input [`From<RestartPolicy> for std::sync::Arc<str>`]
2596/// impl and the sibling `{&'static str, String, Cow<'static, str>,
2597/// Box<str>}` forward-projection corner already return.
2598///
2599/// Closes the substrate-wide trait-idiomatic
2600/// [`std::sync::Arc<str>`] forward-projection family opened one
2601/// commit prior (b05724e) on the paired owned-input
2602/// [`From<RestartPolicy> for std::sync::Arc<str>`] impl — closes
2603/// the `{Self, &Self}` input-shape corner of the
2604/// [`std::sync::Arc<str>`] axis on the second (and third-and-final)
2605/// M2 OTP-shape closed-set fieldless typed enum peer on the caixa
2606/// surface, exactly as b3e72d7 closed the paired
2607/// [`std::sync::Arc<str>`] corner on the sibling-restart
2608/// [`RestartStrategy`] first-mover one commit after its owning half
2609/// (bca2ec8) landed, and as cb1d068 closed the paired [`Box<str>`]
2610/// corner on this enum one commit after its owning half (0a1b313)
2611/// landed. Rust's standard library carries `impl From<&str> for
2612/// std::sync::Arc<str>` and `impl From<String> for
2613/// std::sync::Arc<str>` but no blanket `impl<T: AsRef<str>> From<&T>
2614/// for std::sync::Arc<str>` (nor a `Copy`-based `impl<T: Copy,
2615/// U: From<T>> From<&T> for U`), so every closed-set fieldless typed
2616/// enum peer on the substrate that carries the paired owned-input
2617/// [`std::sync::Arc<str>`] axis but not the borrowed-input axis
2618/// forces every borrowed-input [`std::sync::Arc<str>`]-parameterized
2619/// call site through a spurious [`Copy`] deref
2620/// (`std::sync::Arc::<str>::from((*policy).as_str())`) or a
2621/// `std::sync::Arc::<str>::from(policy.as_str())` open-code whose
2622/// type bounds have no compile-time link back to the substrate
2623/// primitive.
2624///
2625/// Pinned load-bearing by
2626/// [`tests::restart_policy_from_borrowed_into_arc_str_routes_through_as_str_accessor`]
2627/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2628/// three-arm [`RestartPolicy::ALL`] emit-set on the borrowed-input
2629/// surface, plus a blanket-derived [`Into`] shape witness, a
2630/// cross-axis pin against the paired owned-input
2631/// [`From<RestartPolicy> for std::sync::Arc<str>`] and the sibling
2632/// borrowed-input `{&'static str, String, Cow<'static, str>,
2633/// Box<str>}` return-shape axes, and a
2634/// `.iter().map(std::sync::Arc::<str>::from)` pipe witness over
2635/// [`RestartPolicy::ALL`]).
2636impl From<&RestartPolicy> for std::sync::Arc<str> {
2637 fn from(policy: &RestartPolicy) -> std::sync::Arc<str> {
2638 std::sync::Arc::<str>::from(policy.as_str())
2639 }
2640}
2641
2642// Fleet-wide dispatcher-catalog registrations for caixa's OTP
2643// supervisor surface — two more typed shadows over Erlang/OTP
2644// primitives the substrate now mechanically tracks (see
2645// theory/UNIFIED-COMPUTING-MODEL.md §VI for the roadmap +
2646// theory/TYPED-ABSORPTION.md for the absorption arc).
2647gen_platform::register_dispatcher!("caixa.restart-strategy", RestartStrategy);
2648gen_platform::register_dispatcher!("caixa.restart-policy", RestartPolicy);
2649
2650/// One child entry in the supervisor's `:children` list.
2651///
2652/// Every child references another caixa by `:caixa <nome>` + version
2653/// constraint. The supervisor materializes one ComputeUnit per entry.
2654#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2655#[serde(rename_all = "camelCase")]
2656pub struct ChildSpec {
2657 /// The child caixa's `:nome`. Must resolve via the same dependency
2658 /// resolution path as `:deps` (caixa-resolver).
2659 pub caixa: String,
2660
2661 /// Semver constraint (`"^0.1"`, `"~0.1.2"`, etc.) — same shape as
2662 /// [`crate::dep::Dep::versao`].
2663 pub versao: String,
2664
2665 /// Restart policy — an author-omitted slot degrades onto the
2666 /// substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`]
2667 /// (`permanent`, the Erlang/OTP worker-child default) through the
2668 /// [`Default for RestartPolicy`] impl this `#[serde(default)]` routes
2669 /// to.
2670 #[serde(default)]
2671 pub restart: RestartPolicy,
2672}
2673
2674impl ChildSpec {
2675 /// Substrate-canonical per-`:children` child-caixa `:nome` scalar
2676 /// accessor every consumer that reads the OTP-shape supervised
2677 /// child's identity keys off — returns the author-declared
2678 /// `:children :caixa` byte-string verbatim as a `&str`, borrowed
2679 /// from the typed slot's own [`String`] storage.
2680 ///
2681 /// The `:children :caixa` slot carries the DNS-1123 label — the
2682 /// child caixa's `:nome` — that every emitted cluster artifact
2683 /// derives its `metadata.name` from verbatim: the rendered
2684 /// `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name` per child, the
2685 /// [`crate::LABEL_PROGRAM`] label value on every child's pod
2686 /// identity, and the per-child K8s Service `metadata.name` the
2687 /// future wasm-operator (M3) provisions for inter-child supervision-
2688 /// tree wiring. Every downstream consumer that fans on the child's
2689 /// caixa-name keys off this scalar (the [`SupervisorSpec::validate`]
2690 /// per-child DNS-1123 gate at
2691 /// `require_valid_dns_1123_label(child.nome(), …)`, the per-child
2692 /// duplicate-detection [`crate::render::insert_first_seen`] key, the
2693 /// [`validate_no_self_supervision`] cross-slot equality check
2694 /// against the parent's `:nome`, every `SupervisorError` variant
2695 /// carrying the offending child caixa verbatim for `feira lint`
2696 /// rendering, the future wasm-operator's hierarchical reconciliation
2697 /// scheduler's per-child ComputeUnit-name projection, the future M4
2698 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2699 /// admission webhook).
2700 ///
2701 /// Prior to this lift the `.caixa` byte-string was accessed inline
2702 /// at seven sites in `supervisor.rs` — the DNS-1123 gate's
2703 /// `&child.caixa`, the four `SupervisorError::{ChildCaixaInvalid,
2704 /// EmptyChildVersion, ChildVersaoInvalid, DuplicateChildCaixa}`
2705 /// carriers' `child.caixa.clone()`, the dedup key's
2706 /// `child.caixa.as_str()`, and the [`validate_no_self_supervision`]
2707 /// `child.caixa == parent_nome` cross-slot check — seven open-coded
2708 /// field-accesses that expressed no compile-time link back to the
2709 /// typed slot. A future extension of the `:children :caixa` axis to
2710 /// a richer author surface (a per-cluster alias table the operator
2711 /// pins through a future `:placement`-scoped slot on the supervisor
2712 /// tree, a namespace-qualified rewrite the M4 CR materializer
2713 /// applies per-CR, a per-child overlay from the future `:children
2714 /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
2715 /// acknowledges) would have had to be threaded through every
2716 /// open-coded copy in lockstep or one consumer would silently
2717 /// disagree with the peers on which caixa a given child resolves to
2718 /// — a child-set lookup that treated the name as `"cart-worker"`
2719 /// while the peer duplicate-detector treated it as
2720 /// `"tenant-a/cart-worker"` would silently split the
2721 /// `DuplicateChildCaixa` membership-lookup diagnostic from the
2722 /// self-supervision detector's parent-equality check, a two-consumer
2723 /// split at the validator far from the source `caixa.lisp` with no
2724 /// field naming the identity-drift root cause. Lifting the resolution
2725 /// rule to a typed method on the substrate primitive means every
2726 /// downstream consumer of the Supervisor's per-`:children` identity
2727 /// surface reaches for exactly one typed dispatch — the resolver's
2728 /// accept-set migrates as a unit on any future axis addition.
2729 ///
2730 /// Sibling of the peer per-`:membros` [`crate::Membro::nome`]
2731 /// (4a32abf) member-caixa `:nome` scalar accessor on the M3
2732 /// mesh-slot surface — same "one typed dispatch on the substrate
2733 /// primitive, thin projections at each consumer" discipline extended
2734 /// onto the M2 supervisor-tree per-`:children` child-identity axis.
2735 /// The two typed axes (`Membro::nome` on the M3 Aplicacao side,
2736 /// `ChildSpec::nome` on the M2 Supervisor side) now share one
2737 /// accessor discipline for the shared substrate concept "another
2738 /// caixa referenced by `:nome`". Peer of the second M2 slot scalar
2739 /// accessor [`crate::UpgradeFromEntry::prior_versao`] (75d27a8) on
2740 /// the sibling per-`:upgrade-from :from` OTP-appup axis — the M2
2741 /// slot family's typed-accessor discipline now spans both the
2742 /// upgrade axis (`:upgrade-from`) and the supervision axis
2743 /// (`:children`), matching the closed M3 mesh-slot accessor family's
2744 /// shape. Named `nome()` to match the tatara-lisp author-surface
2745 /// term the field's docstring already reaches for ("The child
2746 /// caixa's `:nome`") and the peer [`crate::Membro::nome`] /
2747 /// [`crate::Caixa::nome`] / [`crate::dep::Dep::nome`] field-name
2748 /// discipline the substrate already carries — the accessor's name
2749 /// maps directly onto the canonical caixa-identity vocabulary rather
2750 /// than shadowing the field's storage-side `caixa` label.
2751 #[must_use]
2752 pub const fn nome(&self) -> &str {
2753 self.caixa.as_str()
2754 }
2755
2756 /// Substrate-canonical per-`:children` child-caixa `:versao` semver-
2757 /// requirement scalar accessor every consumer that reads the OTP-shape
2758 /// supervised child's version pin keys off — returns the author-declared
2759 /// `:children :versao` byte-string verbatim as a `&str`, borrowed from
2760 /// the typed slot's own [`String`] storage.
2761 ///
2762 /// The `:children :versao` slot carries the Cargo-shaped semver
2763 /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that pins
2764 /// which release of the supervised child caixa the OTP-shape supervisor
2765 /// tree materializes against — the same requirement grammar the peer
2766 /// `:deps :versao` / `:membros :versao` axes carry, resolved through the
2767 /// shared [`crate::render::require_valid_versao_requirement`] cascade
2768 /// and the shared [`crate::version::parse_requirement`] parser. Every
2769 /// downstream consumer that fans on the child's version pin keys off
2770 /// this scalar (the [`SupervisorSpec::validate`] per-child requirement
2771 /// gate at `require_valid_versao_requirement(child.versao_requirement(),
2772 /// …)`, the [`SupervisorError::ChildVersaoInvalid`] variant's carrier
2773 /// for `feira lint` rendering, every future per-cluster version-lock
2774 /// overlay the caixa-operator's hierarchical reconciliation scheduler
2775 /// pins through a future `:placement`-scoped supervisor-tree slot, the
2776 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2777 /// per-child version resolver, the future wasm-operator's per-child
2778 /// lacre BLAKE3-closure lookup at `ComputeUnit` materialization time).
2779 ///
2780 /// Prior to this lift the `.versao` byte-string was accessed inline at
2781 /// two `&str`-shaped sites in `caixa-core/src/supervisor.rs` — the
2782 /// [`SupervisorSpec::validate`] requirement-gate call
2783 /// `require_valid_versao_requirement(&child.versao, …)` and the
2784 /// [`SupervisorError::ChildVersaoInvalid`] carrier at
2785 /// `versao: child.versao.clone()` — two open-coded field-accesses that
2786 /// expressed no compile-time link back to the typed slot. A future
2787 /// extension of the `:children :versao` axis to a richer author surface
2788 /// (a per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
2789 /// flow, a lacre-projected concrete-version rewrite the operator
2790 /// materializes at CR-admission time, a future `:children :versao-lock`
2791 /// per-cluster override slot the wasm-operator's hierarchical
2792 /// reconciliation scheduler authors per-CR) would have had to be
2793 /// threaded through both open-coded copies in lockstep or one consumer
2794 /// would silently disagree with the peer on which release constraint a
2795 /// given child resolves to — the requirement-gate call reading
2796 /// `"^0.1"` while the error-body carrier read `"tenant-a-pin/^0.1"`
2797 /// would silently split the `ChildVersaoInvalid` diagnostic quote from
2798 /// the actual gate rejection input, a two-consumer split at the
2799 /// validator far from the source `caixa.lisp` with no field naming the
2800 /// version-pin drift root cause. Lifting the resolution rule to a typed
2801 /// method on the substrate primitive means every downstream
2802 /// requirement-facing consumer of the Supervisor's per-`:children`
2803 /// version-pin surface reaches for exactly one typed dispatch — the
2804 /// resolver's accept-set migrates as a unit on any future axis addition.
2805 ///
2806 /// Sibling of the peer per-`:membros` [`crate::Membro::versao_requirement`]
2807 /// (a40b0e3) member-caixa `:versao` scalar accessor on the M3 mesh-slot
2808 /// surface — same "one typed dispatch on the substrate primitive, thin
2809 /// projections at each consumer" discipline extended onto the M2
2810 /// supervisor-tree per-`:children` child-version-pin axis. The two typed
2811 /// axes (`Membro::versao_requirement` on the M3 Aplicacao side,
2812 /// `ChildSpec::versao_requirement` on the M2 Supervisor side) now share
2813 /// one accessor discipline for the shared substrate concept "another
2814 /// caixa referenced by a Cargo-shaped semver requirement". Peer of the
2815 /// sibling per-`:children` [`ChildSpec::nome`] (57c61d0) child-caixa
2816 /// `:nome` scalar accessor — the pair
2817 /// `(nome(), versao_requirement())` jointly projects the
2818 /// `(caixa, versao)` field pair every OTP-shape supervisor-tree consumer
2819 /// that fans on per-child identity + version pin keys off, closing the
2820 /// last unlifted per-`:children` `String`-carry axis so every downstream
2821 /// per-`:children` reader now routes through a typed dispatch on the
2822 /// substrate primitive. Named `versao_requirement()` rather than
2823 /// `versao()` because the field's storage-side `.versao` label is
2824 /// already the author-surface term (`:versao`); the accessor's name
2825 /// carries the semantic role — the semver *requirement* string the
2826 /// shared [`crate::version::parse_requirement`] entry-point consumes —
2827 /// so a raw field access and a typed dispatch read differently at every
2828 /// consumer site. Matches the peer [`crate::Membro::versao_requirement`]
2829 /// naming discipline verbatim.
2830 #[must_use]
2831 pub const fn versao_requirement(&self) -> &str {
2832 self.versao.as_str()
2833 }
2834
2835 /// Substrate-canonical per-`:children` `:restart` OTP-shaped
2836 /// per-child post-exit restart-decision policy scalar accessor every
2837 /// consumer that dispatches on the supervised child's post-exit
2838 /// reconcile posture keys off — returns the author-declared
2839 /// `:children :restart` variant verbatim as a [`RestartPolicy`],
2840 /// `Copy`-projected from the typed slot's own [`RestartPolicy`]
2841 /// storage.
2842 ///
2843 /// The `:children :restart` slot carries the closed-set OTP-shaped
2844 /// per-child restart-decision policy discriminator
2845 /// ([`RestartPolicy::Permanent`] — always restart, the OTP `permanent`
2846 /// worker-child default; [`RestartPolicy::Transient`] — restart only
2847 /// on abnormal exit, the OTP `transient` clean-completion-aware
2848 /// default; [`RestartPolicy::Temporary`] — never restart, the OTP
2849 /// `temporary` one-shot default) that every downstream consumer of
2850 /// the Supervisor's per-child post-exit reconcile branch keys off.
2851 /// Every future downstream consumer that fans on the per-child
2852 /// restart-decision keys off this scalar (the future `feira app
2853 /// graph` per-child restart column, the future wasm-operator's
2854 /// per-child post-exit restart-decision branch, the future M4
2855 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2856 /// admission webhook, the `caixa-operator`'s hierarchical
2857 /// reconciliation scheduler's per-child post-exit reconcile branch,
2858 /// the [`RestartPolicy::as_str`] `Serialize`-derive-pinning path the
2859 /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
2860 /// pin threads through).
2861 ///
2862 /// Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
2863 /// (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
2864 /// scalar accessor and the M3 mesh-slot
2865 /// [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
2866 /// [`crate::PlacementStrategy`] distribution-strategy scalar accessor
2867 /// — same "one typed dispatch on the substrate primitive,
2868 /// `Copy`-projected closed-set enum-arm discriminator that partitions
2869 /// the downstream renderer's per-arm fan-out" discipline extended
2870 /// onto the M2 supervisor-slot per-`:children` restart-decision-policy
2871 /// `Copy`-composite-enum scalar axis. Third axis on the per-`:children`
2872 /// [`ChildSpec`] type — companion to the sibling per-`:children`
2873 /// [`ChildSpec::nome`] (57c61d0) child-caixa `:nome` scalar accessor
2874 /// and the per-`:children` [`ChildSpec::versao_requirement`]
2875 /// (2c053c8) child-caixa `:versao` semver-requirement scalar accessor
2876 /// on the sibling `String`-carry axes. The triple
2877 /// `(nome(), versao_requirement(), restart())` jointly projects the
2878 /// `(caixa, versao, restart)` field trio every OTP-shape supervisor-
2879 /// tree consumer that fans on per-child identity + version pin +
2880 /// restart-decision keys off, closing the last unlifted per-`:children`
2881 /// axis so every downstream per-`:children` reader now routes through
2882 /// a typed dispatch on the substrate primitive. Named `restart()` to
2883 /// match the storage field's name and the author-surface
2884 /// `:children :restart` slot term verbatim; the accessor's identity
2885 /// name maps onto the canonical OTP-shape per-child restart-decision-
2886 /// policy vocabulary the [`RestartPolicy`] enum's docstring already
2887 /// carries.
2888 ///
2889 /// Declared `pub const fn` to close the last non-`const`
2890 /// `Copy`-return raw-field-getter posture on the M2
2891 /// per-`:children` [`ChildSpec`] substrate-primitive surface — peer
2892 /// of the sibling M2 per-`:supervisor`
2893 /// [`SupervisorSpec::estrategia`] (converted in this commit)
2894 /// `Copy`-composite-enum accessor, the sibling M2 per-`:supervisor`
2895 /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
2896 /// already lifted, and the peer M3 mesh-slot per-`:entrada`
2897 /// [`crate::Entrada::port`] (bafa004) / per-`:placement`
2898 /// [`crate::Placement::estrategia`] (bafa004) `Copy`-return
2899 /// `pub const fn` scalar accessors on the sibling M3 surface. Every
2900 /// downstream substrate-side `const`-context consumer of the
2901 /// per-`:children` restart-decision-policy scalar (a future
2902 /// module-scope `const _:() = assert!(matches!(child.restart(),
2903 /// RestartPolicy::Permanent))` invariant pin on a typed fixture, a
2904 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
2905 /// admission-webhook `const fn` per-child restart-decision floor
2906 /// over a typed [`ChildSpec`], any future `const fn` supervisor-tree
2907 /// composer over the substrate primitive that fans on the per-child
2908 /// restart-decision policy at compile time) now reaches through the
2909 /// same typed dispatch on the substrate primitive at const-eval
2910 /// time as at runtime. A future non-`Copy`-return promotion of the
2911 /// scalar (an `Option<RestartPolicy>`-shape migration on the
2912 /// per-child restart-decision axis once heterogeneous per-cluster
2913 /// restart-policy overlays land, a per-tenant restart-policy-alias
2914 /// table the M4 CR materializer resolves per-CR) that would drop
2915 /// the `const` qualifier fails the fail-before-pass-after pin
2916 /// [`tests::child_spec_restart_accessor_is_const_fn`] at caixa-core
2917 /// build time rather than surfacing as a downstream consumer
2918 /// regression.
2919 #[must_use]
2920 pub const fn restart(&self) -> RestartPolicy {
2921 self.restart
2922 }
2923}
2924
2925/// Supervisor-typed slots that live alongside the standard Caixa
2926/// fields when `:kind Supervisor`. Held flat in [`crate::Caixa`] so
2927/// the manifest stays a single typed form; this struct exists for
2928/// validation + conversion.
2929#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2930#[serde(rename_all = "camelCase")]
2931pub struct SupervisorSpec {
2932 /// Restart strategy. Defaults to [`RestartStrategy::OneForOne`].
2933 #[serde(default)]
2934 pub estrategia: RestartStrategy,
2935
2936 /// Max restarts within [`Self::restart_window`] before the
2937 /// supervisor itself terminates (and its parent supervisor decides
2938 /// what to do). Default 5.
2939 #[serde(default = "default_max_restarts")]
2940 pub max_restarts: u32,
2941
2942 /// Sliding window for `max_restarts`. Authored as a duration
2943 /// string (`"60s"`, `"5m"`); absent = "never reset". A `Some(0s)`
2944 /// is rejected by [`Self::validate`] — Erlang/OTP's
2945 /// `MaxIntensity / Period` invariant requires a positive window
2946 /// (a zero-period supervisor either trips on the first failure or
2947 /// never trips, depending on operator interpretation, neither of
2948 /// which is the author's intent). Omit the slot to express "no
2949 /// reset"; carry a positive duration to express the sliding window.
2950 #[serde(
2951 default,
2952 skip_serializing_if = "Option::is_none",
2953 with = "duration_codec"
2954 )]
2955 pub restart_window: Option<Duration>,
2956
2957 /// Static children. Empty for `SimpleOneForOne` (children added
2958 /// dynamically); required for the other three strategies.
2959 #[serde(default)]
2960 pub children: Vec<ChildSpec>,
2961}
2962
2963const fn default_max_restarts() -> u32 {
2964 // Route the private serde-`#[serde(default = "…")]` helper through
2965 // the substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] typed
2966 // `pub const` rather than the raw `5` literal — one source of truth
2967 // for the Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
2968 // default across the two production consumers that currently
2969 // dispatch on it (this helper via `#[serde(default = "…")]` on
2970 // `SupervisorSpec::max_restarts` and the [`Default for SupervisorSpec`]
2971 // impl at line 962). Pinned by
2972 // `default_max_restarts_helper_routes_through_lifted_default` +
2973 // `supervisor_spec_default_max_restarts_routes_through_lifted_default`
2974 // in the tests module; peer of the sibling caixa-core
2975 // [`crate::manifest::Caixa::supervisor_view`] `unwrap_or(…)` fold
2976 // that now routes its author-omitted `:max-restarts` arm through
2977 // the same lifted constant.
2978 SUPERVISOR_MAX_RESTARTS_DEFAULT
2979}
2980
2981/// Substrate-canonical Erlang/OTP-shaped `MaxIntensity` restart-budget-
2982/// count default for the `:supervisor :max-restarts` axis — the
2983/// canonical `{intensity, 5, 60}` `MaxIntensity` half of Learn You Some
2984/// Erlang's worker-supervisor default, extracted as a typed `pub const`
2985/// so every substrate-side consumer that resolves "what
2986/// [`SupervisorSpec::max_restarts`] value does an author-omitted
2987/// `:max-restarts` slot degrade onto?" reaches for exactly one
2988/// substrate-primitive `u32`.
2989///
2990/// The `:max-restarts` default axis has two production consumers on the
2991/// substrate side today (both prior to this lift folded onto raw `5`
2992/// literals with no compile-time link back to a shared truth): the
2993/// serde-`#[serde(default = "default_max_restarts")]` helper on
2994/// [`SupervisorSpec::max_restarts`] that every author-omitted
2995/// `:supervisor :max-restarts` slot lands in past the derive-macro's
2996/// wire-format compose, and the [`crate::manifest::Caixa::supervisor_view`]
2997/// `.max_restarts().unwrap_or(5)` fold that every downstream consumer of
2998/// the composed [`SupervisorSpec`] altitude reaches through
2999/// (`feira app graph`, the future wasm-operator's per-supervisor
3000/// restart-intensity counter, the future M4
3001/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3002/// webhook, the caixa-operator's hierarchical reconciliation scheduler).
3003/// A pair of open-coded `5`s across two files that expressed no
3004/// compile-time link back to the shared OTP-canonical default — a
3005/// future rebrand of the default (a tightening to Elixir's
3006/// `Supervisor.max_restarts: 3`, a widening to a per-cluster overlay
3007/// the operator pins through a future
3008/// `:supervisor :max-restarts-overrides` slot the MESH-COMPOSITION
3009/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
3010/// plain `u32` count to a richer `{MaxR, MaxT}` per-child-cohort
3011/// restart-budget-partition once the INSPIRATIONS §II.2 Erlang/OTP
3012/// per-child-cohort roadmap lands) would have had to be threaded
3013/// through both open-coded copies in lockstep or the wire-format
3014/// author-omitted arm and the view-construction author-omitted arm
3015/// would silently disagree on which restart-budget an omitted
3016/// `:max-restarts` resolves to (an author writing `:supervisor
3017/// (:max-restarts ())` would round-trip through serde with the new
3018/// default while `supervisor_view` silently continued to compose the
3019/// stale `5`, or vice versa), a two-consumer split at the composition
3020/// boundary far from the source `caixa.lisp` with no field naming the
3021/// default-drift root cause. Lifting the resolution rule to a typed
3022/// `pub const` on the substrate primitive means every downstream
3023/// consumer of the per-Supervisor default-restart-budget-count surface
3024/// reaches for exactly one substrate-primitive `u32` — the resolver's
3025/// accepted value migrates as a unit on any future axis change.
3026///
3027/// The `5` value pins Learn You Some Erlang's `{intensity, 5, 60}`
3028/// worker-supervisor default (the closest canonical OTP-shape
3029/// production reference the substrate carries, matching the sibling
3030/// `60s` `Period` default the [`Default for SupervisorSpec`] impl pairs
3031/// this constant with on the paired sliding-window axis). Two orders of
3032/// magnitude below the [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` ceiling
3033/// (the upper bracket on the same axis, sibling of this lower default;
3034/// both are typed `u32` const bounds on the `:supervisor :max-restarts`
3035/// axis and now share one accessor discipline on the substrate) and
3036/// above the OTP-`supervisor` callback-module `MaxR = 1` minimum-
3037/// restart floor — the "one restart, then escalate" default is
3038/// deliberately loose enough to absorb a short burst of transient
3039/// child failures without escalating past the supervisor's parent
3040/// while remaining tight enough to trip the `MaxIntensity / Period`
3041/// ratio's escalation on a genuinely-stuck child within the sibling
3042/// `60s` sliding window.
3043///
3044/// Lifted as a typed `pub const` so the bound has exactly one source
3045/// of truth — the serde-side wire-format author-omitted arm at
3046/// [`default_max_restarts`], the [`Default for SupervisorSpec`] impl's
3047/// struct-literal default field, and the caixa-core
3048/// [`crate::manifest::Caixa::supervisor_view`] fold's author-omitted
3049/// arm all read from one place. Same shape every other typed default
3050/// in this crate carries (the sibling
3051/// [`SUPERVISOR_MAX_RESTARTS_MAX`] upper cap on the same axis, the
3052/// paired [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the
3053/// sibling `:restart-window` axis, and the peer
3054/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
3055/// per-renderer defaults on the caixa-flux / caixa-helm rendering
3056/// axes).
3057pub const SUPERVISOR_MAX_RESTARTS_DEFAULT: u32 = 5;
3058
3059/// Upper-bound ceiling on the `:supervisor :max-restarts` axis — every
3060/// validated [`SupervisorSpec::max_restarts`] past
3061/// [`SupervisorSpec::validate`] lies in `1..=SUPERVISOR_MAX_RESTARTS_MAX`.
3062///
3063/// The typed field is `u32` (the zero-floor arm
3064/// [`SupervisorError::ZeroMaxRestarts`] already brackets the bottom edge),
3065/// so a programmatic struct literal
3066/// (`SupervisorSpec { max_restarts: u32::MAX, .. }`) and the equivalent
3067/// author-surface form (`:max-restarts 4294967295` or any
3068/// `:max-restarts 100000`-shape typo landing in the slot) both round-trip
3069/// cleanly through serde — a structurally unbounded `u32` ceiling. The
3070/// runtime substrate consuming the value (Erlang/OTP's
3071/// `MaxIntensity / Period` ratio, the future wasm-operator's
3072/// per-supervisor restart-intensity counter, the M4
3073/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook)
3074/// then turned a typed `:max-restarts` policy into a no-op supervisor: the
3075/// escalation threshold is structurally so high that no realistic
3076/// restarts-per-`:restart-window` traffic shape can reach it, the
3077/// supervisor never escalates to its parent, and a bad child can loop
3078/// inside the window indefinitely with the parent supervisor structurally
3079/// never receiving the "this subtree has exceeded its restart budget"
3080/// signal the typed slot is meant to express — the canonical
3081/// "supervisor intensity declared, no escalation" footgun, exactly the
3082/// peer of the [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap
3083/// on the `:politicas :circuit-breaker :max-failures` axis (both are
3084/// "trip the next-higher protection layer after N events in a rolling
3085/// window" counters with identical degenerate-at-the-high-end shape).
3086///
3087/// The `1000` ceiling matches the sibling
3088/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] (the closest
3089/// peer — same "events-per-window trip threshold" semantics, same `u32`
3090/// type, same no-op-at-the-high-end failure mode) so the M4
3091/// `mesh.pleme.io/v1alpha1/Supervisor` / `.../Aplicacao` CR materializers
3092/// and the future wasm-operator's per-supervisor restart-intensity
3093/// counter reach for either field knowing the value is in `1..=1000`
3094/// without re-validating at the reconciler layer. The cap sits two
3095/// orders of magnitude above every documented Erlang/OTP production
3096/// playbook recommendation (Learn You Some Erlang's
3097/// `{intensity, 5, 60}` worker-supervisor default, Elixir's `Supervisor`
3098/// `max_restarts: 3` default, OTP's `supervisor` callback module
3099/// `MaxR = 1` / `MaxT = 5` "minimal-restart" default, Riak Core's
3100/// typical `MaxR ∈ 5..=100`, RabbitMQ's broker-supervisor `MaxR = 5`
3101/// default) and below the clearly-pathological "effectively no
3102/// escalation" floor (`10_000`, `100_000`, `u32::MAX`): a value the
3103/// author can plausibly want at hyperscale (a long-running supervisor
3104/// over a very-flaky pool tolerating thousands of transient restarts
3105/// before escalating), but a hard wall above which the typed policy is
3106/// structurally a no-op carried verbatim on every emitted child-restart
3107/// reconciliation contract.
3108///
3109/// Lifted as a typed `pub const` so the bound has exactly one source of
3110/// truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
3111/// materializer's admission webhook and the wasm-operator-side
3112/// per-supervisor restart-intensity reconciler read from one place. Same
3113/// shape every other typed upper bound in this crate carries
3114/// ([`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
3115/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
3116/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
3117/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3118/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3119/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3120pub const SUPERVISOR_MAX_RESTARTS_MAX: u32 = 1000;
3121
3122/// Upper-bound ceiling on the `:supervisor :restart-window` axis —
3123/// every validated `Some(`[`SupervisorSpec::restart_window`]`)` past
3124/// [`SupervisorSpec::validate`] lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
3125/// (inclusive on both ends, integer-millisecond magnitudes by the
3126/// canonical-form gate immediately preceding).
3127///
3128/// The typed field is `Option<Duration>` (the zero-floor arm
3129/// [`SupervisorError::RestartWindowZero`] already rejects
3130/// `Some(Duration::ZERO)`, and the canonical-form arm
3131/// [`SupervisorError::RestartWindowNotCanonical`] already rejects
3132/// sub-millisecond residue), so a programmatic struct literal
3133/// (`SupervisorSpec { restart_window: Some(Duration::from_secs(86_400)),
3134/// .. }` — 24h) and the equivalent author-surface form
3135/// (`(:supervisor (:restart-window "24h"))` — the shared duration codec
3136/// emits `"<n>h"` for any integer-hour magnitude) both round-trip
3137/// cleanly through serde — a structurally unbounded `Duration` ceiling.
3138/// A `:restart-window` value far above the documented Erlang/OTP
3139/// `MaxIntensity / Period` production-playbook band (Learn You Some
3140/// Erlang's `{intensity, 5, 60}` worker-supervisor `Period = 60s`
3141/// default, Elixir's `Supervisor` `max_seconds: 5` default, OTP's
3142/// `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's
3143/// `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default)
3144/// degenerates the supervisor's restart-intensity counter into a
3145/// lifetime counter: the rolling failure-counting window is structurally
3146/// so long that transient restarts are never forgotten, so the
3147/// `MaxIntensity / Period` ratio degenerates from "trip the parent
3148/// supervisor when the child has exceeded its restart budget *within
3149/// the recent window*" to "trip the parent when the child has exceeded
3150/// its restart budget *over its lifetime*" — every transient restart
3151/// counts against the budget forever, the supervisor's reset semantic
3152/// never reaches the child, and the typed `:restart-window` slot
3153/// becomes a no-op rolling window carried on every emitted hierarchical
3154/// reconciliation contract. The canonical
3155/// rolling-window-degenerates-to-lifetime-counter footgun the sibling
3156/// [`crate::POLICY_BREAKER_WINDOW_MAX`] cap closes on the peer
3157/// `:politicas :circuit-breaker :window` axis with identical shape (both
3158/// are "rolling failure-counting window with a per-`Period` reset" Duration
3159/// axes whose lifetime-counter degenerate at the high end is the same
3160/// "the reset semantic never fires" CSE invariant violation).
3161///
3162/// The `1h` (3600s = `3_600_000` ms) ceiling matches the largest unit
3163/// the shared duration codec emits (`"<n>h"` for any integer-hour
3164/// magnitude) — every value in the canonical authoring form's
3165/// `<integer><unit>` grammar at or below this cap renders to a clean
3166/// canonical string — and matches the three sibling typed-`Duration`
3167/// caps already lifted to this surface
3168/// ([`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
3169/// [`crate::POLICY_BREAKER_WINDOW_MAX`]). All four typed-`Duration`
3170/// axes — per-process `:limits :wall-clock`, per-edge `:politicas
3171/// :timeout`, per-breaker `:politicas :circuit-breaker :window`, and
3172/// per-supervisor `:supervisor :restart-window` — now share a single
3173/// uniform top edge at the codec's largest emitted unit so the next
3174/// typed-slot wiring (the future wasm-operator's per-supervisor
3175/// `MaxIntensity / Period` reconciler, the M4
3176/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3177/// webhook, the `caixa-operator`'s hierarchical reconciliation
3178/// scheduler) reaches for any of the four knowing the value is in
3179/// `1ms..=1h` without re-validating at the renderer layer. The cap sits
3180/// two orders of magnitude above every documented Erlang/OTP / Elixir /
3181/// Riak Core / RabbitMQ production-playbook recommendation band
3182/// (`5s..=300s`) and below the clearly-pathological "rolling window
3183/// degenerates to lifetime counter" floor (`24h`, `7d`, `Duration::MAX`):
3184/// a value the author can plausibly want for a very-low-traffic
3185/// long-tail failure-restart window over a hyperscale-flaky child pool,
3186/// but a hard wall above which the rolling-window contract is
3187/// structurally a lifetime-counter contract.
3188///
3189/// Lifted as a typed `pub const` so the bound has exactly one source
3190/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
3191/// materializer's admission webhook, the wasm-operator-side
3192/// per-supervisor `MaxIntensity / Period` reconciler, and the
3193/// `caixa-operator`'s hierarchical reconciliation scheduler all read
3194/// from one place. Same shape every other typed upper bound in this
3195/// crate carries ([`SUPERVISOR_MAX_RESTARTS_MAX`],
3196/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
3197/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
3198/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
3199/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3200/// [`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
3201/// [`crate::POLICY_BREAKER_WINDOW_MAX`],
3202/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3203/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3204pub const SUPERVISOR_RESTART_WINDOW_MAX: Duration = Duration::from_secs(3600);
3205
3206/// Substrate-canonical Erlang/OTP-shaped `Period` sliding-window-duration
3207/// default for the `:supervisor :restart-window` axis — the canonical
3208/// `{intensity, 5, 60}` `Period` half of Learn You Some Erlang's
3209/// worker-supervisor default, extracted as a typed `pub const` so every
3210/// substrate-side consumer that resolves "what
3211/// [`SupervisorSpec::restart_window`] value does an author-omitted
3212/// `:restart-window` slot degrade onto?" reaches for exactly one
3213/// substrate-primitive [`Duration`].
3214///
3215/// The `:restart-window` default axis has one production consumer on the
3216/// substrate side today: the [`Default for SupervisorSpec`] impl's
3217/// struct-literal `restart_window` field, which prior to this lift folded
3218/// onto a raw `Duration::from_secs(60)` literal with no compile-time link
3219/// back to the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity`
3220/// half of the same `{intensity, 5, 60}` OTP-canonical default. The
3221/// [`crate::manifest::Caixa::supervisor_view`] fold deliberately does
3222/// *not* fall back to this default on the sibling `:restart-window` axis
3223/// — an author-omitted `:supervisor :restart-window` composes to
3224/// `restart_window: None` (the shared codec's soft-swallow shape),
3225/// keeping author-declared intent ("no reset — never escalate on rolling
3226/// window") distinct from the [`Default for SupervisorSpec`] "canonical
3227/// 60s Period" arm every programmatic `SupervisorSpec::default()` caller
3228/// resolves to. Prior to this lift the paired `{intensity, 5, 60}` OTP
3229/// default was split across two files with no compile-time link between
3230/// the halves: [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] pinned the
3231/// `MaxIntensity` half at the substrate primitive while the `Period`
3232/// half rode as an open-coded literal at the composition site, so a
3233/// future coherent rebrand of the paired canonical (a tightening to
3234/// Elixir's `{max_restarts: 3, max_seconds: 5}`, a widening to a
3235/// per-cluster overlay the operator pins through a future
3236/// `:supervisor :restart-window-overrides` slot the MESH-COMPOSITION
3237/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
3238/// paired constants to a per-child-cohort `{MaxR, MaxT}` restart-budget-
3239/// partition once the INSPIRATIONS §II.2 Erlang/OTP per-child-cohort
3240/// roadmap lands) would have had to migrate the `MaxIntensity` half
3241/// through the lifted constant and the `Period` half through a raw
3242/// literal in lockstep or the two halves of the same OTP-canonical
3243/// default would silently drift out of pairing. Lifting the resolution
3244/// rule to a typed `pub const` on the substrate primitive means the
3245/// paired OTP-canonical default migrates as one unit on any future
3246/// axis change.
3247///
3248/// The `60s` value pins Learn You Some Erlang's `{intensity, 5, 60}`
3249/// worker-supervisor default (the closest canonical OTP-shape
3250/// production reference the substrate carries, matching the paired
3251/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5` `MaxIntensity` half this
3252/// constant is the `Period` denominator of on the same
3253/// `MaxIntensity / Period` restart-intensity ratio). Two orders of
3254/// magnitude below the [`SUPERVISOR_RESTART_WINDOW_MAX`] `3600s`
3255/// (`1h`) ceiling (the upper bracket on the same axis, sibling of
3256/// this lower default; both are typed [`Duration`] const bounds on the
3257/// `:supervisor :restart-window` axis and now share one accessor
3258/// discipline on the substrate) and above the OTP-`supervisor`
3259/// callback-module `MaxT = 5` seconds "minimal-window" floor — the "60s
3260/// rolling window" default is deliberately loose enough to absorb a
3261/// short burst of transient child failures without escalating past the
3262/// supervisor's parent while remaining tight enough for the paired
3263/// `MaxIntensity / Period` ratio's escalation to trip on a genuinely-
3264/// stuck child within a human-scale observation window.
3265///
3266/// Lifted as a typed `pub const` so the paired OTP-canonical default has
3267/// exactly one source of truth on each half — the sibling
3268/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half and this
3269/// `Period` `60s` half now share the same substrate-primitive lift
3270/// discipline. Same shape every other typed default in this crate
3271/// carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] paired
3272/// `MaxIntensity` half on the same OTP-canonical `{intensity, 5, 60}`,
3273/// the sibling [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the same
3274/// axis, and the peer [`crate::render::DEFAULT_NAMESPACE`] /
3275/// [`crate::render::DEFAULT_LIBRARY_NAME`] per-renderer defaults on the
3276/// caixa-flux / caixa-helm rendering axes).
3277pub const SUPERVISOR_RESTART_WINDOW_DEFAULT: Duration = Duration::from_secs(60);
3278
3279/// Substrate-canonical Erlang/OTP-shaped sibling-restart-strategy default
3280/// for the `:supervisor :estrategia` axis — the canonical `one_for_one`
3281/// half of Learn You Some Erlang's `{one_for_one, intensity, 5, 60}`
3282/// worker-supervisor default, extracted as a typed `pub const` so every
3283/// substrate-side consumer that resolves "what
3284/// [`SupervisorSpec::estrategia`] variant does an author-omitted
3285/// `:estrategia` slot degrade onto?" reaches for exactly one substrate-
3286/// primitive [`RestartStrategy`].
3287///
3288/// The `:estrategia` default axis has three production consumers on the
3289/// substrate side today: the [`Default for RestartStrategy`] impl's
3290/// return arm, the [`Default for SupervisorSpec`] impl's struct-literal
3291/// `estrategia` field, and the
3292/// [`crate::manifest::Caixa::supervisor_view`] fold's
3293/// `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)` `Option<RestartStrategy>`
3294/// collapse arm — three entry points onto the same OTP-canonical
3295/// `one_for_one` value that prior to this lift folded onto a raw
3296/// `Self::OneForOne` arm at the [`Default for RestartStrategy`] impl and
3297/// implicit `RestartStrategy::default()` routes at the sibling consumers,
3298/// with no compile-time link back to the paired
3299/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` half + the paired
3300/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` half of the same
3301/// `{one_for_one, intensity, 5, 60}` OTP-canonical default. The paired
3302/// triple was split across three altitudes with no compile-time link
3303/// between the halves: the `MaxIntensity` half rode through the lifted
3304/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant (b698ec0) and the `Period`
3305/// half rode through the lifted [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3306/// constant (f7dcd0e) while the `one_for_one` half rode as an open-coded
3307/// discriminator at the [`Default for RestartStrategy`] impl, so a future
3308/// coherent rebrand of the triple (Elixir's `{:one_for_one,
3309/// max_restarts: 3, max_seconds: 5}` — same strategy, different
3310/// intensity/period; an OTP `rest_for_one` widening once the substrate
3311/// discovers startup-order-coupled child cohorts as the more common
3312/// worker-supervisor default; a per-cluster overlay the operator pins
3313/// through a future `:estrategia-overrides` slot the MESH-COMPOSITION
3314/// §III.2 supervision-canary roadmap acknowledges) would have had to
3315/// migrate the `MaxIntensity` + `Period` halves through the lifted
3316/// constants and the `one_for_one` half through an open-coded arm in
3317/// lockstep or the three halves of the same OTP-canonical default would
3318/// silently drift out of pairing. Lifting the resolution rule to a typed
3319/// `pub const` on the substrate primitive means the paired OTP-canonical
3320/// worker-supervisor default migrates as one unit on any future axis
3321/// change.
3322///
3323/// The [`RestartStrategy::OneForOne`] value pins Learn You Some Erlang's
3324/// `{one_for_one, intensity, 5, 60}` worker-supervisor default (the
3325/// closest canonical OTP-shape production reference the substrate
3326/// carries, matching the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5`
3327/// `MaxIntensity` half and the paired [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3328/// `60s` `Period` half). The `one_for_one` strategy — restart only the
3329/// failed child, leaving siblings untouched — is the default for tree-of-
3330/// independent-workers use cases the substrate's [`RestartStrategy`]
3331/// discriminator's own docstring already carries as the default arm; it
3332/// composes with the `{5, 60}` restart-intensity ratio to name the same
3333/// substrate-canonical "canonical worker-supervisor" shape the paired
3334/// halves close on their respective axes.
3335///
3336/// Lifted as a typed `pub const` so the paired OTP-canonical default has
3337/// exactly one source of truth on each of its three halves — the sibling
3338/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half, the
3339/// sibling [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` `60s` half, and
3340/// this `one_for_one` strategy half now share the same substrate-
3341/// primitive lift discipline. Same shape every other typed default in
3342/// this crate carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] +
3343/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] paired halves on the same OTP-
3344/// canonical `{one_for_one, intensity, 5, 60}`, the sibling
3345/// [`SUPERVISOR_MAX_RESTARTS_MAX`] + [`SUPERVISOR_RESTART_WINDOW_MAX`]
3346/// upper caps on the paired sibling axes, and the peer
3347/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
3348/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes).
3349pub const SUPERVISOR_ESTRATEGIA_DEFAULT: RestartStrategy = RestartStrategy::OneForOne;
3350
3351/// Substrate-canonical Erlang/OTP-shaped per-child restart-decision-policy
3352/// default for the `:children :restart` axis — the OTP `permanent`
3353/// worker-child default (`{ChildId, StartFunc, permanent, …}` in a
3354/// `supervisor`'s `init/1` child-spec tuple), extracted as a typed
3355/// `pub const` so every substrate-side consumer that resolves "what
3356/// [`ChildSpec::restart`] variant does an author-omitted `:children
3357/// :restart` slot degrade onto?" reaches for exactly one substrate-
3358/// primitive [`RestartPolicy`].
3359///
3360/// Completes the OTP-shape supervisor-tree default set at the substrate
3361/// primitive. The per-`:supervisor` axis already carries all three of its
3362/// halves as lifted typed constants — [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
3363/// (`one_for_one`, 95ffacc), [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
3364/// (`MaxIntensity` `5`, b698ec0), [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3365/// (`Period` `60s`, f7dcd0e) — while the per-`:children` axis's own
3366/// OTP-canonical default rode as an open-coded `Self::Permanent` arm in
3367/// the [`Default for RestartPolicy`] impl, the last un-lifted default on
3368/// the M2 `:supervisor` slot family. The split mattered because the two
3369/// axes resolve *together* on every author-omitted supervisor: a
3370/// `(defcaixa :kind Supervisor :children ((:caixa "worker" :versao
3371/// "^0.1")))` with no `:estrategia` and no per-child `:restart` degrades
3372/// onto `{one_for_one, 5, 60}` through three lifted constants and onto
3373/// `permanent` through an open-coded enum arm, so a future coherent
3374/// rebrand of the OTP-shape default set (an Elixir-shaped
3375/// `{:one_for_one, max_restarts: 3, max_seconds: 5}` tightening, a
3376/// per-cluster overlay the operator pins through the MESH-COMPOSITION
3377/// §III.2 supervision-canary roadmap slots, an OTP-`transient` widening
3378/// once the substrate discovers clean-completion-aware children as the
3379/// more common child shape) would have had to migrate three halves
3380/// through typed constants and the fourth through a raw enum arm in
3381/// lockstep or the supervisor-level and child-level defaults would
3382/// silently drift apart.
3383///
3384/// The `:children :restart` default axis has two production consumers on
3385/// the substrate side today: the [`Default for RestartPolicy`] impl's
3386/// return arm, and the serde-side `#[serde(default)]` on
3387/// [`ChildSpec::restart`] that resolves an author-omitted `:children
3388/// :restart` slot through that same impl. Both now key off this one
3389/// substrate primitive, so the future wasm-operator's per-child post-exit
3390/// restart-decision branch, the future M4
3391/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
3392/// admission webhook, and the `caixa-operator`'s hierarchical
3393/// reconciliation scheduler's per-child fan-out all reach for one typed
3394/// identifier when they resolve an omitted per-child restart posture.
3395///
3396/// The [`RestartPolicy::Permanent`] value pins Erlang/OTP's `permanent`
3397/// worker-child restart type — always restart the child regardless of how
3398/// it died, the canonical posture for long-running services that must
3399/// always be up, matching the sibling [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
3400/// `one_for_one` tree-of-independent-workers strategy this constant pairs
3401/// with under the same `{one_for_one, intensity, 5, 60}` worker-supervisor
3402/// shape. The two alternatives the closed [`RestartPolicy::ALL`] accept-set
3403/// carries ([`RestartPolicy::Transient`] — restart only on abnormal exit;
3404/// [`RestartPolicy::Temporary`] — never restart) express deliberate
3405/// one-shot / clean-completion-aware postures an author declares
3406/// explicitly, never a posture an omitted slot should silently assume.
3407pub const SUPERVISOR_CHILD_RESTART_DEFAULT: RestartPolicy = RestartPolicy::Permanent;
3408
3409/// Route the manually-authored [`Default`] impl on [`SupervisorSpec`]
3410/// through the substrate-canonical [`SupervisorSpec::otp_canonical`]
3411/// `pub const fn` constructor rather than a struct-literal cascade over
3412/// the paired [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
3413/// [`default_max_restarts`] / [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3414/// lifted consts — one source of truth for the Erlang/OTP-canonical
3415/// `{one_for_one, 5, 60}` worker-supervisor baseline across the two
3416/// paths every downstream consumer already reaches through (the
3417/// hand-authored-until-now [`Default::default`] the
3418/// `..SupervisorSpec::default()` struct-update-syntax on every
3419/// one-axis-under-test fixture in this crate's test module rests on,
3420/// and the `pub const fn` [`SupervisorSpec::otp_canonical`] constructor
3421/// every `const`-context consumer reaches through).
3422///
3423/// Extends the [`Default`]-through-const-ctor fold discipline the
3424/// [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
3425/// (abd52c2), [`crate::aplicacao::MeshPolicy`]
3426/// [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`] (91641a4),
3427/// and [`crate::BehaviorSpec`]
3428/// [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c) folds
3429/// closed on the M2 / M3 `Option`-only "canonical unset baseline"
3430/// typed-slot spec family — extended here onto the M2 supervisor-slot
3431/// [`SupervisorSpec`] whose canonical baseline is not "everything
3432/// `None`" but the OTP-canonical `{one_for_one, 5, 60}` worker-
3433/// supervisor triple. The `empty()` peer's naming did not fit
3434/// (`SupervisorSpec` carries a discriminator-shaped `estrategia` field
3435/// and a non-zero `max_restarts`/`restart_window` pair whose canonical
3436/// shape is Erlang/OTP-descended, not the "no axis declared" bottom
3437/// the sibling `Option`-only slots fold to), so this peer is named
3438/// [`SupervisorSpec::otp_canonical`] instead — the same phrasing the
3439/// existing per-arm pin tests
3440/// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`] /
3441/// [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`] /
3442/// [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
3443/// already reach for. Pinned load-bearing by
3444/// [`tests::supervisor_spec_default_routes_through_otp_canonical_ctor`]
3445/// (byte-parity pin against [`SupervisorSpec::otp_canonical`] under
3446/// [`PartialEq`], sharpening the sibling
3447/// `supervisor_spec_default_*_routes_through_lifted_default` per-arm
3448/// pins from a per-field lift into a whole-struct one-source-of-truth
3449/// pin — the derived-until-now [`Default::default`] and the
3450/// [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
3451/// construction, not by coincidence).
3452impl Default for SupervisorSpec {
3453 #[inline]
3454 fn default() -> Self {
3455 Self::otp_canonical()
3456 }
3457}
3458
3459impl SupervisorSpec {
3460 /// `const`-context peer of the [`Default for SupervisorSpec`]
3461 /// impl (which routes through this constructor) — returns the
3462 /// Erlang/OTP-canonical `{one_for_one, 5, 60}` worker-supervisor
3463 /// baseline this crate reaches for in every fixture-builder
3464 /// `..SupervisorSpec::default()` struct-update expression and
3465 /// every downstream `SupervisorSpec::default()` seed.
3466 ///
3467 /// Each field routes through the same substrate-canonical
3468 /// [`SUPERVISOR_ESTRATEGIA_DEFAULT`] / [`default_max_restarts`] /
3469 /// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] lifted consts the
3470 /// per-arm pin tests
3471 /// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`]
3472 /// / [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`]
3473 /// / [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
3474 /// already assert, so a future coherent rebrand of the OTP-canonical
3475 /// triple (Elixir's `{max_restarts: 3, max_seconds: 5}`, a per-
3476 /// cluster overlay via a future `:restart-window-overrides` slot, a
3477 /// per-child-cohort promotion the INSPIRATIONS.md §II.2 Erlang/OTP
3478 /// absorption roadmap acknowledges) migrates through three typed
3479 /// constants in lockstep, and the paired [`Default`] impl inherits
3480 /// every future extension by construction.
3481 ///
3482 /// `pub const fn` rather than the derived-style `Default::default`
3483 /// or a `pub const SUPERVISOR_SPEC_DEFAULT: SupervisorSpec` item —
3484 /// [`Default::default`] is not `const` on stable Rust, and
3485 /// `SupervisorSpec` is non-`Copy` so a `pub const` item would force
3486 /// every consumer through a [`Clone::clone`]. The `pub const fn`
3487 /// discipline lets `const`-context callers construct the OTP-
3488 /// canonical baseline at compile time without runtime dispatch on
3489 /// the derived [`Default::default`], the same posture the sibling
3490 /// [`crate::LimitsSpec::empty`] (9739971) /
3491 /// [`crate::aplicacao::MeshPolicy::empty`] (6df969b) /
3492 /// [`crate::BehaviorSpec::empty`] (f9b18e3) `Option`-only typed-slot
3493 /// spec `pub const fn` constructors carry on the sibling
3494 /// "everything `None`" baseline axis.
3495 ///
3496 /// Fourth peer on the M2 / M3 typed-slot-spec "const-context peer
3497 /// of the derived-style [`Default`]" family — sibling of the
3498 /// [`crate::LimitsSpec::empty`] / [`crate::aplicacao::MeshPolicy::empty`]
3499 /// / [`crate::BehaviorSpec::empty`] `Option`-only "canonical unset
3500 /// baseline" trio, extended here onto the M2 supervisor-slot
3501 /// [`SupervisorSpec`] whose canonical baseline is not "everything
3502 /// `None`" but the Erlang/OTP-canonical `{one_for_one, 5, 60}`
3503 /// worker-supervisor triple. Named [`Self::otp_canonical`] rather
3504 /// than `empty()` to name the actual invariant the return value
3505 /// pins — the same phrasing already used in the per-arm pin tests
3506 /// on this file. Pinned load-bearing by
3507 /// [`tests::supervisor_spec_otp_canonical_byte_equals_default`] and
3508 /// [`tests::supervisor_spec_otp_canonical_is_usable_in_const_context`].
3509 #[must_use]
3510 pub const fn otp_canonical() -> Self {
3511 Self {
3512 estrategia: SUPERVISOR_ESTRATEGIA_DEFAULT,
3513 max_restarts: default_max_restarts(),
3514 restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3515 children: Vec::new(),
3516 }
3517 }
3518
3519 /// Substrate-canonical per-`:supervisor` `:estrategia` OTP-shaped
3520 /// sibling-restart-strategy scalar accessor every consumer that
3521 /// dispatches on the supervisor's per-sibling restart-decision shape
3522 /// keys off — returns the author-declared `:supervisor :estrategia`
3523 /// variant verbatim as a [`RestartStrategy`], `Copy`-projected from
3524 /// the typed slot's own [`RestartStrategy`] storage.
3525 ///
3526 /// The `:supervisor :estrategia` slot carries the closed-set
3527 /// OTP-shaped sibling-restart-strategy discriminator ([`RestartStrategy::OneForOne`]
3528 /// — restart only the failed child, the Erlang/OTP `one_for_one` default;
3529 /// [`RestartStrategy::OneForAll`] — restart every child on any child
3530 /// failure, the Erlang/OTP `one_for_all` shared-state cohort default;
3531 /// [`RestartStrategy::RestForOne`] — restart the failed child and
3532 /// every child started after it, the Erlang/OTP `rest_for_one`
3533 /// startup-order default; [`RestartStrategy::SimpleOneForOne`] —
3534 /// dynamic children of the same shape, the Erlang/OTP
3535 /// `simple_one_for_one` per-session default) that every downstream
3536 /// consumer of the Supervisor's per-sibling restart-decision fan-out
3537 /// shape keys off. Validated by [`SupervisorSpec::validate`] to be
3538 /// paired coherently with the sibling `:children` axis
3539 /// (`SimpleOneForOne ↔ children.is_empty()` — the cross-slot
3540 /// partition the strategy-arm's [`SupervisorError::SimpleOneForOneWithStaticChildren`]
3541 /// / [`SupervisorError::NoChildren`] refusal cascade pins), and every
3542 /// downstream consumer that reads the strategy keys off this scalar
3543 /// (the [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
3544 /// partition-dispatch `match` arm, the non-`SimpleOneForOne`-arm
3545 /// declared-but-empty [`SupervisorError::NoChildren`] error carrier's
3546 /// `estrategia:` field, the future `feira app graph` per-Supervisor
3547 /// strategy print line, the future wasm-operator's per-supervisor
3548 /// sibling-restart-strategy branch, the future M4
3549 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-strategy
3550 /// admission-webhook resolver, the `caixa-operator`'s hierarchical
3551 /// reconciliation scheduler's per-strategy fan-out).
3552 ///
3553 /// Prior to this lift the `.estrategia` field was accessed inline at
3554 /// two production sites in `caixa-core/src/supervisor.rs` — the
3555 /// [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
3556 /// `match self.estrategia { … }` partition dispatch, and the
3557 /// non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
3558 /// carrier at `estrategia: self.estrategia` — two open-coded
3559 /// field-accesses that expressed no compile-time link back to the
3560 /// typed slot. A future extension of the `:supervisor :estrategia`
3561 /// axis to a richer author surface (a per-cluster strategy override
3562 /// the operator pins through a future `:supervisor :estrategia-overrides`
3563 /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
3564 /// acknowledges, a per-tenant strategy-alias table the M4 CR
3565 /// materializer resolves per-CR, a per-Supervisor dynamic strategy
3566 /// derivation the future adaptive-supervision engine computes from
3567 /// child-failure-history topology, a per-child-cohort strategy split
3568 /// the future `RestForCohort` extension acknowledged by the
3569 /// INSPIRATIONS.md §II.2 Erlang/OTP absorption roadmap acknowledges)
3570 /// would have had to be threaded through every open-coded copy in
3571 /// lockstep — one consumer reading the raw variant while a peer read
3572 /// the operator-resolved variant would silently split the
3573 /// [`SupervisorError::NoChildren`] diagnostic's quoted strategy from
3574 /// the actual partition-dispatch input the empty-children refusal
3575 /// arm reached under, a two-consumer split at the validator far from
3576 /// the source `caixa.lisp` with no field naming the strategy-drift
3577 /// root cause. Lifting the resolution rule to a typed method on the
3578 /// substrate primitive means every downstream consumer of the
3579 /// Supervisor's per-`:supervisor` sibling-restart-strategy surface
3580 /// reaches for exactly one typed dispatch — the resolver's accept-set
3581 /// migrates as a unit on any future axis addition.
3582 ///
3583 /// Peer of the sibling M3 mesh-slot [`crate::Placement::estrategia`]
3584 /// (921fe1b) `Copy`-return `PlacementStrategy` scalar accessor on the
3585 /// per-`:placement` distribution-strategy axis — same "one typed
3586 /// dispatch on the substrate primitive, thin projections at each
3587 /// consumer" discipline extended onto the M2 supervisor-slot
3588 /// per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
3589 /// scalar axis. The two typed axes (`Placement::estrategia` on the
3590 /// M3 Aplicacao side, `SupervisorSpec::estrategia` on the M2
3591 /// Supervisor side) now share one accessor discipline for the shared
3592 /// substrate concept "a `Copy`-projected closed-set enum-arm
3593 /// discriminator that partitions the downstream renderer's per-arm
3594 /// fan-out". First `Copy`-return accessor on the M2 supervisor-slot
3595 /// `SupervisorSpec` type — companion to the sibling per-`:children`
3596 /// [`crate::ChildSpec::nome`] (57c61d0) /
3597 /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
3598 /// scalar accessors on the sibling per-`:children` `String`-carry
3599 /// axes. Named `estrategia()` to match the storage field's name and
3600 /// the peer [`crate::Placement::estrategia`] method-name discipline
3601 /// verbatim; the accessor's identity name maps onto the canonical
3602 /// OTP-shape supervision vocabulary the [`RestartStrategy`] enum's
3603 /// docstring already carries.
3604 ///
3605 /// Declared `pub const fn` to close the M2 supervisor-slot
3606 /// `Copy`-return raw-field-getter `const`-eval-surface pass —
3607 /// sibling of the peer M2 per-`:children` [`ChildSpec::restart`]
3608 /// (converted in this commit) `Copy`-composite-enum accessor, peer
3609 /// of the sibling M2 per-`:supervisor`
3610 /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
3611 /// already lifted, and mirror of the peer M3 mesh-slot
3612 /// per-`:placement` [`crate::Placement::estrategia`] (bafa004)
3613 /// `Copy`-return `pub const fn` scalar accessor whose method-name
3614 /// discipline this accessor was authored to match. Every downstream
3615 /// substrate-side `const`-context consumer of the per-`:supervisor`
3616 /// sibling-restart-strategy scalar (a future module-scope `const
3617 /// _:() = assert!(matches!(sup.estrategia(),
3618 /// RestartStrategy::OneForOne))` invariant pin on a typed fixture,
3619 /// a future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
3620 /// admission-webhook `const fn` per-supervisor strategy-arm floor
3621 /// over a typed [`SupervisorSpec`], any future `const fn`
3622 /// supervisor-tree composer over the substrate primitive that fans
3623 /// on the sibling-restart-strategy at compile time) now reaches
3624 /// through the same typed dispatch on the substrate primitive at
3625 /// const-eval time as at runtime. A future non-`Copy`-return
3626 /// promotion of the scalar (an `Option<RestartStrategy>`-shape
3627 /// migration once the substrate grows per-cluster strategy overlays
3628 /// the [`SupervisorSpec`] docstring already anticipates, a
3629 /// per-tenant strategy-alias table the M4 CR materializer resolves
3630 /// per-CR) that would drop the `const` qualifier fails the
3631 /// fail-before-pass-after pin
3632 /// [`tests::supervisor_spec_estrategia_accessor_is_const_fn`] at
3633 /// caixa-core build time rather than surfacing as a downstream
3634 /// consumer regression.
3635 #[must_use]
3636 pub const fn estrategia(&self) -> RestartStrategy {
3637 self.estrategia
3638 }
3639
3640 /// Substrate-canonical per-`:supervisor` `:max-restarts` OTP-shaped
3641 /// `MaxIntensity` restart-budget scalar accessor every consumer that
3642 /// reads the supervisor's per-`:restart-window` restart-budget count
3643 /// keys off — returns the author-declared `:supervisor :max-restarts`
3644 /// typed `u32` verbatim, `Copy`-projected from the typed slot's own
3645 /// `u32` storage (`u32` is `Copy`, so the accessor returns by value; no
3646 /// borrow of `&self` past the call). Non-optional (the `u32` field
3647 /// carries the restart-budget count as a required axis with a
3648 /// [`default_max_restarts`]-supplied default; the zero-floor arm
3649 /// [`SupervisorError::ZeroMaxRestarts`] and the cap arm
3650 /// [`SupervisorError::MaxRestartsExceedsCap`] jointly bracket the
3651 /// accept-set to `1..=SUPERVISOR_MAX_RESTARTS_MAX`).
3652 ///
3653 /// The `:supervisor :max-restarts` slot carries the Erlang/OTP
3654 /// `MaxIntensity` restart-budget count that pairs with the sibling
3655 /// `:restart-window` `Period` to form the `MaxIntensity / Period`
3656 /// restart-intensity ratio the supervisor trips its own escalation on
3657 /// (`theory/RUNTIME-PATTERNS.md` §II.2, Learn You Some Erlang's
3658 /// `{intensity, 5, 60}` worker-supervisor default). Every downstream
3659 /// consumer of the Supervisor's per-`:supervisor` restart-budget count
3660 /// keys off this scalar (the [`SupervisorSpec::validate`] zero-floor +
3661 /// upper-cap bracket at
3662 /// `require_positive_bounded_u32(self.max_restarts(), …)`, the future
3663 /// wasm-operator's per-supervisor restart-intensity counter's
3664 /// budget-vs-count comparator, the future M4
3665 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3666 /// webhook, the `caixa-operator`'s hierarchical reconciliation
3667 /// scheduler's per-supervisor escalation-decision branch, every
3668 /// `SupervisorError::MaxRestartsExceedsCap` variant carrying the
3669 /// offending count verbatim for `feira lint` rendering).
3670 ///
3671 /// Prior to this lift the `.max_restarts` field was accessed inline at
3672 /// one production site in `caixa-core/src/supervisor.rs` — the
3673 /// [`SupervisorSpec::validate`] `require_positive_bounded_u32(self
3674 /// .max_restarts, …)` bracket-gate call — one open-coded field-access
3675 /// that expressed no compile-time link back to the typed slot. A
3676 /// future extension of the `:max-restarts` axis to a richer author
3677 /// surface (a per-cluster restart-budget override the operator pins
3678 /// through a future `:supervisor :max-restarts-overrides` slot the
3679 /// MESH-COMPOSITION §III.2 supervision-canary roadmap acknowledges,
3680 /// a per-tenant restart-budget-alias table the M4 CR materializer
3681 /// resolves per-CR, a per-supervisor dynamic restart-budget derivation
3682 /// the future adaptive-supervision engine computes from child-failure-
3683 /// history topology, a promotion of the plain `u32` count to a richer
3684 /// `{MaxR, MaxT}` tuple once Erlang/OTP's per-child-cohort restart-
3685 /// budget-partition slot comes into scope) would have had to be
3686 /// threaded through every open-coded copy in lockstep or the validate
3687 /// gate and the future M4 emit path would silently disagree on which
3688 /// restart-budget count a given supervisor resolves to — an author's
3689 /// `:max-restarts 5` would satisfy validate while the emit path
3690 /// silently read a drifted other value (a `:max-restarts 10000`
3691 /// no-op supervisor at the emit boundary would carry the author's
3692 /// declared `5` verbatim in `feira lint` output while the future
3693 /// wasm-operator's restart-intensity counter operated under the
3694 /// drifted count), a two-consumer split at the validator far from the
3695 /// source `caixa.lisp` with no field naming the restart-budget-drift
3696 /// root cause. Lifting the resolution rule to a typed method on the
3697 /// substrate primitive means every downstream consumer of the
3698 /// Supervisor's per-`:supervisor` restart-budget-count surface reaches
3699 /// for exactly one typed dispatch — the resolver's accept-set migrates
3700 /// as a unit on any future axis addition.
3701 ///
3702 /// Peer of the sibling M3 mesh-slot [`crate::CircuitBreaker::max_failures`]
3703 /// (3a74062) `Copy`-return `u32` sub-struct required-scalar accessor
3704 /// on the per-`:politicas :circuit-breaker :max-failures` Envoy-
3705 /// outlier-detection trip-threshold axis — same "one typed dispatch on
3706 /// the substrate primitive, thin projections at each consumer"
3707 /// discipline extended onto the M2 supervisor-slot per-`:supervisor`
3708 /// restart-budget-count `Copy`-`u32` scalar axis. The two typed axes
3709 /// (`CircuitBreaker::max_failures` on the M3 Aplicacao side,
3710 /// `SupervisorSpec::max_restarts` on the M2 Supervisor side) now share
3711 /// one accessor discipline for the shared substrate concept "a
3712 /// `Copy`-projected required `u32` count that trips the next-higher
3713 /// protection layer after N events in a rolling window" — both are
3714 /// counters with identical degenerate-at-the-high-end shape and share
3715 /// the paired [`crate::POLICY_BREAKER_MAX_FAILURES_MAX`] /
3716 /// [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` cap. Second `Copy`-return
3717 /// accessor on the M2 supervisor-slot `SupervisorSpec` type, sibling
3718 /// to the [`SupervisorSpec::estrategia`] (eafb619) `Copy`-composite-
3719 /// enum `RestartStrategy` accessor. Named `max_restarts()` to match
3720 /// the storage field's name verbatim and the peer
3721 /// [`crate::CircuitBreaker::max_failures`] method-name discipline; the
3722 /// accessor's identity maps onto the canonical OTP-shape supervision
3723 /// vocabulary the [`SupervisorSpec::max_restarts`] field's docstring
3724 /// already carries.
3725 #[must_use]
3726 pub const fn max_restarts(&self) -> u32 {
3727 self.max_restarts
3728 }
3729
3730 /// Substrate-canonical per-`:supervisor` `:restart-window` OTP-shaped
3731 /// `Period` sliding-window scalar accessor every consumer of the
3732 /// supervisor's `MaxIntensity / Period` restart-intensity denominator
3733 /// keys off — returns the author-declared `:supervisor :restart-window`
3734 /// typed [`Duration`] verbatim as an `Option<Duration>`, copied out of
3735 /// the typed slot's own `Option<Duration>` storage (`Duration` is
3736 /// `Copy`, so `Option<Duration>` is `Copy` and the accessor returns by
3737 /// value; no borrow of `&self` past the call). `None` when the slot is
3738 /// absent (the canonical "never reset — every restart across the
3739 /// supervisor's lifetime counts against the sibling `:max-restarts`
3740 /// budget" sentinel the field's own docstring names and the peer
3741 /// `validate_accepts_none_restart_window` pin locks in on the
3742 /// [`SupervisorSpec::validate`] entry-side).
3743 ///
3744 /// The `:supervisor :restart-window` slot carries the Erlang/OTP
3745 /// `Period` sliding-observation-interval that pairs with the sibling
3746 /// `:max-restarts` `MaxIntensity` restart-budget count to form the
3747 /// `MaxIntensity / Period` restart-intensity ratio the supervisor
3748 /// trips its own escalation on (`theory/RUNTIME-PATTERNS.md` §II.2,
3749 /// Learn You Some Erlang's `{intensity, 5, 60}` worker-supervisor
3750 /// default). The typed slot's `Option<Duration>` accept-set —
3751 /// zero-floor rejected through [`SupervisorError::RestartWindowZero`]
3752 /// (Erlang/OTP's `MaxIntensity / Period` invariant requires
3753 /// `Period > 0`; a zero period either trips on the first failure or
3754 /// never trips depending on operator interpretation, neither of which
3755 /// is the author's intent — omit the slot to express "no reset";
3756 /// carry a positive duration to express the sliding window),
3757 /// integer-millisecond canonical form enforced through
3758 /// [`SupervisorError::RestartWindowNotCanonical`] (the duration
3759 /// codec's canonical form emits `"1500ms"` not `"1.5s"` and the
3760 /// future wasm-operator's per-supervisor restart-intensity counter
3761 /// quantizes at milliseconds), upper-bounded by
3762 /// [`SUPERVISOR_RESTART_WINDOW_MAX`] (1h — the coarsest per-
3763 /// supervisor rolling window any operationally-reachable supervisor
3764 /// can honor without spanning multiple scheduler epochs the
3765 /// hierarchical-reconciliation scheduler treats as independent) —
3766 /// maps onto the future wasm-operator (M3) per-supervisor
3767 /// restart-intensity counter's rolling-observation-interval, the
3768 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
3769 /// per-`spec.restartWindow` admission webhook, and the sibling
3770 /// `duration_codec`-serialized wire scalar every downstream consumer
3771 /// of the supervisor's per-`:supervisor` restart-intensity denominator
3772 /// keys off.
3773 ///
3774 /// Prior to this lift the `.restart_window` field was accessed inline
3775 /// at one production site in `caixa-core/src/supervisor.rs` — the
3776 /// [`SupervisorSpec::validate`] `if let Some(w) = self.restart_window {
3777 /// … }` zero-floor + canonical-form + upper-cap bracket arm — one
3778 /// open-coded field-access that expressed no compile-time link back to
3779 /// the typed slot. A future extension of the `:restart-window` axis to
3780 /// a richer author surface (a per-cluster restart-window override the
3781 /// operator pins through a future `:supervisor :restart-window-overrides`
3782 /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
3783 /// acknowledges, a per-tenant restart-window-alias table the M4 CR
3784 /// materializer resolves per-CR, a per-supervisor dynamic
3785 /// restart-window derivation the future adaptive-supervision engine
3786 /// computes from child-failure-history topology, a promotion of the
3787 /// plain `Option<Duration>` window to a richer `{observation, cooldown}`
3788 /// pair once Erlang/OTP's per-child-cohort observation-interval-
3789 /// partition slot comes into scope) would have had to be threaded
3790 /// through every open-coded copy in lockstep or the validate gate and
3791 /// the future M4 emit path would silently disagree on which
3792 /// restart-window a given supervisor resolves to — an author's
3793 /// `:restart-window "60s"` would satisfy validate while the emit path
3794 /// silently read a drifted other value (a `Some(Duration::from_secs(60))`
3795 /// authored slot at the emit boundary would carry the author's
3796 /// declared window verbatim in `feira lint` output while the future
3797 /// wasm-operator's restart-intensity counter operated under a
3798 /// drifted window, or vice versa: an author's `:restart-window ()`
3799 /// would carry the "never reset" sentinel through validate while the
3800 /// emit path silently substituted a default sliding window), a
3801 /// two-consumer split at the validator far from the source
3802 /// `caixa.lisp` with no field naming the restart-window-drift root
3803 /// cause. Lifting the resolution rule to a typed method on the
3804 /// substrate primitive means every downstream consumer of the
3805 /// Supervisor's per-`:supervisor` restart-intensity-denominator
3806 /// surface reaches for exactly one typed dispatch — the resolver's
3807 /// accept-set migrates as a unit on any future axis addition.
3808 ///
3809 /// Third `Copy`-return accessor on the M2 supervisor-slot
3810 /// `SupervisorSpec` type, closing the last unlifted per-`:supervisor`
3811 /// scalar-value axis (`children: Vec<ChildSpec>` carries a `Vec`
3812 /// payload rather than a `Copy`-scalar, and the per-`:children`
3813 /// [`crate::ChildSpec::nome`] (57c61d0) /
3814 /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
3815 /// scalar accessors already close the per-element `String`-carry
3816 /// axes). Sibling to the peer M2 [`crate::LimitsSpec::wall_clock`]
3817 /// (8cb717b) `Option<Duration>` accessor on the `:limits` slot's
3818 /// per-outermost-call wall-clock-deadline axis and the peer M3
3819 /// [`crate::MeshPolicy::timeout`] (7073d0f) `Option<Duration>`
3820 /// accessor on the `:politicas` slot's per-call-deadline axis — all
3821 /// three share the shared substrate concept "a `Copy`-projected
3822 /// optional `Duration` that carries a positive integer-millisecond
3823 /// canonical value with a `1ms..=<axis-specific>_MAX` accept-set and
3824 /// the paired zero-floor / non-canonical / above-cap refusal cascade"
3825 /// through the same [`crate::render::require_positive_canonical_bounded_duration`]
3826 /// bracket-helper the three axes each route through. Named
3827 /// `restart_window()` to match the storage field's name verbatim and
3828 /// the peer [`crate::LimitsSpec::wall_clock`] /
3829 /// [`crate::MeshPolicy::timeout`] method-name discipline; the
3830 /// accessor's identity maps onto the canonical OTP-shape supervision
3831 /// vocabulary the [`SupervisorSpec::restart_window`] field's docstring
3832 /// already carries.
3833 #[must_use]
3834 pub const fn restart_window(&self) -> Option<Duration> {
3835 self.restart_window
3836 }
3837
3838 /// Substrate-canonical per-`:supervisor` `:children` OTP-shaped
3839 /// static-child-list slice accessor every consumer that walks the
3840 /// supervisor's declared child set keys off — returns the author-
3841 /// declared `:supervisor :children` `Vec<ChildSpec>` verbatim as a
3842 /// `&[ChildSpec]` slice-view, borrowed from the typed slot's own
3843 /// `Vec<ChildSpec>` storage (a zero-copy slice-view over the same
3844 /// backing buffer the `Serialize`/`Deserialize` derives round-trip
3845 /// through). Non-optional: an empty slice is the load-bearing
3846 /// "author declared `:children ()`" sentinel every consumer of the
3847 /// cross-slot `SimpleOneForOne ↔ children.is_empty()` partition
3848 /// keys off (`SimpleOneForOne` requires the empty slice; the peer
3849 /// three strategies require a non-empty slice — the paired
3850 /// [`SupervisorError::SimpleOneForOneWithStaticChildren`] /
3851 /// [`SupervisorError::NoChildren`] refusal cascade pins the
3852 /// partition on both arms).
3853 ///
3854 /// The `:supervisor :children` slot carries the OTP-shaped static
3855 /// child list the supervisor materializes one ComputeUnit per
3856 /// entry from — the Erlang/OTP `supervisor:init/1`'s
3857 /// `{ok, {SupFlags, ChildSpecs}}` `ChildSpecs` list, projected
3858 /// through the tatara-lisp `:children` author surface onto a typed
3859 /// `Vec<ChildSpec>` whose per-element `(nome(),
3860 /// versao_requirement(), restart)` triple the per-child
3861 /// [`SupervisorSpec::validate`] loop already gates through the
3862 /// lifted [`ChildSpec::nome`] (57c61d0) /
3863 /// [`ChildSpec::versao_requirement`] (2c053c8) scalar accessors.
3864 /// Every downstream consumer that fans on the static child list
3865 /// keys off this slice (the [`SupervisorSpec::validate`]
3866 /// `SimpleOneForOne ↔ non-SimpleOneForOne` partition dispatch's
3867 /// `.is_empty()` probe on both arms, the [`SupervisorSpec::validate`]
3868 /// per-child DNS-1123 / semver-requirement / duplicate-detection
3869 /// fan-out loop, every future wasm-operator (M3) per-supervisor
3870 /// hierarchical-reconciliation scheduler's per-child ComputeUnit
3871 /// materialization loop, the future M4
3872 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
3873 /// admission-webhook fan-out, the future `feira app graph`
3874 /// per-supervisor tree-print traversal).
3875 ///
3876 /// Prior to this lift the `.children` `Vec<ChildSpec>` was accessed
3877 /// inline at three production sites in `caixa-core/src/supervisor.rs`
3878 /// — the [`SupervisorSpec::validate`] `SimpleOneForOne`-arm
3879 /// `!self.children.is_empty()` cross-slot refusal probe, the peer
3880 /// non-`SimpleOneForOne`-arm `self.children.is_empty()`
3881 /// [`SupervisorError::NoChildren`] refusal probe, and the per-child
3882 /// validate loop's `for child in &self.children` traversal head —
3883 /// three open-coded field-accesses that expressed no compile-time
3884 /// link back to the typed slot. A future extension of the
3885 /// `:supervisor :children` axis to a richer author surface (a
3886 /// per-cluster child-set overlay the operator pins through a future
3887 /// `:supervisor :children-overrides` slot the MESH-COMPOSITION §III.2
3888 /// supervision-canary roadmap acknowledges, a per-tenant
3889 /// child-set-alias table the M4 CR materializer resolves per-CR,
3890 /// a per-supervisor dynamic-child derivation the future adaptive-
3891 /// supervision engine computes from child-failure-history topology,
3892 /// a promotion of the plain `Vec<ChildSpec>` to a richer
3893 /// `{static, dynamic}` partition once Erlang/OTP's
3894 /// `simple_one_for_one` dynamic-child slot comes into typed scope)
3895 /// would have had to be threaded through all three open-coded copies
3896 /// in lockstep or one consumer would silently disagree with the
3897 /// peers on which child-set a given supervisor resolves to — the
3898 /// `SimpleOneForOne`-arm probe reading the raw slot while the peer
3899 /// non-`SimpleOneForOne`-arm probe read an operator-resolved slot
3900 /// would silently split the partition-dispatch's two-arm coherence
3901 /// (a supervisor that satisfies neither arm's precondition, or that
3902 /// satisfies both, at the cost of the paired
3903 /// `SimpleOneForOneWithStaticChildren`/`NoChildren` refusal cascade
3904 /// silently drifting from the per-child validate loop's actual
3905 /// traversal input), a three-consumer split at the validator far
3906 /// from the source `caixa.lisp` with no field naming the
3907 /// child-set-drift root cause. Lifting the resolution rule to a
3908 /// typed method on the substrate primitive means every downstream
3909 /// consumer of the Supervisor's per-`:supervisor` static-child-list
3910 /// surface reaches for exactly one typed dispatch — the resolver's
3911 /// accept-set migrates as a unit on any future axis addition.
3912 ///
3913 /// First slice-return (`&[T]`) accessor on any M2 or M3 typed slot
3914 /// — the seed for the same "one typed dispatch on the substrate
3915 /// primitive, thin projections at each consumer" discipline the
3916 /// closed [`crate::LimitsSpec`] / [`BehaviorSpec`] /
3917 /// [`crate::UpgradeFromEntry`] scalar-accessor families each carry
3918 /// on their `Copy` / `Option<Copy>` / `Option<&str>` axes, extended
3919 /// onto the first `Vec`-carry axis on the substrate. The four peer
3920 /// `Vec`-carry axes still unlifted at the time of this seed —
3921 /// [`crate::Placement::clusters`] (`Vec<String>` per-cluster
3922 /// distribution-target list), [`crate::AplicacaoSpec::membros`]
3923 /// (`Vec<Membro>` per-Aplicacao member list),
3924 /// [`crate::AplicacaoSpec::contratos`] (`Vec<WitContract>`
3925 /// per-Aplicacao WIT-typed edge list),
3926 /// [`crate::UpgradeFromEntry::instructions`]
3927 /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
3928 /// — inherit this accessor's discipline as future compounding runs
3929 /// migrate their consumers onto the shared slice-return shape.
3930 /// Fourth (and final) accessor on the M2 supervisor-slot
3931 /// `SupervisorSpec` type, sibling to the three `Copy`-return
3932 /// [`SupervisorSpec::estrategia`] (eafb619) /
3933 /// [`SupervisorSpec::max_restarts`] (7844f4e) /
3934 /// [`SupervisorSpec::restart_window`] (7e7b32f) accessors — closes
3935 /// the last unlifted per-`:supervisor` field axis (the
3936 /// `Vec<ChildSpec>` static-child-list carrier) so every downstream
3937 /// per-`:supervisor` reader now routes through a typed dispatch on
3938 /// the substrate primitive. Named `children()` to match the storage
3939 /// field's name verbatim and the tatara-lisp author-surface term
3940 /// (`:children`) the field's own docstring already carries; the
3941 /// accessor's identity maps onto the canonical OTP-shape
3942 /// supervision vocabulary the [`SupervisorSpec::children`] field's
3943 /// docstring already reaches for ("Static children ..."). Returns
3944 /// `&[ChildSpec]` (not `&Vec<ChildSpec>`) because every downstream
3945 /// consumer of the child list treats it as a read-only sequence —
3946 /// the slice-view is the narrowest borrow that supports every
3947 /// present + roadmapped consumer (`.is_empty()`, `.iter()`,
3948 /// index, `.len()`) without leaking the backing `Vec`'s
3949 /// grow/push/reserve surface that no consumer of the typed view
3950 /// reaches for (the storage-side `Vec` remains reachable through
3951 /// the `pub children` field for the mutation-carrying
3952 /// `Caixa::supervisor_view` fold-in path in
3953 /// `manifest.rs:supervisor_view`).
3954 #[must_use]
3955 pub const fn children(&self) -> &[ChildSpec] {
3956 self.children.as_slice()
3957 }
3958
3959 /// Validate the supervisor's typed shape — strategy ↔ children
3960 /// invariants, max_restarts > 0, restart_window > 0 when set,
3961 /// per-child non-empty + duplicate-free names.
3962 ///
3963 /// Mirrors the value-shape discipline applied to every other
3964 /// typed slot:
3965 ///
3966 /// - `Some(Duration::ZERO)` on a Duration-bearing axis is the
3967 /// same "0 means the opposite of what you think" footgun
3968 /// closed for `:politicas :timeout` (Envoy interprets a zero
3969 /// timeout as `infinite`), `:politicas :circuit-breaker
3970 /// :window`, and `:limits :wall-clock`. The
3971 /// `MaxIntensity / Period` ratio in Erlang/OTP's
3972 /// `supervisor` requires `Period > 0`; a zero period either
3973 /// trips on the first failure or never trips depending on
3974 /// operator interpretation, neither of which is the
3975 /// author's intent. Omit `:restart-window` to express "no
3976 /// reset"; carry a positive duration to express the window.
3977 /// - duplicate `:children` `:caixa` names are the same
3978 /// graph-node-set / multiset distinction closed for
3979 /// `:membros` (4bb3f3d), `:placement :clusters` (c7c7799),
3980 /// and `:entrada :paths` (eb3456d). Two children with the
3981 /// same `:caixa` materialize as two ComputeUnits with the
3982 /// same name in the cluster's HelmRelease values, one
3983 /// silently overwriting the other. Erlang/OTP's
3984 /// `child_spec.id` is required-unique per supervisor;
3985 /// pleme-io enforces the same set-not-multiset shape on
3986 /// `:caixa` (the load-bearing identity in our renderer).
3987 pub fn validate(&self) -> Result<(), SupervisorError> {
3988 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition
3989 // dispatch and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
3990 // error carrier's `estrategia:` field through the lifted
3991 // [`SupervisorSpec::estrategia`] accessor rather than the raw
3992 // `self.estrategia` field access — the two production consumers
3993 // of the per-`:supervisor` sibling-restart-strategy scalar now
3994 // key off exactly one typed dispatch on the substrate primitive,
3995 // so any future rebrand on the axis (a per-cluster strategy
3996 // override the operator pins through a future `:supervisor
3997 // :estrategia-overrides` slot, a per-tenant strategy-alias table
3998 // the M4 CR materializer resolves per-CR) migrates as a single
3999 // caixa-core edit rather than a coordinated rewrite of the two
4000 // call sites — sibling of the peer M3 [`crate::Placement::estrategia`]
4001 // (921fe1b) four-consumer migration on the per-`:placement`
4002 // distribution-strategy axis.
4003 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition-
4004 // dispatch's paired `.is_empty()` cross-slot refusal probes
4005 // (the `SimpleOneForOne`-arm
4006 // [`SupervisorError::SimpleOneForOneWithStaticChildren`] refusal
4007 // and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
4008 // refusal) through the lifted [`SupervisorSpec::children`]
4009 // slice-return accessor rather than the raw `self.children`
4010 // field access — the two paired production consumers of the
4011 // per-`:supervisor` static-child-list scalar-shape now key off
4012 // exactly one typed dispatch on the substrate primitive, so any
4013 // future rebrand on the axis (a per-cluster child-set overlay
4014 // the operator pins through a future `:supervisor
4015 // :children-overrides` slot, a per-tenant child-set-alias table
4016 // the M4 CR materializer resolves per-CR) migrates as a single
4017 // caixa-core edit rather than a coordinated rewrite of the
4018 // paired arms — first slice-return migration on any typed slot,
4019 // seed for the peer per-`:placement :clusters`,
4020 // per-`:membros`, per-`:contratos`, and per-`:upgrade-from
4021 // :instructions` `Vec`-carry axes.
4022 match self.estrategia() {
4023 RestartStrategy::SimpleOneForOne => {
4024 // SimpleOneForOne: children added at runtime. Static
4025 // list must be empty (one shape declared elsewhere).
4026 if !self.children().is_empty() {
4027 return Err(SupervisorError::SimpleOneForOneWithStaticChildren);
4028 }
4029 }
4030 _ => {
4031 if self.children().is_empty() {
4032 return Err(SupervisorError::no_children(self.estrategia()));
4033 }
4034 }
4035 }
4036 // Zero-floor + upper-cap bracket on the typed `:max-restarts`
4037 // axis. See [`crate::render::require_positive_bounded_u32`] for
4038 // the ordering discipline (zero-floor arm strictly precedes cap
4039 // arm so `0` surfaces the self-locating `ZeroMaxRestarts`
4040 // diagnostic with its counter-axis remediation directly named,
4041 // not the misleading `0 > SUPERVISOR_MAX_RESTARTS_MAX == false`
4042 // cap-arm miss). Until this bracket landed the top edge ran all
4043 // the way to `u32::MAX` and a struct-literal
4044 // `SupervisorSpec { max_restarts: 100_000, .. }` (or the
4045 // equivalent author-surface `:max-restarts 100000` /
4046 // `:max-restarts 4294967295` typo landing in the slot) silently
4047 // passed validate. The runtime substrate consuming the value
4048 // (Erlang/OTP's `MaxIntensity / Period` ratio, the future
4049 // wasm-operator's per-supervisor restart-intensity counter, the
4050 // M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
4051 // admission webhook) then turned a typed `:max-restarts`
4052 // policy into a no-op supervisor: the escalation threshold is
4053 // structurally so high that no realistic
4054 // restarts-per-`:restart-window` traffic shape can reach it,
4055 // the supervisor never escalates to its parent, and a bad
4056 // child can loop inside the window indefinitely with the
4057 // parent supervisor structurally never receiving the "this
4058 // subtree has exceeded its restart budget" signal the typed
4059 // slot is meant to express. The bracket set is
4060 // `1..=SUPERVISOR_MAX_RESTARTS_MAX`, peer with the
4061 // [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap on
4062 // the sibling `:politicas :circuit-breaker :max-failures` axis:
4063 // both are "trip the next-higher protection layer after N
4064 // events in a rolling window" counters with identical
4065 // degenerate-at-the-high-end shape and now share one canonical
4066 // bracket helper. The bracket precedes the sibling
4067 // `:restart-window` zero-floor / canonical-millisecond arms so
4068 // an over-cap `max_restarts` paired with a structurally invalid
4069 // window surfaces the bracket diagnostic first, mirroring the
4070 // `PolicyBreakerMaxFailuresExceedsCap` / window-axis cross-arm
4071 // ordering on the peer `:politicas :circuit-breaker` slot.
4072 // Route the [`SupervisorSpec::validate`] `:max-restarts` zero-floor +
4073 // upper-cap bracket-gate through the lifted [`SupervisorSpec::max_restarts`]
4074 // accessor rather than the raw `self.max_restarts` field access —
4075 // the one production consumer of the per-`:supervisor`
4076 // restart-budget-count scalar now keys off exactly one typed
4077 // dispatch on the substrate primitive, so any future rebrand on
4078 // the axis (a per-cluster restart-budget override the operator
4079 // pins through a future `:supervisor :max-restarts-overrides`
4080 // slot, a per-tenant restart-budget-alias table the M4 CR
4081 // materializer resolves per-CR) migrates as a single caixa-core
4082 // edit rather than a coordinated rewrite — sibling of the peer M3
4083 // [`crate::CircuitBreaker::max_failures`] (3a74062) migration on
4084 // the per-`:politicas :circuit-breaker :max-failures` axis.
4085 crate::render::require_positive_bounded_u32(
4086 self.max_restarts(),
4087 SUPERVISOR_MAX_RESTARTS_MAX,
4088 || SupervisorError::ZeroMaxRestarts,
4089 SupervisorError::max_restarts_exceeds_cap,
4090 )?;
4091 // Route the [`SupervisorSpec::validate`] `:restart-window`
4092 // zero-floor + integer-millisecond canonical-form + upper-cap
4093 // bracket-gate through the lifted [`SupervisorSpec::restart_window`]
4094 // accessor rather than the raw `self.restart_window` field access —
4095 // the one production consumer of the per-`:supervisor`
4096 // restart-intensity-denominator scalar now keys off exactly one
4097 // typed dispatch on the substrate primitive, so any future rebrand
4098 // on the axis (a per-cluster restart-window override the operator
4099 // pins through a future `:supervisor :restart-window-overrides`
4100 // slot, a per-tenant restart-window-alias table the M4 CR
4101 // materializer resolves per-CR) migrates as a single caixa-core
4102 // edit rather than a coordinated rewrite — sibling of the peer M2
4103 // [`crate::LimitsSpec::wall_clock`] (8cb717b) validate-arm-route
4104 // on the per-`:limits :wall-clock` axis and the peer M3
4105 // [`crate::MeshPolicy::timeout`] (7073d0f) accessor-route on the
4106 // per-`:politicas :timeout` axis.
4107 if let Some(w) = self.restart_window() {
4108 // Zero-floor + integer-millisecond canonical-form +
4109 // upper-cap bracket on the typed `:restart-window` axis.
4110 // See
4111 // [`crate::render::require_positive_canonical_bounded_duration`]
4112 // for the full three-arm ordering discipline (zero-floor
4113 // strictly precedes canonical-form so `Duration::ZERO`
4114 // surfaces the self-locating `RestartWindowZero`
4115 // diagnostic; canonical-form strictly precedes the cap arm
4116 // so a sub-millisecond above-cap value surfaces the more
4117 // fundamental round-trip-shape diagnostic first) and the
4118 // three peer typed-`Duration` sites that share this
4119 // canonical bracket ([`crate::MeshPolicy::timeout`],
4120 // [`crate::CircuitBreaker::window`],
4121 // [`crate::LimitsSpec::wall_clock`]). Every validated
4122 // value lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
4123 // (1ms..=1h), integer-millisecond granularity.
4124 crate::render::require_positive_canonical_bounded_duration(
4125 w,
4126 SUPERVISOR_RESTART_WINDOW_MAX,
4127 || SupervisorError::RestartWindowZero,
4128 SupervisorError::restart_window_not_canonical,
4129 SupervisorError::restart_window_exceeds_cap,
4130 )?;
4131 }
4132 // Route the per-child DNS-1123 / semver-requirement / duplicate-
4133 // detection fan-out loop through the lifted named per-slot gate
4134 // [`SupervisorSpec::validate_children`] rather than an inline
4135 // three-per-child cascade — every future consumer that wants to
4136 // re-check only the `:children` slot's per-entry axes (the M4
4137 // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
4138 // admission webhook re-validating one added/renamed child, the
4139 // future wasm-operator's per-child dynamic-add re-validator on
4140 // the `SimpleOneForOne` runtime-add path once dynamic-children
4141 // graduate to a typed slot, a future partial re-validator on a
4142 // per-`:children`-entry patch) reaches every per-entry axis
4143 // through one dispatch rather than re-inlining the three-arm
4144 // cascade in lockstep with `validate` or paying the peer
4145 // `:estrategia`/`:max-restarts`/`:restart-window` gates to
4146 // reach one entry check. Sibling of the peer M3 mesh-slot
4147 // per-slot gate family (`validate_membros` — the exact peer on
4148 // the M3 side, [`crate::AplicacaoSpec::validate_membros`];
4149 // `validate_contratos` — 906a5c6; `validate_entrada` — 20cd523;
4150 // `validate_placement`; `validate_politicas` routing through
4151 // `MeshPolicy::validate` — f03a154) — the M2 supervisor-slot
4152 // per-slot gate discipline now spans both the M3 mesh-slot
4153 // family and the M2 `:children` per-child-cascade axis on one
4154 // shape: one named per-slot gate per typed per-entry loop.
4155 self.validate_children()?;
4156 Ok(())
4157 }
4158
4159 /// Named per-slot gate on the M2 `:supervisor :children` per-entry
4160 /// axis — folds the per-child DNS-1123 name gate, semver-requirement
4161 /// gate, and duplicate-`:caixa` dedup arm into one call every
4162 /// consumer that wants to re-validate one `:children` entry (or the
4163 /// whole list) against the same accept-set [`SupervisorSpec::validate`]
4164 /// admits reaches through.
4165 ///
4166 /// Peer of the M3 mesh-slot [`crate::AplicacaoSpec::validate_membros`]
4167 /// per-slot gate on the analogous per-entry axis (`:membros`) — same
4168 /// three-per-entry shape (DNS-1123 name + semver-requirement +
4169 /// duplicate-`:caixa` dedup), lifted to one named substrate
4170 /// primitive per slot. The M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
4171 /// materializer's admission webhook re-checking one added or renamed
4172 /// child, the future wasm-operator's per-child dynamic-add
4173 /// re-validator on the `SimpleOneForOne` runtime-add path once
4174 /// dynamic-children graduate to a typed slot, a future partial
4175 /// re-validator on a per-`:children`-entry patch — each reaches the
4176 /// three per-entry axes through this one dispatch rather than
4177 /// re-inlining the three-arm cascade in lockstep with `validate`
4178 /// (the duplication the PRIME DIRECTIVE names as a bug) or paying
4179 /// the peer `:estrategia`/`:max-restarts`/`:restart-window` gates to
4180 /// reach one entry check.
4181 ///
4182 /// Self-contained on `&self` — resolves its own dedup `HashSet`
4183 /// through [`SupervisorSpec::children`] rather than borrowing one
4184 /// threaded down from `validate`, the same posture the peer M3
4185 /// mesh-slot per-slot gates ([`crate::AplicacaoSpec::validate_membros`],
4186 /// [`crate::AplicacaoSpec::validate_contratos`],
4187 /// [`crate::AplicacaoSpec::validate_entrada`],
4188 /// [`crate::AplicacaoSpec::validate_placement`]) each carry, so a
4189 /// consumer that reaches this gate directly (without first calling
4190 /// `validate`) still runs the full per-child cascade — pinned by
4191 /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
4192 /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
4193 /// + `validate_children_is_self_contained_on_children_slot`.
4194 ///
4195 /// The three per-entry arms run in the same canonical order the
4196 /// pre-lift inline cascade encoded (DNS-1123 → semver → dedup), so
4197 /// the diagnostic every author-declared per-`:children` entry surfaces
4198 /// through `validate` is byte-equal to the diagnostic this gate
4199 /// surfaces when called directly — the equivalence-pin pair
4200 /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
4201 /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
4202 /// asserts the two altitudes discriminate the same set on every
4203 /// per-entry-covered input.
4204 pub fn validate_children(&self) -> Result<(), SupervisorError> {
4205 let mut seen = std::collections::HashSet::new();
4206 for child in self.children() {
4207 // Every emitted cluster artifact's `metadata.name` for a
4208 // supervised child derives from this `:children :caixa` value
4209 // verbatim — the rendered `wasm.pleme.io/v1alpha1/ComputeUnit
4210 // .metadata.name` per child, the [`crate::LABEL_PROGRAM`]
4211 // label value on every child's pod identity, and the per-
4212 // child K8s [`Service`][svc] `metadata.name` the future
4213 // wasm-operator (M3) provisions for inter-child supervision
4214 // tree wiring. Each apiserver-side schema on each landing
4215 // site enforces the DNS-1123 label rule on admission; a
4216 // structurally invalid child name (`"Worker"`, `"my_worker"`,
4217 // `"team.worker"`, `"-worker"`, `"worker-"`, the >63-byte
4218 // UUID-shaped mistaken-identity slug) silently passes the
4219 // prior empty-/duplicate-only gate and the failure surfaces
4220 // at `kubectl apply` time as a `metadata.name: Invalid value`
4221 // rejection, far from the source caixa.lisp, with no field
4222 // naming the offending `:children` entry. Lifting the gate
4223 // to caixa-build time mirrors the `:membros :caixa` value-
4224 // shape trajectory (3f9d7a0) and the `:placement :clusters`
4225 // trajectory (6cbb900) onto the third DNS-1123-label-shaped
4226 // identifier axis — the supervisor tree's child names —
4227 // through the lifted
4228 // [`crate::render::require_valid_dns_1123_label`] gate the
4229 // seven peer name axes (`:membros :caixa`, `:placement
4230 // :clusters`, `:placement :affinity`, `:contratos :de`/`:para`,
4231 // `:entrada :para`, `:nome`, `:upgrade-from :module`) each
4232 // route through, so drift between the eight axes' accepted
4233 // DNS-1123-label sets is structurally impossible.
4234 //
4235 // [svc]: https://kubernetes.io/docs/concepts/services-networking/service/
4236 crate::render::require_valid_dns_1123_label(
4237 child.nome(),
4238 || SupervisorError::EmptyChildName,
4239 |reason| SupervisorError::child_caixa_invalid(child.nome(), reason),
4240 )?;
4241 // The author surface for `:children :versao` is the same
4242 // Cargo-shaped semver requirement string `:deps :versao` and
4243 // `:membros :versao` carry — and the lacre pipeline resolves
4244 // all three axes through the same
4245 // [`crate::version::parse_requirement`] entry-point. The
4246 // shared [`crate::render::require_valid_versao_requirement`]
4247 // helper brackets the empty-first + parse cascade both peer
4248 // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
4249 // [`crate::AplicacaoSpec::validate_membros`] on `:membros
4250 // :versao`) route through, so drift between the three axes'
4251 // accepted requirement sets is structurally impossible and
4252 // the parse-side no-op the empty-first arm closes (semver's
4253 // empty parse yields an implicit `*`) lives in exactly one
4254 // predicate. Every `ChildSpec::versao` past validate is
4255 // round-trippable through [`crate::parse_requirement`]
4256 // without re-checking at the resolver layer, and the three
4257 // `:versao` typed surfaces (`:deps`, `:membros`, `:children`)
4258 // are now structurally equivalent by construction.
4259 crate::render::require_valid_versao_requirement(
4260 child.versao_requirement(),
4261 || SupervisorError::empty_child_version(child.nome()),
4262 |reason| {
4263 SupervisorError::child_versao_invalid(
4264 child.nome(),
4265 child.versao_requirement(),
4266 reason,
4267 )
4268 },
4269 )?;
4270 crate::render::insert_first_seen(&mut seen, child.nome(), || {
4271 SupervisorError::duplicate_child_caixa(child.nome())
4272 })?;
4273 }
4274 Ok(())
4275 }
4276}
4277
4278/// Cross-slot coherence gate on the supervision tree: no
4279/// `:children :caixa` entry may name the supervisor's own `:nome`.
4280///
4281/// A supervisor that lists itself as a child is a degenerate self-parent
4282/// — the supervision tree is a DAG rooted at the supervisor (OTP child
4283/// specs reference *distinct* child processes; a supervisor is never its
4284/// own child), and the wasm-operator's hierarchical reconciliation would
4285/// otherwise be handed a node that is its own parent: a one-node cycle it
4286/// either rejects far from the source `caixa.lisp` or recurses on. Because
4287/// every `:nome` is a globally-unique substrate identity (DNS-1123 label +
4288/// lacre closure root), a child whose `:caixa` equals the supervisor's
4289/// `:nome` *is* the supervisor itself, not a coincidentally-named peer.
4290///
4291/// Lives outside [`SupervisorSpec::validate`] because the typed view
4292/// carries the children but not the parent `:nome`; mirrors the
4293/// cross-slot precedence gate `validate_upgrade_from_against_versao`
4294/// (which likewise reads one slot against another at the
4295/// [`crate::layout`] wire-up site) and the mesh self-edge gate
4296/// `AplicacaoSpec`'s `ContratoSelfLoop` — the same "an edge from a graph
4297/// node to itself is structurally not a tree/mesh edge" discipline, here
4298/// on the supervision-tree axis.
4299pub fn validate_no_self_supervision(
4300 children: &[ChildSpec],
4301 parent_nome: &str,
4302) -> Result<(), SupervisorError> {
4303 for child in children {
4304 if child.nome() == parent_nome {
4305 return Err(SupervisorError::child_supervises_self(parent_nome));
4306 }
4307 }
4308 Ok(())
4309}
4310
4311#[derive(Debug, Error, PartialEq, Eq)]
4312pub enum SupervisorError {
4313 #[error("supervisor :estrategia {estrategia:?} requires at least one :children entry")]
4314 NoChildren { estrategia: RestartStrategy },
4315 #[error(
4316 "SimpleOneForOne supervisors must declare zero static children (children spawn dynamically)"
4317 )]
4318 SimpleOneForOneWithStaticChildren,
4319 #[error(":max-restarts must be > 0")]
4320 ZeroMaxRestarts,
4321 #[error(
4322 ":supervisor :max-restarts ({max_restarts}) exceeds the supervisor-policy ceiling \
4323 (SUPERVISOR_MAX_RESTARTS_MAX = 1000) — a value above this cap turns the typed \
4324 restart-intensity policy into a no-op supervisor: the escalation threshold is \
4325 structurally so high that no realistic restarts-per-:restart-window traffic shape \
4326 can reach it, so the supervisor never escalates to its parent and a bad child can \
4327 loop inside the window indefinitely. Every typed-slot consumer (Erlang/OTP's \
4328 MaxIntensity/Period ratio, the future wasm-operator's per-supervisor \
4329 restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
4330 materializer's admission webhook) emits a `:max-restarts` declaration that is \
4331 structurally never reached. Pin a value in 1..=1000 (Erlang/OTP / Elixir / Riak \
4332 Core / RabbitMQ production playbooks recommend 3..=100; the OTP `supervisor` \
4333 callback module's `MaxR = 1` minimal-restart default sits at the bottom of the \
4334 band) or restructure the supervision tree (split the flaky child into its own \
4335 sub-supervisor with a tighter budget) if you need a higher restart tolerance."
4336 )]
4337 MaxRestartsExceedsCap { max_restarts: u32 },
4338 #[error(
4339 ":restart-window must be > 0 when set — Erlang/OTP's MaxIntensity/Period \
4340 requires Period > 0; a zero window either trips on the first failure or \
4341 never trips depending on operator interpretation. Omit :restart-window to \
4342 express `never reset`; carry a positive duration to express the window."
4343 )]
4344 RestartWindowZero,
4345 #[error(
4346 ":supervisor :restart-window ({window:?}) carries a sub-millisecond residue the shared `duration_codec` cannot round-trip — \
4347 the codec truncates to `as_millis()` before picking the canonical unit, so a value with `subsec_nanos() % 1_000_000 != 0` either \
4348 truncates on first serialize (e.g. `Duration::from_micros(1500)` → \"1ms\" → `Duration::from_millis(1)` ≠ original) or renders \
4349 as \"0s\" the `RestartWindowZero` arm then rejects on re-validate. Pin an integer-millisecond magnitude in the canonical authoring form \
4350 (`<integer><unit>` for unit ∈ {{ms, s, m, h}}, e.g. `\"500ms\"`, `\"30s\"`, `\"2m\"`, `\"1h\"`) or omit the field for `never reset`"
4351 )]
4352 RestartWindowNotCanonical { window: Duration },
4353 #[error(
4354 ":supervisor :restart-window ({window:?}) exceeds the supervisor-policy ceiling \
4355 (SUPERVISOR_RESTART_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
4356 per-supervisor rolling-window restart-intensity counter into a lifetime counter: the \
4357 failure-counting window is structurally so long that transient restarts are never \
4358 forgotten, the MaxIntensity/Period ratio degenerates from `trip the parent supervisor \
4359 when the child has exceeded its restart budget within the recent window` to `trip the \
4360 parent when the child has exceeded its restart budget over its lifetime`, and the \
4361 supervisor's reset semantic never reaches the child — every typed-slot consumer \
4362 (Erlang/OTP's MaxIntensity/Period reconciler, the future wasm-operator's \
4363 per-supervisor restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
4364 materializer's admission webhook, the caixa-operator's hierarchical reconciliation \
4365 scheduler) emits a `:restart-window` declaration that is structurally a no-op rolling \
4366 window. Pin a value in 1ms..=1h (Learn You Some Erlang's `{{intensity, 5, 60}}` \
4367 worker-supervisor `Period = 60s` default, Elixir's `Supervisor` `max_seconds: 5` \
4368 default, OTP's `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's \
4369 `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default — every Erlang/OTP \
4370 / Elixir production playbook sits in the 5s..=300s band; the longest documented \
4371 per-supervisor restart-window any pleme-io substrate playbook recommends maxes at \
4372 ~30m) or omit :restart-window to express `never reset` (the supervisor's restart \
4373 budget then becomes a strict lifetime counter by design, not a degenerate one — the \
4374 author surfaces the lifetime-counter semantic explicitly at the slot, rather than \
4375 hiding it behind a rolling-window declaration the cap arm rejects)"
4376 )]
4377 RestartWindowExceedsCap { window: Duration },
4378 #[error("child entry has empty :caixa name")]
4379 EmptyChildName,
4380 #[error(
4381 "child :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
4382 (the K8s apiserver enforces this rule on every `metadata.name` / Service \
4383 name / label value the child name lands in — the per-child \
4384 `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name`, the `LABEL_PROGRAM` \
4385 label value, and the future wasm-operator per-child Service `metadata.name` \
4386 — each apiserver-side schema rejects names that don't match; use a \
4387 lowercase alphanumeric + hyphen identifier like `\"worker\"` or `\"cache-v2\"`)"
4388 )]
4389 ChildCaixaInvalid { caixa: String, reason: String },
4390 #[error("child {caixa:?} has empty :versao constraint")]
4391 EmptyChildVersion { caixa: String },
4392 #[error(
4393 "child {caixa:?} :versao {versao:?} is not a valid semver requirement: \
4394 {reason} (use Cargo-shaped forms like `\"^0.1\"`, `\"~0.1.2\"`, \
4395 `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` and \
4396 `:membros :versao` carry; the lacre pipeline resolves all three \
4397 through the same parser)"
4398 )]
4399 ChildVersaoInvalid {
4400 caixa: String,
4401 versao: String,
4402 reason: String,
4403 },
4404 #[error(
4405 "child {caixa:?} appears more than once (Erlang/OTP requires unique \
4406 child_spec.id per supervisor; duplicate children materialize as duplicate \
4407 ComputeUnits in the rendered chart, one silently overwriting the other)"
4408 )]
4409 DuplicateChildCaixa { caixa: String },
4410 #[error(
4411 "supervisor {caixa:?} lists itself as a :children entry — a supervisor is \
4412 never its own child (the supervision tree is a DAG rooted at the supervisor; \
4413 OTP child specs reference distinct child processes). Since every :nome is a \
4414 globally-unique substrate identity, a child naming the supervisor's own :nome \
4415 is a one-node reconciliation cycle, not a coincidentally-named peer; drop the \
4416 self-referential :children entry or rename it to the actual child caixa."
4417 )]
4418 ChildSupervisesSelf { caixa: String },
4419}
4420
4421// Fold the three `SupervisorError::<Variant> { caixa: <&str>.to_string() }`
4422// caixa-only struct-variant wire-up sites at [`SupervisorSpec::validate_children`]
4423// and [`validate_no_self_supervision`] onto one substrate primitive per
4424// typed variant — the sibling on `SupervisorError` of the four uniform-shape
4425// `LayoutError`-envelope constructor families the peer
4426// [`crate::layout::layout_violation_ctors!`] macro closed (131ca0d, 16
4427// variants on `{ caixa, issue }`), the [`crate::layout::layout_slot_kind_ctors!`]
4428// macro closed (0419438, 4 variants on `{ caixa, kind, slots }`), the
4429// [`crate::LayoutError::missing_entry`] one-variant ctor closed (1b09f9d,
4430// on `{ kind, path }`), and the [`crate::layout::layout_nome_only_ctors!`]
4431// macro closed (3fe3dd7, 6 variants on `<Variant>(String)`), plus the
4432// [`crate::AplicacaoError::entrada_host_invalid`] one-variant ctor
4433// (17dd504, `{ host, reason }`), the [`crate::aplicacao::contrato_target_ctors!`]
4434// macro (14b81d5, 2 variants on `{ de, para, wit, expected }`), and the
4435// [`crate::aplicacao::contrato_empty_pair_ctors!`] macro (8580068, 4
4436// variants on `{ de, para }`) already at that discipline on the peer
4437// `AplicacaoError` envelopes.
4438//
4439// Each of the three wire-up sites on this shape (`EmptyChildVersion` at
4440// the per-`:children` semver-requirement empty-first arm, `DuplicateChildCaixa`
4441// at the per-`:children` dedup arm, `ChildSupervisesSelf` at the cross-slot
4442// self-supervision arm) opened the identical
4443// `SupervisorError::<Variant> { caixa: <&str>.to_string() }` struct-literal —
4444// the exact "same block re-inlined at every consumer" shape the PRIME
4445// DIRECTIVE names as a bug, on the same altitude the peer `LayoutError` /
4446// `AplicacaoError` families each closed on their sibling envelopes. The
4447// three variants share one `{ caixa: String }` shape, so the fold routes
4448// each wire-up site through one dispatch per typed variant.
4449//
4450// The macro below generates one static constructor per variant of shape
4451// `fn <slot>(caixa: &str) -> SupervisorError`, so every wire-up site
4452// collapses onto one dispatch:
4453// `SupervisorError::<slot>(<&str>)`, byte-equal to the pre-lift
4454// struct-literal on the same `&str` fixture. The uniform one-field
4455// construction (`caixa: caixa.to_string()`) is spelled once — inside the
4456// macro — rather than at every wire-up site. Every constructor is
4457// `#[must_use]` so a caller who mistakenly discards the constructed error
4458// trips a compile warning at the wire-up site.
4459//
4460// Every future consumer that wants to construct one of these three
4461// variants outside `SupervisorSpec::validate_children` /
4462// `validate_no_self_supervision` — a deferred
4463// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
4464// webhook re-checking one added/renamed child, a future
4465// `feira validate --supervisor` per-caixa admission verb, a per-child
4466// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path
4467// once dynamic-children graduate to a typed slot, a per-Supervisor
4468// overlay resolver rejecting a duplicate/self-supervising child against
4469// a cluster-local snapshot — now reaches each variant through one call
4470// rather than re-inlining the three-line struct-literal in lockstep
4471// with the three in-crate wire-up sites.
4472macro_rules! supervisor_caixa_only_ctors {
4473 ($($ctor:ident => $variant:ident),* $(,)?) => {
4474 impl SupervisorError {
4475 $(
4476 #[doc = concat!(
4477 "Construct a [`SupervisorError::",
4478 stringify!($variant),
4479 "`] naming the offending `:children :caixa` (or ",
4480 "supervisor `:nome`, on the self-supervision arm). ",
4481 "Folds the uniform `Self::",
4482 stringify!($variant),
4483 " { caixa: caixa.to_string() }` one-field ",
4484 "struct-literal onto one substrate primitive so ",
4485 "every [`SupervisorSpec::validate_children`] / ",
4486 "[`validate_no_self_supervision`] wire-up on this ",
4487 "variant reads through one dispatch rather than the ",
4488 "pre-lift open-coded struct-literal block."
4489 )]
4490 #[must_use]
4491 pub fn $ctor(caixa: &str) -> Self {
4492 Self::$variant { caixa: caixa.to_string() }
4493 }
4494 )*
4495 }
4496 };
4497}
4498
4499supervisor_caixa_only_ctors! {
4500 empty_child_version => EmptyChildVersion,
4501 duplicate_child_caixa => DuplicateChildCaixa,
4502 child_supervises_self => ChildSupervisesSelf,
4503}
4504
4505// Fold the two `SupervisorError::{ChildCaixaInvalid, ChildVersaoInvalid}`
4506// struct-variant wire-up sites at [`SupervisorSpec::validate_children`] onto
4507// one substrate primitive per typed variant — the M2 supervisor-side siblings
4508// of the peer [`crate::AplicacaoError::membro_caixa_invalid`] two-slot ctor
4509// already lifted through the sibling
4510// [`crate::aplicacao::aplicacao_field_reason_ctors!`] macro (981060b) on the
4511// peer `AplicacaoError { caixa: String, reason: String }` envelope. The
4512// `ChildCaixaInvalid` variant carries the same `{ <name>: String, reason:
4513// String }` two-slot shape the peer seven-variant
4514// [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold closed on the
4515// `AplicacaoError` envelope (`MembroCaixaInvalid`, `EntradaParaInvalid`,
4516// `EntradaHostInvalid`, `EntradaPathInvalid`, `PlacementClusterInvalid`,
4517// `PlacementAffinityInvalid`, `ShardKeyInvalid`); the `ChildVersaoInvalid`
4518// variant carries the `{ caixa: String, versao: String, reason: String }`
4519// three-slot shape the sibling `AplicacaoError::MembroVersaoInvalid` axis
4520// carries on the same `:versao` value-shape.
4521//
4522// Each of the two wire-up sites opened the same closure-shaped
4523// `|reason| SupervisorError::<Variant> { caixa: child.nome().to_string(),
4524// [versao: child.versao_requirement().to_string(),] reason }` block inside
4525// the paired [`crate::render::require_valid_dns_1123_label`] and
4526// [`crate::render::require_valid_versao_requirement`] callbacks — the exact
4527// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE names
4528// as a bug, on the same altitude the peer `AplicacaoError` /
4529// `SupervisorError` / `LayoutError` / `DepError` / `LimitsError` ctor
4530// families already closed on their sibling envelopes.
4531//
4532// The two `#[must_use]` inherent constructors below fold each wire-up onto
4533// one dispatch: `SupervisorError::child_caixa_invalid(<name>, <reason>)`
4534// and `SupervisorError::child_versao_invalid(<name>, <versao>, <reason>)`,
4535// byte-equal to the pre-lift struct-literal on the same scalar fixtures.
4536// The uniform per-field `.to_string()` / `.into()` construction is spelled
4537// once — inside each ctor body — rather than at every wire-up site. The
4538// `reason: impl Into<String>` bound accepts both `&str` literals and
4539// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
4540// diagnostic shape at the lift, matching the peer
4541// [`aplicacao_field_reason_ctors!`] and
4542// [`crate::aplicacao::contrato_pair_value_reason_ctors!`] bounds on the
4543// sibling envelopes.
4544//
4545// Every future consumer that wants to construct one of these two variants
4546// outside `SupervisorSpec::validate_children` — a deferred
4547// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook
4548// re-checking one added/renamed child's `:caixa` or `:versao`, a future
4549// `feira validate --supervisor` per-caixa admission verb, a per-child
4550// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path once
4551// dynamic-children graduate to a typed slot, a per-Supervisor overlay
4552// resolver rejecting a shape-invalid child `:caixa`/`:versao` against a
4553// cluster-local snapshot — now reaches each variant through one call rather
4554// than re-inlining the per-shape struct-literal block in lockstep with the
4555// two in-crate wire-up sites.
4556impl SupervisorError {
4557 /// Construct a [`SupervisorError::ChildCaixaInvalid`] naming the
4558 /// offending `:children :caixa` value under the given `reason`. Folds
4559 /// the uniform `Self::ChildCaixaInvalid { caixa: caixa.to_string(),
4560 /// reason: reason.into() }` two-slot struct-literal onto one substrate
4561 /// primitive so every wire-up on this variant reads through one
4562 /// dispatch, matching the peer
4563 /// [`crate::AplicacaoError::membro_caixa_invalid`] ctor's shape on the
4564 /// sibling `AplicacaoError { caixa: String, reason: String }`
4565 /// envelope. `reason` accepts both `&str` literals and `format!(…)`
4566 /// outputs through the `impl Into<String>` bound.
4567 #[must_use]
4568 pub fn child_caixa_invalid(caixa: &str, reason: impl Into<String>) -> Self {
4569 Self::ChildCaixaInvalid {
4570 caixa: caixa.to_string(),
4571 reason: reason.into(),
4572 }
4573 }
4574
4575 /// Construct a [`SupervisorError::ChildVersaoInvalid`] naming the
4576 /// offending `:children :caixa` and its `:versao` requirement under
4577 /// the given `reason`. Folds the uniform `Self::ChildVersaoInvalid {
4578 /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
4579 /// reason.into() }` three-slot struct-literal onto one substrate
4580 /// primitive so every wire-up on this variant reads through one
4581 /// dispatch, matching the sibling `AplicacaoError::MembroVersaoInvalid
4582 /// { caixa, versao, reason }` three-slot axis on the peer
4583 /// `AplicacaoError` envelope. `reason` accepts both `&str` literals
4584 /// and `format!(…)` outputs through the `impl Into<String>` bound.
4585 #[must_use]
4586 pub fn child_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
4587 Self::ChildVersaoInvalid {
4588 caixa: caixa.to_string(),
4589 versao: versao.to_string(),
4590 reason: reason.into(),
4591 }
4592 }
4593}
4594
4595// Fold the four `SupervisorError::<Variant> { <field>: <Copy> }` one-field
4596// Copy-scalar struct-variant wire-up sites at [`SupervisorSpec::validate`]'s
4597// three bracket-arms — one struct-literal at the `:children`-empty
4598// non-`SimpleOneForOne` refusal cascade (`NoChildren { estrategia }`) plus
4599// three `impl FnOnce(<ty>) -> SupervisorError` bracket-closures at the
4600// [`crate::render::require_positive_bounded_u32`] `:max-restarts` cap arm
4601// (`MaxRestartsExceedsCap { max_restarts }`) and the paired
4602// [`crate::render::require_positive_canonical_bounded_duration`]
4603// `:restart-window` canonical-form + cap arms (`RestartWindowNotCanonical
4604// { window }`, `RestartWindowExceedsCap { window }`) — onto one substrate
4605// primitive per typed variant, matching the sibling
4606// [`crate::aplicacao::aplicacao_policy_scalar_ctors!`] macro (7ef425e, 8
4607// variants on the same `{ <field>: Duration | u32 }` shape) at that
4608// discipline on the peer `AplicacaoError` envelope's per-`:politicas`
4609// scalar axis. Every variant is a one-field `Copy`-pass-through struct-
4610// literal — `RestartStrategy | u32 | Duration` — so the fold routes each
4611// wire-up site through one dispatch per typed variant without a runtime-
4612// work delta.
4613//
4614// Each of the four wire-up sites opened the identical
4615// `SupervisorError::<Variant> { <field>: <val> }` struct-literal — the
4616// exact "same block re-inlined at every consumer" shape the PRIME
4617// DIRECTIVE names as a bug, on the same altitude the peer
4618// `aplicacao_policy_scalar_ctors!` fold closed on the sibling
4619// `AplicacaoError` envelope's per-`:politicas` per-axis cap / canonical-
4620// form arms. The four variants share one `{ <field>: <Copy> }` shape, so
4621// the fold routes each wire-up site through one dispatch per typed
4622// variant.
4623//
4624// The macro below generates one static constructor per variant of shape
4625// `const fn <ctor>(<field>: <ty>) -> SupervisorError`, so every wire-up
4626// site collapses onto one dispatch: `SupervisorError::<ctor>(<val>)`,
4627// byte-equal to the pre-lift struct-literal on the same `Copy`-`<ty>`
4628// fixture — as a direct call at the [`SupervisorSpec::validate`]
4629// `:children`-empty refusal, or as a bare function pointer in the
4630// `impl FnOnce(<ty>) -> SupervisorError` bracket-closure slot every
4631// [`crate::render::require_positive_bounded_u32`] /
4632// [`crate::render::require_positive_canonical_bounded_duration`] gate
4633// carries — rather than the pre-lift open-coded one-line closure over
4634// the same one-field struct-literal. `const fn` preserves the `Copy`-
4635// pass-through's zero-runtime-work property verbatim. Every constructor
4636// is `#[must_use]` so a caller who mistakenly discards the constructed
4637// error trips a compile warning at the wire-up site.
4638//
4639// Every future consumer that wants to construct one of these four
4640// variants outside `SupervisorSpec::validate` — a deferred
4641// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
4642// webhook re-checking one edited `:estrategia` / `:max-restarts` /
4643// `:restart-window` slot against the cap + canonical-form cascade, a
4644// future `feira validate --supervisor` per-caixa admission verb re-
4645// running the shape gates on demand, a per-Supervisor overlay resolver
4646// rejecting an author-supplied slot against a cluster-local snapshot —
4647// now reaches each variant through one call rather than re-inlining the
4648// per-shape struct-literal block in lockstep with the four in-crate
4649// wire-up sites.
4650macro_rules! supervisor_scalar_ctors {
4651 ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
4652 impl SupervisorError {
4653 $(
4654 #[doc = concat!(
4655 "Construct a [`SupervisorError::",
4656 stringify!($variant),
4657 "`] naming the offending per-`:supervisor` `",
4658 stringify!($field),
4659 "` scalar. Folds the uniform `Self::",
4660 stringify!($variant),
4661 " { ",
4662 stringify!($field),
4663 " }` one-field `Copy`-pass-through struct-literal onto ",
4664 "one substrate primitive so every per-axis wire-up on ",
4665 "this variant reads through one dispatch — as a direct ",
4666 "call (`SupervisorError::",
4667 stringify!($ctor),
4668 "(<val>)`, byte-equal to the pre-lift struct-literal on ",
4669 "the same `Copy`-`",
4670 stringify!($ty),
4671 "` fixture) or as a bare function pointer in the ",
4672 "`impl FnOnce(",
4673 stringify!($ty),
4674 ") -> SupervisorError` bracket-closure slot every ",
4675 "`crate::render::require_positive_bounded_*` / ",
4676 "`crate::render::require_positive_canonical_bounded_*` ",
4677 "gate carries — rather than the pre-lift open-coded ",
4678 "one-line closure over the same one-field struct-",
4679 "literal. `const fn` preserves the `Copy`-pass-through's ",
4680 "zero-runtime-work property verbatim."
4681 )]
4682 #[must_use]
4683 pub const fn $ctor($field: $ty) -> Self {
4684 Self::$variant { $field }
4685 }
4686 )*
4687 }
4688 };
4689}
4690
4691supervisor_scalar_ctors! {
4692 no_children => NoChildren { estrategia: RestartStrategy },
4693 max_restarts_exceeds_cap => MaxRestartsExceedsCap { max_restarts: u32 },
4694 restart_window_not_canonical => RestartWindowNotCanonical { window: Duration },
4695 restart_window_exceeds_cap => RestartWindowExceedsCap { window: Duration },
4696}
4697
4698/// Shared duration string codec for the typed slots that take a
4699/// duration (`restart_window`, `MeshPolicy::timeout`,
4700/// `CircuitBreaker::window`, …). Public so [`crate::aplicacao`] can
4701/// reuse it without duplicating the parser.
4702pub mod duration_codec {
4703 use super::Duration;
4704 use serde::{Deserializer, Serializer};
4705
4706 pub fn serialize<S: Serializer>(v: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
4707 // Route through the canonical [`crate::render::serialize_option_via_str`]
4708 // — the substrate-side single-owner primitive for the forward
4709 // arm of the typed-magnitude codec family. See its docstring
4710 // for the full sibling roster.
4711 crate::render::serialize_option_via_str(v, s, render)
4712 }
4713
4714 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
4715 // Route through the canonical [`crate::render::deserialize_option_via_str`]
4716 // — the substrate-side single-owner primitive for the reverse
4717 // arm of the typed-magnitude codec family. See its docstring
4718 // for the full sibling roster.
4719 crate::render::deserialize_option_via_str(d, parse)
4720 }
4721
4722 pub(crate) fn parse(s: &str) -> Result<Duration, String> {
4723 // Paired whitespace-rejection arm — same canonical-form
4724 // render-determinism discipline as the peer
4725 // `limits::parse_byte_size` / `limits::parse_duration` /
4726 // `limits::parse_millicores` /
4727 // `aplicacao::rate_limit_codec::parse` sites: the ASCII
4728 // byte-scan closes the WhatWG-conformant whitespace bytes
4729 // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
4730 // `char::is_whitespace` scan closes the strictly-complementary
4731 // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
4732 // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
4733 // codepoints) that `str::trim` at parse entry silently strips.
4734 // Either drift class would round-trip through `render` to a
4735 // *different* canonical form on next emit — breaking the
4736 // THEORY.md Part V render-determinism contract on three typed-
4737 // duration slots at once (`:supervisor :restart-window`,
4738 // `:politicas :timeout`, `:politicas :circuit-breaker :window`)
4739 // via the shared codec.
4740 //
4741 // Routed through the lifted [`crate::render::reject_whitespace`]
4742 // primitive — the substrate-side single-owner paired-arm gate
4743 // every typed-magnitude codec in caixa-core shares.
4744 crate::render::reject_whitespace::<String, _, _>(
4745 s,
4746 |b| {
4747 format!(
4748 "duration: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
4749 authoring form for the typed duration slots routed through this shared codec \
4750 (`:supervisor :restart-window`, `:politicas :timeout`, \
4751 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
4752 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no whitespace bytes \
4753 anywhere. A whitespace-carrying shape (`\" 30s\"`, `\"30s \"`, `\"30 s\"`, \
4754 `\"\\t30s\"`, `\"30s\\n\"`) round-trips through `render` to a *different* \
4755 canonical form (`\"30s\"`) on first serialize — breaking the THEORY.md \
4756 Part V render-determinism contract every typed slot carries. Strip every \
4757 whitespace byte (write `\"30s\"` verbatim)"
4758 )
4759 },
4760 |ch| {
4761 format!(
4762 "duration: value {s:?} contains non-ASCII Unicode whitespace character \
4763 {ch:?} (U+{cp:04X}) — the canonical authoring form for the typed \
4764 duration slots routed through this shared codec (`:supervisor \
4765 :restart-window`, `:politicas :timeout`, `:politicas :circuit-breaker \
4766 :window`) is `<integer><unit>` (e.g. `\"30s\"`, `\"500ms\"`, `\"2m\"`, \
4767 `\"1h\"`) with no whitespace characters anywhere (ASCII or Unicode). A \
4768 non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}30s\"`, \
4769 `\"30s\\u{{2028}}\"`, `\"30\\u{{2003}}s\"`) survives the ASCII byte-scan \
4770 but `str::trim` (which uses `char::is_whitespace` — the Unicode \
4771 `White_Space` property, strictly wider than the ASCII byte set) silently \
4772 strips it at parse entry, and the value round-trips through `render` to \
4773 a *different* canonical form (`\"30s\"`) on first serialize — breaking \
4774 the THEORY.md Part V render-determinism contract every typed slot \
4775 carries. Strip every non-ASCII whitespace character (write `\"30s\"` \
4776 verbatim with only ASCII bytes)",
4777 cp = ch as u32
4778 )
4779 },
4780 )?;
4781 let s = s.trim();
4782 // Routed through the lifted
4783 // [`crate::render::split_magnitude_and_alpha_unit`] primitive —
4784 // the single-owner split every ASCII-alphabetic-unit typed-
4785 // magnitude codec in caixa-core (`limits::parse_byte_size` /
4786 // `limits::parse_duration` / this shared duration codec) shares.
4787 // See its docstring for the full sibling roster on the same
4788 // primitive altitude.
4789 let (num_part, unit) = crate::render::split_magnitude_and_alpha_unit(s);
4790 let num_trim = num_part.trim();
4791 // The canonical authoring form for every typed slot routed
4792 // through this shared codec — `:supervisor :restart-window`,
4793 // `:politicas :timeout`, `:politicas :circuit-breaker :window`
4794 // — is `<integer><unit>`. Every magnitude [`render`] emits is a
4795 // non-negative integer with no decimal point and no leading
4796 // sign, so the parser's accepted set must match for
4797 // serialize/deserialize to round-trip without canonical-form
4798 // drift. Until this gate landed the parser accepted any
4799 // `f64`-shaped magnitude (`"1.5s"` → 1500ms, `"1.0s"` → 1s,
4800 // `"0.5m"` → 30s, `"+30s"` → 30s) and serde silently round-
4801 // tripped the value to a *different* canonical string on the
4802 // next emit (`"1.5s"` → 1500ms → `"1500ms"`, `"1.0s"` → 1s →
4803 // `"1s"`, `"0.5m"` → 30s → `"30s"`, `"+30s"` → 30s → `"30s"`)
4804 // — breaking the THEORY.md Part V render-determinism contract
4805 // on three typed slots at once. Same canonical-form discipline
4806 // `crate::limits::parse_duration` (818dd38, the immediate
4807 // predecessor on the peer `:limits :wall-clock` codec) applies;
4808 // this gate lifts the discipline onto the shared codec that
4809 // backs the remaining three typed-duration slots in caixa-core.
4810 //
4811 // Strict canonical form: every byte of the magnitude is an
4812 // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
4813 // inputs the gate distinguishes "non-canonical-but-numeric"
4814 // (parses as f64 or i64 — surfaced with a self-locating
4815 // diagnostic naming the canonical authoring form, the
4816 // round-trip drift each rejected shape would produce on first
4817 // serialize, and the canonical-form remediation) from
4818 // "garbage" (parses as neither — surfaced with the existing
4819 // narrower "bad duration magnitude" wording so its diagnostic
4820 // shape remains stable for the parser-shape footgun case).
4821 // The pre-existing `num < 0.0` arm is now unreachable — the
4822 // digit-only gate strictly precedes magnitude parsing, and a
4823 // leading `-` is not an ASCII digit, so `"-30s"` lands on the
4824 // non-canonical-but-numeric branch with the `-30` named
4825 // verbatim in the diagnostic rather than the prior
4826 // value-laundered "negative duration in \"-30s\"" wording.
4827 //
4828 // Routed through the lifted
4829 // [`crate::render::is_digit_only_magnitude`] predicate — the
4830 // same source of truth the four peer typed-magnitude codec
4831 // sites share.
4832 let digit_only = crate::render::is_digit_only_magnitude(num_trim);
4833 if !digit_only {
4834 let numeric = num_trim.parse::<f64>().is_ok() || num_trim.parse::<i64>().is_ok();
4835 if numeric {
4836 return Err(format!(
4837 "duration: magnitude {num_trim:?} is not a non-negative integer — the \
4838 canonical authoring form for the typed duration slots routed through \
4839 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
4840 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
4841 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no decimal point and \
4842 no leading `+` / `-` sign. A fractional / decimal-shaped magnitude \
4843 (`\"1.5s\"`, `\"1.0s\"`, `\"0.5m\"`, `\"+30s\"`, `\"-30s\"`) round-trips \
4844 through `render` to a *different* canonical form (`\"1500ms\"`, `\"1s\"`, \
4845 `\"30s\"`, `\"30s\"`, `\"30s\"`) on first serialize — breaking the \
4846 THEORY.md Part V render-determinism contract every typed slot carries. \
4847 Pick an integer magnitude in the unit that divides cleanly (write \
4848 `\"1500ms\"` instead of `\"1.5s\"`; `\"30s\"` instead of `\"0.5m\"`)"
4849 ));
4850 }
4851 return Err(format!("bad duration magnitude in {s:?}"));
4852 }
4853 // Leading-zero arm — peer with the `rate_limit_codec` leading-
4854 // zero arm (4f46830) on the same canonical-form render-
4855 // determinism axis. The digit-only gate accepts `"030s"`,
4856 // `"00s"`, `"01h"`, `"0500ms"` as `u64::from_str` parses them
4857 // losslessly (= 30, 0, 1, 500), but `render` emits the leading-
4858 // zero-stripped form (`"30s"`, `"0s"`, `"1h"`, `"500ms"`) — a
4859 // *different* canonical string on the next emit, breaking the
4860 // THEORY.md Part V render-determinism contract the same way
4861 // `"+30s"` did before the leading-`+` arm landed. The single-
4862 // byte magnitude `"0"` (or `"0s"` / `"0ms"`) round-trips
4863 // losslessly through `render` (`render(Duration::ZERO)` emits
4864 // `"0s"`) — the downstream semantic-zero gates (e.g.
4865 // `SupervisorError::ZeroRestartWindow` on
4866 // `:supervisor :restart-window`,
4867 // `AplicacaoError::PolicyTimeoutZero` /
4868 // `PolicyCircuitBreakerWindowZero` on the typed `:politicas`
4869 // duration slots) refuse zero-magnitude authoring at the typed-
4870 // validate layer above, so the single-byte `"0"` stays in the
4871 // accepted set at this codec layer and the diagnostic
4872 // partitioning between canonical-form drift (this arm) and
4873 // semantic-zero (the downstream gates) remains stable.
4874 // Peer with the future leading-zero arms on the two remaining
4875 // typed-magnitude codecs the trajectory acknowledges:
4876 // `limits::parse_duration` backing `:limits :wall-clock`,
4877 // `limits::parse_byte_size` backing `:limits :memory` — each
4878 // carries the same canonical-form-drift class today; this
4879 // gate lands the discipline on the shared duration codec
4880 // first because the `rate_limit_codec` predecessor on the
4881 // same canonical-form-drift axis is the closest peer on the
4882 // trajectory.
4883 //
4884 // Routed through the lifted
4885 // [`crate::render::is_leading_zero_padded_magnitude`]
4886 // predicate — the same source of truth the four peer
4887 // typed-magnitude codec sites share.
4888 if crate::render::is_leading_zero_padded_magnitude(num_trim) {
4889 return Err(format!(
4890 "duration: magnitude {num_trim:?} has a non-canonical leading zero — the \
4891 canonical authoring form for the typed duration slots routed through \
4892 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
4893 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
4894 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no leading-zero padding \
4895 on the magnitude. A leading-zero magnitude (`\"030s\"`, `\"00s\"`, \
4896 `\"01h\"`, `\"0500ms\"`) round-trips through `render` to a *different* \
4897 canonical form (`\"30s\"`, `\"0s\"`, `\"1h\"`, `\"500ms\"`) on first \
4898 serialize — breaking the THEORY.md Part V render-determinism contract \
4899 every typed slot carries. Strip the leading zeros (write \
4900 `\"30s\"` instead of `\"030s\"`)"
4901 ));
4902 }
4903 // The digit-only gate guarantees every byte is `[0-9]`, and
4904 // the leading-zero arm above guarantees the magnitude is
4905 // either the single byte `"0"` or starts with `[1-9]`, so
4906 // the only way `u64::from_str` can fail here is overflow (the
4907 // magnitude exceeds `u64::MAX`). Surface that with an
4908 // overflow-shaped wording so the diagnostic names the offending
4909 // magnitude verbatim rather than collapsing onto the
4910 // non-canonical arm. The codec now operates on `u64` end-to-end
4911 // — every accepted magnitude is integer-exact; no f64 mantissa
4912 // drift between author-supplied magnitude and the consumer's
4913 // `Duration` value. Same shape `crate::limits::parse_duration`
4914 // (818dd38) carries on the peer `:limits :wall-clock` axis.
4915 let num: u64 = num_trim.parse::<u64>().map_err(|_| {
4916 format!("bad duration magnitude in {s:?} (digit-only magnitude overflows u64)")
4917 })?;
4918 // Route the `{"ms" | "s" | "" | "m" | "h"} → Duration`
4919 // unit-arm dispatch through the canonical
4920 // [`crate::render::duration_from_integer_magnitude_and_unit`]
4921 // primitive — the substrate-side single-owner unit-dispatch
4922 // table every typed-duration codec in caixa-core routes
4923 // through (peer: `crate::limits::parse_duration` backing
4924 // `:limits :wall-clock`). Every unit conversion is integer-
4925 // exact for an integer magnitude; overflow surfaces via the
4926 // typed `DurationUnitError::Overflow { multiplier }`
4927 // discriminant so this arm reconstructs the pre-lift
4928 // `"duration <num><unit> overflows u64 (magnitude × 60 …)"`
4929 // wording verbatim from `num` / `unit_trim` / the returned
4930 // `multiplier`, and the unknown-unit arm reconstructs the
4931 // pre-lift `"unknown duration unit \"<other>\""` wording from
4932 // the caller-scoped `unit_trim`. Load-bearing pinned by
4933 // `crate::render::tests::duration_from_integer_magnitude_and_unit_matches_pre_lift_unit_dispatch_table`.
4934 let unit_trim = unit.trim();
4935 let dur = crate::render::duration_from_integer_magnitude_and_unit(num, unit_trim).map_err(
4936 |e| match e {
4937 crate::render::DurationUnitError::Overflow { multiplier } => format!(
4938 "duration {num}{unit_trim} overflows u64 (magnitude × {multiplier} > 2^64-1)"
4939 ),
4940 crate::render::DurationUnitError::UnknownUnit => {
4941 format!("unknown duration unit {unit_trim:?}")
4942 }
4943 },
4944 )?;
4945 Ok(dur)
4946 }
4947
4948 /// Render a [`Duration`] in the canonical pleme-io duration string
4949 /// form (`"30s"`, `"1m"`, `"1h"`, `"500ms"`). The same form every
4950 /// caixa typed-duration slot serializes to and the same form K8s
4951 /// Gateway API HTTPRoute `timeouts` / `backendRequest` and Cilium
4952 /// EnvoyConfig per-route timeouts both expect (an integer
4953 /// followed by `s`/`m`/`h`/`ms`, no fractional values, no leading
4954 /// `+`). Lifted to `pub` so caixa-side renderers
4955 /// (`caixa-mesh::gateway_routes`'s :politicas :timeout overlay,
4956 /// the future per-:politicas `CiliumClusterwideEnvoyConfig`
4957 /// emitter, the future caixa-otel collector pipeline emitter) can
4958 /// consume the same canonical formatter without re-inlining the
4959 /// magnitude/unit decision tree (and inheriting the same drift
4960 /// footguns: a subtly different `300ms` vs `0.3s` rendering breaks
4961 /// downstream apply-time parsing in non-obvious ways).
4962 pub fn render(d: Duration) -> String {
4963 let total_ms = d.as_millis();
4964 if total_ms == 0 {
4965 return "0s".into();
4966 }
4967 if total_ms.is_multiple_of(3600 * 1000) {
4968 return format!("{}h", total_ms / (3600 * 1000));
4969 }
4970 if total_ms.is_multiple_of(60 * 1000) {
4971 return format!("{}m", total_ms / (60 * 1000));
4972 }
4973 if total_ms.is_multiple_of(1000) {
4974 return format!("{}s", total_ms / 1000);
4975 }
4976 format!("{total_ms}ms")
4977 }
4978
4979 /// True iff `d` round-trips losslessly through [`render`] + [`parse`].
4980 ///
4981 /// [`render`] truncates a `Duration` to `as_millis()` before picking the
4982 /// largest divisor unit, so any sub-millisecond residue
4983 /// (`d.subsec_nanos() % 1_000_000 != 0`) silently breaks the THEORY.md
4984 /// §V.2.7 render-determinism contract:
4985 ///
4986 /// - `Duration::from_micros(1500)` (= `1_500_000` ns) → `as_millis() == 1`
4987 /// → renders `"1ms"` → parses back to `Duration::from_millis(1)` =
4988 /// `1_000_000` ns ≠ original `1_500_000` ns;
4989 /// - `Duration::from_nanos(1)` (= 1 ns) → `as_millis() == 0` →
4990 /// renders the literal `"0s"`, which the per-axis zero-floor gate
4991 /// on every typed-`Duration` slot then rejects on re-validate.
4992 ///
4993 /// Lifted to a `pub` predicate next to the [`render`] / [`parse`] pair so
4994 /// the codec's round-trippable accepted set lives in exactly one place —
4995 /// every typed-`Duration` slot that routes through this shared codec
4996 /// (`SupervisorSpec::restart_window` via [`super::duration_codec`],
4997 /// [`crate::MeshPolicy::timeout`] / [`crate::CircuitBreaker::window`] via
4998 /// `supervisor::duration_codec` + [`super::duration_codec_required`]) and
4999 /// every typed-`Duration` slot whose own codec shares the same
5000 /// `as_millis()`-truncation shape ([`crate::LimitsSpec::wall_clock`] via
5001 /// [`crate::limits`]'s in-module `parse_duration` / `render_duration`
5002 /// pair) calls this predicate from its `validate()` to bracket the
5003 /// accepted set against the codec's accepted set, structurally. Drift
5004 /// between the codec's granularity and any typed slot's accepted set is
5005 /// then a single-source-of-truth edit at this predicate rather than a
5006 /// silent round-trip break the next consumer discovers at apply time.
5007 ///
5008 /// Peer of [`crate::aplicacao::POLICY_RETRIES_MAX`] /
5009 /// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] and the
5010 /// `is_dns_1123_label` / `is_canonical_rate_limit_window` predicate
5011 /// family — same "typed-slot's valid set matches its codec's accepted
5012 /// set, structurally" discipline carried at the codec layer.
5013 #[must_use]
5014 pub fn is_integer_millisecond_duration(d: Duration) -> bool {
5015 d.subsec_nanos().is_multiple_of(1_000_000)
5016 }
5017}
5018
5019/// Required-Duration variant for fields that aren't Option<Duration>.
5020pub mod duration_codec_required {
5021 use super::Duration;
5022 use serde::{Deserialize, Deserializer, Serializer};
5023
5024 pub fn serialize<S: Serializer>(v: &Duration, s: S) -> Result<S::Ok, S::Error> {
5025 s.serialize_str(&super::duration_codec::render(*v))
5026 }
5027
5028 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
5029 let s = String::deserialize(d)?;
5030 super::duration_codec::parse(&s).map_err(serde::de::Error::custom)
5031 }
5032}
5033
5034#[cfg(test)]
5035mod tests {
5036 use super::*;
5037
5038 fn child(name: &str, ver: &str, restart: RestartPolicy) -> ChildSpec {
5039 ChildSpec {
5040 caixa: name.into(),
5041 versao: ver.into(),
5042 restart,
5043 }
5044 }
5045
5046 #[test]
5047 fn child_spec_string_scalar_accessor_pair_is_const_fn() {
5048 // Fail-before-pass-after pin on [`ChildSpec::nome`] +
5049 // [`ChildSpec::versao_requirement`]'s `const`-eval-surface
5050 // posture. Each accessor projects the per-`:children :caixa`
5051 // / per-`:children :versao` [`String`] storage through the
5052 // `pub const fn` [`String::as_str`] (const-stable since Rust
5053 // 1.87, well within the workspace MSRV) — any future
5054 // accidental downgrade to non-`const` fails the corresponding
5055 // `<name>_via_const_fn` wrapper at caixa-core build time with
5056 // E0015 (`cannot call non-const method`), strictly stronger
5057 // than a runtime `assert!`. Sibling of the peer
5058 // per-M2/M3/universal-axis `String → &str` scalar-accessor
5059 // family pins on the sibling `const`-eval-surface passes
5060 // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
5061 // top-level manifest, [`crate::CaixaVersion::as_str`] at the
5062 // typed-newtype wrapper, [`crate::aplicacao::Membro::nome`] /
5063 // [`crate::aplicacao::Membro::versao_requirement`] at the M3
5064 // membership axis, [`crate::aplicacao::Entrada::hostname`] /
5065 // [`crate::aplicacao::Entrada::destination`] at the M3
5066 // ingress axis,
5067 // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
5068 // M2 upgrade axis, [`crate::dep::Dep::nome`] /
5069 // [`crate::dep::Dep::versao_requirement`] at the dep-graph
5070 // axis, and the per-`:contratos`
5071 // [`crate::aplicacao::WitContract::source`] /
5072 // [`crate::aplicacao::WitContract::destination`] /
5073 // [`crate::aplicacao::WitContract::world_ref`] trio the
5074 // sibling pin at 279823b already anchors).
5075 const fn nome_via_const_fn(c: &ChildSpec) -> &str {
5076 c.nome()
5077 }
5078 const fn versao_via_const_fn(c: &ChildSpec) -> &str {
5079 c.versao_requirement()
5080 }
5081 for (caixa, versao) in [
5082 ("worker-a", "^0.1"),
5083 ("worker-b", "~0.2.3"),
5084 ("collector", "*"),
5085 ] {
5086 let c = child(caixa, versao, RestartPolicy::Permanent);
5087 assert_eq!(nome_via_const_fn(&c), c.nome());
5088 assert_eq!(versao_via_const_fn(&c), c.versao_requirement());
5089 assert_eq!(c.nome(), caixa);
5090 assert_eq!(c.versao_requirement(), versao);
5091 }
5092 }
5093
5094 #[test]
5095 fn supervisor_children_slice_return_accessor_is_const_fn() {
5096 // Fail-before-pass-after pin on [`SupervisorSpec::children`]'s
5097 // `const`-eval-surface posture. The accessor destructures the
5098 // per-`:children` `Vec<ChildSpec>` storage through the
5099 // `pub const fn` [`Vec::as_slice`] (const-stable since Rust
5100 // 1.66, well within the workspace MSRV) — any future
5101 // accidental downgrade to non-`const` fails
5102 // `children_via_const_fn` at caixa-core build time with E0015
5103 // (`cannot call non-const method`), strictly stronger than a
5104 // runtime `assert!`. Sibling of the peer per-M3-mesh-slot
5105 // `Vec → &[T]` slice-return accessor family pin
5106 // [`crate::aplicacao::tests::m3_reference_return_accessor_family_is_const_fn`]
5107 // on the M3 mesh-slot per-`:clusters` / per-`:paths` /
5108 // per-`:membros` / per-`:contratos` slice-return axes, and of
5109 // the peer M2 upgrade-appup axis pin
5110 // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
5111 // on the per-`:upgrade-from :instructions` slice-return axis.
5112 const fn children_via_const_fn(s: &SupervisorSpec) -> &[ChildSpec] {
5113 s.children()
5114 }
5115 // Sweep both the empty-children (leaf-supervisor with no
5116 // static children — the `SimpleOneForOne` dynamic-child
5117 // arm's canonical shape) and the populated-children
5118 // (`OneForOne` / `OneForAll` / `RestForOne` static-child
5119 // arm's canonical shape) axes so the accessor carries a
5120 // const-dispatch pin on both arms.
5121 let s_empty = SupervisorSpec {
5122 estrategia: RestartStrategy::SimpleOneForOne,
5123 max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
5124 restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
5125 children: vec![],
5126 };
5127 assert!(children_via_const_fn(&s_empty).is_empty());
5128 assert_eq!(children_via_const_fn(&s_empty), s_empty.children());
5129 let s_full = SupervisorSpec {
5130 estrategia: RestartStrategy::OneForOne,
5131 max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
5132 restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
5133 children: vec![
5134 child("worker-a", "^0.1", RestartPolicy::Permanent),
5135 child("worker-b", "~0.2.3", RestartPolicy::Transient),
5136 child("collector", "*", RestartPolicy::Temporary),
5137 ],
5138 };
5139 assert_eq!(children_via_const_fn(&s_full).len(), 3);
5140 assert_eq!(children_via_const_fn(&s_full), s_full.children());
5141 }
5142
5143 #[test]
5144 fn default_has_one_for_one_and_5_restarts_in_60s() {
5145 let s = SupervisorSpec::default();
5146 assert_eq!(s.estrategia, RestartStrategy::OneForOne);
5147 assert_eq!(s.max_restarts, 5);
5148 assert_eq!(s.restart_window, Some(Duration::from_secs(60)));
5149 assert!(s.children.is_empty());
5150 }
5151
5152 #[test]
5153 fn validate_one_for_one_requires_children() {
5154 // Explicit-empty via struct-update rather than `let mut s = default(); s.children = vec![];`
5155 // — the peer `validate_simple_one_for_one_forbids_static_children` below already uses
5156 // struct-update to name the axis under test at construction, and this shape matches
5157 // it. Also keeps the "empty children is the axis under test" intent visible at the
5158 // binding site rather than one line down, and side-steps `clippy::field_reassign_with_default`.
5159 let mut s = SupervisorSpec {
5160 children: vec![],
5161 ..SupervisorSpec::default()
5162 };
5163 assert!(matches!(
5164 s.validate().unwrap_err(),
5165 SupervisorError::NoChildren { .. }
5166 ));
5167 s.children = vec![child("worker", "^0.1", RestartPolicy::Permanent)];
5168 s.validate().unwrap();
5169 }
5170
5171 #[test]
5172 fn validate_simple_one_for_one_forbids_static_children() {
5173 let mut s = SupervisorSpec {
5174 estrategia: RestartStrategy::SimpleOneForOne,
5175 ..SupervisorSpec::default()
5176 };
5177 s.children
5178 .push(child("w", "^0.1", RestartPolicy::Permanent));
5179 assert_eq!(
5180 s.validate().unwrap_err(),
5181 SupervisorError::SimpleOneForOneWithStaticChildren
5182 );
5183 s.children.clear();
5184 s.validate().unwrap();
5185 }
5186
5187 #[test]
5188 fn validate_rejects_zero_max_restarts() {
5189 let s = SupervisorSpec {
5190 max_restarts: 0,
5191 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5192 ..SupervisorSpec::default()
5193 };
5194 assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
5195 }
5196
5197 // ── upper-cap: SUPERVISOR_MAX_RESTARTS_MAX brackets the typed slot ─────
5198 //
5199 // The cap arm lifts the `:politicas :circuit-breaker :max-failures` /
5200 // `POLICY_BREAKER_MAX_FAILURES_MAX` (2b51ace) discipline onto the peer
5201 // `:supervisor :max-restarts` axis — both fields are "trip the
5202 // next-higher protection layer after N events in a rolling window"
5203 // counters with identical degenerate-at-the-high-end shape, so the
5204 // typed-slot's accepted set lies in `1..=1000` on the supervisor side
5205 // exactly as it lies in `1..=1000` on the breaker side.
5206
5207 #[test]
5208 fn validate_rejects_max_restarts_above_cap() {
5209 // The fail-before-pass-after pin: `SUPERVISOR_MAX_RESTARTS_MAX +
5210 // 1` is structurally one past the cap and silently passed
5211 // validate on every pre-gate codebase because the typed slot's
5212 // only check was the zero-floor arm. The no-op-supervisor vector
5213 // only surfaced at the runtime substrate (Erlang/OTP
5214 // MaxIntensity/Period ratio, the future wasm-operator's
5215 // per-supervisor restart-intensity counter) far from the source
5216 // caixa.lisp with no field naming the offending supervisor.
5217 let s = SupervisorSpec {
5218 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5219 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5220 ..SupervisorSpec::default()
5221 };
5222 assert_eq!(
5223 s.validate().unwrap_err(),
5224 SupervisorError::MaxRestartsExceedsCap {
5225 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5226 }
5227 );
5228 }
5229
5230 #[test]
5231 fn validate_rejects_max_restarts_far_above_cap() {
5232 // The `u32::MAX` worst case — the four-billion-restart
5233 // threshold a typo (`:max-restarts 4294967295`) or a
5234 // struct-literal copy-paste lands in the slot. Pin the cap
5235 // arm's coverage explicitly across the full `u32` overflow so
5236 // a future relaxation that drops the upper bound surfaces
5237 // here. Same shape every other typed-cap arm on this surface
5238 // carries (POLICY_BREAKER_MAX_FAILURES_MAX,
5239 // POLICY_RETRIES_MAX, POLICY_RATE_LIMIT_MAX).
5240 let s = SupervisorSpec {
5241 max_restarts: u32::MAX,
5242 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5243 ..SupervisorSpec::default()
5244 };
5245 assert_eq!(
5246 s.validate().unwrap_err(),
5247 SupervisorError::MaxRestartsExceedsCap {
5248 max_restarts: u32::MAX,
5249 }
5250 );
5251 }
5252
5253 #[test]
5254 fn validate_accepts_max_restarts_at_cap() {
5255 // The boundary value — exactly SUPERVISOR_MAX_RESTARTS_MAX —
5256 // must validate. The cap is inclusive on the top edge,
5257 // matching the POLICY_BREAKER_MAX_FAILURES_MAX /
5258 // POLICY_RETRIES_MAX / LIMITS_MEMORY_WASM32_MAX_BYTES
5259 // discipline on the sibling capped axes. Pin the boundary
5260 // explicitly so a future off-by-one tightening
5261 // (`>= SUPERVISOR_MAX_RESTARTS_MAX` instead of `>`) surfaces
5262 // here as a test failure rather than a silent contract
5263 // narrowing.
5264 let s = SupervisorSpec {
5265 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX,
5266 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5267 ..SupervisorSpec::default()
5268 };
5269 s.validate()
5270 .expect("max_restarts == SUPERVISOR_MAX_RESTARTS_MAX must validate");
5271 }
5272
5273 #[test]
5274 fn validate_accepts_max_restarts_typical_values() {
5275 // The documented production-playbook band positive-control
5276 // sweep — every value Erlang/OTP / Elixir / Riak Core /
5277 // RabbitMQ recommend (1..=100) must pass, plus a sweep
5278 // through the hyperscale band (200, 500, 1000) the cap
5279 // accepts. Pin the inclusive validated set explicitly so a
5280 // future tightening of the ceiling surfaces here.
5281 for n in [1u32, 3, 5, 10, 20, 50, 100, 200, 500, 1000] {
5282 let s = SupervisorSpec {
5283 max_restarts: n,
5284 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5285 ..SupervisorSpec::default()
5286 };
5287 s.validate()
5288 .unwrap_or_else(|e| panic!("max_restarts={n} must validate; got {e:?}"));
5289 }
5290 }
5291
5292 #[test]
5293 fn zero_max_restarts_takes_precedence_over_cap() {
5294 // The cross-arm ordering pin: `0` is structurally outside
5295 // both `1..` (zero-floor) and `..=SUPERVISOR_MAX_RESTARTS_MAX`
5296 // (cap), but the zero-floor diagnostic is the more
5297 // self-locating one (it directly names the counter-axis
5298 // remediation), so the validate gate must fire on zero first.
5299 // Same shape every other zero-then-shape ordering on this
5300 // surface uses (PolicyRetriesZero then
5301 // PolicyRetriesExceedsCap; PolicyBreakerZeroFailures then
5302 // PolicyBreakerMaxFailuresExceedsCap).
5303 let s = SupervisorSpec {
5304 max_restarts: 0,
5305 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5306 ..SupervisorSpec::default()
5307 };
5308 assert_eq!(
5309 s.validate().unwrap_err(),
5310 SupervisorError::ZeroMaxRestarts,
5311 "max_restarts == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
5312 );
5313 }
5314
5315 #[test]
5316 fn max_restarts_cap_takes_precedence_over_restart_window_gates() {
5317 // The cross-arm ordering pin between the cap and the sibling
5318 // `:restart-window` gates (zero-window, canonical-window). A
5319 // supervisor carrying both an over-cap `max_restarts` AND a
5320 // structurally invalid window (zero, sub-ms) must surface the
5321 // cap diagnostic first — the cap arm is wired immediately
5322 // after the zero-restart arm and strictly before the window
5323 // arms, so the offending value the diagnostic names matches
5324 // the order the author would discover the gates by reading
5325 // top-to-bottom through `SupervisorSpec::validate`. Pin the
5326 // order so a future refactor that reorders the arms surfaces
5327 // here as a test failure rather than a silent diagnostic
5328 // regression. Peer of
5329 // `circuit_breaker_max_failures_cap_takes_precedence_over_window_gates`
5330 // on the sibling `:politicas :circuit-breaker` slot.
5331 let s = SupervisorSpec {
5332 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5333 restart_window: Some(Duration::ZERO),
5334 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5335 ..SupervisorSpec::default()
5336 };
5337 assert_eq!(
5338 s.validate().unwrap_err(),
5339 SupervisorError::MaxRestartsExceedsCap {
5340 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5341 },
5342 "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
5343 );
5344 }
5345
5346 #[test]
5347 fn max_restarts_cap_diagnostic_carries_offending_value() {
5348 // The diagnostic-shape pin: the offending `u32` is carried
5349 // verbatim into the `SupervisorError::MaxRestartsExceedsCap`
5350 // variant so the surfaced error message names the value the
5351 // author wrote (`":supervisor :max-restarts (50000) exceeds the
5352 // supervisor-policy ceiling …"`), not just the cap. Same
5353 // self-locating diagnostic shape every other typed-cap arm on
5354 // this surface carries
5355 // (`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` carries
5356 // the offending failure count verbatim,
5357 // `AplicacaoError::PolicyRetriesExceedsCap` carries the offending
5358 // retries count verbatim).
5359 let s = SupervisorSpec {
5360 max_restarts: 50_000,
5361 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5362 ..SupervisorSpec::default()
5363 };
5364 let err = s.validate().unwrap_err();
5365 assert!(
5366 matches!(
5367 err,
5368 SupervisorError::MaxRestartsExceedsCap {
5369 max_restarts: 50_000
5370 }
5371 ),
5372 "got {err:?}"
5373 );
5374 let msg = err.to_string();
5375 assert!(
5376 msg.contains("50000"),
5377 ":supervisor :max-restarts cap diagnostic must carry the offending value verbatim (got: {msg})"
5378 );
5379 }
5380
5381 #[test]
5382 fn supervisor_max_restarts_default_pins_otp_canonical_value() {
5383 // Pin [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] at `5` — the
5384 // Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
5385 // half of Learn You Some Erlang's worker-supervisor default,
5386 // sibling of the `60s` `Period` half that the paired
5387 // [`Default for SupervisorSpec`] impl already pins on the
5388 // sibling `restart_window` axis. Pinning the literal here
5389 // surfaces a future rebrand (a tightening to Elixir's `3`,
5390 // a widening to a per-cluster overlay the operator pins
5391 // through a future `:max-restarts-overrides` slot) as a
5392 // deliberate test edit, not a silent contract migration.
5393 // Peer of the sibling
5394 // [`supervisor_max_restarts_cap_pins_canonical_value`]
5395 // upper-bracket pin on the same axis.
5396 assert_eq!(SUPERVISOR_MAX_RESTARTS_DEFAULT, 5);
5397 }
5398
5399 #[test]
5400 fn default_max_restarts_helper_routes_through_lifted_default() {
5401 // Composition pin: the private `default_max_restarts()`
5402 // serde-`#[serde(default = "…")]` helper on
5403 // [`SupervisorSpec::max_restarts`] must route through the
5404 // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
5405 // typed `pub const` rather than a raw `5` literal. Prior to
5406 // the lift the helper carried an inline `5` with no compile-
5407 // time link back to the shared default, so the wire-format
5408 // author-omitted arm and the caixa-core
5409 // [`crate::manifest::Caixa::supervisor_view`] fold's `unwrap_or(5)`
5410 // arm could silently split on any future default rebrand.
5411 // Byte-parity against the lifted constant closes the split.
5412 assert_eq!(default_max_restarts(), SUPERVISOR_MAX_RESTARTS_DEFAULT);
5413 }
5414
5415 #[test]
5416 fn supervisor_spec_default_max_restarts_routes_through_lifted_default() {
5417 // Composition pin: the [`Default for SupervisorSpec`] impl's
5418 // struct-literal `max_restarts` field must route through the
5419 // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
5420 // typed `pub const` (via the private helper this test's
5421 // sibling `default_max_restarts_helper_routes_through_lifted_default`
5422 // already pins onto the constant). Structurally: every
5423 // `SupervisorSpec::default()` call must yield a
5424 // `max_restarts` field byte-equal to the lifted constant
5425 // (the two paired defaults — the serde-side wire-format arm
5426 // and the struct-literal default arm — cannot silently split
5427 // on any future default rebrand). Peer of the sibling
5428 // `default_has_one_for_one_and_5_restarts_in_60s` shape pin
5429 // — this pin closes the byte-parity arm on the two paired
5430 // altitude entry points onto the shared substrate constant.
5431 assert_eq!(
5432 SupervisorSpec::default().max_restarts(),
5433 SUPERVISOR_MAX_RESTARTS_DEFAULT,
5434 );
5435 }
5436
5437 #[test]
5438 fn supervisor_restart_window_default_pins_otp_canonical_value() {
5439 // Pin [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] at `60s` — the
5440 // Erlang/OTP-canonical `{intensity, 5, 60}` `Period` half of
5441 // Learn You Some Erlang's worker-supervisor default, paired
5442 // with the sibling `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5`
5443 // `MaxIntensity` half this constant is the sliding-window
5444 // denominator of on the same `MaxIntensity / Period`
5445 // restart-intensity ratio. Pinning the literal here surfaces a
5446 // future coherent rebrand of the paired default (Elixir's
5447 // `{max_restarts: 3, max_seconds: 5}`, a per-cluster overlay
5448 // the operator pins through a future
5449 // `:restart-window-overrides` slot) as a deliberate test edit,
5450 // not a silent contract migration. Peer of the sibling
5451 // [`supervisor_max_restarts_default_pins_otp_canonical_value`]
5452 // paired-half pin on the same OTP-canonical default and the
5453 // [`supervisor_restart_window_cap_pins_canonical_value`]
5454 // upper-bracket pin on the same axis.
5455 assert_eq!(SUPERVISOR_RESTART_WINDOW_DEFAULT, Duration::from_secs(60),);
5456 }
5457
5458 #[test]
5459 fn supervisor_spec_default_restart_window_routes_through_lifted_default() {
5460 // Composition pin: the [`Default for SupervisorSpec`] impl's
5461 // struct-literal `restart_window` field must route through the
5462 // substrate-canonical [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
5463 // typed `pub const` rather than a raw
5464 // `Duration::from_secs(60)` literal. Prior to this lift the
5465 // paired `{intensity, 5, 60}` OTP-canonical default was split
5466 // across two altitudes with no compile-time link between the
5467 // halves — the `MaxIntensity` half rode through the lifted
5468 // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant while the
5469 // `Period` half rode as an open-coded literal at the
5470 // composition site, so a future coherent rebrand of the paired
5471 // canonical would have had to migrate one half through the
5472 // constant and the other through a raw literal in lockstep.
5473 // Byte-parity against the lifted constant on the `Period` half
5474 // closes the split — the paired OTP-canonical default now
5475 // migrates as one unit on any future axis change. Peer of the
5476 // sibling
5477 // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
5478 // byte-parity pin on the paired `MaxIntensity` half.
5479 assert_eq!(
5480 SupervisorSpec::default().restart_window(),
5481 Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
5482 );
5483 }
5484
5485 #[test]
5486 fn supervisor_estrategia_default_pins_otp_canonical_value() {
5487 // Pin [`SUPERVISOR_ESTRATEGIA_DEFAULT`] at [`RestartStrategy::OneForOne`]
5488 // — the Erlang/OTP-canonical `one_for_one` half of Learn You Some
5489 // Erlang's `{one_for_one, intensity, 5, 60}` worker-supervisor
5490 // canonical default, paired with the sibling
5491 // `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5` `MaxIntensity` half and the
5492 // sibling `SUPERVISOR_RESTART_WINDOW_DEFAULT` `60s` `Period` half
5493 // this constant is the strategy discriminator of on the same
5494 // OTP-canonical worker-supervisor default. Pinning the arm here
5495 // surfaces a future coherent rebrand of the paired triple (Elixir's
5496 // `{:one_for_one, max_restarts: 3, max_seconds: 5}` on the sibling
5497 // intensity/period axes leaving this strategy arm untouched, an OTP
5498 // `rest_for_one` widening once the substrate discovers startup-
5499 // order-coupled child cohorts as the more common worker-supervisor
5500 // shape, a per-cluster overlay the operator pins through a future
5501 // `:estrategia-overrides` slot the MESH-COMPOSITION §III.2
5502 // supervision-canary roadmap acknowledges) as a deliberate test
5503 // edit, not a silent contract migration. Peer of the sibling
5504 // [`supervisor_max_restarts_default_pins_otp_canonical_value`] +
5505 // [`supervisor_restart_window_default_pins_otp_canonical_value`]
5506 // paired-half pins on the same OTP-canonical default.
5507 assert_eq!(SUPERVISOR_ESTRATEGIA_DEFAULT, RestartStrategy::OneForOne);
5508 }
5509
5510 #[test]
5511 fn restart_strategy_default_routes_through_lifted_default() {
5512 // Composition pin: the [`Default for RestartStrategy`] impl's
5513 // return arm must route through the substrate-canonical
5514 // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
5515 // a raw `Self::OneForOne` arm. Prior to the lift the impl carried
5516 // an inline `Self::OneForOne` with no compile-time link back to
5517 // the shared OTP-canonical `one_for_one` strategy the paired
5518 // [`Default for SupervisorSpec`] impl's struct-literal `estrategia`
5519 // field and the [`crate::manifest::Caixa::supervisor_view`] fold's
5520 // `.unwrap_or_default()` (now
5521 // `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)`) arm both key off —
5522 // so a future rebrand of the OTP-canonical strategy default (an
5523 // OTP `rest_for_one` widening once the substrate discovers
5524 // startup-order-coupled child cohorts as the more common worker-
5525 // supervisor shape, a per-cluster overlay the operator pins
5526 // through a future `:estrategia-overrides` slot) would have had to
5527 // be threaded through the `Default` impl and the two peer routes
5528 // in lockstep or the three consumers would silently split. Byte-
5529 // parity against the lifted constant closes the split. Peer of
5530 // the sibling
5531 // [`default_max_restarts_helper_routes_through_lifted_default`] +
5532 // [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
5533 // composition pins on the paired `MaxIntensity` + `Period` halves.
5534 assert_eq!(RestartStrategy::default(), SUPERVISOR_ESTRATEGIA_DEFAULT,);
5535 }
5536
5537 #[test]
5538 fn supervisor_spec_default_estrategia_routes_through_lifted_default() {
5539 // Composition pin: the [`Default for SupervisorSpec`] impl's
5540 // struct-literal `estrategia` field must route through the
5541 // substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed
5542 // `pub const` (either directly, or via the
5543 // [`RestartStrategy::default`] impl that the sibling
5544 // `restart_strategy_default_routes_through_lifted_default` pin
5545 // already routes onto the constant). Structurally: every
5546 // `SupervisorSpec::default()` call must yield an `estrategia`
5547 // field byte-equal to the lifted constant (the three paired
5548 // defaults — the [`Default for RestartStrategy`] impl arm, the
5549 // struct-literal default arm here, and the
5550 // [`crate::manifest::Caixa::supervisor_view`] fold arm — cannot
5551 // silently split on any future default rebrand). Peer of the
5552 // sibling
5553 // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
5554 // + [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
5555 // byte-parity pins on the paired `MaxIntensity` + `Period` halves
5556 // of the same `SupervisorSpec::default()` composed altitude.
5557 assert_eq!(
5558 SupervisorSpec::default().estrategia(),
5559 SUPERVISOR_ESTRATEGIA_DEFAULT,
5560 );
5561 }
5562
5563 #[test]
5564 fn supervisor_spec_default_routes_through_otp_canonical_ctor() {
5565 // Composition pin: the [`Default for SupervisorSpec`] impl must
5566 // route through the substrate-canonical
5567 // [`SupervisorSpec::otp_canonical`] `pub const fn` constructor
5568 // rather than a re-hand-authored struct-literal cascade. Sharpens
5569 // the sibling per-arm
5570 // `supervisor_spec_default_*_routes_through_lifted_default` pins
5571 // from a per-field lift into a whole-struct one-source-of-truth
5572 // pin — the derived-until-now [`Default::default`] and the
5573 // [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
5574 // construction, not by coincidence.
5575 //
5576 // A future extension of the OTP-canonical baseline (a fifth
5577 // `restart_intensity` field the Erlang/OTP `#supervisor` record
5578 // grows, a per-child-cohort split of the `restart_window` /
5579 // `max_restarts` pair, an M4 `mesh.pleme.io/v1alpha1/Supervisor`
5580 // CR materializer's admission-time overlay pass) reaches both
5581 // paths through exactly one edit on
5582 // [`SupervisorSpec::otp_canonical`] — the derived path could
5583 // silently disagree with the constructor's shape on any new
5584 // field whose [`Default::default`] resolves to a different arm
5585 // than the OTP-canonical baseline the constructor names, while
5586 // this delegated impl reaches the constructor directly and
5587 // picks up every future extension by construction.
5588 //
5589 // Fourth peer on the M2 / M3 typed-slot-spec
5590 // [`Default`]-through-const-ctor fold family — sibling of the
5591 // [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
5592 // (abd52c2), [`crate::aplicacao::MeshPolicy`]
5593 // [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`]
5594 // (91641a4), and [`crate::BehaviorSpec`]
5595 // [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c)
5596 // per-`Option`-only-typed-slot folds — extended here onto the
5597 // M2 supervisor-slot [`SupervisorSpec`] whose canonical baseline
5598 // is not "everything `None`" but the Erlang/OTP-canonical
5599 // `{one_for_one, 5, 60}` worker-supervisor triple.
5600 assert_eq!(SupervisorSpec::default(), SupervisorSpec::otp_canonical());
5601 }
5602
5603 #[test]
5604 fn supervisor_spec_otp_canonical_byte_equals_default() {
5605 // Value pin: [`SupervisorSpec::otp_canonical`] must byte-equal
5606 // the hand-authored `{one_for_one, 5, 60, []}` OTP-canonical
5607 // baseline the sibling `default_has_one_for_one_and_5_restarts_in_60s`
5608 // pin already asserts against the [`Default::default`] path.
5609 // Sharpens the pair-invariant into a per-constructor pin so a
5610 // future extension of [`SupervisorSpec`] with a fifth field
5611 // whose OTP-canonical shape is non-`Default::default`-equivalent
5612 // trips at caixa-core test time rather than at a downstream
5613 // consumer that composed [`SupervisorSpec::otp_canonical`] with
5614 // [`SupervisorSpec::validate`] as its "canonical baseline
5615 // seed".
5616 let canonical = SupervisorSpec::otp_canonical();
5617 assert_eq!(canonical.estrategia, RestartStrategy::OneForOne);
5618 assert_eq!(canonical.max_restarts, 5);
5619 assert_eq!(canonical.restart_window, Some(Duration::from_secs(60)));
5620 assert!(canonical.children.is_empty());
5621 }
5622
5623 #[test]
5624 fn supervisor_spec_otp_canonical_is_usable_in_const_context() {
5625 // Const-context pin: [`SupervisorSpec::otp_canonical`] must
5626 // remain callable from a `const`-bound position so downstream
5627 // `const`-context callers wanting a canonical OTP-baseline seed
5628 // can construct one at compile time without runtime dispatch on
5629 // the derived [`Default::default`]. Peer of the sibling
5630 // `pub const fn` [`crate::LimitsSpec::empty`] /
5631 // [`crate::aplicacao::MeshPolicy::empty`] /
5632 // [`crate::BehaviorSpec::empty`] constructors on the sibling
5633 // typed-slot-spec `pub const fn` axis. If a future edit breaks
5634 // the `const`-eligibility of [`SupervisorSpec::otp_canonical`]
5635 // (a non-`const` field-default helper, a non-`const`-stable
5636 // container type promotion), this evaluation fails at
5637 // build time on this file rather than at a downstream
5638 // `const`-context call site.
5639 const CANONICAL: SupervisorSpec = SupervisorSpec::otp_canonical();
5640 assert_eq!(CANONICAL.estrategia, SUPERVISOR_ESTRATEGIA_DEFAULT);
5641 assert_eq!(CANONICAL.max_restarts, SUPERVISOR_MAX_RESTARTS_DEFAULT);
5642 assert_eq!(
5643 CANONICAL.restart_window,
5644 Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
5645 );
5646 assert!(CANONICAL.children.is_empty());
5647 }
5648
5649 #[test]
5650 fn supervisor_child_restart_default_pins_otp_canonical_value() {
5651 // Pin [`SUPERVISOR_CHILD_RESTART_DEFAULT`] at
5652 // [`RestartPolicy::Permanent`] — Erlang/OTP's `permanent`
5653 // worker-child restart type (`{ChildId, StartFunc, permanent, …}`
5654 // in a `supervisor`'s `init/1` child-spec tuple), the per-child
5655 // half of the same OTP-shape supervisor-tree default set whose
5656 // per-`:supervisor` halves the sibling
5657 // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
5658 // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] /
5659 // [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] constants pin. Pinning the
5660 // arm here surfaces a future rebrand of the per-child default (an
5661 // OTP-`transient` widening once the substrate discovers clean-
5662 // completion-aware children as the more common child shape, a
5663 // per-cluster overlay the operator pins through a future
5664 // `:restart-overrides` slot the MESH-COMPOSITION §III.2
5665 // supervision-canary roadmap acknowledges) as a deliberate test
5666 // edit, not a silent contract migration. Peer of the sibling
5667 // [`supervisor_estrategia_default_pins_otp_canonical_value`] /
5668 // [`supervisor_max_restarts_default_pins_otp_canonical_value`] /
5669 // [`supervisor_restart_window_default_pins_otp_canonical_value`]
5670 // value pins on the per-`:supervisor` halves.
5671 assert_eq!(SUPERVISOR_CHILD_RESTART_DEFAULT, RestartPolicy::Permanent);
5672 }
5673
5674 #[test]
5675 fn restart_policy_default_routes_through_lifted_default() {
5676 // Composition pin: the [`Default for RestartPolicy`] impl's return
5677 // arm must route through the substrate-canonical
5678 // [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const` rather
5679 // than a raw `Self::Permanent` arm. Prior to the lift the impl
5680 // carried an inline `Self::Permanent` with no compile-time link
5681 // back to the OTP-shape supervisor-tree default set whose three
5682 // per-`:supervisor` halves already rode through lifted constants
5683 // — so a future coherent rebrand of the set would have had to
5684 // migrate three halves through typed constants and this fourth
5685 // through a raw enum arm in lockstep or the supervisor-level and
5686 // child-level defaults would silently drift apart. Byte-parity
5687 // against the lifted constant closes the split. Peer of the
5688 // sibling
5689 // [`restart_strategy_default_routes_through_lifted_default`]
5690 // composition pin on the per-`:supervisor` `:estrategia` axis.
5691 assert_eq!(RestartPolicy::default(), SUPERVISOR_CHILD_RESTART_DEFAULT);
5692 }
5693
5694 #[test]
5695 fn child_spec_serde_default_restart_routes_through_lifted_default() {
5696 // Composition pin: the serde-side `#[serde(default)]` on
5697 // [`ChildSpec::restart`] — the wire-format author-omitted
5698 // `:children :restart` arm — must resolve onto the substrate-
5699 // canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const`
5700 // (via the [`Default for RestartPolicy`] impl the sibling
5701 // `restart_policy_default_routes_through_lifted_default` pin
5702 // already routes onto the constant). Structurally: a `ChildSpec`
5703 // deserialized from a payload that omits the `restart` key must
5704 // yield a `restart` field byte-equal to the lifted constant, so
5705 // the wire-format author-omitted arm and the
5706 // [`RestartPolicy::default`] impl arm cannot silently split on any
5707 // future default rebrand. Peer of the sibling
5708 // [`supervisor_spec_default_estrategia_routes_through_lifted_default`]
5709 // / [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
5710 // / [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
5711 // byte-parity pins on the per-`:supervisor` halves of the same
5712 // author-omitted-slot resolution surface.
5713 let omitted: ChildSpec = serde_json::from_str(r#"{"caixa":"worker","versao":"^0.1"}"#)
5714 .expect("ChildSpec must deserialize with the restart key omitted");
5715 assert_eq!(
5716 omitted.restart(),
5717 SUPERVISOR_CHILD_RESTART_DEFAULT,
5718 "an author-omitted :children :restart slot must degrade onto \
5719 the SUPERVISOR_CHILD_RESTART_DEFAULT typed pub const (got \
5720 {:?}, expected {:?})",
5721 omitted.restart(),
5722 SUPERVISOR_CHILD_RESTART_DEFAULT,
5723 );
5724 }
5725
5726 #[test]
5727 fn supervisor_max_restarts_cap_pins_canonical_value() {
5728 // The SUPERVISOR_MAX_RESTARTS_MAX constant pins the value at
5729 // 1000 — the same ceiling the peer
5730 // POLICY_BREAKER_MAX_FAILURES_MAX cap carries on the
5731 // `:politicas :circuit-breaker :max-failures` axis (both are
5732 // "trip the next-higher protection layer after N events in a
5733 // rolling window" counters with identical
5734 // degenerate-at-the-high-end shape; uniform top edge so the
5735 // M4 CR materializers and the wasm-operator reconciler reach
5736 // for either field knowing the value is in `1..=1000`). Two
5737 // orders of magnitude above every documented Erlang/OTP /
5738 // Elixir / Riak Core / RabbitMQ production-playbook
5739 // recommendation band and below the clearly-pathological
5740 // "effectively no escalation" floor (10_000, 100_000,
5741 // u32::MAX). Pinning the literal value here surfaces a future
5742 // drift (a relaxation to 10_000, a tightening to 100) as a
5743 // deliberate test edit, not a silent contract narrowing.
5744 assert_eq!(SUPERVISOR_MAX_RESTARTS_MAX, 1000);
5745 }
5746
5747 #[test]
5748 fn validate_rejects_empty_child_name() {
5749 let s = SupervisorSpec {
5750 children: vec![child("", "^0.1", RestartPolicy::Permanent)],
5751 ..SupervisorSpec::default()
5752 };
5753 assert_eq!(s.validate().unwrap_err(), SupervisorError::EmptyChildName);
5754 }
5755
5756 #[test]
5757 fn validate_rejects_empty_child_version() {
5758 let s = SupervisorSpec {
5759 children: vec![child("w", "", RestartPolicy::Permanent)],
5760 ..SupervisorSpec::default()
5761 };
5762 assert!(matches!(
5763 s.validate().unwrap_err(),
5764 SupervisorError::EmptyChildVersion { .. }
5765 ));
5766 }
5767
5768 // ── value-shape: parse-as-VersionReq on :children :versao ─────────────
5769
5770 #[test]
5771 fn validate_rejects_invalid_child_versao_requirement() {
5772 // The fail-before-pass-after pin: a non-empty but malformed
5773 // semver requirement (`"^bad-version"`) silently passed
5774 // `validate()` on every pre-gate codebase because the prior
5775 // shape only refused the empty string. The parse failure
5776 // surfaced far downstream at lacre-resolve time with a
5777 // `semver::Error` that didn't name which `:children` entry
5778 // carried the typo. The new gate moves the check to caixa-build
5779 // time at the source caixa.lisp — the third `:versao` typed
5780 // axis (`:children`) joins `:deps` and `:membros` (9888b13) at
5781 // structural parity.
5782 let s = SupervisorSpec {
5783 children: vec![
5784 child("worker", "^0.1", RestartPolicy::Permanent),
5785 child("cache", "^bad-version", RestartPolicy::Transient),
5786 ],
5787 ..SupervisorSpec::default()
5788 };
5789 let err = s.validate().unwrap_err();
5790 assert!(
5791 matches!(
5792 err,
5793 SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
5794 if caixa == "cache" && versao == "^bad-version"
5795 ),
5796 "got {err:?}"
5797 );
5798 }
5799
5800 #[test]
5801 fn validate_rejects_child_versao_with_double_caret_typo() {
5802 // `"^^0.1"` is the canonical doubled-caret typo — looks
5803 // Cargo-shaped on first glance but fails the parser because
5804 // semver doesn't accept stacked operators. Pin this
5805 // adjacent-shape footgun explicitly so a future relaxation that
5806 // accepts "looks-canonical-but-isn't" forms surfaces here.
5807 let s = SupervisorSpec {
5808 children: vec![child("worker", "^^0.1", RestartPolicy::Permanent)],
5809 ..SupervisorSpec::default()
5810 };
5811 let err = s.validate().unwrap_err();
5812 assert!(
5813 matches!(
5814 err,
5815 SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
5816 if caixa == "worker" && versao == "^^0.1"
5817 ),
5818 "got {err:?}"
5819 );
5820 }
5821
5822 #[test]
5823 fn validate_rejects_child_versao_with_v_prefixed_tag() {
5824 // `"v0.1"` is the canonical "git-tag-shape leaking into the
5825 // semver requirement slot" typo — an author copies the
5826 // publish-side git-tag string verbatim into `:versao`, but
5827 // Cargo's semver parser rejects the leading `v`. Same
5828 // adjacent-shape footgun pinned for `:membros :versao`
5829 // (9888b13).
5830 let s = SupervisorSpec {
5831 children: vec![child("worker", "v0.1", RestartPolicy::Permanent)],
5832 ..SupervisorSpec::default()
5833 };
5834 let err = s.validate().unwrap_err();
5835 assert!(
5836 matches!(
5837 err,
5838 SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
5839 if caixa == "worker" && versao == "v0.1"
5840 ),
5841 "got {err:?}"
5842 );
5843 }
5844
5845 #[test]
5846 fn validate_accepts_canonical_child_versao_forms() {
5847 // The Cargo-shaped requirement forms `:deps :versao` and
5848 // `:membros :versao` already accept via
5849 // `crate::parse_requirement` must pass the children gate
5850 // without re-validating at the resolver layer. Pin every leg so
5851 // a future tightening of the canonical set surfaces here as a
5852 // test failure.
5853 for form in [
5854 "^0.1", // caret — minor-range pin (the most common shape)
5855 "~0.1.2", // tilde — patch-range pin
5856 "0.1.0", // exact — single-version pin
5857 "*", // wildcard — any version (semver::VersionReq::STAR)
5858 ">=0.1, <2", // multi-range — comma-separated comparators
5859 ] {
5860 let s = SupervisorSpec {
5861 children: vec![child("worker", form, RestartPolicy::Permanent)],
5862 ..SupervisorSpec::default()
5863 };
5864 s.validate()
5865 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
5866 }
5867 }
5868
5869 #[test]
5870 fn child_versao_empty_takes_precedence_over_invalid() {
5871 // Order pin: the existing `EmptyChildVersion` diagnostic (which
5872 // doesn't try to parse) fires before the new
5873 // `ChildVersaoInvalid` parse-side diagnostic, so an empty
5874 // `:versao` keeps its narrower error message —
5875 // `parse_requirement` would also reject `""`, but the
5876 // empty-string arm is the more self-locating diagnostic for the
5877 // author. Same ordering discipline as
5878 // `membro_versao_empty_takes_precedence_over_invalid` in
5879 // aplicacao.rs.
5880 let s = SupervisorSpec {
5881 children: vec![child("worker", "", RestartPolicy::Permanent)],
5882 ..SupervisorSpec::default()
5883 };
5884 let err = s.validate().unwrap_err();
5885 assert!(
5886 matches!(err, SupervisorError::EmptyChildVersion { ref caixa } if caixa == "worker"),
5887 "got {err:?}"
5888 );
5889 }
5890
5891 #[test]
5892 fn child_versao_invalid_fires_before_duplicate_check() {
5893 // Order pin: a malformed requirement on a non-duplicate entry
5894 // surfaces *its own* diagnostic (which names the offending
5895 // `:versao` string), even when a later entry would otherwise
5896 // collapse onto an earlier name. The per-entry shape gate runs
5897 // inline before the duplicate-key insert — parallel to
5898 // `membro_versao_invalid_fires_before_duplicate_check` in
5899 // aplicacao.rs and the b0c8389 / c4213a4 ordering discipline.
5900 let s = SupervisorSpec {
5901 children: vec![
5902 child("worker", "^bad", RestartPolicy::Permanent),
5903 child("cache", "^0.1", RestartPolicy::Transient),
5904 child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
5905 ],
5906 ..SupervisorSpec::default()
5907 };
5908 let err = s.validate().unwrap_err();
5909 assert!(
5910 matches!(
5911 err,
5912 SupervisorError::ChildVersaoInvalid { ref caixa, .. } if caixa == "worker"
5913 ),
5914 "got {err:?}"
5915 );
5916 }
5917
5918 #[test]
5919 fn child_versao_invalid_diagnostic_carries_offending_versao() {
5920 // The diagnostic-shape pin: the error names the offending
5921 // `:versao` value verbatim so the author can grep their
5922 // caixa.lisp without re-running the build, and carries a
5923 // non-empty `reason` from `semver::VersionReq::parse` so the
5924 // parser's own wording flows through to the diagnostic.
5925 let s = SupervisorSpec {
5926 children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
5927 ..SupervisorSpec::default()
5928 };
5929 let err = s.validate().unwrap_err();
5930 let SupervisorError::ChildVersaoInvalid {
5931 caixa,
5932 versao,
5933 reason,
5934 } = err
5935 else {
5936 panic!("expected ChildVersaoInvalid, got other variant");
5937 };
5938 assert_eq!(caixa, "worker");
5939 assert_eq!(versao, "not-a-req");
5940 assert!(
5941 !reason.is_empty(),
5942 "ChildVersaoInvalid `reason` must carry the parser's wording verbatim"
5943 );
5944 }
5945
5946 // ── value-shape: DNS-1123 label rule on :children :caixa ──────────────
5947
5948 #[test]
5949 fn validate_rejects_child_caixa_with_uppercase() {
5950 // The canonical "I copied the Servico's display name verbatim"
5951 // typo — child caixa names are lowercase per K8s DNS-1123 label
5952 // rule. The diagnostic names the offending name and suggests the
5953 // lower-cased fix in one edit, mirroring the
5954 // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0).
5955 let s = SupervisorSpec {
5956 children: vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
5957 ..SupervisorSpec::default()
5958 };
5959 let err = s.validate().unwrap_err();
5960 let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
5961 panic!("expected ChildCaixaInvalid, got other variant");
5962 };
5963 assert_eq!(caixa, "Worker");
5964 assert!(
5965 reason.contains("uppercase"),
5966 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
5967 );
5968 assert!(
5969 reason.contains("\"worker\""),
5970 "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
5971 );
5972 }
5973
5974 #[test]
5975 fn validate_rejects_child_caixa_with_underscore() {
5976 // The canonical "I'm thinking of a Python module / Postgres
5977 // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
5978 // label schema. K8s rejects `metadata.name: my_worker` at
5979 // admission time with an opaque `field is invalid` (no source-
5980 // citing diagnostic). The gate moves it to caixa-build time.
5981 let s = SupervisorSpec {
5982 children: vec![child("my_worker", "^0.1", RestartPolicy::Permanent)],
5983 ..SupervisorSpec::default()
5984 };
5985 let err = s.validate().unwrap_err();
5986 assert!(
5987 matches!(
5988 err,
5989 SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
5990 if caixa == "my_worker" && reason.contains('_')
5991 ),
5992 "got {err:?}"
5993 );
5994 }
5995
5996 #[test]
5997 fn validate_rejects_child_caixa_with_dot() {
5998 // A `:children :caixa` entry is a single DNS-1123 label, not a
5999 // subdomain. The K8s Service / ComputeUnit `metadata.name` rules
6000 // forbid dots. Same shape as `rejects_membro_caixa_with_dot`
6001 // (3f9d7a0) on the peer name axis.
6002 let s = SupervisorSpec {
6003 children: vec![child("team.worker", "^0.1", RestartPolicy::Permanent)],
6004 ..SupervisorSpec::default()
6005 };
6006 let err = s.validate().unwrap_err();
6007 assert!(
6008 matches!(
6009 err,
6010 SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
6011 if caixa == "team.worker" && reason.contains('.')
6012 ),
6013 "got {err:?}"
6014 );
6015 }
6016
6017 #[test]
6018 fn validate_rejects_child_caixa_with_leading_hyphen() {
6019 // DNS-1123 / DNS-1035 boundary rule: labels must start and end
6020 // with an alphanumeric. The K8s apiserver rejects `-worker`
6021 // outright; the renderer would emit a `metadata.name: "-worker"`
6022 // that fails admission far from the source caixa.lisp.
6023 let s = SupervisorSpec {
6024 children: vec![child("-worker", "^0.1", RestartPolicy::Permanent)],
6025 ..SupervisorSpec::default()
6026 };
6027 let err = s.validate().unwrap_err();
6028 assert!(
6029 matches!(
6030 err,
6031 SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
6032 if caixa == "-worker" && reason.contains("start and end")
6033 ),
6034 "got {err:?}"
6035 );
6036 }
6037
6038 #[test]
6039 fn validate_rejects_child_caixa_with_trailing_hyphen() {
6040 // The symmetric arm of the boundary rule. Pin separately so
6041 // both ends of the label are covered against a future relaxation
6042 // that only checks one boundary.
6043 let s = SupervisorSpec {
6044 children: vec![child("worker-", "^0.1", RestartPolicy::Permanent)],
6045 ..SupervisorSpec::default()
6046 };
6047 let err = s.validate().unwrap_err();
6048 assert!(
6049 matches!(
6050 err,
6051 SupervisorError::ChildCaixaInvalid { ref caixa, .. }
6052 if caixa == "worker-"
6053 ),
6054 "got {err:?}"
6055 );
6056 }
6057
6058 #[test]
6059 fn validate_rejects_child_caixa_with_unicode() {
6060 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
6061 // (`xn--…`) by the author before it reaches K8s. The byte-by-
6062 // byte ASCII validity check rejects multi-byte UTF-8 sequences
6063 // by the first byte that fails the `[a-z0-9-]` predicate.
6064 let s = SupervisorSpec {
6065 children: vec![child("café", "^0.1", RestartPolicy::Permanent)],
6066 ..SupervisorSpec::default()
6067 };
6068 let err = s.validate().unwrap_err();
6069 assert!(
6070 matches!(
6071 err,
6072 SupervisorError::ChildCaixaInvalid { ref caixa, .. }
6073 if caixa == "café"
6074 ),
6075 "got {err:?}"
6076 );
6077 }
6078
6079 #[test]
6080 fn validate_rejects_child_caixa_with_whitespace() {
6081 // Whitespace is the canonical "I pasted from a sketch / doc"
6082 // footgun. The apiserver rejects every `metadata.name` value
6083 // carrying whitespace; pin the gate fires at the right boundary.
6084 let s = SupervisorSpec {
6085 children: vec![child("my worker", "^0.1", RestartPolicy::Permanent)],
6086 ..SupervisorSpec::default()
6087 };
6088 let err = s.validate().unwrap_err();
6089 assert!(
6090 matches!(
6091 err,
6092 SupervisorError::ChildCaixaInvalid { ref caixa, .. }
6093 if caixa == "my worker"
6094 ),
6095 "got {err:?}"
6096 );
6097 }
6098
6099 #[test]
6100 fn validate_rejects_child_caixa_too_long() {
6101 // The 64-byte boundary pin. DNS-1123 / DNS-1035 cap labels at
6102 // 63 bytes; the K8s apiserver rejects every `metadata.name`
6103 // axis over the limit at admission time. The diagnostic names
6104 // both the cap and the actual length so the author can shorten
6105 // in one edit, mirroring `rejects_membro_caixa_too_long`
6106 // (3f9d7a0) and `rejects_placement_cluster_too_long` (6cbb900).
6107 let too_long = "a".repeat(64);
6108 let s = SupervisorSpec {
6109 children: vec![child(&too_long, "^0.1", RestartPolicy::Permanent)],
6110 ..SupervisorSpec::default()
6111 };
6112 let err = s.validate().unwrap_err();
6113 let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
6114 panic!("expected ChildCaixaInvalid, got other variant");
6115 };
6116 assert_eq!(caixa, too_long);
6117 assert!(
6118 reason.contains("63"),
6119 "diagnostic must name the 63-byte cap (got: {reason:?})"
6120 );
6121 assert!(
6122 reason.contains("64"),
6123 "diagnostic must name the actual length (got: {reason:?})"
6124 );
6125 }
6126
6127 #[test]
6128 fn child_caixa_max_length_validates() {
6129 // The 63-byte boundary control pin — exactly-at-the-cap is
6130 // accepted, mirroring `membro_caixa_max_length_validates`
6131 // (3f9d7a0) and `placement_cluster_max_length_validates`
6132 // (6cbb900). Pinned separately so a future off-by-one tightening
6133 // surfaces here.
6134 let max_label = "a".repeat(63);
6135 let s = SupervisorSpec {
6136 children: vec![child(&max_label, "^0.1", RestartPolicy::Permanent)],
6137 ..SupervisorSpec::default()
6138 };
6139 s.validate().unwrap();
6140 }
6141
6142 #[test]
6143 fn validate_accepts_canonical_child_caixa_forms() {
6144 // The realistic shapes a supervised child's `:caixa` carries —
6145 // single-word `worker`, version-suffixed `cache-v2`, single-char
6146 // `a`, two-char `db`, digit-start `2-pool`, longer hyphen-joined
6147 // `payment-retry`, all-digit `0`. Pin every leg so a future
6148 // tightening (e.g. requiring a leading lowercase letter) surfaces
6149 // here as a test failure. Mirrors `accepts_canonical_membro_caixa_forms`
6150 // (3f9d7a0) and `accepts_canonical_placement_cluster_forms`
6151 // (6cbb900).
6152 for form in [
6153 "worker",
6154 "cache-v2",
6155 "a",
6156 "db",
6157 "2-pool",
6158 "payment-retry",
6159 "0",
6160 ] {
6161 let s = SupervisorSpec {
6162 children: vec![child(form, "^0.1", RestartPolicy::Permanent)],
6163 ..SupervisorSpec::default()
6164 };
6165 s.validate()
6166 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
6167 }
6168 }
6169
6170 #[test]
6171 fn child_caixa_empty_takes_precedence_over_invalid() {
6172 // Order pin: the existing `EmptyChildName` diagnostic (which
6173 // doesn't try to parse the DNS-1123 shape) fires before the new
6174 // `ChildCaixaInvalid` per-axis gate, so an empty `:caixa` keeps
6175 // its narrower error message — `is_dns_1123_label` would reject
6176 // the empty string too (boundary check on the first byte), but
6177 // the empty-string arm is the more self-locating diagnostic for
6178 // the author. Same ordering discipline as
6179 // `membro_caixa_empty_takes_precedence_over_invalid` in
6180 // aplicacao.rs.
6181 let s = SupervisorSpec {
6182 children: vec![child("", "^0.1", RestartPolicy::Permanent)],
6183 ..SupervisorSpec::default()
6184 };
6185 let err = s.validate().unwrap_err();
6186 assert_eq!(err, SupervisorError::EmptyChildName);
6187 }
6188
6189 #[test]
6190 fn child_caixa_invalid_fires_before_versao_check() {
6191 // Order pin: the per-axis shape gate runs inline before the
6192 // per-entry versao check, so a malformed `:caixa` on an entry
6193 // whose `:versao` would also fail surfaces the more self-
6194 // locating name-axis diagnostic first. Parallel to
6195 // `membro_versao_invalid_fires_before_duplicate_check` (9888b13)
6196 // and `placement_cluster_invalid_fires_before_duplicate_check`
6197 // (6cbb900).
6198 let s = SupervisorSpec {
6199 children: vec![child("My_Worker", "", RestartPolicy::Permanent)],
6200 ..SupervisorSpec::default()
6201 };
6202 let err = s.validate().unwrap_err();
6203 assert!(
6204 matches!(
6205 err,
6206 SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "My_Worker"
6207 ),
6208 "got {err:?}"
6209 );
6210 }
6211
6212 #[test]
6213 fn child_caixa_invalid_fires_before_duplicate_check() {
6214 // Order pin: a malformed name on a non-duplicate entry surfaces
6215 // its own diagnostic, even when a later entry would otherwise
6216 // collapse onto an earlier name. The per-entry shape gate runs
6217 // inline before the duplicate-key HashSet insert, mirroring
6218 // `placement_cluster_invalid_fires_before_duplicate_check`
6219 // (6cbb900).
6220 let s = SupervisorSpec {
6221 children: vec![
6222 child("Worker", "^0.1", RestartPolicy::Permanent),
6223 child("cache", "^0.1", RestartPolicy::Transient),
6224 child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
6225 ],
6226 ..SupervisorSpec::default()
6227 };
6228 let err = s.validate().unwrap_err();
6229 assert!(
6230 matches!(
6231 err,
6232 SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "Worker"
6233 ),
6234 "got {err:?}"
6235 );
6236 }
6237
6238 #[test]
6239 fn child_caixa_invalid_diagnostic_carries_offending_caixa() {
6240 // The diagnostic-shape pin: the error names the offending
6241 // `:caixa` verbatim plus a non-empty parser-shaped `reason` so
6242 // the author can grep their caixa.lisp without re-running the
6243 // build. Mirrors the diagnostic-shape sweep on every prior
6244 // value-shape gate (3f9d7a0, 6cbb900, c7d05ec).
6245 let s = SupervisorSpec {
6246 children: vec![child("My_Worker", "^0.1", RestartPolicy::Permanent)],
6247 ..SupervisorSpec::default()
6248 };
6249 let err = s.validate().unwrap_err();
6250 let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
6251 panic!("expected ChildCaixaInvalid, got other variant");
6252 };
6253 assert_eq!(caixa, "My_Worker");
6254 assert!(
6255 !reason.is_empty(),
6256 "ChildCaixaInvalid `reason` must carry the parser's wording verbatim"
6257 );
6258 }
6259
6260 // ── value-shape: zero restart_window + duplicate child names ──────────
6261
6262 #[test]
6263 fn validate_accepts_none_restart_window() {
6264 // Omitted `:restart-window` is the "never reset" sentinel —
6265 // valid by design. Mirrors :limits axes where None = unbounded.
6266 let s = SupervisorSpec {
6267 restart_window: None,
6268 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6269 ..SupervisorSpec::default()
6270 };
6271 s.validate().unwrap();
6272 }
6273
6274 #[test]
6275 fn validate_rejects_zero_restart_window() {
6276 // Same "0 means the opposite of what you think" footgun closed
6277 // for :politicas :timeout (Envoy treats 0s as infinite) and
6278 // :limits :wall-clock (wasmtime traps before the call starts).
6279 // Erlang/OTP's MaxIntensity/Period requires Period > 0.
6280 let s = SupervisorSpec {
6281 restart_window: Some(Duration::ZERO),
6282 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6283 ..SupervisorSpec::default()
6284 };
6285 assert_eq!(
6286 s.validate().unwrap_err(),
6287 SupervisorError::RestartWindowZero
6288 );
6289 }
6290
6291 // ── value-shape: integer-ms canonical-form on :restart-window ─────────
6292 //
6293 // The fourth (and last) typed-`Duration` axis in caixa-core to get
6294 // the integer-millisecond canonical-form gate — peer with
6295 // `:limits :wall-clock` (82fc3ef), `:politicas :timeout` (a4ae535),
6296 // and `:politicas :circuit-breaker :window` (a4ae535). The serde
6297 // path is already gated at the shared codec layer (see
6298 // `restart_window_serde_rejects_fractional_seconds`); this arm
6299 // closes the programmatic-struct-literal path the codec gate can't
6300 // see.
6301
6302 #[test]
6303 fn validate_rejects_sub_millisecond_restart_window() {
6304 // The fail-before-pass-after pin: a programmatic
6305 // `Duration::from_micros(1500)` (= 1_500_000 ns) silently passed
6306 // `validate` on every pre-gate codebase, then truncated to
6307 // `as_millis() == 1` on first serialize — the shared codec
6308 // emits `"1ms"`, parses it back to `Duration::from_millis(1)` =
6309 // 1_000_000 ns, the typed `restart_window` no longer matches
6310 // its rendered form.
6311 let s = SupervisorSpec {
6312 restart_window: Some(Duration::from_micros(1500)),
6313 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6314 ..SupervisorSpec::default()
6315 };
6316 match s.validate().unwrap_err() {
6317 SupervisorError::RestartWindowNotCanonical { window } => {
6318 assert_eq!(window, Duration::from_micros(1500));
6319 }
6320 other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
6321 }
6322 }
6323
6324 #[test]
6325 fn validate_rejects_one_nanosecond_restart_window() {
6326 // The far-sub-ms case: `Duration::from_nanos(1)` is non-zero
6327 // (so `RestartWindowZero` doesn't fire) but `as_millis() == 0`,
6328 // so the shared codec emits the literal `"0s"` — the next
6329 // serde round-trip would parse back to `Duration::ZERO`, which
6330 // the `RestartWindowZero` arm then rejects on re-validate. The
6331 // canonical-form gate at this layer surfaces a self-locating
6332 // diagnostic naming the offending Duration verbatim rather
6333 // than a downstream `RestartWindowZero` whose remediation
6334 // points at omitting the slot.
6335 let s = SupervisorSpec {
6336 restart_window: Some(Duration::from_nanos(1)),
6337 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6338 ..SupervisorSpec::default()
6339 };
6340 match s.validate().unwrap_err() {
6341 SupervisorError::RestartWindowNotCanonical { window } => {
6342 assert_eq!(window, Duration::from_nanos(1));
6343 }
6344 other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
6345 }
6346 }
6347
6348 #[test]
6349 fn validate_rejects_nanosecond_past_canonical_boundary_restart_window() {
6350 // The 1-ns-past-1ms boundary case: a `Duration` carrying
6351 // 1_000_001 ns is structurally past the integer-ms granularity
6352 // floor — `subsec_nanos() % 1_000_000 == 1`. The codec round-
6353 // trip would truncate to `1ms` and the consumer would observe
6354 // a 1-ns drift on every emit. Same boundary the peer
6355 // `validate_rejects_nanosecond_past_canonical_boundary` test
6356 // in limits.rs pins for the `:limits :wall-clock` axis.
6357 let w = Duration::from_nanos(1_000_001);
6358 let s = SupervisorSpec {
6359 restart_window: Some(w),
6360 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6361 ..SupervisorSpec::default()
6362 };
6363 assert_eq!(
6364 s.validate().unwrap_err(),
6365 SupervisorError::RestartWindowNotCanonical { window: w }
6366 );
6367 }
6368
6369 #[test]
6370 fn validate_accepts_integer_millisecond_restart_window_values() {
6371 // The positive-control sweep: every `Duration` the shared
6372 // codec can round-trip losslessly — the canonical
6373 // `<integer>{ms,s,m,h}` set the codec's `render` / `parse`
6374 // pair emits and accepts — passes `validate` without
6375 // surfacing the new canonical-form arm. Mirrors
6376 // `validate_accepts_integer_millisecond_wall_clock_values` on
6377 // the sibling `:limits :wall-clock` axis.
6378 for w in [
6379 Duration::from_millis(1),
6380 Duration::from_millis(500),
6381 Duration::from_millis(1500),
6382 Duration::from_secs(1),
6383 Duration::from_secs(30),
6384 Duration::from_secs(60),
6385 Duration::from_secs(120),
6386 Duration::from_secs(3600),
6387 ] {
6388 let s = SupervisorSpec {
6389 restart_window: Some(w),
6390 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6391 ..SupervisorSpec::default()
6392 };
6393 s.validate()
6394 .unwrap_or_else(|e| panic!("integer-ms {w:?} must validate, got {e:?}"));
6395 }
6396 }
6397
6398 #[test]
6399 fn validate_restart_window_zero_takes_precedence_over_canonical_gate() {
6400 // Cross-arm ordering pin: `Duration::ZERO` has
6401 // `subsec_nanos() == 0` and would otherwise pass the
6402 // canonical-form arm — the zero-floor arm must fire first so
6403 // the more self-locating `RestartWindowZero` diagnostic (with
6404 // its omit-axis remediation directly named) leads. Same
6405 // posture every peer zero-then-shape gate uses
6406 // (`WallClockZero` → `WallClockNotCanonical`,
6407 // `PolicyTimeoutZero` → `PolicyTimeoutNotCanonical`,
6408 // `PolicyBreakerZeroWindow` → `PolicyBreakerWindowNotCanonical`).
6409 let s = SupervisorSpec {
6410 restart_window: Some(Duration::ZERO),
6411 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6412 ..SupervisorSpec::default()
6413 };
6414 assert_eq!(
6415 s.validate().unwrap_err(),
6416 SupervisorError::RestartWindowZero
6417 );
6418 }
6419
6420 #[test]
6421 fn restart_window_canonical_diagnostic_carries_offending_duration() {
6422 // Diagnostic-shape pin: the canonical-form arm names the
6423 // offending `Duration` verbatim so the author's grep lands on
6424 // the field's value, not a generic "duration not canonical"
6425 // message. Same shape every other typed-canonical-form arm
6426 // on this surface carries (`WallClockNotCanonical` carries
6427 // the offending `Duration` verbatim,
6428 // `PolicyTimeoutNotCanonical` carries the offending
6429 // `Duration` verbatim).
6430 let w = Duration::from_micros(500);
6431 let s = SupervisorSpec {
6432 restart_window: Some(w),
6433 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6434 ..SupervisorSpec::default()
6435 };
6436 let err = s.validate().unwrap_err();
6437 let msg = err.to_string();
6438 assert!(
6439 msg.contains("500"),
6440 "diagnostic must carry the offending magnitude verbatim (got {msg:?})"
6441 );
6442 assert!(
6443 msg.contains("sub-millisecond"),
6444 "diagnostic must name the sub-millisecond residue class (got {msg:?})"
6445 );
6446 }
6447
6448 #[test]
6449 fn restart_window_validated_value_round_trips_through_codec() {
6450 // The structural property the canonical-ms gate enforces:
6451 // every `SupervisorSpec::restart_window` past
6452 // `SupervisorSpec::validate` round-trips losslessly through
6453 // the shared duration codec (serialize → string →
6454 // deserialize → equal value). Pin this end-to-end so a future
6455 // change to either side (the validate gate's accepted
6456 // granularity, the codec's parse/render unit set) that breaks
6457 // the alignment surfaces here. Peer of
6458 // `wall_clock_validated_value_round_trips_through_codec` on
6459 // the sibling `:limits :wall-clock` axis.
6460 for w in [
6461 Duration::from_millis(1),
6462 Duration::from_millis(1500),
6463 Duration::from_secs(30),
6464 Duration::from_secs(3600),
6465 ] {
6466 let s = SupervisorSpec {
6467 restart_window: Some(w),
6468 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6469 ..SupervisorSpec::default()
6470 };
6471 s.validate().unwrap();
6472 let json = serde_json::to_string(&s).unwrap();
6473 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6474 assert_eq!(back.restart_window, Some(w));
6475 }
6476 }
6477
6478 // ── value-shape: upper cap on :restart-window ─────────────────────────
6479 //
6480 // The fourth (and last) typed-`Duration` axis in caixa-core to get
6481 // the 1h upper cap — peer with `:limits :wall-clock` (51e0dbd),
6482 // `:politicas :timeout` (2e8ee7e), and `:politicas
6483 // :circuit-breaker :window` (379a814). Brackets the typed
6484 // `:restart-window` axis structurally: every validated value lies
6485 // in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`, integer-millisecond
6486 // granularity, closing the
6487 // rolling-window-degenerates-to-lifetime-counter footgun the prior
6488 // zero-floor-and-canonical-form-only checks left open.
6489
6490 #[test]
6491 fn validate_rejects_restart_window_above_cap() {
6492 // The fail-before-pass-after pin: 3601s = 1h + 1s is
6493 // structurally one canonical-tick past the
6494 // [`SUPERVISOR_RESTART_WINDOW_MAX`] ceiling (1h = 3600s) — an
6495 // integer-millisecond magnitude the canonical-form arm above
6496 // accepts cleanly, that the shared duration codec round-trips
6497 // losslessly as `"3601s"`, and that silently passed validate on
6498 // every pre-gate codebase because the typed slot's only checks
6499 // were the zero-floor and canonical-form arms. The runtime
6500 // substrate consuming the value (Erlang/OTP's MaxIntensity/
6501 // Period reconciler, the future wasm-operator's per-supervisor
6502 // restart-intensity counter) reaches for a `Duration` so long
6503 // no realistic restart-recovery pattern resets the counter,
6504 // far from the source caixa.lisp.
6505 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
6506 let s = SupervisorSpec {
6507 restart_window: Some(w),
6508 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6509 ..SupervisorSpec::default()
6510 };
6511 assert_eq!(
6512 s.validate().unwrap_err(),
6513 SupervisorError::RestartWindowExceedsCap { window: w }
6514 );
6515 }
6516
6517 #[test]
6518 fn validate_rejects_restart_window_one_millisecond_above_cap() {
6519 // Boundary case: exactly 1ms past the cap (the granularity the
6520 // canonical-form gate enforces). Catches a future "strictly
6521 // less than" half-measure and pins the diagnostic to name the
6522 // offending `Duration` verbatim. Peer of
6523 // `validate_rejects_wall_clock_one_millisecond_above_cap` /
6524 // `rejects_policy_timeout_one_millisecond_above_cap` /
6525 // `rejects_circuit_breaker_window_one_millisecond_above_cap`
6526 // on the sibling typed-`Duration` axes' top edges.
6527 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
6528 let s = SupervisorSpec {
6529 restart_window: Some(w),
6530 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6531 ..SupervisorSpec::default()
6532 };
6533 assert_eq!(
6534 s.validate().unwrap_err(),
6535 SupervisorError::RestartWindowExceedsCap { window: w }
6536 );
6537 }
6538
6539 #[test]
6540 fn validate_rejects_restart_window_far_above_cap() {
6541 // The "obvious authoring footgun" case: a `(:restart-window "24h")`,
6542 // `(:restart-window "7d")`, or any "I want a lifetime counter
6543 // but wrote a `<integer>h` magnitude anyway" typo — values the
6544 // canonical-form arm accepts as integer-millisecond magnitudes,
6545 // the codec round-trips losslessly through serde, but the
6546 // operator's `MaxIntensity / Period` reconciler cannot honor
6547 // as a meaningful rolling window. Until this gate landed
6548 // validate accepted them. Pin the common above-cap values (24h,
6549 // 7d, ~11.5d) so a future relaxation that drops the upper bound
6550 // surfaces here.
6551 for w in [
6552 Duration::from_secs(86_400), // 24h
6553 Duration::from_secs(604_800), // 7d
6554 Duration::from_secs(1_000_000), // ~11.5 days
6555 ] {
6556 let s = SupervisorSpec {
6557 restart_window: Some(w),
6558 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6559 ..SupervisorSpec::default()
6560 };
6561 assert_eq!(
6562 s.validate().unwrap_err(),
6563 SupervisorError::RestartWindowExceedsCap { window: w }
6564 );
6565 }
6566 }
6567
6568 #[test]
6569 fn validate_accepts_restart_window_at_cap() {
6570 // The boundary value — exactly [`SUPERVISOR_RESTART_WINDOW_MAX`]
6571 // (1h) — must validate. The cap is inclusive on the top edge,
6572 // matching the [`crate::LIMITS_WALL_CLOCK_MAX`] /
6573 // [`crate::POLICY_TIMEOUT_MAX`] /
6574 // [`crate::POLICY_BREAKER_WINDOW_MAX`] discipline on the sibling
6575 // capped axes. Pin the boundary explicitly so a future
6576 // off-by-one tightening (`>= SUPERVISOR_RESTART_WINDOW_MAX`
6577 // instead of `>`) surfaces here as a test failure rather than a
6578 // silent contract narrowing.
6579 let s = SupervisorSpec {
6580 restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
6581 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6582 ..SupervisorSpec::default()
6583 };
6584 s.validate()
6585 .expect("restart_window == SUPERVISOR_RESTART_WINDOW_MAX must validate");
6586 }
6587
6588 #[test]
6589 fn validate_accepts_restart_window_typical_values() {
6590 // The documented Erlang/OTP / Elixir / Riak Core / RabbitMQ
6591 // per-supervisor production-playbook band positive-control
6592 // sweep — every value Learn You Some Erlang's `{intensity, 5,
6593 // 60}` worker-supervisor `Period = 60s` default, Elixir's
6594 // `Supervisor` `max_seconds: 5` default, OTP's `supervisor`
6595 // callback module `MaxT = 5..=60` typical, Riak Core's `MaxT ∈
6596 // 10s..=300s`, and RabbitMQ broker-supervisor `MaxT = 5s`
6597 // default recommend (5s..=300s) must pass, plus a sweep
6598 // through the long-tail-flaky-pool band (5m, 15m, 30m, 1h) the
6599 // cap accepts. Mirrors `validate_accepts_wall_clock_typical_values`
6600 // on the sibling `:limits :wall-clock` axis.
6601 for w in [
6602 Duration::from_millis(1),
6603 Duration::from_millis(500),
6604 Duration::from_secs(1),
6605 Duration::from_secs(5), // RabbitMQ broker-supervisor default
6606 Duration::from_secs(10), // Riak Core lower
6607 Duration::from_secs(30),
6608 Duration::from_secs(60), // Learn You Some Erlang default
6609 Duration::from_secs(120), // OTP supervisor MaxT typical
6610 Duration::from_secs(300), // Riak Core upper
6611 Duration::from_secs(900), // 15m
6612 Duration::from_secs(1800),
6613 Duration::from_secs(3600), // exactly 1h, the cap
6614 ] {
6615 let s = SupervisorSpec {
6616 restart_window: Some(w),
6617 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6618 ..SupervisorSpec::default()
6619 };
6620 s.validate()
6621 .unwrap_or_else(|e| panic!("restart_window={w:?} must validate; got {e:?}"));
6622 }
6623 }
6624
6625 #[test]
6626 fn restart_window_zero_takes_precedence_over_cap() {
6627 // The cross-arm ordering pin: `Duration::ZERO` is structurally
6628 // outside both `>= 1ms` (zero-floor) and `<=
6629 // SUPERVISOR_RESTART_WINDOW_MAX` (cap), but the zero-floor
6630 // diagnostic is the more self-locating one (it directly names
6631 // the omit-axis remediation), so the validate gate must fire
6632 // on zero first. Same shape every other zero-then-cap ordering
6633 // on this surface uses (`WallClockZero` then
6634 // `WallClockExceedsCap`, `PolicyTimeoutZero` then
6635 // `PolicyTimeoutExceedsCap`, `PolicyBreakerZeroWindow` then
6636 // `PolicyBreakerWindowExceedsCap`).
6637 let s = SupervisorSpec {
6638 restart_window: Some(Duration::ZERO),
6639 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6640 ..SupervisorSpec::default()
6641 };
6642 assert_eq!(
6643 s.validate().unwrap_err(),
6644 SupervisorError::RestartWindowZero,
6645 "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
6646 );
6647 }
6648
6649 #[test]
6650 fn restart_window_canonical_takes_precedence_over_cap() {
6651 // The cross-arm ordering pin: a `Duration` that is *both*
6652 // sub-millisecond (non-canonical-form) and structurally above
6653 // the cap surfaces the canonical-form diagnostic first,
6654 // because the round-trip-shape break is the more fundamental
6655 // issue (the value can't even round-trip through the codec,
6656 // so the cap diagnostic naming `1ms..=1h` would be misleading
6657 // — there's no integer-ms form of the offending value). Pin
6658 // the order so a future refactor that reorders the arms
6659 // surfaces here as a test failure rather than a silent
6660 // diagnostic regression. Peer of
6661 // `wall_clock_canonical_takes_precedence_over_cap` /
6662 // `policy_timeout_canonical_takes_precedence_over_cap`.
6663 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_nanos(1);
6664 let s = SupervisorSpec {
6665 restart_window: Some(w),
6666 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6667 ..SupervisorSpec::default()
6668 };
6669 assert_eq!(
6670 s.validate().unwrap_err(),
6671 SupervisorError::RestartWindowNotCanonical { window: w },
6672 "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
6673 );
6674 }
6675
6676 #[test]
6677 fn max_restarts_cap_takes_precedence_over_restart_window_cap() {
6678 // The cross-arm ordering pin between the `:max-restarts` cap
6679 // and the sibling `:restart-window` cap. A supervisor carrying
6680 // both an over-cap `max_restarts` AND an over-cap window must
6681 // surface the `MaxRestartsExceedsCap` diagnostic first — the
6682 // cap arm is wired immediately after the zero-restart arm and
6683 // strictly before every window-axis arm (zero / canonical /
6684 // cap), so the offending value the diagnostic names matches
6685 // the order the author would discover the gates by reading
6686 // top-to-bottom through `SupervisorSpec::validate`. Pin the
6687 // order so a future refactor that reorders the arms surfaces
6688 // here as a test failure rather than a silent diagnostic
6689 // regression. Peer of
6690 // `max_restarts_cap_takes_precedence_over_restart_window_gates`
6691 // on the sibling zero / canonical window arms.
6692 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
6693 let s = SupervisorSpec {
6694 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
6695 restart_window: Some(w),
6696 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6697 ..SupervisorSpec::default()
6698 };
6699 assert_eq!(
6700 s.validate().unwrap_err(),
6701 SupervisorError::MaxRestartsExceedsCap {
6702 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
6703 },
6704 "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
6705 );
6706 }
6707
6708 #[test]
6709 fn restart_window_cap_diagnostic_carries_offending_value() {
6710 // The diagnostic-shape pin: the offending `Duration` is
6711 // carried verbatim into the
6712 // [`SupervisorError::RestartWindowExceedsCap`] variant so the
6713 // surfaced error message names the value the author wrote,
6714 // not just the cap. Same self-locating diagnostic shape every
6715 // other typed-cap arm on this surface carries
6716 // (`WallClockExceedsCap` carries the offending `Duration`
6717 // verbatim, `PolicyTimeoutExceedsCap` carries the offending
6718 // `Duration` verbatim, `PolicyBreakerWindowExceedsCap` carries
6719 // the offending `Duration` verbatim).
6720 let w = Duration::from_secs(7200); // 2h
6721 let s = SupervisorSpec {
6722 restart_window: Some(w),
6723 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6724 ..SupervisorSpec::default()
6725 };
6726 let err = s.validate().unwrap_err();
6727 assert!(
6728 matches!(err, SupervisorError::RestartWindowExceedsCap { window } if window == w),
6729 "got {err:?}"
6730 );
6731 let msg = err.to_string();
6732 assert!(
6733 msg.contains("7200"),
6734 ":supervisor :restart-window cap diagnostic must carry the offending value verbatim (got: {msg})"
6735 );
6736 }
6737
6738 #[test]
6739 fn supervisor_restart_window_cap_pins_canonical_value() {
6740 // The SUPERVISOR_RESTART_WINDOW_MAX constant pins the value at
6741 // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
6742 // shared duration codec emits as a clean canonical string
6743 // (`"<n>h"`). Pinning the literal value here surfaces a future
6744 // drift (a relaxation to 24h, a tightening to 5m) as a
6745 // deliberate test edit, not a silent contract narrowing.
6746 //
6747 // The four typed-`Duration` caps on the validation surface
6748 // (`LIMITS_WALL_CLOCK_MAX` per-process, `POLICY_TIMEOUT_MAX`
6749 // per-edge, `POLICY_BREAKER_WINDOW_MAX` per-breaker,
6750 // `SUPERVISOR_RESTART_WINDOW_MAX` per-supervisor) share a
6751 // single uniform top edge at the codec's largest emitted unit
6752 // — a structural-property invariant the equality assertions
6753 // here enshrine, so a future drift on any of the four
6754 // surfaces as a deliberate test edit. Same shape every other
6755 // typed-cap value pin uses
6756 // (`wall_clock_cap_pins_canonical_value`,
6757 // `policy_timeout_cap_pins_canonical_value`,
6758 // `circuit_breaker_window_cap_pins_canonical_value`).
6759 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, Duration::from_secs(3600));
6760 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX.as_millis(), 3_600_000);
6761 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::LIMITS_WALL_CLOCK_MAX);
6762 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::POLICY_TIMEOUT_MAX);
6763 assert_eq!(
6764 SUPERVISOR_RESTART_WINDOW_MAX,
6765 crate::POLICY_BREAKER_WINDOW_MAX
6766 );
6767 }
6768
6769 #[test]
6770 fn restart_window_cap_value_round_trips_through_codec() {
6771 // The codec round-trip property the cap arm preserves: the
6772 // [`SUPERVISOR_RESTART_WINDOW_MAX`] constant itself round-trips
6773 // through the shared duration codec — every value at the cap
6774 // serializes to the canonical `"1h"` form and parses back
6775 // identically. Pin the round-trip so a future change to the
6776 // codec's unit set or to the cap's magnitude that breaks the
6777 // round-trip property surfaces here. Peer of
6778 // `wall_clock_cap_value_round_trips_through_codec` on the
6779 // sibling `:limits :wall-clock` axis.
6780 let s = SupervisorSpec {
6781 restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
6782 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6783 ..SupervisorSpec::default()
6784 };
6785 s.validate().unwrap();
6786 let json = serde_json::to_string(&s).unwrap();
6787 assert!(
6788 json.contains("\"1h\""),
6789 "SUPERVISOR_RESTART_WINDOW_MAX must serialize to the canonical `\"1h\"` form (got {json})"
6790 );
6791 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6792 assert_eq!(back.restart_window, Some(SUPERVISOR_RESTART_WINDOW_MAX));
6793 }
6794
6795 #[test]
6796 fn validate_rejects_duplicate_child_caixa() {
6797 // Two children with the same :caixa render to two ComputeUnits
6798 // with the same name in the cluster's HelmRelease values —
6799 // one silently overwrites the other. Erlang/OTP's child_spec.id
6800 // is required-unique per supervisor; same set-not-multiset
6801 // discipline applied here as for :membros / :placement
6802 // :clusters / :entrada :paths.
6803 let s = SupervisorSpec {
6804 children: vec![
6805 child("worker", "^0.1", RestartPolicy::Permanent),
6806 child("cache", "^0.1", RestartPolicy::Transient),
6807 child("worker", "^0.2", RestartPolicy::Permanent),
6808 ],
6809 ..SupervisorSpec::default()
6810 };
6811 let err = s.validate().unwrap_err();
6812 assert!(
6813 matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "worker"),
6814 "got {err:?}"
6815 );
6816 }
6817
6818 #[test]
6819 fn validate_duplicate_child_diagnostic_names_first_collision() {
6820 // Iteration walks the :children list in declaration order —
6821 // the diagnostic names the first repeat, deterministically,
6822 // even when multiple names duplicate.
6823 let s = SupervisorSpec {
6824 children: vec![
6825 child("a", "^0.1", RestartPolicy::Permanent),
6826 child("b", "^0.1", RestartPolicy::Permanent),
6827 child("a", "^0.1", RestartPolicy::Permanent),
6828 child("b", "^0.1", RestartPolicy::Permanent),
6829 ],
6830 ..SupervisorSpec::default()
6831 };
6832 let err = s.validate().unwrap_err();
6833 assert!(
6834 matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "a"),
6835 "got {err:?}"
6836 );
6837 }
6838
6839 // ── self-supervision cross-slot gate ──────────────────────────
6840
6841 #[test]
6842 fn validate_no_self_supervision_rejects_self_referential_child() {
6843 // A supervisor whose `:children` lists its own `:nome` is a
6844 // one-node reconciliation cycle — rejected, naming the parent.
6845 let children = vec![
6846 child("worker", "^0.1", RestartPolicy::Permanent),
6847 child("orquestra", "^0.1", RestartPolicy::Permanent),
6848 ];
6849 let err = validate_no_self_supervision(&children, "orquestra").unwrap_err();
6850 assert!(
6851 matches!(err, SupervisorError::ChildSupervisesSelf { ref caixa } if caixa == "orquestra"),
6852 "got {err:?}"
6853 );
6854 }
6855
6856 #[test]
6857 fn validate_no_self_supervision_accepts_distinct_children() {
6858 // Positive control: distinct child names (including a child that
6859 // is itself a supervisor — nested trees are valid OTP) pass.
6860 let children = vec![
6861 child("worker", "^0.1", RestartPolicy::Permanent),
6862 child("sub-tree", "^0.1", RestartPolicy::Permanent),
6863 ];
6864 validate_no_self_supervision(&children, "orquestra").unwrap();
6865 }
6866
6867 #[test]
6868 fn validate_no_self_supervision_empty_children_is_ok() {
6869 // SimpleOneForOne / no-static-children supervisors have nothing
6870 // to self-reference — the gate is vacuously satisfied.
6871 validate_no_self_supervision(&[], "orquestra").unwrap();
6872 }
6873
6874 #[test]
6875 fn validate_simple_one_for_one_skips_uniqueness_check() {
6876 // SimpleOneForOne supervisors carry no static children — the
6877 // duplicate-child loop never runs. A zero-window declaration
6878 // on a SimpleOneForOne supervisor still trips the window check
6879 // (window applies to dynamic children too).
6880 let s = SupervisorSpec {
6881 estrategia: RestartStrategy::SimpleOneForOne,
6882 restart_window: None,
6883 children: vec![],
6884 ..SupervisorSpec::default()
6885 };
6886 s.validate().unwrap();
6887 let s_zero = SupervisorSpec {
6888 estrategia: RestartStrategy::SimpleOneForOne,
6889 restart_window: Some(Duration::ZERO),
6890 children: vec![],
6891 ..SupervisorSpec::default()
6892 };
6893 assert_eq!(
6894 s_zero.validate().unwrap_err(),
6895 SupervisorError::RestartWindowZero
6896 );
6897 }
6898
6899 #[test]
6900 fn validate_zero_window_runs_after_max_restarts_check() {
6901 // Pin the order: max_restarts == 0 fires before
6902 // restart_window == 0s, so an author with both wrong sees the
6903 // counter-axis diagnostic first (matches the order in the
6904 // struct and in the doc comment).
6905 let s = SupervisorSpec {
6906 max_restarts: 0,
6907 restart_window: Some(Duration::ZERO),
6908 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6909 ..SupervisorSpec::default()
6910 };
6911 assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
6912 }
6913
6914 #[test]
6915 fn round_trip_all_strategies() {
6916 for &strat in RestartStrategy::ALL {
6917 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
6918 // shape partition through the [`gen_platform::IsVariant`]
6919 // derive-generated [`RestartStrategy::is_simple_one_for_one`]
6920 // predicate rather than the raw
6921 // `matches!(strat, RestartStrategy::SimpleOneForOne)`
6922 // open-coded pattern-match — same closed-set-typed-enum
6923 // arm-discriminator dispatch discipline the sibling
6924 // [`crate::upgrade::UpgradeInstruction::is_restart`] convergence
6925 // (915a934) extended onto its two paired positive / negated
6926 // `matches!` filter sites, and the sibling
6927 // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
6928 // predicate convergence (766ec63) extended onto the M3 mesh-
6929 // slot per-`:placement` distribution-strategy `matches!`
6930 // discriminator axis. See the sibling
6931 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
6932 // fixture and the peer `manifest::tests::
6933 // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
6934 // fixture — all three sites (the last unlifted
6935 // `matches!`-based arm-discriminator axis on the OTP-shape
6936 // supervisor sibling-restart-strategy closed-set typed enum,
6937 // acknowledged in 915a934's Prior-commits footnote as the
6938 // outstanding follow-up) now consult one typed dispatch on
6939 // the substrate primitive.
6940 let s = SupervisorSpec {
6941 estrategia: strat,
6942 children: if strat.is_simple_one_for_one() {
6943 vec![]
6944 } else {
6945 vec![child("w", "^0.1", RestartPolicy::Permanent)]
6946 },
6947 ..SupervisorSpec::default()
6948 };
6949 let json = serde_json::to_string(&s).unwrap();
6950 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6951 assert_eq!(s, back);
6952 }
6953 }
6954
6955 #[test]
6956 fn round_trip_all_restart_policies() {
6957 for policy in [
6958 RestartPolicy::Permanent,
6959 RestartPolicy::Temporary,
6960 RestartPolicy::Transient,
6961 ] {
6962 let c = child("w", "^0.1", policy);
6963 let json = serde_json::to_string(&c).unwrap();
6964 let back: ChildSpec = serde_json::from_str(&json).unwrap();
6965 assert_eq!(c, back);
6966 }
6967 }
6968
6969 #[test]
6970 fn restart_strategy_is_simple_one_for_one_predicate_partitions_the_arm_set() {
6971 // The fail-before-pass-after pin on the `gen_platform::IsVariant`
6972 // derive's [`RestartStrategy::is_simple_one_for_one`] arm-
6973 // discriminator predicate: [`RestartStrategy::SimpleOneForOne`]
6974 // is the only variant that satisfies `.is_simple_one_for_one()`;
6975 // every static-children-bearing arm (`OneForOne` / `OneForAll`
6976 // / `RestForOne`) returns `false`. This pin makes the partition
6977 // invariant load-bearing at caixa-core test time so a future
6978 // derive regression (a hole that returns `false` for
6979 // `SimpleOneForOne` too, or a byte-collision that flips a second
6980 // variant to `true`) trips here rather than laundering the arm
6981 // at the three test-fixture builder sites (a hole flips the
6982 // `SimpleOneForOne` fixture to carry a non-empty children list
6983 // and the subsequent `SupervisorSpec::validate` would refuse the
6984 // fixture with [`SupervisorError::SimpleOneForOneWithStaticChildren`];
6985 // a collision flips a peer strategy's fixture to carry an empty
6986 // children list and the subsequent `validate` would refuse with
6987 // [`SupervisorError::NoChildren`] — either way, the pin fires
6988 // here, at the derive site, rather than at the fixture-refusal
6989 // site far away). Peer of the sibling
6990 // [`crate::upgrade::tests::upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
6991 // (915a934) pin on the M2 OTP-appup axis and the sibling
6992 // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
6993 // pin on the M0 `:kind` axis.
6994 let cases: &[(RestartStrategy, bool)] = &[
6995 (RestartStrategy::OneForOne, false),
6996 (RestartStrategy::OneForAll, false),
6997 (RestartStrategy::RestForOne, false),
6998 (RestartStrategy::SimpleOneForOne, true),
6999 ];
7000 for (variant, expected) in cases {
7001 assert_eq!(
7002 variant.is_simple_one_for_one(),
7003 *expected,
7004 "RestartStrategy::{variant:?}.is_simple_one_for_one() must \
7005 return {expected} (partition invariant on the \
7006 IsVariant-derived arm-discriminator predicate — every \
7007 test-fixture site that partitions the `:children` slot \
7008 shape on `SimpleOneForOne ↔ non-SimpleOneForOne` keys \
7009 off this typed dispatch, so a derive regression must \
7010 surface here rather than at the fixture-refusal site)"
7011 );
7012 }
7013 }
7014
7015 #[test]
7016 fn restart_strategy_fixture_partition_routes_through_is_simple_one_for_one_predicate() {
7017 // Byte-identity pin on the `SimpleOneForOne ↔ non-SimpleOneForOne`
7018 // fixture-shape partition against the pre-lift
7019 // `matches!(strat, RestartStrategy::SimpleOneForOne)` open-coded
7020 // pattern-match every test-fixture builder site previously
7021 // coupled to inline. Asserts the two projections agree byte-for-
7022 // byte on every arm of the enum, so a future derive regression
7023 // that flipped either predicate's arm-set would surface here at
7024 // caixa-core test time rather than at the three fixture-builder
7025 // sites (`supervisor::tests::round_trip_all_strategies`,
7026 // `supervisor::tests::supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`,
7027 // `manifest::tests::caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`)
7028 // far from the derive site. Same peer-shape byte-identity pin
7029 // every sibling `IsVariant`-derive-routed convergence carries on
7030 // the substrate's closed-set typed-enum surface (peer of
7031 // [`crate::upgrade::tests::validate_restart_exclusive_routes_through_is_restart_predicate`]
7032 // on the M2 OTP-appup axis).
7033 for &strat in RestartStrategy::ALL {
7034 let via_predicate = strat.is_simple_one_for_one();
7035 let via_matches = matches!(strat, RestartStrategy::SimpleOneForOne);
7036 assert_eq!(
7037 via_predicate, via_matches,
7038 "RestartStrategy::{strat:?}: is_simple_one_for_one() must \
7039 byte-equal matches!(_, RestartStrategy::SimpleOneForOne) — \
7040 the pre-lift open-coded pattern and the \
7041 IsVariant-derived predicate are the same axis, \
7042 one typed dispatch"
7043 );
7044 }
7045 }
7046
7047 #[test]
7048 fn duration_codec_round_trip_canonical_units() {
7049 // Note the canonical-form rule: durations serialize to the
7050 // *largest* unit that divides cleanly, so 60s ↔ "1m" and not
7051 // "60s" — but the round-trip preserves the underlying Duration.
7052 let cases = [
7053 ("30s", Duration::from_secs(30)),
7054 ("5m", Duration::from_secs(300)),
7055 ("1h", Duration::from_secs(3600)),
7056 ("500ms", Duration::from_millis(500)),
7057 ];
7058 for (lit, dur) in cases {
7059 let s = SupervisorSpec {
7060 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7061 restart_window: Some(dur),
7062 ..SupervisorSpec::default()
7063 };
7064 let json = serde_json::to_string(&s).unwrap();
7065 assert!(
7066 json.contains(&format!("\"{lit}\"")),
7067 "expected \"{lit}\" in {json}"
7068 );
7069 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
7070 assert_eq!(back.restart_window, Some(dur));
7071 }
7072 }
7073
7074 #[test]
7075 fn duration_canonicalizes_to_largest_unit() {
7076 // 60 seconds → "1m" (largest cleanly-divisible unit), but the
7077 // typed Duration still equals 60s on the way back.
7078 let s = SupervisorSpec {
7079 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7080 restart_window: Some(Duration::from_secs(60)),
7081 ..SupervisorSpec::default()
7082 };
7083 let json = serde_json::to_string(&s).unwrap();
7084 assert!(json.contains("\"1m\""), "{json}");
7085 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
7086 assert_eq!(back.restart_window, Some(Duration::from_secs(60)));
7087 }
7088
7089 #[test]
7090 fn three_child_one_for_one_validates() {
7091 let s = SupervisorSpec {
7092 estrategia: RestartStrategy::OneForOne,
7093 max_restarts: 5,
7094 restart_window: Some(Duration::from_secs(60)),
7095 children: vec![
7096 child("worker", "^0.1", RestartPolicy::Permanent),
7097 child("cache", "^0.1", RestartPolicy::Transient),
7098 child("scratch", "^0.1", RestartPolicy::Temporary),
7099 ],
7100 };
7101 s.validate().unwrap();
7102 }
7103
7104 #[test]
7105 fn json_uses_pascal_case_for_strategy_and_policy() {
7106 // Variant names are PascalCase by default in serde, matching
7107 // tatara-lisp's enum convention (`:estrategia OneForOne`).
7108 let c = child("w", "^0.1", RestartPolicy::Permanent);
7109 let json = serde_json::to_string(&c).unwrap();
7110 assert!(json.contains("\"Permanent\""));
7111 assert!(!json.contains("\"permanent\""));
7112
7113 let s = SupervisorSpec {
7114 estrategia: RestartStrategy::OneForOne,
7115 children: vec![c],
7116 ..SupervisorSpec::default()
7117 };
7118 let json = serde_json::to_string(&s).unwrap();
7119 assert!(json.contains("\"estrategia\":\"OneForOne\""));
7120 }
7121
7122 // ── shared duration codec: integer-magnitude canonical-form gate ──
7123 //
7124 // The gate lifts the discipline `crate::limits::parse_duration`
7125 // (818dd38) carries on the peer `:limits :wall-clock` codec onto
7126 // the shared codec backing the remaining three typed-duration
7127 // slots: `:supervisor :restart-window`, `:politicas :timeout`, and
7128 // `:politicas :circuit-breaker :window`. Every magnitude `render`
7129 // emits is a non-negative integer with no decimal point and no
7130 // leading sign, so the codec's accepted set must match for
7131 // serialize/deserialize to round-trip without canonical-form
7132 // drift.
7133
7134 #[test]
7135 fn parse_accepts_integer_canonical_units() {
7136 // Pin the happy-path: every canonical author shape `render`
7137 // ever emits parses to the same `Duration` value, so the
7138 // codec's accepted set is at least a superset of its emitted
7139 // set on the canonical-unit axis.
7140 for (lit, dur) in [
7141 ("30s", Duration::from_secs(30)),
7142 ("500ms", Duration::from_millis(500)),
7143 ("2m", Duration::from_secs(120)),
7144 ("1h", Duration::from_secs(3600)),
7145 ("0s", Duration::ZERO),
7146 ] {
7147 assert_eq!(
7148 duration_codec::parse(lit).unwrap(),
7149 dur,
7150 "parse({lit:?}) should be {dur:?}"
7151 );
7152 }
7153 }
7154
7155 #[test]
7156 fn parse_accepts_bare_integer_as_seconds() {
7157 // The `"s" | ""` arm: a bare integer with no unit is read as
7158 // seconds. Pin this so the unit-empty form keeps parsing (it
7159 // renders to `"<n>s"` on serialize — that's a unit-choice
7160 // drift the integer-magnitude gate does NOT close, matching
7161 // the `parse_byte_size` `"1024"` → `"1KiB"` scope decision in
7162 // the peer `:limits :memory` codec).
7163 assert_eq!(
7164 duration_codec::parse("30").unwrap(),
7165 Duration::from_secs(30)
7166 );
7167 }
7168
7169 #[test]
7170 fn parse_rejects_fractional_seconds_with_canonical_form_diagnostic() {
7171 // `"1.5s"` parses as f64 to 1.5 → renders back as `"1500ms"`
7172 // on first serialize — DRIFT. The integer-magnitude gate names
7173 // the offending `"1.5"` verbatim and points at the canonical
7174 // remediation `"1500ms"`.
7175 let err = duration_codec::parse("1.5s").unwrap_err();
7176 assert!(err.contains("\"1.5\""), "missing magnitude in {err:?}");
7177 assert!(
7178 err.contains("not a non-negative integer"),
7179 "missing canonical-form reason in {err:?}"
7180 );
7181 assert!(
7182 err.contains("\"1500ms\""),
7183 "missing canonical-form remediation in {err:?}"
7184 );
7185 }
7186
7187 #[test]
7188 fn parse_rejects_decimal_shaped_integer_seconds() {
7189 // `"1.0s"` is the trickiest drift class: numerically `1.0s` is
7190 // `1s` exactly, so the round-trip looks correct — but the
7191 // emitted canonical form is `"1s"`, not `"1.0s"`. Gate the
7192 // decimal-shape-with-integer-value form so author intent is
7193 // never silently rewritten.
7194 let err = duration_codec::parse("1.0s").unwrap_err();
7195 assert!(err.contains("\"1.0\""), "missing magnitude in {err:?}");
7196 assert!(
7197 err.contains("not a non-negative integer"),
7198 "missing canonical-form reason in {err:?}"
7199 );
7200 }
7201
7202 #[test]
7203 fn parse_rejects_half_unit_minute() {
7204 // `"0.5m"` is the unit-fraction footgun — author writes a
7205 // human-readable half-minute, serde silently rewrites to
7206 // `"30s"` on next emit. The gate names the offending
7207 // magnitude `"0.5"` and points at the integer-in-smaller-unit
7208 // form.
7209 let err = duration_codec::parse("0.5m").unwrap_err();
7210 assert!(err.contains("\"0.5\""), "missing magnitude in {err:?}");
7211 assert!(
7212 err.contains("\"30s\""),
7213 "missing canonical-form remediation in {err:?}"
7214 );
7215 }
7216
7217 #[test]
7218 fn parse_rejects_leading_plus_sign() {
7219 // `u64::from_str` rejects `"+30"` but `f64::from_str` accepts
7220 // it as `30.0` — the prior parser used f64 so `"+30s"` parsed
7221 // cleanly to 30s and round-tripped to `"30s"` on next emit
7222 // (DRIFT). The digit-only gate closes the leading-sign class
7223 // first; the diagnostic names `"+30"` verbatim.
7224 let err = duration_codec::parse("+30s").unwrap_err();
7225 assert!(err.contains("\"+30\""), "missing magnitude in {err:?}");
7226 assert!(
7227 err.contains("not a non-negative integer"),
7228 "missing canonical-form reason in {err:?}"
7229 );
7230 }
7231
7232 #[test]
7233 fn parse_rejects_leading_minus_sign() {
7234 // The former `num < 0.0` arm: `"-30s"` parsed as f64 to -30,
7235 // rejected with `"negative duration in \"-30s\""`. Under the
7236 // integer-magnitude gate the diagnostic is unified — `-30` is
7237 // non-digit-only, f64-numeric, and surfaces with the canonical-
7238 // form reason (no leading `+` / `-` sign) naming the offending
7239 // `"-30"` verbatim. Same diagnostic shape as every other
7240 // rejected non-integer magnitude.
7241 let err = duration_codec::parse("-30s").unwrap_err();
7242 assert!(err.contains("\"-30\""), "missing magnitude in {err:?}");
7243 assert!(
7244 err.contains("not a non-negative integer"),
7245 "missing canonical-form reason in {err:?}"
7246 );
7247 }
7248
7249 #[test]
7250 fn parse_garbage_still_falls_through_to_bad_magnitude() {
7251 // Non-digit-only AND non-numeric (`"--1s"`, `"abc"`) falls
7252 // through to the narrower "bad duration magnitude" arm — the
7253 // canonical-form diagnostic is reserved for the parser-shape
7254 // footgun case, not the "not a number at all" case. Same
7255 // shape `parse_byte_size`'s `BadByteMagnitude` arm carries on
7256 // the peer `:limits :memory` codec.
7257 let err = duration_codec::parse("--1s").unwrap_err();
7258 assert!(
7259 err.contains("bad duration magnitude"),
7260 "expected bad-magnitude wording in {err:?}"
7261 );
7262 }
7263
7264 #[test]
7265 fn parse_digit_only_magnitude_carries_zero_f64_drift() {
7266 // The accepted set is now closed under `u64`-exact integer
7267 // arithmetic: `"500ms"` → `Duration::from_millis(500)` exactly,
7268 // `"3600s"` → `Duration::from_secs(3600)` exactly, `"1h"` →
7269 // `Duration::from_secs(3600)` exactly, no f64 mantissa drift
7270 // possible. Pin the integer-exact arms across the four unit
7271 // suffixes so a future refactor that reaches back for f64
7272 // (`from_secs_f64`, `mul_f64`) surfaces here.
7273 assert_eq!(
7274 duration_codec::parse("3600s").unwrap(),
7275 Duration::from_secs(3600)
7276 );
7277 assert_eq!(
7278 duration_codec::parse("60m").unwrap(),
7279 Duration::from_secs(3600)
7280 );
7281 assert_eq!(
7282 duration_codec::parse("1h").unwrap(),
7283 Duration::from_secs(3600)
7284 );
7285 assert_eq!(
7286 duration_codec::parse("999ms").unwrap(),
7287 Duration::from_millis(999)
7288 );
7289 }
7290
7291 #[test]
7292 fn restart_window_serde_rejects_fractional_seconds() {
7293 // The shared codec backs `SupervisorSpec::restart_window`
7294 // (`with = "duration_codec"`) — so the gate applies on serde
7295 // deserialize for the typed Supervisor slot. A
7296 // `{"restartWindow":"1.5s"}` payload that previously round-
7297 // tripped to a different canonical string on next serialize
7298 // is now refused at deserialize with the integer-magnitude
7299 // diagnostic.
7300 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
7301 "restartWindow":"1.5s",
7302 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
7303 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7304 let msg = err.to_string();
7305 assert!(
7306 msg.contains("not a non-negative integer"),
7307 "expected integer-magnitude diagnostic in {msg:?}"
7308 );
7309 assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
7310 }
7311
7312 #[test]
7313 fn restart_window_serde_rejects_leading_plus() {
7314 // The `u64::from_str` leading-`+` permissiveness gap that
7315 // motivated the digit-only gate (the `f64`-side accepted
7316 // `"+30"`, the prior parser silently round-tripped to `"30s"`)
7317 // is now closed on the shared codec — surfaces as a structured
7318 // diagnostic at the serde layer for every typed-duration slot.
7319 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
7320 "restartWindow":"+30s",
7321 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
7322 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7323 let msg = err.to_string();
7324 assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
7325 assert!(
7326 msg.contains("not a non-negative integer"),
7327 "missing canonical-form reason in {msg:?}"
7328 );
7329 }
7330
7331 #[test]
7332 fn parse_rejects_leading_zero_magnitude() {
7333 // `"030s"` is digit-only, so the existing non-digit-only / sign
7334 // / fractional arm doesn't catch it — `u64::from_str("030")`
7335 // returns `Ok(30)`, so before this gate `"030s"` parsed to
7336 // `Duration::from_secs(30)` and round-tripped through `render`
7337 // to `"30s"` — a *different* canonical string on the next emit,
7338 // breaking the THEORY.md Part V render-determinism contract
7339 // exactly the way `"+30s"` did before the leading-`+` arm
7340 // landed. Peer with the `rate_limit_codec` leading-zero arm
7341 // (4f46830) on the same canonical-form-drift axis.
7342 let err = duration_codec::parse("030s").unwrap_err();
7343 assert!(
7344 err.contains("non-canonical leading zero"),
7345 "expected leading-zero diagnostic in {err:?}"
7346 );
7347 assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
7348 assert!(
7349 err.contains("\"30s\""),
7350 "missing canonical-form remediation in {err:?}"
7351 );
7352 assert!(
7353 err.contains("THEORY.md"),
7354 "missing render-determinism citation in {err:?}"
7355 );
7356 }
7357
7358 #[test]
7359 fn parse_rejects_multi_digit_zero_magnitude() {
7360 // `"00s"` and `"00ms"` are the all-zero leading-zero footgun —
7361 // digit-only, parse losslessly to `Duration::ZERO`, but render
7362 // back to `"0s"` (the single-byte canonical form) on the next
7363 // emit. The leading-zero arm refuses the drift class at the
7364 // codec layer; the semantic-zero gate downstream
7365 // (`SupervisorError::ZeroRestartWindow`, etc.) would refuse
7366 // the single-byte canonical form `"0s"` separately on the
7367 // typed-validate layer.
7368 let err = duration_codec::parse("00s").unwrap_err();
7369 assert!(
7370 err.contains("non-canonical leading zero"),
7371 "expected leading-zero diagnostic in {err:?}"
7372 );
7373 assert!(err.contains("\"00\""), "missing magnitude in {err:?}");
7374 }
7375
7376 #[test]
7377 fn parse_rejects_leading_zero_per_hour_window() {
7378 // `"01h"` is the per-hour-window footgun — multi-byte magnitude
7379 // starting with `0`, parses losslessly to `Duration::from_secs(3600)`,
7380 // renders to `"1h"` (DRIFT). The arm is unit-agnostic: every
7381 // canonical unit suffix the codec accepts (`ms` / `s` / `m` /
7382 // `h` / bare-integer-as-seconds) inherits the same gate.
7383 let err = duration_codec::parse("01h").unwrap_err();
7384 assert!(
7385 err.contains("non-canonical leading zero"),
7386 "expected leading-zero diagnostic in {err:?}"
7387 );
7388 assert!(err.contains("\"01\""), "missing magnitude in {err:?}");
7389 }
7390
7391 #[test]
7392 fn parse_rejects_leading_zero_bare_integer_as_seconds() {
7393 // The `parse_accepts_bare_integer_as_seconds` happy-path
7394 // (`"30"` → 30s) inherits the leading-zero arm: `"030"` is
7395 // multi-byte starts-with-`0`, parses losslessly to
7396 // `Duration::from_secs(30)`, renders to `"30s"` (DRIFT). The
7397 // bare-integer surface accepts permissive unit-empty
7398 // shorthand but still must reject leading-zero padding.
7399 let err = duration_codec::parse("030").unwrap_err();
7400 assert!(
7401 err.contains("non-canonical leading zero"),
7402 "expected leading-zero diagnostic in {err:?}"
7403 );
7404 assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
7405 }
7406
7407 #[test]
7408 fn parse_accepts_single_zero_magnitude_at_codec_layer() {
7409 // The codec-layer / typed-validate-layer boundary: `"0s"` /
7410 // `"0ms"` / `"0"` are the single-byte canonical-zero forms —
7411 // each round-trips losslessly through `render`
7412 // (`render(Duration::ZERO)` → `"0s"`), so the codec layer
7413 // accepts them. The downstream semantic-zero gates
7414 // (`SupervisorError::ZeroRestartWindow`,
7415 // `AplicacaoError::PolicyTimeoutZero`,
7416 // `AplicacaoError::PolicyCircuitBreakerWindowZero`) refuse
7417 // zero-magnitude authoring at the typed-validate layer above,
7418 // peer with the `rate_limit_codec` codec-layer / typed-
7419 // validate-layer partition for `"0/s"`.
7420 assert_eq!(duration_codec::parse("0s").unwrap(), Duration::ZERO);
7421 assert_eq!(duration_codec::parse("0ms").unwrap(), Duration::ZERO);
7422 assert_eq!(duration_codec::parse("0").unwrap(), Duration::ZERO);
7423 }
7424
7425 #[test]
7426 fn parse_accepts_canonical_magnitude_with_leading_one() {
7427 // The complementary boundary: a future tightening cannot
7428 // drift into rejecting valid canonical magnitudes that
7429 // happen to start with `1` (or any digit `[1-9]`). Pin
7430 // every canonical-unit suffix so the leading-zero arm
7431 // remains strictly narrower than the digit-only arm.
7432 assert_eq!(
7433 duration_codec::parse("100ms").unwrap(),
7434 Duration::from_millis(100)
7435 );
7436 assert_eq!(
7437 duration_codec::parse("100s").unwrap(),
7438 Duration::from_secs(100)
7439 );
7440 assert_eq!(
7441 duration_codec::parse("10m").unwrap(),
7442 Duration::from_secs(600)
7443 );
7444 assert_eq!(
7445 duration_codec::parse("10h").unwrap(),
7446 Duration::from_secs(36_000)
7447 );
7448 }
7449
7450 #[test]
7451 fn restart_window_serde_rejects_leading_zero() {
7452 // The shared codec backs `SupervisorSpec::restart_window`
7453 // (`with = "duration_codec"`) — so the leading-zero arm
7454 // applies on serde deserialize for the typed Supervisor slot.
7455 // A `{"restartWindow":"030s"}` payload that previously round-
7456 // tripped to a different canonical string on next serialize
7457 // is now refused at deserialize with the leading-zero
7458 // diagnostic. Peer with `restart_window_serde_rejects_leading_plus`
7459 // / `restart_window_serde_rejects_fractional_seconds` on the
7460 // same canonical-form-drift axis.
7461 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
7462 "restartWindow":"030s",
7463 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
7464 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7465 let msg = err.to_string();
7466 assert!(
7467 msg.contains("non-canonical leading zero"),
7468 "expected leading-zero diagnostic in {msg:?}"
7469 );
7470 assert!(msg.contains("\"030\""), "missing magnitude in {msg:?}");
7471 }
7472
7473 #[test]
7474 fn parse_rejects_leading_whitespace() {
7475 // `" 30s"` — the canonical paste-from-aligned-doc /
7476 // paste-from-YAML-quoted-plain-scalar footgun. Before this
7477 // gate the top-level `s.trim()` at parse entry silently ate
7478 // the leading space and parsed the value to
7479 // `Duration::from_secs(30)`, which then round-tripped through
7480 // `render` to `"30s"` (a *different* canonical string on the
7481 // next emit) — the exact canonical-form-drift class the
7482 // leading-`+` / leading-zero arms already close, extended
7483 // to the whitespace-byte class. Peer with the sibling
7484 // `rate_limit_codec` whitespace-rejection arm (1ad7755) on
7485 // the M3 `:politicas` axis.
7486 let err = duration_codec::parse(" 30s").unwrap_err();
7487 assert!(
7488 err.contains("contains whitespace byte"),
7489 "expected whitespace diagnostic in {err:?}"
7490 );
7491 assert!(err.contains("0x20"), "missing offending byte in {err:?}");
7492 assert!(
7493 err.contains("THEORY.md"),
7494 "missing render-determinism contract citation in {err:?}"
7495 );
7496 }
7497
7498 #[test]
7499 fn parse_rejects_trailing_whitespace() {
7500 // `"30s "` — the canonical shell-history / trailing-space
7501 // paste footgun. Before this gate the top-level `s.trim()`
7502 // silently ate the trailing space and parsed to
7503 // `Duration::from_secs(30)`, round-tripping to `"30s"` on the
7504 // next emit — same canonical-form drift as the leading-space
7505 // sibling, closed on the same whitespace-byte arm.
7506 let err = duration_codec::parse("30s ").unwrap_err();
7507 assert!(
7508 err.contains("contains whitespace byte"),
7509 "expected whitespace diagnostic in {err:?}"
7510 );
7511 assert!(err.contains("0x20"), "missing offending byte in {err:?}");
7512 }
7513
7514 #[test]
7515 fn parse_rejects_internal_whitespace_between_magnitude_and_unit() {
7516 // `"30 s"` — the canonical typographically-spaced author
7517 // shape (the same idiom every prose reference to a duration
7518 // renders as, mistakenly retained when the value is pasted
7519 // into a codec-shaped slot). Before this gate the per-part
7520 // `num_part.trim()` / `unit.trim()` calls silently ate the
7521 // whitespace between the magnitude and the unit and parsed
7522 // the value to `Duration::from_secs(30)`, round-tripping to
7523 // `"30s"` — the codec's *internal* whitespace-tolerance
7524 // vector, orthogonal to the leading / trailing surface but
7525 // the same canonical-form-drift class. Pins the arm as
7526 // strictly stronger than the pre-existing top-level
7527 // `s.trim()` behavior: it fires on whitespace anywhere in
7528 // the value, not just at the string boundary.
7529 let err = duration_codec::parse("30 s").unwrap_err();
7530 assert!(
7531 err.contains("contains whitespace byte"),
7532 "expected whitespace diagnostic in {err:?}"
7533 );
7534 assert!(err.contains("0x20"), "missing offending byte in {err:?}");
7535 }
7536
7537 #[test]
7538 fn parse_rejects_tab_byte() {
7539 // `"\t30s"` — the canonical paste-from-indented-doc /
7540 // paste-from-YAML-block-scalar footgun where a tab byte leads
7541 // the magnitude. Pins that the gate covers tab (`0x09`) as
7542 // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
7543 // members and both would be silently swallowed by `s.trim()`
7544 // pre-gate. The `is_ascii_whitespace` coverage extends beyond
7545 // space alone to the full ASCII-whitespace set (space `0x20`,
7546 // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
7547 // the tab arm as a representative of the non-space members.
7548 let err = duration_codec::parse("\t30s").unwrap_err();
7549 assert!(
7550 err.contains("contains whitespace byte"),
7551 "expected whitespace diagnostic in {err:?}"
7552 );
7553 assert!(
7554 err.contains("0x09"),
7555 "missing offending tab byte in {err:?}"
7556 );
7557 }
7558
7559 #[test]
7560 fn restart_window_serde_rejects_whitespace() {
7561 // The shared codec backs `SupervisorSpec::restart_window`
7562 // (`with = "duration_codec"`) — so the whitespace arm
7563 // applies on serde deserialize for the typed Supervisor slot.
7564 // A `{"restartWindow":" 30s"}` payload that previously round-
7565 // tripped to a different canonical string on next serialize
7566 // is now refused at deserialize with the whitespace-byte
7567 // diagnostic. Peer with `restart_window_serde_rejects_leading_zero`
7568 // / `restart_window_serde_rejects_leading_plus` /
7569 // `restart_window_serde_rejects_fractional_seconds` on the
7570 // same canonical-form-drift axis.
7571 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
7572 "restartWindow":" 30s",
7573 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
7574 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7575 let msg = err.to_string();
7576 assert!(
7577 msg.contains("contains whitespace byte"),
7578 "expected whitespace diagnostic in {msg:?}"
7579 );
7580 assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
7581 }
7582
7583 // ── canonical-form: non-ASCII Unicode `White_Space` duration gate ─────
7584 //
7585 // Successor to the ASCII-whitespace arm (a7ae622) on the shared
7586 // duration codec — closes the strictly-complementary class the
7587 // byte-scan cannot see, through the lifted
7588 // [`crate::render::find_non_ascii_whitespace_char`] predicate.
7589 // Applies to `:supervisor :restart-window`, `:politicas :timeout`,
7590 // and `:politicas :circuit-breaker :window` simultaneously via
7591 // this shared codec.
7592
7593 #[test]
7594 fn duration_codec_parse_rejects_leading_nbsp() {
7595 // NBSP prefix — the strictly-complementary drift class the
7596 // ASCII byte-scan cannot see. `str::trim` strips it silently
7597 // and the value drifts to `"30s"` on next serialize.
7598 let err = duration_codec::parse("\u{00A0}30s").unwrap_err();
7599 assert!(
7600 err.contains("non-ASCII Unicode whitespace character"),
7601 "expected non-ASCII whitespace diagnostic in {err:?}"
7602 );
7603 assert!(err.contains("U+00A0"), "missing codepoint in {err:?}");
7604 }
7605
7606 #[test]
7607 fn duration_codec_parse_rejects_trailing_line_separator() {
7608 // LINE SEPARATOR (`\u{2028}`) trailing — paste-from-web-doc
7609 // footgun.
7610 let err = duration_codec::parse("30s\u{2028}").unwrap_err();
7611 assert!(
7612 err.contains("non-ASCII Unicode whitespace character"),
7613 "expected non-ASCII whitespace diagnostic in {err:?}"
7614 );
7615 assert!(err.contains("U+2028"), "missing codepoint in {err:?}");
7616 }
7617
7618 #[test]
7619 fn duration_codec_parse_accepts_ascii_only_forms_after_unicode_arm() {
7620 // Positive-control pin: every ASCII-only canonical form the
7621 // renderer emits stays accepted through the new arm.
7622 assert_eq!(
7623 duration_codec::parse("30s").unwrap(),
7624 Duration::from_secs(30)
7625 );
7626 assert_eq!(
7627 duration_codec::parse("500ms").unwrap(),
7628 Duration::from_millis(500)
7629 );
7630 assert_eq!(
7631 duration_codec::parse("1h").unwrap(),
7632 Duration::from_secs(3600)
7633 );
7634 }
7635
7636 #[test]
7637 fn restart_window_serde_rejects_non_ascii_whitespace() {
7638 // The shared codec backs `SupervisorSpec::restart_window` — so
7639 // the new non-ASCII Unicode whitespace arm applies on serde
7640 // deserialize for the typed Supervisor slot. A
7641 // `{"restartWindow":" 30s"}` payload that previously
7642 // survived the ASCII byte-scan (only ASCII whitespace was
7643 // refused) is now refused at deserialize with the
7644 // non-ASCII-whitespace-and-codepoint diagnostic.
7645 let payload = "{\"estrategia\":\"OneForOne\",\"maxRestarts\":5,\
7646 \"restartWindow\":\"\u{00A0}30s\",\
7647 \"children\":[{\"caixa\":\"w\",\"versao\":\"^0.1\",\"restart\":\"Permanent\"}]}";
7648 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7649 let msg = err.to_string();
7650 assert!(
7651 msg.contains("non-ASCII Unicode whitespace character"),
7652 "expected non-ASCII whitespace diagnostic in {msg:?}"
7653 );
7654 assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
7655 }
7656
7657 // ── drift-detection: serde-derive-to-SUPERVISOR_KEY_* identity ────────
7658
7659 #[test]
7660 fn supervisor_spec_serde_keys_match_lifted_supervisor_key_consts() {
7661 // Load-bearing invariant: the four `SUPERVISOR_KEY_*` consts
7662 // (`SUPERVISOR_KEY_ESTRATEGIA` / `SUPERVISOR_KEY_MAX_RESTARTS` /
7663 // `SUPERVISOR_KEY_RESTART_WINDOW` / `SUPERVISOR_KEY_CHILDREN`)
7664 // name the exact camelCase JSON keys the
7665 // `#[serde(rename_all = "camelCase")]` attribute on
7666 // `SupervisorSpec` emits. Serialize a fully-populated spec (each
7667 // field carries `Some(_)` / non-empty) and pin that each canonical
7668 // byte-sequence appears verbatim in the JSON — a future accidental
7669 // `rename_all = "snake_case"` / `"kebab-case"` / verbatim-field-
7670 // name flip at the derive attribute (any of which would silently
7671 // break every downstream JSON consumer that reaches for one of the
7672 // four consts via `Value::get(...)`) surfaces here as a build-time
7673 // test failure at `supervisor.rs`, not as an apply-time
7674 // `.get(<stale-canonical-const>)` returning `None` far from the
7675 // derive-attr drift's commit. Peer with the sibling
7676 // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
7677 // (d8b8b4f) pin on the M2 `:limits` axis — same discipline the
7678 // M2 typed-slot family established, extended here to close the
7679 // top-level Supervisor axis.
7680 let spec = SupervisorSpec {
7681 estrategia: RestartStrategy::OneForOne,
7682 max_restarts: 5,
7683 restart_window: Some(Duration::from_secs(60)),
7684 children: vec![ChildSpec {
7685 caixa: "w".into(),
7686 versao: "^0.1".into(),
7687 restart: RestartPolicy::Permanent,
7688 }],
7689 };
7690 let json = serde_json::to_string(&spec).unwrap();
7691 for key in [
7692 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7693 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7694 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7695 crate::render::SUPERVISOR_KEY_CHILDREN,
7696 ] {
7697 let quoted = format!("\"{key}\"");
7698 assert!(
7699 json.contains("ed),
7700 "serialized SupervisorSpec must carry the lifted \
7701 SUPERVISOR_KEY_* byte-sequence {quoted} verbatim in \
7702 the JSON emission (got: {json})",
7703 );
7704 }
7705 }
7706
7707 #[test]
7708 fn supervisor_key_consts_are_pairwise_distinct() {
7709 // Cross-axis drift-detection pin: a future collapse of two
7710 // canonical top-level byte-strings onto the same value (e.g. an
7711 // accidental copy-paste flip of `SUPERVISOR_KEY_CHILDREN` to
7712 // also read `"estrategia"`) would silently reroute every
7713 // downstream probe on one axis onto the sibling axis's overlay
7714 // entry and pass every propagation-probe test that expected only
7715 // the stale axis's value. Peer of the sibling four-way distinct
7716 // pin on the `M2_LIMITS_KEY_*` tetrad (d8b8b4f).
7717 let all = [
7718 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7719 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7720 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7721 crate::render::SUPERVISOR_KEY_CHILDREN,
7722 ];
7723 for (i, a) in all.iter().enumerate() {
7724 for b in all.iter().skip(i + 1) {
7725 assert_ne!(
7726 a, b,
7727 "SUPERVISOR_KEY_* consts must be pairwise-distinct \
7728 canonical byte-sequences — got `{a}` == `{b}`",
7729 );
7730 }
7731 }
7732 }
7733
7734 #[test]
7735 fn supervisor_key_consts_are_lower_camel_case_shape() {
7736 // Shape-pin: every `SUPERVISOR_KEY_*` const must be a
7737 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
7738 // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
7739 // capital, no whitespace / dots) — the canonical shape the
7740 // `#[serde(rename_all = "camelCase")]` derive produces on
7741 // `SupervisorSpec`. A future flip to a non-camelCase attribute
7742 // at the derive surfaces both here (this test fails on the
7743 // stale-constant shape) and at
7744 // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
7745 // (that test fails on the mismatch between const and derive).
7746 // Peer with `m2_limits_key_consts_are_lower_camel_case_shape`
7747 // (d8b8b4f) on the sibling M2 `:limits` axis.
7748 for key in [
7749 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7750 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7751 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7752 crate::render::SUPERVISOR_KEY_CHILDREN,
7753 ] {
7754 assert!(
7755 !key.is_empty(),
7756 "SUPERVISOR_KEY_* must be non-empty (got {key:?})"
7757 );
7758 let first = key.chars().next().unwrap();
7759 assert!(
7760 first.is_ascii_lowercase(),
7761 "SUPERVISOR_KEY_* must lead with an ASCII-lowercase byte \
7762 (got {key:?}, leads with {first:?})",
7763 );
7764 assert!(
7765 key.chars().all(|c| c.is_ascii_alphanumeric()),
7766 "SUPERVISOR_KEY_* must be ASCII-alphanumeric only \
7767 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
7768 );
7769 }
7770 }
7771
7772 #[test]
7773 fn supervisor_key_consts_are_byte_distinct_from_supervisor_author_key_peers() {
7774 // Cross-axis drift pin: the four `SUPERVISOR_KEY_*` consts
7775 // (camelCase JSON keys, no leading colon) must never collide
7776 // byte-for-byte with the four peer `SUPERVISOR_AUTHOR_KEY_*`
7777 // consts (kebab-case author-facing labels with leading colon)
7778 // that sit next to them at `caixa_core::render`. Both families
7779 // cover the same four typed Supervisor slots on two distinct
7780 // axes (author-side kebab vs renderer-side camelCase);
7781 // collapsing either family onto the other's byte-shape would
7782 // silently reroute the render-side probe onto the author-facing
7783 // surface, or vice versa. Peer of the byte-distinctness
7784 // discipline the `M3_PLACEMENT_KEY_ESTRATEGIA` docstring names
7785 // against the peer `M3_AUTHOR_KEY_PLACEMENT`.
7786 let pairs = [
7787 (
7788 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7789 crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA,
7790 ),
7791 (
7792 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7793 crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS,
7794 ),
7795 (
7796 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7797 crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW,
7798 ),
7799 (
7800 crate::render::SUPERVISOR_KEY_CHILDREN,
7801 crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN,
7802 ),
7803 ];
7804 for (json_key, author_key) in pairs {
7805 assert_ne!(
7806 json_key, author_key,
7807 "SUPERVISOR_KEY_* (JSON side) must differ byte-for-byte \
7808 from the peer SUPERVISOR_AUTHOR_KEY_* (author side); \
7809 got JSON `{json_key}` == author `{author_key}`",
7810 );
7811 }
7812 }
7813
7814 // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_KEY_* identity ──
7815
7816 #[test]
7817 fn child_spec_serde_keys_match_lifted_supervisor_child_key_consts() {
7818 // Load-bearing invariant: the three `SUPERVISOR_CHILD_KEY_*` consts
7819 // (`SUPERVISOR_CHILD_KEY_CAIXA` / `SUPERVISOR_CHILD_KEY_VERSAO` /
7820 // `SUPERVISOR_CHILD_KEY_RESTART`) name the exact camelCase JSON
7821 // keys the `#[serde(rename_all = "camelCase")]` attribute on
7822 // `ChildSpec` emits. Serialize a fully-populated `ChildSpec` and
7823 // pin that each canonical byte-sequence appears verbatim in the
7824 // JSON — a future accidental `rename_all = "snake_case"` /
7825 // `"kebab-case"` / verbatim-field-name flip at the derive
7826 // attribute (any of which would silently break every downstream
7827 // JSON consumer that reaches for one of the three consts via
7828 // `Value::get(...)`) surfaces here as a build-time test failure at
7829 // `supervisor.rs`, not as an apply-time
7830 // `.get(<stale-canonical-const>)` returning `None` far from the
7831 // derive-attr drift's commit. Peer with the enclosing
7832 // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
7833 // (40cc4e5) pin on the M2 supervision-tree top-level axis — same
7834 // discipline the SupervisorSpec top-level lift established,
7835 // extended here to the sibling per-`:children` entry `ChildSpec`
7836 // derive so the last M2 typed-struct sub-block
7837 // `#[serde(rename_all = "camelCase")]` axis on the Supervisor
7838 // surface without a lifted serde-key peer joins the substrate's
7839 // "one canonical byte-string per typed serialized-key axis"
7840 // discipline.
7841 let c = ChildSpec {
7842 caixa: "worker".into(),
7843 versao: "^0.1".into(),
7844 restart: RestartPolicy::Permanent,
7845 };
7846 let json = serde_json::to_string(&c).unwrap();
7847 for key in [
7848 crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
7849 crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
7850 crate::render::SUPERVISOR_CHILD_KEY_RESTART,
7851 ] {
7852 let quoted = format!("\"{key}\"");
7853 assert!(
7854 json.contains("ed),
7855 "serialized ChildSpec must carry the lifted \
7856 SUPERVISOR_CHILD_KEY_* byte-sequence {quoted} verbatim \
7857 in the JSON emission (got: {json})",
7858 );
7859 }
7860 }
7861
7862 #[test]
7863 fn supervisor_child_key_consts_are_pairwise_distinct() {
7864 // Cross-axis drift-detection pin: a future collapse of two
7865 // canonical `ChildSpec` per-entry byte-strings onto the same
7866 // value (e.g. an accidental copy-paste flip of
7867 // `SUPERVISOR_CHILD_KEY_RESTART` to also read `"caixa"`) would
7868 // silently reroute every downstream probe on one axis onto the
7869 // sibling axis's overlay entry and pass every propagation-probe
7870 // test that expected only the stale axis's value. Peer of the
7871 // sibling three-way distinct pin on the `CONTRATO_KEY_*` triad
7872 // (ca463a4) and the two-way distinct pin on the `MEMBRO_KEY_*`
7873 // pair (ce80ca0).
7874 let all = [
7875 crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
7876 crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
7877 crate::render::SUPERVISOR_CHILD_KEY_RESTART,
7878 ];
7879 for (i, a) in all.iter().enumerate() {
7880 for b in all.iter().skip(i + 1) {
7881 assert_ne!(
7882 a, b,
7883 "SUPERVISOR_CHILD_KEY_* consts must be pairwise-\
7884 distinct canonical byte-sequences — got `{a}` == `{b}`",
7885 );
7886 }
7887 }
7888 }
7889
7890 #[test]
7891 fn supervisor_child_key_consts_are_lower_camel_case_shape() {
7892 // Shape-pin: every `SUPERVISOR_CHILD_KEY_*` const must be a
7893 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
7894 // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
7895 // capital, no whitespace / dots) — the canonical shape the
7896 // `#[serde(rename_all = "camelCase")]` derive produces on
7897 // `ChildSpec`. A future flip to a non-camelCase attribute at the
7898 // derive surfaces both here (this test fails on the
7899 // stale-constant shape) and at
7900 // `child_spec_serde_keys_match_lifted_supervisor_child_key_consts`
7901 // (that test fails on the mismatch between const and derive).
7902 // Peer with `supervisor_key_consts_are_lower_camel_case_shape`
7903 // (40cc4e5) on the sibling `SupervisorSpec` top-level axis.
7904 for key in [
7905 crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
7906 crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
7907 crate::render::SUPERVISOR_CHILD_KEY_RESTART,
7908 ] {
7909 assert!(
7910 !key.is_empty(),
7911 "SUPERVISOR_CHILD_KEY_* must be non-empty (got {key:?})"
7912 );
7913 let first = key.chars().next().unwrap();
7914 assert!(
7915 first.is_ascii_lowercase(),
7916 "SUPERVISOR_CHILD_KEY_* must lead with an ASCII-lowercase \
7917 byte (got {key:?}, leads with {first:?})",
7918 );
7919 assert!(
7920 key.chars().all(|c| c.is_ascii_alphanumeric()),
7921 "SUPERVISOR_CHILD_KEY_* must be ASCII-alphanumeric only \
7922 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
7923 );
7924 }
7925 }
7926
7927 // ── drift-detection: serde-derive-to-SUPERVISOR_ESTRATEGIA_* identity ────
7928
7929 #[test]
7930 fn restart_strategy_variants_serialize_to_lifted_scalar_values() {
7931 // The fail-before-pass-after pin: pre-lift there was no
7932 // single-source binding between the [`RestartStrategy`] variant
7933 // name the un-`rename`d `Serialize` derive emits under
7934 // [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the byte-string
7935 // every downstream cluster-side dispatcher (the future
7936 // wasm-operator's per-supervisor sibling-restart branch, the
7937 // future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
7938 // admission-time enum-arm bind, the `caixa-operator`'s
7939 // hierarchical reconciliation scheduler's per-strategy fan-out)
7940 // probes verbatim. A future `#[serde(rename_all = "kebab-case")]`
7941 // attribute on the enum — or a per-variant `#[serde(rename = "…")]`
7942 // override, or a variant rename in the source — would silently
7943 // rebrand the emitted scalar under one spelling while every
7944 // downstream dispatcher still probed the other, with the failure
7945 // surfacing at the operator's reconcile posture (subtrees coming
7946 // up under the `default()` `OneForOne` arm rather than the typed
7947 // slot's declared strategy — a bad child would then only take
7948 // itself down instead of the sibling set the author intended, so
7949 // shared-state children fall out of sync) far from the source
7950 // rebrand commit and with no field naming the drift. Pinning the
7951 // two paths (the `Serialize` derive's serialized string AND the
7952 // [`RestartStrategy::as_str`] helper) to the same four lifted
7953 // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
7954 // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
7955 // [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
7956 // [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
7957 // byte-strings makes any future drift on either endpoint fail
7958 // here at caixa-core build time. Peer of the M3
7959 // `placement_strategy_variants_serialize_to_lifted_scalar_values`
7960 // (3f0e21c) on the sibling `PlacementStrategy` axis — same
7961 // three-path-convergence discipline, extended to close the
7962 // OTP-shaped per-supervisor sibling-restart axis.
7963 for (variant, expected) in [
7964 (
7965 RestartStrategy::OneForOne,
7966 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
7967 ),
7968 (
7969 RestartStrategy::OneForAll,
7970 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
7971 ),
7972 (
7973 RestartStrategy::RestForOne,
7974 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
7975 ),
7976 (
7977 RestartStrategy::SimpleOneForOne,
7978 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
7979 ),
7980 ] {
7981 let json = serde_json::to_string(&variant).unwrap();
7982 assert_eq!(
7983 json,
7984 format!("\"{expected}\""),
7985 "RestartStrategy::{variant:?} must serialize to {expected:?}"
7986 );
7987 assert_eq!(
7988 variant.as_str(),
7989 expected,
7990 "RestartStrategy::{variant:?}.as_str() must return the lifted \
7991 SUPERVISOR_ESTRATEGIA_* constant"
7992 );
7993 }
7994 }
7995
7996 #[test]
7997 fn supervisor_estrategia_consts_are_pairwise_distinct() {
7998 // Cross-arm drift-detection pin: a future collapse of two
7999 // canonical variant byte-strings onto the same value (e.g. an
8000 // accidental copy-paste flip of `SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`
8001 // to also read `"OneForOne"`) would silently reroute every
8002 // downstream operator's per-strategy dispatch onto the sibling
8003 // arm's reconcile branch and pass every propagation-probe test
8004 // that expected only the stale arm's value — the mis-strategied
8005 // subtree would come up with the wrong sibling-restart posture
8006 // on every subsequent failure. Peer of the sibling four-way
8007 // distinct pin `supervisor_key_consts_are_pairwise_distinct`
8008 // (40cc4e5) on the top-level `SUPERVISOR_KEY_*` axis.
8009 let all = [
8010 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8011 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8012 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8013 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8014 ];
8015 for (i, a) in all.iter().enumerate() {
8016 for (j, b) in all.iter().enumerate() {
8017 if i != j {
8018 assert_ne!(
8019 a, b,
8020 "SUPERVISOR_ESTRATEGIA_* consts must be pairwise distinct \
8021 — got duplicate {a:?} at indices {i} and {j}",
8022 );
8023 }
8024 }
8025 }
8026 }
8027
8028 #[test]
8029 fn restart_strategy_display_routes_through_as_str_helper() {
8030 // The fail-before-pass-after pin on the first half of the
8031 // three-path convergence: pre-convergence the sibling
8032 // OTP-shape typed enum [`RestartStrategy`] carried a
8033 // [`std::fmt::Display`] surface via its
8034 // `#[discriminant(also_display)]` gen-platform derive route,
8035 // which arrived kebab-case as `"one-for-one"` /
8036 // `"one-for-all"` / `"rest-for-one"` /
8037 // `"simple-one-for-one"` while the wire format ran as
8038 // PascalCase `"OneForOne"` / `"OneForAll"` / `"RestForOne"` /
8039 // `"SimpleOneForOne"` through the un-`rename`d serde derive.
8040 // Every consumer reaching for a strategy byte-string past the
8041 // wire format had to pick between three paths
8042 // ([`RestartStrategy::as_str`], the `Serialize` derive's
8043 // serialized string, or `format!("{v}")` on the
8044 // discriminant-Display route), any two of which a future
8045 // variant rename or `#[serde(rename_all = "kebab-case")]`
8046 // attribute would silently desynchronize. Wiring
8047 // [`std::fmt::Display`] through [`RestartStrategy::as_str`]
8048 // closes the third path: every `format!("{v}")` call reaches
8049 // the same lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
8050 // const the wire format and the [`RestartStrategy::as_str`]
8051 // helper already route through, so a future variant rename
8052 // lands at exactly one place. Pin the routing here so a future
8053 // `impl std::fmt::Display for RestartStrategy`
8054 // reimplementation that hand-rolls the arms instead of
8055 // delegating to [`RestartStrategy::as_str`] fails at
8056 // caixa-core build time. Peer of the M3
8057 // `placement_strategy_display_routes_through_as_str_helper`
8058 // (cc8f749) which the M3 axis converged first.
8059 for &variant in RestartStrategy::ALL {
8060 assert_eq!(
8061 variant.to_string(),
8062 variant.as_str(),
8063 "RestartStrategy::{variant:?} Display must route through \
8064 RestartStrategy::as_str (single source of truth: the lifted \
8065 SUPERVISOR_ESTRATEGIA_* const the wire format also emits)"
8066 );
8067 }
8068 }
8069
8070 #[test]
8071 fn restart_strategy_display_matches_serialized_wire_byte_string() {
8072 // The fail-before-pass-after pin on the second half of the
8073 // three-path convergence: `Display` (user-facing text) agrees
8074 // byte-for-byte with the `Serialize` derive's wire format
8075 // (canonical camelCase-schema `SUPERVISOR_KEY_ESTRATEGIA`
8076 // scalar) on every variant. Pre-convergence the two paths
8077 // were structurally independent — a future
8078 // `#[serde(rename_all = "kebab-case")]` attribute on the
8079 // enum would silently rebrand the emitted wire scalar
8080 // (`one-for-one`, `one-for-all`, `rest-for-one`,
8081 // `simple-one-for-one`) while every consumer that
8082 // pretty-prints the strategy (the future wasm-operator's
8083 // per-supervisor sibling-restart-strategy diagnostic line,
8084 // the future `feira app graph` per-supervisor strategy line,
8085 // the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
8086 // materializer's admission-webhook rejection body) would
8087 // still emit the PascalCase form the `as_str` / `Display`
8088 // route returns, with the mismatch surfacing at consumer
8089 // parse time / operator dispatch time far from the source
8090 // rebrand commit. Pin the two paths byte-for-byte here so any
8091 // future serde-attribute or variant-rename drift is a
8092 // caixa-core-build-time test failure at this call, not a
8093 // silent per-consumer dispatch miss. Peer of the M3
8094 // `placement_strategy_display_matches_serialized_wire_byte_string`
8095 // (cc8f749) which the M3 axis converged first.
8096 for &variant in RestartStrategy::ALL {
8097 let wire = serde_json::to_string(&variant).unwrap();
8098 let unquoted = wire
8099 .strip_prefix('"')
8100 .and_then(|s| s.strip_suffix('"'))
8101 .expect("serialized RestartStrategy is a JSON string");
8102 assert_eq!(
8103 variant.to_string(),
8104 unquoted,
8105 "RestartStrategy::{variant:?} Display byte-string must match the \
8106 Serialize derive's wire byte-string (three-path convergence: \
8107 Display + as_str + Serialize all resolve to the same \
8108 SUPERVISOR_ESTRATEGIA_* const)"
8109 );
8110 }
8111 }
8112
8113 #[test]
8114 fn restart_strategy_as_ref_str_routes_through_as_str_accessor() {
8115 // Fail-before-pass-after byte-parity pin on the lifted
8116 // `impl AsRef<str> for RestartStrategy` — asserts the
8117 // standard-library trait impl and the substrate-primitive
8118 // [`RestartStrategy::as_str`] `pub const fn` accessor resolve
8119 // to the same `&str` per instance across the four-arm
8120 // closed set, so any future silent detour that routes the
8121 // impl through a divergent projection (a per-arm inline
8122 // `match self { RestartStrategy::OneForOne => "OneForOne", … }`
8123 // re-inlining that opens a compile-time link to the un-lifted
8124 // arm-literal, a swap onto the kebab-case
8125 // [`gen_platform::Discriminant`] catalog identity that would
8126 // collide the wire axis with the dispatcher-catalog axis) trips
8127 // at caixa-core test time under `PartialEq` rather than at a
8128 // downstream `impl AsRef<str>`-bound consumer's silent split.
8129 // Sweeps every one of the four arms
8130 // [`RestartStrategy::ALL`] carries so no arm's projection is
8131 // covered only by the sibling wire-format `Serialize` derive
8132 // path. Peer of the sibling
8133 // [`crate::version::tests::caixa_version_as_ref_str_routes_through_as_str_accessor`]
8134 // (16d5c7e) `AsRef<str>`-byte-parity pin on the paired
8135 // top-level `:versao` typed newtype — the two pins together
8136 // cover the substrate primitive's `AsRef<str>` projection axis
8137 // on the paired newtype + closed-set-typed-enum surface.
8138 for &variant in RestartStrategy::ALL {
8139 assert_eq!(
8140 <RestartStrategy as AsRef<str>>::as_ref(&variant),
8141 variant.as_str(),
8142 "AsRef<str> impl on RestartStrategy::{variant:?} must \
8143 byte-equal RestartStrategy::as_str on the same instance \
8144 — divergence signals a silent detour off the substrate-\
8145 primitive accessor"
8146 );
8147 }
8148 }
8149
8150 #[test]
8151 fn restart_strategy_as_ref_str_routes_through_display_via_shared_accessor() {
8152 // Fail-before-pass-after byte-parity pin on the three-path
8153 // convergence discipline the M2 sibling-restart primitive now
8154 // carries on the `&str`-projection axis:
8155 // `<RestartStrategy as AsRef<str>>::as_ref(&s)` (the newly
8156 // lifted impl), `format!("{s}")` (the pre-existing
8157 // [`fmt::Display`] impl), and `s.as_str()` (the substrate-
8158 // primitive `pub const fn` accessor both trait impls delegate
8159 // through) must resolve to the same byte-string on every
8160 // instance across the four-arm closed set. Refuses any future
8161 // divergence between the two trait impls (a stray
8162 // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
8163 // rather than delegating through the shared accessor; a
8164 // hypothetical `AsRef<str>` rewrite that inlines a per-arm
8165 // literal cascade) that would silently split the two
8166 // projection paths of the same closed-set typed enum. Mirrors
8167 // the sibling three-path-convergence discipline the peer
8168 // [`crate::CaixaVersion`] typed newtype carries on its
8169 // `AsRef<str>` / `Display` / `as_str` triple
8170 // (version.rs pin
8171 // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
8172 // 16d5c7e).
8173 for &variant in RestartStrategy::ALL {
8174 let via_as_ref: &str = <RestartStrategy as AsRef<str>>::as_ref(&variant);
8175 let via_display: String = format!("{variant}");
8176 let via_accessor: &str = variant.as_str();
8177 assert_eq!(via_as_ref, via_accessor);
8178 assert_eq!(via_display, via_accessor);
8179 assert_eq!(via_as_ref, via_display.as_str());
8180 }
8181 }
8182
8183 #[test]
8184 fn restart_strategy_all_enumerates_every_variant_exactly_once() {
8185 // Fail-before-pass-after pin on the [`RestartStrategy::ALL`]
8186 // exhaustive-iteration surface: every variant appears exactly
8187 // once, and the slice length matches the arm count of the
8188 // closed set. Every consumer that walks the accepted-strategy
8189 // set (a future `feira supervisor --estrategia …` CLI-side
8190 // arg-parse's "did you mean" hint, a future M4 admission-
8191 // webhook's rejection body naming the accepted-`:estrategia`
8192 // list, the [`RestartStrategy::from_wire`] reverse-projection
8193 // consumers that iterate the accept-set for diagnostic
8194 // rendering) reads through this slice, so a future arm addition
8195 // that grows the enum but forgets to grow [`Self::ALL`]
8196 // silently truncates every downstream consumer's accept-set at
8197 // the same pre-addition boundary — this pin fails at caixa-core
8198 // build time on the pairwise-distinct + arm-count invariants.
8199 //
8200 // Peer of the sibling [`crate::CaixaKind::ALL`] (6b1f4fb) /
8201 // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
8202 // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
8203 // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
8204 // pins on the peer closed-set typed-enum axes.
8205 let all: &[RestartStrategy] = RestartStrategy::ALL;
8206 assert_eq!(
8207 all.len(),
8208 4,
8209 "RestartStrategy::ALL must enumerate every variant of the \
8210 four-arm closed set (OneForOne, OneForAll, RestForOne, \
8211 SimpleOneForOne); got {all:?}"
8212 );
8213 for (i, a) in all.iter().enumerate() {
8214 for (j, b) in all.iter().enumerate() {
8215 if i != j {
8216 assert_ne!(
8217 a, b,
8218 "RestartStrategy::ALL must carry every variant exactly \
8219 once — got duplicate {a:?} at indices {i} and {j}"
8220 );
8221 }
8222 }
8223 }
8224 for variant in [
8225 RestartStrategy::OneForOne,
8226 RestartStrategy::OneForAll,
8227 RestartStrategy::RestForOne,
8228 RestartStrategy::SimpleOneForOne,
8229 ] {
8230 assert!(
8231 all.contains(&variant),
8232 "RestartStrategy::ALL must contain {variant:?} — a future arm \
8233 addition that grows the enum but forgets to grow the ALL slice \
8234 silently truncates every downstream consumer's accept-set at \
8235 the pre-addition boundary"
8236 );
8237 }
8238 }
8239
8240 #[test]
8241 fn restart_strategy_wire_names_covers_every_arm() {
8242 // Load-bearing pin on the substrate-canonical
8243 // [`RestartStrategy::WIRE_NAMES`] exhaustive accept-set roster
8244 // on the `PascalCase` wire byte-string axis: every variant of
8245 // the sibling [`RestartStrategy::ALL`] exhaustive-iteration
8246 // surface must project through [`RestartStrategy::as_str`] onto
8247 // an entry the [`RestartStrategy::WIRE_NAMES`] roster carries,
8248 // and the roster's length must byte-equal
8249 // `RestartStrategy::ALL.len()` so a silent skew between the
8250 // [`RestartStrategy::as_str`] match's arm-set and the roster's
8251 // arm-set trips here at caixa-core test time rather than at a
8252 // downstream M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
8253 // admission-webhook rejection body's wire-form `:estrategia`
8254 // accepted-set enumeration miss / a `feira supervisor
8255 // --estrategia …` "did you mean" hint drift / a future
8256 // wasm-operator per-reconcile-step diagnostic log line's
8257 // accepted-wire-form enumeration miss. A future arm addition
8258 // (an OTP-`rest_for_all` arm the theory
8259 // [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
8260 // might reach for once the four canonical OTP strategies stop
8261 // covering the substrate's discovered load-shape) extends
8262 // [`RestartStrategy::ALL`] as a single edit and this pin
8263 // sweeps the new arm by iteration; the paired
8264 // [`RestartStrategy::WIRE_NAMES`] roster must grow in lockstep
8265 // or this assertion trips. Every entry is further pinned to
8266 // open with an ASCII uppercase byte so a silent collapse of
8267 // the wire-form axis with the peer kebab-case
8268 // dispatcher-catalog axis (an entry byte-identical to a
8269 // sibling [`Self::discriminant`] kebab byte-string that would
8270 // let a wire-axis consumer accept the dispatcher-catalog
8271 // vocabulary) trips here rather than at a downstream K8s-CR
8272 // round-trip miss.
8273 //
8274 // Peer of the sibling
8275 // [`crate::kind::tests::caixa_kind_wire_names_covers_every_arm`]
8276 // (bd708bd) pin on the top-level typed-kind discriminator's
8277 // `PascalCase` wire byte-string axis, and of the sibling
8278 // [`crate::upgrade::tests::upgrade_instruction_wire_forms_covers_every_arm`]
8279 // (cc42c0e) /
8280 // [`crate::upgrade::tests::upgrade_instruction_lisp_forms_covers_every_arm`]
8281 // (1898d77) pins on the OTP-appup discriminator's two-axis
8282 // roster split — the same closed-set exhaustive-roster
8283 // coverage discipline extended here onto the first M2
8284 // OTP-shape sibling-restart closed-set typed enum.
8285 //
8286 // Fail-before-pass-after locally verified by mutating one arm
8287 // of the paired [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
8288 // const family (e.g. dropping the trailing `e` from
8289 // `"OneForOne"` → `"OneForOn"`) — the length pin still passes
8290 // but the `contains` check fires on the mutated arm; and by
8291 // shortening the roster to three entries — the length pin
8292 // fires first.
8293 assert_eq!(
8294 RestartStrategy::WIRE_NAMES.len(),
8295 RestartStrategy::ALL.len(),
8296 "RestartStrategy::WIRE_NAMES.len() must byte-equal \
8297 RestartStrategy::ALL.len() — a mismatch means the roster \
8298 and the enum's arm-set have drifted; downstream consumers \
8299 that fan through both will silently disagree on the \
8300 accepted arm-set"
8301 );
8302 for &variant in RestartStrategy::ALL {
8303 let wire = variant.as_str();
8304 assert!(
8305 RestartStrategy::WIRE_NAMES.contains(&wire),
8306 "RestartStrategy::{variant:?}.as_str() = {wire:?} must \
8307 be a member of RestartStrategy::WIRE_NAMES — the \
8308 emitter and the roster have drifted out of lockstep"
8309 );
8310 }
8311 for tag in RestartStrategy::WIRE_NAMES {
8312 let first = tag.chars().next().unwrap_or_else(|| {
8313 panic!(
8314 "RestartStrategy::WIRE_NAMES entry {tag:?} must be \
8315 a non-empty PascalCase byte-string"
8316 )
8317 });
8318 assert!(
8319 first.is_ascii_uppercase(),
8320 "RestartStrategy::WIRE_NAMES entry {tag:?} must open \
8321 with an ASCII uppercase byte (PascalCase wire form) — \
8322 a lowercase entry would collide the wire-form axis \
8323 with the peer kebab-case dispatcher-catalog axis \
8324 [`RestartStrategy::discriminant`] serves"
8325 );
8326 }
8327 }
8328
8329 #[test]
8330 fn restart_strategy_from_wire_accepts_every_lifted_constant() {
8331 // Fail-before-pass-after pin on the forward accept-set of the
8332 // [`RestartStrategy::from_wire`] reverse projection: every
8333 // canonical [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
8334 // constant the [`RestartStrategy::as_str`] emitter walks parses
8335 // back to its paired variant. Any future arm addition that
8336 // grows the emitter's `as_str` match but forgets to grow the
8337 // parser's `from_wire` match silently splits the two halves of
8338 // the round-trip — the wire byte-string one non-serde consumer
8339 // parses from the one the emitter wrote — with the failure
8340 // surfacing at parse time far from the rebrand commit. Pinning
8341 // the four-arm accept-set here catches the drift at caixa-core
8342 // build time.
8343 //
8344 // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
8345 // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
8346 // accept-set pins on the peer closed-set typed-enum `str → Self`
8347 // axes.
8348 for (wire, expected) in [
8349 (
8350 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8351 RestartStrategy::OneForOne,
8352 ),
8353 (
8354 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8355 RestartStrategy::OneForAll,
8356 ),
8357 (
8358 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8359 RestartStrategy::RestForOne,
8360 ),
8361 (
8362 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8363 RestartStrategy::SimpleOneForOne,
8364 ),
8365 ] {
8366 let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
8367 panic!(
8368 "RestartStrategy::from_wire({wire:?}) must accept every \
8369 SUPERVISOR_ESTRATEGIA_* constant — got None for the \
8370 lifted canonical byte-string that RestartStrategy::{expected:?} \
8371 serializes as under SUPERVISOR_KEY_ESTRATEGIA"
8372 )
8373 });
8374 assert_eq!(
8375 parsed, expected,
8376 "RestartStrategy::from_wire({wire:?}) must return \
8377 RestartStrategy::{expected:?}; got RestartStrategy::{parsed:?}"
8378 );
8379 }
8380 }
8381
8382 #[test]
8383 fn restart_strategy_from_wire_round_trips_through_as_str() {
8384 // Fail-before-pass-after pin on the closed round-trip between
8385 // the forward [`RestartStrategy::as_str`] emitter and the
8386 // reverse [`RestartStrategy::from_wire`] parser: for every
8387 // variant in [`RestartStrategy::ALL`], parsing the emitter's
8388 // output must return exactly the same variant. Any per-arm
8389 // divergence — a future arm added to `as_str` but not
8390 // `from_wire`, an accidental copy-paste flip in one but not
8391 // the other — silently splits the emit and parse halves and
8392 // the failure surfaces at consumer parse time far from the
8393 // drift site. The `ALL`-iterating shape means a future arm
8394 // addition picks up the coverage by construction.
8395 //
8396 // Peer of the sibling
8397 // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
8398 // (18c7342) round-trip pin on
8399 // [`crate::aplicacao::PlacementStrategy::from_wire`] and
8400 // [`crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`]
8401 // (6b1f4fb) round-trip pin on [`crate::CaixaKind::from_wire`].
8402 for &variant in RestartStrategy::ALL {
8403 let wire = variant.as_str();
8404 let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
8405 panic!(
8406 "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
8407 must be Some({variant:?}) — the two halves of the round-trip \
8408 dispatch on the same lifted SUPERVISOR_ESTRATEGIA_* consts; \
8409 got None on wire byte-string {wire:?}"
8410 )
8411 });
8412 assert_eq!(
8413 parsed, variant,
8414 "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
8415 must round-trip to the same variant; got {parsed:?}"
8416 );
8417 }
8418 }
8419
8420 #[test]
8421 fn restart_strategy_from_wire_rejects_unknown_byte_strings() {
8422 // Fail-before-pass-after pin on the closed-set refusal
8423 // discipline of [`RestartStrategy::from_wire`]: every
8424 // byte-string outside the four-arm accept-set returns `None`
8425 // rather than silently collapsing onto the [`Default`]
8426 // (`OneForOne`) arm or an arbitrary neighbor. The refusal set
8427 // exercised here sweeps the load-bearing drift shapes: the
8428 // empty string (a stripped serde-attribute drift), all-
8429 // whitespace strings (the canonical text-editor accidental
8430 // padding shape), the kebab-case dispatcher-catalog identities
8431 // (`"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
8432 // `"simple-one-for-one"` — the [`gen_platform::FromStrKind`]-
8433 // derived [`std::str::FromStr`] accept-set, which parses the
8434 // *other* axis of this enum's two-axis split and must not leak
8435 // into the `from_wire` PascalCase-wire accept-set), the
8436 // lowercased single-word forms (`"oneforone"`), the padded
8437 // canonical scalar (`" OneForOne "`), the trailing-newline
8438 // shapes (`"OneForOne\n"`), and neighboring-but-unknown arms
8439 // (`"AllForOne"` — the canonical typo direction).
8440 //
8441 // Peer of the sibling
8442 // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
8443 // (2aa6d23) +
8444 // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
8445 // (18c7342) refusal pins on the peer closed-set typed-enum
8446 // axes.
8447 for bad in [
8448 "",
8449 " ",
8450 "\n",
8451 "\t",
8452 "one-for-one",
8453 "one-for-all",
8454 "rest-for-one",
8455 "simple-one-for-one",
8456 "oneforone",
8457 "OneForOnes",
8458 "one_for_one",
8459 "one for one",
8460 "ONEFORONE",
8461 "OneForOne ",
8462 " OneForOne",
8463 " SimpleOneForOne ",
8464 "OneForOne\n",
8465 "restforone",
8466 "REST_FOR_ONE",
8467 "AllForOne",
8468 "Simple",
8469 "?",
8470 ] {
8471 assert!(
8472 RestartStrategy::from_wire(bad).is_none(),
8473 "RestartStrategy::from_wire({bad:?}) must return None — the \
8474 parser's accept-set is exactly the four RestartStrategy::as_str \
8475 outputs (OneForOne, OneForAll, RestForOne, SimpleOneForOne), \
8476 and this byte-string is outside that closed set"
8477 );
8478 }
8479 }
8480
8481 #[test]
8482 fn restart_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
8483 // Fail-before-pass-after pin on the fourth path of the four-path
8484 // convergence: `from_wire` (the reverse projection) inverts the
8485 // `Serialize` derive's wire byte-string on every variant.
8486 // Together with the pre-existing three-path convergence
8487 // (`Display` + `as_str` + `Serialize` all resolve to the same
8488 // lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const,
8489 // pinned by
8490 // [`restart_strategy_display_matches_serialized_wire_byte_string`])
8491 // this closes the round-trip: the wire byte-string the
8492 // `Serialize` derive emits parses back to the same variant
8493 // through `from_wire`, so any future serde-attribute or variant-
8494 // rename drift on the emit half now surfaces as a matched drift
8495 // on the parse half at caixa-core build time — the two halves
8496 // migrate as a unit through the lifted consts on any future
8497 // rename, and the round-trip cannot silently split.
8498 //
8499 // Peer of the sibling
8500 // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
8501 // (18c7342) wire-format pin on
8502 // [`crate::aplicacao::PlacementStrategy::from_wire`].
8503 for &variant in RestartStrategy::ALL {
8504 let wire = serde_json::to_string(&variant).unwrap();
8505 let unquoted = wire
8506 .strip_prefix('"')
8507 .and_then(|s| s.strip_suffix('"'))
8508 .expect("serialized RestartStrategy is a JSON string");
8509 let parsed = RestartStrategy::from_wire(unquoted).unwrap_or_else(|| {
8510 panic!(
8511 "RestartStrategy::from_wire({unquoted:?}) must accept the \
8512 Serialize derive's wire byte-string for \
8513 RestartStrategy::{variant:?} — the four-path convergence \
8514 (Display + as_str + Serialize + from_wire) resolves through \
8515 the same lifted SUPERVISOR_ESTRATEGIA_* const; got None"
8516 )
8517 });
8518 assert_eq!(
8519 parsed, variant,
8520 "RestartStrategy::from_wire of the Serialize derive's wire \
8521 byte-string for RestartStrategy::{variant:?} must round-trip \
8522 to the same variant; got {parsed:?}"
8523 );
8524 }
8525 }
8526
8527 #[test]
8528 fn restart_strategy_try_from_str_routes_through_from_wire_accessor() {
8529 // Fail-before-pass-after byte-parity pin on the newly lifted
8530 // `impl TryFrom<&str> for RestartStrategy` — asserts the standard-
8531 // library trait impl and the substrate-primitive
8532 // [`RestartStrategy::from_wire`] `Option<Self>` accessor resolve to
8533 // the same four-arm accept-set across every arm the exhaustive
8534 // [`RestartStrategy::ALL`] slice enumerates. Any future silent
8535 // detour that routes the trait impl through a divergent projection
8536 // (a per-arm inline `match s { "OneForOne" => Ok(Self::OneForOne),
8537 // … }` re-inlining that opens a compile-time link to the un-
8538 // lifted arm-literal, a hypothetical `#[serde(rename_all = "…")]`
8539 // attribute drift that silently splits the wire byte-string from
8540 // every consumer that reaches for this typed dispatch, an
8541 // accidental swap onto the kebab-case dispatcher-catalog axis the
8542 // pre-existing [`std::str::FromStr`] impl parses through and which
8543 // would collide the two-axis wire/catalog split the sibling
8544 // [`RestartStrategy::from_wire`] doc block makes load-bearing)
8545 // trips at caixa-core test time under `assert_eq!` rather than at
8546 // a downstream `impl TryFrom<&str>`-bound consumer's silent split.
8547 // Sweeps every one of the four arms [`RestartStrategy::ALL`]
8548 // carries so no arm's projection is covered only by the sibling
8549 // method-named `from_wire` path. Peer of the sibling
8550 // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
8551 // (3c83606),
8552 // [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
8553 // (bf33136), and the M3
8554 // [`crate::aplicacao::tests::placement_strategy_try_from_str_routes_through_from_wire_accessor`]
8555 // (6fd00cd) — extends the trait-idiomatic reverse-projection axis
8556 // onto the first M2-OTP-shape closed-set typed enum on the caixa
8557 // surface.
8558 for &variant in RestartStrategy::ALL {
8559 let wire = variant.as_str();
8560 assert_eq!(
8561 <RestartStrategy as TryFrom<&str>>::try_from(wire),
8562 Ok(variant),
8563 "TryFrom<&str> impl on RestartStrategy must round-trip \
8564 RestartStrategy::{variant:?}.as_str() = {wire:?} back to \
8565 Ok(RestartStrategy::{variant:?}) — divergence from \
8566 RestartStrategy::from_wire signals a silent detour off \
8567 the substrate-primitive accessor"
8568 );
8569 assert_eq!(
8570 <RestartStrategy as TryFrom<&str>>::try_from(wire).ok(),
8571 RestartStrategy::from_wire(wire),
8572 "TryFrom<&str> ok()-projection on {wire:?} must byte-equal \
8573 RestartStrategy::from_wire on the same input"
8574 );
8575 }
8576 }
8577
8578 #[test]
8579 fn restart_strategy_try_from_str_rejects_unknown_byte_strings() {
8580 // Rejection witness on the `impl TryFrom<&str> for
8581 // RestartStrategy` — sweeps a candidate set of byte-strings
8582 // outside the four-arm PascalCase wire accept-set the sibling
8583 // [`RestartStrategy::as_str`] emits and asserts every one lands on
8584 // `Err(())`, so a future accidental widening of the trait impl's
8585 // accept-set (a stray additional
8586 // `_ if s.eq_ignore_ascii_case("OneForOne") => Ok(…)` case-fold
8587 // path, a silent inclusion of the kebab-case dispatcher-catalog
8588 // byte-string the pre-existing [`std::str::FromStr`] impl the
8589 // [`gen_platform::FromStrKind`] derive installs parses onto the
8590 // wire axis — which would collide the two-axis
8591 // wire/dispatcher-catalog split the sibling
8592 // [`RestartStrategy::from_wire`] doc block makes load-bearing —
8593 // an English-rebrand or plural-arm silent alias that would
8594 // widen the wire accept-set past the OTP-canonical four) trips at
8595 // caixa-core test time. The candidate set includes the empty
8596 // string, whitespace-only padding, the kebab-case dispatcher-
8597 // catalog byte-strings on the sibling axis (a caller who confuses
8598 // the two axes trips here rather than at a downstream consumer's
8599 // silent reject), a lowercase / uppercase / mixed-case fold of
8600 // each PascalCase arm (a caller who assumes case-fold acceptance
8601 // trips here), leading/trailing whitespace padding, the trailing-
8602 // newline shape, quote-wrapped candidates, and a residual set of
8603 // plausible-but-wrong English rebrand candidates. Peer of the
8604 // sibling
8605 // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
8606 // (3c83606) and
8607 // [`crate::aplicacao::tests::placement_strategy_try_from_str_rejects_unknown_byte_strings`]
8608 // (6fd00cd) rejection witnesses.
8609 let rejected: &[&str] = &[
8610 "",
8611 " ",
8612 "\n",
8613 "\t",
8614 "one-for-one",
8615 "one-for-all",
8616 "rest-for-one",
8617 "simple-one-for-one",
8618 "oneforone",
8619 "one_for_one",
8620 "OneForOnes",
8621 "ONEFORONE",
8622 "oneforall",
8623 "restforone",
8624 "simpleoneforone",
8625 "OneForOne ",
8626 " OneForOne",
8627 " OneForAll ",
8628 "OneForOne\n",
8629 "RestForOne\t",
8630 "OneForEach",
8631 "AllForOne",
8632 "one for one",
8633 "\"OneForOne\"",
8634 "?",
8635 ];
8636 for &input in rejected {
8637 assert_eq!(
8638 <RestartStrategy as TryFrom<&str>>::try_from(input),
8639 Err(()),
8640 "TryFrom<&str> impl on RestartStrategy must reject the \
8641 non-wire byte-string {input:?} — silent acceptance signals \
8642 an accept-set widening off the paired \
8643 RestartStrategy::from_wire resolver"
8644 );
8645 }
8646 }
8647
8648 #[test]
8649 fn restart_strategy_try_from_str_and_from_wire_partition_the_accept_set() {
8650 // Cross-axis partition pin: the paired `TryFrom<&str>` and
8651 // `from_wire` reverse projections must resolve identically on
8652 // *every* input, not just the ones [`RestartStrategy::ALL`]
8653 // enumerates. Sweeps a mixed candidate set spanning accepted
8654 // (four-arm PascalCase wire byte-strings) and rejected (kebab-case
8655 // dispatcher-catalog byte-strings, empty, whitespace-padded,
8656 // quoted, English-rebrand candidates) inputs and asserts the
8657 // trait's `Result::ok()` projection byte-equals the method-named
8658 // resolver's `Option<Self>` return-shape on each, locking the two
8659 // paths together by construction so any future detour (a stray
8660 // `try_from` special-case that widens or narrows the accept-set
8661 // outside the paired `from_wire` resolver, an accidental swap
8662 // onto the kebab-case [`std::str::FromStr`] impl the
8663 // [`gen_platform::FromStrKind`] derive installs on the sibling
8664 // dispatcher-catalog axis) trips at caixa-core test time. Peer of
8665 // the sibling
8666 // [`crate::kind::tests::caixa_kind_try_from_str_and_from_wire_partition_the_accept_set`]
8667 // pin — extends the round-trip discipline onto the M2-OTP-shape
8668 // sibling-restart axis.
8669 let candidates: &[&str] = &[
8670 "OneForOne",
8671 "OneForAll",
8672 "RestForOne",
8673 "SimpleOneForOne",
8674 "",
8675 "one-for-one",
8676 "one-for-all",
8677 "rest-for-one",
8678 "simple-one-for-one",
8679 "oneforone",
8680 "unknown",
8681 "OneForOne ",
8682 " OneForOne",
8683 "\"OneForOne\"",
8684 "OneForEach",
8685 "?",
8686 ];
8687 for &input in candidates {
8688 let via_trait: Option<RestartStrategy> =
8689 <RestartStrategy as TryFrom<&str>>::try_from(input).ok();
8690 let via_method: Option<RestartStrategy> = RestartStrategy::from_wire(input);
8691 assert_eq!(
8692 via_trait, via_method,
8693 "TryFrom<&str> and from_wire must resolve identically on \
8694 input {input:?} — divergence signals the two reverse-\
8695 projection paths have drifted onto different accept-sets"
8696 );
8697 }
8698 }
8699
8700 #[test]
8701 fn restart_strategy_from_into_static_str_routes_through_as_str_accessor() {
8702 // Fail-before-pass-after byte-parity pin on the newly lifted
8703 // `impl From<RestartStrategy> for &'static str` — asserts the
8704 // standard-library trait impl and the substrate-primitive
8705 // [`RestartStrategy::as_str`] `pub const fn` accessor resolve to
8706 // the same four-arm emit-set across every arm the exhaustive
8707 // [`RestartStrategy::ALL`] slice enumerates. Any future silent
8708 // detour that routes the trait impl through a divergent
8709 // projection (a per-arm inline `match strategy { OneForOne =>
8710 // "OneForOne", … }` re-inlining that opens a compile-time link to
8711 // the un-lifted arm-literal, an accidental swap onto the sibling
8712 // kebab-case [`Self::discriminant`] dispatcher-catalog axis that
8713 // would collide the two-axis wire/catalog split the sibling
8714 // [`RestartStrategy::from_wire`] doc block makes load-bearing) trips
8715 // at caixa-core test time under `assert_eq!` rather than at a
8716 // downstream `impl Into<&'static str>`-bound consumer's silent
8717 // split. Sweeps every one of the four arms
8718 // [`RestartStrategy::ALL`] carries so no arm's projection is
8719 // covered only by the sibling method-named `as_str` /
8720 // [`std::fmt::Display`] / [`AsRef<str>`] paths. Materializes the
8721 // `<&'static str as From<RestartStrategy>>::from` output in a
8722 // `const`-shape binding to make the `'static` lifetime promise a
8723 // build-time invariant — a future accidental downgrade of any of
8724 // the four arms' [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
8725 // constants to a non-`&'static str` (a `String::leak()`-produced
8726 // return, a `Box::leak`-cast) trips at caixa-core build time
8727 // rather than at a downstream `'static`-bound consumer.
8728 const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
8729 const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
8730 const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
8731 const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
8732 for &variant in RestartStrategy::ALL {
8733 let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8734 let via_method: &'static str = variant.as_str();
8735 assert_eq!(
8736 via_trait, via_method,
8737 "From<RestartStrategy> for &'static str impl must round-trip \
8738 RestartStrategy::{variant:?} to the same lifted \
8739 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str returns — \
8740 divergence signals a silent detour off the substrate-primitive \
8741 accessor"
8742 );
8743 let via_into: &'static str = variant.into();
8744 assert_eq!(
8745 via_into, via_method,
8746 "Into<&'static str>::into on RestartStrategy::{variant:?} must \
8747 byte-equal RestartStrategy::as_str on the same input — the \
8748 blanket-derived Into shape must resolve to the same as_str \
8749 dispatch as the explicit From impl"
8750 );
8751 }
8752 assert_eq!(
8753 [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
8754 [
8755 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8756 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8757 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8758 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8759 ],
8760 "const-context RestartStrategy::as_str must resolve to the four \
8761 lifted SUPERVISOR_ESTRATEGIA_* consts — a future accidental \
8762 downgrade of any arm to a non-const or non-static byte-string \
8763 breaks the `&'static str`-lifetime promise the paired \
8764 From<RestartStrategy> for &'static str impl carries by \
8765 construction"
8766 );
8767 }
8768
8769 #[test]
8770 fn restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set() {
8771 // Cross-axis partition pin: the paired trait-idiomatic
8772 // `From<RestartStrategy> for &'static str` forward projection and
8773 // the method-named [`RestartStrategy::as_str`] forward projection
8774 // must resolve identically on *every* arm, not just the ones
8775 // named in the primary byte-parity pin above. Sweeps every
8776 // [`RestartStrategy::ALL`] arm and asserts the trait's `From::from`
8777 // output byte-equals the method-named accessor's return-value on
8778 // each, locking the two forward-projection paths together by
8779 // construction so any future detour (a stray `From` special-case
8780 // that lands on a divergent per-arm literal outside the paired
8781 // `as_str` dispatch, a hypothetical rebrand touching one axis
8782 // without the other) trips at caixa-core test time. Peer of the
8783 // sibling reverse-projection partition pin
8784 // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
8785 // — extends the round-trip discipline onto the trait-idiomatic
8786 // *forward* axis, closing the two-way `Self ↔ &'static str`
8787 // round-trip on the trait-idiomatic pair
8788 // (`From<Self> for &'static str` + `TryFrom<&str> for Self`) as
8789 // well as the pre-existing method-named pair
8790 // (`as_str` + `from_wire`).
8791 for &variant in RestartStrategy::ALL {
8792 let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8793 let via_method: &'static str = variant.as_str();
8794 assert_eq!(
8795 via_trait, via_method,
8796 "From<RestartStrategy> for &'static str and \
8797 RestartStrategy::as_str must resolve identically on \
8798 RestartStrategy::{variant:?} — divergence signals the \
8799 two forward-projection paths have drifted onto different \
8800 emit-sets"
8801 );
8802 }
8803 // Round-trip witness: every arm's forward `From` output re-parses
8804 // through the paired trait-idiomatic reverse `TryFrom<&str>` back
8805 // to the original variant. Closes the two-way `RestartStrategy ↔
8806 // &'static str` round-trip on the trait-idiomatic axis pair,
8807 // mirroring the pre-existing method-named `as_str` + `from_wire`
8808 // round-trip on the substrate-primitive axis pair.
8809 for &variant in RestartStrategy::ALL {
8810 let emitted: &'static str = variant.into();
8811 let re_parsed: Result<RestartStrategy, ()> =
8812 <RestartStrategy as TryFrom<&str>>::try_from(emitted);
8813 assert_eq!(
8814 re_parsed,
8815 Ok(variant),
8816 "trait-idiomatic axis pair must round-trip \
8817 RestartStrategy::{variant:?} through `.into::<&'static \
8818 str>()` and back through `TryFrom<&str>` — a break signals \
8819 the forward-emit and reverse-parse axes have drifted onto \
8820 different vocabularies"
8821 );
8822 }
8823 }
8824
8825 #[test]
8826 fn restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
8827 // Fail-before-pass-after byte-parity pin on the newly lifted
8828 // `impl From<&RestartStrategy> for &'static str` — asserts the
8829 // borrowed-input standard-library trait impl and the substrate-
8830 // primitive [`RestartStrategy::as_str`] `pub const fn` accessor
8831 // resolve to the same four-arm emit-set across every arm the
8832 // exhaustive [`RestartStrategy::ALL`] slice enumerates. Rust's
8833 // `From` trait does not auto-derive the borrowed-input sibling
8834 // from a paired owned-input impl (no `impl<T, U> From<&T> for U
8835 // where T: Copy, U: From<T>` blanket in `core`), so the
8836 // borrowed-input axis is a distinct trait-idiomatic surface
8837 // that a `.iter().map(Into::into)` shape over
8838 // [`RestartStrategy::ALL`] (whose iterator yields
8839 // `&RestartStrategy`, not `RestartStrategy`) reaches through
8840 // this impl and no other — the paired owned-input
8841 // [`From<RestartStrategy>`] impl requires an explicit
8842 // `.copied()` / dereference before the trait fires.
8843 // Materializes the `<&'static str as
8844 // From<&RestartStrategy>>::from` output in a `const`-shape
8845 // binding to make the `'static` lifetime promise a build-time
8846 // invariant.
8847 const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
8848 const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
8849 const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
8850 const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
8851 for variant in RestartStrategy::ALL {
8852 let via_trait: &'static str = <&'static str as From<&RestartStrategy>>::from(variant);
8853 let via_method: &'static str = variant.as_str();
8854 assert_eq!(
8855 via_trait, via_method,
8856 "From<&RestartStrategy> for &'static str impl must \
8857 round-trip &RestartStrategy::{variant:?} to the same \
8858 lifted SUPERVISOR_ESTRATEGIA_* const \
8859 RestartStrategy::as_str returns — divergence signals a \
8860 silent detour off the substrate-primitive accessor"
8861 );
8862 let via_into: &'static str = variant.into();
8863 assert_eq!(
8864 via_into, via_method,
8865 "Into<&'static str>::into on &RestartStrategy::{variant:?} \
8866 must byte-equal RestartStrategy::as_str on the same input — \
8867 the blanket-derived Into shape must resolve to the same \
8868 as_str dispatch as the explicit From impl"
8869 );
8870 }
8871 assert_eq!(
8872 [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
8873 [
8874 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8875 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8876 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8877 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8878 ],
8879 "const-context RestartStrategy::as_str must resolve to the \
8880 four lifted SUPERVISOR_ESTRATEGIA_* consts — the borrowed-\
8881 input From<&RestartStrategy> for &'static str impl inherits \
8882 its `'static` lifetime promise from the same accessor the \
8883 owned-input sibling routes through"
8884 );
8885 }
8886
8887 #[test]
8888 fn restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
8889 // Cross-axis partition pin: the paired trait-idiomatic
8890 // owned-input `From<RestartStrategy> for &'static str` (523157d
8891 // campaign-shape) and borrowed-input `From<&RestartStrategy> for
8892 // &'static str` (this lift) forward projections must resolve
8893 // identically on every arm, locking the two input-shape paths
8894 // together so any future detour trips at caixa-core test time.
8895 // Then a witness that a `.iter().map(Into::into)` pipe over
8896 // [`RestartStrategy::ALL`] (whose iterator yields
8897 // `&RestartStrategy`) materializes the four-arm accept-set
8898 // through the borrowed-input axis alone — the exact shape a
8899 // future wasm-operator per-supervisor sibling-restart-strategy
8900 // diagnostic line, a future substrate-wide per-arm diagnostic
8901 // column, or a
8902 // `HashMap::<&'static str, RestartStrategy>::from_iter(
8903 // RestartStrategy::ALL.iter().map(|s| (s.into(), *s)))`-style
8904 // per-strategy lookup reaches through — closing the two-way
8905 // owned/borrowed input-shape symmetry on the forward-projection
8906 // trait-idiomatic axis. Peer of the sibling
8907 // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8908 // (64aa742) /
8909 // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8910 // (5ab993a) /
8911 // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
8912 // (807b0b5) partition pins on the sibling closed-set typed-enum
8913 // discriminator axes — extends the borrowed-input axis
8914 // discipline onto the first M2 OTP-shape sibling-restart
8915 // closed-set typed enum on the caixa surface. Also closes the
8916 // direct two-way `&Self → &'static str → Self` round-trip via
8917 // the paired [`TryFrom<&str>`] axis — unlike the peer
8918 // [`crate::CaixaKind`] axis pair (whose forward `From` emits
8919 // lowercase Portuguese diagnostic bytes while the reverse
8920 // `TryFrom` parses `PascalCase` wire bytes, forcing the round-
8921 // trip through an intermediate wire-vocab hop), the
8922 // [`RestartStrategy::as_str`] emit and
8923 // [`RestartStrategy::from_wire`] parse share the same
8924 // `PascalCase` vocabulary by construction, so the borrowed-
8925 // input forward axis and the reverse axis compose directly.
8926 for &variant in RestartStrategy::ALL {
8927 let owned: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8928 let borrowed: &'static str = <&'static str as From<&RestartStrategy>>::from(&variant);
8929 assert_eq!(
8930 owned, borrowed,
8931 "From<RestartStrategy> and From<&RestartStrategy> for \
8932 &'static str must resolve identically on \
8933 RestartStrategy::{variant:?} — divergence signals the \
8934 owned-input and borrowed-input forward-projection paths \
8935 have drifted onto different emit-sets"
8936 );
8937 }
8938 let via_iter: Vec<&'static str> = RestartStrategy::ALL.iter().map(Into::into).collect();
8939 let via_method: Vec<&'static str> =
8940 RestartStrategy::ALL.iter().map(|s| s.as_str()).collect();
8941 assert_eq!(
8942 via_iter, via_method,
8943 "`.iter().map(Into::into)` over RestartStrategy::ALL must \
8944 byte-equal `.iter().map(|s| s.as_str())` on every arm — the \
8945 borrowed-input `From<&RestartStrategy> for &'static str` \
8946 axis is what makes the `.iter().map(Into::into)` shape route \
8947 through the substrate-primitive `RestartStrategy::as_str` \
8948 accessor rather than through a per-call-site `.copied()` / \
8949 dereference detour"
8950 );
8951 for variant in RestartStrategy::ALL {
8952 let emitted: &'static str = variant.into();
8953 let re_parsed: Result<RestartStrategy, ()> =
8954 <RestartStrategy as TryFrom<&str>>::try_from(emitted);
8955 assert_eq!(
8956 re_parsed,
8957 Ok(*variant),
8958 "trait-idiomatic borrowed-input forward-projection + \
8959 reverse-projection axis pair must round-trip \
8960 &RestartStrategy::{variant:?} through `.into::<&'static \
8961 str>()` (via the borrowed-input axis) and back through \
8962 `TryFrom<&str>` — a break signals the borrowed-input \
8963 forward-emit and reverse-parse axes have drifted onto \
8964 different vocabularies"
8965 );
8966 }
8967 }
8968
8969 #[test]
8970 fn restart_strategy_from_into_owned_string_routes_through_as_str_accessor() {
8971 // Fail-before-pass-after byte-parity pin on the newly lifted
8972 // `impl From<RestartStrategy> for String` — asserts the
8973 // owned-`String`-returning standard-library trait impl and the
8974 // substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
8975 // accessor resolve to the same four-arm emit-set across every
8976 // arm the exhaustive [`RestartStrategy::ALL`] slice enumerates.
8977 // Rust's standard library does not carry a blanket
8978 // `impl<T: AsRef<str>> From<T> for String` (nor an
8979 // `impl<T: fmt::Display> From<T> for String`), so the
8980 // owned-`String` forward-projection axis is a distinct
8981 // trait-idiomatic surface that a
8982 // `let key: String = strategy.into();`-shaped call site
8983 // reaches through this impl and no other — the paired sibling
8984 // `From<RestartStrategy> for &'static str` impl forces every
8985 // owned-`String` call site through an explicit
8986 // `.to_owned()` / `String::from` restatement.
8987 for &variant in RestartStrategy::ALL {
8988 let via_trait: String = <String as From<RestartStrategy>>::from(variant);
8989 let via_method: &'static str = variant.as_str();
8990 assert_eq!(
8991 via_trait.as_str(),
8992 via_method,
8993 "From<RestartStrategy> for String impl must round-trip \
8994 RestartStrategy::{variant:?} to the same lifted \
8995 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
8996 returns — divergence signals a silent detour off the \
8997 substrate-primitive accessor"
8998 );
8999 let via_into: String = variant.into();
9000 assert_eq!(
9001 via_into.as_str(),
9002 via_method,
9003 "Into<String>::into on RestartStrategy::{variant:?} must \
9004 byte-equal RestartStrategy::as_str on the same input — the \
9005 blanket-derived Into shape must resolve to the same as_str \
9006 dispatch as the explicit From impl"
9007 );
9008 }
9009 }
9010
9011 #[test]
9012 fn restart_strategy_from_into_owned_string_and_static_str_agree_on_every_arm() {
9013 // Cross-axis partition pin: the paired trait-idiomatic
9014 // owned-`String` `From<RestartStrategy> for String` (this lift)
9015 // and owned-`&'static str` `From<RestartStrategy> for &'static
9016 // str` (523157d) forward projections must resolve identically
9017 // on every arm, locking the two return-type-shape paths
9018 // together so any future detour trips at caixa-core test time.
9019 // Also byte-parity witness against the sibling
9020 // [`ToString::to_string`] surface routed through
9021 // [`std::fmt::Display`] — the three owned-heap-string paths
9022 // (`.into::<String>()`, `String::from`, `.to_string()`) must
9023 // resolve identically on every arm so a future consumer that
9024 // picks any of the three lands on the same lifted
9025 // SUPERVISOR_ESTRATEGIA_* const. Then a direct round-trip
9026 // witness through the paired trait-idiomatic reverse
9027 // [`TryFrom<&str>`] axis on the owned-`String`'s
9028 // [`String::as_str`] borrow that closes the two-way
9029 // `Self → String → Self` round-trip on the trait-idiomatic
9030 // owned-`String` forward + reverse axis pair.
9031 for &variant in RestartStrategy::ALL {
9032 let owned_string: String = <String as From<RestartStrategy>>::from(variant);
9033 let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
9034 assert_eq!(
9035 owned_string.as_str(),
9036 owned_static,
9037 "From<RestartStrategy> for String and From<RestartStrategy> \
9038 for &'static str must resolve identically on \
9039 RestartStrategy::{variant:?} — divergence signals the \
9040 owned-`String` and owned-`&'static str` forward-projection \
9041 return-type-shape paths have drifted onto different \
9042 emit-sets"
9043 );
9044 let via_to_string: String = variant.to_string();
9045 assert_eq!(
9046 owned_string, via_to_string,
9047 "From<RestartStrategy> for String must byte-equal \
9048 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
9049 divergence signals the trait-idiomatic owned-`String` \
9050 forward-projection axis and the ToString-through-Display \
9051 axis have drifted onto different emit-sets"
9052 );
9053 }
9054 let via_iter: Vec<String> = RestartStrategy::ALL
9055 .iter()
9056 .copied()
9057 .map(String::from)
9058 .collect();
9059 let via_method: Vec<String> = RestartStrategy::ALL
9060 .iter()
9061 .map(|s| s.as_str().to_owned())
9062 .collect();
9063 assert_eq!(
9064 via_iter, via_method,
9065 "`.iter().copied().map(String::from)` over RestartStrategy::ALL \
9066 must byte-equal `.iter().map(|s| s.as_str().to_owned())` on \
9067 every arm — the owned-`String` `From<RestartStrategy> for \
9068 String` axis is what makes the `String::from` composition \
9069 route through the substrate-primitive `RestartStrategy::as_str` \
9070 accessor rather than through a per-call-site `.to_owned()` / \
9071 `String::from(strategy.as_str())` detour"
9072 );
9073 for &variant in RestartStrategy::ALL {
9074 let emitted: String = variant.into();
9075 let re_parsed: Result<RestartStrategy, ()> =
9076 <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
9077 assert_eq!(
9078 re_parsed,
9079 Ok(variant),
9080 "trait-idiomatic owned-`String` forward-projection + \
9081 reverse-projection axis pair must round-trip \
9082 RestartStrategy::{variant:?} through `.into::<String>()` \
9083 and back through `TryFrom<&str>` on the owned-`String`'s \
9084 String::as_str borrow — a break signals the owned-`String` \
9085 forward-emit and reverse-parse axes have drifted onto \
9086 different vocabularies"
9087 );
9088 }
9089 }
9090
9091 #[test]
9092 fn restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
9093 // Fail-before-pass-after byte-parity pin on the newly lifted
9094 // `impl From<&RestartStrategy> for String` — asserts the
9095 // borrowed-input owned-`String`-returning standard-library trait
9096 // impl and the substrate-primitive [`RestartStrategy::as_str`]
9097 // `pub const fn` accessor resolve to the same four-arm emit-set
9098 // across every arm the exhaustive [`RestartStrategy::ALL`] slice
9099 // enumerates. Rust's standard library does not carry a blanket
9100 // `impl<T: AsRef<str>> From<&T> for String` (nor an
9101 // `impl<T: fmt::Display> From<&T> for String`), so the
9102 // borrowed-input owned-`String` forward-projection axis is a
9103 // distinct trait-idiomatic surface that a
9104 // `let key: String = (&strategy).into();`-shaped call site
9105 // reaches through this impl and no other — the paired sibling
9106 // `From<RestartStrategy> for String` impl forces every
9107 // borrowed-input call site through an explicit `Copy` deref
9108 // (`String::from(*strategy)`) or an `.as_str().to_owned()` /
9109 // `.to_string()` detour.
9110 for &variant in RestartStrategy::ALL {
9111 let via_trait: String = <String as From<&RestartStrategy>>::from(&variant);
9112 let via_method: &'static str = variant.as_str();
9113 assert_eq!(
9114 via_trait.as_str(),
9115 via_method,
9116 "From<&RestartStrategy> for String impl must round-trip \
9117 &RestartStrategy::{variant:?} to the same lifted \
9118 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
9119 returns — divergence signals a silent detour off the \
9120 substrate-primitive accessor"
9121 );
9122 let via_into: String = (&variant).into();
9123 assert_eq!(
9124 via_into.as_str(),
9125 via_method,
9126 "Into<String>::into on &RestartStrategy::{variant:?} must \
9127 byte-equal RestartStrategy::as_str on the same input — the \
9128 blanket-derived Into shape must resolve to the same as_str \
9129 dispatch as the explicit From impl"
9130 );
9131 }
9132 }
9133
9134 #[test]
9135 fn restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
9136 // Cross-axis partition pin: the newly lifted trait-idiomatic
9137 // borrowed-input owned-`String` `From<&RestartStrategy> for
9138 // String` (this lift), the paired owned-input owned-`String`
9139 // `From<RestartStrategy> for String` (7baa18a), the paired
9140 // borrowed-input owned-`&'static str` `From<&RestartStrategy>
9141 // for &'static str` (e941836), and the paired owned-input
9142 // owned-`&'static str` `From<RestartStrategy> for &'static str`
9143 // (523157d) — every corner of the `{Self, &Self} × {&'static
9144 // str, String}` 2×2 trait-idiomatic projection family — must
9145 // resolve identically on every arm, locking the four
9146 // return-shape × input-shape paths together so any future
9147 // detour trips at caixa-core test time. Also byte-parity
9148 // witness against the sibling [`ToString::to_string`] surface
9149 // routed through [`std::fmt::Display`] and a direct round-trip
9150 // witness through the paired trait-idiomatic reverse
9151 // [`TryFrom<&str>`] axis on the owned-`String`'s
9152 // [`String::as_str`] borrow that closes the two-way
9153 // `&Self → String → Self` round-trip on the trait-idiomatic
9154 // borrowed-input owned-`String` forward + reverse axis pair.
9155 for &variant in RestartStrategy::ALL {
9156 let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
9157 let owned_string: String = <String as From<RestartStrategy>>::from(variant);
9158 let borrowed_static: &'static str =
9159 <&'static str as From<&RestartStrategy>>::from(&variant);
9160 let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
9161 assert_eq!(
9162 borrowed_string, owned_string,
9163 "From<&RestartStrategy> for String and From<RestartStrategy> \
9164 for String must resolve identically on \
9165 RestartStrategy::{variant:?} — divergence signals the \
9166 borrowed-input and owned-input owned-`String` \
9167 forward-projection input-shape paths have drifted onto \
9168 different emit-sets"
9169 );
9170 assert_eq!(
9171 borrowed_string.as_str(),
9172 borrowed_static,
9173 "From<&RestartStrategy> for String and From<&RestartStrategy> \
9174 for &'static str must resolve identically on \
9175 RestartStrategy::{variant:?} — divergence signals the \
9176 borrowed-input `&'static str` and owned-`String` \
9177 return-shape paths have drifted onto different emit-sets"
9178 );
9179 assert_eq!(
9180 borrowed_string.as_str(),
9181 owned_static,
9182 "From<&RestartStrategy> for String and From<RestartStrategy> \
9183 for &'static str must resolve identically on \
9184 RestartStrategy::{variant:?} — divergence signals a break \
9185 in the diagonal corner of the {{Self, &Self}} × \
9186 {{&'static str, String}} 2×2 trait-idiomatic \
9187 projection family"
9188 );
9189 let via_to_string: String = variant.to_string();
9190 assert_eq!(
9191 borrowed_string, via_to_string,
9192 "From<&RestartStrategy> for String must byte-equal \
9193 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
9194 divergence signals the trait-idiomatic borrowed-input \
9195 owned-`String` forward-projection axis and the \
9196 ToString-through-Display axis have drifted onto different \
9197 emit-sets"
9198 );
9199 }
9200 let via_iter: Vec<String> = RestartStrategy::ALL.iter().map(String::from).collect();
9201 let via_method: Vec<String> = RestartStrategy::ALL
9202 .iter()
9203 .map(|s| s.as_str().to_owned())
9204 .collect();
9205 assert_eq!(
9206 via_iter, via_method,
9207 "`.iter().map(String::from)` over RestartStrategy::ALL — a \
9208 call site whose iteration axis holds `&RestartStrategy` by \
9209 construction — must byte-equal `.iter().map(|s| \
9210 s.as_str().to_owned())` on every arm — the borrowed-input \
9211 owned-`String` `From<&RestartStrategy> for String` axis is \
9212 what makes the `String::from` composition route through the \
9213 substrate-primitive `RestartStrategy::as_str` accessor \
9214 without a spurious `Copy` deref (which would only be \
9215 reachable through the owned-input `From<RestartStrategy> for \
9216 String` axis by first calling `.copied()` on the iterator)"
9217 );
9218 for &variant in RestartStrategy::ALL {
9219 let emitted: String = (&variant).into();
9220 let re_parsed: Result<RestartStrategy, ()> =
9221 <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
9222 assert_eq!(
9223 re_parsed,
9224 Ok(variant),
9225 "trait-idiomatic borrowed-input owned-`String` \
9226 forward-projection + reverse-projection axis pair must \
9227 round-trip &RestartStrategy::{variant:?} through \
9228 `.into::<String>()` on the borrowed-input surface and \
9229 back through `TryFrom<&str>` on the owned-`String`'s \
9230 String::as_str borrow — a break signals the \
9231 borrowed-input owned-`String` forward-emit and \
9232 reverse-parse axes have drifted onto different \
9233 vocabularies"
9234 );
9235 }
9236 }
9237
9238 #[test]
9239 fn restart_strategy_from_into_static_cow_str_routes_through_as_str_accessor() {
9240 // Fail-before-pass-after byte-parity pin on the newly lifted
9241 // `impl From<RestartStrategy> for std::borrow::Cow<'static, str>` —
9242 // asserts the standard-library trait impl and the substrate-
9243 // primitive [`super::RestartStrategy::as_str`] `pub const fn`
9244 // accessor resolve to the same four-arm emit-set across every
9245 // arm the exhaustive [`super::RestartStrategy::ALL`] slice
9246 // enumerates. Rust's standard library does not carry a blanket
9247 // `impl<T: AsRef<str>> From<T> for Cow<'static, str>` (nor an
9248 // `impl<T: fmt::Display> From<T> for Cow<'static, str>`), so
9249 // the `Cow<'static, str>` forward-projection axis is a
9250 // distinct trait-idiomatic surface that a
9251 // `let key: Cow<'static, str> = strategy.into();`-shaped call
9252 // site reaches through this impl and no other — the paired
9253 // sibling `From<RestartStrategy> for &'static str` and
9254 // `From<RestartStrategy> for String` impls force every
9255 // `Cow<'static, str>`-parameterized call site through a
9256 // `Cow::Borrowed(strategy.as_str())` /
9257 // `Cow::Owned(strategy.to_string())` composition whose type
9258 // bounds have no compile-time link back to the substrate
9259 // primitive.
9260 //
9261 // Also asserts the projection lands on the zero-alloc
9262 // [`std::borrow::Cow::Borrowed`] arm (not the
9263 // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
9264 // [`super::RestartStrategy::as_str`] accessor's `&'static str`
9265 // return lifetime by construction makes the borrowed arm the
9266 // type-correct projection with no runtime allocation. Any
9267 // future silent detour that routes the impl through the owned
9268 // arm (an accidental `Cow::Owned(strategy.to_string())` rewrite
9269 // that would allocate on every call site where the
9270 // `&'static str` return of [`super::RestartStrategy::as_str`]
9271 // makes the zero-alloc borrowed projection type-correct) trips
9272 // at caixa-core test time under the
9273 // [`std::borrow::Cow::Borrowed`] discriminator witness rather
9274 // than at a downstream `Cow<'static, str>`-bound consumer's
9275 // silent allocation.
9276 //
9277 // First peer on the substrate-wide trait-idiomatic
9278 // [`std::borrow::Cow<'static, str>`] forward-projection family
9279 // to extend the axis off the top-level [`super::CaixaKind`]
9280 // enum (99c1735 owned-input, d45c409 borrowed-input) onto the
9281 // first M2 OTP-shape closed-set fieldless typed enum on the
9282 // caixa surface.
9283 for &variant in RestartStrategy::ALL {
9284 let via_trait: std::borrow::Cow<'static, str> =
9285 <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
9286 let via_method: &'static str = variant.as_str();
9287 assert_eq!(
9288 via_trait.as_ref(),
9289 via_method,
9290 "From<RestartStrategy> for Cow<'static, str> impl must \
9291 round-trip RestartStrategy::{variant:?} to the same \
9292 lifted SUPERVISOR_ESTRATEGIA_* const \
9293 RestartStrategy::as_str returns — divergence signals a \
9294 silent detour off the substrate-primitive accessor"
9295 );
9296 assert!(
9297 matches!(via_trait, std::borrow::Cow::Borrowed(_)),
9298 "From<RestartStrategy> for Cow<'static, str> impl must \
9299 land on the zero-alloc Cow::Borrowed arm on \
9300 RestartStrategy::{variant:?} — a Cow::Owned outcome \
9301 signals the projection has silently allocated where \
9302 the substrate-primitive RestartStrategy::as_str \
9303 `&'static str` return makes the borrowed arm the \
9304 type-correct projection"
9305 );
9306 let via_into: std::borrow::Cow<'static, str> = variant.into();
9307 assert_eq!(
9308 via_into.as_ref(),
9309 via_method,
9310 "Into<Cow<'static, str>>::into on \
9311 RestartStrategy::{variant:?} must byte-equal \
9312 RestartStrategy::as_str on the same input — the \
9313 blanket-derived Into shape must resolve to the same \
9314 as_str dispatch as the explicit From impl"
9315 );
9316 assert!(
9317 matches!(via_into, std::borrow::Cow::Borrowed(_)),
9318 "Into<Cow<'static, str>>::into on \
9319 RestartStrategy::{variant:?} must land on the \
9320 zero-alloc Cow::Borrowed arm — the blanket-derived \
9321 Into shape must resolve to the same Cow::Borrowed \
9322 dispatch as the explicit From impl"
9323 );
9324 }
9325 }
9326
9327 #[test]
9328 fn restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
9329 // Cross-axis partition pin: the newly lifted trait-idiomatic
9330 // `From<RestartStrategy> for std::borrow::Cow<'static, str>`
9331 // (this lift), the paired owned-input `From<RestartStrategy>
9332 // for &'static str` (523157d), and the paired owned-input
9333 // `From<RestartStrategy> for String` (7baa18a) forward
9334 // projections must resolve identically on every arm, locking
9335 // the three return-shape paths together by construction so any
9336 // future detour trips at caixa-core test time. Also byte-parity
9337 // witness against the sibling [`ToString::to_string`] surface
9338 // routed through [`std::fmt::Display`] — every owned-heap-
9339 // string path (the `Cow::Owned` promotion of this axis's
9340 // `.into_owned()`, `From<RestartStrategy> for String`, and
9341 // `.to_string()`) resolves to the same lifted
9342 // [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const per arm.
9343 //
9344 // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
9345 // witness over [`super::RestartStrategy::ALL`] that
9346 // materializes the four-arm accept-set through the
9347 // [`std::borrow::Cow<'static, str>`] axis alone — the exact
9348 // shape a future `axum::response::IntoResponse` per-strategy
9349 // rejection-body composer, a future M4 admission-webhook
9350 // per-strategy rejection-reason emitter whose typing rules out
9351 // the sibling [`AsRef<str>`] borrowed return, or a future
9352 // substrate-wide per-strategy diagnostic surface that binds
9353 // through a [`Cow<'static, str>`] boundary reaches through.
9354 // The pipe witness also pins the zero-alloc discipline: every
9355 // element in the collected vector satisfies the
9356 // [`std::borrow::Cow::Borrowed`] arm predicate, so a future
9357 // accidental silent-allocation regression on the pipe's
9358 // iteration axis is a caixa-core-test-time failure.
9359 for &variant in RestartStrategy::ALL {
9360 let via_cow: std::borrow::Cow<'static, str> =
9361 <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
9362 let via_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
9363 let via_string: String = <String as From<RestartStrategy>>::from(variant);
9364 assert_eq!(
9365 via_cow.as_ref(),
9366 via_static,
9367 "From<RestartStrategy> for Cow<'static, str> and \
9368 From<RestartStrategy> for &'static str must resolve \
9369 identically on RestartStrategy::{variant:?} — \
9370 divergence signals the Cow<'static, str> and \
9371 &'static str return-shape paths have drifted onto \
9372 different emit-sets"
9373 );
9374 assert_eq!(
9375 via_cow.as_ref(),
9376 via_string.as_str(),
9377 "From<RestartStrategy> for Cow<'static, str> and \
9378 From<RestartStrategy> for String must resolve \
9379 identically on RestartStrategy::{variant:?} — \
9380 divergence signals the Cow<'static, str> and String \
9381 return-shape paths have drifted onto different \
9382 emit-sets"
9383 );
9384 let via_to_string: String = variant.to_string();
9385 assert_eq!(
9386 via_cow.as_ref(),
9387 via_to_string.as_str(),
9388 "From<RestartStrategy> for Cow<'static, str> must \
9389 byte-equal RestartStrategy::to_string on \
9390 RestartStrategy::{variant:?} — divergence signals the \
9391 trait-idiomatic Cow<'static, str> forward-projection \
9392 axis and the ToString-through-Display axis have \
9393 drifted onto different emit-sets"
9394 );
9395 }
9396 let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
9397 .iter()
9398 .copied()
9399 .map(std::borrow::Cow::from)
9400 .collect();
9401 let via_method: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
9402 .iter()
9403 .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
9404 .collect();
9405 assert_eq!(
9406 via_iter, via_method,
9407 "`.iter().copied().map(Cow::from)` over \
9408 RestartStrategy::ALL must byte-equal `.iter().map(|s| \
9409 Cow::Borrowed(s.as_str()))` on every arm — the \
9410 trait-idiomatic `From<RestartStrategy> for Cow<'static, \
9411 str>` axis is what makes the `Cow::from` composition \
9412 route through the substrate-primitive \
9413 `RestartStrategy::as_str` accessor with the zero-alloc \
9414 Cow::Borrowed arm by construction, rather than a \
9415 per-call-site `Cow::Owned(strategy.to_string())` \
9416 allocation"
9417 );
9418 for cow in &via_iter {
9419 assert!(
9420 matches!(cow, std::borrow::Cow::Borrowed(_)),
9421 "every element of the \
9422 .iter().copied().map(Cow::from) pipe over \
9423 RestartStrategy::ALL must land on the zero-alloc \
9424 Cow::Borrowed arm — a Cow::Owned outcome on any arm \
9425 signals the pipe's iteration axis has silently \
9426 allocated where the substrate-primitive \
9427 RestartStrategy::as_str `&'static str` return makes \
9428 the borrowed arm the type-correct projection"
9429 );
9430 }
9431 }
9432
9433 #[test]
9434 fn restart_strategy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
9435 // Fail-before-pass-after byte-parity pin on the newly lifted
9436 // `impl From<&RestartStrategy> for std::borrow::Cow<'static, str>` —
9437 // asserts the borrowed-input standard-library trait impl and
9438 // the substrate-primitive [`super::RestartStrategy::as_str`]
9439 // `pub const fn` accessor resolve to the same four-arm emit-
9440 // set across every arm the exhaustive
9441 // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
9442 // standard library does not carry a blanket
9443 // `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor a
9444 // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
9445 // the borrowed-input `Cow<'static, str>` forward-projection
9446 // axis is a distinct trait-idiomatic surface that a
9447 // `let key: Cow<'static, str> = (&strategy).into();`-shaped
9448 // call site or a
9449 // `RestartStrategy::ALL.iter().map(Cow::from)`-shaped pipe
9450 // reaches through this impl and no other — the paired owned-
9451 // input `From<RestartStrategy> for Cow<'static, str>` impl
9452 // (7dd28b3) forces every borrowed-input call site through an
9453 // explicit `Copy` deref (`Cow::from(*strategy)`) or a
9454 // `Cow::Borrowed(strategy.as_str())` open-code whose type
9455 // bounds have no compile-time link back to the substrate
9456 // primitive.
9457 //
9458 // Also asserts the projection lands on the zero-alloc
9459 // [`std::borrow::Cow::Borrowed`] arm (not the
9460 // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
9461 // [`super::RestartStrategy::as_str`] accessor's `&'static str`
9462 // return lifetime by construction makes the borrowed arm the
9463 // type-correct projection with no runtime allocation on the
9464 // borrowed-input surface just as on the paired owned-input
9465 // surface.
9466 //
9467 // Second peer on the substrate-wide trait-idiomatic
9468 // [`std::borrow::Cow<'static, str>`] forward-projection family
9469 // on this enum — closes the `{Self, &Self}` input-shape
9470 // corner of the [`Cow<'static, str>`] axis on the first M2
9471 // OTP-shape closed-set fieldless typed enum peer on the caixa
9472 // surface (`:supervisor :estrategia`), exactly as d45c409
9473 // closed it on the top-level [`super::CaixaKind`] one commit
9474 // after the owning half (99c1735) landed. Every future
9475 // closed-set fieldless typed enum peer on the substrate is a
9476 // future target of the campaign.
9477 for &variant in RestartStrategy::ALL {
9478 let via_trait: std::borrow::Cow<'static, str> =
9479 <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
9480 let via_method: &'static str = variant.as_str();
9481 assert_eq!(
9482 via_trait.as_ref(),
9483 via_method,
9484 "From<&RestartStrategy> for Cow<'static, str> impl must \
9485 round-trip &RestartStrategy::{variant:?} to the same \
9486 lifted SUPERVISOR_ESTRATEGIA_* const \
9487 RestartStrategy::as_str returns — divergence signals a \
9488 silent detour off the substrate-primitive accessor"
9489 );
9490 assert!(
9491 matches!(via_trait, std::borrow::Cow::Borrowed(_)),
9492 "From<&RestartStrategy> for Cow<'static, str> impl must \
9493 land on the zero-alloc Cow::Borrowed arm on \
9494 &RestartStrategy::{variant:?} — a Cow::Owned outcome \
9495 signals the projection has silently allocated where \
9496 the substrate-primitive RestartStrategy::as_str \
9497 `&'static str` return makes the borrowed arm the \
9498 type-correct projection"
9499 );
9500 let via_into: std::borrow::Cow<'static, str> = (&variant).into();
9501 assert_eq!(
9502 via_into.as_ref(),
9503 via_method,
9504 "Into<Cow<'static, str>>::into on \
9505 &RestartStrategy::{variant:?} must byte-equal \
9506 RestartStrategy::as_str on the same input — the \
9507 blanket-derived Into shape must resolve to the same \
9508 as_str dispatch as the explicit From impl"
9509 );
9510 assert!(
9511 matches!(via_into, std::borrow::Cow::Borrowed(_)),
9512 "Into<Cow<'static, str>>::into on \
9513 &RestartStrategy::{variant:?} must land on the \
9514 zero-alloc Cow::Borrowed arm — the blanket-derived \
9515 Into shape must resolve to the same Cow::Borrowed \
9516 dispatch as the explicit From impl"
9517 );
9518 }
9519 }
9520
9521 #[test]
9522 fn restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
9523 // Cross-axis partition pin: the newly lifted trait-idiomatic
9524 // borrowed-input `From<&RestartStrategy> for
9525 // std::borrow::Cow<'static, str>` (this lift), the paired
9526 // owned-input `From<RestartStrategy> for
9527 // std::borrow::Cow<'static, str>` (7dd28b3), the paired
9528 // borrowed-input owned-`&'static str` `From<&RestartStrategy>
9529 // for &'static str`, and the paired borrowed-input owned-
9530 // `String` `From<&RestartStrategy> for String` must resolve
9531 // identically on every arm, locking the four
9532 // return-shape × input-shape paths together by construction so
9533 // any future detour trips at caixa-core test time. Also byte-
9534 // parity witness against the sibling [`ToString::to_string`]
9535 // surface routed through [`std::fmt::Display`] — every owned-
9536 // heap-string path (this axis's `.into_owned()` promotion, the
9537 // paired [`From<&RestartStrategy> for String`], and
9538 // `.to_string()`) resolves to the same lifted
9539 // [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const per arm.
9540 //
9541 // Then a `.iter().map(std::borrow::Cow::from)` pipe witness
9542 // over [`super::RestartStrategy::ALL`] — whose iterator yields
9543 // `&RestartStrategy` by construction, so the borrowed-input
9544 // [`Cow<'static, str>`] axis is what routes the pipe through
9545 // the substrate-primitive [`super::RestartStrategy::as_str`]
9546 // accessor without a spurious [`Copy`] deref (which would only
9547 // be reachable through the owned-input
9548 // [`From<RestartStrategy> for Cow<'static, str>`] axis by
9549 // first calling `.copied()` on the iterator). The pipe witness
9550 // also pins the zero-alloc discipline: every element in the
9551 // collected vector satisfies the [`std::borrow::Cow::Borrowed`]
9552 // arm predicate, so a future accidental silent-allocation
9553 // regression on the pipe's iteration axis is a caixa-core-
9554 // test-time failure.
9555 for &strategy in RestartStrategy::ALL {
9556 let borrowed_cow: std::borrow::Cow<'static, str> =
9557 <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&strategy);
9558 let owned_cow: std::borrow::Cow<'static, str> =
9559 <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(strategy);
9560 let borrowed_static: &'static str =
9561 <&'static str as From<&RestartStrategy>>::from(&strategy);
9562 let borrowed_string: String = <String as From<&RestartStrategy>>::from(&strategy);
9563 assert_eq!(
9564 borrowed_cow, owned_cow,
9565 "From<&RestartStrategy> for Cow<'static, str> and \
9566 From<RestartStrategy> for Cow<'static, str> must \
9567 resolve identically on RestartStrategy::{strategy:?} — \
9568 divergence signals the borrowed-input and owned-input \
9569 Cow<'static, str> forward-projection input-shape \
9570 paths have drifted onto different emit-sets"
9571 );
9572 assert_eq!(
9573 borrowed_cow.as_ref(),
9574 borrowed_static,
9575 "From<&RestartStrategy> for Cow<'static, str> and \
9576 From<&RestartStrategy> for &'static str must resolve \
9577 identically on RestartStrategy::{strategy:?} — \
9578 divergence signals the borrowed-input Cow<'static, \
9579 str> and &'static str return-shape paths have drifted \
9580 onto different emit-sets"
9581 );
9582 assert_eq!(
9583 borrowed_cow.as_ref(),
9584 borrowed_string.as_str(),
9585 "From<&RestartStrategy> for Cow<'static, str> and \
9586 From<&RestartStrategy> for String must resolve \
9587 identically on RestartStrategy::{strategy:?} — \
9588 divergence signals the borrowed-input Cow<'static, \
9589 str> and owned-`String` return-shape paths have \
9590 drifted onto different emit-sets"
9591 );
9592 let via_to_string: String = strategy.to_string();
9593 assert_eq!(
9594 borrowed_cow.as_ref(),
9595 via_to_string.as_str(),
9596 "From<&RestartStrategy> for Cow<'static, str> must \
9597 byte-equal RestartStrategy::to_string on \
9598 RestartStrategy::{strategy:?} — divergence signals \
9599 the trait-idiomatic borrowed-input Cow<'static, str> \
9600 forward-projection axis and the ToString-through-\
9601 Display axis have drifted onto different emit-sets"
9602 );
9603 }
9604 let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
9605 .iter()
9606 .map(std::borrow::Cow::from)
9607 .collect();
9608 let via_method: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
9609 .iter()
9610 .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
9611 .collect();
9612 assert_eq!(
9613 via_iter, via_method,
9614 "`.iter().map(Cow::from)` over RestartStrategy::ALL — a \
9615 call site whose iteration axis holds `&RestartStrategy` \
9616 by construction — must byte-equal `.iter().map(|s| \
9617 Cow::Borrowed(s.as_str()))` on every arm — the borrowed-\
9618 input Cow<'static, str> `From<&RestartStrategy> for \
9619 Cow<'static, str>` axis is what makes the `Cow::from` \
9620 composition route through the substrate-primitive \
9621 `RestartStrategy::as_str` accessor with the zero-alloc \
9622 Cow::Borrowed arm by construction and without a spurious \
9623 `Copy` deref (which would only be reachable through the \
9624 owned-input `From<RestartStrategy> for Cow<'static, str>` \
9625 axis by first calling `.copied()` on the iterator)"
9626 );
9627 for cow in &via_iter {
9628 assert!(
9629 matches!(cow, std::borrow::Cow::Borrowed(_)),
9630 "every element of the .iter().map(Cow::from) pipe \
9631 over RestartStrategy::ALL must land on the zero-\
9632 alloc Cow::Borrowed arm — a Cow::Owned outcome on \
9633 any arm signals the pipe's iteration axis has \
9634 silently allocated where the substrate-primitive \
9635 RestartStrategy::as_str `&'static str` return makes \
9636 the borrowed arm the type-correct projection"
9637 );
9638 }
9639 }
9640
9641 #[test]
9642 fn restart_strategy_from_into_box_str_routes_through_as_str_accessor() {
9643 // Fail-before-pass-after byte-parity pin on the newly lifted
9644 // `impl From<RestartStrategy> for Box<str>` — asserts the
9645 // owned-input standard-library trait impl and the
9646 // substrate-primitive [`super::RestartStrategy::as_str`]
9647 // `pub const fn` accessor resolve to the same four-arm emit-
9648 // set across every arm the exhaustive
9649 // [`super::RestartStrategy::ALL`] slice enumerates. Opens the
9650 // substrate-wide `Box<str>` forward-projection campaign tier
9651 // on the first M2 OTP-shape closed-set fieldless typed enum
9652 // peer on the caixa surface (`:supervisor :estrategia`),
9653 // immediately after the paired `Cow<'static, str>` axis
9654 // (7dd28b3 / ee577fd) closed the
9655 // `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
9656 // 2×3 corner on this enum. Rust's standard library carries
9657 // `impl From<&str> for Box<str>` and
9658 // `impl From<String> for Box<str>` but no blanket
9659 // `impl<T: AsRef<str>> From<T> for Box<str>`, so this axis is
9660 // a distinct trait-idiomatic surface that a
9661 // `let key: Box<str> = strategy.into();`-shaped call site
9662 // reaches through this impl and no other — a paired
9663 // `Box::from(strategy.as_str())` open-code has no compile-
9664 // time link back to the substrate primitive.
9665 for &variant in RestartStrategy::ALL {
9666 let via_trait: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
9667 let via_method: &'static str = variant.as_str();
9668 assert_eq!(
9669 via_trait.as_ref(),
9670 via_method,
9671 "From<RestartStrategy> for Box<str> impl must round-\
9672 trip RestartStrategy::{variant:?} to the same lifted \
9673 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
9674 returns — divergence signals a silent detour off the \
9675 substrate-primitive accessor"
9676 );
9677 let via_into: Box<str> = variant.into();
9678 assert_eq!(
9679 via_into.as_ref(),
9680 via_method,
9681 "Into<Box<str>>::into on RestartStrategy::{variant:?} \
9682 must byte-equal RestartStrategy::as_str on the same \
9683 input — the blanket-derived Into shape must resolve \
9684 to the same as_str dispatch as the explicit From impl"
9685 );
9686 }
9687 }
9688
9689 #[test]
9690 fn restart_strategy_from_borrowed_into_box_str_routes_through_as_str_accessor() {
9691 // Fail-before-pass-after byte-parity pin on the newly lifted
9692 // `impl From<&RestartStrategy> for Box<str>` — asserts the
9693 // borrowed-input standard-library trait impl and the
9694 // substrate-primitive [`super::RestartStrategy::as_str`]
9695 // `pub const fn` accessor resolve to the same four-arm emit-
9696 // set across every arm the exhaustive
9697 // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
9698 // standard library does not carry a blanket
9699 // `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
9700 // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
9701 // so the borrowed-input `Box<str>` forward-projection axis
9702 // is a distinct trait-idiomatic surface that a
9703 // `let key: Box<str> = (&strategy).into();`-shaped call site
9704 // or a `RestartStrategy::ALL.iter().map(Box::<str>::from)`-
9705 // shaped pipe reaches through this impl and no other — the
9706 // paired owned-input `From<RestartStrategy> for Box<str>`
9707 // impl (69ef45c) forces every borrowed-input call site
9708 // through an explicit `Copy` deref
9709 // (`Box::<str>::from((*strategy).as_str())`) or a
9710 // `Box::<str>::from(strategy.as_str())` open-code whose
9711 // type bounds have no compile-time link back to the
9712 // substrate primitive.
9713 //
9714 // Second peer on the substrate-wide trait-idiomatic
9715 // [`Box<str>`] forward-projection family on this enum —
9716 // closes the `{Self, &Self}` input-shape corner of the
9717 // [`Box<str>`] axis on the first M2 OTP-shape closed-set
9718 // fieldless typed enum peer on the caixa surface
9719 // (`:supervisor :estrategia`), exactly as ee577fd closed
9720 // the paired [`Cow<'static, str>`] axis one commit after
9721 // its owning half (7dd28b3) landed. Every future closed-
9722 // set fieldless typed enum peer on the substrate is a
9723 // future target of the campaign.
9724 //
9725 // Also byte-parity witness against the paired owned-input
9726 // [`From<RestartStrategy> for Box<str>`] and the sibling
9727 // borrowed-input [`From<&RestartStrategy> for &'static str`],
9728 // [`From<&RestartStrategy> for String`], and
9729 // [`From<&RestartStrategy> for Cow<'static, str>`]
9730 // return-shape axes — locking the four
9731 // return-shape × input-shape paths together by construction
9732 // so any future detour trips at caixa-core test time. Then a
9733 // `.iter().map(Box::<str>::from)` pipe witness over
9734 // [`super::RestartStrategy::ALL`] — whose iterator yields
9735 // `&RestartStrategy` by construction, so the borrowed-input
9736 // [`Box<str>`] axis is what routes the pipe through the
9737 // substrate-primitive [`super::RestartStrategy::as_str`]
9738 // accessor without a spurious [`Copy`] deref (which would
9739 // only be reachable through the owned-input
9740 // [`From<RestartStrategy> for Box<str>`] axis by first
9741 // calling `.copied()` on the iterator).
9742 for &variant in RestartStrategy::ALL {
9743 let via_trait: Box<str> = <Box<str> as From<&RestartStrategy>>::from(&variant);
9744 let via_method: &'static str = variant.as_str();
9745 assert_eq!(
9746 via_trait.as_ref(),
9747 via_method,
9748 "From<&RestartStrategy> for Box<str> impl must \
9749 round-trip &RestartStrategy::{variant:?} to the same \
9750 lifted SUPERVISOR_ESTRATEGIA_* const \
9751 RestartStrategy::as_str returns — divergence signals \
9752 a silent detour off the substrate-primitive accessor"
9753 );
9754 let via_into: Box<str> = (&variant).into();
9755 assert_eq!(
9756 via_into.as_ref(),
9757 via_method,
9758 "Into<Box<str>>::into on &RestartStrategy::{variant:?} \
9759 must byte-equal RestartStrategy::as_str on the same \
9760 input — the blanket-derived Into shape must resolve \
9761 to the same as_str dispatch as the explicit From impl"
9762 );
9763 let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
9764 assert_eq!(
9765 via_trait, owned_box,
9766 "From<&RestartStrategy> for Box<str> and \
9767 From<RestartStrategy> for Box<str> must resolve \
9768 identically on RestartStrategy::{variant:?} — \
9769 divergence signals the borrowed-input and owned-input \
9770 Box<str> forward-projection input-shape paths have \
9771 drifted onto different emit-sets"
9772 );
9773 let borrowed_static: &'static str =
9774 <&'static str as From<&RestartStrategy>>::from(&variant);
9775 assert_eq!(
9776 via_trait.as_ref(),
9777 borrowed_static,
9778 "From<&RestartStrategy> for Box<str> and \
9779 From<&RestartStrategy> for &'static str must resolve \
9780 identically on RestartStrategy::{variant:?} — \
9781 divergence signals the borrowed-input Box<str> and \
9782 &'static str return-shape paths have drifted onto \
9783 different emit-sets"
9784 );
9785 let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
9786 assert_eq!(
9787 via_trait.as_ref(),
9788 borrowed_string.as_str(),
9789 "From<&RestartStrategy> for Box<str> and \
9790 From<&RestartStrategy> for String must resolve \
9791 identically on RestartStrategy::{variant:?} — \
9792 divergence signals the borrowed-input Box<str> and \
9793 owned-`String` return-shape paths have drifted onto \
9794 different emit-sets"
9795 );
9796 let borrowed_cow: std::borrow::Cow<'static, str> =
9797 <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
9798 assert_eq!(
9799 via_trait.as_ref(),
9800 borrowed_cow.as_ref(),
9801 "From<&RestartStrategy> for Box<str> and \
9802 From<&RestartStrategy> for Cow<'static, str> must \
9803 resolve identically on RestartStrategy::{variant:?} — \
9804 divergence signals the borrowed-input Box<str> and \
9805 Cow<'static, str> return-shape paths have drifted \
9806 onto different emit-sets"
9807 );
9808 }
9809 let via_iter: Vec<Box<str>> = RestartStrategy::ALL.iter().map(Box::<str>::from).collect();
9810 let via_method: Vec<Box<str>> = RestartStrategy::ALL
9811 .iter()
9812 .map(|s| Box::<str>::from(s.as_str()))
9813 .collect();
9814 assert_eq!(
9815 via_iter, via_method,
9816 "`.iter().map(Box::<str>::from)` over \
9817 RestartStrategy::ALL — a call site whose iteration axis \
9818 holds `&RestartStrategy` by construction — must byte-\
9819 equal `.iter().map(|s| Box::<str>::from(s.as_str()))` \
9820 on every arm — the borrowed-input Box<str> \
9821 `From<&RestartStrategy> for Box<str>` axis is what \
9822 makes the `Box::<str>::from` composition route through \
9823 the substrate-primitive `RestartStrategy::as_str` \
9824 accessor without a spurious `Copy` deref (which would \
9825 only be reachable through the owned-input \
9826 `From<RestartStrategy> for Box<str>` axis by first \
9827 calling `.copied()` on the iterator)"
9828 );
9829 }
9830
9831 #[test]
9832 fn restart_strategy_from_into_arc_str_routes_through_as_str_accessor() {
9833 // Fail-before-pass-after byte-parity pin on the newly lifted
9834 // `impl From<RestartStrategy> for std::sync::Arc<str>` — asserts
9835 // the owned-input standard-library trait impl and the
9836 // substrate-primitive [`super::RestartStrategy::as_str`]
9837 // `pub const fn` accessor resolve to the same four-arm emit-
9838 // set across every arm the exhaustive
9839 // [`super::RestartStrategy::ALL`] slice enumerates. Opens the
9840 // substrate-wide [`std::sync::Arc<str>`] forward-projection
9841 // campaign tier on the first M2 OTP-shape closed-set fieldless
9842 // typed enum peer on the caixa surface
9843 // (`:supervisor :estrategia`), immediately after the paired
9844 // [`Box<str>`] axis (69ef45c / 59ae5dc) closed the
9845 // `{Self, &Self} × {&'static str, String, Cow<'static, str>,
9846 // Box<str>}` 2×4 corner on this enum. Rust's standard library
9847 // carries `impl From<&str> for std::sync::Arc<str>` and
9848 // `impl From<String> for std::sync::Arc<str>` but no blanket
9849 // `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor
9850 // an `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`),
9851 // so this axis is a distinct trait-idiomatic surface that a
9852 // `let key: std::sync::Arc<str> = strategy.into();`-shaped call
9853 // site reaches through this impl and no other — a paired
9854 // `std::sync::Arc::<str>::from(strategy.as_str())` open-code
9855 // has no compile-time link back to the substrate primitive,
9856 // and a two-step `std::sync::Arc::<str>::from(String::from(
9857 // strategy))` composition through the owned-`String` axis
9858 // allocates twice (once into the intermediate `String`, once
9859 // into the [`Arc<str>`] on the `From<String>` conversion)
9860 // where the single-step trait impl allocates once.
9861 //
9862 // Cross-axis byte-parity witness against the sibling owned-
9863 // input `{&'static str, String, Cow<'static, str>, Box<str>}`
9864 // return-shape axes — locking the five return-shape paths on
9865 // the owned-input surface together by construction so any
9866 // future detour off the substrate-primitive
9867 // [`super::RestartStrategy::as_str`] accessor trips at caixa-
9868 // core test time.
9869 for &variant in RestartStrategy::ALL {
9870 let via_trait: std::sync::Arc<str> =
9871 <std::sync::Arc<str> as From<RestartStrategy>>::from(variant);
9872 let via_method: &'static str = variant.as_str();
9873 assert_eq!(
9874 via_trait.as_ref(),
9875 via_method,
9876 "From<RestartStrategy> for std::sync::Arc<str> impl \
9877 must round-trip RestartStrategy::{variant:?} to the \
9878 same lifted SUPERVISOR_ESTRATEGIA_* const \
9879 RestartStrategy::as_str returns — divergence signals \
9880 a silent detour off the substrate-primitive accessor"
9881 );
9882 let via_into: std::sync::Arc<str> = variant.into();
9883 assert_eq!(
9884 via_into.as_ref(),
9885 via_method,
9886 "Into<std::sync::Arc<str>>::into on \
9887 RestartStrategy::{variant:?} must byte-equal \
9888 RestartStrategy::as_str on the same input — the \
9889 blanket-derived Into shape must resolve to the same \
9890 as_str dispatch as the explicit From impl"
9891 );
9892 let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
9893 assert_eq!(
9894 via_trait.as_ref(),
9895 owned_static,
9896 "From<RestartStrategy> for std::sync::Arc<str> and \
9897 From<RestartStrategy> for &'static str must resolve \
9898 identically on RestartStrategy::{variant:?} — \
9899 divergence signals the owned-input std::sync::Arc<str> \
9900 and &'static str return-shape paths have drifted onto \
9901 different emit-sets"
9902 );
9903 let owned_string: String = <String as From<RestartStrategy>>::from(variant);
9904 assert_eq!(
9905 via_trait.as_ref(),
9906 owned_string.as_str(),
9907 "From<RestartStrategy> for std::sync::Arc<str> and \
9908 From<RestartStrategy> for String must resolve \
9909 identically on RestartStrategy::{variant:?} — \
9910 divergence signals the owned-input std::sync::Arc<str> \
9911 and owned-`String` return-shape paths have drifted \
9912 onto different emit-sets"
9913 );
9914 let owned_cow: std::borrow::Cow<'static, str> =
9915 <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
9916 assert_eq!(
9917 via_trait.as_ref(),
9918 owned_cow.as_ref(),
9919 "From<RestartStrategy> for std::sync::Arc<str> and \
9920 From<RestartStrategy> for Cow<'static, str> must \
9921 resolve identically on RestartStrategy::{variant:?} — \
9922 divergence signals the owned-input std::sync::Arc<str> \
9923 and Cow<'static, str> return-shape paths have drifted \
9924 onto different emit-sets"
9925 );
9926 let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
9927 assert_eq!(
9928 via_trait.as_ref(),
9929 owned_box.as_ref(),
9930 "From<RestartStrategy> for std::sync::Arc<str> and \
9931 From<RestartStrategy> for Box<str> must resolve \
9932 identically on RestartStrategy::{variant:?} — \
9933 divergence signals the owned-input std::sync::Arc<str> \
9934 and Box<str> return-shape paths have drifted onto \
9935 different emit-sets"
9936 );
9937 }
9938 }
9939
9940 #[test]
9941 fn restart_strategy_from_borrowed_into_arc_str_routes_through_as_str_accessor() {
9942 // Fail-before-pass-after byte-parity pin on the newly lifted
9943 // `impl From<&RestartStrategy> for std::sync::Arc<str>` —
9944 // asserts the borrowed-input standard-library trait impl and
9945 // the substrate-primitive [`super::RestartStrategy::as_str`]
9946 // `pub const fn` accessor resolve to the same four-arm emit-
9947 // set across every arm the exhaustive
9948 // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
9949 // standard library does not carry a blanket
9950 // `impl<T: AsRef<str>> From<&T> for std::sync::Arc<str>` (nor
9951 // a `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
9952 // so the borrowed-input [`std::sync::Arc<str>`] forward-
9953 // projection axis is a distinct trait-idiomatic surface that a
9954 // `let key: std::sync::Arc<str> = (&strategy).into();`-shaped
9955 // call site or a
9956 // `RestartStrategy::ALL.iter().map(std::sync::Arc::<str>::from)`-
9957 // shaped pipe reaches through this impl and no other — the
9958 // paired owned-input
9959 // `From<RestartStrategy> for std::sync::Arc<str>` impl
9960 // (bca2ec8) forces every borrowed-input call site through an
9961 // explicit `Copy` deref
9962 // (`std::sync::Arc::<str>::from((*strategy).as_str())`) or a
9963 // `std::sync::Arc::<str>::from(strategy.as_str())` open-code
9964 // whose type bounds have no compile-time link back to the
9965 // substrate primitive.
9966 //
9967 // Second peer on the substrate-wide trait-idiomatic
9968 // [`std::sync::Arc<str>`] forward-projection family on this
9969 // enum — closes the `{Self, &Self}` input-shape corner of
9970 // the [`std::sync::Arc<str>`] axis on the first M2 OTP-shape
9971 // closed-set fieldless typed enum peer on the caixa surface
9972 // (`:supervisor :estrategia`), exactly as 59ae5dc closed the
9973 // paired [`Box<str>`] axis one commit after its owning half
9974 // (69ef45c) landed. Every future closed-set fieldless typed
9975 // enum peer on the substrate is a future target of the
9976 // campaign.
9977 //
9978 // Also byte-parity witness against the paired owned-input
9979 // [`From<RestartStrategy> for std::sync::Arc<str>`] and the
9980 // sibling borrowed-input
9981 // [`From<&RestartStrategy> for &'static str`],
9982 // [`From<&RestartStrategy> for String`],
9983 // [`From<&RestartStrategy> for Cow<'static, str>`], and
9984 // [`From<&RestartStrategy> for Box<str>`] return-shape axes —
9985 // locking the five return-shape × input-shape paths together
9986 // by construction so any future detour trips at caixa-core
9987 // test time. Then a
9988 // `.iter().map(std::sync::Arc::<str>::from)` pipe witness over
9989 // [`super::RestartStrategy::ALL`] — whose iterator yields
9990 // `&RestartStrategy` by construction, so the borrowed-input
9991 // [`std::sync::Arc<str>`] axis is what routes the pipe
9992 // through the substrate-primitive
9993 // [`super::RestartStrategy::as_str`] accessor without a
9994 // spurious [`Copy`] deref (which would only be reachable
9995 // through the owned-input
9996 // [`From<RestartStrategy> for std::sync::Arc<str>`] axis by
9997 // first calling `.copied()` on the iterator).
9998 for &variant in RestartStrategy::ALL {
9999 let via_trait: std::sync::Arc<str> =
10000 <std::sync::Arc<str> as From<&RestartStrategy>>::from(&variant);
10001 let via_method: &'static str = variant.as_str();
10002 assert_eq!(
10003 via_trait.as_ref(),
10004 via_method,
10005 "From<&RestartStrategy> for std::sync::Arc<str> impl \
10006 must round-trip &RestartStrategy::{variant:?} to the \
10007 same lifted SUPERVISOR_ESTRATEGIA_* const \
10008 RestartStrategy::as_str returns — divergence signals \
10009 a silent detour off the substrate-primitive accessor"
10010 );
10011 let via_into: std::sync::Arc<str> = (&variant).into();
10012 assert_eq!(
10013 via_into.as_ref(),
10014 via_method,
10015 "Into<std::sync::Arc<str>>::into on \
10016 &RestartStrategy::{variant:?} must byte-equal \
10017 RestartStrategy::as_str on the same input — the \
10018 blanket-derived Into shape must resolve to the same \
10019 as_str dispatch as the explicit From impl"
10020 );
10021 let owned_arc: std::sync::Arc<str> =
10022 <std::sync::Arc<str> as From<RestartStrategy>>::from(variant);
10023 assert_eq!(
10024 via_trait, owned_arc,
10025 "From<&RestartStrategy> for std::sync::Arc<str> and \
10026 From<RestartStrategy> for std::sync::Arc<str> must \
10027 resolve identically on RestartStrategy::{variant:?} — \
10028 divergence signals the borrowed-input and owned-input \
10029 std::sync::Arc<str> forward-projection input-shape \
10030 paths have drifted onto different emit-sets"
10031 );
10032 let borrowed_static: &'static str =
10033 <&'static str as From<&RestartStrategy>>::from(&variant);
10034 assert_eq!(
10035 via_trait.as_ref(),
10036 borrowed_static,
10037 "From<&RestartStrategy> for std::sync::Arc<str> and \
10038 From<&RestartStrategy> for &'static str must resolve \
10039 identically on RestartStrategy::{variant:?} — \
10040 divergence signals the borrowed-input \
10041 std::sync::Arc<str> and &'static str return-shape \
10042 paths have drifted onto different emit-sets"
10043 );
10044 let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
10045 assert_eq!(
10046 via_trait.as_ref(),
10047 borrowed_string.as_str(),
10048 "From<&RestartStrategy> for std::sync::Arc<str> and \
10049 From<&RestartStrategy> for String must resolve \
10050 identically on RestartStrategy::{variant:?} — \
10051 divergence signals the borrowed-input \
10052 std::sync::Arc<str> and owned-`String` return-shape \
10053 paths have drifted onto different emit-sets"
10054 );
10055 let borrowed_cow: std::borrow::Cow<'static, str> =
10056 <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
10057 assert_eq!(
10058 via_trait.as_ref(),
10059 borrowed_cow.as_ref(),
10060 "From<&RestartStrategy> for std::sync::Arc<str> and \
10061 From<&RestartStrategy> for Cow<'static, str> must \
10062 resolve identically on RestartStrategy::{variant:?} — \
10063 divergence signals the borrowed-input \
10064 std::sync::Arc<str> and Cow<'static, str> return-shape \
10065 paths have drifted onto different emit-sets"
10066 );
10067 let borrowed_box: Box<str> = <Box<str> as From<&RestartStrategy>>::from(&variant);
10068 assert_eq!(
10069 via_trait.as_ref(),
10070 borrowed_box.as_ref(),
10071 "From<&RestartStrategy> for std::sync::Arc<str> and \
10072 From<&RestartStrategy> for Box<str> must resolve \
10073 identically on RestartStrategy::{variant:?} — \
10074 divergence signals the borrowed-input \
10075 std::sync::Arc<str> and Box<str> return-shape paths \
10076 have drifted onto different emit-sets"
10077 );
10078 }
10079 let via_iter: Vec<std::sync::Arc<str>> = RestartStrategy::ALL
10080 .iter()
10081 .map(std::sync::Arc::<str>::from)
10082 .collect();
10083 let via_method: Vec<std::sync::Arc<str>> = RestartStrategy::ALL
10084 .iter()
10085 .map(|s| std::sync::Arc::<str>::from(s.as_str()))
10086 .collect();
10087 assert_eq!(
10088 via_iter, via_method,
10089 "`.iter().map(std::sync::Arc::<str>::from)` over \
10090 RestartStrategy::ALL — a call site whose iteration axis \
10091 holds `&RestartStrategy` by construction — must byte-\
10092 equal `.iter().map(|s| std::sync::Arc::<str>::from(s.as_str()))` \
10093 on every arm — the borrowed-input std::sync::Arc<str> \
10094 `From<&RestartStrategy> for std::sync::Arc<str>` axis is \
10095 what makes the `std::sync::Arc::<str>::from` composition \
10096 route through the substrate-primitive \
10097 `RestartStrategy::as_str` accessor without a spurious \
10098 `Copy` deref (which would only be reachable through the \
10099 owned-input `From<RestartStrategy> for std::sync::Arc<str>` \
10100 axis by first calling `.copied()` on the iterator)"
10101 );
10102 }
10103
10104 #[test]
10105 fn restart_policy_try_from_str_routes_through_from_wire_accessor() {
10106 // Fail-before-pass-after byte-parity pin on the newly lifted
10107 // `impl TryFrom<&str> for RestartPolicy` — asserts the standard-
10108 // library trait impl and the substrate-primitive
10109 // [`RestartPolicy::from_wire`] `Option<Self>` accessor resolve to
10110 // the same three-arm accept-set across every arm the exhaustive
10111 // [`RestartPolicy::ALL`] slice enumerates. Any future silent
10112 // detour that routes the trait impl through a divergent
10113 // projection (a per-arm inline `match s { "Permanent" =>
10114 // Ok(Self::Permanent), … }` re-inlining that opens a compile-time
10115 // link to the un-lifted arm-literal, a hypothetical
10116 // `#[serde(rename_all = "…")]` attribute drift that silently
10117 // splits the wire byte-string from every consumer that reaches
10118 // for this typed dispatch, an accidental swap onto the kebab-case
10119 // dispatcher-catalog axis the pre-existing [`std::str::FromStr`]
10120 // impl parses through and which would collide the two-axis
10121 // wire/catalog split the sibling [`RestartPolicy::from_wire`]
10122 // doc block makes load-bearing) trips at caixa-core test time
10123 // under `assert_eq!` rather than at a downstream
10124 // `impl TryFrom<&str>`-bound consumer's silent split. Sweeps
10125 // every one of the three arms [`RestartPolicy::ALL`] carries so
10126 // no arm's projection is covered only by the sibling method-
10127 // named `from_wire` path. Peer of the sibling
10128 // [`restart_strategy_try_from_str_routes_through_from_wire_accessor`]
10129 // (5b828ed) — extends the trait-idiomatic reverse-projection
10130 // axis onto the third and final M2-OTP-shape closed-set typed
10131 // enum on the caixa surface (the paired per-child restart-
10132 // decision-policy sibling on the same M2 `:supervisor` slot).
10133 for &variant in RestartPolicy::ALL {
10134 let wire = variant.as_str();
10135 assert_eq!(
10136 <RestartPolicy as TryFrom<&str>>::try_from(wire),
10137 Ok(variant),
10138 "TryFrom<&str> impl on RestartPolicy must round-trip \
10139 RestartPolicy::{variant:?}.as_str() = {wire:?} back to \
10140 Ok(RestartPolicy::{variant:?}) — divergence from \
10141 RestartPolicy::from_wire signals a silent detour off \
10142 the substrate-primitive accessor"
10143 );
10144 assert_eq!(
10145 <RestartPolicy as TryFrom<&str>>::try_from(wire).ok(),
10146 RestartPolicy::from_wire(wire),
10147 "TryFrom<&str> ok()-projection on {wire:?} must byte-\
10148 equal RestartPolicy::from_wire on the same input"
10149 );
10150 }
10151 }
10152
10153 #[test]
10154 fn restart_policy_try_from_str_rejects_unknown_byte_strings() {
10155 // Rejection witness on the `impl TryFrom<&str> for
10156 // RestartPolicy` — sweeps a candidate set of byte-strings
10157 // outside the three-arm PascalCase wire accept-set the sibling
10158 // [`RestartPolicy::as_str`] emits and asserts every one lands on
10159 // `Err(())`, so a future accidental widening of the trait impl's
10160 // accept-set (a stray additional
10161 // `_ if s.eq_ignore_ascii_case("Permanent") => Ok(…)` case-fold
10162 // path, a silent inclusion of the kebab-case dispatcher-catalog
10163 // byte-string the pre-existing [`std::str::FromStr`] impl the
10164 // [`gen_platform::FromStrKind`] derive installs parses onto the
10165 // wire axis — which would collide the two-axis
10166 // wire/dispatcher-catalog split the sibling
10167 // [`RestartPolicy::from_wire`] doc block makes load-bearing —
10168 // an English-rebrand or plural-arm silent alias that would widen
10169 // the wire accept-set past the OTP-canonical three) trips at
10170 // caixa-core test time. The candidate set includes the empty
10171 // string, whitespace-only padding, the kebab-case dispatcher-
10172 // catalog byte-strings on the sibling axis (a caller who
10173 // confuses the two axes trips here rather than at a downstream
10174 // consumer's silent reject), a lowercase / uppercase / mixed-case
10175 // fold of each PascalCase arm (a caller who assumes case-fold
10176 // acceptance trips here), leading/trailing whitespace padding,
10177 // the trailing-newline shape, quote-wrapped candidates, and a
10178 // residual set of plausible-but-wrong English rebrand
10179 // candidates. Peer of the sibling
10180 // [`restart_strategy_try_from_str_rejects_unknown_byte_strings`]
10181 // (5b828ed) rejection witness.
10182 let rejected: &[&str] = &[
10183 "",
10184 " ",
10185 "\n",
10186 "\t",
10187 "permanent",
10188 "temporary",
10189 "transient",
10190 "PERMANENT",
10191 "TEMPORARY",
10192 "TRANSIENT",
10193 "Permanents",
10194 "Permanent ",
10195 " Permanent",
10196 " Temporary ",
10197 "Permanent\n",
10198 "Transient\t",
10199 "\"Permanent\"",
10200 "Ephemeral",
10201 "Always",
10202 "Never",
10203 "OnAbnormalExit",
10204 "intrinsic",
10205 "?",
10206 ];
10207 for &input in rejected {
10208 assert_eq!(
10209 <RestartPolicy as TryFrom<&str>>::try_from(input),
10210 Err(()),
10211 "TryFrom<&str> impl on RestartPolicy must reject the \
10212 non-wire byte-string {input:?} — silent acceptance \
10213 signals an accept-set widening off the paired \
10214 RestartPolicy::from_wire resolver"
10215 );
10216 }
10217 }
10218
10219 #[test]
10220 fn restart_policy_try_from_str_and_from_wire_partition_the_accept_set() {
10221 // Cross-axis partition pin: the paired `TryFrom<&str>` and
10222 // `from_wire` reverse projections must resolve identically on
10223 // *every* input, not just the ones [`RestartPolicy::ALL`]
10224 // enumerates. Sweeps a mixed candidate set spanning accepted
10225 // (three-arm PascalCase wire byte-strings) and rejected (kebab-
10226 // case dispatcher-catalog byte-strings, empty, whitespace-
10227 // padded, quoted, English-rebrand candidates) inputs and asserts
10228 // the trait's `Result::ok()` projection byte-equals the method-
10229 // named resolver's `Option<Self>` return-shape on each, locking
10230 // the two paths together by construction so any future detour
10231 // (a stray `try_from` special-case that widens or narrows the
10232 // accept-set outside the paired `from_wire` resolver, an
10233 // accidental swap onto the kebab-case [`std::str::FromStr`]
10234 // impl the [`gen_platform::FromStrKind`] derive installs on the
10235 // sibling dispatcher-catalog axis) trips at caixa-core test
10236 // time. Peer of the sibling
10237 // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
10238 // pin — extends the round-trip discipline onto the M2-OTP-shape
10239 // per-child restart-policy axis.
10240 let candidates: &[&str] = &[
10241 "Permanent",
10242 "Temporary",
10243 "Transient",
10244 "",
10245 "permanent",
10246 "temporary",
10247 "transient",
10248 "PERMANENT",
10249 "unknown",
10250 "Permanent ",
10251 " Permanent",
10252 "\"Permanent\"",
10253 "Ephemeral",
10254 "OnAbnormalExit",
10255 "?",
10256 ];
10257 for &input in candidates {
10258 let via_trait: Option<RestartPolicy> =
10259 <RestartPolicy as TryFrom<&str>>::try_from(input).ok();
10260 let via_method: Option<RestartPolicy> = RestartPolicy::from_wire(input);
10261 assert_eq!(
10262 via_trait, via_method,
10263 "TryFrom<&str> and from_wire must resolve identically on \
10264 input {input:?} — divergence signals the two reverse-\
10265 projection paths have drifted onto different accept-sets"
10266 );
10267 }
10268 }
10269
10270 #[test]
10271 fn restart_policy_from_into_static_str_routes_through_as_str_accessor() {
10272 // Fail-before-pass-after byte-parity pin on the newly lifted
10273 // `impl From<RestartPolicy> for &'static str` — asserts the
10274 // standard-library trait impl and the substrate-primitive
10275 // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
10276 // the same three-arm emit-set across every arm the exhaustive
10277 // [`RestartPolicy::ALL`] slice enumerates. Any future silent
10278 // detour that routes the trait impl through a divergent
10279 // projection (a per-arm inline `match policy { Permanent =>
10280 // "Permanent", … }` re-inlining that opens a compile-time link
10281 // to the un-lifted arm-literal, an accidental swap onto the
10282 // sibling kebab-case [`Self::discriminant`] dispatcher-catalog
10283 // axis that would collide the two-axis wire/catalog split the
10284 // sibling [`RestartPolicy::from_wire`] doc block makes
10285 // load-bearing) trips at caixa-core test time under
10286 // `assert_eq!` rather than at a downstream
10287 // `impl Into<&'static str>`-bound consumer's silent split.
10288 // Sweeps every one of the three arms [`RestartPolicy::ALL`]
10289 // carries so no arm's projection is covered only by the sibling
10290 // method-named `as_str` / [`std::fmt::Display`] / [`AsRef<str>`]
10291 // paths. Materializes the `<&'static str as
10292 // From<RestartPolicy>>::from` output in a `const`-shape binding
10293 // to make the `'static` lifetime promise a build-time invariant
10294 // — a future accidental downgrade of any of the three arms'
10295 // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] constants to a
10296 // non-`&'static str` (a `String::leak()`-produced return, a
10297 // `Box::leak`-cast) trips at caixa-core build time rather than
10298 // at a downstream `'static`-bound consumer. Peer of the sibling
10299 // [`restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
10300 // (523157d) — extends the trait-idiomatic forward-projection
10301 // axis onto the second (and second-of-two-in-M2) closed-set
10302 // typed enum on the caixa surface (the paired per-child
10303 // restart-decision-policy sibling on the same M2 `:supervisor`
10304 // slot).
10305 const PERMANENT: &str = RestartPolicy::Permanent.as_str();
10306 const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
10307 const TRANSIENT: &str = RestartPolicy::Transient.as_str();
10308 for &variant in RestartPolicy::ALL {
10309 let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
10310 let via_method: &'static str = variant.as_str();
10311 assert_eq!(
10312 via_trait, via_method,
10313 "From<RestartPolicy> for &'static str impl must round-trip \
10314 RestartPolicy::{variant:?} to the same lifted \
10315 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str returns — \
10316 divergence signals a silent detour off the substrate-primitive \
10317 accessor"
10318 );
10319 let via_into: &'static str = variant.into();
10320 assert_eq!(
10321 via_into, via_method,
10322 "Into<&'static str>::into on RestartPolicy::{variant:?} must \
10323 byte-equal RestartPolicy::as_str on the same input — the \
10324 blanket-derived Into shape must resolve to the same as_str \
10325 dispatch as the explicit From impl"
10326 );
10327 }
10328 assert_eq!(
10329 [PERMANENT, TEMPORARY, TRANSIENT],
10330 [
10331 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
10332 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
10333 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
10334 ],
10335 "const-context RestartPolicy::as_str must resolve to the three \
10336 lifted SUPERVISOR_CHILD_RESTART_* consts — a future accidental \
10337 downgrade of any arm to a non-const or non-static byte-string \
10338 breaks the `&'static str`-lifetime promise the paired \
10339 From<RestartPolicy> for &'static str impl carries by \
10340 construction"
10341 );
10342 }
10343
10344 #[test]
10345 fn restart_policy_from_into_static_str_and_as_str_partition_the_emit_set() {
10346 // Cross-axis partition pin: the paired trait-idiomatic
10347 // `From<RestartPolicy> for &'static str` forward projection and
10348 // the method-named [`RestartPolicy::as_str`] forward projection
10349 // must resolve identically on *every* arm, not just the ones
10350 // named in the primary byte-parity pin above. Sweeps every
10351 // [`RestartPolicy::ALL`] arm and asserts the trait's `From::from`
10352 // output byte-equals the method-named accessor's return-value on
10353 // each, locking the two forward-projection paths together by
10354 // construction so any future detour (a stray `From` special-case
10355 // that lands on a divergent per-arm literal outside the paired
10356 // `as_str` dispatch, a hypothetical rebrand touching one axis
10357 // without the other) trips at caixa-core test time. Peer of the
10358 // sibling forward-projection partition pin
10359 // [`restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
10360 // (523157d) — extends the round-trip discipline onto the
10361 // second-of-two M2-OTP-shape closed-set typed enum on the caixa
10362 // surface, closing the two-way `Self ↔ &'static str` round-trip
10363 // on the trait-idiomatic pair (`From<Self> for &'static str` +
10364 // `TryFrom<&str> for Self`) as well as the pre-existing method-
10365 // named pair (`as_str` + `from_wire`).
10366 for &variant in RestartPolicy::ALL {
10367 let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
10368 let via_method: &'static str = variant.as_str();
10369 assert_eq!(
10370 via_trait, via_method,
10371 "From<RestartPolicy> for &'static str and \
10372 RestartPolicy::as_str must resolve identically on \
10373 RestartPolicy::{variant:?} — divergence signals the \
10374 two forward-projection paths have drifted onto different \
10375 emit-sets"
10376 );
10377 }
10378 // Round-trip witness: every arm's forward `From` output re-parses
10379 // through the paired trait-idiomatic reverse `TryFrom<&str>` back
10380 // to the original variant. Closes the two-way `RestartPolicy ↔
10381 // &'static str` round-trip on the trait-idiomatic axis pair,
10382 // mirroring the pre-existing method-named `as_str` + `from_wire`
10383 // round-trip on the substrate-primitive axis pair.
10384 for &variant in RestartPolicy::ALL {
10385 let emitted: &'static str = variant.into();
10386 let re_parsed: Result<RestartPolicy, ()> =
10387 <RestartPolicy as TryFrom<&str>>::try_from(emitted);
10388 assert_eq!(
10389 re_parsed,
10390 Ok(variant),
10391 "trait-idiomatic axis pair must round-trip \
10392 RestartPolicy::{variant:?} through `.into::<&'static \
10393 str>()` and back through `TryFrom<&str>` — a break signals \
10394 the forward-emit and reverse-parse axes have drifted onto \
10395 different vocabularies"
10396 );
10397 }
10398 }
10399
10400 #[test]
10401 fn restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
10402 // Fail-before-pass-after byte-parity pin on the newly lifted
10403 // `impl From<&RestartPolicy> for &'static str` — asserts the
10404 // borrowed-input standard-library trait impl and the substrate-
10405 // primitive [`RestartPolicy::as_str`] `pub const fn` accessor
10406 // resolve to the same three-arm emit-set across every arm the
10407 // exhaustive [`RestartPolicy::ALL`] slice enumerates. Rust's
10408 // `From` trait does not auto-derive the borrowed-input sibling
10409 // from a paired owned-input impl (no `impl<T, U> From<&T> for U
10410 // where T: Copy, U: From<T>` blanket in `core`), so the
10411 // borrowed-input axis is a distinct trait-idiomatic surface
10412 // that a `.iter().map(Into::into)` shape over
10413 // [`RestartPolicy::ALL`] (whose iterator yields
10414 // `&RestartPolicy`, not `RestartPolicy`) reaches through this
10415 // impl and no other — the paired owned-input
10416 // [`From<RestartPolicy>`] impl requires an explicit `.copied()`
10417 // / dereference before the trait fires. Materializes the
10418 // `<&'static str as From<&RestartPolicy>>::from` output in a
10419 // `const`-shape binding to make the `'static` lifetime promise
10420 // a build-time invariant.
10421 const PERMANENT: &str = RestartPolicy::Permanent.as_str();
10422 const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
10423 const TRANSIENT: &str = RestartPolicy::Transient.as_str();
10424 for variant in RestartPolicy::ALL {
10425 let via_trait: &'static str = <&'static str as From<&RestartPolicy>>::from(variant);
10426 let via_method: &'static str = variant.as_str();
10427 assert_eq!(
10428 via_trait, via_method,
10429 "From<&RestartPolicy> for &'static str impl must round-trip \
10430 &RestartPolicy::{variant:?} to the same lifted \
10431 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
10432 returns — divergence signals a silent detour off the \
10433 substrate-primitive accessor"
10434 );
10435 let via_into: &'static str = variant.into();
10436 assert_eq!(
10437 via_into, via_method,
10438 "Into<&'static str>::into on &RestartPolicy::{variant:?} \
10439 must byte-equal RestartPolicy::as_str on the same input — \
10440 the blanket-derived Into shape must resolve to the same \
10441 as_str dispatch as the explicit From impl"
10442 );
10443 }
10444 assert_eq!(
10445 [PERMANENT, TEMPORARY, TRANSIENT],
10446 [
10447 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
10448 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
10449 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
10450 ],
10451 "const-context RestartPolicy::as_str must resolve to the three \
10452 lifted SUPERVISOR_CHILD_RESTART_* consts — the borrowed-input \
10453 From<&RestartPolicy> for &'static str impl inherits its \
10454 `'static` lifetime promise from the same accessor the \
10455 owned-input sibling routes through"
10456 );
10457 }
10458
10459 #[test]
10460 fn restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
10461 // Cross-axis partition pin: the paired trait-idiomatic
10462 // owned-input `From<RestartPolicy> for &'static str` (9fb37d0
10463 // campaign-shape) and borrowed-input `From<&RestartPolicy> for
10464 // &'static str` (this lift) forward projections must resolve
10465 // identically on every arm, locking the two input-shape paths
10466 // together so any future detour trips at caixa-core test time.
10467 // Then a witness that a `.iter().map(Into::into)` pipe over
10468 // [`RestartPolicy::ALL`] (whose iterator yields
10469 // `&RestartPolicy`) materializes the three-arm accept-set
10470 // through the borrowed-input axis alone — the exact shape a
10471 // future wasm-operator per-child post-exit restart-decision
10472 // diagnostic line, a future substrate-wide per-arm diagnostic
10473 // column, or a
10474 // `HashMap::<&'static str, RestartPolicy>::from_iter(
10475 // RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
10476 // per-policy lookup reaches through — closing the two-way
10477 // owned/borrowed input-shape symmetry on the forward-projection
10478 // trait-idiomatic axis. Peer of the sibling
10479 // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
10480 // (64aa742) /
10481 // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
10482 // (5ab993a) /
10483 // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
10484 // (807b0b5) /
10485 // [`restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
10486 // (e941836) partition pins on the sibling closed-set typed-enum
10487 // discriminator axes — extends the borrowed-input axis
10488 // discipline onto the second-of-two M2 OTP-shape closed-set
10489 // typed enum on the caixa surface (per-child restart-decision
10490 // policy). Also closes the direct two-way `&Self → &'static
10491 // str → Self` round-trip via the paired [`TryFrom<&str>`] axis
10492 // — unlike the peer [`crate::CaixaKind`] axis pair (whose
10493 // forward `From` emits lowercase Portuguese diagnostic bytes
10494 // while the reverse `TryFrom` parses `PascalCase` wire bytes,
10495 // forcing the round-trip through an intermediate wire-vocab
10496 // hop), the [`RestartPolicy::as_str`] emit and
10497 // [`RestartPolicy::from_wire`] parse share the same
10498 // `PascalCase` vocabulary by construction, so the borrowed-
10499 // input forward axis and the reverse axis compose directly.
10500 for &variant in RestartPolicy::ALL {
10501 let owned: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
10502 let borrowed: &'static str = <&'static str as From<&RestartPolicy>>::from(&variant);
10503 assert_eq!(
10504 owned, borrowed,
10505 "From<RestartPolicy> and From<&RestartPolicy> for \
10506 &'static str must resolve identically on \
10507 RestartPolicy::{variant:?} — divergence signals the \
10508 owned-input and borrowed-input forward-projection paths \
10509 have drifted onto different emit-sets"
10510 );
10511 }
10512 let via_iter: Vec<&'static str> = RestartPolicy::ALL.iter().map(Into::into).collect();
10513 let via_method: Vec<&'static str> = RestartPolicy::ALL.iter().map(|p| p.as_str()).collect();
10514 assert_eq!(
10515 via_iter, via_method,
10516 "`.iter().map(Into::into)` over RestartPolicy::ALL must \
10517 byte-equal `.iter().map(|p| p.as_str())` on every arm — the \
10518 borrowed-input `From<&RestartPolicy> for &'static str` axis \
10519 is what makes the `.iter().map(Into::into)` shape route \
10520 through the substrate-primitive `RestartPolicy::as_str` \
10521 accessor rather than through a per-call-site `.copied()` / \
10522 dereference detour"
10523 );
10524 for variant in RestartPolicy::ALL {
10525 let emitted: &'static str = variant.into();
10526 let re_parsed: Result<RestartPolicy, ()> =
10527 <RestartPolicy as TryFrom<&str>>::try_from(emitted);
10528 assert_eq!(
10529 re_parsed,
10530 Ok(*variant),
10531 "trait-idiomatic borrowed-input forward-projection + \
10532 reverse-projection axis pair must round-trip \
10533 &RestartPolicy::{variant:?} through `.into::<&'static \
10534 str>()` (via the borrowed-input axis) and back through \
10535 `TryFrom<&str>` — a break signals the borrowed-input \
10536 forward-emit and reverse-parse axes have drifted onto \
10537 different vocabularies"
10538 );
10539 }
10540 }
10541
10542 #[test]
10543 fn restart_policy_from_into_owned_string_routes_through_as_str_accessor() {
10544 // Fail-before-pass-after byte-parity pin on the newly lifted
10545 // `impl From<RestartPolicy> for String` — asserts the
10546 // owned-`String`-returning standard-library trait impl and the
10547 // substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
10548 // accessor resolve to the same three-arm emit-set across every
10549 // arm the exhaustive [`RestartPolicy::ALL`] slice enumerates.
10550 // Rust's standard library does not carry a blanket
10551 // `impl<T: AsRef<str>> From<T> for String` (nor an
10552 // `impl<T: fmt::Display> From<T> for String`), so the
10553 // owned-`String` forward-projection axis is a distinct
10554 // trait-idiomatic surface that a `let key: String =
10555 // policy.into();`-shaped call site reaches through this impl
10556 // and no other — the paired sibling `From<RestartPolicy> for
10557 // &'static str` impl forces every owned-`String` call site
10558 // through an explicit `.to_owned()` / `String::from`
10559 // restatement. Peer of the first-mover
10560 // [`restart_strategy_from_into_owned_string_routes_through_as_str_accessor`]
10561 // (7baa18a) — extends the trait-idiomatic owned-`String`
10562 // forward-projection axis onto the second-of-two M2 OTP-shape
10563 // closed-set typed enums on the caixa surface (per-child
10564 // restart-decision-policy sibling on the same M2 `:supervisor`
10565 // slot).
10566 for &variant in RestartPolicy::ALL {
10567 let via_trait: String = <String as From<RestartPolicy>>::from(variant);
10568 let via_method: &'static str = variant.as_str();
10569 assert_eq!(
10570 via_trait.as_str(),
10571 via_method,
10572 "From<RestartPolicy> for String impl must round-trip \
10573 RestartPolicy::{variant:?} to the same lifted \
10574 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
10575 returns — divergence signals a silent detour off the \
10576 substrate-primitive accessor"
10577 );
10578 let via_into: String = variant.into();
10579 assert_eq!(
10580 via_into.as_str(),
10581 via_method,
10582 "Into<String>::into on RestartPolicy::{variant:?} must \
10583 byte-equal RestartPolicy::as_str on the same input — the \
10584 blanket-derived Into shape must resolve to the same as_str \
10585 dispatch as the explicit From impl"
10586 );
10587 }
10588 }
10589
10590 #[test]
10591 fn restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm() {
10592 // Cross-axis partition pin: the paired trait-idiomatic
10593 // owned-`String` `From<RestartPolicy> for String` (this lift)
10594 // and owned-`&'static str` `From<RestartPolicy> for &'static
10595 // str` (9fb37d0) forward projections must resolve identically
10596 // on every arm, locking the two return-type-shape paths
10597 // together so any future detour trips at caixa-core test time.
10598 // Also byte-parity witness against the sibling
10599 // [`ToString::to_string`] surface routed through
10600 // [`std::fmt::Display`] — the three owned-heap-string paths
10601 // (`.into::<String>()`, `String::from`, `.to_string()`) must
10602 // resolve identically on every arm so a future consumer that
10603 // picks any of the three lands on the same lifted
10604 // SUPERVISOR_CHILD_RESTART_* const. Then a `.iter().copied()
10605 // .map(String::from)` pipe witness over [`RestartPolicy::ALL`]
10606 // that materializes the three-arm accept-set through the
10607 // owned-`String` axis alone — the exact shape a future
10608 // wasm-operator per-child post-exit restart-decision
10609 // diagnostic line composer or a
10610 // `HashMap::<String, RestartPolicy>::from_iter(
10611 // RestartPolicy::ALL.iter().copied().map(|p| (p.into(), p)))`-style
10612 // owned-key per-policy lookup reaches through — closing the
10613 // owned-`String` forward-projection axis's iterator-pipe
10614 // shape. Then a direct round-trip witness through the paired
10615 // trait-idiomatic reverse [`TryFrom<&str>`] axis on the
10616 // owned-`String`'s [`String::as_str`] borrow that closes the
10617 // two-way `Self → String → Self` round-trip on the trait-
10618 // idiomatic owned-`String` forward + reverse axis pair —
10619 // unlike the peer [`crate::CaixaKind`] axis pair (whose
10620 // forward `From` emits lowercase Portuguese diagnostic bytes
10621 // while the reverse `TryFrom` parses `PascalCase` wire bytes,
10622 // forcing the round-trip through an intermediate wire-vocab
10623 // hop), the [`RestartPolicy::as_str`] emit and
10624 // [`RestartPolicy::from_wire`] parse share the same
10625 // `PascalCase` vocabulary by construction, so the owned-
10626 // `String` forward axis and the reverse axis compose directly.
10627 for &variant in RestartPolicy::ALL {
10628 let owned_string: String = <String as From<RestartPolicy>>::from(variant);
10629 let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
10630 assert_eq!(
10631 owned_string.as_str(),
10632 owned_static,
10633 "From<RestartPolicy> for String and From<RestartPolicy> \
10634 for &'static str must resolve identically on \
10635 RestartPolicy::{variant:?} — divergence signals the \
10636 owned-`String` and owned-`&'static str` forward-projection \
10637 return-type-shape paths have drifted onto different \
10638 emit-sets"
10639 );
10640 let via_to_string: String = variant.to_string();
10641 assert_eq!(
10642 owned_string, via_to_string,
10643 "From<RestartPolicy> for String must byte-equal \
10644 RestartPolicy::to_string on RestartPolicy::{variant:?} — \
10645 divergence signals the trait-idiomatic owned-`String` \
10646 forward-projection axis and the ToString-through-Display \
10647 axis have drifted onto different emit-sets"
10648 );
10649 }
10650 let via_iter: Vec<String> = RestartPolicy::ALL
10651 .iter()
10652 .copied()
10653 .map(String::from)
10654 .collect();
10655 let via_method: Vec<String> = RestartPolicy::ALL
10656 .iter()
10657 .map(|p| p.as_str().to_owned())
10658 .collect();
10659 assert_eq!(
10660 via_iter, via_method,
10661 "`.iter().copied().map(String::from)` over RestartPolicy::ALL \
10662 must byte-equal `.iter().map(|p| p.as_str().to_owned())` on \
10663 every arm — the owned-`String` `From<RestartPolicy> for \
10664 String` axis is what makes the `String::from` composition \
10665 route through the substrate-primitive `RestartPolicy::as_str` \
10666 accessor rather than through a per-call-site `.to_owned()` / \
10667 `String::from(policy.as_str())` detour"
10668 );
10669 for &variant in RestartPolicy::ALL {
10670 let emitted: String = variant.into();
10671 let re_parsed: Result<RestartPolicy, ()> =
10672 <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
10673 assert_eq!(
10674 re_parsed,
10675 Ok(variant),
10676 "trait-idiomatic owned-`String` forward-projection + \
10677 reverse-projection axis pair must round-trip \
10678 RestartPolicy::{variant:?} through `.into::<String>()` \
10679 and back through `TryFrom<&str>` on the owned-`String`'s \
10680 String::as_str borrow — a break signals the owned-`String` \
10681 forward-emit and reverse-parse axes have drifted onto \
10682 different vocabularies"
10683 );
10684 }
10685 }
10686
10687 #[test]
10688 fn restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
10689 // Fail-before-pass-after byte-parity pin on the newly lifted
10690 // `impl From<&RestartPolicy> for String` — asserts the
10691 // borrowed-input owned-`String`-returning standard-library
10692 // trait impl and the substrate-primitive
10693 // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
10694 // the same three-arm emit-set across every arm the exhaustive
10695 // [`RestartPolicy::ALL`] slice enumerates. Rust's standard
10696 // library does not carry a blanket `impl<T: AsRef<str>>
10697 // From<&T> for String` (nor an `impl<T: fmt::Display> From<&T>
10698 // for String`), so the borrowed-input owned-`String` forward-
10699 // projection axis is a distinct trait-idiomatic surface that a
10700 // `let key: String = (&policy).into();`-shaped call site
10701 // reaches through this impl and no other — the paired sibling
10702 // `From<RestartPolicy> for String` impl forces every borrowed-
10703 // input call site through an explicit `Copy` deref
10704 // (`String::from(*policy)`) or an `.as_str().to_owned()` /
10705 // `.to_string()` detour. Peer of the first-mover
10706 // [`restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
10707 // (579385f) — extends the trait-idiomatic borrowed-input
10708 // owned-`String` forward-projection axis onto the second-of-
10709 // two M2 OTP-shape closed-set typed enums on the caixa surface
10710 // (per-child restart-decision-policy sibling on the same M2
10711 // `:supervisor` slot).
10712 for &variant in RestartPolicy::ALL {
10713 let via_trait: String = <String as From<&RestartPolicy>>::from(&variant);
10714 let via_method: &'static str = variant.as_str();
10715 assert_eq!(
10716 via_trait.as_str(),
10717 via_method,
10718 "From<&RestartPolicy> for String impl must round-trip \
10719 &RestartPolicy::{variant:?} to the same lifted \
10720 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
10721 returns — divergence signals a silent detour off the \
10722 substrate-primitive accessor"
10723 );
10724 let via_into: String = (&variant).into();
10725 assert_eq!(
10726 via_into.as_str(),
10727 via_method,
10728 "Into<String>::into on &RestartPolicy::{variant:?} must \
10729 byte-equal RestartPolicy::as_str on the same input — \
10730 the blanket-derived Into shape must resolve to the \
10731 same as_str dispatch as the explicit From impl"
10732 );
10733 }
10734 }
10735
10736 #[test]
10737 fn restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
10738 // Cross-axis partition pin: the newly lifted trait-idiomatic
10739 // borrowed-input owned-`String` `From<&RestartPolicy> for
10740 // String` (this lift), the paired owned-input owned-`String`
10741 // `From<RestartPolicy> for String` (7851725), the paired
10742 // borrowed-input owned-`&'static str` `From<&RestartPolicy>
10743 // for &'static str` (842c7f3), and the paired owned-input
10744 // owned-`&'static str` `From<RestartPolicy> for &'static str`
10745 // (9fb37d0) — every corner of the `{Self, &Self} × {&'static
10746 // str, String}` 2×2 trait-idiomatic projection family — must
10747 // resolve identically on every arm, locking the four
10748 // return-shape × input-shape paths together so any future
10749 // detour trips at caixa-core test time. Also byte-parity
10750 // witness against the sibling [`ToString::to_string`] surface
10751 // routed through [`std::fmt::Display`] and a direct round-trip
10752 // witness through the paired trait-idiomatic reverse
10753 // [`TryFrom<&str>`] axis on the owned-`String`'s
10754 // [`String::as_str`] borrow that closes the two-way
10755 // `&Self → String → Self` round-trip on the trait-idiomatic
10756 // borrowed-input owned-`String` forward + reverse axis pair.
10757 // Peer of the first-mover
10758 // [`restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
10759 // (579385f) — closes the whole `{Self, &Self} × {&'static str,
10760 // String}` 2×2 projection corner on both M2 OTP-shape sibling
10761 // peers.
10762 for &variant in RestartPolicy::ALL {
10763 let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
10764 let owned_string: String = <String as From<RestartPolicy>>::from(variant);
10765 let borrowed_static: &'static str =
10766 <&'static str as From<&RestartPolicy>>::from(&variant);
10767 let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
10768 assert_eq!(
10769 borrowed_string, owned_string,
10770 "From<&RestartPolicy> for String and From<RestartPolicy> \
10771 for String must resolve identically on \
10772 RestartPolicy::{variant:?} — divergence signals the \
10773 borrowed-input and owned-input owned-`String` \
10774 forward-projection input-shape paths have drifted onto \
10775 different emit-sets"
10776 );
10777 assert_eq!(
10778 borrowed_string.as_str(),
10779 borrowed_static,
10780 "From<&RestartPolicy> for String and From<&RestartPolicy> \
10781 for &'static str must resolve identically on \
10782 RestartPolicy::{variant:?} — divergence signals the \
10783 borrowed-input `&'static str` and owned-`String` \
10784 return-shape paths have drifted onto different \
10785 emit-sets"
10786 );
10787 assert_eq!(
10788 borrowed_string.as_str(),
10789 owned_static,
10790 "From<&RestartPolicy> for String and From<RestartPolicy> \
10791 for &'static str must resolve identically on \
10792 RestartPolicy::{variant:?} — divergence signals a \
10793 break in the diagonal corner of the {{Self, &Self}} × \
10794 {{&'static str, String}} 2×2 trait-idiomatic \
10795 projection family"
10796 );
10797 let via_to_string: String = variant.to_string();
10798 assert_eq!(
10799 borrowed_string, via_to_string,
10800 "From<&RestartPolicy> for String must byte-equal \
10801 RestartPolicy::to_string on RestartPolicy::{variant:?} \
10802 — divergence signals the trait-idiomatic borrowed-input \
10803 owned-`String` forward-projection axis and the \
10804 ToString-through-Display axis have drifted onto \
10805 different emit-sets"
10806 );
10807 }
10808 let via_iter: Vec<String> = RestartPolicy::ALL.iter().map(String::from).collect();
10809 let via_method: Vec<String> = RestartPolicy::ALL
10810 .iter()
10811 .map(|p| p.as_str().to_owned())
10812 .collect();
10813 assert_eq!(
10814 via_iter, via_method,
10815 "`.iter().map(String::from)` over RestartPolicy::ALL — a \
10816 call site whose iteration axis holds `&RestartPolicy` by \
10817 construction — must byte-equal `.iter().map(|p| \
10818 p.as_str().to_owned())` on every arm — the borrowed-input \
10819 owned-`String` `From<&RestartPolicy> for String` axis is \
10820 what makes the `String::from` composition route through \
10821 the substrate-primitive `RestartPolicy::as_str` accessor \
10822 without a spurious `Copy` deref (which would only be \
10823 reachable through the owned-input `From<RestartPolicy> \
10824 for String` axis by first calling `.copied()` on the \
10825 iterator)"
10826 );
10827 for &variant in RestartPolicy::ALL {
10828 let emitted: String = (&variant).into();
10829 let re_parsed: Result<RestartPolicy, ()> =
10830 <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
10831 assert_eq!(
10832 re_parsed,
10833 Ok(variant),
10834 "trait-idiomatic borrowed-input owned-`String` \
10835 forward-projection + reverse-projection axis pair must \
10836 round-trip &RestartPolicy::{variant:?} through \
10837 `.into::<String>()` on the borrowed-input surface and \
10838 back through `TryFrom<&str>` on the owned-`String`'s \
10839 String::as_str borrow — a break signals the \
10840 borrowed-input owned-`String` forward-emit and \
10841 reverse-parse axes have drifted onto different \
10842 vocabularies"
10843 );
10844 }
10845 }
10846
10847 #[test]
10848 fn restart_policy_from_into_static_cow_str_routes_through_as_str_accessor() {
10849 // Fail-before-pass-after byte-parity pin on the newly lifted
10850 // `impl From<RestartPolicy> for std::borrow::Cow<'static, str>` —
10851 // asserts the standard-library trait impl and the substrate-
10852 // primitive [`super::RestartPolicy::as_str`] `pub const fn`
10853 // accessor resolve to the same three-arm emit-set across every
10854 // arm the exhaustive [`super::RestartPolicy::ALL`] slice
10855 // enumerates. Rust's standard library does not carry a blanket
10856 // `impl<T: AsRef<str>> From<T> for Cow<'static, str>` (nor an
10857 // `impl<T: fmt::Display> From<T> for Cow<'static, str>`), so
10858 // the `Cow<'static, str>` forward-projection axis is a
10859 // distinct trait-idiomatic surface that a
10860 // `let key: Cow<'static, str> = policy.into();`-shaped call
10861 // site reaches through this impl and no other — the paired
10862 // sibling `From<RestartPolicy> for &'static str` and
10863 // `From<RestartPolicy> for String` impls force every
10864 // `Cow<'static, str>`-parameterized call site through a
10865 // `Cow::Borrowed(policy.as_str())` /
10866 // `Cow::Owned(policy.to_string())` composition whose type
10867 // bounds have no compile-time link back to the substrate
10868 // primitive.
10869 //
10870 // Also asserts the projection lands on the zero-alloc
10871 // [`std::borrow::Cow::Borrowed`] arm (not the
10872 // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
10873 // [`super::RestartPolicy::as_str`] accessor's `&'static str`
10874 // return lifetime by construction makes the borrowed arm the
10875 // type-correct projection with no runtime allocation. Any
10876 // future silent detour that routes the impl through the owned
10877 // arm (an accidental `Cow::Owned(policy.to_string())` rewrite
10878 // that would allocate on every call site where the
10879 // `&'static str` return of [`super::RestartPolicy::as_str`]
10880 // makes the zero-alloc borrowed projection type-correct) trips
10881 // at caixa-core test time under the
10882 // [`std::borrow::Cow::Borrowed`] discriminator witness rather
10883 // than at a downstream `Cow<'static, str>`-bound consumer's
10884 // silent allocation.
10885 //
10886 // Second peer on the substrate-wide trait-idiomatic
10887 // [`std::borrow::Cow<'static, str>`] forward-projection family
10888 // to extend the axis off the top-level [`super::CaixaKind`]
10889 // enum (99c1735 owned-input, d45c409 borrowed-input) onto the
10890 // second (and second-of-two-in-M2) M2 OTP-shape closed-set
10891 // fieldless typed enum peer on the caixa surface — closes the
10892 // M2 OTP-shape tier of the campaign on the owned-input axis
10893 // (both sibling peers, `RestartStrategy` and `RestartPolicy`,
10894 // now carry the owned-input Cow<'static, str> forward
10895 // projection).
10896 for &variant in RestartPolicy::ALL {
10897 let via_trait: std::borrow::Cow<'static, str> =
10898 <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
10899 let via_method: &'static str = variant.as_str();
10900 assert_eq!(
10901 via_trait.as_ref(),
10902 via_method,
10903 "From<RestartPolicy> for Cow<'static, str> impl must \
10904 round-trip RestartPolicy::{variant:?} to the same \
10905 lifted SUPERVISOR_CHILD_RESTART_* const \
10906 RestartPolicy::as_str returns — divergence signals a \
10907 silent detour off the substrate-primitive accessor"
10908 );
10909 assert!(
10910 matches!(via_trait, std::borrow::Cow::Borrowed(_)),
10911 "From<RestartPolicy> for Cow<'static, str> impl must \
10912 land on the zero-alloc Cow::Borrowed arm on \
10913 RestartPolicy::{variant:?} — a Cow::Owned outcome \
10914 signals the projection has silently allocated where \
10915 the substrate-primitive RestartPolicy::as_str \
10916 `&'static str` return makes the borrowed arm the \
10917 type-correct projection"
10918 );
10919 let via_into: std::borrow::Cow<'static, str> = variant.into();
10920 assert_eq!(
10921 via_into.as_ref(),
10922 via_method,
10923 "Into<Cow<'static, str>>::into on \
10924 RestartPolicy::{variant:?} must byte-equal \
10925 RestartPolicy::as_str on the same input — the \
10926 blanket-derived Into shape must resolve to the same \
10927 as_str dispatch as the explicit From impl"
10928 );
10929 assert!(
10930 matches!(via_into, std::borrow::Cow::Borrowed(_)),
10931 "Into<Cow<'static, str>>::into on \
10932 RestartPolicy::{variant:?} must land on the \
10933 zero-alloc Cow::Borrowed arm — the blanket-derived \
10934 Into shape must resolve to the same Cow::Borrowed \
10935 dispatch as the explicit From impl"
10936 );
10937 }
10938 }
10939
10940 #[test]
10941 fn restart_policy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
10942 // Cross-axis partition pin: the newly lifted trait-idiomatic
10943 // `From<RestartPolicy> for std::borrow::Cow<'static, str>`
10944 // (this lift), the paired owned-input `From<RestartPolicy>
10945 // for &'static str` (9fb37d0), and the paired owned-input
10946 // `From<RestartPolicy> for String` (7851725) forward
10947 // projections must resolve identically on every arm, locking
10948 // the three return-shape paths together by construction so any
10949 // future detour trips at caixa-core test time. Also byte-parity
10950 // witness against the sibling [`ToString::to_string`] surface
10951 // routed through [`std::fmt::Display`] — every owned-heap-
10952 // string path (the `Cow::Owned` promotion of this axis's
10953 // `.into_owned()`, `From<RestartPolicy> for String`, and
10954 // `.to_string()`) resolves to the same lifted
10955 // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const per arm.
10956 //
10957 // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
10958 // witness over [`super::RestartPolicy::ALL`] that
10959 // materializes the three-arm accept-set through the
10960 // [`std::borrow::Cow<'static, str>`] axis alone — the exact
10961 // shape a future `axum::response::IntoResponse` per-policy
10962 // rejection-body composer, a future M4 admission-webhook
10963 // per-policy rejection-reason emitter whose typing rules out
10964 // the sibling [`AsRef<str>`] borrowed return, or a future
10965 // substrate-wide per-policy diagnostic surface that binds
10966 // through a [`Cow<'static, str>`] boundary reaches through.
10967 // The pipe witness also pins the zero-alloc discipline: every
10968 // element in the collected vector satisfies the
10969 // [`std::borrow::Cow::Borrowed`] arm predicate, so a future
10970 // accidental silent-allocation regression on the pipe's
10971 // iteration axis is a caixa-core-test-time failure. Peer of
10972 // the first-mover
10973 // [`restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
10974 // (7dd28b3) on the sibling M2 OTP-shape sibling-restart axis
10975 // — closes the whole owned-input `Cow<'static, str>` +
10976 // paired `{&'static str, String}` cross-axis-parity corner on
10977 // both M2 OTP-shape sibling peers.
10978 for &variant in RestartPolicy::ALL {
10979 let via_cow: std::borrow::Cow<'static, str> =
10980 <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
10981 let via_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
10982 let via_string: String = <String as From<RestartPolicy>>::from(variant);
10983 assert_eq!(
10984 via_cow.as_ref(),
10985 via_static,
10986 "From<RestartPolicy> for Cow<'static, str> and \
10987 From<RestartPolicy> for &'static str must resolve \
10988 identically on RestartPolicy::{variant:?} — \
10989 divergence signals the Cow<'static, str> and \
10990 &'static str return-shape paths have drifted onto \
10991 different emit-sets"
10992 );
10993 assert_eq!(
10994 via_cow.as_ref(),
10995 via_string.as_str(),
10996 "From<RestartPolicy> for Cow<'static, str> and \
10997 From<RestartPolicy> for String must resolve \
10998 identically on RestartPolicy::{variant:?} — \
10999 divergence signals the Cow<'static, str> and String \
11000 return-shape paths have drifted onto different \
11001 emit-sets"
11002 );
11003 let via_to_string: String = variant.to_string();
11004 assert_eq!(
11005 via_cow.as_ref(),
11006 via_to_string.as_str(),
11007 "From<RestartPolicy> for Cow<'static, str> must \
11008 byte-equal RestartPolicy::to_string on \
11009 RestartPolicy::{variant:?} — divergence signals the \
11010 trait-idiomatic Cow<'static, str> forward-projection \
11011 axis and the ToString-through-Display axis have \
11012 drifted onto different emit-sets"
11013 );
11014 }
11015 let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
11016 .iter()
11017 .copied()
11018 .map(std::borrow::Cow::from)
11019 .collect();
11020 let via_method: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
11021 .iter()
11022 .map(|p| std::borrow::Cow::Borrowed(p.as_str()))
11023 .collect();
11024 assert_eq!(
11025 via_iter, via_method,
11026 "`.iter().copied().map(Cow::from)` over \
11027 RestartPolicy::ALL must byte-equal `.iter().map(|p| \
11028 Cow::Borrowed(p.as_str()))` on every arm — the \
11029 trait-idiomatic `From<RestartPolicy> for Cow<'static, \
11030 str>` axis is what makes the `Cow::from` composition \
11031 route through the substrate-primitive \
11032 `RestartPolicy::as_str` accessor with the zero-alloc \
11033 Cow::Borrowed arm by construction, rather than a \
11034 per-call-site `Cow::Owned(policy.to_string())` \
11035 allocation"
11036 );
11037 for cow in &via_iter {
11038 assert!(
11039 matches!(cow, std::borrow::Cow::Borrowed(_)),
11040 "every element of the \
11041 .iter().copied().map(Cow::from) pipe over \
11042 RestartPolicy::ALL must land on the zero-alloc \
11043 Cow::Borrowed arm — a Cow::Owned outcome on any arm \
11044 signals the pipe's iteration axis has silently \
11045 allocated where the substrate-primitive \
11046 RestartPolicy::as_str `&'static str` return makes \
11047 the borrowed arm the type-correct projection"
11048 );
11049 }
11050 }
11051
11052 #[test]
11053 fn restart_policy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
11054 // Fail-before-pass-after byte-parity pin on the newly lifted
11055 // `impl From<&RestartPolicy> for std::borrow::Cow<'static, str>` —
11056 // asserts the borrowed-input standard-library trait impl and
11057 // the substrate-primitive [`super::RestartPolicy::as_str`]
11058 // `pub const fn` accessor resolve to the same three-arm emit-
11059 // set across every arm the exhaustive
11060 // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
11061 // standard library does not carry a blanket
11062 // `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor a
11063 // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
11064 // the borrowed-input `Cow<'static, str>` forward-projection
11065 // axis is a distinct trait-idiomatic surface that a
11066 // `let key: Cow<'static, str> = (&policy).into();`-shaped
11067 // call site or a
11068 // `RestartPolicy::ALL.iter().map(Cow::from)`-shaped pipe
11069 // reaches through this impl and no other — the paired owned-
11070 // input `From<RestartPolicy> for Cow<'static, str>` impl
11071 // (0612398) forces every borrowed-input call site through an
11072 // explicit `Copy` deref (`Cow::from(*policy)`) or a
11073 // `Cow::Borrowed(policy.as_str())` open-code whose type
11074 // bounds have no compile-time link back to the substrate
11075 // primitive.
11076 //
11077 // Also asserts the projection lands on the zero-alloc
11078 // [`std::borrow::Cow::Borrowed`] arm (not the
11079 // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
11080 // [`super::RestartPolicy::as_str`] accessor's `&'static str`
11081 // return lifetime by construction makes the borrowed arm the
11082 // type-correct projection with no runtime allocation on the
11083 // borrowed-input surface just as on the paired owned-input
11084 // surface.
11085 //
11086 // Closes the `{Self, &Self}` input-shape corner on the M2
11087 // OTP-shape per-child-restart [`Cow<'static, str>`] axis on
11088 // the second-of-two-in-M2 closed-set fieldless typed enum peer
11089 // on the caixa surface (`:supervisor :children :restart`),
11090 // exactly as d45c409 closed it on the top-level
11091 // [`super::CaixaKind`] one commit after the owning half
11092 // (99c1735) landed and as 9b3e4b3 closed it on the sibling
11093 // M2 OTP-shape [`super::RestartStrategy`] one commit after
11094 // (7dd28b3) landed. This lift closes the whole M2 OTP-shape
11095 // tier of the substrate-wide Cow<'static, str> forward-
11096 // projection campaign on both input-shape corners
11097 // ({Self, &Self}) of both M2 OTP-shape sibling peers.
11098 for &variant in RestartPolicy::ALL {
11099 let via_trait: std::borrow::Cow<'static, str> =
11100 <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
11101 let via_method: &'static str = variant.as_str();
11102 assert_eq!(
11103 via_trait.as_ref(),
11104 via_method,
11105 "From<&RestartPolicy> for Cow<'static, str> impl must \
11106 round-trip &RestartPolicy::{variant:?} to the same \
11107 lifted SUPERVISOR_CHILD_RESTART_* const \
11108 RestartPolicy::as_str returns — divergence signals a \
11109 silent detour off the substrate-primitive accessor"
11110 );
11111 assert!(
11112 matches!(via_trait, std::borrow::Cow::Borrowed(_)),
11113 "From<&RestartPolicy> for Cow<'static, str> impl must \
11114 land on the zero-alloc Cow::Borrowed arm on \
11115 &RestartPolicy::{variant:?} — a Cow::Owned outcome \
11116 signals the projection has silently allocated where \
11117 the substrate-primitive RestartPolicy::as_str \
11118 `&'static str` return makes the borrowed arm the \
11119 type-correct projection"
11120 );
11121 let via_into: std::borrow::Cow<'static, str> = (&variant).into();
11122 assert_eq!(
11123 via_into.as_ref(),
11124 via_method,
11125 "Into<Cow<'static, str>>::into on \
11126 &RestartPolicy::{variant:?} must byte-equal \
11127 RestartPolicy::as_str on the same input — the \
11128 blanket-derived Into shape must resolve to the same \
11129 as_str dispatch as the explicit From impl"
11130 );
11131 assert!(
11132 matches!(via_into, std::borrow::Cow::Borrowed(_)),
11133 "Into<Cow<'static, str>>::into on \
11134 &RestartPolicy::{variant:?} must land on the \
11135 zero-alloc Cow::Borrowed arm — the blanket-derived \
11136 Into shape must resolve to the same Cow::Borrowed \
11137 dispatch as the explicit From impl"
11138 );
11139 }
11140 }
11141
11142 #[test]
11143 fn restart_policy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
11144 // Cross-axis partition pin: the newly lifted trait-idiomatic
11145 // borrowed-input `From<&RestartPolicy> for
11146 // std::borrow::Cow<'static, str>` (this lift), the paired
11147 // owned-input `From<RestartPolicy> for
11148 // std::borrow::Cow<'static, str>` (0612398), the paired
11149 // borrowed-input owned-`&'static str` `From<&RestartPolicy>
11150 // for &'static str`, and the paired borrowed-input owned-
11151 // `String` `From<&RestartPolicy> for String` must resolve
11152 // identically on every arm, locking the four
11153 // return-shape × input-shape paths together by construction so
11154 // any future detour trips at caixa-core test time. Also byte-
11155 // parity witness against the sibling [`ToString::to_string`]
11156 // surface routed through [`std::fmt::Display`] — every owned-
11157 // heap-string path (this axis's `.into_owned()` promotion, the
11158 // paired [`From<&RestartPolicy> for String`], and
11159 // `.to_string()`) resolves to the same lifted
11160 // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const per arm.
11161 //
11162 // Then a `.iter().map(std::borrow::Cow::from)` pipe witness
11163 // over [`super::RestartPolicy::ALL`] — whose iterator yields
11164 // `&RestartPolicy` by construction, so the borrowed-input
11165 // [`Cow<'static, str>`] axis is what routes the pipe through
11166 // the substrate-primitive [`super::RestartPolicy::as_str`]
11167 // accessor without a spurious [`Copy`] deref (which would only
11168 // be reachable through the owned-input
11169 // [`From<RestartPolicy> for Cow<'static, str>`] axis by first
11170 // calling `.copied()` on the iterator). The pipe witness also
11171 // pins the zero-alloc discipline: every element in the
11172 // collected vector satisfies the [`std::borrow::Cow::Borrowed`]
11173 // arm predicate, so a future accidental silent-allocation
11174 // regression on the pipe's iteration axis is a caixa-core-
11175 // test-time failure. Peer of the sibling
11176 // [`restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
11177 // (9b3e4b3) on the M2 OTP-shape sibling-restart axis — closes
11178 // the whole borrowed-input `Cow<'static, str>` +
11179 // paired `{&'static str, String}` cross-axis-parity corner on
11180 // both M2 OTP-shape sibling peers.
11181 for &policy in RestartPolicy::ALL {
11182 let borrowed_cow: std::borrow::Cow<'static, str> =
11183 <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&policy);
11184 let owned_cow: std::borrow::Cow<'static, str> =
11185 <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(policy);
11186 let borrowed_static: &'static str =
11187 <&'static str as From<&RestartPolicy>>::from(&policy);
11188 let borrowed_string: String = <String as From<&RestartPolicy>>::from(&policy);
11189 assert_eq!(
11190 borrowed_cow, owned_cow,
11191 "From<&RestartPolicy> for Cow<'static, str> and \
11192 From<RestartPolicy> for Cow<'static, str> must \
11193 resolve identically on RestartPolicy::{policy:?} — \
11194 divergence signals the borrowed-input and owned-input \
11195 Cow<'static, str> forward-projection input-shape \
11196 paths have drifted onto different emit-sets"
11197 );
11198 assert_eq!(
11199 borrowed_cow.as_ref(),
11200 borrowed_static,
11201 "From<&RestartPolicy> for Cow<'static, str> and \
11202 From<&RestartPolicy> for &'static str must resolve \
11203 identically on RestartPolicy::{policy:?} — \
11204 divergence signals the borrowed-input Cow<'static, \
11205 str> and &'static str return-shape paths have drifted \
11206 onto different emit-sets"
11207 );
11208 assert_eq!(
11209 borrowed_cow.as_ref(),
11210 borrowed_string.as_str(),
11211 "From<&RestartPolicy> for Cow<'static, str> and \
11212 From<&RestartPolicy> for String must resolve \
11213 identically on RestartPolicy::{policy:?} — \
11214 divergence signals the borrowed-input Cow<'static, \
11215 str> and owned-`String` return-shape paths have \
11216 drifted onto different emit-sets"
11217 );
11218 let via_to_string: String = policy.to_string();
11219 assert_eq!(
11220 borrowed_cow.as_ref(),
11221 via_to_string.as_str(),
11222 "From<&RestartPolicy> for Cow<'static, str> must \
11223 byte-equal RestartPolicy::to_string on \
11224 RestartPolicy::{policy:?} — divergence signals \
11225 the trait-idiomatic borrowed-input Cow<'static, str> \
11226 forward-projection axis and the ToString-through-\
11227 Display axis have drifted onto different emit-sets"
11228 );
11229 }
11230 let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
11231 .iter()
11232 .map(std::borrow::Cow::from)
11233 .collect();
11234 let via_method: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
11235 .iter()
11236 .map(|p| std::borrow::Cow::Borrowed(p.as_str()))
11237 .collect();
11238 assert_eq!(
11239 via_iter, via_method,
11240 "`.iter().map(Cow::from)` over RestartPolicy::ALL — a \
11241 call site whose iteration axis holds `&RestartPolicy` \
11242 by construction — must byte-equal `.iter().map(|p| \
11243 Cow::Borrowed(p.as_str()))` on every arm — the borrowed-\
11244 input Cow<'static, str> `From<&RestartPolicy> for \
11245 Cow<'static, str>` axis is what makes the `Cow::from` \
11246 composition route through the substrate-primitive \
11247 `RestartPolicy::as_str` accessor with the zero-alloc \
11248 Cow::Borrowed arm by construction and without a spurious \
11249 `Copy` deref (which would only be reachable through the \
11250 owned-input `From<RestartPolicy> for Cow<'static, str>` \
11251 axis by first calling `.copied()` on the iterator)"
11252 );
11253 for cow in &via_iter {
11254 assert!(
11255 matches!(cow, std::borrow::Cow::Borrowed(_)),
11256 "every element of the .iter().map(Cow::from) pipe \
11257 over RestartPolicy::ALL must land on the zero-\
11258 alloc Cow::Borrowed arm — a Cow::Owned outcome on \
11259 any arm signals the pipe's iteration axis has \
11260 silently allocated where the substrate-primitive \
11261 RestartPolicy::as_str `&'static str` return makes \
11262 the borrowed arm the type-correct projection"
11263 );
11264 }
11265 }
11266
11267 #[test]
11268 fn restart_policy_from_into_box_str_routes_through_as_str_accessor() {
11269 // Fail-before-pass-after byte-parity pin on the newly lifted
11270 // `impl From<RestartPolicy> for Box<str>` — asserts the
11271 // owned-input standard-library trait impl and the
11272 // substrate-primitive [`super::RestartPolicy::as_str`]
11273 // `pub const fn` accessor resolve to the same three-arm emit-
11274 // set across every arm the exhaustive
11275 // [`super::RestartPolicy::ALL`] slice enumerates. Extends the
11276 // substrate-wide `Box<str>` forward-projection campaign tier
11277 // opened one commit prior (69ef45c) on the paired sibling-
11278 // restart [`RestartStrategy`] onto the second (and third-and-
11279 // final) M2 OTP-shape closed-set fieldless typed enum peer on
11280 // the caixa surface (`:children :restart`), immediately after
11281 // the paired `Cow<'static, str>` axis (0612398 / b4dc55c)
11282 // closed the
11283 // `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
11284 // 2×3 corner on this enum. Rust's standard library carries
11285 // `impl From<&str> for Box<str>` and
11286 // `impl From<String> for Box<str>` but no blanket
11287 // `impl<T: AsRef<str>> From<T> for Box<str>`, so this axis is
11288 // a distinct trait-idiomatic surface that a
11289 // `let key: Box<str> = policy.into();`-shaped call site
11290 // reaches through this impl and no other — a paired
11291 // `Box::from(policy.as_str())` open-code has no compile-time
11292 // link back to the substrate primitive. Peer of the sibling
11293 // [`restart_strategy_from_into_box_str_routes_through_as_str_accessor`]
11294 // (69ef45c) — extends the trait-idiomatic owned-input
11295 // [`Box<str>`] forward-projection axis onto the third and
11296 // final M2-OTP-shape closed-set typed enum on the caixa
11297 // surface.
11298 for &variant in RestartPolicy::ALL {
11299 let via_trait: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
11300 let via_method: &'static str = variant.as_str();
11301 assert_eq!(
11302 via_trait.as_ref(),
11303 via_method,
11304 "From<RestartPolicy> for Box<str> impl must round-\
11305 trip RestartPolicy::{variant:?} to the same lifted \
11306 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
11307 returns — divergence signals a silent detour off the \
11308 substrate-primitive accessor"
11309 );
11310 let via_into: Box<str> = variant.into();
11311 assert_eq!(
11312 via_into.as_ref(),
11313 via_method,
11314 "Into<Box<str>>::into on RestartPolicy::{variant:?} \
11315 must byte-equal RestartPolicy::as_str on the same \
11316 input — the blanket-derived Into shape must resolve \
11317 to the same as_str dispatch as the explicit From impl"
11318 );
11319 }
11320 }
11321
11322 #[test]
11323 fn restart_policy_from_borrowed_into_box_str_routes_through_as_str_accessor() {
11324 // Fail-before-pass-after byte-parity pin on the newly lifted
11325 // `impl From<&RestartPolicy> for Box<str>` — asserts the
11326 // borrowed-input standard-library trait impl and the
11327 // substrate-primitive [`super::RestartPolicy::as_str`]
11328 // `pub const fn` accessor resolve to the same three-arm emit-
11329 // set across every arm the exhaustive
11330 // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
11331 // standard library does not carry a blanket
11332 // `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
11333 // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
11334 // so the borrowed-input `Box<str>` forward-projection axis
11335 // is a distinct trait-idiomatic surface that a
11336 // `let key: Box<str> = (&policy).into();`-shaped call site
11337 // or a `RestartPolicy::ALL.iter().map(Box::<str>::from)`-
11338 // shaped pipe reaches through this impl and no other — the
11339 // paired owned-input `From<RestartPolicy> for Box<str>`
11340 // impl (0a1b313) forces every borrowed-input call site
11341 // through an explicit `Copy` deref
11342 // (`Box::<str>::from((*policy).as_str())`) or a
11343 // `Box::<str>::from(policy.as_str())` open-code whose
11344 // type bounds have no compile-time link back to the
11345 // substrate primitive.
11346 //
11347 // Fourth (and closing) peer on the substrate-wide trait-
11348 // idiomatic [`Box<str>`] forward-projection family on the
11349 // M2 OTP-shape tier — closes the `{Self, &Self}` input-
11350 // shape corner of the [`Box<str>`] axis on the second (and
11351 // third-and-final) M2 OTP-shape closed-set fieldless typed
11352 // enum peer on the caixa surface (`:children :restart`),
11353 // exactly as b4dc55c closed the paired [`Cow<'static, str>`]
11354 // axis one commit after its owning half (0612398) landed
11355 // on this enum. Every remaining closed-set fieldless typed
11356 // enum peer on the M3 mesh-shape / outside-M3 caixa-core /
11357 // render-side / outside-caixa-core tiers is a future
11358 // target of the campaign.
11359 //
11360 // Also byte-parity witness against the paired owned-input
11361 // [`From<RestartPolicy> for Box<str>`] and the sibling
11362 // borrowed-input [`From<&RestartPolicy> for &'static str`],
11363 // [`From<&RestartPolicy> for String`], and
11364 // [`From<&RestartPolicy> for Cow<'static, str>`]
11365 // return-shape axes — locking the four
11366 // return-shape × input-shape paths together by construction
11367 // so any future detour trips at caixa-core test time. Then a
11368 // `.iter().map(Box::<str>::from)` pipe witness over
11369 // [`super::RestartPolicy::ALL`] — whose iterator yields
11370 // `&RestartPolicy` by construction, so the borrowed-input
11371 // [`Box<str>`] axis is what routes the pipe through the
11372 // substrate-primitive [`super::RestartPolicy::as_str`]
11373 // accessor without a spurious [`Copy`] deref (which would
11374 // only be reachable through the owned-input
11375 // [`From<RestartPolicy> for Box<str>`] axis by first
11376 // calling `.copied()` on the iterator).
11377 for &variant in RestartPolicy::ALL {
11378 let via_trait: Box<str> = <Box<str> as From<&RestartPolicy>>::from(&variant);
11379 let via_method: &'static str = variant.as_str();
11380 assert_eq!(
11381 via_trait.as_ref(),
11382 via_method,
11383 "From<&RestartPolicy> for Box<str> impl must round-\
11384 trip &RestartPolicy::{variant:?} to the same lifted \
11385 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
11386 returns — divergence signals a silent detour off the \
11387 substrate-primitive accessor"
11388 );
11389 let via_into: Box<str> = (&variant).into();
11390 assert_eq!(
11391 via_into.as_ref(),
11392 via_method,
11393 "Into<Box<str>>::into on &RestartPolicy::{variant:?} \
11394 must byte-equal RestartPolicy::as_str on the same \
11395 input — the blanket-derived Into shape must resolve \
11396 to the same as_str dispatch as the explicit From impl"
11397 );
11398 let owned_box: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
11399 assert_eq!(
11400 via_trait, owned_box,
11401 "From<&RestartPolicy> for Box<str> and \
11402 From<RestartPolicy> for Box<str> must resolve \
11403 identically on RestartPolicy::{variant:?} — \
11404 divergence signals the borrowed-input and owned-input \
11405 Box<str> forward-projection input-shape paths have \
11406 drifted onto different emit-sets"
11407 );
11408 let borrowed_static: &'static str =
11409 <&'static str as From<&RestartPolicy>>::from(&variant);
11410 assert_eq!(
11411 via_trait.as_ref(),
11412 borrowed_static,
11413 "From<&RestartPolicy> for Box<str> and \
11414 From<&RestartPolicy> for &'static str must resolve \
11415 identically on RestartPolicy::{variant:?} — \
11416 divergence signals the borrowed-input Box<str> and \
11417 &'static str return-shape paths have drifted onto \
11418 different emit-sets"
11419 );
11420 let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
11421 assert_eq!(
11422 via_trait.as_ref(),
11423 borrowed_string.as_str(),
11424 "From<&RestartPolicy> for Box<str> and \
11425 From<&RestartPolicy> for String must resolve \
11426 identically on RestartPolicy::{variant:?} — \
11427 divergence signals the borrowed-input Box<str> and \
11428 owned-`String` return-shape paths have drifted onto \
11429 different emit-sets"
11430 );
11431 let borrowed_cow: std::borrow::Cow<'static, str> =
11432 <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
11433 assert_eq!(
11434 via_trait.as_ref(),
11435 borrowed_cow.as_ref(),
11436 "From<&RestartPolicy> for Box<str> and \
11437 From<&RestartPolicy> for Cow<'static, str> must \
11438 resolve identically on RestartPolicy::{variant:?} — \
11439 divergence signals the borrowed-input Box<str> and \
11440 Cow<'static, str> return-shape paths have drifted \
11441 onto different emit-sets"
11442 );
11443 }
11444 let via_iter: Vec<Box<str>> = RestartPolicy::ALL.iter().map(Box::<str>::from).collect();
11445 let via_method: Vec<Box<str>> = RestartPolicy::ALL
11446 .iter()
11447 .map(|p| Box::<str>::from(p.as_str()))
11448 .collect();
11449 assert_eq!(
11450 via_iter, via_method,
11451 "`.iter().map(Box::<str>::from)` over \
11452 RestartPolicy::ALL — a call site whose iteration axis \
11453 holds `&RestartPolicy` by construction — must byte-\
11454 equal `.iter().map(|p| Box::<str>::from(p.as_str()))` \
11455 on every arm — the borrowed-input Box<str> \
11456 `From<&RestartPolicy> for Box<str>` axis is what \
11457 makes the `Box::<str>::from` composition route through \
11458 the substrate-primitive `RestartPolicy::as_str` \
11459 accessor without a spurious `Copy` deref (which would \
11460 only be reachable through the owned-input \
11461 `From<RestartPolicy> for Box<str>` axis by first \
11462 calling `.copied()` on the iterator)"
11463 );
11464 }
11465
11466 #[test]
11467 fn restart_policy_from_into_arc_str_routes_through_as_str_accessor() {
11468 // Fail-before-pass-after byte-parity pin on the newly lifted
11469 // `impl From<RestartPolicy> for std::sync::Arc<str>` — asserts
11470 // the owned-input standard-library trait impl and the
11471 // substrate-primitive [`super::RestartPolicy::as_str`]
11472 // `pub const fn` accessor resolve to the same three-arm emit-
11473 // set across every arm the exhaustive
11474 // [`super::RestartPolicy::ALL`] slice enumerates. Extends the
11475 // substrate-wide [`std::sync::Arc<str>`] forward-projection
11476 // campaign tier opened one projection tier prior (bca2ec8) on
11477 // the paired sibling-restart [`RestartStrategy`] owned-input
11478 // first-mover onto the second (and third-and-final) M2 OTP-
11479 // shape closed-set fieldless typed enum peer on the caixa
11480 // surface (`:children :restart`), immediately after the paired
11481 // [`Box<str>`] axis (0a1b313 / cb1d068) closed the
11482 // `{Self, &Self} × {&'static str, String, Cow<'static, str>,
11483 // Box<str>}` 2×4 corner on this enum. Rust's standard library
11484 // carries `impl From<&str> for std::sync::Arc<str>` and
11485 // `impl From<String> for std::sync::Arc<str>` but no blanket
11486 // `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor
11487 // an `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`),
11488 // so this axis is a distinct trait-idiomatic surface that a
11489 // `let key: std::sync::Arc<str> = policy.into();`-shaped call
11490 // site reaches through this impl and no other — a paired
11491 // `std::sync::Arc::<str>::from(policy.as_str())` open-code
11492 // has no compile-time link back to the substrate primitive,
11493 // and a two-step `std::sync::Arc::<str>::from(String::from(
11494 // policy))` composition through the owned-`String` axis
11495 // allocates twice (once into the intermediate `String`, once
11496 // into the [`Arc<str>`] on the `From<String>` conversion)
11497 // where the single-step trait impl allocates once.
11498 //
11499 // Cross-axis byte-parity witness against the sibling owned-
11500 // input `{&'static str, String, Cow<'static, str>, Box<str>}`
11501 // return-shape axes — locking the five return-shape paths on
11502 // the owned-input surface together by construction so any
11503 // future detour off the substrate-primitive
11504 // [`super::RestartPolicy::as_str`] accessor trips at caixa-
11505 // core test time.
11506 for &variant in RestartPolicy::ALL {
11507 let via_trait: std::sync::Arc<str> =
11508 <std::sync::Arc<str> as From<RestartPolicy>>::from(variant);
11509 let via_method: &'static str = variant.as_str();
11510 assert_eq!(
11511 via_trait.as_ref(),
11512 via_method,
11513 "From<RestartPolicy> for std::sync::Arc<str> impl \
11514 must round-trip RestartPolicy::{variant:?} to the \
11515 same lifted SUPERVISOR_CHILD_RESTART_* const \
11516 RestartPolicy::as_str returns — divergence signals \
11517 a silent detour off the substrate-primitive accessor"
11518 );
11519 let via_into: std::sync::Arc<str> = variant.into();
11520 assert_eq!(
11521 via_into.as_ref(),
11522 via_method,
11523 "Into<std::sync::Arc<str>>::into on \
11524 RestartPolicy::{variant:?} must byte-equal \
11525 RestartPolicy::as_str on the same input — the \
11526 blanket-derived Into shape must resolve to the same \
11527 as_str dispatch as the explicit From impl"
11528 );
11529 let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
11530 assert_eq!(
11531 via_trait.as_ref(),
11532 owned_static,
11533 "From<RestartPolicy> for std::sync::Arc<str> and \
11534 From<RestartPolicy> for &'static str must resolve \
11535 identically on RestartPolicy::{variant:?} — \
11536 divergence signals the owned-input std::sync::Arc<str> \
11537 and &'static str return-shape paths have drifted onto \
11538 different emit-sets"
11539 );
11540 let owned_string: String = <String as From<RestartPolicy>>::from(variant);
11541 assert_eq!(
11542 via_trait.as_ref(),
11543 owned_string.as_str(),
11544 "From<RestartPolicy> for std::sync::Arc<str> and \
11545 From<RestartPolicy> for String must resolve \
11546 identically on RestartPolicy::{variant:?} — \
11547 divergence signals the owned-input std::sync::Arc<str> \
11548 and owned-`String` return-shape paths have drifted \
11549 onto different emit-sets"
11550 );
11551 let owned_cow: std::borrow::Cow<'static, str> =
11552 <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
11553 assert_eq!(
11554 via_trait.as_ref(),
11555 owned_cow.as_ref(),
11556 "From<RestartPolicy> for std::sync::Arc<str> and \
11557 From<RestartPolicy> for Cow<'static, str> must \
11558 resolve identically on RestartPolicy::{variant:?} — \
11559 divergence signals the owned-input std::sync::Arc<str> \
11560 and Cow<'static, str> return-shape paths have drifted \
11561 onto different emit-sets"
11562 );
11563 let owned_box: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
11564 assert_eq!(
11565 via_trait.as_ref(),
11566 owned_box.as_ref(),
11567 "From<RestartPolicy> for std::sync::Arc<str> and \
11568 From<RestartPolicy> for Box<str> must resolve \
11569 identically on RestartPolicy::{variant:?} — \
11570 divergence signals the owned-input std::sync::Arc<str> \
11571 and Box<str> return-shape paths have drifted onto \
11572 different emit-sets"
11573 );
11574 }
11575 }
11576
11577 #[test]
11578 fn restart_policy_from_borrowed_into_arc_str_routes_through_as_str_accessor() {
11579 // Fail-before-pass-after byte-parity pin on the newly lifted
11580 // `impl From<&RestartPolicy> for std::sync::Arc<str>` —
11581 // asserts the borrowed-input standard-library trait impl and
11582 // the substrate-primitive [`super::RestartPolicy::as_str`]
11583 // `pub const fn` accessor resolve to the same three-arm
11584 // emit-set across every arm the exhaustive
11585 // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
11586 // standard library carries `impl From<&str> for
11587 // std::sync::Arc<str>` and `impl From<String> for
11588 // std::sync::Arc<str>` but no blanket
11589 // `impl<T: AsRef<str>> From<&T> for std::sync::Arc<str>` (nor
11590 // a `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
11591 // so the borrowed-input [`std::sync::Arc<str>`] forward-
11592 // projection axis is a distinct trait-idiomatic surface that
11593 // a `let key: std::sync::Arc<str> = (&policy).into();`-shaped
11594 // call site or a
11595 // `RestartPolicy::ALL.iter().map(std::sync::Arc::<str>::from)`-
11596 // shaped pipe reaches through this impl and no other — the
11597 // paired owned-input [`From<RestartPolicy> for
11598 // std::sync::Arc<str>`] impl (b05724e) forces every borrowed-
11599 // input call site through an explicit [`Copy`] deref
11600 // (`std::sync::Arc::<str>::from((*policy).as_str())`) or a
11601 // `std::sync::Arc::<str>::from(policy.as_str())` open-code
11602 // whose type bounds have no compile-time link back to the
11603 // substrate primitive.
11604 //
11605 // Closes the `{Self, &Self}` input-shape corner of the
11606 // substrate-wide trait-idiomatic [`std::sync::Arc<str>`]
11607 // forward-projection family on the second (and third-and-
11608 // final) M2 OTP-shape closed-set fieldless typed enum peer
11609 // on the caixa surface (`:children :restart`), one commit
11610 // after b05724e opened the owned-input half — exactly as
11611 // b3e72d7 closed the paired [`std::sync::Arc<str>`] corner on
11612 // the sibling-restart [`RestartStrategy`] first-mover one
11613 // commit after its owning half (bca2ec8) landed, and as
11614 // cb1d068 closed the paired [`Box<str>`] corner on this
11615 // enum one commit after its owning half (0a1b313) landed.
11616 //
11617 // Also byte-parity witness against the paired owned-input
11618 // [`From<RestartPolicy> for std::sync::Arc<str>`] and the
11619 // sibling borrowed-input [`From<&RestartPolicy> for
11620 // &'static str`], [`From<&RestartPolicy> for String`],
11621 // [`From<&RestartPolicy> for Cow<'static, str>`], and
11622 // [`From<&RestartPolicy> for Box<str>`] return-shape axes —
11623 // locking the five return-shape × input-shape paths together
11624 // by construction so any future detour off the substrate-
11625 // primitive [`super::RestartPolicy::as_str`] accessor trips
11626 // at caixa-core test time. Then a
11627 // `.iter().map(std::sync::Arc::<str>::from)` pipe witness
11628 // over [`super::RestartPolicy::ALL`] — whose iterator yields
11629 // `&RestartPolicy` by construction, so the borrowed-input
11630 // [`std::sync::Arc<str>`] axis is what routes the pipe
11631 // through the substrate-primitive
11632 // [`super::RestartPolicy::as_str`] accessor without a
11633 // spurious [`Copy`] deref (which would only be reachable
11634 // through the owned-input
11635 // [`From<RestartPolicy> for std::sync::Arc<str>`] axis by
11636 // first calling `.copied()` on the iterator).
11637 for &variant in RestartPolicy::ALL {
11638 let via_trait: std::sync::Arc<str> =
11639 <std::sync::Arc<str> as From<&RestartPolicy>>::from(&variant);
11640 let via_method: &'static str = variant.as_str();
11641 assert_eq!(
11642 via_trait.as_ref(),
11643 via_method,
11644 "From<&RestartPolicy> for std::sync::Arc<str> impl \
11645 must round-trip &RestartPolicy::{variant:?} to the \
11646 same lifted SUPERVISOR_CHILD_RESTART_* const \
11647 RestartPolicy::as_str returns — divergence signals \
11648 a silent detour off the substrate-primitive accessor"
11649 );
11650 let via_into: std::sync::Arc<str> = (&variant).into();
11651 assert_eq!(
11652 via_into.as_ref(),
11653 via_method,
11654 "Into<std::sync::Arc<str>>::into on \
11655 &RestartPolicy::{variant:?} must byte-equal \
11656 RestartPolicy::as_str on the same input — the \
11657 blanket-derived Into shape must resolve to the same \
11658 as_str dispatch as the explicit From impl"
11659 );
11660 let owned_arc: std::sync::Arc<str> =
11661 <std::sync::Arc<str> as From<RestartPolicy>>::from(variant);
11662 assert_eq!(
11663 via_trait, owned_arc,
11664 "From<&RestartPolicy> for std::sync::Arc<str> and \
11665 From<RestartPolicy> for std::sync::Arc<str> must \
11666 resolve identically on RestartPolicy::{variant:?} — \
11667 divergence signals the borrowed-input and owned-input \
11668 std::sync::Arc<str> forward-projection input-shape \
11669 paths have drifted onto different emit-sets"
11670 );
11671 let borrowed_static: &'static str =
11672 <&'static str as From<&RestartPolicy>>::from(&variant);
11673 assert_eq!(
11674 via_trait.as_ref(),
11675 borrowed_static,
11676 "From<&RestartPolicy> for std::sync::Arc<str> and \
11677 From<&RestartPolicy> for &'static str must resolve \
11678 identically on RestartPolicy::{variant:?} — \
11679 divergence signals the borrowed-input std::sync::Arc<str> \
11680 and &'static str return-shape paths have drifted onto \
11681 different emit-sets"
11682 );
11683 let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
11684 assert_eq!(
11685 via_trait.as_ref(),
11686 borrowed_string.as_str(),
11687 "From<&RestartPolicy> for std::sync::Arc<str> and \
11688 From<&RestartPolicy> for String must resolve \
11689 identically on RestartPolicy::{variant:?} — \
11690 divergence signals the borrowed-input std::sync::Arc<str> \
11691 and owned-`String` return-shape paths have drifted \
11692 onto different emit-sets"
11693 );
11694 let borrowed_cow: std::borrow::Cow<'static, str> =
11695 <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
11696 assert_eq!(
11697 via_trait.as_ref(),
11698 borrowed_cow.as_ref(),
11699 "From<&RestartPolicy> for std::sync::Arc<str> and \
11700 From<&RestartPolicy> for Cow<'static, str> must \
11701 resolve identically on RestartPolicy::{variant:?} — \
11702 divergence signals the borrowed-input std::sync::Arc<str> \
11703 and Cow<'static, str> return-shape paths have drifted \
11704 onto different emit-sets"
11705 );
11706 let borrowed_box: Box<str> = <Box<str> as From<&RestartPolicy>>::from(&variant);
11707 assert_eq!(
11708 via_trait.as_ref(),
11709 borrowed_box.as_ref(),
11710 "From<&RestartPolicy> for std::sync::Arc<str> and \
11711 From<&RestartPolicy> for Box<str> must resolve \
11712 identically on RestartPolicy::{variant:?} — \
11713 divergence signals the borrowed-input std::sync::Arc<str> \
11714 and Box<str> return-shape paths have drifted onto \
11715 different emit-sets"
11716 );
11717 }
11718 let via_iter: Vec<std::sync::Arc<str>> = RestartPolicy::ALL
11719 .iter()
11720 .map(std::sync::Arc::<str>::from)
11721 .collect();
11722 let via_method: Vec<std::sync::Arc<str>> = RestartPolicy::ALL
11723 .iter()
11724 .map(|p| std::sync::Arc::<str>::from(p.as_str()))
11725 .collect();
11726 assert_eq!(
11727 via_iter, via_method,
11728 "`.iter().map(std::sync::Arc::<str>::from)` over \
11729 RestartPolicy::ALL — a call site whose iteration axis \
11730 holds `&RestartPolicy` by construction — must byte-\
11731 equal `.iter().map(|p| std::sync::Arc::<str>::from(p.as_str()))` \
11732 on every arm — the borrowed-input std::sync::Arc<str> \
11733 `From<&RestartPolicy> for std::sync::Arc<str>` axis is \
11734 what makes the `std::sync::Arc::<str>::from` composition \
11735 route through the substrate-primitive \
11736 `RestartPolicy::as_str` accessor without a spurious \
11737 `Copy` deref (which would only be reachable through the \
11738 owned-input `From<RestartPolicy> for std::sync::Arc<str>` \
11739 axis by first calling `.copied()` on the iterator)"
11740 );
11741 }
11742
11743 // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_RESTART_* identity ─
11744
11745 #[test]
11746 fn restart_policy_variants_serialize_to_lifted_scalar_values() {
11747 // The fail-before-pass-after pin: pre-lift there was no
11748 // single-source binding between the [`RestartPolicy`] variant
11749 // name the un-`rename`d `Serialize` derive emits under
11750 // [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
11751 // byte-string every downstream cluster-side dispatcher (the
11752 // future wasm-operator's per-child post-exit restart-decision
11753 // branch, the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
11754 // materializer's admission-time enum-arm bind, the
11755 // `caixa-operator`'s hierarchical reconciliation scheduler's
11756 // per-child-policy fan-out) probes verbatim. A future
11757 // `#[serde(rename_all = "kebab-case")]` attribute on the enum —
11758 // or a per-variant `#[serde(rename = "…")]` override, or a
11759 // variant rename in the source — would silently rebrand the
11760 // emitted scalar under one spelling while every downstream
11761 // dispatcher still probed the other, with the failure surfacing
11762 // at the operator's reconcile posture (children coming up under
11763 // the `default()` `Permanent` arm rather than the typed slot's
11764 // declared policy — a `:temporary` `oneShot` child would be
11765 // restarted on clean exit, treating the successful-completion
11766 // signal as failure and re-running the completion-terminal
11767 // one-shot indefinitely; a `:transient` child that clean-exited
11768 // would be restarted, masking the clean-completion contract)
11769 // far from the source rebrand commit and with no field naming
11770 // the drift. Pinning the two paths (the `Serialize` derive's
11771 // serialized string AND the [`RestartPolicy::as_str`] helper)
11772 // to the same three lifted
11773 // [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
11774 // [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
11775 // [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
11776 // byte-strings makes any future drift on either endpoint fail
11777 // here at caixa-core build time. Peer of the sibling
11778 // [`restart_strategy_variants_serialize_to_lifted_scalar_values`]
11779 // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
11780 // and the M3
11781 // `placement_strategy_variants_serialize_to_lifted_scalar_values`
11782 // (3f0e21c) on the per-Aplicacao distribution-strategy axis —
11783 // same three-path-convergence discipline, extended to close the
11784 // third OTP-shaped closed-enum discriminator axis on the caixa
11785 // typed surface (per-child restart-decision policy).
11786 for (variant, expected) in [
11787 (
11788 RestartPolicy::Permanent,
11789 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
11790 ),
11791 (
11792 RestartPolicy::Temporary,
11793 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
11794 ),
11795 (
11796 RestartPolicy::Transient,
11797 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
11798 ),
11799 ] {
11800 let json = serde_json::to_string(&variant).unwrap();
11801 assert_eq!(
11802 json,
11803 format!("\"{expected}\""),
11804 "RestartPolicy::{variant:?} must serialize to {expected:?}"
11805 );
11806 assert_eq!(
11807 variant.as_str(),
11808 expected,
11809 "RestartPolicy::{variant:?}.as_str() must return the lifted \
11810 SUPERVISOR_CHILD_RESTART_* constant"
11811 );
11812 }
11813 }
11814
11815 #[test]
11816 fn supervisor_child_restart_consts_are_pairwise_distinct() {
11817 // Cross-arm drift-detection pin: a future collapse of two
11818 // canonical variant byte-strings onto the same value (e.g. an
11819 // accidental copy-paste flip of `SUPERVISOR_CHILD_RESTART_TRANSIENT`
11820 // to also read `"Permanent"`) would silently reroute every
11821 // downstream operator's per-child-policy dispatch onto the
11822 // sibling arm's reconcile branch and pass every propagation-probe
11823 // test that expected only the stale arm's value — a `:transient`
11824 // child would come up under the `:permanent` restart-decision
11825 // posture on every subsequent clean exit, so a completion-terminal
11826 // child would be restarted indefinitely against its declared
11827 // policy. Peer of the sibling
11828 // [`supervisor_estrategia_consts_are_pairwise_distinct`]
11829 // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
11830 // and the four-way distinct pin
11831 // `supervisor_key_consts_are_pairwise_distinct` (40cc4e5) on the
11832 // top-level `SUPERVISOR_KEY_*` axis.
11833 let all = [
11834 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
11835 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
11836 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
11837 ];
11838 for (i, a) in all.iter().enumerate() {
11839 for (j, b) in all.iter().enumerate() {
11840 if i != j {
11841 assert_ne!(
11842 a, b,
11843 "SUPERVISOR_CHILD_RESTART_* consts must be pairwise distinct \
11844 — got duplicate {a:?} at indices {i} and {j}",
11845 );
11846 }
11847 }
11848 }
11849 }
11850
11851 #[test]
11852 fn restart_policy_display_routes_through_as_str_helper() {
11853 // The fail-before-pass-after pin on the first half of the
11854 // three-path convergence: pre-convergence [`RestartPolicy`]
11855 // carried a [`std::fmt::Display`] surface via its
11856 // `#[discriminant(also_display)]` gen-platform derive route,
11857 // which arrived kebab-case as `"permanent"` / `"temporary"`
11858 // / `"transient"` on this three-arm enum (whose variant
11859 // names each collapse to their own lowercase form under the
11860 // kebab-case transform) while the wire format ran as
11861 // PascalCase `"Permanent"` / `"Temporary"` / `"Transient"`
11862 // through the un-`rename`d serde derive. Every consumer
11863 // reaching for a policy byte-string past the wire format had
11864 // to pick between three paths ([`RestartPolicy::as_str`],
11865 // the `Serialize` derive's serialized string, or
11866 // `format!("{v}")` on the discriminant-Display route), any
11867 // two of which a future variant rename or
11868 // `#[serde(rename_all = "kebab-case")]` attribute would
11869 // silently desynchronize. Wiring [`std::fmt::Display`]
11870 // through [`RestartPolicy::as_str`] closes the third path:
11871 // every `format!("{v}")` call reaches the same lifted
11872 // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the
11873 // wire format and the [`RestartPolicy::as_str`] helper
11874 // already route through, so a future variant rename lands at
11875 // exactly one place. Pin the routing here so a future
11876 // `impl std::fmt::Display for RestartPolicy`
11877 // reimplementation that hand-rolls the arms instead of
11878 // delegating to [`RestartPolicy::as_str`] fails at
11879 // caixa-core build time. Peer of the sibling
11880 // [`restart_strategy_display_routes_through_as_str_helper`]
11881 // on the per-supervisor sibling-restart-strategy axis and
11882 // the M3
11883 // `placement_strategy_display_routes_through_as_str_helper`
11884 // (cc8f749) — the third of three OTP-shape closed-enum
11885 // discriminator axes on the caixa typed surface now
11886 // converged onto the same three-path
11887 // (Display → as_str → lifted const) discipline.
11888 for variant in [
11889 RestartPolicy::Permanent,
11890 RestartPolicy::Temporary,
11891 RestartPolicy::Transient,
11892 ] {
11893 assert_eq!(
11894 variant.to_string(),
11895 variant.as_str(),
11896 "RestartPolicy::{variant:?} Display must route through \
11897 RestartPolicy::as_str (single source of truth: the lifted \
11898 SUPERVISOR_CHILD_RESTART_* const the wire format also emits)"
11899 );
11900 }
11901 }
11902
11903 #[test]
11904 fn restart_policy_display_matches_serialized_wire_byte_string() {
11905 // The fail-before-pass-after pin on the second half of the
11906 // three-path convergence: `Display` (user-facing text) agrees
11907 // byte-for-byte with the `Serialize` derive's wire format
11908 // (canonical camelCase-schema `SUPERVISOR_CHILD_KEY_RESTART`
11909 // scalar) on every variant. Pre-convergence the two paths
11910 // were structurally independent — a future
11911 // `#[serde(rename_all = "kebab-case")]` attribute on the
11912 // enum would silently rebrand the emitted wire scalar
11913 // (`permanent`, `temporary`, `transient`) while every
11914 // consumer that pretty-prints the policy (the future
11915 // wasm-operator's per-child post-exit restart-decision
11916 // diagnostic line, the future `feira app graph` per-child
11917 // restart column, the future M4
11918 // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
11919 // per-child admission-webhook rejection body) would still
11920 // emit the PascalCase form the `as_str` / `Display` route
11921 // returns, with the mismatch surfacing at consumer parse
11922 // time / operator dispatch time far from the source rebrand
11923 // commit. Pin the two paths byte-for-byte here so any future
11924 // serde-attribute or variant-rename drift is a
11925 // caixa-core-build-time test failure at this call, not a
11926 // silent per-consumer dispatch miss. Peer of the sibling
11927 // [`restart_strategy_display_matches_serialized_wire_byte_string`]
11928 // on the per-supervisor sibling-restart-strategy axis and
11929 // the M3
11930 // `placement_strategy_display_matches_serialized_wire_byte_string`
11931 // (cc8f749).
11932 for variant in [
11933 RestartPolicy::Permanent,
11934 RestartPolicy::Temporary,
11935 RestartPolicy::Transient,
11936 ] {
11937 let wire = serde_json::to_string(&variant).unwrap();
11938 let unquoted = wire
11939 .strip_prefix('"')
11940 .and_then(|s| s.strip_suffix('"'))
11941 .expect("serialized RestartPolicy is a JSON string");
11942 assert_eq!(
11943 variant.to_string(),
11944 unquoted,
11945 "RestartPolicy::{variant:?} Display byte-string must match the \
11946 Serialize derive's wire byte-string (three-path convergence: \
11947 Display + as_str + Serialize all resolve to the same \
11948 SUPERVISOR_CHILD_RESTART_* const)"
11949 );
11950 }
11951 }
11952
11953 #[test]
11954 fn restart_policy_as_ref_str_routes_through_as_str_accessor() {
11955 // Fail-before-pass-after byte-parity pin on the lifted
11956 // `impl AsRef<str> for RestartPolicy` — asserts the
11957 // standard-library trait impl and the substrate-primitive
11958 // [`RestartPolicy::as_str`] `pub const fn` accessor resolve
11959 // to the same `&str` per instance across the three-arm
11960 // closed set, so any future silent detour that routes the
11961 // impl through a divergent projection (a per-arm inline
11962 // `match self { RestartPolicy::Permanent => "Permanent", … }`
11963 // re-inlining that opens a compile-time link to the un-lifted
11964 // arm-literal, a swap onto the kebab-case
11965 // [`gen_platform::Discriminant`] catalog identity that would
11966 // collide the wire axis with the dispatcher-catalog axis) trips
11967 // at caixa-core test time under `PartialEq` rather than at a
11968 // downstream `impl AsRef<str>`-bound consumer's silent split.
11969 // Sweeps every one of the three arms
11970 // [`RestartPolicy::ALL`] carries so no arm's projection is
11971 // covered only by the sibling wire-format `Serialize` derive
11972 // path. Peer of the sibling
11973 // [`restart_strategy_as_ref_str_routes_through_as_str_accessor`]
11974 // (63eb1a4) on the paired per-supervisor sibling-restart-
11975 // strategy axis and the [`crate::CaixaVersion`]
11976 // `AsRef<str>`-byte-parity pin (16d5c7e) on the paired
11977 // top-level `:versao` typed newtype — the three pins together
11978 // cover the substrate primitive's `AsRef<str>` projection axis
11979 // on the paired newtype + M2 closed-set-typed-enum surface.
11980 for &variant in RestartPolicy::ALL {
11981 assert_eq!(
11982 <RestartPolicy as AsRef<str>>::as_ref(&variant),
11983 variant.as_str(),
11984 "AsRef<str> impl on RestartPolicy::{variant:?} must \
11985 byte-equal RestartPolicy::as_str on the same instance \
11986 — divergence signals a silent detour off the substrate-\
11987 primitive accessor"
11988 );
11989 }
11990 }
11991
11992 #[test]
11993 fn restart_policy_as_ref_str_routes_through_display_via_shared_accessor() {
11994 // Fail-before-pass-after byte-parity pin on the three-path
11995 // convergence discipline the M2 per-child-restart-policy
11996 // primitive now carries on the `&str`-projection axis:
11997 // `<RestartPolicy as AsRef<str>>::as_ref(&v)` (the newly
11998 // lifted impl), `format!("{v}")` (the pre-existing
11999 // [`fmt::Display`] impl), and `v.as_str()` (the substrate-
12000 // primitive `pub const fn` accessor both trait impls delegate
12001 // through) must resolve to the same byte-string on every
12002 // instance across the three-arm closed set. Refuses any future
12003 // divergence between the two trait impls (a stray
12004 // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
12005 // rather than delegating through the shared accessor; a
12006 // hypothetical `AsRef<str>` rewrite that inlines a per-arm
12007 // literal cascade) that would silently split the two
12008 // projection paths of the same closed-set typed enum. Mirrors
12009 // the sibling three-path-convergence discipline the peer
12010 // [`RestartStrategy`] typed enum carries on its
12011 // `AsRef<str>` / `Display` / `as_str` triple
12012 // (supervisor.rs pin
12013 // `restart_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
12014 // 63eb1a4) and the [`crate::CaixaVersion`] typed newtype
12015 // carries on the same triple (version.rs pin
12016 // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
12017 // 16d5c7e).
12018 for &variant in RestartPolicy::ALL {
12019 let via_as_ref: &str = <RestartPolicy as AsRef<str>>::as_ref(&variant);
12020 let via_display: String = format!("{variant}");
12021 let via_accessor: &str = variant.as_str();
12022 assert_eq!(via_as_ref, via_accessor);
12023 assert_eq!(via_display, via_accessor);
12024 assert_eq!(via_as_ref, via_display.as_str());
12025 }
12026 }
12027
12028 #[test]
12029 fn restart_policy_all_enumerates_every_variant_exactly_once() {
12030 // Fail-before-pass-after pin on the [`RestartPolicy::ALL`]
12031 // exhaustive-iteration surface: every variant appears exactly
12032 // once, and the slice length matches the arm count of the
12033 // closed set. Every consumer that walks the accepted-policy
12034 // set (a future `feira supervisor --restart …` CLI-side
12035 // arg-parse's "did you mean" hint, a future M4 admission-
12036 // webhook's per-child rejection body naming the accepted-
12037 // `:restart` list, the [`RestartPolicy::from_wire`] reverse-
12038 // projection consumers that iterate the accept-set for
12039 // diagnostic rendering) reads through this slice, so a future
12040 // arm addition that grows the enum but forgets to grow
12041 // [`Self::ALL`] silently truncates every downstream consumer's
12042 // accept-set at the same pre-addition boundary — this pin
12043 // fails at caixa-core build time on the pairwise-distinct +
12044 // arm-count invariants.
12045 //
12046 // Peer of the sibling [`RestartStrategy::ALL`] (4eec29c) /
12047 // [`crate::CaixaKind::ALL`] (6b1f4fb) /
12048 // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
12049 // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
12050 // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
12051 // pins on the peer closed-set typed-enum axes.
12052 let all: &[RestartPolicy] = RestartPolicy::ALL;
12053 assert_eq!(
12054 all.len(),
12055 3,
12056 "RestartPolicy::ALL must enumerate every variant of the \
12057 three-arm closed set (Permanent, Temporary, Transient); \
12058 got {all:?}"
12059 );
12060 for (i, a) in all.iter().enumerate() {
12061 for (j, b) in all.iter().enumerate() {
12062 if i != j {
12063 assert_ne!(
12064 a, b,
12065 "RestartPolicy::ALL must carry every variant exactly \
12066 once — got duplicate {a:?} at indices {i} and {j}"
12067 );
12068 }
12069 }
12070 }
12071 for variant in [
12072 RestartPolicy::Permanent,
12073 RestartPolicy::Temporary,
12074 RestartPolicy::Transient,
12075 ] {
12076 assert!(
12077 all.contains(&variant),
12078 "RestartPolicy::ALL must contain {variant:?} — a future arm \
12079 addition that grows the enum but forgets to grow the ALL slice \
12080 silently truncates every downstream consumer's accept-set at \
12081 the pre-addition boundary"
12082 );
12083 }
12084 }
12085
12086 #[test]
12087 fn restart_policy_wire_names_covers_every_arm() {
12088 // Load-bearing pin on the substrate-canonical
12089 // [`RestartPolicy::WIRE_NAMES`] exhaustive accept-set roster on
12090 // the `PascalCase` wire byte-string axis: every variant of the
12091 // sibling [`RestartPolicy::ALL`] exhaustive-iteration surface
12092 // must project through [`RestartPolicy::as_str`] onto an entry
12093 // the [`RestartPolicy::WIRE_NAMES`] roster carries, and the
12094 // roster's length must byte-equal `RestartPolicy::ALL.len()` so
12095 // a silent skew between the [`RestartPolicy::as_str`] match's
12096 // arm-set and the roster's arm-set trips here at caixa-core
12097 // test time rather than at a downstream M4
12098 // `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook
12099 // rejection body's wire-form `:restart` accepted-set
12100 // enumeration miss / a `feira supervisor --restart …` "did you
12101 // mean" hint drift / a future wasm-operator per-reconcile-step
12102 // diagnostic log line's accepted-wire-form enumeration miss.
12103 // A future arm addition (an OTP-`intrinsic` fourth arm the
12104 // theory
12105 // [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
12106 // might reach for once the three canonical OTP restart policies
12107 // stop covering the substrate's discovered load-shape) extends
12108 // [`RestartPolicy::ALL`] as a single edit and this pin sweeps
12109 // the new arm by iteration; the paired
12110 // [`RestartPolicy::WIRE_NAMES`] roster must grow in lockstep or
12111 // this assertion trips. Every entry is further pinned to open
12112 // with an ASCII uppercase byte so a silent collapse of the
12113 // wire-form axis with the peer kebab-case dispatcher-catalog
12114 // axis (an entry byte-identical to a sibling
12115 // [`RestartPolicy::discriminant`] kebab byte-string that would
12116 // let a wire-axis consumer accept the dispatcher-catalog
12117 // vocabulary) trips here rather than at a downstream K8s-CR
12118 // round-trip miss.
12119 //
12120 // Peer of the sibling
12121 // [`restart_strategy_wire_names_covers_every_arm`] (3033f45)
12122 // pin on the first M2 OTP-shape sibling-restart closed-set
12123 // typed enum, the sibling
12124 // [`crate::aplicacao::tests::placement_strategy_wire_names_covers_every_arm`]
12125 // (3e5b194) pin on the first M3 mesh-shape distribution-strategy
12126 // closed-set typed enum, the sibling
12127 // [`crate::kind::tests::caixa_kind_wire_names_covers_every_arm`]
12128 // (bd708bd) pin on the top-level typed-kind discriminator's
12129 // `PascalCase` wire byte-string axis, and the sibling
12130 // [`crate::upgrade::tests::upgrade_instruction_wire_forms_covers_every_arm`]
12131 // (cc42c0e) /
12132 // [`crate::upgrade::tests::upgrade_instruction_lisp_forms_covers_every_arm`]
12133 // (1898d77) pins on the OTP-appup discriminator's two-axis
12134 // roster split — the same closed-set exhaustive-roster coverage
12135 // discipline extended here onto the second and final M2
12136 // OTP-shape sibling-enum on the caixa surface, closing the
12137 // per-child restart-decision-policy axis paired with the peer
12138 // per-supervisor sibling-restart-strategy axis on the same M2
12139 // `:supervisor` slot.
12140 //
12141 // Fail-before-pass-after locally verified by mutating one arm
12142 // of the paired [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
12143 // const family (e.g. dropping the trailing `t` from
12144 // `"Permanent"` → `"Permanen"`) — the length pin still passes
12145 // but the `contains` check fires on the mutated arm; and by
12146 // shortening the roster to two entries — the length pin fires
12147 // first.
12148 assert_eq!(
12149 RestartPolicy::WIRE_NAMES.len(),
12150 RestartPolicy::ALL.len(),
12151 "RestartPolicy::WIRE_NAMES.len() must byte-equal \
12152 RestartPolicy::ALL.len() — a mismatch means the roster \
12153 and the enum's arm-set have drifted; downstream consumers \
12154 that fan through both will silently disagree on the \
12155 accepted arm-set"
12156 );
12157 for &variant in RestartPolicy::ALL {
12158 let wire = variant.as_str();
12159 assert!(
12160 RestartPolicy::WIRE_NAMES.contains(&wire),
12161 "RestartPolicy::{variant:?}.as_str() = {wire:?} must \
12162 be a member of RestartPolicy::WIRE_NAMES — the \
12163 emitter and the roster have drifted out of lockstep"
12164 );
12165 }
12166 for tag in RestartPolicy::WIRE_NAMES {
12167 let first = tag.chars().next().unwrap_or_else(|| {
12168 panic!(
12169 "RestartPolicy::WIRE_NAMES entry {tag:?} must be \
12170 a non-empty PascalCase byte-string"
12171 )
12172 });
12173 assert!(
12174 first.is_ascii_uppercase(),
12175 "RestartPolicy::WIRE_NAMES entry {tag:?} must open \
12176 with an ASCII uppercase byte (PascalCase wire form) — \
12177 a lowercase entry would collide the wire-form axis \
12178 with the peer kebab-case dispatcher-catalog axis \
12179 [`RestartPolicy::discriminant`] serves"
12180 );
12181 }
12182 }
12183
12184 #[test]
12185 fn restart_policy_from_wire_accepts_every_lifted_constant() {
12186 // Fail-before-pass-after pin on the forward accept-set of the
12187 // [`RestartPolicy::from_wire`] reverse projection: every
12188 // canonical [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
12189 // constant the [`RestartPolicy::as_str`] emitter walks parses
12190 // back to its paired variant. Any future arm addition that
12191 // grows the emitter's `as_str` match but forgets to grow the
12192 // parser's `from_wire` match silently splits the two halves of
12193 // the round-trip — the wire byte-string one non-serde consumer
12194 // parses from the one the emitter wrote — with the failure
12195 // surfacing at the operator's reconcile posture (a `:temporary`
12196 // `oneShot` child restarted on clean exit, a `:transient` child
12197 // restarted after clean completion) far from the rebrand
12198 // commit. Pinning the three-arm accept-set here catches the
12199 // drift at caixa-core build time.
12200 //
12201 // Peer of the sibling [`RestartStrategy::from_wire`] (4eec29c)
12202 // + [`crate::CaixaKind::from_wire`] (2aa6d23)
12203 // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
12204 // accept-set pins on the peer closed-set typed-enum `str → Self`
12205 // axes.
12206 for (wire, expected) in [
12207 (
12208 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
12209 RestartPolicy::Permanent,
12210 ),
12211 (
12212 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
12213 RestartPolicy::Temporary,
12214 ),
12215 (
12216 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
12217 RestartPolicy::Transient,
12218 ),
12219 ] {
12220 let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
12221 panic!(
12222 "RestartPolicy::from_wire({wire:?}) must accept every \
12223 SUPERVISOR_CHILD_RESTART_* constant — got None for the \
12224 lifted canonical byte-string that RestartPolicy::{expected:?} \
12225 serializes as under SUPERVISOR_CHILD_KEY_RESTART"
12226 )
12227 });
12228 assert_eq!(
12229 parsed, expected,
12230 "RestartPolicy::from_wire({wire:?}) must return \
12231 RestartPolicy::{expected:?}; got RestartPolicy::{parsed:?}"
12232 );
12233 }
12234 }
12235
12236 #[test]
12237 fn restart_policy_from_wire_round_trips_through_as_str() {
12238 // Fail-before-pass-after pin on the closed round-trip between
12239 // the forward [`RestartPolicy::as_str`] emitter and the
12240 // reverse [`RestartPolicy::from_wire`] parser: for every
12241 // variant in [`RestartPolicy::ALL`], parsing the emitter's
12242 // output must return exactly the same variant. Any per-arm
12243 // divergence — a future arm added to `as_str` but not
12244 // `from_wire`, an accidental copy-paste flip in one but not
12245 // the other — silently splits the emit and parse halves and
12246 // the failure surfaces at consumer parse time far from the
12247 // drift site. The `ALL`-iterating shape means a future arm
12248 // addition picks up the coverage by construction.
12249 //
12250 // Peer of the sibling
12251 // [`restart_strategy_from_wire_round_trips_through_as_str`]
12252 // (4eec29c) round-trip pin on
12253 // [`RestartStrategy::from_wire`] and the M3
12254 // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
12255 // (18c7342) round-trip pin on
12256 // [`crate::aplicacao::PlacementStrategy::from_wire`].
12257 for &variant in RestartPolicy::ALL {
12258 let wire = variant.as_str();
12259 let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
12260 panic!(
12261 "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
12262 must be Some({variant:?}) — the two halves of the round-trip \
12263 dispatch on the same lifted SUPERVISOR_CHILD_RESTART_* consts; \
12264 got None on wire byte-string {wire:?}"
12265 )
12266 });
12267 assert_eq!(
12268 parsed, variant,
12269 "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
12270 must round-trip to the same variant; got {parsed:?}"
12271 );
12272 }
12273 }
12274
12275 #[test]
12276 fn restart_policy_from_wire_rejects_unknown_byte_strings() {
12277 // Fail-before-pass-after pin on the closed-set refusal
12278 // discipline of [`RestartPolicy::from_wire`]: every
12279 // byte-string outside the three-arm accept-set returns `None`
12280 // rather than silently collapsing onto the [`Default`]
12281 // (`Permanent`) arm or an arbitrary neighbor. The refusal set
12282 // exercised here sweeps the load-bearing drift shapes: the
12283 // empty string (a stripped serde-attribute drift), all-
12284 // whitespace strings (the canonical text-editor accidental
12285 // padding shape), the kebab-case dispatcher-catalog identities
12286 // (`"permanent"` / `"temporary"` / `"transient"` — the
12287 // [`gen_platform::FromStrKind`]-derived [`std::str::FromStr`]
12288 // accept-set, which parses the *other* axis of this enum's
12289 // two-axis split and must not leak into the `from_wire`
12290 // PascalCase-wire accept-set — a lowercase leak here would
12291 // silently accept the operator's kebab-case
12292 // dispatcher-catalog probe under the wire-axis parser and mis-
12293 // route a `:permanent` intent), the padded canonical scalar
12294 // (`" Permanent "`), the trailing-newline shapes
12295 // (`"Permanent\n"`), the uppercase-single-word forms
12296 // (`"PERMANENT"`), and neighboring-but-unknown arms
12297 // (`"Restart"` — the canonical typo direction toward the
12298 // sibling [`RestartStrategy`] enum's own wire-arm namespace).
12299 //
12300 // Peer of the sibling
12301 // [`restart_strategy_from_wire_rejects_unknown_byte_strings`]
12302 // (4eec29c) +
12303 // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
12304 // (2aa6d23) +
12305 // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
12306 // (18c7342) refusal pins on the peer closed-set typed-enum
12307 // axes.
12308 for bad in [
12309 "",
12310 " ",
12311 "\n",
12312 "\t",
12313 "permanent",
12314 "temporary",
12315 "transient",
12316 "PERMANENT",
12317 "TEMPORARY",
12318 "TRANSIENT",
12319 "Permanents",
12320 "Permanent ",
12321 " Permanent",
12322 " Transient ",
12323 "Permanent\n",
12324 "perma",
12325 "Trans",
12326 "OneForOne",
12327 "Restart",
12328 "?",
12329 ] {
12330 assert!(
12331 RestartPolicy::from_wire(bad).is_none(),
12332 "RestartPolicy::from_wire({bad:?}) must return None — the \
12333 parser's accept-set is exactly the three RestartPolicy::as_str \
12334 outputs (Permanent, Temporary, Transient), and this \
12335 byte-string is outside that closed set"
12336 );
12337 }
12338 }
12339
12340 #[test]
12341 fn restart_policy_from_wire_matches_serialize_derive_wire_byte_string() {
12342 // Fail-before-pass-after pin on the fourth path of the four-path
12343 // convergence: `from_wire` (the reverse projection) inverts the
12344 // `Serialize` derive's wire byte-string on every variant.
12345 // Together with the pre-existing three-path convergence
12346 // (`Display` + `as_str` + `Serialize` all resolve to the same
12347 // lifted [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const,
12348 // pinned by
12349 // [`restart_policy_display_matches_serialized_wire_byte_string`])
12350 // this closes the round-trip: the wire byte-string the
12351 // `Serialize` derive emits parses back to the same variant
12352 // through `from_wire`, so any future serde-attribute or variant-
12353 // rename drift on the emit half now surfaces as a matched drift
12354 // on the parse half at caixa-core build time — the two halves
12355 // migrate as a unit through the lifted consts on any future
12356 // rename, and the round-trip cannot silently split.
12357 //
12358 // Peer of the sibling
12359 // [`restart_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
12360 // (4eec29c) wire-format pin on
12361 // [`RestartStrategy::from_wire`] and the M3
12362 // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
12363 // (18c7342) wire-format pin on
12364 // [`crate::aplicacao::PlacementStrategy::from_wire`].
12365 for &variant in RestartPolicy::ALL {
12366 let wire = serde_json::to_string(&variant).unwrap();
12367 let unquoted = wire
12368 .strip_prefix('"')
12369 .and_then(|s| s.strip_suffix('"'))
12370 .expect("serialized RestartPolicy is a JSON string");
12371 let parsed = RestartPolicy::from_wire(unquoted).unwrap_or_else(|| {
12372 panic!(
12373 "RestartPolicy::from_wire({unquoted:?}) must accept the \
12374 Serialize derive's wire byte-string for \
12375 RestartPolicy::{variant:?} — the four-path convergence \
12376 (Display + as_str + Serialize + from_wire) resolves through \
12377 the same lifted SUPERVISOR_CHILD_RESTART_* const; got None"
12378 )
12379 });
12380 assert_eq!(
12381 parsed, variant,
12382 "RestartPolicy::from_wire of the Serialize derive's wire \
12383 byte-string for RestartPolicy::{variant:?} must round-trip \
12384 to the same variant; got {parsed:?}"
12385 );
12386 }
12387 }
12388
12389 // ── drift-detection: ChildSpec::nome accessor pins ────────────────────
12390 //
12391 // The M2 supervisor-tree sibling of the M3 `Membro::nome` (4a32abf) pin
12392 // pair (`membro_nome_returns_caixa_byte_equal_across_permutations` +
12393 // `membro_nome_borrows_from_caixa_storage`) — extended here to the M2
12394 // per-`:children` child-caixa `:nome` axis, sibling to the first M2
12395 // slot scalar accessor `UpgradeFromEntry::prior_versao` (75d27a8) on
12396 // the peer per-`:upgrade-from :from` axis. The three pins jointly
12397 // brace the accessor against every future silent detour that would
12398 // desynchronize it from the raw `.caixa` field access every consumer
12399 // previously open-coded.
12400
12401 #[test]
12402 fn child_spec_nome_returns_caixa_byte_equal_across_permutations() {
12403 // The canonical per-`:children` child-caixa `:nome`-scalar pin:
12404 // [`ChildSpec::nome`] must return the `:children :caixa` field
12405 // byte-for-byte across every DNS-1123-label value the upstream
12406 // [`crate::render::require_valid_dns_1123_label`] gate at
12407 // `SupervisorSpec::validate` admits. Peer of the sibling
12408 // `membro_nome_returns_caixa_byte_equal_across_permutations`
12409 // (4a32abf) pin on the M3 per-`:membros` axis — same "the
12410 // substrate-primitive accessor must byte-equal the raw field
12411 // access verbatim across every author-declared value" discipline
12412 // extended to the M2 supervisor-tree per-`:children` arm. Pins
12413 // against a future silent detour that re-normalized the child
12414 // identity (an accidental `.to_lowercase()` — every `:children
12415 // :caixa` is validated as a DNS-1123 label upstream, so any
12416 // re-normalization is redundant + a drift surface between the
12417 // validator and the accessor), a namespace-prefix rewrite (an
12418 // accidental `format!("{namespace}/{caixa}")` per-CR
12419 // fully-qualified rewrite that didn't land on the peer axes), or
12420 // a per-cluster alias stamp the future wasm-operator's
12421 // hierarchical reconciliation scheduler authors on one consumer
12422 // without the others. Five values sweep the accept-set the
12423 // DNS-1123 gate upstream admits (short single-word / dashed /
12424 // v-suffixed / mixed-digit child names).
12425 for name in [
12426 "worker",
12427 "cache-server",
12428 "scratch-job",
12429 "orders-v2",
12430 "session-8080",
12431 ] {
12432 let c = ChildSpec {
12433 caixa: name.into(),
12434 versao: "^0.1".into(),
12435 restart: RestartPolicy::Permanent,
12436 };
12437 assert_eq!(
12438 c.nome(),
12439 name,
12440 "ChildSpec::nome must return :children :caixa verbatim \
12441 (got {:?}, expected {name:?})",
12442 c.nome(),
12443 );
12444 assert_eq!(
12445 c.nome(),
12446 c.caixa.as_str(),
12447 "ChildSpec::nome must byte-equal the .caixa field access",
12448 );
12449 }
12450 }
12451
12452 #[test]
12453 fn child_spec_nome_borrows_from_caixa_storage() {
12454 // The borrow-not-copy pin: [`ChildSpec::nome`] must return a
12455 // `&str` slice that borrows from the typed slot's own [`String`]
12456 // storage — same-address invariant with `c.caixa.as_str()`. Pins
12457 // against a future silent detour that allocated a fresh `String`
12458 // (`self.caixa.clone()` in the body would type-check but silently
12459 // drop the borrow, and every downstream consumer that assumed
12460 // the returned slice outlives `&self` would break on a stale-
12461 // reference use-after-free — the [`crate::render::insert_first_seen`]
12462 // dedup key at [`SupervisorSpec::validate`], the
12463 // [`validate_no_self_supervision`] equality check against the
12464 // parent's `:nome` string slice, the DNS-1123 gate's `&str`
12465 // borrow — each would silently misbehave if this accessor
12466 // produced a detached copy). Peer of the sibling
12467 // `membro_nome_borrows_from_caixa_storage` (4a32abf) pin on the
12468 // M3 per-`:membros` axis and the
12469 // `prior_versao_borrows_from_from_storage` (75d27a8) pin on the
12470 // first M2 slot scalar accessor.
12471 let c = ChildSpec {
12472 caixa: "worker".into(),
12473 versao: "^0.1".into(),
12474 restart: RestartPolicy::Permanent,
12475 };
12476 let name = c.nome();
12477 let caixa_slice = c.caixa.as_str();
12478 assert_eq!(
12479 name.as_ptr(),
12480 caixa_slice.as_ptr(),
12481 "ChildSpec::nome must borrow from the .caixa String's backing \
12482 storage — a fresh allocation here means the accessor no \
12483 longer names the substrate-primitive typed dispatch and \
12484 every downstream consumer would silently carry a detached \
12485 copy",
12486 );
12487 assert_eq!(
12488 name.len(),
12489 caixa_slice.len(),
12490 "ChildSpec::nome and .caixa.as_str() must byte-equal in length \
12491 as well as in address",
12492 );
12493 }
12494
12495 #[test]
12496 fn validate_gates_child_nome_through_lifted_accessor() {
12497 // Bilateral coherence pin: every `:children :caixa` that
12498 // [`SupervisorSpec::validate`] accepts is one
12499 // [`crate::render::require_valid_dns_1123_label`] accepts on the
12500 // accessor-projected value, and vice versa on the reject side.
12501 // This closes the "the validator reads through the accessor"
12502 // contract structurally — a future silent detour that made the
12503 // accessor return a different byte-string than the validator
12504 // gates against would surface here as a coverage mismatch, not
12505 // as an apply-time DNS-1123 rejection at
12506 // `metadata.name: Invalid value` far from the caixa.lisp source.
12507 // Peer of the M2 sibling
12508 // `validate_parses_prior_versao_through_lifted_accessor`
12509 // (75d27a8) on the per-`:upgrade-from :from` axis and the M3
12510 // `validate_membros` peer discipline.
12511 //
12512 // Accept-set sweep: five DNS-1123-label values the upstream gate
12513 // admits.
12514 for ok_name in ["a", "worker", "cache-server", "orders-v2", "svc-8080"] {
12515 let s = SupervisorSpec {
12516 children: vec![ChildSpec {
12517 caixa: ok_name.into(),
12518 versao: "^0.1".into(),
12519 restart: RestartPolicy::Permanent,
12520 }],
12521 ..SupervisorSpec::default()
12522 };
12523 s.validate().unwrap_or_else(|e| {
12524 panic!(
12525 "SupervisorSpec::validate must accept :children :caixa {ok_name:?} \
12526 (upstream DNS-1123 gate accepts it): got {e:?}",
12527 );
12528 });
12529 let c = ChildSpec {
12530 caixa: ok_name.into(),
12531 versao: "^0.1".into(),
12532 restart: RestartPolicy::Permanent,
12533 };
12534 crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| ())
12535 .unwrap_or_else(|()| {
12536 panic!(
12537 "require_valid_dns_1123_label must accept the accessor-projected \
12538 :children :caixa {ok_name:?}",
12539 );
12540 });
12541 }
12542 // Reject-set sweep: five DNS-1123-label-violating shapes the
12543 // upstream gate refuses (empty / uppercase / underscore / dot /
12544 // leading-hyphen). Every rejection at the validator must
12545 // correspond to a rejection when the accessor's projected value
12546 // is fed back through the shared gate.
12547 for bad_name in ["", "Worker", "my_worker", "team.worker", "-worker"] {
12548 let s = SupervisorSpec {
12549 children: vec![ChildSpec {
12550 caixa: bad_name.into(),
12551 versao: "^0.1".into(),
12552 restart: RestartPolicy::Permanent,
12553 }],
12554 ..SupervisorSpec::default()
12555 };
12556 let err = s.validate().unwrap_err();
12557 assert!(
12558 matches!(
12559 err,
12560 SupervisorError::EmptyChildName | SupervisorError::ChildCaixaInvalid { .. }
12561 ),
12562 "SupervisorSpec::validate must reject :children :caixa {bad_name:?} \
12563 via the DNS-1123 gate: got {err:?}",
12564 );
12565 let c = ChildSpec {
12566 caixa: bad_name.into(),
12567 versao: "^0.1".into(),
12568 restart: RestartPolicy::Permanent,
12569 };
12570 assert!(
12571 crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| (),)
12572 .is_err(),
12573 "require_valid_dns_1123_label must reject the accessor-projected \
12574 :children :caixa {bad_name:?}",
12575 );
12576 }
12577 }
12578
12579 // ── drift-detection: ChildSpec::versao_requirement accessor pins ──────
12580 //
12581 // Sibling of the peer per-`:membros` `membro_versao_requirement_*`
12582 // (a40b0e3) pin pair on the M3 mesh-slot surface — extended here to the
12583 // M2 supervisor-tree per-`:children` child-`:versao` axis, sibling to
12584 // the just-landed [`ChildSpec::nome`] (57c61d0) child-`:nome` pin
12585 // trio on the peer per-`:children` `String`-carry axis. The three pins
12586 // jointly brace the accessor against every future silent detour that
12587 // would desynchronize it from the raw `.versao` field access the
12588 // requirement gate + error carrier previously open-coded.
12589 //
12590 // Closes the last unlifted per-`:children` `String`-carry axis: the
12591 // pair (`nome`, `versao_requirement`) now jointly projects the
12592 // (`.caixa`, `.versao`) field pair every OTP-shape supervisor-tree
12593 // consumer that fans on per-child identity + version pin reads,
12594 // matching the peer M3 (`Membro::nome`, `Membro::versao_requirement`)
12595 // pair discipline verbatim.
12596 #[test]
12597 fn child_spec_versao_requirement_returns_versao_byte_equal_across_permutations() {
12598 // The canonical per-`:children` child-`:versao`-scalar pin:
12599 // [`ChildSpec::versao_requirement`] must return the `:children
12600 // :versao` field byte-for-byte across every Cargo-shaped semver
12601 // requirement value the upstream
12602 // [`crate::render::require_valid_versao_requirement`] gate admits.
12603 // Peer of the sibling
12604 // `membro_versao_requirement_returns_versao_byte_equal_across_permutations`
12605 // (a40b0e3) pin on the M3 per-`:membros` axis — same "the
12606 // substrate-primitive accessor must byte-equal the raw field
12607 // access verbatim across every author-declared value" discipline
12608 // extended to the M2 supervisor-tree per-`:children` arm. Pins
12609 // against a future silent detour that re-canonicalized the
12610 // requirement (an accidental `.to_string()` via
12611 // [`crate::version::parse_requirement`] → [`std::fmt::Display`]
12612 // round-trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and
12613 // silently drifted the error carrier's quoted requirement away
12614 // from the source `caixa.lisp`, an accidental whitespace trim on
12615 // `"^ 0.1"` that no consumer ever produced from the field-access
12616 // side, an accidental per-cluster lacre-projected concrete-version
12617 // rewrite that didn't land on the peer requirement-gate call).
12618 // Five values sweep the accept-set the shared
12619 // [`crate::render::require_valid_versao_requirement`] gate admits
12620 // (caret / tilde / exact / wildcard / bare-major).
12621 for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
12622 let c = ChildSpec {
12623 caixa: "worker".into(),
12624 versao: req.into(),
12625 restart: RestartPolicy::Permanent,
12626 };
12627 assert_eq!(
12628 c.versao_requirement(),
12629 req,
12630 "ChildSpec::versao_requirement must return :children :versao \
12631 verbatim (got {:?}, expected {req:?})",
12632 c.versao_requirement(),
12633 );
12634 assert_eq!(
12635 c.versao_requirement(),
12636 c.versao.as_str(),
12637 "ChildSpec::versao_requirement must byte-equal the .versao \
12638 field access",
12639 );
12640 }
12641 }
12642
12643 #[test]
12644 fn child_spec_versao_requirement_borrows_from_versao_storage() {
12645 // The borrow-not-copy pin: [`ChildSpec::versao_requirement`] must
12646 // return a `&str` slice that borrows from the typed slot's own
12647 // [`String`] storage — same-address invariant with
12648 // `c.versao.as_str()`. Pins against a future silent detour that
12649 // allocated a fresh `String` (`self.versao.clone()` in the body
12650 // would type-check but silently drop the borrow, and every
12651 // downstream consumer that assumed the returned slice outlives
12652 // `&self` — the [`crate::render::require_valid_versao_requirement`]
12653 // gate's `&str` borrow, the [`SupervisorError::ChildVersaoInvalid`]
12654 // `.to_string()` carrier's byte-length assumption — would silently
12655 // misbehave if this accessor produced a detached copy). Peer of
12656 // the sibling `child_spec_nome_borrows_from_caixa_storage`
12657 // (57c61d0) pin on the per-`:children` `:nome` axis and the M3
12658 // `membro_versao_requirement_borrows_from_versao_storage` (a40b0e3)
12659 // pin on the peer per-`:membros` `:versao` axis.
12660 let c = ChildSpec {
12661 caixa: "worker".into(),
12662 versao: "^0.1".into(),
12663 restart: RestartPolicy::Permanent,
12664 };
12665 let req = c.versao_requirement();
12666 let versao_slice = c.versao.as_str();
12667 assert_eq!(
12668 req.as_ptr(),
12669 versao_slice.as_ptr(),
12670 "ChildSpec::versao_requirement must borrow from the .versao \
12671 String's backing storage — a fresh allocation here means the \
12672 accessor no longer names the substrate-primitive typed \
12673 dispatch and every downstream consumer would silently carry \
12674 a detached copy",
12675 );
12676 assert_eq!(
12677 req.len(),
12678 versao_slice.len(),
12679 "ChildSpec::versao_requirement and .versao.as_str() must \
12680 byte-equal in length as well as in address",
12681 );
12682 }
12683
12684 #[test]
12685 fn validate_gates_child_versao_through_lifted_accessor() {
12686 // Bilateral coherence pin: every `:children :versao` that
12687 // [`SupervisorSpec::validate`] accepts is one
12688 // [`crate::render::require_valid_versao_requirement`] accepts on
12689 // the accessor-projected value, and vice versa on the reject side.
12690 // This closes the "the validator reads through the accessor"
12691 // contract structurally — a future silent detour that made the
12692 // accessor return a different byte-string than the validator gates
12693 // against would surface here as a coverage mismatch, not as a
12694 // resolver-time semver-parse rejection at lacre-closure time far
12695 // from the caixa.lisp source. Peer of the sibling
12696 // `validate_gates_child_nome_through_lifted_accessor` (57c61d0) on
12697 // the per-`:children :caixa` axis and the M2
12698 // `validate_parses_prior_versao_through_lifted_accessor` (75d27a8)
12699 // on the peer per-`:upgrade-from :from` axis.
12700 //
12701 // Accept-set sweep: five Cargo-shaped semver requirement values
12702 // the upstream gate admits (caret / tilde / exact / wildcard /
12703 // bare-major).
12704 for ok_req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
12705 let s = SupervisorSpec {
12706 children: vec![ChildSpec {
12707 caixa: "worker".into(),
12708 versao: ok_req.into(),
12709 restart: RestartPolicy::Permanent,
12710 }],
12711 ..SupervisorSpec::default()
12712 };
12713 s.validate().unwrap_or_else(|e| {
12714 panic!(
12715 "SupervisorSpec::validate must accept :children :versao {ok_req:?} \
12716 (upstream versao-requirement gate accepts it): got {e:?}",
12717 );
12718 });
12719 let c = ChildSpec {
12720 caixa: "worker".into(),
12721 versao: ok_req.into(),
12722 restart: RestartPolicy::Permanent,
12723 };
12724 crate::render::require_valid_versao_requirement(
12725 c.versao_requirement(),
12726 || (),
12727 |_reason| (),
12728 )
12729 .unwrap_or_else(|()| {
12730 panic!(
12731 "require_valid_versao_requirement must accept the accessor-projected \
12732 :children :versao {ok_req:?}",
12733 );
12734 });
12735 }
12736 // Reject-set sweep: five requirement-violating shapes the upstream
12737 // gate refuses. The empty string closes the empty-first arm of the
12738 // shared [`crate::render::require_valid_versao_requirement`]
12739 // cascade; the four non-empty arms exercise distinct semver-parse
12740 // failure modes the M3 peer per-`:membros` reject-set already pins
12741 // (`rejects_invalid_membro_versao_requirement` on `^bad-version`,
12742 // `rejects_membro_versao_with_double_caret_typo` on `^^0.1`,
12743 // `rejects_membro_versao_with_v_prefixed_tag` on `v0.1`) — the
12744 // shared parser routing means the same reject-set must fail
12745 // identically at the M2 supervisor-tree per-`:children` accessor
12746 // arm here. Every rejection at the validator must correspond to a
12747 // rejection when the accessor's projected value is fed back
12748 // through the shared gate.
12749 //
12750 // (Bare partial magnitudes like `"0.1"` and bare identifiers like
12751 // `"not-a-semver"` are intentionally *not* in the reject-set: the
12752 // semver crate accepts `"0.1"` as an implicit `^0.1` requirement,
12753 // and the identifier-tail arm's grammar admits some non-canonical
12754 // shapes — matching what the M3 peer test suite already documents
12755 // as the shared parser's accept-set edges.)
12756 for bad_req in ["", "v0.1.0", "^bad-version", "^^0.1", "v0.1"] {
12757 let s = SupervisorSpec {
12758 children: vec![ChildSpec {
12759 caixa: "worker".into(),
12760 versao: bad_req.into(),
12761 restart: RestartPolicy::Permanent,
12762 }],
12763 ..SupervisorSpec::default()
12764 };
12765 let err = s.validate().unwrap_err();
12766 assert!(
12767 matches!(
12768 err,
12769 SupervisorError::EmptyChildVersion { .. }
12770 | SupervisorError::ChildVersaoInvalid { .. }
12771 ),
12772 "SupervisorSpec::validate must reject :children :versao {bad_req:?} \
12773 via the versao-requirement gate: got {err:?}",
12774 );
12775 let c = ChildSpec {
12776 caixa: "worker".into(),
12777 versao: bad_req.into(),
12778 restart: RestartPolicy::Permanent,
12779 };
12780 assert!(
12781 crate::render::require_valid_versao_requirement(
12782 c.versao_requirement(),
12783 || (),
12784 |_reason| (),
12785 )
12786 .is_err(),
12787 "require_valid_versao_requirement must reject the accessor-projected \
12788 :children :versao {bad_req:?}",
12789 );
12790 }
12791 }
12792
12793 // ── per-`:children` `:restart` typed-accessor coherence pins ──────────
12794 //
12795 // The [`ChildSpec::restart`] accessor lift closes the last unlifted
12796 // per-`:children` axis (the pair `nome()` + `versao_requirement()`
12797 // already project the `String`-carry `(caixa, versao)` fields; the
12798 // `Copy`-composite-enum `restart` field is the third and final axis).
12799 // Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
12800 // (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
12801 // scalar accessor and the M3 mesh-slot [`crate::Placement::estrategia`]
12802 // (921fe1b) `Copy`-return [`crate::PlacementStrategy`] distribution-
12803 // strategy scalar accessor — same "one typed dispatch on the substrate
12804 // primitive, `Copy`-projected closed-set enum-arm discriminator" shape
12805 // extended onto the M2 supervisor-slot per-`:children` restart-decision
12806 // axis. The pin below covers the accessor's byte-equal projection
12807 // against the raw field access across every variant in the closed
12808 // accept-set (`Permanent`, `Transient`, `Temporary`).
12809
12810 #[test]
12811 fn child_spec_restart_returns_restart_verbatim_across_permutations() {
12812 // The canonical per-`:children` restart-decision-policy-scalar
12813 // pin: [`ChildSpec::restart`] must return the `:children :restart`
12814 // field verbatim as a [`RestartPolicy`], `Copy`-projected from the
12815 // typed slot's own [`RestartPolicy`] storage across every variant
12816 // in the closed accept-set (`Permanent`, `Transient`, `Temporary`).
12817 // Pins against a future silent detour that re-derived the policy
12818 // from a peer axis (an accidental fallback to
12819 // `if is_supervisor_child { Permanent } else { Temporary }` that
12820 // collapsed the child's kind axis into the restart discriminator),
12821 // a variant remap the operator authors on one consumer without the
12822 // other, or a stale-derive detour that substituted
12823 // [`RestartPolicy::default`] when the field held any explicit
12824 // variant (which would silently collapse the distinction between
12825 // "author explicitly declared `:restart Permanent`" and "author
12826 // omitted the slot and inherited the default" the future
12827 // per-cluster restart-decision override slot depends on).
12828 //
12829 // Peer of the sibling per-`:supervisor`
12830 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
12831 // (eafb619) pin on the M2 supervisor-slot sibling-restart-strategy
12832 // axis and the M3
12833 // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
12834 // (921fe1b) pin on the per-`:placement` distribution-strategy axis
12835 // — same "the substrate-primitive accessor must byte-equal the raw
12836 // field access verbatim across every author-declared value"
12837 // discipline extended onto the M2 supervisor-slot per-`:children`
12838 // restart-decision-policy axis, closing the last unlifted axis on
12839 // the per-`:children` [`ChildSpec`] type.
12840 for restart in [
12841 RestartPolicy::Permanent,
12842 RestartPolicy::Transient,
12843 RestartPolicy::Temporary,
12844 ] {
12845 let c = ChildSpec {
12846 caixa: "worker".into(),
12847 versao: "^0.1".into(),
12848 restart,
12849 };
12850 assert_eq!(
12851 c.restart(),
12852 restart,
12853 "ChildSpec::restart must return :children :restart \
12854 verbatim (got {:?}, expected {restart:?})",
12855 c.restart(),
12856 );
12857 assert_eq!(
12858 c.restart(),
12859 c.restart,
12860 "ChildSpec::restart accessor and .restart field access \
12861 must byte-equal — the accessor is the substrate-primitive \
12862 typed dispatch every downstream per-child restart-\
12863 decision consumer must route through",
12864 );
12865 }
12866 }
12867
12868 // ── per-`:supervisor` `:estrategia` typed-accessor coherence pins ─────
12869 //
12870 // The [`SupervisorSpec::estrategia`] accessor lift extends the peer M3
12871 // [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
12872 // distribution-strategy accessor discipline onto the M2 supervisor-slot
12873 // per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
12874 // scalar axis. The two pins below cover (1) the accessor's byte-equal
12875 // projection against the raw field access across every variant in the
12876 // closed accept-set, and (2) the two-consumer coherence between the
12877 // [`SupervisorSpec::validate`] partition-dispatch `match` arm and the
12878 // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
12879 // carrier's `estrategia:` field — peer of the sibling M3
12880 // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
12881 // / `validate_placement_reads_through_lifted_estrategia_accessor` pin
12882 // pair on the per-`:placement` distribution-strategy axis.
12883
12884 #[test]
12885 fn supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations() {
12886 // The canonical per-`:supervisor` sibling-restart-strategy-scalar
12887 // pin: [`SupervisorSpec::estrategia`] must return the
12888 // `:supervisor :estrategia` field verbatim as a
12889 // [`RestartStrategy`], `Copy`-projected from the typed slot's own
12890 // [`RestartStrategy`] storage across every variant in the closed
12891 // accept-set (`OneForOne`, `OneForAll`, `RestForOne`,
12892 // `SimpleOneForOne`). Pins against a future silent detour that
12893 // re-derived the strategy from a peer axis (an accidental
12894 // fallback to `if children.is_empty() { SimpleOneForOne } else {
12895 // OneForOne }` collapse that read the children-count axis into
12896 // the strategy discriminator), a variant remap the operator
12897 // authors on one consumer without the other, or a stale-derive
12898 // detour that substituted [`RestartStrategy::default`] when the
12899 // field held any explicit variant (which would silently collapse
12900 // the distinction between "author explicitly declared
12901 // `:estrategia OneForOne`" and "author omitted the slot and
12902 // inherited the default" the future per-cluster strategy override
12903 // slot depends on). Peer of the sibling M3
12904 // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
12905 // (921fe1b) pin on the M3 mesh-slot `Copy`-composite-enum scalar
12906 // axis — same "the substrate-primitive accessor must byte-equal
12907 // the raw field access verbatim across every author-declared
12908 // value" discipline extended onto the M2 supervisor-slot
12909 // per-`:supervisor` sibling-restart-strategy axis.
12910 for &estrategia in RestartStrategy::ALL {
12911 // `SimpleOneForOne` requires `children.is_empty()`; the peer
12912 // three strategies require a non-empty static children list.
12913 // Build each shape coherently so the pin's fixture would
12914 // itself pass [`SupervisorSpec::validate`] once fed through
12915 // the sibling coherence pin below — the byte-equal projection
12916 // asserted here is a strictly weaker property (a `Copy` field
12917 // read) that does not depend on `validate` running, but
12918 // keeping the fixture validate-clean means a future extension
12919 // of the pin to exercise `validate` end-to-end does not have
12920 // to re-author the children shape.
12921 //
12922 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
12923 // shape partition through the [`gen_platform::IsVariant`]
12924 // derive-generated
12925 // [`RestartStrategy::is_simple_one_for_one`] predicate rather
12926 // than the raw `matches!(estrategia, RestartStrategy::
12927 // SimpleOneForOne)` open-coded pattern-match — same closed-
12928 // set-typed-enum arm-discriminator dispatch discipline the
12929 // sibling [`crate::upgrade::UpgradeInstruction::is_restart`]
12930 // convergence (915a934) extended onto its two paired positive
12931 // / negated `matches!` sites and the peer
12932 // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
12933 // predicate convergence (766ec63) extended onto the M3 mesh-
12934 // slot per-`:placement` distribution-strategy discriminator
12935 // axis. See the sibling `round_trip_all_strategies` and the
12936 // peer `manifest::tests::
12937 // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
12938 // fixture for the two peer sites the same lift closes on.
12939 let children = if estrategia.is_simple_one_for_one() {
12940 Vec::new()
12941 } else {
12942 vec![ChildSpec {
12943 caixa: "worker".into(),
12944 versao: "^0.1".into(),
12945 restart: RestartPolicy::Permanent,
12946 }]
12947 };
12948 let s = SupervisorSpec {
12949 estrategia,
12950 children,
12951 ..SupervisorSpec::default()
12952 };
12953 assert_eq!(
12954 s.estrategia(),
12955 estrategia,
12956 "SupervisorSpec::estrategia must return :supervisor :estrategia \
12957 verbatim (got {:?}, expected {estrategia:?})",
12958 s.estrategia(),
12959 );
12960 assert_eq!(
12961 s.estrategia(),
12962 s.estrategia,
12963 "SupervisorSpec::estrategia accessor and .estrategia field \
12964 access must byte-equal — the accessor is the substrate-\
12965 primitive typed dispatch every downstream sibling-restart-\
12966 strategy consumer must route through",
12967 );
12968 }
12969 }
12970
12971 #[test]
12972 fn validate_reads_through_lifted_estrategia_accessor() {
12973 // Two-consumer coherence pin: the [`SupervisorSpec::validate`]
12974 // `SimpleOneForOne ↔ non-SimpleOneForOne` `match` partition
12975 // dispatch (which reads through [`SupervisorSpec::estrategia`]
12976 // to fan across the strategy-arm shape-gate cascades) and the
12977 // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
12978 // error carrier's `estrategia:` field (which reads through
12979 // [`SupervisorSpec::estrategia`] to name the strategy the empty
12980 // `:children` list was declared against) must both key off the
12981 // lifted accessor, so any future rebrand on the typed slot's
12982 // reader shape lands at exactly one place. Pins the two-site
12983 // coherence by exercising the `NoChildren` error surface end-to-
12984 // end across every non-`SimpleOneForOne` variant and asserting
12985 // the surfaced `estrategia:` field byte-equals the accessor's
12986 // return. Peer of the sibling M3
12987 // `validate_placement_reads_through_lifted_estrategia_accessor`
12988 // (921fe1b) three-consumer coherence pin on the per-`:placement`
12989 // distribution-strategy axis.
12990 for estrategia in [
12991 RestartStrategy::OneForOne,
12992 RestartStrategy::OneForAll,
12993 RestartStrategy::RestForOne,
12994 ] {
12995 let s = SupervisorSpec {
12996 estrategia,
12997 children: Vec::new(),
12998 ..SupervisorSpec::default()
12999 };
13000 let err = s.validate().unwrap_err();
13001 match err {
13002 SupervisorError::NoChildren { estrategia: e } => {
13003 assert_eq!(
13004 e,
13005 s.estrategia(),
13006 "NoChildren.estrategia must byte-equal \
13007 SupervisorSpec::estrategia() — the empty-`:children` \
13008 refusal reads through the lifted accessor",
13009 );
13010 assert_eq!(
13011 e, estrategia,
13012 "NoChildren.estrategia must carry the author-declared \
13013 :supervisor :estrategia variant verbatim (got {e:?}, \
13014 expected {estrategia:?})",
13015 );
13016 }
13017 other => panic!("expected NoChildren, got {other:?} for estrategia={estrategia:?}"),
13018 }
13019 }
13020 }
13021
13022 // ── per-`:supervisor` `:max-restarts` typed-accessor coherence pins ────
13023 //
13024 // The [`SupervisorSpec::max_restarts`] accessor lift extends the peer M3
13025 // [`crate::CircuitBreaker::max_failures`] (3a74062) `Copy`-return
13026 // required-`u32` scalar accessor discipline onto the M2 supervisor-slot
13027 // per-`:supervisor` restart-budget-count `Copy`-`u32` scalar axis.
13028 // The two pins below cover (1) the accessor's byte-equal projection
13029 // against the raw field access across every representative value in
13030 // the `u32` accept-set (`1` lower boundary, `SUPERVISOR_MAX_RESTARTS_MAX`
13031 // upper boundary, `0` past-the-guard zero sentinel, `u32::MAX`
13032 // past-the-guard cap sentinel), and (2) the [`SupervisorSpec::validate`]
13033 // zero-floor / cap composition — the validate gate and the accessor
13034 // must route through the same substrate-primitive typed dispatch, so
13035 // any future silent detour that had the accessor perform a
13036 // bounds-collapsing clamp would fail here at caixa-core build time.
13037 // Peer of the sibling M3
13038 // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
13039 // (3a74062) pin on the per-`CircuitBreaker :max-failures` axis.
13040
13041 #[test]
13042 fn supervisor_spec_max_restarts_returns_max_restarts_u32_byte_equal_across_permutations() {
13043 // The canonical per-`:supervisor` restart-budget-count scalar pin:
13044 // [`SupervisorSpec::max_restarts`] must return the `:supervisor
13045 // :max-restarts` typed `u32` verbatim, `Copy`-projected from the
13046 // typed slot's own `u32` storage, byte-equal to the raw field
13047 // access across every representative value in the accept-set —
13048 // `1` (the lower boundary of the `1..=SUPERVISOR_MAX_RESTARTS_MAX`
13049 // accept-set the surrounding [`SupervisorSpec::validate`] gate
13050 // carves out on the sibling `ZeroMaxRestarts` refusal),
13051 // `SUPERVISOR_MAX_RESTARTS_MAX` (the upper boundary the same gate
13052 // carves out on the sibling `MaxRestartsExceedsCap` refusal), `0`
13053 // (a past-the-guard sentinel that pins the accessor doesn't
13054 // perform a silent bounds-collapse into `1` on the zero arm —
13055 // validate rejects zero but the accessor must ship the raw slot
13056 // verbatim so a validate-time gate regression surfaces at the
13057 // emit boundary rather than being silently absorbed), `u32::MAX`
13058 // (a past-the-guard sentinel that pins the accessor doesn't
13059 // perform a silent bounds-collapse through
13060 // `SUPERVISOR_MAX_RESTARTS_MAX` at the return path).
13061 //
13062 // Peer of the sibling M3
13063 // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
13064 // (3a74062) pin on the M3 mesh-slot `Copy`-`u32` sub-struct
13065 // required-scalar axis — same "the substrate-primitive accessor
13066 // must byte-equal the raw field access verbatim across every
13067 // value in the `u32` accept-set" discipline extended onto the M2
13068 // supervisor-slot per-`:supervisor` restart-budget-count axis.
13069 for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX, 0, u32::MAX] {
13070 let s = SupervisorSpec {
13071 max_restarts,
13072 ..SupervisorSpec::default()
13073 };
13074 assert_eq!(
13075 s.max_restarts(),
13076 max_restarts,
13077 "SupervisorSpec::max_restarts must return :supervisor \
13078 :max-restarts verbatim (got {}, expected {max_restarts})",
13079 s.max_restarts(),
13080 );
13081 assert_eq!(
13082 s.max_restarts(),
13083 s.max_restarts,
13084 "SupervisorSpec::max_restarts accessor and .max_restarts \
13085 field access must byte-equal — the accessor is the \
13086 substrate-primitive typed dispatch every downstream \
13087 restart-budget-count consumer must route through",
13088 );
13089 }
13090 }
13091
13092 #[test]
13093 fn validate_max_restarts_zero_floor_and_cap_arms_route_through_accessor() {
13094 // Composition pin: [`SupervisorSpec::validate`]'s `:max-restarts`
13095 // zero-floor + upper-cap bracket must key off
13096 // [`SupervisorSpec::max_restarts`], not the raw `.max_restarts`
13097 // field access. Structurally: a `SupervisorSpec { max_restarts:
13098 // 0, .. }` must surface the `ZeroMaxRestarts` refusal exactly, a
13099 // `SupervisorSpec { max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
13100 // .. }` must surface the `MaxRestartsExceedsCap` refusal exactly
13101 // (with the offending count carried verbatim from the accessor
13102 // return), and a `SupervisorSpec { max_restarts: 1, .. }` (the
13103 // lower boundary of the accept-set) plus a `SupervisorSpec {
13104 // max_restarts: SUPERVISOR_MAX_RESTARTS_MAX, .. }` (the upper
13105 // boundary) must pass validate. The four together jointly pin the
13106 // accessor + validate-gate composition: any future silent detour
13107 // that had the accessor return a fresh `1` on the zero arm (a
13108 // `.max_restarts().max(1)` collapse) would silently absorb the
13109 // `ZeroMaxRestarts` refusal at the accessor boundary and the
13110 // validate gate would accept a struct-literal `SupervisorSpec {
13111 // max_restarts: 0, .. }` — the composition pin catches that at
13112 // caixa-core build time.
13113 //
13114 // Peer of the sibling M3
13115 // `validate_politicas_max_failures_zero_floor_arm_routes_through_accessor`
13116 // (3a74062) pin on the sibling per-`CircuitBreaker :max-failures`
13117 // composition axis — same "the validate / shape-gate predicate
13118 // must route through the substrate-primitive typed dispatch"
13119 // discipline extended onto the peer M2 supervisor-slot
13120 // required-`u32` composition axis.
13121 let child = ChildSpec {
13122 caixa: "worker".into(),
13123 versao: "^0.1".into(),
13124 restart: RestartPolicy::Permanent,
13125 };
13126 // Zero-floor arm.
13127 let s = SupervisorSpec {
13128 max_restarts: 0,
13129 children: vec![child.clone()],
13130 ..SupervisorSpec::default()
13131 };
13132 assert_eq!(
13133 s.validate().unwrap_err(),
13134 SupervisorError::ZeroMaxRestarts,
13135 "validate must reject max_restarts == 0 with ZeroMaxRestarts \
13136 — the accessor and the validate gate must route through the \
13137 same substrate-primitive typed dispatch on the zero-floor arm",
13138 );
13139 // Cap arm — the surfaced `max_restarts:` field must byte-equal
13140 // the accessor's return so a future rebrand on the accessor
13141 // lands in the diagnostic without a coordinated rewrite.
13142 let over_cap = SUPERVISOR_MAX_RESTARTS_MAX + 1;
13143 let s = SupervisorSpec {
13144 max_restarts: over_cap,
13145 children: vec![child.clone()],
13146 ..SupervisorSpec::default()
13147 };
13148 match s.validate().unwrap_err() {
13149 SupervisorError::MaxRestartsExceedsCap { max_restarts } => {
13150 assert_eq!(
13151 max_restarts,
13152 s.max_restarts(),
13153 "MaxRestartsExceedsCap.max_restarts must byte-equal \
13154 SupervisorSpec::max_restarts() — the cap-arm refusal \
13155 reads through the lifted accessor",
13156 );
13157 assert_eq!(
13158 max_restarts, over_cap,
13159 "MaxRestartsExceedsCap.max_restarts must carry the \
13160 author-declared :supervisor :max-restarts value \
13161 verbatim (got {max_restarts}, expected {over_cap})",
13162 );
13163 }
13164 other => panic!("expected MaxRestartsExceedsCap, got {other:?}"),
13165 }
13166 // Lower + upper accept-set boundaries.
13167 for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX] {
13168 let s = SupervisorSpec {
13169 max_restarts,
13170 children: vec![child.clone()],
13171 ..SupervisorSpec::default()
13172 };
13173 assert!(
13174 s.validate().is_ok(),
13175 "validate must accept max_restarts == {max_restarts} \
13176 (an accept-set boundary of \
13177 1..=SUPERVISOR_MAX_RESTARTS_MAX)",
13178 );
13179 }
13180 }
13181
13182 // ── per-`:supervisor` `:restart-window` typed-accessor coherence pins ─
13183 //
13184 // The [`SupervisorSpec::restart_window`] accessor lift extends the peer
13185 // M2 [`crate::LimitsSpec::wall_clock`] (8cb717b) `Option<Duration>`
13186 // accessor discipline and the peer M3 [`crate::MeshPolicy::timeout`]
13187 // (7073d0f) `Option<Duration>` accessor discipline onto the M2
13188 // supervisor-slot per-`:supervisor` restart-intensity-denominator
13189 // `Option<Duration>` scalar axis — third `Copy`-return accessor on the
13190 // M2 supervisor-slot `SupervisorSpec` type, closing the last unlifted
13191 // per-`:supervisor` scalar-value axis. The three pins below cover
13192 // (1) the accessor's byte-equal projection against the raw field
13193 // access across every representative value in the `Option<Duration>`
13194 // accept-set (`None` never-reset sentinel, `Some(Duration::from_millis(1))`
13195 // lower boundary, `Some(SUPERVISOR_RESTART_WINDOW_MAX)` upper boundary,
13196 // `Some(Duration::ZERO)` past-the-guard zero sentinel, `Some(Duration::MAX)`
13197 // past-the-guard above-cap sentinel), (2) the [`SupervisorSpec::validate`]
13198 // `if let Some(w) = self.restart_window() { … }` bracket-arm
13199 // composition — the validate gate and the accessor must route through
13200 // the same substrate-primitive typed dispatch, so any future silent
13201 // detour that had the accessor perform a bounds-collapsing clamp
13202 // would fail here at caixa-core build time, and (3) the accessor's
13203 // by-copy idempotence pin — the returned `Option<Duration>` must
13204 // outlive `&self` and two successive calls must return byte-equal
13205 // values. Peer of the sibling M2
13206 // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
13207 // (8cb717b) pin on the per-`:limits :wall-clock` axis and the sibling
13208 // M3 `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
13209 // (7073d0f) pin on the per-`:politicas :timeout` axis.
13210
13211 #[test]
13212 fn supervisor_spec_restart_window_returns_option_duration_byte_equal_across_permutations() {
13213 // The canonical per-`:supervisor` restart-intensity-denominator
13214 // scalar pin: [`SupervisorSpec::restart_window`] must return the
13215 // `:supervisor :restart-window` typed [`Duration`] verbatim as an
13216 // `Option<Duration>`, `Copy`-projected from the typed slot's own
13217 // `Option<Duration>` storage, byte-equal to the raw field access
13218 // across every representative value in the accept-set — `None`
13219 // (the "never reset — every restart across the supervisor's
13220 // lifetime counts against the sibling `:max-restarts` budget"
13221 // sentinel the field's own docstring names and the peer
13222 // `validate_accepts_none_restart_window` pin locks in on the
13223 // [`SupervisorSpec::validate`] entry-side),
13224 // `Some(Duration::from_millis(1))` (the structural minimum a
13225 // validated `:restart-window` may carry, the integer-millisecond
13226 // floor [`SupervisorError::RestartWindowNotCanonical`] rejects
13227 // everything sub-ms; `Duration::ZERO` is separately rejected by
13228 // [`SupervisorError::RestartWindowZero`]),
13229 // `Some(SUPERVISOR_RESTART_WINDOW_MAX)` (the upper boundary the
13230 // surrounding [`SupervisorSpec::validate`] gate carves out on the
13231 // sibling [`SupervisorError::RestartWindowExceedsCap`] refusal),
13232 // `Some(Duration::ZERO)` (a past-the-guard sentinel that pins the
13233 // accessor doesn't perform a silent bounds-collapse into `None` on
13234 // the zero-Duration arm — validate rejects zero but the accessor
13235 // must ship the raw slot verbatim so a validate-time gate
13236 // regression surfaces at the emit boundary rather than being
13237 // silently absorbed), and `Some(Duration::MAX)` (a past-the-guard
13238 // sentinel that pins the accessor doesn't perform a silent
13239 // bounds-collapse through [`SUPERVISOR_RESTART_WINDOW_MAX`] at the
13240 // return path).
13241 //
13242 // Peer of the sibling M2
13243 // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
13244 // (8cb717b) pin on the per-`:limits :wall-clock` axis and the
13245 // sibling M3
13246 // `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
13247 // (7073d0f) pin on the per-`:politicas :timeout` axis — same "the
13248 // substrate-primitive accessor must byte-equal the raw field
13249 // access verbatim across every value in the `Option<Duration>`
13250 // accept-set" discipline extended onto the M2 supervisor-slot
13251 // per-`:supervisor` `Option<Duration>` axis. Pins against a future
13252 // silent detour that re-derived the restart-window from a peer
13253 // axis (an accidental `.max_restarts.into()` collapse that read
13254 // the restart-budget-count as a duration — the two axes serve
13255 // different halves of the `MaxIntensity / Period` restart-
13256 // intensity ratio, and confusing them silently inverts the
13257 // ratio's numerator and denominator), a `None → Some(Duration::ZERO)`
13258 // "zero means never reset" collapse (the canonical
13259 // `Option<Duration>` → `Duration` collapse footgun the
13260 // [`SupervisorError::RestartWindowZero`] validate arm guards on
13261 // the peer zero-floor axis; a zero period either trips on the
13262 // first failure or never trips depending on operator
13263 // interpretation, neither of which is the author's "never reset"
13264 // intent that `None` expresses structurally), or a per-arm
13265 // variant swap that landed on one consumer without the other.
13266 for restart_window in [
13267 None,
13268 Some(Duration::from_millis(1)),
13269 Some(SUPERVISOR_RESTART_WINDOW_MAX),
13270 Some(Duration::ZERO),
13271 Some(Duration::MAX),
13272 ] {
13273 let s = SupervisorSpec {
13274 restart_window,
13275 ..SupervisorSpec::default()
13276 };
13277 assert_eq!(
13278 s.restart_window(),
13279 restart_window,
13280 "SupervisorSpec::restart_window must return :supervisor \
13281 :restart-window verbatim (got {:?}, expected {restart_window:?})",
13282 s.restart_window(),
13283 );
13284 assert_eq!(
13285 s.restart_window(),
13286 s.restart_window,
13287 "SupervisorSpec::restart_window accessor and \
13288 .restart_window field access must byte-equal — the \
13289 accessor is the substrate-primitive typed dispatch every \
13290 downstream restart-intensity-denominator consumer must \
13291 route through",
13292 );
13293 }
13294 }
13295
13296 #[test]
13297 fn validate_restart_window_bracket_arm_routes_through_accessor() {
13298 // Composition pin: [`SupervisorSpec::validate`]'s
13299 // `:restart-window` `if let Some(w) = self.restart_window() { … }`
13300 // zero-floor + integer-millisecond canonical-form + upper-cap
13301 // bracket-arm must key off [`SupervisorSpec::restart_window`], not
13302 // the raw `.restart_window` field access. Structurally: a
13303 // `SupervisorSpec { restart_window: None, .. }` must pass the
13304 // arm gate structurally (the `if let Some(_)` shape returns
13305 // early on the `None` arm — the accessor and the validate gate
13306 // must agree on `None → skip the bracket cascade` so an authored
13307 // `:restart-window ()` structurally routes through the "never
13308 // reset" sentinel path), a `SupervisorSpec { restart_window:
13309 // Some(Duration::ZERO), .. }` must surface the `RestartWindowZero`
13310 // refusal exactly, a `SupervisorSpec { restart_window:
13311 // Some(Duration::from_micros(1500)), .. }` must surface the
13312 // `RestartWindowNotCanonical` refusal exactly (with the offending
13313 // duration carried verbatim from the accessor return), a
13314 // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX
13315 // + Duration::from_millis(1)), .. }` must surface the
13316 // `RestartWindowExceedsCap` refusal exactly (with the offending
13317 // duration carried verbatim from the accessor return), and a
13318 // `SupervisorSpec { restart_window: Some(Duration::from_millis(1)),
13319 // .. }` (the lower boundary of the accept-set) plus a
13320 // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
13321 // .. }` (the upper boundary) must pass validate. The six together
13322 // jointly pin the accessor + validate-gate composition: any future
13323 // silent detour that had the accessor return a fresh `None` on any
13324 // `Some` arm (a `.restart_window().filter(|w| !w.is_zero())`
13325 // collapse) would silently absorb the `RestartWindowZero` refusal
13326 // at the accessor boundary and the validate gate would accept a
13327 // struct-literal `SupervisorSpec { restart_window:
13328 // Some(Duration::ZERO), .. }` — the composition pin catches that
13329 // at caixa-core build time.
13330 //
13331 // Peer of the sibling M2 [`crate::LimitsSpec::wall_clock`]
13332 // (8cb717b) validate-arm-route pin on the per-`:limits :wall-clock`
13333 // axis and the peer M3 [`crate::MeshPolicy::timeout`] (7073d0f)
13334 // accessor-composition pin on the per-`:politicas :timeout` axis —
13335 // same "the validate / shape-gate predicate must route through
13336 // the substrate-primitive typed dispatch" discipline extended
13337 // onto the peer M2 supervisor-slot optional-`Duration` axis.
13338 let child = ChildSpec {
13339 caixa: "worker".into(),
13340 versao: "^0.1".into(),
13341 restart: RestartPolicy::Permanent,
13342 };
13343 // None arm — must not surface any :restart-window-shaped refusal;
13344 // the `if let Some(_)` bracket returns early on `None` structurally.
13345 let s = SupervisorSpec {
13346 restart_window: None,
13347 children: vec![child.clone()],
13348 ..SupervisorSpec::default()
13349 };
13350 assert!(
13351 s.validate().is_ok(),
13352 "validate must accept restart_window: None (the never-reset \
13353 sentinel) — the `if let Some(_)` bracket returns early on \
13354 the None arm and the accessor must agree",
13355 );
13356 // Zero-floor arm.
13357 let s = SupervisorSpec {
13358 restart_window: Some(Duration::ZERO),
13359 children: vec![child.clone()],
13360 ..SupervisorSpec::default()
13361 };
13362 assert_eq!(
13363 s.validate().unwrap_err(),
13364 SupervisorError::RestartWindowZero,
13365 "validate must reject restart_window == Some(Duration::ZERO) \
13366 with RestartWindowZero — the accessor and the validate gate \
13367 must route through the same substrate-primitive typed \
13368 dispatch on the zero-floor arm",
13369 );
13370 // Non-canonical (sub-ms) arm — the surfaced `window:` field must
13371 // byte-equal the accessor's return so a future rebrand on the
13372 // accessor lands in the diagnostic without a coordinated rewrite.
13373 let sub_ms = Duration::from_micros(1500);
13374 let s = SupervisorSpec {
13375 restart_window: Some(sub_ms),
13376 children: vec![child.clone()],
13377 ..SupervisorSpec::default()
13378 };
13379 match s.validate().unwrap_err() {
13380 SupervisorError::RestartWindowNotCanonical { window } => {
13381 assert_eq!(
13382 Some(window),
13383 s.restart_window(),
13384 "RestartWindowNotCanonical.window must byte-equal \
13385 SupervisorSpec::restart_window().unwrap() — the \
13386 non-canonical-arm refusal reads through the lifted \
13387 accessor",
13388 );
13389 assert_eq!(
13390 window, sub_ms,
13391 "RestartWindowNotCanonical.window must carry the \
13392 author-declared :supervisor :restart-window value \
13393 verbatim (got {window:?}, expected {sub_ms:?})",
13394 );
13395 }
13396 other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
13397 }
13398 // Cap arm — the surfaced `window:` field must byte-equal the
13399 // accessor's return.
13400 let over_cap = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
13401 let s = SupervisorSpec {
13402 restart_window: Some(over_cap),
13403 children: vec![child.clone()],
13404 ..SupervisorSpec::default()
13405 };
13406 match s.validate().unwrap_err() {
13407 SupervisorError::RestartWindowExceedsCap { window } => {
13408 assert_eq!(
13409 Some(window),
13410 s.restart_window(),
13411 "RestartWindowExceedsCap.window must byte-equal \
13412 SupervisorSpec::restart_window().unwrap() — the \
13413 cap-arm refusal reads through the lifted accessor",
13414 );
13415 assert_eq!(
13416 window, over_cap,
13417 "RestartWindowExceedsCap.window must carry the \
13418 author-declared :supervisor :restart-window value \
13419 verbatim (got {window:?}, expected {over_cap:?})",
13420 );
13421 }
13422 other => panic!("expected RestartWindowExceedsCap, got {other:?}"),
13423 }
13424 // Lower + upper accept-set boundaries.
13425 for restart_window in [Duration::from_millis(1), SUPERVISOR_RESTART_WINDOW_MAX] {
13426 let s = SupervisorSpec {
13427 restart_window: Some(restart_window),
13428 children: vec![child.clone()],
13429 ..SupervisorSpec::default()
13430 };
13431 assert!(
13432 s.validate().is_ok(),
13433 "validate must accept restart_window == Some({restart_window:?}) \
13434 (an accept-set boundary of \
13435 1ms..=SUPERVISOR_RESTART_WINDOW_MAX)",
13436 );
13437 }
13438 }
13439
13440 #[test]
13441 fn supervisor_spec_restart_window_projects_option_duration_by_copy() {
13442 // The by-copy pin: [`SupervisorSpec::restart_window`] returns
13443 // `Option<Duration>` by copy — `Duration` is `Copy` (so
13444 // `Option<Duration>` is `Copy`) and the accessor must return by
13445 // value, not by reference. Peer of the sibling M2
13446 // [`crate::LimitsSpec::wall_clock`] (8cb717b) by-copy pin on the
13447 // per-`:limits :wall-clock` axis and the sibling M3
13448 // [`crate::MeshPolicy::timeout`] (7073d0f) by-copy pin on the
13449 // per-`:politicas :timeout` axis, extended onto the peer M2
13450 // supervisor-slot `Option<Duration>` copy-invariant shape — the
13451 // accessor's returned `Option<Duration>` must outlive `&self`
13452 // (multiple calls must return equal values from a dropped-`&self`
13453 // copy, since the returned Option carries no borrow), and calling
13454 // the accessor twice on the same SupervisorSpec must yield the
13455 // same `Option<Duration>` verbatim (idempotent, no side effects
13456 // on `&self`).
13457 //
13458 // Pins against a future silent detour that returned
13459 // `Option<&Duration>` (which would type-check but silently break
13460 // every downstream caller — the future wasm-operator's
13461 // per-supervisor restart-intensity counter consumes `Duration` by
13462 // value and `&Duration` would fold to a detached copy at the call
13463 // site), an accidental `Option::as_ref()` projection
13464 // (`self.restart_window.as_ref()` would also type-check but
13465 // return `Option<&Duration>`), or a one-arm-only accessor that
13466 // reads `Some(*w)` in the Some arm but reads a fresh
13467 // `Default::default()` (which would collapse to `Duration::ZERO`,
13468 // not `None`) in the None arm — a footgun the
13469 // [`SupervisorError::RestartWindowZero`] validate arm explicitly
13470 // closes since Erlang/OTP's `MaxIntensity / Period` invariant
13471 // requires `Period > 0` and `None` structurally expresses "never
13472 // reset" instead.
13473 for restart_window in [
13474 None,
13475 Some(Duration::from_millis(1)),
13476 Some(Duration::from_secs(60)),
13477 Some(SUPERVISOR_RESTART_WINDOW_MAX),
13478 ] {
13479 let s = SupervisorSpec {
13480 restart_window,
13481 ..SupervisorSpec::default()
13482 };
13483 let first = s.restart_window();
13484 let second = s.restart_window();
13485 assert_eq!(
13486 first, second,
13487 "SupervisorSpec::restart_window must be idempotent — two \
13488 successive calls on the same &self must return the \
13489 same Option<Duration>",
13490 );
13491 assert_eq!(
13492 first, restart_window,
13493 "SupervisorSpec::restart_window must return :supervisor \
13494 :restart-window verbatim by copy — got {first:?}, \
13495 expected {restart_window:?}",
13496 );
13497 }
13498 }
13499
13500 // ── per-`:supervisor` `:children` typed-accessor coherence pins ─────────
13501 //
13502 // The [`SupervisorSpec::children`] accessor lift is the seed of the
13503 // slice-return (`&[T]`) accessor discipline on the substrate — the four
13504 // peer `Vec`-carry axes ([`crate::Placement::clusters`],
13505 // [`crate::AplicacaoSpec::membros`], [`crate::AplicacaoSpec::contratos`],
13506 // [`crate::UpgradeFromEntry::instructions`]) still key off the raw field
13507 // access at the time of this seed, and inherit this pin family's
13508 // discipline as future compounding runs migrate their consumers. The
13509 // three pins below cover (1) the accessor's byte-equal projection
13510 // against the raw field access across the empty / singleton / cohort
13511 // fixtures the [`SupervisorSpec::validate`] partition-dispatch fans
13512 // between, (2) the [`SupervisorSpec::validate`] `SimpleOneForOne ↔
13513 // non-SimpleOneForOne` partition dispatch's paired `.is_empty()`
13514 // consumer routing through the accessor on both arms, and (3) the
13515 // per-child validate loop's traversal reading the same slice-view the
13516 // accessor projects. Peer of the sibling M2
13517 // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
13518 // two-consumer coherence pin on the per-`:supervisor`
13519 // sibling-restart-strategy `Copy`-composite-enum scalar axis, extended
13520 // onto the per-`:supervisor` static-child-list `Vec`-carry axis.
13521
13522 #[test]
13523 fn supervisor_spec_children_returns_children_slice_byte_equal_across_permutations() {
13524 // The canonical per-`:supervisor` static-child-list scalar-shape
13525 // pin: [`SupervisorSpec::children`] must return the `:supervisor
13526 // :children` typed `Vec<ChildSpec>` verbatim as a `&[ChildSpec]`
13527 // slice-view over the same backing buffer the raw
13528 // `self.children.as_slice()` field access borrows from, byte-
13529 // equal across every representative fixture in the accept-set —
13530 // the empty slice (the `SimpleOneForOne`-arm sentinel),
13531 // the singleton slice (the minimal non-`SimpleOneForOne` shape),
13532 // and a two-child cohort (a peer non-`SimpleOneForOne` shape
13533 // with the peer three restart-policy variants in play).
13534 //
13535 // Pins against a future silent detour that returned
13536 // `&Vec<ChildSpec>` (which would type-check but leak the
13537 // storage-side `Vec`'s grow/push/reserve surface no consumer of
13538 // the typed view reaches for), a fresh-allocated
13539 // `Vec<ChildSpec>` copy (which would type-check via a coercion
13540 // but silently break every downstream caller that relied on the
13541 // slice sharing the backing buffer's identity), or an
13542 // out-of-order or length-drifted projection (which would silently
13543 // split the per-child validate loop's traversal input from the
13544 // paired partition-dispatch `.is_empty()` probe's input).
13545 //
13546 // Peer of the sibling
13547 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
13548 // (eafb619) `Copy`-composite-enum byte-equal pin on the
13549 // per-`:supervisor` sibling-restart-strategy axis, extended onto
13550 // the per-`:supervisor` static-child-list `Vec`-carry axis.
13551 let fixtures: Vec<Vec<ChildSpec>> = vec![
13552 Vec::new(),
13553 vec![child("worker", "^0.1", RestartPolicy::Permanent)],
13554 vec![
13555 child("worker", "^0.1", RestartPolicy::Permanent),
13556 child("cache-server", "^0.1", RestartPolicy::Transient),
13557 ],
13558 vec![
13559 child("worker", "^0.1", RestartPolicy::Permanent),
13560 child("cache-server", "^0.1", RestartPolicy::Transient),
13561 child("scratch-job", "^0.1", RestartPolicy::Temporary),
13562 ],
13563 ];
13564 for children in fixtures {
13565 let s = SupervisorSpec {
13566 children: children.clone(),
13567 ..SupervisorSpec::default()
13568 };
13569 assert_eq!(
13570 s.children(),
13571 children.as_slice(),
13572 "SupervisorSpec::children must return :supervisor \
13573 :children verbatim (got {:?}, expected {:?})",
13574 s.children(),
13575 children.as_slice(),
13576 );
13577 assert_eq!(
13578 s.children(),
13579 s.children.as_slice(),
13580 "SupervisorSpec::children accessor and \
13581 .children.as_slice() field access must byte-equal — \
13582 the accessor is the substrate-primitive typed \
13583 dispatch every downstream static-child-list consumer \
13584 must route through",
13585 );
13586 assert_eq!(
13587 s.children().len(),
13588 s.children.len(),
13589 "SupervisorSpec::children().len() must byte-equal \
13590 self.children.len() — a length-drift would silently \
13591 split the paired partition-dispatch `.is_empty()` \
13592 probe input from the per-child validate loop's \
13593 traversal input",
13594 );
13595 }
13596 }
13597
13598 #[test]
13599 fn validate_reads_through_lifted_children_accessor() {
13600 // Three-consumer coherence pin: the [`SupervisorSpec::validate`]
13601 // `SimpleOneForOne`-arm `!self.children().is_empty()` refusal
13602 // probe (which must trip [`SupervisorError::SimpleOneForOneWithStaticChildren`]
13603 // when the accessor projects a non-empty slice under a
13604 // `SimpleOneForOne` estrategia), the peer non-`SimpleOneForOne`-arm
13605 // `self.children().is_empty()` refusal probe (which must trip
13606 // [`SupervisorError::NoChildren`] when the accessor projects the
13607 // empty slice under any peer estrategia), and the per-child
13608 // validate loop's `for child in self.children()` traversal
13609 // (which must reach every entry in the same order the accessor
13610 // projects) must all key off the lifted accessor, so any future
13611 // rebrand on the typed slot's reader shape lands at exactly one
13612 // place. Pins the three-site coherence by exercising each
13613 // production consumer end-to-end: (1) the
13614 // `SimpleOneForOneWithStaticChildren` refusal under a non-empty
13615 // slice + `SimpleOneForOne` estrategia, (2) the `NoChildren`
13616 // refusal under the empty slice + non-`SimpleOneForOne`
13617 // estrategia across every peer variant, and (3) the per-child
13618 // duplicate-detection surface fires on the second entry of a
13619 // two-child cohort that shares a `:caixa` name (which requires
13620 // the loop to reach both entries — a first-entry-only projection
13621 // would silently pass since the dedup HashSet has room for the
13622 // first insert).
13623 //
13624 // Peer of the sibling M2
13625 // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
13626 // two-consumer coherence pin on the per-`:supervisor`
13627 // sibling-restart-strategy axis, extended onto the
13628 // per-`:supervisor` static-child-list `Vec`-carry axis.
13629
13630 // (1) `SimpleOneForOne`-arm probe: a non-empty slice under a
13631 // `SimpleOneForOne` estrategia must trip
13632 // `SimpleOneForOneWithStaticChildren`.
13633 let s = SupervisorSpec {
13634 estrategia: RestartStrategy::SimpleOneForOne,
13635 children: vec![child("worker", "^0.1", RestartPolicy::Permanent)],
13636 ..SupervisorSpec::default()
13637 };
13638 assert_eq!(
13639 s.validate().unwrap_err(),
13640 SupervisorError::SimpleOneForOneWithStaticChildren,
13641 "SimpleOneForOne + non-empty children must trip \
13642 SimpleOneForOneWithStaticChildren — the accessor projects \
13643 a non-empty slice, and the SimpleOneForOne-arm refusal \
13644 probe reads through the lifted accessor",
13645 );
13646 assert!(
13647 !s.children().is_empty(),
13648 "the SimpleOneForOne-arm refusal input must be a non-empty \
13649 slice per the accessor's projection",
13650 );
13651
13652 // (2) Peer non-`SimpleOneForOne`-arm probe: the empty slice
13653 // under any peer estrategia must trip `NoChildren`.
13654 for estrategia in [
13655 RestartStrategy::OneForOne,
13656 RestartStrategy::OneForAll,
13657 RestartStrategy::RestForOne,
13658 ] {
13659 let s = SupervisorSpec {
13660 estrategia,
13661 children: Vec::new(),
13662 ..SupervisorSpec::default()
13663 };
13664 match s.validate().unwrap_err() {
13665 SupervisorError::NoChildren { estrategia: e } => {
13666 assert_eq!(
13667 e, estrategia,
13668 "NoChildren.estrategia must carry the author-\
13669 declared :supervisor :estrategia variant \
13670 verbatim (got {e:?}, expected {estrategia:?})",
13671 );
13672 }
13673 other => panic!(
13674 "expected NoChildren, got {other:?} for \
13675 estrategia={estrategia:?}"
13676 ),
13677 }
13678 assert!(
13679 s.children().is_empty(),
13680 "the non-SimpleOneForOne-arm refusal input must be the \
13681 empty slice per the accessor's projection",
13682 );
13683 }
13684
13685 // (3) Per-child validate loop: a two-child cohort that shares a
13686 // `:caixa` name must trip `DuplicateChildCaixa` — the loop must
13687 // reach both entries through the accessor.
13688 let s = SupervisorSpec {
13689 estrategia: RestartStrategy::OneForOne,
13690 children: vec![
13691 child("worker", "^0.1", RestartPolicy::Permanent),
13692 child("worker", "^0.2", RestartPolicy::Transient),
13693 ],
13694 ..SupervisorSpec::default()
13695 };
13696 match s.validate().unwrap_err() {
13697 SupervisorError::DuplicateChildCaixa { caixa } => {
13698 assert_eq!(
13699 caixa, "worker",
13700 "DuplicateChildCaixa.caixa must carry the shared \
13701 child `:caixa` name verbatim",
13702 );
13703 }
13704 other => panic!("expected DuplicateChildCaixa, got {other:?}"),
13705 }
13706 assert_eq!(
13707 s.children().len(),
13708 2,
13709 "the per-child validate loop's traversal input must be a \
13710 two-element slice per the accessor's projection",
13711 );
13712 }
13713
13714 // Shared helper for the M2 per-`:children` per-slot-gate ≡
13715 // `validate` equivalence pins: builds an `OneForOne`-estrategia
13716 // one-cohort spec whose peer `:estrategia`↔`:children.is_empty()`
13717 // partition, `:max-restarts` zero-floor/cap, and `:restart-window`
13718 // bracket all pass cleanly so the sole failing surface is the
13719 // per-child cascade [`SupervisorSpec::validate_children`] owns, and
13720 // pins the two-altitude equivalence on the paired probe.
13721 fn assert_validate_children_matches_gate(children: Vec<ChildSpec>, expected: &SupervisorError) {
13722 let s = SupervisorSpec {
13723 estrategia: RestartStrategy::OneForOne,
13724 children,
13725 ..SupervisorSpec::default()
13726 };
13727 let via_gate = s.validate_children().unwrap_err();
13728 let via_validate = s.validate().unwrap_err();
13729 assert_eq!(&via_gate, expected, "validate_children direct dispatch",);
13730 assert_eq!(&via_validate, expected, "validate() end-to-end dispatch",);
13731 assert_eq!(
13732 via_gate, via_validate,
13733 "per-slot gate ≡ validate() must discriminate the same \
13734 refusal shape",
13735 );
13736 }
13737
13738 #[test]
13739 fn validate_children_matches_gate_on_per_axis_refusal_shapes() {
13740 // Fail-before-pass-after equivalence pin on the M2
13741 // per-`:children` per-slot gate ≡ [`SupervisorSpec::validate`]
13742 // convergence — sibling of the M3 mesh-slot
13743 // `validate_membros_*` / `validate_contratos_*` /
13744 // `validate_entrada_*` per-slot-gate ≡ `validate` pins on the
13745 // peer per-entry axes. Sweeps four of the five refusal shapes
13746 // the per-slot gate owns: (1) `EmptyChildName` on an empty-
13747 // `:caixa` child, (2) `ChildCaixaInvalid` on a structurally
13748 // invalid `:caixa` DNS-1123 label, (3) `EmptyChildVersion` on
13749 // an empty-`:versao` child, (4) `DuplicateChildCaixa` on a
13750 // duplicate-`:caixa` fan-out. Companion pin
13751 // `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
13752 // covers `ChildVersaoInvalid` (whose parser-owned reason string
13753 // needs pattern-matching, not equality) and the clean-pass
13754 // canonical fixture; together the two pins guarantee the
13755 // per-slot gate and `validate` discriminate the same set on
13756 // every per-child-covered input.
13757 assert_validate_children_matches_gate(
13758 vec![child("", "^0.1", RestartPolicy::Permanent)],
13759 &SupervisorError::EmptyChildName,
13760 );
13761 assert_validate_children_matches_gate(
13762 vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
13763 &SupervisorError::ChildCaixaInvalid {
13764 caixa: "Worker".into(),
13765 reason: "contains uppercase character 'W' (K8s DNS-1123 label names are lowercase-only; use \"worker\")".into(),
13766 },
13767 );
13768 assert_validate_children_matches_gate(
13769 vec![child("worker", "", RestartPolicy::Permanent)],
13770 &SupervisorError::EmptyChildVersion {
13771 caixa: "worker".into(),
13772 },
13773 );
13774 assert_validate_children_matches_gate(
13775 vec![
13776 child("worker", "^0.1", RestartPolicy::Permanent),
13777 child("worker", "^0.2", RestartPolicy::Transient),
13778 ],
13779 &SupervisorError::DuplicateChildCaixa {
13780 caixa: "worker".into(),
13781 },
13782 );
13783 }
13784
13785 #[test]
13786 fn validate_children_matches_gate_on_versao_invalid_and_clean_pass() {
13787 // Second half of the two-altitude equivalence pin — covers the
13788 // one refusal shape whose reason string is parser-owned
13789 // (`ChildVersaoInvalid`, whose reason comes from the shared
13790 // [`crate::version::parse_requirement`] impl and may drift) and
13791 // the clean-pass canonical fixture. Sibling pin
13792 // `validate_children_matches_gate_on_per_axis_refusal_shapes`
13793 // covers the four equality-comparable refusal shapes.
13794 let s_bad_versao = SupervisorSpec {
13795 estrategia: RestartStrategy::OneForOne,
13796 children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
13797 ..SupervisorSpec::default()
13798 };
13799 let via_gate = s_bad_versao.validate_children().unwrap_err();
13800 let via_validate = s_bad_versao.validate().unwrap_err();
13801 match (&via_gate, &via_validate) {
13802 (
13803 SupervisorError::ChildVersaoInvalid {
13804 caixa: cg,
13805 versao: vg,
13806 ..
13807 },
13808 SupervisorError::ChildVersaoInvalid {
13809 caixa: cv,
13810 versao: vv,
13811 ..
13812 },
13813 ) => {
13814 assert_eq!(cg, "worker", "per-slot gate :caixa carrier");
13815 assert_eq!(vg, "not-a-req", "per-slot gate :versao carrier");
13816 assert_eq!(cv, "worker", "validate() :caixa carrier");
13817 assert_eq!(vv, "not-a-req", "validate() :versao carrier");
13818 }
13819 other => panic!("expected ChildVersaoInvalid on both altitudes, got {other:?}"),
13820 }
13821 assert_eq!(
13822 via_gate, via_validate,
13823 "per-slot gate ≡ validate() on ChildVersaoInvalid full envelope",
13824 );
13825
13826 let s_ok = SupervisorSpec {
13827 estrategia: RestartStrategy::OneForOne,
13828 children: vec![
13829 child("worker-a", "^0.1", RestartPolicy::Permanent),
13830 child("worker-b", "~0.2.3", RestartPolicy::Transient),
13831 child("collector", "*", RestartPolicy::Temporary),
13832 ],
13833 ..SupervisorSpec::default()
13834 };
13835 s_ok.validate_children()
13836 .expect("per-slot gate must accept the clean-pass fixture");
13837 s_ok.validate()
13838 .expect("validate() must accept the clean-pass fixture");
13839 }
13840
13841 #[test]
13842 fn validate_children_is_self_contained_on_children_slot() {
13843 // Self-containment pin: [`SupervisorSpec::validate_children`]
13844 // resolves the per-child cascade against `&self` alone, without
13845 // depending on the peer `:estrategia`/`:max-restarts`/
13846 // `:restart-window` gates having run first — same posture the M3
13847 // peer per-slot gates carry (`validate_membros`,
13848 // `validate_contratos`, `validate_entrada`, `validate_placement`,
13849 // routing through their own oracles rather than borrowing state
13850 // threaded down from `validate`). A future consumer that reaches
13851 // the per-slot gate directly on a spec whose peer slots would
13852 // fail `validate` still surfaces the per-child refusal, not the
13853 // peer refusal.
13854 //
13855 // Construct a spec whose `:max-restarts` is `0` (which would
13856 // trip [`SupervisorError::ZeroMaxRestarts`] at `validate` after
13857 // the partition-dispatch) and whose `:children` carries a
13858 // `DuplicateChildCaixa` shape: the per-slot gate called directly
13859 // must surface `DuplicateChildCaixa`, proving it does not depend
13860 // on the peer `:max-restarts` gate running first.
13861 let s = SupervisorSpec {
13862 estrategia: RestartStrategy::OneForOne,
13863 max_restarts: 0,
13864 restart_window: Some(Duration::from_secs(60)),
13865 children: vec![
13866 child("worker", "^0.1", RestartPolicy::Permanent),
13867 child("worker", "^0.2", RestartPolicy::Transient),
13868 ],
13869 };
13870 assert_eq!(
13871 s.validate_children().unwrap_err(),
13872 SupervisorError::DuplicateChildCaixa {
13873 caixa: "worker".into(),
13874 },
13875 "per-slot gate must resolve per-child refusal directly against \
13876 `&self` — a dependency on the peer `:max-restarts` gate \
13877 running first would surface ZeroMaxRestarts here instead",
13878 );
13879 // The peer gate is still the surface `validate` reaches — pin
13880 // the ordering to establish that `validate_children` truly runs
13881 // last in `validate`'s dispatch, so a direct call bypasses the
13882 // peer gates on any spec whose per-child cascade would fail.
13883 assert_eq!(
13884 s.validate().unwrap_err(),
13885 SupervisorError::ZeroMaxRestarts,
13886 "validate() must surface the peer `:max-restarts` gate before \
13887 reaching the per-child cascade — this pins the dispatch \
13888 ordering the per-slot gate's self-containment complements",
13889 );
13890 }
13891
13892 #[test]
13893 fn child_spec_restart_accessor_is_const_fn() {
13894 // The [`ChildSpec::restart`] per-`:children` restart-decision-
13895 // policy `Copy`-return scalar accessor is declared
13896 // `#[must_use] pub const fn` — matching the sibling M2
13897 // per-`:supervisor` [`SupervisorSpec::estrategia`] (pinned by
13898 // [`supervisor_spec_estrategia_accessor_is_const_fn`] below,
13899 // both converted in this commit), the sibling M2
13900 // per-`:supervisor` [`SupervisorSpec::max_restarts`] (b698ec0)
13901 // `Copy`-`u32` accessor already `pub const fn`, and the peer M3
13902 // mesh-slot per-`:entrada` [`crate::Entrada::port`] (bafa004) /
13903 // per-`:placement` [`crate::Placement::estrategia`] (bafa004)
13904 // `Copy`-return `pub const fn` scalar accessors on the sibling
13905 // M3 surface. Pin the `const`-eval posture here so a future
13906 // accidental downgrade to non-`const` (an added runtime helper
13907 // reachable only from a non-`const` context, an
13908 // `Option<RestartPolicy>`-shape migration on the per-child
13909 // restart-decision axis once heterogeneous per-cluster
13910 // restart-policy overlays land that would silently drop the
13911 // `const` qualifier, a manual hand-rolled shadow) trips at
13912 // caixa-core build time rather than surfacing as a downstream
13913 // `const`-context regression far from the declaration.
13914 //
13915 // Same shape as the sibling M3
13916 // [`crate::aplicacao::tests::placement_estrategia_accessor_is_const_fn`]
13917 // and [`crate::aplicacao::tests::entrada_port_accessor_is_const_fn`]
13918 // (bafa004) pins on the peer M3 mesh-slot `Copy`-return scalar
13919 // accessor axis — the load-bearing witness lives in the
13920 // module-scope `const fn` wrapper `restart_via_const_fn` below:
13921 // a body that calls [`ChildSpec::restart`] under a `const fn`
13922 // signature is well-formed only when the callee is itself
13923 // `const fn`, so any future accidental downgrade of
13924 // [`ChildSpec::restart`] to non-`const` fails at caixa-core
13925 // build time (const-eval E0015 `cannot call non-const method`),
13926 // strictly stronger than a runtime `assert!(CONST)` and
13927 // side-stepping the destructor-in-const restriction that
13928 // blocks direct `const _: RestartPolicy = FIXTURE.restart()`
13929 // items on `ChildSpec`'s `String` carriers.
13930 //
13931 // The runtime body sweeps every closed-set [`RestartPolicy`]
13932 // arm and asserts the wrapped and direct dispatches agree.
13933 const fn restart_via_const_fn(c: &ChildSpec) -> RestartPolicy {
13934 c.restart()
13935 }
13936 for restart in [
13937 RestartPolicy::Permanent,
13938 RestartPolicy::Transient,
13939 RestartPolicy::Temporary,
13940 ] {
13941 let c = ChildSpec {
13942 caixa: "worker".into(),
13943 versao: "^0.1".into(),
13944 restart,
13945 };
13946 assert_eq!(
13947 restart_via_const_fn(&c),
13948 c.restart(),
13949 "const-fn-wrapped and direct dispatch on \
13950 ChildSpec::restart must agree for {restart:?}",
13951 );
13952 assert_eq!(
13953 c.restart(),
13954 restart,
13955 "ChildSpec::restart must return the storage-side \
13956 RestartPolicy verbatim for {restart:?} (a violation \
13957 means the accessor stopped being a raw field-return \
13958 copy)",
13959 );
13960 }
13961 }
13962
13963 #[test]
13964 fn supervisor_spec_estrategia_accessor_is_const_fn() {
13965 // The [`SupervisorSpec::estrategia`] per-`:supervisor`
13966 // sibling-restart-strategy `Copy`-return scalar accessor is
13967 // declared `#[must_use] pub const fn` — matching the sibling M2
13968 // per-`:children` [`ChildSpec::restart`] (pinned by
13969 // [`child_spec_restart_accessor_is_const_fn`] above, both
13970 // converted in this commit), the sibling M2 per-`:supervisor`
13971 // [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32`
13972 // accessor already `pub const fn`, and mirroring the peer M3
13973 // mesh-slot per-`:placement`
13974 // [`crate::Placement::estrategia`] (bafa004) `Copy`-return
13975 // `pub const fn` scalar accessor whose method-name discipline
13976 // the [`SupervisorSpec::estrategia`] method was authored to
13977 // match. Pin the `const`-eval posture here so a future
13978 // accidental downgrade to non-`const` (an added runtime helper
13979 // reachable only from a non-`const` context, an
13980 // `Option<RestartStrategy>`-shape migration once the substrate
13981 // grows per-cluster strategy overlays that would silently drop
13982 // the `const` qualifier, a manual hand-rolled shadow) trips at
13983 // caixa-core build time rather than surfacing as a downstream
13984 // `const`-context regression far from the declaration.
13985 //
13986 // Same shape as the sibling
13987 // [`child_spec_restart_accessor_is_const_fn`] pin above — the
13988 // load-bearing witness lives in the module-scope `const fn`
13989 // wrapper `estrategia_via_const_fn` below: a body that calls
13990 // [`SupervisorSpec::estrategia`] under a `const fn` signature
13991 // is well-formed only when the callee is itself `const fn`,
13992 // side-stepping the destructor-in-const restriction that would
13993 // otherwise block a direct
13994 // `const _: RestartStrategy = FIXTURE.estrategia()` item on
13995 // `SupervisorSpec`'s `Vec<ChildSpec>` / `Option<Duration>`
13996 // carriers.
13997 //
13998 // The runtime body sweeps every closed-set [`RestartStrategy`]
13999 // arm via [`RestartStrategy::ALL`] and asserts the wrapped and
14000 // direct dispatches agree.
14001 const fn estrategia_via_const_fn(s: &SupervisorSpec) -> RestartStrategy {
14002 s.estrategia()
14003 }
14004 for &estrategia in RestartStrategy::ALL {
14005 let s = SupervisorSpec {
14006 estrategia,
14007 max_restarts: 5,
14008 restart_window: Some(Duration::from_secs(60)),
14009 children: Vec::new(),
14010 };
14011 assert_eq!(
14012 estrategia_via_const_fn(&s),
14013 s.estrategia(),
14014 "const-fn-wrapped and direct dispatch on \
14015 SupervisorSpec::estrategia must agree for {estrategia:?}",
14016 );
14017 assert_eq!(
14018 s.estrategia(),
14019 estrategia,
14020 "SupervisorSpec::estrategia must return the storage-side \
14021 RestartStrategy verbatim for {estrategia:?} (a violation \
14022 means the accessor stopped being a raw field-return \
14023 copy)",
14024 );
14025 }
14026 }
14027
14028 // Per-variant equivalence pins for the [`supervisor_caixa_only_ctors!`]
14029 // macro definition (see the paired doc-block above the macro
14030 // definition) — every generated `<ctor>(caixa: &str) -> Self`
14031 // constructor folds the uniform `Self::<Variant> { caixa:
14032 // caixa.to_string() }` one-field struct-literal onto one substrate
14033 // primitive. The three per-variant equivalence pins below
14034 // (fail-before-pass-after by construction — a byte-mismatched macro
14035 // arm would trip its equivalence pin first) lock each generated
14036 // constructor to its struct-literal peer under `PartialEq`, so
14037 // every wire-up in [`SupervisorSpec::validate_children`] and
14038 // [`validate_no_self_supervision`] on that variant produces a
14039 // byte-equal `SupervisorError` to the pre-lift open-coded
14040 // struct-literal. The cross-axis pin that follows (non-default
14041 // caixa name) routes the sole constructor input axis through
14042 // `.to_string()`, so the fold does not silently collapse onto a
14043 // fixed name.
14044 //
14045 // Peer of the sibling `<slot>_ctor_matches_tuple_literal_wrap` /
14046 // `<slot>_violation_ctor_matches_struct_literal_wrap` /
14047 // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
14048 // `missing_entry_ctor_matches_struct_literal_wrap` /
14049 // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
14050 // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
14051 // `contrato_missing_target_ctor_matches_struct_literal_wrap` /
14052 // `<variant>_ctor_matches_struct_literal_wrap` equivalence pins
14053 // on the six sibling ctor families the recent trajectory closed
14054 // on the peer `LayoutError` / `AplicacaoError` envelopes.
14055
14056 #[test]
14057 fn empty_child_version_ctor_matches_struct_literal_wrap() {
14058 assert_eq!(
14059 SupervisorError::empty_child_version("worker"),
14060 SupervisorError::EmptyChildVersion {
14061 caixa: "worker".to_string(),
14062 },
14063 "generated empty_child_version ctor must produce byte-equal \
14064 SupervisorError to the open-coded struct-literal wrap on the \
14065 same &str fixture",
14066 );
14067 }
14068
14069 #[test]
14070 fn duplicate_child_caixa_ctor_matches_struct_literal_wrap() {
14071 assert_eq!(
14072 SupervisorError::duplicate_child_caixa("worker"),
14073 SupervisorError::DuplicateChildCaixa {
14074 caixa: "worker".to_string(),
14075 },
14076 "generated duplicate_child_caixa ctor must produce byte-equal \
14077 SupervisorError to the open-coded struct-literal wrap on the \
14078 same &str fixture",
14079 );
14080 }
14081
14082 #[test]
14083 fn child_supervises_self_ctor_matches_struct_literal_wrap() {
14084 assert_eq!(
14085 SupervisorError::child_supervises_self("orquestra"),
14086 SupervisorError::ChildSupervisesSelf {
14087 caixa: "orquestra".to_string(),
14088 },
14089 "generated child_supervises_self ctor must produce byte-equal \
14090 SupervisorError to the open-coded struct-literal wrap on the \
14091 same &str fixture",
14092 );
14093 }
14094
14095 // Per-variant equivalence pins for the two lifted
14096 // [`SupervisorError::child_caixa_invalid`] /
14097 // [`SupervisorError::child_versao_invalid`] inherent constructors
14098 // (fail-before-pass-after by construction — a byte-mismatched ctor body
14099 // would trip its equivalence pin first). Each pins the ctor output to
14100 // its pre-lift struct-literal peer under `PartialEq`, so every wire-up
14101 // in [`SupervisorSpec::validate_children`] on the two variants
14102 // produces a byte-equal `SupervisorError` to the pre-lift open-coded
14103 // struct-literal on the same scalar fixtures. Peers of the sibling
14104 // `membro_caixa_invalid_ctor_matches_struct_literal_wrap` /
14105 // `entrada_para_invalid_ctor_matches_struct_literal_wrap` / … pins on
14106 // the peer `AplicacaoError` envelope's
14107 // [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold.
14108
14109 #[test]
14110 fn child_caixa_invalid_ctor_matches_struct_literal_wrap() {
14111 let caixa = "Worker";
14112 let reason = "sample reason text";
14113 assert_eq!(
14114 SupervisorError::child_caixa_invalid(caixa, reason),
14115 SupervisorError::ChildCaixaInvalid {
14116 caixa: caixa.to_string(),
14117 reason: reason.to_string(),
14118 },
14119 "lifted child_caixa_invalid ctor must produce byte-equal \
14120 SupervisorError to the open-coded struct-literal wrap on the \
14121 same (&str, reason) fixture",
14122 );
14123 }
14124
14125 #[test]
14126 fn child_versao_invalid_ctor_matches_struct_literal_wrap() {
14127 let caixa = "worker";
14128 let versao = "not-a-req";
14129 let reason = "sample reason text";
14130 assert_eq!(
14131 SupervisorError::child_versao_invalid(caixa, versao, reason),
14132 SupervisorError::ChildVersaoInvalid {
14133 caixa: caixa.to_string(),
14134 versao: versao.to_string(),
14135 reason: reason.to_string(),
14136 },
14137 "lifted child_versao_invalid ctor must produce byte-equal \
14138 SupervisorError to the open-coded struct-literal wrap on the \
14139 same (&str, &str, reason) fixture",
14140 );
14141 }
14142
14143 #[test]
14144 fn supervisor_child_reason_ctors_route_reason_through_into_uniformly() {
14145 // Cross-axis pin: sweep the two lifted `{ …, reason }` ctors
14146 // against a `&str`-literal vs. `format!(…)` reason input to pin
14147 // both constructors accept the `impl Into<String>` bound
14148 // uniformly, so neither wire-up site drifts under a per-arm
14149 // wrapper transformation on the caller-side `reason` axis. Peer
14150 // of the sibling
14151 // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
14152 // sweep on the peer `AplicacaoError` envelope.
14153 let via_literal = "literal reason text";
14154 let via_format = format!("{} reason text", "literal");
14155 assert_eq!(
14156 SupervisorError::child_caixa_invalid("Worker", via_literal),
14157 SupervisorError::child_caixa_invalid("Worker", via_format.clone()),
14158 );
14159 assert_eq!(
14160 SupervisorError::child_versao_invalid("worker", "not-a-req", via_literal),
14161 SupervisorError::child_versao_invalid("worker", "not-a-req", via_format),
14162 );
14163 }
14164
14165 #[test]
14166 fn supervisor_caixa_only_ctors_route_caixa_through_to_string() {
14167 // Cross-axis pin: sweep the sole constructor input axis (`caixa:
14168 // &str`) through a non-default fixture name against every
14169 // generated arm in the [`supervisor_caixa_only_ctors!`] macro,
14170 // so any wrapper-side lowercase / trim / truncate / re-order on
14171 // the `caixa.to_string()` sole-field construction surfaces
14172 // here rather than at a downstream diagnostic-shape mismatch.
14173 // Peer of the sibling `nome_only_ctor_routes_caixa_through_
14174 // nome_accessor` / `entrada_host_invalid_ctor_routes_host_
14175 // through_to_string` / `contrato_target_ctors_route_edge_
14176 // triple_through_verbatim` / `contrato_empty_pair_ctors_
14177 // route_edge_pair_through_verbatim` cross-axis routing pins on
14178 // the peer `LayoutError` / `AplicacaoError` envelopes; extended
14179 // here onto the `SupervisorError` `{ caixa: String }` envelope
14180 // so every substrate-primitive ctor family in caixa-core
14181 // guarantees the sole-field construction routes the caller's
14182 // `&str` through `.to_string()` verbatim.
14183 let name = "cache-v2";
14184 assert_eq!(
14185 SupervisorError::empty_child_version(name),
14186 SupervisorError::EmptyChildVersion {
14187 caixa: name.to_string(),
14188 },
14189 );
14190 assert_eq!(
14191 SupervisorError::duplicate_child_caixa(name),
14192 SupervisorError::DuplicateChildCaixa {
14193 caixa: name.to_string(),
14194 },
14195 );
14196 assert_eq!(
14197 SupervisorError::child_supervises_self(name),
14198 SupervisorError::ChildSupervisesSelf {
14199 caixa: name.to_string(),
14200 },
14201 );
14202 }
14203
14204 // ── supervisor_scalar_ctors! per-variant + cross-axis pins ──────────────
14205 //
14206 // Per-variant byte-equality pins guaranteeing every generated ctor arm in
14207 // the [`supervisor_scalar_ctors!`] macro produces a `SupervisorError`
14208 // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
14209 // one-line struct-literal on the same `Copy`-`RestartStrategy | u32 |
14210 // Duration` fixture, plus one cross-axis sweep that routes each per-variant
14211 // `<field>: <ty>` scalar through the sole `$field:ident: $ty:ty` axis the
14212 // macro exposes so any wrapper-side truncation / re-order / silent `.into()`
14213 // / silent constant-substitution on any one variant surfaces here rather
14214 // than at a downstream per-`:supervisor` diagnostic-shape drift. Peer of the
14215 // sibling per-variant pins on `aplicacao_policy_scalar_ctors!` (7ef425e,
14216 // the 8-variant `AplicacaoError` `{ <field>: Duration | u32 }` fold on the
14217 // per-`:politicas` per-axis cap / canonical-form arms), plus the sibling
14218 // `supervisor_caixa_only_ctors!` (db09650), `SupervisorError::
14219 // {child_caixa_invalid,child_versao_invalid}` (d2ef2ec), and the peer
14220 // `DepError` / `AplicacaoError` / `LayoutError` / `LimitsError` /
14221 // `BehaviorError` / `UpgradeError` per-envelope ctor-macro pins.
14222 #[test]
14223 fn no_children_ctor_matches_struct_literal_wrap() {
14224 let estrategia = RestartStrategy::OneForAll;
14225 assert_eq!(
14226 SupervisorError::no_children(estrategia),
14227 SupervisorError::NoChildren { estrategia },
14228 "generated no_children ctor must produce byte-equal \
14229 `SupervisorError::NoChildren` to the pre-lift struct-literal wrap \
14230 on the same `Copy`-`RestartStrategy` fixture",
14231 );
14232 }
14233
14234 #[test]
14235 fn max_restarts_exceeds_cap_ctor_matches_struct_literal_wrap() {
14236 let max_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 1;
14237 assert_eq!(
14238 SupervisorError::max_restarts_exceeds_cap(max_restarts),
14239 SupervisorError::MaxRestartsExceedsCap { max_restarts },
14240 "generated max_restarts_exceeds_cap ctor must produce byte-equal \
14241 `SupervisorError::MaxRestartsExceedsCap` to the pre-lift \
14242 struct-literal wrap on the same `Copy`-`u32` fixture",
14243 );
14244 }
14245
14246 #[test]
14247 fn restart_window_not_canonical_ctor_matches_struct_literal_wrap() {
14248 let window = Duration::from_micros(1_500);
14249 assert_eq!(
14250 SupervisorError::restart_window_not_canonical(window),
14251 SupervisorError::RestartWindowNotCanonical { window },
14252 "generated restart_window_not_canonical ctor must produce \
14253 byte-equal `SupervisorError::RestartWindowNotCanonical` to the \
14254 pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
14255 );
14256 }
14257
14258 #[test]
14259 fn restart_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
14260 let window = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
14261 assert_eq!(
14262 SupervisorError::restart_window_exceeds_cap(window),
14263 SupervisorError::RestartWindowExceedsCap { window },
14264 "generated restart_window_exceeds_cap ctor must produce \
14265 byte-equal `SupervisorError::RestartWindowExceedsCap` to the \
14266 pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
14267 );
14268 }
14269
14270 #[test]
14271 fn supervisor_scalar_ctors_route_field_through_copy_uniformly() {
14272 // Cross-axis routing pin: sweep each generated `<field>: <ty>`
14273 // constructor input axis through a non-default `Copy` fixture against
14274 // every arm in the [`supervisor_scalar_ctors!`] macro, so any wrapper-
14275 // side silent `.into()` / silent constant-substitution / silent field
14276 // re-name away from the canonical `estrategia | max_restarts | window`
14277 // axes on any one variant, or a `RestartStrategy | u32 | Duration`
14278 // axis silently rerouted through some other `Copy` coercion, surfaces
14279 // here rather than at a downstream per-`:supervisor` diagnostic-shape
14280 // drift. Peer of the sibling
14281 // `aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly`
14282 // (7ef425e) cross-axis routing pin on the peer `AplicacaoError`
14283 // envelope's per-`:politicas` per-axis ctor family, extended here onto
14284 // the last M2 per-`:supervisor` `Copy`-scalar `SupervisorError`
14285 // variant family folded onto a substrate primitive.
14286 //
14287 // Fixtures picked out of each variant's accept-set boundary rather
14288 // than the default value so a silent constant-substitution to a per-
14289 // variant sentinel surfaces here on the structural-equality assertion.
14290 // The `RestartStrategy` fixture picks `RestForOne` (a non-default arm
14291 // that isn't the `OneForOne` [`SUPERVISOR_ESTRATEGIA_DEFAULT`] and
14292 // isn't the `SimpleOneForOne` arm the sibling
14293 // `SimpleOneForOneWithStaticChildren` unit variant intercepts). The
14294 // `max_restarts` fixture picks an above-cap magnitude the cap arm
14295 // rejects; the two `Duration` fixtures pick the sub-millisecond and
14296 // above-cap ends of the `:restart-window` canonical-form + cap
14297 // bracket respectively.
14298 let estrategia = RestartStrategy::RestForOne;
14299 let above_cap_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 137;
14300 let sub_ms = Duration::from_micros(1_500);
14301 let above_hour = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
14302 assert_eq!(
14303 SupervisorError::no_children(estrategia),
14304 SupervisorError::NoChildren { estrategia },
14305 );
14306 assert_eq!(
14307 SupervisorError::max_restarts_exceeds_cap(above_cap_restarts),
14308 SupervisorError::MaxRestartsExceedsCap {
14309 max_restarts: above_cap_restarts,
14310 },
14311 );
14312 assert_eq!(
14313 SupervisorError::restart_window_not_canonical(sub_ms),
14314 SupervisorError::RestartWindowNotCanonical { window: sub_ms },
14315 );
14316 assert_eq!(
14317 SupervisorError::restart_window_exceeds_cap(above_hour),
14318 SupervisorError::RestartWindowExceedsCap { window: above_hour },
14319 );
14320 }
14321
14322 #[test]
14323 fn supervisor_scalar_ctors_are_const_zero_runtime_work() {
14324 // Const-eval pin: the [`supervisor_scalar_ctors!`] macro spells every
14325 // generated ctor `const fn` so a caller can pin a `SupervisorError`
14326 // at compile time — the same zero-runtime-work property the pre-lift
14327 // `|<slot>| SupervisorError::<Variant> { <slot> }` closure carried on
14328 // its `Copy`-pass-through construction path (no `.to_string()` /
14329 // `.into()` allocation, no branching). If any future edit silently
14330 // drops the `const` qualifier from the macro body the per-arm `const`
14331 // bindings below fail to compile, which surfaces the regression at
14332 // the substrate-primitive definition rather than at some downstream
14333 // consumer that had come to rely on the `const`-constructibility.
14334 // Peer of the sibling
14335 // `aplicacao_policy_scalar_ctors_are_const_zero_runtime_work`
14336 // (7ef425e) const-eval pin on the peer `AplicacaoError` envelope's
14337 // per-`:politicas` per-axis ctor family.
14338 const NO_CHILDREN: SupervisorError =
14339 SupervisorError::no_children(RestartStrategy::OneForAll);
14340 const MAX_RESTARTS_CAP: SupervisorError = SupervisorError::max_restarts_exceeds_cap(1_337);
14341 const WINDOW_NC: SupervisorError =
14342 SupervisorError::restart_window_not_canonical(Duration::from_micros(1));
14343 const WINDOW_CAP: SupervisorError =
14344 SupervisorError::restart_window_exceeds_cap(Duration::from_secs(3_601));
14345 assert!(matches!(NO_CHILDREN, SupervisorError::NoChildren { .. }));
14346 assert!(matches!(
14347 MAX_RESTARTS_CAP,
14348 SupervisorError::MaxRestartsExceedsCap { .. }
14349 ));
14350 assert!(matches!(
14351 WINDOW_NC,
14352 SupervisorError::RestartWindowNotCanonical { .. }
14353 ));
14354 assert!(matches!(
14355 WINDOW_CAP,
14356 SupervisorError::RestartWindowExceedsCap { .. }
14357 ));
14358 }
14359}