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/// Substrate-canonical [`AsRef<[u8]>`] byte-view projection on the M2
1327/// OTP-shape sibling-restart [`RestartStrategy`] closed-set fieldless
1328/// typed enum — routes byte-for-byte through the substrate-primitive
1329/// [`RestartStrategy::as_str`] `pub const fn` accessor via
1330/// [`str::as_bytes`] on the returned `&'static str`, so any future
1331/// consumer that binds a [`RestartStrategy`] through a standard-library
1332/// `<T: AsRef<[u8]>>` trait bound reaches the same four-arm lifted
1333/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
1334/// [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
1335/// [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
1336/// [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
1337/// `PascalCase` wire byte-string emit-set the paired sibling
1338/// [`AsRef<str>`] (5b828ed) / [`std::fmt::Display`] /
1339/// [`RestartStrategy::as_str`] str-view surfaces and every
1340/// `{Self, &Self} × {&'static str, String, Cow<'static, str>, Box<str>,
1341/// std::sync::Arc<str>}` reverse-projection corner already return —
1342/// through the byte-view axis, which the str-view axes cannot express.
1343///
1344/// Rust's standard library carries `impl AsRef<[u8]> for str` and
1345/// `impl AsRef<[u8]> for String`, so the two-hop composition
1346/// `strategy.as_str().as_bytes()` (or, equivalently,
1347/// `AsRef::<str>::as_ref(&strategy).as_bytes()`) is reachable through
1348/// the pre-existing str-view axis alone. But that two-hop shape has no
1349/// compile-time link back to the byte-projection axis, forces every
1350/// downstream `<T: AsRef<[u8]>>`-bound consumer to open-code the
1351/// two-hop composition at every call site, and admits a silent split
1352/// whenever a future call site takes a sibling reverse-projection axis
1353/// whose `.as_bytes()` byte-tail carries no compile-time byte-view
1354/// surface (`Display` returns a formatter, `String` / `Box<str>` /
1355/// `Arc<str>` allocate). The lifted single-hop impl closes the
1356/// byte-view axis so every future `<T: AsRef<[u8]>>`-bound consumer
1357/// reaches the substrate primitive through one trait dispatch, and
1358/// every future arm addition (an OTP-`rest_for_all` fifth arm the
1359/// theory
1360/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1361/// might reach for once the four canonical OTP strategies stop covering
1362/// the substrate's discovered load-shape) grows the byte-view axis
1363/// through one edit on the substrate-primitive `as_str` accessor, not a
1364/// coordinated rewrite across every future `<T: AsRef<[u8]>>`-bound
1365/// consumer's arm-set.
1366///
1367/// The primary compounding target is the same `caixa-lacre` BLAKE3
1368/// content-address closure the peer [`crate::CaixaKind`] (69d8d86),
1369/// [`crate::dialeto::CaixaDialeto`] (8151347),
1370/// [`crate::dep::DepList`] (05ffaca),
1371/// [`crate::aplicacao::PlacementStrategy`] (daa8705), and
1372/// [`crate::aplicacao::RateLimitUnit`] (4867e0f) `AsRef<[u8]>` impls
1373/// open onto: [`blake3::hash`] and [`blake3::Hasher::update`] both bind
1374/// their input through `impl AsRef<[u8]>`, so any future per-supervisor
1375/// content-address tag that folds an `:estrategia` discriminator
1376/// byte-tag into the [`crate::Lacre`] closure (a hypothetical
1377/// `hasher.update(estrategia);`-shape composition partitioning the
1378/// four OTP restart-topology closures at content-address time so
1379/// downstream `Lacre` consumers key per-strategy reconciliation caches
1380/// off the typed discriminator rather than the sibling `&'static str`
1381/// wire scalar) reaches the substrate-primitive `as_str` accessor
1382/// through this impl and no other.
1383///
1384/// Opens the trait-idiomatic byte-view axis on the first M2 OTP-shape
1385/// closed-set fieldless typed enum peer on the caixa surface
1386/// (`:supervisor :estrategia`), extending the substrate-wide byte-view
1387/// campaign the sibling [`crate::CaixaKind`] first-mover (69d8d86)
1388/// opened onto the fifth in-caixa-core enum peer. The remaining
1389/// in-caixa-core closed-set fieldless typed-enum peers
1390/// ([`RestartPolicy`], [`crate::aplicacao::WitShape`],
1391/// [`crate::upgrade::UpgradeInstruction`],
1392/// [`crate::render::PathShapeViolation`]) each carry the same
1393/// [`AsRef<str>`] + `pub const fn as_str` substrate-primitive accessor
1394/// discipline, so a future extension of the byte-view axis onto each
1395/// peer reaches through one impl per enum keyed to that peer's
1396/// substrate-primitive accessor.
1397///
1398/// Pinned load-bearing by
1399/// [`tests::restart_strategy_as_ref_bytes_routes_through_as_str_accessor`]
1400/// (fail-before-pass-after byte-parity pin against
1401/// [`RestartStrategy::as_str`] `.as_bytes()` across the four-arm
1402/// [`RestartStrategy::ALL`] emit-set, cross-axis witness against the
1403/// paired str-view [`AsRef<str>`] / [`std::fmt::Display`] /
1404/// [`RestartStrategy::as_str`] axes' `.as_bytes()` byte-tails,
1405/// cross-axis witness against the paired reverse-projection
1406/// `{&'static str, String, Cow<'static, str>, Box<str>,
1407/// std::sync::Arc<str>}` return-shape axes' `.as_bytes()` byte-tails,
1408/// a `<T: AsRef<[u8]>>`-bound-consumer witness that a generic
1409/// byte-input function accepts a [`RestartStrategy`] directly through
1410/// the trait bound, and a `blake3::Hasher::update`-shape byte-input
1411/// surface witness routed through the `<T: AsRef<[u8]>>`-bound
1412/// consumer axis to reach the caixa-lacre compounding target). Any
1413/// future silent detour that routes the byte-view impl off the
1414/// substrate-primitive [`RestartStrategy::as_str`] accessor (a per-arm
1415/// inline `b"OneForOne".as_slice()`-shaped re-inlining that opens a
1416/// compile-time link to the un-lifted arm-literal, a swap onto the
1417/// kebab-case [`gen_platform::Discriminant`] catalog identity that
1418/// would collide the wire axis with the dispatcher-catalog axis) trips
1419/// at caixa-core test time rather than at a downstream byte-consumer's
1420/// silent split.
1421impl AsRef<[u8]> for RestartStrategy {
1422 fn as_ref(&self) -> &[u8] {
1423 self.as_str().as_bytes()
1424 }
1425}
1426
1427/// Per-child restart policy.
1428///
1429/// Permanent / Temporary / Transient match Erlang/OTP semantics 1:1.
1430#[derive(
1431 Serialize,
1432 Deserialize,
1433 Debug,
1434 Clone,
1435 Copy,
1436 PartialEq,
1437 Eq,
1438 Hash,
1439 gen_platform::TypedDispatcher,
1440 gen_platform::Discriminant,
1441 gen_platform::IsVariant,
1442 gen_platform::FromStrKind,
1443)]
1444pub enum RestartPolicy {
1445 /// Always restart the child, regardless of how it died. Used for
1446 /// long-running services that must always be up.
1447 Permanent,
1448 /// Never restart. Used for one-shot work whose completion is
1449 /// itself the success signal (`oneShot` triggers map here).
1450 Temporary,
1451 /// Restart only when the child died *abnormally* (non-zero exit
1452 /// or unhandled exception). A clean exit completes the child.
1453 Transient,
1454}
1455
1456impl Default for RestartPolicy {
1457 fn default() -> Self {
1458 // Route the [`Default for RestartPolicy`] impl's return arm through
1459 // the substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed
1460 // `pub const` rather than a raw `Self::Permanent` arm — one source
1461 // of truth for the Erlang/OTP-canonical `permanent` worker-child
1462 // default across the two production consumers that currently
1463 // dispatch on it (this impl at the [`RestartPolicy::default`] call
1464 // and the serde-side `#[serde(default)]` on
1465 // [`ChildSpec::restart`] that resolves an author-omitted
1466 // `:children :restart` slot through `RestartPolicy::default()`).
1467 // Peer of the sibling per-`:supervisor` axis
1468 // [`Default for RestartStrategy`] → [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
1469 // route (95ffacc) — the two impls now share one substrate-primitive
1470 // lift discipline, so any future coherent rebrand of the OTP-shape
1471 // supervisor+child default set migrates through typed constants in
1472 // lockstep instead of splitting a lifted supervisor half against
1473 // an open-coded child half. Pinned by
1474 // `restart_policy_default_routes_through_lifted_default` +
1475 // `child_spec_serde_default_restart_routes_through_lifted_default`
1476 // in the tests module.
1477 SUPERVISOR_CHILD_RESTART_DEFAULT
1478 }
1479}
1480
1481impl RestartPolicy {
1482 /// Exhaustive iteration surface for every consumer that walks the
1483 /// closed three-arm [`RestartPolicy`] discriminator set (the future
1484 /// M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1485 /// per-child admission-webhook rejection body naming the accepted-
1486 /// `:restart` list, a future `feira supervisor --restart …` CLI
1487 /// arg-parse's "did you mean" hint via a [`Self::from_wire`]-scan
1488 /// over the slice, the future `feira app graph` per-child restart
1489 /// column, any future round-trip fuzz harness that sweeps every
1490 /// arm). A future arm addition (an OTP-`intrinsic` fourth arm the
1491 /// theory
1492 /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1493 /// might reach for once the three canonical OTP restart policies
1494 /// stop covering the substrate's discovered load-shape) extends
1495 /// this slice as one edit and every consumer picks up the new entry
1496 /// by construction; the compiler-checked exhaustiveness on the
1497 /// sibling method `match` arms ([`Self::as_str`] / [`Self::from_wire`])
1498 /// is the build-time guarantee that no arm forgets to grow.
1499 ///
1500 /// Peer of the sibling closed-set typed enums'
1501 /// [`RestartStrategy::ALL`] (4eec29c) /
1502 /// [`crate::CaixaKind::ALL`] (6b1f4fb) /
1503 /// [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
1504 /// [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
1505 /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
1506 /// surfaces — the sixth (and the third and final M2 OTP-shape)
1507 /// closed-set typed enum on the caixa surface to converge onto the
1508 /// same one-canonical-arm-list-per-enum discipline. Sibling axis to
1509 /// the peer [`RestartStrategy::ALL`] on the per-supervisor
1510 /// sibling-restart-strategy axis; this closes the per-child
1511 /// restart-decision-policy axis on the same M2 `:supervisor` slot.
1512 pub const ALL: &'static [Self] = &[Self::Permanent, Self::Temporary, Self::Transient];
1513
1514 /// Substrate-canonical exhaustive accept-set on the [`RestartPolicy`]
1515 /// `PascalCase` wire byte-string axis — the closed three-arm roster
1516 /// of every byte-string [`Self::as_str`] returns, routed byte-for-byte
1517 /// through the paired
1518 /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1519 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1520 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] lifted
1521 /// `pub const` roster the [`Self::as_str`] emitter (and the
1522 /// [`std::fmt::Display`] impl / `Serialize` derive routed through it)
1523 /// walks — and byte-for-byte the same three strings the un-`rename`d
1524 /// `Serialize` derive emits under the paired
1525 /// [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] tag key on every
1526 /// JSON / YAML CR round-trip.
1527 ///
1528 /// Peer of the sibling [`crate::CaixaKind::WIRE_NAMES`] (bd708bd)
1529 /// roster on the top-level typed-kind discriminator's `PascalCase`
1530 /// wire byte-string axis, the sibling
1531 /// [`RestartStrategy::WIRE_NAMES`] (3033f45) roster on the per-
1532 /// supervisor sibling-restart-strategy axis (the first M2 OTP-shape
1533 /// closed-set typed enum to converge onto the paired-roster
1534 /// discipline), the sibling
1535 /// [`crate::aplicacao::PlacementStrategy::WIRE_NAMES`] (3e5b194)
1536 /// roster on the first M3 mesh-shape distribution-strategy closed-
1537 /// set typed enum, and the sibling
1538 /// [`crate::upgrade::UpgradeInstruction::WIRE_FORMS`] (cc42c0e) /
1539 /// [`crate::upgrade::UpgradeInstruction::LISP_FORMS`] (1898d77)
1540 /// rosters on the OTP-appup discriminator's two-axis roster split —
1541 /// the same closed-set exhaustive-accept-set roster discipline
1542 /// extended here onto the second and final M2 OTP-shape sibling-
1543 /// enum on the caixa surface, closing the per-child restart-decision-
1544 /// policy axis paired with the peer [`RestartStrategy::WIRE_NAMES`]
1545 /// per-supervisor sibling-restart-strategy axis on the same M2
1546 /// `:supervisor` slot.
1547 ///
1548 /// Downstream consumers of the closed accepted-wire-form set — a
1549 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR admission-
1550 /// webhook rejection body enumerating the accepted JSON `:restart`
1551 /// values verbatim (as distinct from the kebab-case dispatcher-
1552 /// catalog enumeration [`Self::discriminant`] serves, whose per-arm
1553 /// form `"permanent"` / `"temporary"` / `"transient"` structurally
1554 /// disagrees with the wire byte-string these `PascalCase` entries
1555 /// carry — the split the sibling
1556 /// [`tests::restart_policy_display_matches_serialized_wire_byte_string`]
1557 /// pin already makes load-bearing), a future `feira supervisor
1558 /// --restart …` CLI-side "did you mean" hint whose candidate-list
1559 /// must byte-match the wire form the operator's per-child dispatch
1560 /// keys off, a future `feira app graph` per-child `:restart`-
1561 /// histogram column that renders zero-count arms, a future
1562 /// `caixa-operator` per-reconcile-step diagnostic log line
1563 /// enumerating accepted wire forms on an unknown-policy rejection,
1564 /// a future
1565 /// `tracing::field::valuable::Value::List` structured-log accepted-
1566 /// wire-form emit — now reach for one lifted substrate-primitive
1567 /// roster rather than open-coding a three-string array-literal
1568 /// (`["Permanent", "Temporary", "Transient"]`) whose arm-set has no
1569 /// compile-time link back to the typed [`RestartPolicy`] enum. A
1570 /// future arm addition (an OTP-`intrinsic` fourth arm the theory
1571 /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1572 /// might reach for once the three canonical OTP restart policies
1573 /// stop covering the substrate's discovered load-shape) extends
1574 /// this roster as a single edit — paired with the [`Self::as_str`]
1575 /// match's compiler-checked exhaustiveness on the new arm — and
1576 /// every consumer picks up the new wire form by construction rather
1577 /// than a coordinated array-literal rewrite across every downstream
1578 /// site.
1579 ///
1580 /// Length is pinned load-bearing at `RestartPolicy::ALL.len()`
1581 /// (three) by
1582 /// [`tests::restart_policy_wire_names_covers_every_arm`], every
1583 /// variant's [`Self::as_str`] projection is pinned to a member of
1584 /// the roster so a silent skew between the emitter's arm-set and
1585 /// this const's arm-set trips at caixa-core test time rather than at
1586 /// a downstream consumer's accepted-set enumeration miss, and every
1587 /// entry is further pinned to open with an ASCII uppercase byte so
1588 /// a silent collapse of the `PascalCase` wire-form axis with the
1589 /// peer kebab-case dispatcher-catalog axis (an entry byte-identical
1590 /// to a sibling [`Self::discriminant`] kebab byte-string that would
1591 /// let a wire-axis consumer accept the dispatcher-catalog
1592 /// vocabulary) trips here rather than at a downstream K8s-CR round-
1593 /// trip miss.
1594 pub const WIRE_NAMES: &'static [&'static str] = &[
1595 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
1596 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
1597 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
1598 ];
1599
1600 /// Canonical PascalCase discriminator scalar this variant serializes
1601 /// as under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`]. The three
1602 /// arms return the paired
1603 /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1604 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1605 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] lifted
1606 /// constants so every substrate consumer that dispatches on the
1607 /// per-child restart-decision policy (the future wasm-operator's
1608 /// per-child post-exit restart-decision branch, the future M4
1609 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
1610 /// admission-time enum-arm bind, the `caixa-operator`'s hierarchical
1611 /// reconciliation scheduler's per-child-policy fan-out) reads the
1612 /// same byte-string the `Serialize` derive emits — the pin test in
1613 /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
1614 /// asserts the two paths agree, peer of the M2
1615 /// [`RestartStrategy::as_str`] (09ffb2d) on the sibling per-supervisor
1616 /// sibling-restart-strategy axis and the M3
1617 /// [`crate::aplicacao::PlacementStrategy::as_str`] (cc8f749) on the
1618 /// per-Aplicacao distribution-strategy axis — the third of three
1619 /// OTP-shaped closed-enum discriminator axes on the caixa typed
1620 /// surface to converge onto the same three-path-convergence
1621 /// (`Serialize` derive → `as_str` helper → lifted constant)
1622 /// drift-detection posture.
1623 #[must_use]
1624 pub const fn as_str(self) -> &'static str {
1625 match self {
1626 Self::Permanent => crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
1627 Self::Temporary => crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
1628 Self::Transient => crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
1629 }
1630 }
1631
1632 /// Substrate-canonical reverse projection on the `:children :restart`
1633 /// closed-set axis — parses the `PascalCase` discriminator scalar
1634 /// back to the typed variant, or `None` when `s` is outside the
1635 /// closed-set arm-string set [`Self::as_str`] emits. Dispatches on
1636 /// the same lifted
1637 /// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1638 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1639 /// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] constants
1640 /// the [`Self::as_str`] emitter walks, so the parse and emit halves
1641 /// of the round-trip migrate through one caixa-core edit on any
1642 /// future arm addition.
1643 ///
1644 /// Prior to this lift the substrate carried only the forward
1645 /// `Self → &str` projection on the OTP per-child restart-policy
1646 /// axis (the [`Self::as_str`] emitter, the [`std::fmt::Display`]
1647 /// impl routed through it, the `Serialize` derive that emits the
1648 /// same byte-string under [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`])
1649 /// plus the kebab-case dispatcher-catalog identity via
1650 /// [`Self::discriminant`] — every non-serde consumer that wanted to
1651 /// parse a wire-form `PascalCase` policy scalar had to re-inline a
1652 /// three-arm `match s { "Permanent" => …, "Temporary" => …,
1653 /// "Transient" => …, _ => … }` cascade that expressed no
1654 /// compile-time link back to the typed variant's canonical lifted
1655 /// constant. A future variant rename or per-arm serde-attribute
1656 /// drift would silently split the wire byte-string one non-serde
1657 /// consumer parsed from the one the emitter wrote, with the failure
1658 /// surfacing at the operator's reconcile posture (a `:temporary`
1659 /// `oneShot` child being restarted on clean exit, treating the
1660 /// successful-completion signal as failure and re-running the
1661 /// completion-terminal one-shot indefinitely; a `:transient` child
1662 /// that clean-exited being restarted, masking the clean-completion
1663 /// contract) far from the rebrand commit and with no field naming
1664 /// the drift.
1665 ///
1666 /// Distinct axis from the [`std::str::FromStr`] impl the
1667 /// [`gen_platform::FromStrKind`] derive already installs on this
1668 /// enum by design, not by drift: `FromStr` parses the *kebab-case*
1669 /// dispatcher-catalog identity (`"permanent"` / `"temporary"` /
1670 /// `"transient"` — the inverse of [`Self::discriminant`]), while
1671 /// this method inverts the `PascalCase` wire byte-string
1672 /// [`Self::as_str`] emits. The two-axis split lets the dispatcher-
1673 /// catalog identity live in kebab-case (where every peer catalog
1674 /// identifier already lives) without forcing a wire-format rename
1675 /// on the tatara-lisp author surface (`:restart Permanent`,
1676 /// `PascalCase`) — the same two-axis distinction the sibling
1677 /// [`RestartStrategy::from_wire`] (4eec29c) /
1678 /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
1679 /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
1680 /// carry on their peer closed-set typed-enum wire round-trips.
1681 ///
1682 /// Same closed-set-reverse-projection discipline the sibling
1683 /// [`RestartStrategy::from_wire`] (4eec29c) /
1684 /// [`crate::CaixaKind::from_wire`] (2aa6d23) /
1685 /// [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342) /
1686 /// [`crate::aplicacao::RateLimitUnit::from_suffix`] typed enums
1687 /// carry on the peer wire-side `str → Self` axes — extended onto
1688 /// the M2 OTP-shape per-child restart-policy closed-set axis, the
1689 /// sixth substrate-side closed-set typed enum (and the third and
1690 /// final OTP-shape closed-enum discriminator axis) to converge on
1691 /// the two-way `str ↔ Self` round-trip. Method-named `from_wire`
1692 /// (not `from_str`) to match the peer [`RestartStrategy::from_wire`]
1693 /// shape verbatim and side-step the [`std::str::FromStr`] impl the
1694 /// derive already installs on the sibling kebab-case axis. Returns
1695 /// `Option<Self>` (rather than `Result<Self, _>`) to match the peer
1696 /// shapes: the caller picks the diagnostic form appropriate for
1697 /// its use site.
1698 #[must_use]
1699 pub fn from_wire(s: &str) -> Option<Self> {
1700 match s {
1701 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT => Some(Self::Permanent),
1702 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY => Some(Self::Temporary),
1703 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT => Some(Self::Transient),
1704 _ => None,
1705 }
1706 }
1707}
1708
1709/// [`std::fmt::Display`] routed through [`RestartPolicy::as_str`], so the
1710/// pretty-printed byte-string every consumer that formats the policy as
1711/// user-facing text lands on (the future wasm-operator's per-child
1712/// post-exit restart-decision diagnostic line, the future `feira app
1713/// graph` per-child restart column, the future M4
1714/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
1715/// admission-webhook rejection body) reaches for the same lifted
1716/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1717/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1718/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
1719/// wire-format `Serialize` derive already emits under
1720/// [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
1721/// [`RestartPolicy::as_str`] helper already returns.
1722///
1723/// Pre-convergence the two paths structurally disagreed — the
1724/// `#[derive(gen_platform::Discriminant)]` + `#[discriminant(also_display)]`
1725/// route (now retired here) sent [`std::fmt::Display`] through the
1726/// gen-platform discriminant catalog string, which arrives kebab-case as
1727/// `"permanent"` / `"temporary"` / `"transient"` on this three-arm enum
1728/// (whose variant names each collapse to their own lowercase form under
1729/// the kebab-case transform), while the wire format ran as `PascalCase`
1730/// `"Permanent"` / `"Temporary"` / `"Transient"` through the un-`rename`d
1731/// serde derive. Every consumer that formatted the policy for a
1732/// diagnostic line, a graph column, or a rejection body under
1733/// `format!("{v}")` therefore landed under a different byte-string than
1734/// the wire format the operator's per-child-policy dispatch keyed off —
1735/// a silent split whose apply-time symptom (a `format!("{v}")`-carrying
1736/// diagnostic quoting `"permanent"` while the wire scalar the operator
1737/// probed was `"Permanent"`) surfaced as a confused correlate at
1738/// operator-log time far from the two-declaration site.
1739///
1740/// Routing `Display` through [`RestartPolicy::as_str`] closes the third
1741/// path: every `format!("{v}")` call reaches the same lifted
1742/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the wire format
1743/// and the [`RestartPolicy::as_str`] helper route through — `Debug` (the
1744/// compiler-derived variant name), `Display` (via `as_str`), and `Serialize`
1745/// (via the un-`rename`d derive) all resolve to the same `PascalCase`
1746/// byte-string per variant. A future variant rename or
1747/// `#[serde(rename_all = "kebab-case")]` attribute reaches every path at
1748/// exactly one place, structurally.
1749///
1750/// The dispatcher-catalog identity remains kebab-case — [`Self::discriminant`]
1751/// (from `#[derive(gen_platform::Discriminant)]`) still returns
1752/// `"permanent"` / `"temporary"` / `"transient"`, and the fleet-wide
1753/// [`gen_platform::register_dispatcher!("caixa.restart-policy", …)`]
1754/// registration keys the catalog off the same kebab identity. The two
1755/// naming worlds now live on separate typed methods (`Display` /
1756/// `as_str` for the wire byte-string, `discriminant` for the catalog
1757/// identity) rather than sharing one `Display` route that structurally
1758/// disagrees with the wire format.
1759///
1760/// Pin tests
1761/// [`tests::restart_policy_display_routes_through_as_str_helper`]
1762/// and
1763/// [`tests::restart_policy_display_matches_serialized_wire_byte_string`]
1764/// assert the three paths agree byte-for-byte on every variant, so a
1765/// future variant rename or per-arm serde attribute drift is a build
1766/// error visible at caixa-core test time, not a silent per-consumer
1767/// dispatch miss at apply / reconcile time.
1768///
1769/// Mirrors the M3 [`crate::aplicacao::PlacementStrategy`] `Display` impl
1770/// (aplicacao.rs:2306) on the per-Aplicacao distribution-strategy axis
1771/// and the sibling [`RestartStrategy`] `Display` impl on the
1772/// per-supervisor sibling-restart-strategy axis — same three-path-
1773/// convergence discipline, extended to close the third and final of
1774/// three OTP-shaped closed-enum discriminator axes on the caixa typed
1775/// surface.
1776impl std::fmt::Display for RestartPolicy {
1777 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1778 f.write_str(self.as_str())
1779 }
1780}
1781
1782/// Substrate-canonical [`AsRef<str>`] projection on the M2
1783/// per-child-restart-policy [`RestartPolicy`] closed-set typed enum —
1784/// routes through the same [`RestartPolicy::as_str`] `pub const fn`
1785/// scalar accessor the paired [`std::fmt::Display`] impl and the
1786/// un-`rename`d [`serde::Serialize`] derive already key off, so any
1787/// future consumer that binds a [`RestartPolicy`] through the
1788/// standard-library `impl AsRef<str>` bound (a future
1789/// [`caixa-feira`] `feira supervisor --restart <arm>` verb that
1790/// composes the emitted `PascalCase` wire scalar into a
1791/// [`std::process::Command::arg`] shell-out of the future
1792/// wasm-operator's per-child admission gate, a per-child structured-
1793/// log recorder on the future `caixa-operator`'s hierarchical
1794/// reconciliation surface that accepts `impl AsRef<str>` at the
1795/// `tracing::field::Value` `Str`-arm, a [`std::collections::HashMap`]
1796/// lookup keyed on the restart-policy wire byte through
1797/// `map.get::<str>(policy.as_ref())` on a future per-policy
1798/// dispatch table) reaches the paired
1799/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1800/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1801/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
1802/// lifted-const through one substrate-primitive dispatch rather
1803/// than an open-coded `.as_str()` projection at every wire-up.
1804///
1805/// Peer of the sibling [`std::fmt::Display`] impl on the same
1806/// primitive — both delegate to the shared [`RestartPolicy::as_str`]
1807/// `pub const fn` accessor, so [`format!("{v}")`], `v.as_str()`, and
1808/// `<RestartPolicy as AsRef<str>>::as_ref(&v)` resolve to the same
1809/// byte-string per instance by construction. A future variant rename
1810/// or `#[serde(rename_all = "kebab-case")]` attribute-drift on the
1811/// enum reaches every one of the three paths (plus the wire-format
1812/// `Serialize` derive that already routes through the same lifted
1813/// const) through exactly one caixa-core edit.
1814///
1815/// Same "route the trait impl through the substrate-primitive
1816/// accessor" discipline the sibling [`crate::CaixaVersion`]
1817/// [`AsRef<str>`] impl (16d5c7e) and the paired M2
1818/// [`RestartStrategy`] [`AsRef<str>`] impl (63eb1a4) carry — extends
1819/// the axis onto the paired per-child-restart-decision-policy
1820/// sibling on the same M2 `:supervisor` slot (the second M2
1821/// OTP-shape closed-set typed enum to converge onto the standard-
1822/// library [`AsRef<str>`] projection). Rust-side newtype/typed-enum
1823/// convention pairs [`AsRef<str>`] and [`fmt::Display`] on the same
1824/// primitive so a caller who has one has both; before this lift,
1825/// [`RestartPolicy`] carried [`fmt::Display`] but not the paired
1826/// [`AsRef<str>`] impl the convention names.
1827///
1828/// Pinned load-bearing by
1829/// [`tests::restart_policy_as_ref_str_routes_through_as_str_accessor`]
1830/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1831/// three-arm closed set) and
1832/// [`tests::restart_policy_as_ref_str_routes_through_display_via_shared_accessor`]
1833/// (three-path convergence: `AsRef<str>` + `Display` + `as_str` all
1834/// resolve to the same lifted `SUPERVISOR_CHILD_RESTART_*` const per
1835/// arm) — any future silent detour that routes the impl through a
1836/// divergent projection (a per-arm inline `match self { … }`
1837/// re-inlining that opens a compile-time link to the un-lifted
1838/// arm-literal, a swap onto the kebab-case
1839/// [`gen_platform::Discriminant`] catalog identity that would
1840/// collide the wire axis with the dispatcher-catalog axis) trips at
1841/// caixa-core test time under `assert_eq!` rather than at a
1842/// downstream `impl AsRef<str>`-bound consumer's silent split.
1843impl AsRef<str> for RestartPolicy {
1844 fn as_ref(&self) -> &str {
1845 self.as_str()
1846 }
1847}
1848
1849/// Trait-idiomatic reverse projection on the M2-OTP-shape per-child
1850/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
1851/// byte-for-byte through the paired substrate-primitive
1852/// [`RestartPolicy::from_wire`] `Option<Self>` accessor so every future
1853/// consumer that binds a `PascalCase` `:children :restart` wire
1854/// byte-string through the standard-library `.try_into()` / [`TryFrom`]
1855/// axis (a future [`caixa-feira`] `feira supervisor --restart
1856/// <Permanent|Temporary|Transient>` CLI arg-parse that composes into
1857/// `let restart: RestartPolicy = s.try_into()?`, a future
1858/// `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook that folds a
1859/// `spec.children[*].restart: String` field through
1860/// `RestartPolicy::try_from(&s)?`, a generic
1861/// `<T: TryFrom<&str>>`-bound loader over any of the substrate's closed-
1862/// set typed enums) reaches the same three-arm accept-set the sibling
1863/// [`RestartPolicy::from_wire`] resolver parses through and the sibling
1864/// [`RestartPolicy::as_str`] emits, rather than an open-coded per-arm
1865/// `match s { "Permanent" => …, "Temporary" => …, "Transient" => …, _ =>
1866/// … }` cascade whose arm-set has no compile-time link back to the
1867/// substrate primitive.
1868///
1869/// Complements the pre-existing forward-projection triple
1870/// ([`std::fmt::Display`], [`AsRef<str>`], [`RestartPolicy::as_str`])
1871/// with the paired trait-idiomatic reverse-projection axis: Rust-side
1872/// newtype/typed-enum convention pairs [`AsRef<str>`] with either
1873/// [`std::str::FromStr`] or [`TryFrom<&str>`] on the same primitive so a
1874/// caller who can project *out to* a `&str` can also project *in from*
1875/// one. The [`TryFrom<&str>`] axis is deliberately chosen over
1876/// [`std::str::FromStr`] to sidestep the `clippy::should_implement_trait`
1877/// lint the sibling method-named [`RestartPolicy::from_wire`] would
1878/// trigger under a `FromStr` impl and to avoid colliding with the
1879/// [`std::str::FromStr`] impl the [`gen_platform::FromStrKind`] derive
1880/// already installs on the paired *kebab-case dispatcher-catalog* axis
1881/// (which parses `"permanent"` / `"temporary"` / `"transient"`, the
1882/// inverse of [`Self::discriminant`]) — this impl closes the trait-
1883/// idiomatic reverse axis on the *`PascalCase` wire* half without
1884/// disturbing either the method-named `from_wire` shape every sibling
1885/// closed-set typed enum on the substrate already carries or the
1886/// pre-existing `FromStr` on the dispatcher-catalog half, keeping the
1887/// two-axis split the sibling [`Self::from_wire`] doc block motivates.
1888///
1889/// `type Error = ()` matches the sibling [`RestartPolicy::from_wire`]'s
1890/// `Option<Self>` return-shape's deliberate deferral of error typing: the
1891/// caller picks the diagnostic form appropriate for its use site (a
1892/// future `feira supervisor --restart` arg-parse composes its own
1893/// per-verb "unknown restart: <arg> — accepted: {…}" message enumerating
1894/// [`RestartPolicy::ALL`], a future M4 admission-webhook rejection body
1895/// wraps the `Err(())` outcome with the accepted-set enumeration for
1896/// operator diagnostics, a `Result::map_err` at the call site lifts the
1897/// unit-error to a per-verb error type). Same shape the peer
1898/// [`RestartStrategy`] (5b828ed) on the sibling per-supervisor axis,
1899/// [`crate::CaixaKind`] (3c83606), [`crate::CaixaDialeto`] (bf33136), and
1900/// [`crate::aplicacao::PlacementStrategy`] (6fd00cd) blocks motivate on
1901/// their peer closed-set typed enums' reverse projections.
1902///
1903/// The paired [`TryFrom<&str>`] impl reaches the same three-arm accept-
1904/// set the [`RestartPolicy::from_wire`] resolver dispatches through, so
1905/// any future arm addition (an OTP-`intrinsic` fourth arm the theory
1906/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1907/// might reach for once the three canonical OTP restart policies stop
1908/// covering the substrate's discovered load-shape) grows the trait-
1909/// idiomatic axis by construction — one caixa-core edit on
1910/// [`RestartPolicy::from_wire`] extends both the method-named reverse
1911/// projection every existing consumer keys off and the trait-idiomatic
1912/// reverse projection this impl exposes, without a coordinated rewrite
1913/// across every future `TryFrom<&str>`-bound consumer's arm-set.
1914///
1915/// Extends the substrate-wide closed-set-enum reverse-projection family
1916/// ([`crate::CaixaKind`] via 3c83606, [`crate::CaixaDialeto`] via
1917/// bf33136, [`crate::aplicacao::PlacementStrategy`] via 6fd00cd, and
1918/// [`RestartStrategy`] via 5b828ed) onto the third and final OTP-shape
1919/// closed-enum discriminator axis on the caixa surface — the paired
1920/// per-child `:children :restart` closed set the future wasm-operator's
1921/// hierarchical reconciliation scheduler's per-child post-exit
1922/// restart-decision branch keys off end-to-end.
1923///
1924/// Pinned load-bearing by
1925/// [`tests::restart_policy_try_from_str_routes_through_from_wire_accessor`]
1926/// (byte-parity pin against [`RestartPolicy::from_wire`] across the
1927/// three-arm accept-set),
1928/// [`tests::restart_policy_try_from_str_rejects_unknown_byte_strings`]
1929/// (rejection witness against silent accept-set widening), and
1930/// [`tests::restart_policy_try_from_str_and_from_wire_partition_the_accept_set`]
1931/// (cross-axis partition pin locking the trait and method-named
1932/// projections onto one accept-set).
1933impl TryFrom<&str> for RestartPolicy {
1934 type Error = ();
1935
1936 fn try_from(s: &str) -> Result<Self, Self::Error> {
1937 Self::from_wire(s).ok_or(())
1938 }
1939}
1940
1941/// Trait-idiomatic forward projection on the M2-OTP-shape per-child
1942/// restart-policy [`RestartPolicy`] closed-set typed enum — routes
1943/// byte-for-byte through the paired substrate-primitive
1944/// [`RestartPolicy::as_str`] `pub const fn` accessor. Return type is
1945/// `&'static str` by construction — every [`RestartPolicy::as_str`] arm
1946/// resolves to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const
1947/// &str` with `'static` lifetime, so the trait's return-type promise is
1948/// upheld structurally without a [`String::leak`] cast or a per-arm inline
1949/// literal.
1950///
1951/// Every future consumer that specifically needs `&'static str` lifetime
1952/// bytes on the per-child restart-decision axis (a
1953/// [`tracing::field::valuable::Value::Str`] recording where the `Str`
1954/// arm's typing demands `&'static str`, a
1955/// [`std::borrow::Cow::Borrowed`]`::<'static, str>(policy.into())` composer
1956/// on the future M4 admission-webhook rejection body where the
1957/// `Cow<'static, str>` typing rules out the sibling [`AsRef<str>`]
1958/// borrowed return, a generic `<T: Into<&'static str>>`-bound serializer
1959/// or error formatter that requires the `'static` bound) reaches the same
1960/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
1961/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
1962/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] substrate-
1963/// primitive dispatch rather than an open-coded per-arm literal cascade
1964/// whose arm-set has no compile-time link back to the substrate primitive.
1965///
1966/// Peer of the sibling M2-OTP-shape [`RestartStrategy`] forward-projection
1967/// impl (523157d) on the per-supervisor sibling-restart-strategy axis —
1968/// the second (and second-of-two-in-M2) closed-set typed enum on the
1969/// caixa surface to converge onto the paired trait-idiomatic forward-
1970/// projection axis. With this lift the paired per-child
1971/// `:children :restart` closed-set typed enum carries the full sibling
1972/// quintet ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
1973/// [`TryFrom<&str>`] via 6fdd0d9, `From<Self> for &'static str` via this
1974/// lift) plus the round-trip witness through both the trait-idiomatic
1975/// (`From<Self> for &'static str` + `TryFrom<&str>`) and the method-named
1976/// (`as_str` + `from_wire`) axis pairs — mirrors the sibling
1977/// [`RestartStrategy`] surface arm-for-arm, so every future arm addition
1978/// (an OTP-`intrinsic` fourth arm the theory
1979/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
1980/// might reach for once the three canonical OTP restart policies stop
1981/// covering the substrate's discovered load-shape) grows the trait-
1982/// idiomatic forward axis by construction: one caixa-core edit on
1983/// [`RestartPolicy::as_str`] extends every one of the five sibling
1984/// forward-projection paths ([`std::fmt::Display`], [`AsRef<str>`],
1985/// [`Self::as_str`] itself, this `From<Self> for &'static str`, and the
1986/// un-`rename`d [`serde::Serialize`] derive that also emits `as_str`'s
1987/// bytes) without a coordinated rewrite across every future
1988/// `Into<&'static str>`-bound consumer's arm-set.
1989///
1990/// Pinned load-bearing by
1991/// [`tests::restart_policy_from_into_static_str_routes_through_as_str_accessor`]
1992/// (byte-parity pin against [`RestartPolicy::as_str`] across the
1993/// three-arm emit-set, plus a `const`-context materialization witness for
1994/// the `&'static str` lifetime promise) and
1995/// [`tests::restart_policy_from_into_static_str_and_as_str_partition_the_emit_set`]
1996/// (partition pin asserting `<&'static str as From<RestartPolicy>>::from`
1997/// and [`RestartPolicy::as_str`] agree on every arm, plus a two-way
1998/// round-trip witness through the paired trait-idiomatic reverse-
1999/// projection axis [`TryFrom<&str>`] (6fdd0d9): every
2000/// `policy.into::<&'static str>()` output re-parses back through
2001/// [`RestartPolicy::try_from`] to the original variant, closing the two-
2002/// way `Self ↔ &'static str` round-trip on the trait-idiomatic axis pair).
2003impl From<RestartPolicy> for &'static str {
2004 fn from(policy: RestartPolicy) -> &'static str {
2005 policy.as_str()
2006 }
2007}
2008
2009/// Trait-idiomatic *forward* projection on [`RestartPolicy`] from a
2010/// *borrowed* input onto the `&'static str` axis — the borrowed-input
2011/// companion to the paired owned-input [`From<RestartPolicy> for
2012/// &'static str`] impl immediately above. Routes byte-for-byte through
2013/// the same substrate-primitive [`RestartPolicy::as_str`] `pub const
2014/// fn` accessor so every consumer that binds a `&RestartPolicy`
2015/// through the standard-library `.into()` / [`From<&Self> for &'static
2016/// str`] axis (a `RestartPolicy::ALL.iter().map(<&'static
2017/// str>::from).collect::<Vec<_>>()` per-arm accept-set materializer —
2018/// whose iterator over `&'static [RestartPolicy]` yields
2019/// `&RestartPolicy`, not `RestartPolicy`, so the owned-input
2020/// [`From<RestartPolicy>`] axis alone forces every call site through
2021/// an explicit `.copied()` / dereference / [`Copy`]-bound restatement
2022/// rather than the direct trait-idiomatic projection; a future generic
2023/// `<T: Copy + for<'a> Into<&'static str>>`-bound diagnostic column
2024/// that walks the `iter().map(Into::into)` shape verbatim across every
2025/// substrate-wide closed-set typed enum; the future wasm-operator's
2026/// per-child post-exit restart-decision diagnostic line that composes
2027/// the accepted-set enumeration from an iterated
2028/// `RestartPolicy::ALL.iter().map(|p| p.into())` pipe rather than a
2029/// per-arm `match p { … }` cascade; a future
2030/// `HashMap::<&'static str, RestartPolicy>::from_iter(
2031/// RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
2032/// per-policy reverse-lookup table the sibling [`TryFrom<&str>`] impl
2033/// cannot compose without this borrowed-input axis in place) reaches
2034/// the same three-arm lifted
2035/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2036/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2037/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2038/// paired owned-input [`From<RestartPolicy> for &'static str`], the
2039/// sibling [`std::fmt::Display`], [`AsRef<str>`], and
2040/// [`RestartPolicy::as_str`] surfaces already return.
2041///
2042/// Fifth peer on the substrate-wide trait-idiomatic *borrowed-input*
2043/// forward-projection family opened on [`crate::dep::DepList`]
2044/// (64aa742) and extended onto [`crate::CaixaKind`] (5ab993a),
2045/// [`crate::CaixaDialeto`] (807b0b5), and the paired
2046/// per-supervisor sibling-restart-strategy [`RestartStrategy`]
2047/// (e941836). Rust's `From` trait does not auto-derive the
2048/// `From<&Self>` sibling from a `From<Self>` impl (the blanket
2049/// `impl<T, U> From<&T> for U where T: Copy, U: From<T>` does not
2050/// exist in `core`), so every closed-set typed enum that carries the
2051/// owned-input axis but not the borrowed-input axis forces every
2052/// borrowed-input call site through a `.copied()` /
2053/// `<&'static str>::from(*policy)` / `policy.as_str()` detour whose
2054/// type bounds have no compile-time link to the substrate primitive.
2055/// [`RestartPolicy`] is the second (and second-of-two-in-M2)
2056/// OTP-shape peer to converge onto this campaign — sibling of the
2057/// paired per-supervisor [`RestartStrategy`] borrowed-input axis, so
2058/// with this lift both closed-set typed enums on the M2 `:supervisor`
2059/// slot now carry the full sibling quintet ([`std::fmt::Display`],
2060/// [`AsRef<str>`], [`Self::as_str`], `From<Self> for &'static str`,
2061/// `From<&Self> for &'static str`) plus the paired trait-idiomatic
2062/// reverse projection [`TryFrom<&str>`], closing the borrowed-input
2063/// forward-projection axis on the M2 OTP-shape slot as a unit.
2064///
2065/// Same three-path convergence discipline as the paired owned-input
2066/// impl (this borrowed-input axis, the paired owned-input
2067/// [`From<RestartPolicy> for &'static str`], and
2068/// [`RestartPolicy::as_str`] all route through the same lifted
2069/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const), so a future
2070/// variant rename or per-arm serde-attribute drift reaches every one
2071/// of the six sibling forward-projection paths
2072/// ([`std::fmt::Display`], [`AsRef<str>`], [`Self::as_str`],
2073/// [`From<Self> for &'static str`], this [`From<&Self> for &'static
2074/// str`], and the un-`rename`d [`serde::Serialize`] derive that also
2075/// emits [`Self::as_str`]'s bytes) through exactly one caixa-core
2076/// edit.
2077///
2078/// The [`RestartPolicy::as_str`] emit and [`RestartPolicy::from_wire`]
2079/// parse share the same `PascalCase` vocabulary by construction, so
2080/// the borrowed-input forward axis and the reverse axis compose
2081/// directly — the round-trip witness pin below locks this direct
2082/// composition without the intermediate wire-vocab hop the peer
2083/// [`crate::CaixaKind`] axis pair requires.
2084///
2085/// Pinned load-bearing by
2086/// [`tests::restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor`]
2087/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2088/// three-arm emit-set via a borrowed input, plus a `const`-context
2089/// materialization witness for the `&'static str` lifetime promise,
2090/// plus a blanket `.into()` shape) and
2091/// [`tests::restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
2092/// (cross-axis partition pin against the paired owned-input
2093/// [`From<RestartPolicy> for &'static str`] impl, plus a
2094/// `.iter().map(Into::into)` pipe witness over
2095/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
2096/// [`TryFrom<&str>`] that closes the two-way `&Self → &'static str →
2097/// Self` round-trip without the wire-vocab intermediate the peer
2098/// [`crate::CaixaKind`] axis pair requires).
2099impl From<&RestartPolicy> for &'static str {
2100 fn from(policy: &RestartPolicy) -> &'static str {
2101 policy.as_str()
2102 }
2103}
2104
2105/// Trait-idiomatic *owned-`String`* forward projection on the second
2106/// M2 OTP-shape closed-set typed enum ([`RestartPolicy`]) — the
2107/// owned-heap-string companion to the paired `&'static str`-returning
2108/// [`From<RestartPolicy> for &'static str`] / [`From<&RestartPolicy>
2109/// for &'static str`] impls immediately above. Routes byte-for-byte
2110/// through the substrate-primitive [`RestartPolicy::as_str`] `pub
2111/// const fn` accessor (via [`str::to_owned`]) so every consumer that
2112/// binds a [`RestartPolicy`] through the standard-library `.into()` /
2113/// [`From<Self> for String`] (equivalently [`Into<String>`]) axis — a
2114/// future `serde_json::Value::String(policy.into())` structured-payload
2115/// composer where the `Value::String` arm typing demands an owned
2116/// [`String`] and the sibling [`&'static str`]-returning axis forces
2117/// an explicit `.to_owned()` / `String::from` restatement at every
2118/// call site, a future `HashMap::<String, RestartPolicy>::from_iter(
2119/// RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))` per-policy
2120/// lookup where the map's key type is owned [`String`] rather than
2121/// [`&'static str`], a future `Cow::<'static, str>::Owned(policy.into())`
2122/// composer on the future M4 admission-webhook rejection body's
2123/// owned-arm, the future wasm-operator's per-child post-exit
2124/// diagnostic emit `serde_json::json!({ "restart": policy })` where the
2125/// JSON serializer's `Serialize` impl on [`String`] owns the emit-path
2126/// — reaches the same three-arm lifted
2127/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2128/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2129/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2130/// paired [`std::fmt::Display`], [`AsRef<str>`],
2131/// [`RestartPolicy::as_str`], and the two `&'static str`-returning
2132/// forward-projection impls already return.
2133///
2134/// Extends the trait-idiomatic *owned-`String`* forward-projection
2135/// axis onto the second-of-two M2 OTP-shape closed-set typed enums on
2136/// the caixa surface — mirror of the first-mover
2137/// [`From<RestartStrategy> for String`] (7baa18a) that opened this
2138/// axis on the sibling supervisor-level strategy enum. Rust's standard
2139/// library does not carry a blanket `impl<T: AsRef<str>> From<T> for
2140/// String` (nor an `impl<T: fmt::Display> From<T> for String`), so
2141/// every closed-set typed enum that carries the paired `AsRef<str>` /
2142/// `Display` / `From<Self> for &'static str` triple but not the
2143/// owned-[`String`] axis forces every owned-string call site through a
2144/// `.to_string()` / `.as_str().to_owned()` / `String::from(policy.as_str())`
2145/// detour whose type bounds have no compile-time link to the
2146/// substrate primitive.
2147///
2148/// Deliberately routes through the human-readable
2149/// [`RestartPolicy::as_str`] axis — for this enum the wire format
2150/// (`PascalCase`, tatara-lisp author surface `:restart Permanent`) and
2151/// the diagnostic byte-string share the same vocabulary by
2152/// construction (unlike the sibling [`crate::CaixaKind`] enum whose
2153/// two axes diverge), so the owned-[`String`] projection lands
2154/// byte-identically on both the wire vocabulary the paired
2155/// [`serde::Serialize`] derive emits and the diagnostic vocabulary the
2156/// [`RestartPolicy::as_str`] helper returns, and — because the paired
2157/// [`TryFrom<&str>`] / [`RestartPolicy::from_wire`] reverse-projection
2158/// axis parses the same `PascalCase` vocabulary — the direct two-way
2159/// `Self → String → Self` round-trip composes without the wire-vocab
2160/// intermediate hop the peer [`crate::CaixaKind`] owned-[`String`]
2161/// axis pair requires.
2162///
2163/// Pinned load-bearing by
2164/// [`tests::restart_policy_from_into_owned_string_routes_through_as_str_accessor`]
2165/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2166/// three-arm emit-set, plus a blanket `.into::<String>()` shape
2167/// witness) and
2168/// [`tests::restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm`]
2169/// (cross-axis partition pin against the paired owned-input
2170/// [`From<RestartPolicy> for &'static str`] impl and the sibling
2171/// [`ToString::to_string`] surface routed through [`std::fmt::Display`],
2172/// plus a `.iter().copied().map(String::from)` pipe witness over
2173/// [`RestartPolicy::ALL`], plus a direct round-trip witness through
2174/// [`TryFrom<&str>`] on the owned-[`String`]'s [`String::as_str`]
2175/// borrow that closes the two-way `Self → String → Self` round-trip
2176/// on the trait-idiomatic owned-[`String`] forward + reverse axis
2177/// pair).
2178impl From<RestartPolicy> for String {
2179 fn from(policy: RestartPolicy) -> String {
2180 policy.as_str().to_owned()
2181 }
2182}
2183
2184/// Trait-idiomatic *borrowed-input, owned-`String` output* forward
2185/// projection on the second-of-two M2 OTP-shape closed-set typed enum
2186/// ([`RestartPolicy`]) — the fourth (and closing) corner of the
2187/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
2188/// projection family on this enum, mirror of the first-mover
2189/// [`From<&RestartStrategy> for String`] (579385f) that opened the
2190/// 2×2-completion corner on the sibling supervisor-level strategy
2191/// enum. Routes byte-for-byte through the substrate-primitive
2192/// [`RestartPolicy::as_str`] `pub const fn` accessor (via
2193/// [`str::to_owned`]) so every consumer that holds a borrowed
2194/// [`&RestartPolicy`] and needs an owned [`String`] — a future
2195/// `serde_json::Value::String(String::from(&policy))` structured-payload
2196/// composer over a borrowed field, a future `Iterator::map` over
2197/// `&[RestartPolicy]` that projects to owned keys through
2198/// `.iter().map(String::from)`, a future `HashMap::<String,
2199/// RestartPolicy>::from_iter` that keys off a borrowed-iteration axis
2200/// where dereferencing the policy would force an unnecessary `Copy` at
2201/// every step, the future wasm-operator's per-supervisor
2202/// `child_policies.iter().map(String::from).collect()` per-child post-
2203/// exit restart-decision diagnostic emit whose iteration axis is
2204/// borrowed by construction — reaches the same three-arm lifted
2205/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2206/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2207/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2208/// paired [`std::fmt::Display`], [`AsRef<str>`],
2209/// [`RestartPolicy::as_str`], and the three other trait-idiomatic
2210/// forward-projection impls
2211/// ([`From<RestartPolicy> for &'static str`],
2212/// [`From<&RestartPolicy> for &'static str`],
2213/// [`From<RestartPolicy> for String`]) already return.
2214///
2215/// Second peer on the substrate-wide trait-idiomatic *borrowed-input,
2216/// owned-`String` output* forward-projection family opened on
2217/// [`crate::supervisor::RestartStrategy`] (579385f) — closes the
2218/// `{Self, &Self} × {&'static str, String}` 2×2 projection corner on
2219/// both M2 OTP-shape sibling peers (the paired supervisor-level
2220/// sibling-restart-strategy axis and the per-child restart-decision-
2221/// policy axis), so the whole M2 OTP-shape axis pair now carries the
2222/// full four-corner family by construction. Rust's standard library
2223/// does not carry a blanket `impl<T: AsRef<str>> From<&T> for String`
2224/// (nor an `impl<T: fmt::Display> From<&T> for String`), so every
2225/// closed-set typed enum that carries the paired `AsRef<str>` /
2226/// `Display` / `From<Self> for &'static str` / `From<&Self> for
2227/// &'static str` / `From<Self> for String` quintuple but not the
2228/// borrowed-input owned-[`String`] axis forces every borrowed-input
2229/// owned-string call site through a `policy.as_str().to_owned()` /
2230/// `String::from(*policy)` (with a spurious `Copy`) /
2231/// `policy.to_string()` (through `Display`) detour whose type bounds
2232/// have no compile-time link to the substrate primitive.
2233///
2234/// Deliberately routes through the human-readable
2235/// [`RestartPolicy::as_str`] axis — for this enum the wire format
2236/// (`PascalCase`, tatara-lisp author surface `:restart Permanent`) and
2237/// the diagnostic byte-string share the same vocabulary by
2238/// construction (unlike the sibling [`crate::CaixaKind`] enum whose
2239/// two axes diverge), so the borrowed-input owned-[`String`]
2240/// projection lands byte-identically on both the wire vocabulary the
2241/// paired [`serde::Serialize`] derive emits and the diagnostic
2242/// vocabulary the [`RestartPolicy::as_str`] helper returns, and —
2243/// because the paired [`TryFrom<&str>`] / [`RestartPolicy::from_wire`]
2244/// reverse-projection axis parses the same `PascalCase` vocabulary —
2245/// the direct two-way `&Self → String → Self` round-trip composes
2246/// without the wire-vocab intermediate hop the peer
2247/// [`crate::CaixaKind`] axis pair requires.
2248///
2249/// The remaining thirteen closed-set typed enums on the caixa
2250/// substrate surface (`CaixaKind`, `CaixaDialeto`, `DepList`,
2251/// `PlacementStrategy`, `WitShape`, `RateLimitUnit`,
2252/// `PathShapeViolation`, `InvariantKind`, `ArchVerdict`, `Severity`,
2253/// `FixSafety`, `Semantic`, `FerriteRuntime`) are the future targets
2254/// of this 2×2-completion campaign — each carries the same paired
2255/// quintuple that this borrowed-input owned-[`String`] axis extends
2256/// onto.
2257///
2258/// Pinned load-bearing by
2259/// [`tests::restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
2260/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2261/// three-arm emit-set through the borrowed-input surface) and
2262/// [`tests::restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
2263/// (cross-axis partition pin against the paired owned-input owned-
2264/// [`String`] [`From<RestartPolicy> for String`] impl, the paired
2265/// borrowed-input owned-[`&'static str`] [`From<&RestartPolicy> for
2266/// &'static str`] impl, and the sibling [`ToString::to_string`]
2267/// surface routed through [`std::fmt::Display`], plus a direct round-
2268/// trip witness through [`TryFrom<&str>`] on the owned-[`String`]'s
2269/// [`String::as_str`] borrow that closes the two-way
2270/// `&Self → String → Self` round-trip on the trait-idiomatic
2271/// borrowed-input owned-[`String`] forward + reverse axis pair).
2272impl From<&RestartPolicy> for String {
2273 fn from(policy: &RestartPolicy) -> String {
2274 policy.as_str().to_owned()
2275 }
2276}
2277
2278/// Trait-idiomatic *owned-input, [`std::borrow::Cow<'static, str>`]
2279/// output* forward projection on the M2 OTP-shape per-child-restart
2280/// [`RestartPolicy`] closed-set typed enum — extends the substrate-
2281/// wide [`std::borrow::Cow<'static, str>`] forward-projection family
2282/// opened on [`crate::CaixaKind`] (99c1735 owned-input, d45c409
2283/// borrowed-input) and first extended off it onto the sibling M2
2284/// OTP-shape sibling-restart [`RestartStrategy`] (7dd28b3 owned-input,
2285/// 9b3e4b3 borrowed-input) onto the second (and second-of-two-in-M2)
2286/// M2 OTP-shape closed-set fieldless typed enum peer on the caixa
2287/// surface (`:children :restart`). Routes byte-for-byte through the
2288/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2289/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
2290/// that binds a [`RestartPolicy`] through the trait-idiomatic
2291/// [`std::borrow::Cow<'static, str>`] axis — a future
2292/// `axum::response::IntoResponse` composer whose per-policy
2293/// diagnostic-body typing rules out the sibling [`AsRef<str>`]
2294/// borrowed return, a future M4 admission-webhook rejection body
2295/// that composes the accepted-policy enumeration through the same
2296/// `RestartPolicy::ALL.iter().map(Cow::from)` shape [`crate::CaixaKind`]
2297/// and [`RestartStrategy`] already route through, a generic `<T: for<'a>
2298/// Into<std::borrow::Cow<'static, str>>>`-bound structured-log
2299/// emitter on a per-child-policy diagnostic column — reaches the same
2300/// three-arm lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`]
2301/// / [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2302/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2303/// paired [`std::fmt::Display`], [`AsRef<str>`],
2304/// [`RestartPolicy::as_str`], and the four
2305/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
2306/// forward-projection corners already return.
2307///
2308/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
2309/// [`std::borrow::Cow::Owned`] — the substrate-primitive
2310/// [`RestartPolicy::as_str`] accessor's return carries the `&'static
2311/// str` lifetime by construction (each `match` arm resolves to a
2312/// [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const &str`
2313/// with static lifetime), so the zero-alloc borrowed arm is the
2314/// type-correct projection with no runtime allocation.
2315///
2316/// Rust's standard library carries no blanket `impl<T: AsRef<str>>
2317/// From<T> for Cow<'static, str>` (nor an `impl<T: fmt::Display>
2318/// From<T> for Cow<'static, str>`), so the paired sibling
2319/// [`From<RestartPolicy> for &'static str`] (9fb37d0),
2320/// [`From<RestartPolicy> for String`] (7851725), [`AsRef<str>`], and
2321/// [`std::fmt::Display`] surfaces do not implicitly extend to a
2322/// [`Cow<'static, str>`]-bound call site — every such site is forced
2323/// through a `Cow::Borrowed(policy.as_str())` /
2324/// `Cow::Owned(policy.to_string())` open-code whose type bounds have
2325/// no compile-time link back to the substrate primitive until this
2326/// lift.
2327///
2328/// Second peer to extend the substrate-wide trait-idiomatic
2329/// [`std::borrow::Cow<'static, str>`] forward-projection axis off the
2330/// top-level [`crate::CaixaKind`] enum (99c1735 owned-input, d45c409
2331/// borrowed-input) onto the wider substrate — closes the M2 OTP-shape
2332/// tier of the campaign (both sibling peers, `RestartStrategy` and
2333/// `RestartPolicy`, now carry the owned-input Cow<'static, str>
2334/// forward projection) so the remaining eleven peers
2335/// (`PlacementStrategy`, `RateLimitUnit`, `DepList`, `CaixaDialeto`,
2336/// and the outside-`caixa-core` peers `WitShape`, `PathShapeViolation`,
2337/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
2338/// `FerriteRuntime`) are the future targets. Every future arm addition
2339/// (an OTP-`intrinsic` fourth restart policy the ABSORPTION-ROADMAP
2340/// might reach for once the three canonical OTP restart policies stop
2341/// covering the substrate's discovered load-shape) grows the
2342/// Cow<'static, str> axis by construction through one caixa-core edit
2343/// on [`RestartPolicy::as_str`] — rather than a coordinated rewrite
2344/// across every future Cow<'static, str>-bound consumer site.
2345///
2346/// Pinned load-bearing by
2347/// [`tests::restart_policy_from_into_static_cow_str_routes_through_as_str_accessor`]
2348/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
2349/// against [`RestartPolicy::as_str`] across the three-arm
2350/// [`RestartPolicy::ALL`]) and
2351/// [`tests::restart_policy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
2352/// (cross-axis partition pin against the paired [`From<RestartPolicy>
2353/// for &'static str`], [`From<RestartPolicy> for String`], and
2354/// [`ToString`]-through-[`std::fmt::Display`] axes, plus a
2355/// `.iter().copied().map(Cow::from)` pipe witness over
2356/// [`RestartPolicy::ALL`] that materializes the three-arm accept-set
2357/// through the [`Cow<'static, str>`] axis alone and pins the
2358/// zero-alloc discipline on every element).
2359impl From<RestartPolicy> for std::borrow::Cow<'static, str> {
2360 fn from(policy: RestartPolicy) -> std::borrow::Cow<'static, str> {
2361 std::borrow::Cow::Borrowed(policy.as_str())
2362 }
2363}
2364
2365/// Trait-idiomatic *borrowed-input, [`std::borrow::Cow<'static, str>`]
2366/// output* forward projection on the M2 OTP-shape per-child-restart
2367/// [`RestartPolicy`] closed-set typed enum — the borrowed-input
2368/// companion to the paired owned-input
2369/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl
2370/// immediately above (0612398). Routes byte-for-byte through the same
2371/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2372/// accessor (via [`std::borrow::Cow::Borrowed`]) so every consumer
2373/// that holds a `&RestartPolicy` and needs a
2374/// [`std::borrow::Cow<'static, str>`] — a
2375/// `RestartPolicy::ALL.iter().map(std::borrow::Cow::from).collect::<Vec<_>>()`
2376/// per-arm accept-set materializer (whose iterator over
2377/// `&'static [RestartPolicy]` yields `&RestartPolicy`, not
2378/// `RestartPolicy`, so the paired owned-input
2379/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] axis
2380/// alone forces every call site through an explicit `.copied()` /
2381/// dereference / [`Copy`]-bound restatement rather than the direct
2382/// trait-idiomatic projection), a future generic
2383/// `<T: for<'a> Into<std::borrow::Cow<'static, str>>>`-bound emitter
2384/// on a per-child-policy diagnostic column that walks the
2385/// `iter().map(Into::into)` shape verbatim, the future M4 admission-
2386/// webhook rejection body that composes the accepted-policy
2387/// enumeration from an iterated
2388/// `RestartPolicy::ALL.iter().map(|p| p.into())` pipe rather than a
2389/// per-arm `match p { … }` cascade — reaches the same three-arm
2390/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2391/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2392/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2393/// paired [`std::fmt::Display`], [`AsRef<str>`],
2394/// [`RestartPolicy::as_str`], the four
2395/// `{Self, &Self} × {&'static str, String}` 2×2 trait-idiomatic
2396/// forward-projection corners, and the paired owned-input
2397/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl
2398/// already return.
2399///
2400/// Deliberately returns [`std::borrow::Cow::Borrowed`] rather than
2401/// [`std::borrow::Cow::Owned`] — the substrate-primitive
2402/// [`RestartPolicy::as_str`] accessor's return carries the
2403/// `&'static str` lifetime by construction (each `match` arm resolves
2404/// to a [`crate::render::SUPERVISOR_CHILD_RESTART_*`] `pub const &str`
2405/// with static lifetime), so the zero-alloc borrowed arm is the
2406/// type-correct projection with no runtime allocation.
2407///
2408/// Closes the `{Self, &Self}` input-shape corner on the M2 OTP-shape
2409/// per-child-restart [`std::borrow::Cow<'static, str>`] axis opened
2410/// one commit prior (0612398) on the paired owned-input
2411/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`] impl —
2412/// second-of-two-in-M2 closed-set fieldless typed enum peer on the
2413/// caixa surface (paired with the sibling-restart [`RestartStrategy`]
2414/// which carries both {Self, &Self} × Cow<'static, str> corners since
2415/// 7dd28b3 owned-input, 9b3e4b3 borrowed-input), exactly as d45c409
2416/// closed it on the top-level [`crate::CaixaKind`] one commit after
2417/// the owning half (99c1735) landed. This lift closes the whole M2
2418/// OTP-shape tier of the substrate-wide [`Cow<'static, str>`]
2419/// forward-projection campaign on both input-shape corners
2420/// ({Self, &Self}) of both M2 OTP-shape sibling peers
2421/// ([`RestartStrategy`] and [`RestartPolicy`]), so the remaining
2422/// eleven substrate-wide peers (`PlacementStrategy`, `RateLimitUnit`,
2423/// `DepList`, `CaixaDialeto`, `WitShape`, `PathShapeViolation`,
2424/// `InvariantKind`, `ArchVerdict`, `Severity`, `FixSafety`, `Semantic`,
2425/// `FerriteRuntime`) become the future targets of the campaign. Rust's
2426/// standard library does not carry a blanket
2427/// `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor an
2428/// `impl<T: fmt::Display> From<&T> for Cow<'static, str>`), so every
2429/// closed-set fieldless typed enum peer on the substrate that carries
2430/// the paired owned-input [`Cow<'static, str>`] axis but not the
2431/// borrowed-input axis forces every borrowed-input
2432/// [`Cow<'static, str>`]-parameterized call site through a spurious
2433/// [`Copy`] deref (`std::borrow::Cow::from(*policy)`) or a
2434/// `std::borrow::Cow::Borrowed(policy.as_str())` open-code whose type
2435/// bounds have no compile-time link to the substrate primitive.
2436///
2437/// Pinned load-bearing by
2438/// [`tests::restart_policy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor`]
2439/// (byte-parity + zero-alloc [`std::borrow::Cow::Borrowed`]-arm pin
2440/// against [`RestartPolicy::as_str`] across the three-arm
2441/// [`RestartPolicy::ALL`] through the borrowed-input surface) and
2442/// [`tests::restart_policy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
2443/// (cross-axis partition pin against the paired owned-input
2444/// [`From<RestartPolicy> for std::borrow::Cow<'static, str>`], the
2445/// paired borrowed-input owned-`&'static str`
2446/// [`From<&RestartPolicy> for &'static str`], and the paired
2447/// borrowed-input owned-`String` [`From<&RestartPolicy> for String`]
2448/// impls, plus a `.iter().map(std::borrow::Cow::from)` pipe witness
2449/// over [`RestartPolicy::ALL`] — whose iterator yields
2450/// `&RestartPolicy` by construction, so the borrowed-input
2451/// [`Cow<'static, str>`] axis is what routes the pipe through the
2452/// substrate-primitive [`RestartPolicy::as_str`] accessor with the
2453/// zero-alloc [`Cow::Borrowed`] arm by construction and without a
2454/// spurious [`Copy`] deref).
2455impl From<&RestartPolicy> for std::borrow::Cow<'static, str> {
2456 fn from(policy: &RestartPolicy) -> std::borrow::Cow<'static, str> {
2457 std::borrow::Cow::Borrowed(policy.as_str())
2458 }
2459}
2460
2461/// Trait-idiomatic *owned-input, [`Box<str>`] output* forward
2462/// projection on the M2 OTP-shape per-child-restart [`RestartPolicy`]
2463/// closed-set fieldless typed enum — extends the substrate-wide
2464/// `Box<str>` forward-projection campaign tier opened one commit prior
2465/// (69ef45c) on the paired sibling-restart [`RestartStrategy`] onto
2466/// the second (and third-and-final) M2 OTP-shape closed-set fieldless
2467/// typed enum peer on the caixa surface (`:children :restart`),
2468/// immediately after the paired `Cow<'static, str>` axis (0612398 /
2469/// b4dc55c) closed the
2470/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}` 2×3
2471/// corner on this enum. Routes byte-for-byte through the
2472/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2473/// accessor via [`Box::<str>::from`] on the returned `&'static str`,
2474/// so every consumer that binds a
2475/// `let key: Box<str> = policy.into();`-shaped call site — a
2476/// per-child metric-key materializer that stashes the policy
2477/// discriminator in a `Box<str>`-typed heap-owned scalar for cheap
2478/// clone (a shared-nothing per-policy accept-set the `caixa-operator`
2479/// hierarchical reconciliation scheduler's per-child restart-decision
2480/// fan-out carries), a future admission-webhook rejection body whose
2481/// per-arm `Box<str>` field composes from an owned `RestartPolicy`
2482/// handle — reaches the same three-arm lifted
2483/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2484/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2485/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2486/// sibling
2487/// `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
2488/// forward-projection corner already returns. Rust's standard library
2489/// carries `impl From<&str> for Box<str>` and
2490/// `impl From<String> for Box<str>` but no blanket
2491/// `impl<T: AsRef<str>> From<T> for Box<str>` (nor any
2492/// `impl<T: Copy, U: From<T>> From<T> for U` route from the enum), so
2493/// this axis is a distinct trait-idiomatic surface that a downstream
2494/// `RestartPolicy → Box<str>` `.into()` reaches through this impl and
2495/// no other — without a `Box::from(policy.as_str())` open-code whose
2496/// type bounds have no compile-time link back to the substrate
2497/// primitive.
2498///
2499/// Second peer on the substrate-wide trait-idiomatic [`Box<str>`]
2500/// forward-projection family opened on the sibling-restart
2501/// [`RestartStrategy`] (69ef45c / 59ae5dc) — closes the whole M2
2502/// OTP-shape tier of the substrate-wide [`Box<str>`] forward-
2503/// projection campaign's owned-input corner on both M2 OTP-shape
2504/// sibling peers ([`RestartStrategy`] and [`RestartPolicy`]), the
2505/// paired borrowed-input `From<&RestartPolicy> for Box<str>` closer
2506/// and the remaining fieldless-enum peers on the M3 mesh-shape /
2507/// outside-M3 caixa-core / render-side / outside-caixa-core tiers
2508/// are the future targets of the campaign.
2509///
2510/// Pinned load-bearing by
2511/// [`tests::restart_policy_from_into_box_str_routes_through_as_str_accessor`]
2512/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2513/// three-arm [`RestartPolicy::ALL`] emit-set on the owned-input
2514/// surface, plus a blanket-derived [`Into`] shape witness).
2515impl From<RestartPolicy> for Box<str> {
2516 fn from(policy: RestartPolicy) -> Box<str> {
2517 Box::<str>::from(policy.as_str())
2518 }
2519}
2520
2521/// Trait-idiomatic *borrowed-input, [`Box<str>`] output* forward
2522/// projection on the M2 OTP-shape per-child-restart [`RestartPolicy`]
2523/// closed-set fieldless typed enum — the borrowed-input companion to
2524/// the paired owned-input [`From<RestartPolicy> for Box<str>`] impl
2525/// (0a1b313, one commit prior) that closes the `{Self, &Self}`
2526/// input-shape corner of the substrate-wide [`Box<str>`] forward-
2527/// projection axis on the second (and third-and-final) M2 OTP-shape
2528/// closed-set fieldless typed enum peer on the caixa surface
2529/// (`:children :restart`), routing byte-for-byte through the
2530/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2531/// accessor via [`Box::<str>::from`] on the returned `&'static str`.
2532/// Every consumer that holds a `&RestartPolicy` and needs a
2533/// [`Box<str>`] — a
2534/// `RestartPolicy::ALL.iter().map(Box::<str>::from).collect::<Vec<_>>()`
2535/// per-arm accept-set materializer (whose iterator over
2536/// `&'static [RestartPolicy]` yields `&RestartPolicy`, not
2537/// `RestartPolicy`, so the paired owned-input
2538/// [`From<RestartPolicy> for Box<str>`] axis alone forces every
2539/// call site through an explicit [`Copy`] deref or a
2540/// `.copied()` restatement rather than the direct trait-idiomatic
2541/// projection), a per-child metric-key materializer holding
2542/// `&RestartPolicy` through a `caixa-operator` hierarchical
2543/// reconciliation scheduler's borrow lifetime, a future admission-
2544/// webhook rejection body whose per-arm `Box<str>` field composes
2545/// from a borrowed `&RestartPolicy` handle — reaches the
2546/// substrate-primitive [`RestartPolicy::as_str`] accessor through
2547/// this impl and no other, without a
2548/// `Box::<str>::from(policy.as_str())` open-code whose type bounds
2549/// have no compile-time link back to the substrate primitive.
2550///
2551/// Rust's standard library carries `impl From<&str> for Box<str>`
2552/// and `impl From<String> for Box<str>` but no blanket
2553/// `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
2554/// `Copy`-based `impl<T: Copy, U: From<&T> for U`), so every closed-
2555/// set fieldless typed enum peer on the substrate that carries the
2556/// paired owned-input `Box<str>` axis but not the borrowed-input
2557/// axis forces every borrowed-input `Box<str>`-parameterized call
2558/// site through a spurious [`Copy`] deref
2559/// (`Box::<str>::from((*policy).as_str())`) or a
2560/// `Box::<str>::from(policy.as_str())` open-code whose type bounds
2561/// have no compile-time link back to the substrate primitive.
2562///
2563/// Fourth (and closing) peer on the substrate-wide trait-idiomatic
2564/// [`Box<str>`] forward-projection family on the M2 OTP-shape tier
2565/// — closes the whole `{Self, &Self}` input-shape corner of the
2566/// [`Box<str>`] axis on both M2 OTP-shape sibling peers
2567/// ([`RestartStrategy`] and [`RestartPolicy`]), exactly as b4dc55c
2568/// closed the paired [`Cow<'static, str>`] axis one commit after
2569/// its owning half (0612398) landed on this enum. The remaining
2570/// fieldless-enum peers on the M3 mesh-shape / outside-M3 caixa-
2571/// core / render-side / outside-caixa-core tiers are the future
2572/// targets of the [`Box<str>`] campaign.
2573///
2574/// Pinned load-bearing by
2575/// [`tests::restart_policy_from_borrowed_into_box_str_routes_through_as_str_accessor`]
2576/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2577/// three-arm [`RestartPolicy::ALL`] emit-set on the borrowed-input
2578/// surface, plus a blanket-derived [`Into`] shape witness, a
2579/// cross-axis partition pin against the paired owned-input
2580/// [`From<RestartPolicy> for Box<str>`] and the sibling borrowed-
2581/// input `{&'static str, String, Cow<'static, str>}` return-shape
2582/// axes, and a `.iter().map(Box::<str>::from)` pipe witness over
2583/// [`RestartPolicy::ALL`] — whose iterator yields `&RestartPolicy`
2584/// by construction, so the borrowed-input [`Box<str>`] axis is
2585/// what routes the pipe through the substrate-primitive
2586/// [`RestartPolicy::as_str`] accessor without a spurious [`Copy`]
2587/// deref).
2588impl From<&RestartPolicy> for Box<str> {
2589 fn from(policy: &RestartPolicy) -> Box<str> {
2590 Box::<str>::from(policy.as_str())
2591 }
2592}
2593
2594/// Trait-idiomatic *owned-input, [`std::sync::Arc<str>`] output*
2595/// forward projection on the M2 OTP-shape per-child-restart
2596/// [`RestartPolicy`] closed-set fieldless typed enum — routes byte-
2597/// for-byte through the substrate-primitive [`RestartPolicy::as_str`]
2598/// `pub const fn` accessor via [`std::sync::Arc::<str>::from`] on the
2599/// returned `&'static str`, so every consumer that binds a
2600/// [`RestartPolicy`] through the standard-library `.into()` /
2601/// [`From<Self> for std::sync::Arc<str>`] (equivalently
2602/// [`Into<std::sync::Arc<str>>`]) axis — a future admission-webhook's
2603/// per-request `Sync` + `Send`-safe structured-log field composed
2604/// across an `.await` boundary through a
2605/// `<T: Into<std::sync::Arc<str>>>`-bound diagnostic-column dispatch,
2606/// a future wasm-operator's per-child post-exit restart-decision
2607/// pipeline holding a shared-ownership per-arm cache key, a
2608/// `<T: Into<std::sync::Arc<str>>>`-bound `tracing`-span attributes
2609/// collector recording a per-child-policy field onto the parent
2610/// span's shared-ownership context — reaches the same three-arm
2611/// lifted [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2612/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2613/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2614/// sibling
2615/// `{Self, &Self} × {&'static str, String, Cow<'static, str>, Box<str>}`
2616/// forward-projection corner already returns.
2617///
2618/// Second peer on the substrate-wide trait-idiomatic
2619/// [`std::sync::Arc<str>`] forward-projection family opened one
2620/// projection tier prior (bca2ec8) on the paired sibling-restart
2621/// [`RestartStrategy`] owned-input first-mover — extends the tier
2622/// onto the second (and third-and-final) M2 OTP-shape closed-set
2623/// fieldless typed enum peer on the caixa surface
2624/// (`:children :restart`), immediately after the paired [`Box<str>`]
2625/// axis (0a1b313 / cb1d068) closed the whole
2626/// `{Self, &Self} × {&'static str, String, Cow<'static, str>, Box<str>}`
2627/// 2×4 corner on this enum. Rust's standard library carries
2628/// `impl From<&str> for std::sync::Arc<str>` and
2629/// `impl From<String> for std::sync::Arc<str>` but no blanket
2630/// `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor an
2631/// `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`), so this
2632/// axis is a distinct trait-idiomatic surface that a
2633/// `let key: std::sync::Arc<str> = policy.into();`-shaped call site
2634/// reaches through this impl and no other — a paired
2635/// `std::sync::Arc::<str>::from(policy.as_str())` open-code has no
2636/// compile-time link back to the substrate primitive, and a two-step
2637/// `std::sync::Arc::<str>::from(String::from(policy))` composition
2638/// through the owned-`String` axis allocates twice (once into the
2639/// intermediate `String`, once into the [`Arc<str>`] on the
2640/// `From<String>` conversion) where the single-step trait impl
2641/// allocates once.
2642///
2643/// Peer of the sibling [`Box<str>`] second-tier extender (0a1b313) —
2644/// same "extends the substrate-wide projection tier onto the next
2645/// M2 OTP-shape peer" discipline, extended onto the
2646/// [`std::sync::Arc<str>`] axis whose shared-ownership + [`Sync`] +
2647/// [`Send`] contract is the distinct value the [`Box<str>`] axis's
2648/// owned-move return-shape cannot provide.
2649///
2650/// Pinned load-bearing by
2651/// [`tests::restart_policy_from_into_arc_str_routes_through_as_str_accessor`]
2652/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2653/// three-arm [`RestartPolicy::ALL`] emit-set on the owned-input
2654/// surface, plus a blanket-derived [`Into`] shape witness and cross-
2655/// axis byte-parity pins against the sibling owned-input
2656/// `{&'static str, String, Cow<'static, str>, Box<str>}` return-shape
2657/// axes).
2658impl From<RestartPolicy> for std::sync::Arc<str> {
2659 fn from(policy: RestartPolicy) -> std::sync::Arc<str> {
2660 std::sync::Arc::<str>::from(policy.as_str())
2661 }
2662}
2663
2664/// Trait-idiomatic *borrowed-input, [`std::sync::Arc<str>`] output*
2665/// forward projection on the M2 OTP-shape per-child-restart
2666/// [`RestartPolicy`] closed-set fieldless typed enum — closes the
2667/// `{Self, &Self}` input-shape corner of the [`std::sync::Arc<str>`]
2668/// forward-projection axis on the second (and third-and-final) M2
2669/// OTP-shape closed-set fieldless typed enum peer on the caixa
2670/// surface (`:children :restart`), companion to the paired
2671/// owned-input [`From<RestartPolicy> for std::sync::Arc<str>`] impl
2672/// one commit prior (b05724e). Routes byte-for-byte through the
2673/// substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
2674/// accessor (via [`std::sync::Arc::<str>::from`] on the returned
2675/// `&'static str`), so every consumer that binds a
2676/// [`&RestartPolicy`] through the standard-library `.into()` /
2677/// [`From<&Self> for std::sync::Arc<str>`] (equivalently
2678/// [`Into<std::sync::Arc<str>>`]) axis — a future admission-webhook's
2679/// per-request borrowed-`&RestartPolicy` handle rendering a per-arm
2680/// `Sync` + `Send`-safe structured-log field across an `.await`
2681/// boundary through a `<T: Into<std::sync::Arc<str>>>`-bound
2682/// diagnostic-column dispatch, a future wasm-operator's per-child
2683/// post-exit restart-decision pipeline whose
2684/// `.iter().map(std::sync::Arc::<str>::from)` collector reaches
2685/// into the shared-ownership per-arm key without a spurious [`Copy`]
2686/// deref (which would only be reachable through the owned-input
2687/// [`From<RestartPolicy> for std::sync::Arc<str>`] axis by first
2688/// calling `.copied()` on the iterator), a future
2689/// `<T: Into<std::sync::Arc<str>>>`-bound `tracing`-span attributes
2690/// collector recording a borrowed-`&RestartPolicy` per-arm field
2691/// onto the parent span's shared-ownership context — reaches the
2692/// same three-arm lifted
2693/// [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
2694/// [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
2695/// [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`] const the
2696/// paired owned-input [`From<RestartPolicy> for std::sync::Arc<str>`]
2697/// impl and the sibling `{&'static str, String, Cow<'static, str>,
2698/// Box<str>}` forward-projection corner already return.
2699///
2700/// Closes the substrate-wide trait-idiomatic
2701/// [`std::sync::Arc<str>`] forward-projection family opened one
2702/// commit prior (b05724e) on the paired owned-input
2703/// [`From<RestartPolicy> for std::sync::Arc<str>`] impl — closes
2704/// the `{Self, &Self}` input-shape corner of the
2705/// [`std::sync::Arc<str>`] axis on the second (and third-and-final)
2706/// M2 OTP-shape closed-set fieldless typed enum peer on the caixa
2707/// surface, exactly as b3e72d7 closed the paired
2708/// [`std::sync::Arc<str>`] corner on the sibling-restart
2709/// [`RestartStrategy`] first-mover one commit after its owning half
2710/// (bca2ec8) landed, and as cb1d068 closed the paired [`Box<str>`]
2711/// corner on this enum one commit after its owning half (0a1b313)
2712/// landed. Rust's standard library carries `impl From<&str> for
2713/// std::sync::Arc<str>` and `impl From<String> for
2714/// std::sync::Arc<str>` but no blanket `impl<T: AsRef<str>> From<&T>
2715/// for std::sync::Arc<str>` (nor a `Copy`-based `impl<T: Copy,
2716/// U: From<T>> From<&T> for U`), so every closed-set fieldless typed
2717/// enum peer on the substrate that carries the paired owned-input
2718/// [`std::sync::Arc<str>`] axis but not the borrowed-input axis
2719/// forces every borrowed-input [`std::sync::Arc<str>`]-parameterized
2720/// call site through a spurious [`Copy`] deref
2721/// (`std::sync::Arc::<str>::from((*policy).as_str())`) or a
2722/// `std::sync::Arc::<str>::from(policy.as_str())` open-code whose
2723/// type bounds have no compile-time link back to the substrate
2724/// primitive.
2725///
2726/// Pinned load-bearing by
2727/// [`tests::restart_policy_from_borrowed_into_arc_str_routes_through_as_str_accessor`]
2728/// (byte-parity pin against [`RestartPolicy::as_str`] across the
2729/// three-arm [`RestartPolicy::ALL`] emit-set on the borrowed-input
2730/// surface, plus a blanket-derived [`Into`] shape witness, a
2731/// cross-axis pin against the paired owned-input
2732/// [`From<RestartPolicy> for std::sync::Arc<str>`] and the sibling
2733/// borrowed-input `{&'static str, String, Cow<'static, str>,
2734/// Box<str>}` return-shape axes, and a
2735/// `.iter().map(std::sync::Arc::<str>::from)` pipe witness over
2736/// [`RestartPolicy::ALL`]).
2737impl From<&RestartPolicy> for std::sync::Arc<str> {
2738 fn from(policy: &RestartPolicy) -> std::sync::Arc<str> {
2739 std::sync::Arc::<str>::from(policy.as_str())
2740 }
2741}
2742
2743/// Trait-idiomatic byte-view surface on the per-child restart-decision
2744/// policy typed enum.
2745///
2746/// Every consumer that binds its input through the standard-library
2747/// [`AsRef<[u8]>`] trait bound — a byte-keyed
2748/// `HashMap<K: AsRef<[u8]>, V>` per-policy reconciliation-decision
2749/// table lookup on the future wasm-operator supervisor scheduler; a
2750/// `blake3::Hasher::update` / `ring::digest::Context::update` /
2751/// `sha2::Sha256::update` byte-input surface on any future per-child
2752/// content-address digest folded into the [`crate::Lacre`] closure so
2753/// downstream cache-keys partition on the three OTP restart policies
2754/// (`Permanent`, `Temporary`, `Transient`) at content-address time; an
2755/// `std::io::Write::write_all`-bound structured-log per-arm byte-sink —
2756/// reaches the substrate primitive through one trait dispatch rather
2757/// than open-coding the two-hop `restart.as_str().as_bytes()`
2758/// composition at every call site. Routed byte-for-byte through the
2759/// [`RestartPolicy::as_str`] `pub const fn` accessor the paired
2760/// str-view ([`AsRef<str>`], [`std::fmt::Display`],
2761/// [`RestartPolicy::as_str`]) and the five reverse-projection
2762/// (`&'static str`, `String`, `Cow<'static, str>`, `Box<str>`,
2763/// `std::sync::Arc<str>`) return-shape axes already resolve through,
2764/// so any future divergence between the byte-view and str-view axes
2765/// trips at caixa-core test time rather than at a downstream byte-
2766/// consumer's silent split.
2767///
2768/// Peer of the sibling per-supervisor-restart-strategy axis
2769/// [`AsRef<[u8]> for RestartStrategy`] (cd4c4e0, the first M2-OTP-
2770/// shape supervisor slot enum to open this axis) — the sixth
2771/// closed-set fieldless typed enum on the caixa surface to converge
2772/// onto the trait-idiomatic byte-view discipline, and the second (and
2773/// final) M2-OTP-shape sibling to pick it up, closing the byte-view
2774/// axis across the paired `:supervisor :estrategia` +
2775/// `:children :restart` M2 slot pair. Pin load-bearing by the paired
2776/// [`tests::restart_policy_as_ref_bytes_routes_through_as_str_accessor`]
2777/// (fail-before-pass-after byte-parity pin against
2778/// [`RestartPolicy::as_str`] `.as_bytes()` across the three-arm
2779/// [`RestartPolicy::ALL`] emit-set, cross-axis witness against the
2780/// paired str-view [`AsRef<str>`] / [`std::fmt::Display`] /
2781/// [`RestartPolicy::as_str`] axes' `.as_bytes()` byte-tails,
2782/// cross-axis witness against the paired reverse-projection
2783/// `{&'static str, String, Cow<'static, str>, Box<str>,
2784/// std::sync::Arc<str>}` return-shape axes' `.as_bytes()` byte-tails,
2785/// a `<T: AsRef<[u8]>>`-bound-consumer witness that a generic
2786/// byte-input function accepts a [`RestartPolicy`] directly through
2787/// the trait bound, and a `blake3::Hasher::update`-shape byte-input
2788/// surface witness routed through the `<T: AsRef<[u8]>>`-bound
2789/// consumer axis to reach the caixa-lacre compounding target). Any
2790/// future silent detour that routes the byte-view impl off the
2791/// substrate-primitive [`RestartPolicy::as_str`] accessor (a per-arm
2792/// inline `b"Permanent".as_slice()`-shaped re-inlining that opens a
2793/// compile-time link to the un-lifted arm-literal, a swap onto the
2794/// kebab-case [`gen_platform::Discriminant`] catalog identity that
2795/// would collide the wire axis with the dispatcher-catalog axis) trips
2796/// at caixa-core test time rather than at a downstream byte-consumer's
2797/// silent split.
2798impl AsRef<[u8]> for RestartPolicy {
2799 fn as_ref(&self) -> &[u8] {
2800 self.as_str().as_bytes()
2801 }
2802}
2803
2804// Fleet-wide dispatcher-catalog registrations for caixa's OTP
2805// supervisor surface — two more typed shadows over Erlang/OTP
2806// primitives the substrate now mechanically tracks (see
2807// theory/UNIFIED-COMPUTING-MODEL.md §VI for the roadmap +
2808// theory/TYPED-ABSORPTION.md for the absorption arc).
2809gen_platform::register_dispatcher!("caixa.restart-strategy", RestartStrategy);
2810gen_platform::register_dispatcher!("caixa.restart-policy", RestartPolicy);
2811
2812/// One child entry in the supervisor's `:children` list.
2813///
2814/// Every child references another caixa by `:caixa <nome>` + version
2815/// constraint. The supervisor materializes one ComputeUnit per entry.
2816#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2817#[serde(rename_all = "camelCase")]
2818pub struct ChildSpec {
2819 /// The child caixa's `:nome`. Must resolve via the same dependency
2820 /// resolution path as `:deps` (caixa-resolver).
2821 pub caixa: String,
2822
2823 /// Semver constraint (`"^0.1"`, `"~0.1.2"`, etc.) — same shape as
2824 /// [`crate::dep::Dep::versao`].
2825 pub versao: String,
2826
2827 /// Restart policy — an author-omitted slot degrades onto the
2828 /// substrate-canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`]
2829 /// (`permanent`, the Erlang/OTP worker-child default) through the
2830 /// [`Default for RestartPolicy`] impl this `#[serde(default)]` routes
2831 /// to.
2832 #[serde(default)]
2833 pub restart: RestartPolicy,
2834}
2835
2836impl ChildSpec {
2837 /// Substrate-canonical per-`:children` child-caixa `:nome` scalar
2838 /// accessor every consumer that reads the OTP-shape supervised
2839 /// child's identity keys off — returns the author-declared
2840 /// `:children :caixa` byte-string verbatim as a `&str`, borrowed
2841 /// from the typed slot's own [`String`] storage.
2842 ///
2843 /// The `:children :caixa` slot carries the DNS-1123 label — the
2844 /// child caixa's `:nome` — that every emitted cluster artifact
2845 /// derives its `metadata.name` from verbatim: the rendered
2846 /// `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name` per child, the
2847 /// [`crate::LABEL_PROGRAM`] label value on every child's pod
2848 /// identity, and the per-child K8s Service `metadata.name` the
2849 /// future wasm-operator (M3) provisions for inter-child supervision-
2850 /// tree wiring. Every downstream consumer that fans on the child's
2851 /// caixa-name keys off this scalar (the [`SupervisorSpec::validate`]
2852 /// per-child DNS-1123 gate at
2853 /// `require_valid_dns_1123_label(child.nome(), …)`, the per-child
2854 /// duplicate-detection [`crate::render::insert_first_seen`] key, the
2855 /// [`validate_no_self_supervision`] cross-slot equality check
2856 /// against the parent's `:nome`, every `SupervisorError` variant
2857 /// carrying the offending child caixa verbatim for `feira lint`
2858 /// rendering, the future wasm-operator's hierarchical reconciliation
2859 /// scheduler's per-child ComputeUnit-name projection, the future M4
2860 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
2861 /// admission webhook).
2862 ///
2863 /// Prior to this lift the `.caixa` byte-string was accessed inline
2864 /// at seven sites in `supervisor.rs` — the DNS-1123 gate's
2865 /// `&child.caixa`, the four `SupervisorError::{ChildCaixaInvalid,
2866 /// EmptyChildVersion, ChildVersaoInvalid, DuplicateChildCaixa}`
2867 /// carriers' `child.caixa.clone()`, the dedup key's
2868 /// `child.caixa.as_str()`, and the [`validate_no_self_supervision`]
2869 /// `child.caixa == parent_nome` cross-slot check — seven open-coded
2870 /// field-accesses that expressed no compile-time link back to the
2871 /// typed slot. A future extension of the `:children :caixa` axis to
2872 /// a richer author surface (a per-cluster alias table the operator
2873 /// pins through a future `:placement`-scoped slot on the supervisor
2874 /// tree, a namespace-qualified rewrite the M4 CR materializer
2875 /// applies per-CR, a per-child overlay from the future `:children
2876 /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
2877 /// acknowledges) would have had to be threaded through every
2878 /// open-coded copy in lockstep or one consumer would silently
2879 /// disagree with the peers on which caixa a given child resolves to
2880 /// — a child-set lookup that treated the name as `"cart-worker"`
2881 /// while the peer duplicate-detector treated it as
2882 /// `"tenant-a/cart-worker"` would silently split the
2883 /// `DuplicateChildCaixa` membership-lookup diagnostic from the
2884 /// self-supervision detector's parent-equality check, a two-consumer
2885 /// split at the validator far from the source `caixa.lisp` with no
2886 /// field naming the identity-drift root cause. Lifting the resolution
2887 /// rule to a typed method on the substrate primitive means every
2888 /// downstream consumer of the Supervisor's per-`:children` identity
2889 /// surface reaches for exactly one typed dispatch — the resolver's
2890 /// accept-set migrates as a unit on any future axis addition.
2891 ///
2892 /// Sibling of the peer per-`:membros` [`crate::Membro::nome`]
2893 /// (4a32abf) member-caixa `:nome` scalar accessor on the M3
2894 /// mesh-slot surface — same "one typed dispatch on the substrate
2895 /// primitive, thin projections at each consumer" discipline extended
2896 /// onto the M2 supervisor-tree per-`:children` child-identity axis.
2897 /// The two typed axes (`Membro::nome` on the M3 Aplicacao side,
2898 /// `ChildSpec::nome` on the M2 Supervisor side) now share one
2899 /// accessor discipline for the shared substrate concept "another
2900 /// caixa referenced by `:nome`". Peer of the second M2 slot scalar
2901 /// accessor [`crate::UpgradeFromEntry::prior_versao`] (75d27a8) on
2902 /// the sibling per-`:upgrade-from :from` OTP-appup axis — the M2
2903 /// slot family's typed-accessor discipline now spans both the
2904 /// upgrade axis (`:upgrade-from`) and the supervision axis
2905 /// (`:children`), matching the closed M3 mesh-slot accessor family's
2906 /// shape. Named `nome()` to match the tatara-lisp author-surface
2907 /// term the field's docstring already reaches for ("The child
2908 /// caixa's `:nome`") and the peer [`crate::Membro::nome`] /
2909 /// [`crate::Caixa::nome`] / [`crate::dep::Dep::nome`] field-name
2910 /// discipline the substrate already carries — the accessor's name
2911 /// maps directly onto the canonical caixa-identity vocabulary rather
2912 /// than shadowing the field's storage-side `caixa` label.
2913 #[must_use]
2914 pub const fn nome(&self) -> &str {
2915 self.caixa.as_str()
2916 }
2917
2918 /// Substrate-canonical per-`:children` child-caixa `:versao` semver-
2919 /// requirement scalar accessor every consumer that reads the OTP-shape
2920 /// supervised child's version pin keys off — returns the author-declared
2921 /// `:children :versao` byte-string verbatim as a `&str`, borrowed from
2922 /// the typed slot's own [`String`] storage.
2923 ///
2924 /// The `:children :versao` slot carries the Cargo-shaped semver
2925 /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that pins
2926 /// which release of the supervised child caixa the OTP-shape supervisor
2927 /// tree materializes against — the same requirement grammar the peer
2928 /// `:deps :versao` / `:membros :versao` axes carry, resolved through the
2929 /// shared [`crate::render::require_valid_versao_requirement`] cascade
2930 /// and the shared [`crate::version::parse_requirement`] parser. Every
2931 /// downstream consumer that fans on the child's version pin keys off
2932 /// this scalar (the [`SupervisorSpec::validate`] per-child requirement
2933 /// gate at `require_valid_versao_requirement(child.versao_requirement(),
2934 /// …)`, the [`SupervisorError::ChildVersaoInvalid`] variant's carrier
2935 /// for `feira lint` rendering, every future per-cluster version-lock
2936 /// overlay the caixa-operator's hierarchical reconciliation scheduler
2937 /// pins through a future `:placement`-scoped supervisor-tree slot, the
2938 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
2939 /// per-child version resolver, the future wasm-operator's per-child
2940 /// lacre BLAKE3-closure lookup at `ComputeUnit` materialization time).
2941 ///
2942 /// Prior to this lift the `.versao` byte-string was accessed inline at
2943 /// two `&str`-shaped sites in `caixa-core/src/supervisor.rs` — the
2944 /// [`SupervisorSpec::validate`] requirement-gate call
2945 /// `require_valid_versao_requirement(&child.versao, …)` and the
2946 /// [`SupervisorError::ChildVersaoInvalid`] carrier at
2947 /// `versao: child.versao.clone()` — two open-coded field-accesses that
2948 /// expressed no compile-time link back to the typed slot. A future
2949 /// extension of the `:children :versao` axis to a richer author surface
2950 /// (a per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
2951 /// flow, a lacre-projected concrete-version rewrite the operator
2952 /// materializes at CR-admission time, a future `:children :versao-lock`
2953 /// per-cluster override slot the wasm-operator's hierarchical
2954 /// reconciliation scheduler authors per-CR) would have had to be
2955 /// threaded through both open-coded copies in lockstep or one consumer
2956 /// would silently disagree with the peer on which release constraint a
2957 /// given child resolves to — the requirement-gate call reading
2958 /// `"^0.1"` while the error-body carrier read `"tenant-a-pin/^0.1"`
2959 /// would silently split the `ChildVersaoInvalid` diagnostic quote from
2960 /// the actual gate rejection input, a two-consumer split at the
2961 /// validator far from the source `caixa.lisp` with no field naming the
2962 /// version-pin drift root cause. Lifting the resolution rule to a typed
2963 /// method on the substrate primitive means every downstream
2964 /// requirement-facing consumer of the Supervisor's per-`:children`
2965 /// version-pin surface reaches for exactly one typed dispatch — the
2966 /// resolver's accept-set migrates as a unit on any future axis addition.
2967 ///
2968 /// Sibling of the peer per-`:membros` [`crate::Membro::versao_requirement`]
2969 /// (a40b0e3) member-caixa `:versao` scalar accessor on the M3 mesh-slot
2970 /// surface — same "one typed dispatch on the substrate primitive, thin
2971 /// projections at each consumer" discipline extended onto the M2
2972 /// supervisor-tree per-`:children` child-version-pin axis. The two typed
2973 /// axes (`Membro::versao_requirement` on the M3 Aplicacao side,
2974 /// `ChildSpec::versao_requirement` on the M2 Supervisor side) now share
2975 /// one accessor discipline for the shared substrate concept "another
2976 /// caixa referenced by a Cargo-shaped semver requirement". Peer of the
2977 /// sibling per-`:children` [`ChildSpec::nome`] (57c61d0) child-caixa
2978 /// `:nome` scalar accessor — the pair
2979 /// `(nome(), versao_requirement())` jointly projects the
2980 /// `(caixa, versao)` field pair every OTP-shape supervisor-tree consumer
2981 /// that fans on per-child identity + version pin keys off, closing the
2982 /// last unlifted per-`:children` `String`-carry axis so every downstream
2983 /// per-`:children` reader now routes through a typed dispatch on the
2984 /// substrate primitive. Named `versao_requirement()` rather than
2985 /// `versao()` because the field's storage-side `.versao` label is
2986 /// already the author-surface term (`:versao`); the accessor's name
2987 /// carries the semantic role — the semver *requirement* string the
2988 /// shared [`crate::version::parse_requirement`] entry-point consumes —
2989 /// so a raw field access and a typed dispatch read differently at every
2990 /// consumer site. Matches the peer [`crate::Membro::versao_requirement`]
2991 /// naming discipline verbatim.
2992 #[must_use]
2993 pub const fn versao_requirement(&self) -> &str {
2994 self.versao.as_str()
2995 }
2996
2997 /// Substrate-canonical per-`:children` `:restart` OTP-shaped
2998 /// per-child post-exit restart-decision policy scalar accessor every
2999 /// consumer that dispatches on the supervised child's post-exit
3000 /// reconcile posture keys off — returns the author-declared
3001 /// `:children :restart` variant verbatim as a [`RestartPolicy`],
3002 /// `Copy`-projected from the typed slot's own [`RestartPolicy`]
3003 /// storage.
3004 ///
3005 /// The `:children :restart` slot carries the closed-set OTP-shaped
3006 /// per-child restart-decision policy discriminator
3007 /// ([`RestartPolicy::Permanent`] — always restart, the OTP `permanent`
3008 /// worker-child default; [`RestartPolicy::Transient`] — restart only
3009 /// on abnormal exit, the OTP `transient` clean-completion-aware
3010 /// default; [`RestartPolicy::Temporary`] — never restart, the OTP
3011 /// `temporary` one-shot default) that every downstream consumer of
3012 /// the Supervisor's per-child post-exit reconcile branch keys off.
3013 /// Every future downstream consumer that fans on the per-child
3014 /// restart-decision keys off this scalar (the future `feira app
3015 /// graph` per-child restart column, the future wasm-operator's
3016 /// per-child post-exit restart-decision branch, the future M4
3017 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
3018 /// admission webhook, the `caixa-operator`'s hierarchical
3019 /// reconciliation scheduler's per-child post-exit reconcile branch,
3020 /// the [`RestartPolicy::as_str`] `Serialize`-derive-pinning path the
3021 /// [`tests::restart_policy_variants_serialize_to_lifted_scalar_values`]
3022 /// pin threads through).
3023 ///
3024 /// Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
3025 /// (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
3026 /// scalar accessor and the M3 mesh-slot
3027 /// [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
3028 /// [`crate::PlacementStrategy`] distribution-strategy scalar accessor
3029 /// — same "one typed dispatch on the substrate primitive,
3030 /// `Copy`-projected closed-set enum-arm discriminator that partitions
3031 /// the downstream renderer's per-arm fan-out" discipline extended
3032 /// onto the M2 supervisor-slot per-`:children` restart-decision-policy
3033 /// `Copy`-composite-enum scalar axis. Third axis on the per-`:children`
3034 /// [`ChildSpec`] type — companion to the sibling per-`:children`
3035 /// [`ChildSpec::nome`] (57c61d0) child-caixa `:nome` scalar accessor
3036 /// and the per-`:children` [`ChildSpec::versao_requirement`]
3037 /// (2c053c8) child-caixa `:versao` semver-requirement scalar accessor
3038 /// on the sibling `String`-carry axes. The triple
3039 /// `(nome(), versao_requirement(), restart())` jointly projects the
3040 /// `(caixa, versao, restart)` field trio every OTP-shape supervisor-
3041 /// tree consumer that fans on per-child identity + version pin +
3042 /// restart-decision keys off, closing the last unlifted per-`:children`
3043 /// axis so every downstream per-`:children` reader now routes through
3044 /// a typed dispatch on the substrate primitive. Named `restart()` to
3045 /// match the storage field's name and the author-surface
3046 /// `:children :restart` slot term verbatim; the accessor's identity
3047 /// name maps onto the canonical OTP-shape per-child restart-decision-
3048 /// policy vocabulary the [`RestartPolicy`] enum's docstring already
3049 /// carries.
3050 ///
3051 /// Declared `pub const fn` to close the last non-`const`
3052 /// `Copy`-return raw-field-getter posture on the M2
3053 /// per-`:children` [`ChildSpec`] substrate-primitive surface — peer
3054 /// of the sibling M2 per-`:supervisor`
3055 /// [`SupervisorSpec::estrategia`] (converted in this commit)
3056 /// `Copy`-composite-enum accessor, the sibling M2 per-`:supervisor`
3057 /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
3058 /// already lifted, and the peer M3 mesh-slot per-`:entrada`
3059 /// [`crate::Entrada::port`] (bafa004) / per-`:placement`
3060 /// [`crate::Placement::estrategia`] (bafa004) `Copy`-return
3061 /// `pub const fn` scalar accessors on the sibling M3 surface. Every
3062 /// downstream substrate-side `const`-context consumer of the
3063 /// per-`:children` restart-decision-policy scalar (a future
3064 /// module-scope `const _:() = assert!(matches!(child.restart(),
3065 /// RestartPolicy::Permanent))` invariant pin on a typed fixture, a
3066 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
3067 /// admission-webhook `const fn` per-child restart-decision floor
3068 /// over a typed [`ChildSpec`], any future `const fn` supervisor-tree
3069 /// composer over the substrate primitive that fans on the per-child
3070 /// restart-decision policy at compile time) now reaches through the
3071 /// same typed dispatch on the substrate primitive at const-eval
3072 /// time as at runtime. A future non-`Copy`-return promotion of the
3073 /// scalar (an `Option<RestartPolicy>`-shape migration on the
3074 /// per-child restart-decision axis once heterogeneous per-cluster
3075 /// restart-policy overlays land, a per-tenant restart-policy-alias
3076 /// table the M4 CR materializer resolves per-CR) that would drop
3077 /// the `const` qualifier fails the fail-before-pass-after pin
3078 /// [`tests::child_spec_restart_accessor_is_const_fn`] at caixa-core
3079 /// build time rather than surfacing as a downstream consumer
3080 /// regression.
3081 #[must_use]
3082 pub const fn restart(&self) -> RestartPolicy {
3083 self.restart
3084 }
3085}
3086
3087/// Supervisor-typed slots that live alongside the standard Caixa
3088/// fields when `:kind Supervisor`. Held flat in [`crate::Caixa`] so
3089/// the manifest stays a single typed form; this struct exists for
3090/// validation + conversion.
3091#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
3092#[serde(rename_all = "camelCase")]
3093pub struct SupervisorSpec {
3094 /// Restart strategy. Defaults to [`RestartStrategy::OneForOne`].
3095 #[serde(default)]
3096 pub estrategia: RestartStrategy,
3097
3098 /// Max restarts within [`Self::restart_window`] before the
3099 /// supervisor itself terminates (and its parent supervisor decides
3100 /// what to do). Default 5.
3101 #[serde(default = "default_max_restarts")]
3102 pub max_restarts: u32,
3103
3104 /// Sliding window for `max_restarts`. Authored as a duration
3105 /// string (`"60s"`, `"5m"`); absent = "never reset". A `Some(0s)`
3106 /// is rejected by [`Self::validate`] — Erlang/OTP's
3107 /// `MaxIntensity / Period` invariant requires a positive window
3108 /// (a zero-period supervisor either trips on the first failure or
3109 /// never trips, depending on operator interpretation, neither of
3110 /// which is the author's intent). Omit the slot to express "no
3111 /// reset"; carry a positive duration to express the sliding window.
3112 #[serde(
3113 default,
3114 skip_serializing_if = "Option::is_none",
3115 with = "duration_codec"
3116 )]
3117 pub restart_window: Option<Duration>,
3118
3119 /// Static children. Empty for `SimpleOneForOne` (children added
3120 /// dynamically); required for the other three strategies.
3121 #[serde(default)]
3122 pub children: Vec<ChildSpec>,
3123}
3124
3125const fn default_max_restarts() -> u32 {
3126 // Route the private serde-`#[serde(default = "…")]` helper through
3127 // the substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] typed
3128 // `pub const` rather than the raw `5` literal — one source of truth
3129 // for the Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
3130 // default across the two production consumers that currently
3131 // dispatch on it (this helper via `#[serde(default = "…")]` on
3132 // `SupervisorSpec::max_restarts` and the [`Default for SupervisorSpec`]
3133 // impl at line 962). Pinned by
3134 // `default_max_restarts_helper_routes_through_lifted_default` +
3135 // `supervisor_spec_default_max_restarts_routes_through_lifted_default`
3136 // in the tests module; peer of the sibling caixa-core
3137 // [`crate::manifest::Caixa::supervisor_view`] `unwrap_or(…)` fold
3138 // that now routes its author-omitted `:max-restarts` arm through
3139 // the same lifted constant.
3140 SUPERVISOR_MAX_RESTARTS_DEFAULT
3141}
3142
3143/// Substrate-canonical Erlang/OTP-shaped `MaxIntensity` restart-budget-
3144/// count default for the `:supervisor :max-restarts` axis — the
3145/// canonical `{intensity, 5, 60}` `MaxIntensity` half of Learn You Some
3146/// Erlang's worker-supervisor default, extracted as a typed `pub const`
3147/// so every substrate-side consumer that resolves "what
3148/// [`SupervisorSpec::max_restarts`] value does an author-omitted
3149/// `:max-restarts` slot degrade onto?" reaches for exactly one
3150/// substrate-primitive `u32`.
3151///
3152/// The `:max-restarts` default axis has two production consumers on the
3153/// substrate side today (both prior to this lift folded onto raw `5`
3154/// literals with no compile-time link back to a shared truth): the
3155/// serde-`#[serde(default = "default_max_restarts")]` helper on
3156/// [`SupervisorSpec::max_restarts`] that every author-omitted
3157/// `:supervisor :max-restarts` slot lands in past the derive-macro's
3158/// wire-format compose, and the [`crate::manifest::Caixa::supervisor_view`]
3159/// `.max_restarts().unwrap_or(5)` fold that every downstream consumer of
3160/// the composed [`SupervisorSpec`] altitude reaches through
3161/// (`feira app graph`, the future wasm-operator's per-supervisor
3162/// restart-intensity counter, the future M4
3163/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3164/// webhook, the caixa-operator's hierarchical reconciliation scheduler).
3165/// A pair of open-coded `5`s across two files that expressed no
3166/// compile-time link back to the shared OTP-canonical default — a
3167/// future rebrand of the default (a tightening to Elixir's
3168/// `Supervisor.max_restarts: 3`, a widening to a per-cluster overlay
3169/// the operator pins through a future
3170/// `:supervisor :max-restarts-overrides` slot the MESH-COMPOSITION
3171/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
3172/// plain `u32` count to a richer `{MaxR, MaxT}` per-child-cohort
3173/// restart-budget-partition once the INSPIRATIONS §II.2 Erlang/OTP
3174/// per-child-cohort roadmap lands) would have had to be threaded
3175/// through both open-coded copies in lockstep or the wire-format
3176/// author-omitted arm and the view-construction author-omitted arm
3177/// would silently disagree on which restart-budget an omitted
3178/// `:max-restarts` resolves to (an author writing `:supervisor
3179/// (:max-restarts ())` would round-trip through serde with the new
3180/// default while `supervisor_view` silently continued to compose the
3181/// stale `5`, or vice versa), a two-consumer split at the composition
3182/// boundary far from the source `caixa.lisp` with no field naming the
3183/// default-drift root cause. Lifting the resolution rule to a typed
3184/// `pub const` on the substrate primitive means every downstream
3185/// consumer of the per-Supervisor default-restart-budget-count surface
3186/// reaches for exactly one substrate-primitive `u32` — the resolver's
3187/// accepted value migrates as a unit on any future axis change.
3188///
3189/// The `5` value pins Learn You Some Erlang's `{intensity, 5, 60}`
3190/// worker-supervisor default (the closest canonical OTP-shape
3191/// production reference the substrate carries, matching the sibling
3192/// `60s` `Period` default the [`Default for SupervisorSpec`] impl pairs
3193/// this constant with on the paired sliding-window axis). Two orders of
3194/// magnitude below the [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` ceiling
3195/// (the upper bracket on the same axis, sibling of this lower default;
3196/// both are typed `u32` const bounds on the `:supervisor :max-restarts`
3197/// axis and now share one accessor discipline on the substrate) and
3198/// above the OTP-`supervisor` callback-module `MaxR = 1` minimum-
3199/// restart floor — the "one restart, then escalate" default is
3200/// deliberately loose enough to absorb a short burst of transient
3201/// child failures without escalating past the supervisor's parent
3202/// while remaining tight enough to trip the `MaxIntensity / Period`
3203/// ratio's escalation on a genuinely-stuck child within the sibling
3204/// `60s` sliding window.
3205///
3206/// Lifted as a typed `pub const` so the bound has exactly one source
3207/// of truth — the serde-side wire-format author-omitted arm at
3208/// [`default_max_restarts`], the [`Default for SupervisorSpec`] impl's
3209/// struct-literal default field, and the caixa-core
3210/// [`crate::manifest::Caixa::supervisor_view`] fold's author-omitted
3211/// arm all read from one place. Same shape every other typed default
3212/// in this crate carries (the sibling
3213/// [`SUPERVISOR_MAX_RESTARTS_MAX`] upper cap on the same axis, the
3214/// paired [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the
3215/// sibling `:restart-window` axis, and the peer
3216/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
3217/// per-renderer defaults on the caixa-flux / caixa-helm rendering
3218/// axes).
3219pub const SUPERVISOR_MAX_RESTARTS_DEFAULT: u32 = 5;
3220
3221/// Upper-bound ceiling on the `:supervisor :max-restarts` axis — every
3222/// validated [`SupervisorSpec::max_restarts`] past
3223/// [`SupervisorSpec::validate`] lies in `1..=SUPERVISOR_MAX_RESTARTS_MAX`.
3224///
3225/// The typed field is `u32` (the zero-floor arm
3226/// [`SupervisorError::ZeroMaxRestarts`] already brackets the bottom edge),
3227/// so a programmatic struct literal
3228/// (`SupervisorSpec { max_restarts: u32::MAX, .. }`) and the equivalent
3229/// author-surface form (`:max-restarts 4294967295` or any
3230/// `:max-restarts 100000`-shape typo landing in the slot) both round-trip
3231/// cleanly through serde — a structurally unbounded `u32` ceiling. The
3232/// runtime substrate consuming the value (Erlang/OTP's
3233/// `MaxIntensity / Period` ratio, the future wasm-operator's
3234/// per-supervisor restart-intensity counter, the M4
3235/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook)
3236/// then turned a typed `:max-restarts` policy into a no-op supervisor: the
3237/// escalation threshold is structurally so high that no realistic
3238/// restarts-per-`:restart-window` traffic shape can reach it, the
3239/// supervisor never escalates to its parent, and a bad child can loop
3240/// inside the window indefinitely with the parent supervisor structurally
3241/// never receiving the "this subtree has exceeded its restart budget"
3242/// signal the typed slot is meant to express — the canonical
3243/// "supervisor intensity declared, no escalation" footgun, exactly the
3244/// peer of the [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap
3245/// on the `:politicas :circuit-breaker :max-failures` axis (both are
3246/// "trip the next-higher protection layer after N events in a rolling
3247/// window" counters with identical degenerate-at-the-high-end shape).
3248///
3249/// The `1000` ceiling matches the sibling
3250/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] (the closest
3251/// peer — same "events-per-window trip threshold" semantics, same `u32`
3252/// type, same no-op-at-the-high-end failure mode) so the M4
3253/// `mesh.pleme.io/v1alpha1/Supervisor` / `.../Aplicacao` CR materializers
3254/// and the future wasm-operator's per-supervisor restart-intensity
3255/// counter reach for either field knowing the value is in `1..=1000`
3256/// without re-validating at the reconciler layer. The cap sits two
3257/// orders of magnitude above every documented Erlang/OTP production
3258/// playbook recommendation (Learn You Some Erlang's
3259/// `{intensity, 5, 60}` worker-supervisor default, Elixir's `Supervisor`
3260/// `max_restarts: 3` default, OTP's `supervisor` callback module
3261/// `MaxR = 1` / `MaxT = 5` "minimal-restart" default, Riak Core's
3262/// typical `MaxR ∈ 5..=100`, RabbitMQ's broker-supervisor `MaxR = 5`
3263/// default) and below the clearly-pathological "effectively no
3264/// escalation" floor (`10_000`, `100_000`, `u32::MAX`): a value the
3265/// author can plausibly want at hyperscale (a long-running supervisor
3266/// over a very-flaky pool tolerating thousands of transient restarts
3267/// before escalating), but a hard wall above which the typed policy is
3268/// structurally a no-op carried verbatim on every emitted child-restart
3269/// reconciliation contract.
3270///
3271/// Lifted as a typed `pub const` so the bound has exactly one source of
3272/// truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
3273/// materializer's admission webhook and the wasm-operator-side
3274/// per-supervisor restart-intensity reconciler read from one place. Same
3275/// shape every other typed upper bound in this crate carries
3276/// ([`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
3277/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
3278/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
3279/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3280/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3281/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3282pub const SUPERVISOR_MAX_RESTARTS_MAX: u32 = 1000;
3283
3284/// Upper-bound ceiling on the `:supervisor :restart-window` axis —
3285/// every validated `Some(`[`SupervisorSpec::restart_window`]`)` past
3286/// [`SupervisorSpec::validate`] lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
3287/// (inclusive on both ends, integer-millisecond magnitudes by the
3288/// canonical-form gate immediately preceding).
3289///
3290/// The typed field is `Option<Duration>` (the zero-floor arm
3291/// [`SupervisorError::RestartWindowZero`] already rejects
3292/// `Some(Duration::ZERO)`, and the canonical-form arm
3293/// [`SupervisorError::RestartWindowNotCanonical`] already rejects
3294/// sub-millisecond residue), so a programmatic struct literal
3295/// (`SupervisorSpec { restart_window: Some(Duration::from_secs(86_400)),
3296/// .. }` — 24h) and the equivalent author-surface form
3297/// (`(:supervisor (:restart-window "24h"))` — the shared duration codec
3298/// emits `"<n>h"` for any integer-hour magnitude) both round-trip
3299/// cleanly through serde — a structurally unbounded `Duration` ceiling.
3300/// A `:restart-window` value far above the documented Erlang/OTP
3301/// `MaxIntensity / Period` production-playbook band (Learn You Some
3302/// Erlang's `{intensity, 5, 60}` worker-supervisor `Period = 60s`
3303/// default, Elixir's `Supervisor` `max_seconds: 5` default, OTP's
3304/// `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's
3305/// `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default)
3306/// degenerates the supervisor's restart-intensity counter into a
3307/// lifetime counter: the rolling failure-counting window is structurally
3308/// so long that transient restarts are never forgotten, so the
3309/// `MaxIntensity / Period` ratio degenerates from "trip the parent
3310/// supervisor when the child has exceeded its restart budget *within
3311/// the recent window*" to "trip the parent when the child has exceeded
3312/// its restart budget *over its lifetime*" — every transient restart
3313/// counts against the budget forever, the supervisor's reset semantic
3314/// never reaches the child, and the typed `:restart-window` slot
3315/// becomes a no-op rolling window carried on every emitted hierarchical
3316/// reconciliation contract. The canonical
3317/// rolling-window-degenerates-to-lifetime-counter footgun the sibling
3318/// [`crate::POLICY_BREAKER_WINDOW_MAX`] cap closes on the peer
3319/// `:politicas :circuit-breaker :window` axis with identical shape (both
3320/// are "rolling failure-counting window with a per-`Period` reset" Duration
3321/// axes whose lifetime-counter degenerate at the high end is the same
3322/// "the reset semantic never fires" CSE invariant violation).
3323///
3324/// The `1h` (3600s = `3_600_000` ms) ceiling matches the largest unit
3325/// the shared duration codec emits (`"<n>h"` for any integer-hour
3326/// magnitude) — every value in the canonical authoring form's
3327/// `<integer><unit>` grammar at or below this cap renders to a clean
3328/// canonical string — and matches the three sibling typed-`Duration`
3329/// caps already lifted to this surface
3330/// ([`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
3331/// [`crate::POLICY_BREAKER_WINDOW_MAX`]). All four typed-`Duration`
3332/// axes — per-process `:limits :wall-clock`, per-edge `:politicas
3333/// :timeout`, per-breaker `:politicas :circuit-breaker :window`, and
3334/// per-supervisor `:supervisor :restart-window` — now share a single
3335/// uniform top edge at the codec's largest emitted unit so the next
3336/// typed-slot wiring (the future wasm-operator's per-supervisor
3337/// `MaxIntensity / Period` reconciler, the M4
3338/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3339/// webhook, the `caixa-operator`'s hierarchical reconciliation
3340/// scheduler) reaches for any of the four knowing the value is in
3341/// `1ms..=1h` without re-validating at the renderer layer. The cap sits
3342/// two orders of magnitude above every documented Erlang/OTP / Elixir /
3343/// Riak Core / RabbitMQ production-playbook recommendation band
3344/// (`5s..=300s`) and below the clearly-pathological "rolling window
3345/// degenerates to lifetime counter" floor (`24h`, `7d`, `Duration::MAX`):
3346/// a value the author can plausibly want for a very-low-traffic
3347/// long-tail failure-restart window over a hyperscale-flaky child pool,
3348/// but a hard wall above which the rolling-window contract is
3349/// structurally a lifetime-counter contract.
3350///
3351/// Lifted as a typed `pub const` so the bound has exactly one source
3352/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
3353/// materializer's admission webhook, the wasm-operator-side
3354/// per-supervisor `MaxIntensity / Period` reconciler, and the
3355/// `caixa-operator`'s hierarchical reconciliation scheduler all read
3356/// from one place. Same shape every other typed upper bound in this
3357/// crate carries ([`SUPERVISOR_MAX_RESTARTS_MAX`],
3358/// [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`],
3359/// [`crate::aplicacao::POLICY_RETRIES_MAX`],
3360/// [`crate::aplicacao::POLICY_RATE_LIMIT_MAX`],
3361/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3362/// [`crate::LIMITS_WALL_CLOCK_MAX`], [`crate::POLICY_TIMEOUT_MAX`],
3363/// [`crate::POLICY_BREAKER_WINDOW_MAX`],
3364/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3365/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3366pub const SUPERVISOR_RESTART_WINDOW_MAX: Duration = Duration::from_secs(3600);
3367
3368/// Substrate-canonical Erlang/OTP-shaped `Period` sliding-window-duration
3369/// default for the `:supervisor :restart-window` axis — the canonical
3370/// `{intensity, 5, 60}` `Period` half of Learn You Some Erlang's
3371/// worker-supervisor default, extracted as a typed `pub const` so every
3372/// substrate-side consumer that resolves "what
3373/// [`SupervisorSpec::restart_window`] value does an author-omitted
3374/// `:restart-window` slot degrade onto?" reaches for exactly one
3375/// substrate-primitive [`Duration`].
3376///
3377/// The `:restart-window` default axis has one production consumer on the
3378/// substrate side today: the [`Default for SupervisorSpec`] impl's
3379/// struct-literal `restart_window` field, which prior to this lift folded
3380/// onto a raw `Duration::from_secs(60)` literal with no compile-time link
3381/// back to the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity`
3382/// half of the same `{intensity, 5, 60}` OTP-canonical default. The
3383/// [`crate::manifest::Caixa::supervisor_view`] fold deliberately does
3384/// *not* fall back to this default on the sibling `:restart-window` axis
3385/// — an author-omitted `:supervisor :restart-window` composes to
3386/// `restart_window: None` (the shared codec's soft-swallow shape),
3387/// keeping author-declared intent ("no reset — never escalate on rolling
3388/// window") distinct from the [`Default for SupervisorSpec`] "canonical
3389/// 60s Period" arm every programmatic `SupervisorSpec::default()` caller
3390/// resolves to. Prior to this lift the paired `{intensity, 5, 60}` OTP
3391/// default was split across two files with no compile-time link between
3392/// the halves: [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] pinned the
3393/// `MaxIntensity` half at the substrate primitive while the `Period`
3394/// half rode as an open-coded literal at the composition site, so a
3395/// future coherent rebrand of the paired canonical (a tightening to
3396/// Elixir's `{max_restarts: 3, max_seconds: 5}`, a widening to a
3397/// per-cluster overlay the operator pins through a future
3398/// `:supervisor :restart-window-overrides` slot the MESH-COMPOSITION
3399/// §III.2 supervision-canary roadmap acknowledges, a promotion of the
3400/// paired constants to a per-child-cohort `{MaxR, MaxT}` restart-budget-
3401/// partition once the INSPIRATIONS §II.2 Erlang/OTP per-child-cohort
3402/// roadmap lands) would have had to migrate the `MaxIntensity` half
3403/// through the lifted constant and the `Period` half through a raw
3404/// literal in lockstep or the two halves of the same OTP-canonical
3405/// default would silently drift out of pairing. Lifting the resolution
3406/// rule to a typed `pub const` on the substrate primitive means the
3407/// paired OTP-canonical default migrates as one unit on any future
3408/// axis change.
3409///
3410/// The `60s` value pins Learn You Some Erlang's `{intensity, 5, 60}`
3411/// worker-supervisor default (the closest canonical OTP-shape
3412/// production reference the substrate carries, matching the paired
3413/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5` `MaxIntensity` half this
3414/// constant is the `Period` denominator of on the same
3415/// `MaxIntensity / Period` restart-intensity ratio). Two orders of
3416/// magnitude below the [`SUPERVISOR_RESTART_WINDOW_MAX`] `3600s`
3417/// (`1h`) ceiling (the upper bracket on the same axis, sibling of
3418/// this lower default; both are typed [`Duration`] const bounds on the
3419/// `:supervisor :restart-window` axis and now share one accessor
3420/// discipline on the substrate) and above the OTP-`supervisor`
3421/// callback-module `MaxT = 5` seconds "minimal-window" floor — the "60s
3422/// rolling window" default is deliberately loose enough to absorb a
3423/// short burst of transient child failures without escalating past the
3424/// supervisor's parent while remaining tight enough for the paired
3425/// `MaxIntensity / Period` ratio's escalation to trip on a genuinely-
3426/// stuck child within a human-scale observation window.
3427///
3428/// Lifted as a typed `pub const` so the paired OTP-canonical default has
3429/// exactly one source of truth on each half — the sibling
3430/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half and this
3431/// `Period` `60s` half now share the same substrate-primitive lift
3432/// discipline. Same shape every other typed default in this crate
3433/// carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] paired
3434/// `MaxIntensity` half on the same OTP-canonical `{intensity, 5, 60}`,
3435/// the sibling [`SUPERVISOR_RESTART_WINDOW_MAX`] upper cap on the same
3436/// axis, and the peer [`crate::render::DEFAULT_NAMESPACE`] /
3437/// [`crate::render::DEFAULT_LIBRARY_NAME`] per-renderer defaults on the
3438/// caixa-flux / caixa-helm rendering axes).
3439pub const SUPERVISOR_RESTART_WINDOW_DEFAULT: Duration = Duration::from_secs(60);
3440
3441/// Substrate-canonical Erlang/OTP-shaped sibling-restart-strategy default
3442/// for the `:supervisor :estrategia` axis — the canonical `one_for_one`
3443/// half of Learn You Some Erlang's `{one_for_one, intensity, 5, 60}`
3444/// worker-supervisor default, extracted as a typed `pub const` so every
3445/// substrate-side consumer that resolves "what
3446/// [`SupervisorSpec::estrategia`] variant does an author-omitted
3447/// `:estrategia` slot degrade onto?" reaches for exactly one substrate-
3448/// primitive [`RestartStrategy`].
3449///
3450/// The `:estrategia` default axis has three production consumers on the
3451/// substrate side today: the [`Default for RestartStrategy`] impl's
3452/// return arm, the [`Default for SupervisorSpec`] impl's struct-literal
3453/// `estrategia` field, and the
3454/// [`crate::manifest::Caixa::supervisor_view`] fold's
3455/// `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)` `Option<RestartStrategy>`
3456/// collapse arm — three entry points onto the same OTP-canonical
3457/// `one_for_one` value that prior to this lift folded onto a raw
3458/// `Self::OneForOne` arm at the [`Default for RestartStrategy`] impl and
3459/// implicit `RestartStrategy::default()` routes at the sibling consumers,
3460/// with no compile-time link back to the paired
3461/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` half + the paired
3462/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` half of the same
3463/// `{one_for_one, intensity, 5, 60}` OTP-canonical default. The paired
3464/// triple was split across three altitudes with no compile-time link
3465/// between the halves: the `MaxIntensity` half rode through the lifted
3466/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant (b698ec0) and the `Period`
3467/// half rode through the lifted [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3468/// constant (f7dcd0e) while the `one_for_one` half rode as an open-coded
3469/// discriminator at the [`Default for RestartStrategy`] impl, so a future
3470/// coherent rebrand of the triple (Elixir's `{:one_for_one,
3471/// max_restarts: 3, max_seconds: 5}` — same strategy, different
3472/// intensity/period; an OTP `rest_for_one` widening once the substrate
3473/// discovers startup-order-coupled child cohorts as the more common
3474/// worker-supervisor default; a per-cluster overlay the operator pins
3475/// through a future `:estrategia-overrides` slot the MESH-COMPOSITION
3476/// §III.2 supervision-canary roadmap acknowledges) would have had to
3477/// migrate the `MaxIntensity` + `Period` halves through the lifted
3478/// constants and the `one_for_one` half through an open-coded arm in
3479/// lockstep or the three halves of the same OTP-canonical default would
3480/// silently drift out of pairing. Lifting the resolution rule to a typed
3481/// `pub const` on the substrate primitive means the paired OTP-canonical
3482/// worker-supervisor default migrates as one unit on any future axis
3483/// change.
3484///
3485/// The [`RestartStrategy::OneForOne`] value pins Learn You Some Erlang's
3486/// `{one_for_one, intensity, 5, 60}` worker-supervisor default (the
3487/// closest canonical OTP-shape production reference the substrate
3488/// carries, matching the paired [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `5`
3489/// `MaxIntensity` half and the paired [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3490/// `60s` `Period` half). The `one_for_one` strategy — restart only the
3491/// failed child, leaving siblings untouched — is the default for tree-of-
3492/// independent-workers use cases the substrate's [`RestartStrategy`]
3493/// discriminator's own docstring already carries as the default arm; it
3494/// composes with the `{5, 60}` restart-intensity ratio to name the same
3495/// substrate-canonical "canonical worker-supervisor" shape the paired
3496/// halves close on their respective axes.
3497///
3498/// Lifted as a typed `pub const` so the paired OTP-canonical default has
3499/// exactly one source of truth on each of its three halves — the sibling
3500/// [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] `MaxIntensity` `5` half, the
3501/// sibling [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] `Period` `60s` half, and
3502/// this `one_for_one` strategy half now share the same substrate-
3503/// primitive lift discipline. Same shape every other typed default in
3504/// this crate carries (the sibling [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] +
3505/// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] paired halves on the same OTP-
3506/// canonical `{one_for_one, intensity, 5, 60}`, the sibling
3507/// [`SUPERVISOR_MAX_RESTARTS_MAX`] + [`SUPERVISOR_RESTART_WINDOW_MAX`]
3508/// upper caps on the paired sibling axes, and the peer
3509/// [`crate::render::DEFAULT_NAMESPACE`] / [`crate::render::DEFAULT_LIBRARY_NAME`]
3510/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes).
3511pub const SUPERVISOR_ESTRATEGIA_DEFAULT: RestartStrategy = RestartStrategy::OneForOne;
3512
3513/// Substrate-canonical Erlang/OTP-shaped per-child restart-decision-policy
3514/// default for the `:children :restart` axis — the OTP `permanent`
3515/// worker-child default (`{ChildId, StartFunc, permanent, …}` in a
3516/// `supervisor`'s `init/1` child-spec tuple), extracted as a typed
3517/// `pub const` so every substrate-side consumer that resolves "what
3518/// [`ChildSpec::restart`] variant does an author-omitted `:children
3519/// :restart` slot degrade onto?" reaches for exactly one substrate-
3520/// primitive [`RestartPolicy`].
3521///
3522/// Completes the OTP-shape supervisor-tree default set at the substrate
3523/// primitive. The per-`:supervisor` axis already carries all three of its
3524/// halves as lifted typed constants — [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
3525/// (`one_for_one`, 95ffacc), [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
3526/// (`MaxIntensity` `5`, b698ec0), [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3527/// (`Period` `60s`, f7dcd0e) — while the per-`:children` axis's own
3528/// OTP-canonical default rode as an open-coded `Self::Permanent` arm in
3529/// the [`Default for RestartPolicy`] impl, the last un-lifted default on
3530/// the M2 `:supervisor` slot family. The split mattered because the two
3531/// axes resolve *together* on every author-omitted supervisor: a
3532/// `(defcaixa :kind Supervisor :children ((:caixa "worker" :versao
3533/// "^0.1")))` with no `:estrategia` and no per-child `:restart` degrades
3534/// onto `{one_for_one, 5, 60}` through three lifted constants and onto
3535/// `permanent` through an open-coded enum arm, so a future coherent
3536/// rebrand of the OTP-shape default set (an Elixir-shaped
3537/// `{:one_for_one, max_restarts: 3, max_seconds: 5}` tightening, a
3538/// per-cluster overlay the operator pins through the MESH-COMPOSITION
3539/// §III.2 supervision-canary roadmap slots, an OTP-`transient` widening
3540/// once the substrate discovers clean-completion-aware children as the
3541/// more common child shape) would have had to migrate three halves
3542/// through typed constants and the fourth through a raw enum arm in
3543/// lockstep or the supervisor-level and child-level defaults would
3544/// silently drift apart.
3545///
3546/// The `:children :restart` default axis has two production consumers on
3547/// the substrate side today: the [`Default for RestartPolicy`] impl's
3548/// return arm, and the serde-side `#[serde(default)]` on
3549/// [`ChildSpec::restart`] that resolves an author-omitted `:children
3550/// :restart` slot through that same impl. Both now key off this one
3551/// substrate primitive, so the future wasm-operator's per-child post-exit
3552/// restart-decision branch, the future M4
3553/// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
3554/// admission webhook, and the `caixa-operator`'s hierarchical
3555/// reconciliation scheduler's per-child fan-out all reach for one typed
3556/// identifier when they resolve an omitted per-child restart posture.
3557///
3558/// The [`RestartPolicy::Permanent`] value pins Erlang/OTP's `permanent`
3559/// worker-child restart type — always restart the child regardless of how
3560/// it died, the canonical posture for long-running services that must
3561/// always be up, matching the sibling [`SUPERVISOR_ESTRATEGIA_DEFAULT`]
3562/// `one_for_one` tree-of-independent-workers strategy this constant pairs
3563/// with under the same `{one_for_one, intensity, 5, 60}` worker-supervisor
3564/// shape. The two alternatives the closed [`RestartPolicy::ALL`] accept-set
3565/// carries ([`RestartPolicy::Transient`] — restart only on abnormal exit;
3566/// [`RestartPolicy::Temporary`] — never restart) express deliberate
3567/// one-shot / clean-completion-aware postures an author declares
3568/// explicitly, never a posture an omitted slot should silently assume.
3569pub const SUPERVISOR_CHILD_RESTART_DEFAULT: RestartPolicy = RestartPolicy::Permanent;
3570
3571/// Route the manually-authored [`Default`] impl on [`SupervisorSpec`]
3572/// through the substrate-canonical [`SupervisorSpec::otp_canonical`]
3573/// `pub const fn` constructor rather than a struct-literal cascade over
3574/// the paired [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
3575/// [`default_max_restarts`] / [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
3576/// lifted consts — one source of truth for the Erlang/OTP-canonical
3577/// `{one_for_one, 5, 60}` worker-supervisor baseline across the two
3578/// paths every downstream consumer already reaches through (the
3579/// hand-authored-until-now [`Default::default`] the
3580/// `..SupervisorSpec::default()` struct-update-syntax on every
3581/// one-axis-under-test fixture in this crate's test module rests on,
3582/// and the `pub const fn` [`SupervisorSpec::otp_canonical`] constructor
3583/// every `const`-context consumer reaches through).
3584///
3585/// Extends the [`Default`]-through-const-ctor fold discipline the
3586/// [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
3587/// (abd52c2), [`crate::aplicacao::MeshPolicy`]
3588/// [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`] (91641a4),
3589/// and [`crate::BehaviorSpec`]
3590/// [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c) folds
3591/// closed on the M2 / M3 `Option`-only "canonical unset baseline"
3592/// typed-slot spec family — extended here onto the M2 supervisor-slot
3593/// [`SupervisorSpec`] whose canonical baseline is not "everything
3594/// `None`" but the OTP-canonical `{one_for_one, 5, 60}` worker-
3595/// supervisor triple. The `empty()` peer's naming did not fit
3596/// (`SupervisorSpec` carries a discriminator-shaped `estrategia` field
3597/// and a non-zero `max_restarts`/`restart_window` pair whose canonical
3598/// shape is Erlang/OTP-descended, not the "no axis declared" bottom
3599/// the sibling `Option`-only slots fold to), so this peer is named
3600/// [`SupervisorSpec::otp_canonical`] instead — the same phrasing the
3601/// existing per-arm pin tests
3602/// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`] /
3603/// [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`] /
3604/// [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
3605/// already reach for. Pinned load-bearing by
3606/// [`tests::supervisor_spec_default_routes_through_otp_canonical_ctor`]
3607/// (byte-parity pin against [`SupervisorSpec::otp_canonical`] under
3608/// [`PartialEq`], sharpening the sibling
3609/// `supervisor_spec_default_*_routes_through_lifted_default` per-arm
3610/// pins from a per-field lift into a whole-struct one-source-of-truth
3611/// pin — the derived-until-now [`Default::default`] and the
3612/// [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
3613/// construction, not by coincidence).
3614impl Default for SupervisorSpec {
3615 #[inline]
3616 fn default() -> Self {
3617 Self::otp_canonical()
3618 }
3619}
3620
3621impl SupervisorSpec {
3622 /// `const`-context peer of the [`Default for SupervisorSpec`]
3623 /// impl (which routes through this constructor) — returns the
3624 /// Erlang/OTP-canonical `{one_for_one, 5, 60}` worker-supervisor
3625 /// baseline this crate reaches for in every fixture-builder
3626 /// `..SupervisorSpec::default()` struct-update expression and
3627 /// every downstream `SupervisorSpec::default()` seed.
3628 ///
3629 /// Each field routes through the same substrate-canonical
3630 /// [`SUPERVISOR_ESTRATEGIA_DEFAULT`] / [`default_max_restarts`] /
3631 /// [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] lifted consts the
3632 /// per-arm pin tests
3633 /// [`tests::supervisor_estrategia_default_pins_otp_canonical_value`]
3634 /// / [`tests::supervisor_max_restarts_default_pins_otp_canonical_value`]
3635 /// / [`tests::supervisor_restart_window_default_pins_otp_canonical_value`]
3636 /// already assert, so a future coherent rebrand of the OTP-canonical
3637 /// triple (Elixir's `{max_restarts: 3, max_seconds: 5}`, a per-
3638 /// cluster overlay via a future `:restart-window-overrides` slot, a
3639 /// per-child-cohort promotion the INSPIRATIONS.md §II.2 Erlang/OTP
3640 /// absorption roadmap acknowledges) migrates through three typed
3641 /// constants in lockstep, and the paired [`Default`] impl inherits
3642 /// every future extension by construction.
3643 ///
3644 /// `pub const fn` rather than the derived-style `Default::default`
3645 /// or a `pub const SUPERVISOR_SPEC_DEFAULT: SupervisorSpec` item —
3646 /// [`Default::default`] is not `const` on stable Rust, and
3647 /// `SupervisorSpec` is non-`Copy` so a `pub const` item would force
3648 /// every consumer through a [`Clone::clone`]. The `pub const fn`
3649 /// discipline lets `const`-context callers construct the OTP-
3650 /// canonical baseline at compile time without runtime dispatch on
3651 /// the derived [`Default::default`], the same posture the sibling
3652 /// [`crate::LimitsSpec::empty`] (9739971) /
3653 /// [`crate::aplicacao::MeshPolicy::empty`] (6df969b) /
3654 /// [`crate::BehaviorSpec::empty`] (f9b18e3) `Option`-only typed-slot
3655 /// spec `pub const fn` constructors carry on the sibling
3656 /// "everything `None`" baseline axis.
3657 ///
3658 /// Fourth peer on the M2 / M3 typed-slot-spec "const-context peer
3659 /// of the derived-style [`Default`]" family — sibling of the
3660 /// [`crate::LimitsSpec::empty`] / [`crate::aplicacao::MeshPolicy::empty`]
3661 /// / [`crate::BehaviorSpec::empty`] `Option`-only "canonical unset
3662 /// baseline" trio, extended here onto the M2 supervisor-slot
3663 /// [`SupervisorSpec`] whose canonical baseline is not "everything
3664 /// `None`" but the Erlang/OTP-canonical `{one_for_one, 5, 60}`
3665 /// worker-supervisor triple. Named [`Self::otp_canonical`] rather
3666 /// than `empty()` to name the actual invariant the return value
3667 /// pins — the same phrasing already used in the per-arm pin tests
3668 /// on this file. Pinned load-bearing by
3669 /// [`tests::supervisor_spec_otp_canonical_byte_equals_default`] and
3670 /// [`tests::supervisor_spec_otp_canonical_is_usable_in_const_context`].
3671 #[must_use]
3672 pub const fn otp_canonical() -> Self {
3673 Self {
3674 estrategia: SUPERVISOR_ESTRATEGIA_DEFAULT,
3675 max_restarts: default_max_restarts(),
3676 restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
3677 children: Vec::new(),
3678 }
3679 }
3680
3681 /// Substrate-canonical per-`:supervisor` `:estrategia` OTP-shaped
3682 /// sibling-restart-strategy scalar accessor every consumer that
3683 /// dispatches on the supervisor's per-sibling restart-decision shape
3684 /// keys off — returns the author-declared `:supervisor :estrategia`
3685 /// variant verbatim as a [`RestartStrategy`], `Copy`-projected from
3686 /// the typed slot's own [`RestartStrategy`] storage.
3687 ///
3688 /// The `:supervisor :estrategia` slot carries the closed-set
3689 /// OTP-shaped sibling-restart-strategy discriminator ([`RestartStrategy::OneForOne`]
3690 /// — restart only the failed child, the Erlang/OTP `one_for_one` default;
3691 /// [`RestartStrategy::OneForAll`] — restart every child on any child
3692 /// failure, the Erlang/OTP `one_for_all` shared-state cohort default;
3693 /// [`RestartStrategy::RestForOne`] — restart the failed child and
3694 /// every child started after it, the Erlang/OTP `rest_for_one`
3695 /// startup-order default; [`RestartStrategy::SimpleOneForOne`] —
3696 /// dynamic children of the same shape, the Erlang/OTP
3697 /// `simple_one_for_one` per-session default) that every downstream
3698 /// consumer of the Supervisor's per-sibling restart-decision fan-out
3699 /// shape keys off. Validated by [`SupervisorSpec::validate`] to be
3700 /// paired coherently with the sibling `:children` axis
3701 /// (`SimpleOneForOne ↔ children.is_empty()` — the cross-slot
3702 /// partition the strategy-arm's [`SupervisorError::SimpleOneForOneWithStaticChildren`]
3703 /// / [`SupervisorError::NoChildren`] refusal cascade pins), and every
3704 /// downstream consumer that reads the strategy keys off this scalar
3705 /// (the [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
3706 /// partition-dispatch `match` arm, the non-`SimpleOneForOne`-arm
3707 /// declared-but-empty [`SupervisorError::NoChildren`] error carrier's
3708 /// `estrategia:` field, the future `feira app graph` per-Supervisor
3709 /// strategy print line, the future wasm-operator's per-supervisor
3710 /// sibling-restart-strategy branch, the future M4
3711 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-strategy
3712 /// admission-webhook resolver, the `caixa-operator`'s hierarchical
3713 /// reconciliation scheduler's per-strategy fan-out).
3714 ///
3715 /// Prior to this lift the `.estrategia` field was accessed inline at
3716 /// two production sites in `caixa-core/src/supervisor.rs` — the
3717 /// [`SupervisorSpec::validate`] `SimpleOneForOne ↔ non-SimpleOneForOne`
3718 /// `match self.estrategia { … }` partition dispatch, and the
3719 /// non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
3720 /// carrier at `estrategia: self.estrategia` — two open-coded
3721 /// field-accesses that expressed no compile-time link back to the
3722 /// typed slot. A future extension of the `:supervisor :estrategia`
3723 /// axis to a richer author surface (a per-cluster strategy override
3724 /// the operator pins through a future `:supervisor :estrategia-overrides`
3725 /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
3726 /// acknowledges, a per-tenant strategy-alias table the M4 CR
3727 /// materializer resolves per-CR, a per-Supervisor dynamic strategy
3728 /// derivation the future adaptive-supervision engine computes from
3729 /// child-failure-history topology, a per-child-cohort strategy split
3730 /// the future `RestForCohort` extension acknowledged by the
3731 /// INSPIRATIONS.md §II.2 Erlang/OTP absorption roadmap acknowledges)
3732 /// would have had to be threaded through every open-coded copy in
3733 /// lockstep — one consumer reading the raw variant while a peer read
3734 /// the operator-resolved variant would silently split the
3735 /// [`SupervisorError::NoChildren`] diagnostic's quoted strategy from
3736 /// the actual partition-dispatch input the empty-children refusal
3737 /// arm reached under, a two-consumer split at the validator far from
3738 /// the source `caixa.lisp` with no field naming the strategy-drift
3739 /// root cause. Lifting the resolution rule to a typed method on the
3740 /// substrate primitive means every downstream consumer of the
3741 /// Supervisor's per-`:supervisor` sibling-restart-strategy surface
3742 /// reaches for exactly one typed dispatch — the resolver's accept-set
3743 /// migrates as a unit on any future axis addition.
3744 ///
3745 /// Peer of the sibling M3 mesh-slot [`crate::Placement::estrategia`]
3746 /// (921fe1b) `Copy`-return `PlacementStrategy` scalar accessor on the
3747 /// per-`:placement` distribution-strategy axis — same "one typed
3748 /// dispatch on the substrate primitive, thin projections at each
3749 /// consumer" discipline extended onto the M2 supervisor-slot
3750 /// per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
3751 /// scalar axis. The two typed axes (`Placement::estrategia` on the
3752 /// M3 Aplicacao side, `SupervisorSpec::estrategia` on the M2
3753 /// Supervisor side) now share one accessor discipline for the shared
3754 /// substrate concept "a `Copy`-projected closed-set enum-arm
3755 /// discriminator that partitions the downstream renderer's per-arm
3756 /// fan-out". First `Copy`-return accessor on the M2 supervisor-slot
3757 /// `SupervisorSpec` type — companion to the sibling per-`:children`
3758 /// [`crate::ChildSpec::nome`] (57c61d0) /
3759 /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
3760 /// scalar accessors on the sibling per-`:children` `String`-carry
3761 /// axes. Named `estrategia()` to match the storage field's name and
3762 /// the peer [`crate::Placement::estrategia`] method-name discipline
3763 /// verbatim; the accessor's identity name maps onto the canonical
3764 /// OTP-shape supervision vocabulary the [`RestartStrategy`] enum's
3765 /// docstring already carries.
3766 ///
3767 /// Declared `pub const fn` to close the M2 supervisor-slot
3768 /// `Copy`-return raw-field-getter `const`-eval-surface pass —
3769 /// sibling of the peer M2 per-`:children` [`ChildSpec::restart`]
3770 /// (converted in this commit) `Copy`-composite-enum accessor, peer
3771 /// of the sibling M2 per-`:supervisor`
3772 /// [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32` accessor
3773 /// already lifted, and mirror of the peer M3 mesh-slot
3774 /// per-`:placement` [`crate::Placement::estrategia`] (bafa004)
3775 /// `Copy`-return `pub const fn` scalar accessor whose method-name
3776 /// discipline this accessor was authored to match. Every downstream
3777 /// substrate-side `const`-context consumer of the per-`:supervisor`
3778 /// sibling-restart-strategy scalar (a future module-scope `const
3779 /// _:() = assert!(matches!(sup.estrategia(),
3780 /// RestartStrategy::OneForOne))` invariant pin on a typed fixture,
3781 /// a future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer
3782 /// admission-webhook `const fn` per-supervisor strategy-arm floor
3783 /// over a typed [`SupervisorSpec`], any future `const fn`
3784 /// supervisor-tree composer over the substrate primitive that fans
3785 /// on the sibling-restart-strategy at compile time) now reaches
3786 /// through the same typed dispatch on the substrate primitive at
3787 /// const-eval time as at runtime. A future non-`Copy`-return
3788 /// promotion of the scalar (an `Option<RestartStrategy>`-shape
3789 /// migration once the substrate grows per-cluster strategy overlays
3790 /// the [`SupervisorSpec`] docstring already anticipates, a
3791 /// per-tenant strategy-alias table the M4 CR materializer resolves
3792 /// per-CR) that would drop the `const` qualifier fails the
3793 /// fail-before-pass-after pin
3794 /// [`tests::supervisor_spec_estrategia_accessor_is_const_fn`] at
3795 /// caixa-core build time rather than surfacing as a downstream
3796 /// consumer regression.
3797 #[must_use]
3798 pub const fn estrategia(&self) -> RestartStrategy {
3799 self.estrategia
3800 }
3801
3802 /// Substrate-canonical per-`:supervisor` `:max-restarts` OTP-shaped
3803 /// `MaxIntensity` restart-budget scalar accessor every consumer that
3804 /// reads the supervisor's per-`:restart-window` restart-budget count
3805 /// keys off — returns the author-declared `:supervisor :max-restarts`
3806 /// typed `u32` verbatim, `Copy`-projected from the typed slot's own
3807 /// `u32` storage (`u32` is `Copy`, so the accessor returns by value; no
3808 /// borrow of `&self` past the call). Non-optional (the `u32` field
3809 /// carries the restart-budget count as a required axis with a
3810 /// [`default_max_restarts`]-supplied default; the zero-floor arm
3811 /// [`SupervisorError::ZeroMaxRestarts`] and the cap arm
3812 /// [`SupervisorError::MaxRestartsExceedsCap`] jointly bracket the
3813 /// accept-set to `1..=SUPERVISOR_MAX_RESTARTS_MAX`).
3814 ///
3815 /// The `:supervisor :max-restarts` slot carries the Erlang/OTP
3816 /// `MaxIntensity` restart-budget count that pairs with the sibling
3817 /// `:restart-window` `Period` to form the `MaxIntensity / Period`
3818 /// restart-intensity ratio the supervisor trips its own escalation on
3819 /// (`theory/RUNTIME-PATTERNS.md` §II.2, Learn You Some Erlang's
3820 /// `{intensity, 5, 60}` worker-supervisor default). Every downstream
3821 /// consumer of the Supervisor's per-`:supervisor` restart-budget count
3822 /// keys off this scalar (the [`SupervisorSpec::validate`] zero-floor +
3823 /// upper-cap bracket at
3824 /// `require_positive_bounded_u32(self.max_restarts(), …)`, the future
3825 /// wasm-operator's per-supervisor restart-intensity counter's
3826 /// budget-vs-count comparator, the future M4
3827 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
3828 /// webhook, the `caixa-operator`'s hierarchical reconciliation
3829 /// scheduler's per-supervisor escalation-decision branch, every
3830 /// `SupervisorError::MaxRestartsExceedsCap` variant carrying the
3831 /// offending count verbatim for `feira lint` rendering).
3832 ///
3833 /// Prior to this lift the `.max_restarts` field was accessed inline at
3834 /// one production site in `caixa-core/src/supervisor.rs` — the
3835 /// [`SupervisorSpec::validate`] `require_positive_bounded_u32(self
3836 /// .max_restarts, …)` bracket-gate call — one open-coded field-access
3837 /// that expressed no compile-time link back to the typed slot. A
3838 /// future extension of the `:max-restarts` axis to a richer author
3839 /// surface (a per-cluster restart-budget override the operator pins
3840 /// through a future `:supervisor :max-restarts-overrides` slot the
3841 /// MESH-COMPOSITION §III.2 supervision-canary roadmap acknowledges,
3842 /// a per-tenant restart-budget-alias table the M4 CR materializer
3843 /// resolves per-CR, a per-supervisor dynamic restart-budget derivation
3844 /// the future adaptive-supervision engine computes from child-failure-
3845 /// history topology, a promotion of the plain `u32` count to a richer
3846 /// `{MaxR, MaxT}` tuple once Erlang/OTP's per-child-cohort restart-
3847 /// budget-partition slot comes into scope) would have had to be
3848 /// threaded through every open-coded copy in lockstep or the validate
3849 /// gate and the future M4 emit path would silently disagree on which
3850 /// restart-budget count a given supervisor resolves to — an author's
3851 /// `:max-restarts 5` would satisfy validate while the emit path
3852 /// silently read a drifted other value (a `:max-restarts 10000`
3853 /// no-op supervisor at the emit boundary would carry the author's
3854 /// declared `5` verbatim in `feira lint` output while the future
3855 /// wasm-operator's restart-intensity counter operated under the
3856 /// drifted count), a two-consumer split at the validator far from the
3857 /// source `caixa.lisp` with no field naming the restart-budget-drift
3858 /// root cause. Lifting the resolution rule to a typed method on the
3859 /// substrate primitive means every downstream consumer of the
3860 /// Supervisor's per-`:supervisor` restart-budget-count surface reaches
3861 /// for exactly one typed dispatch — the resolver's accept-set migrates
3862 /// as a unit on any future axis addition.
3863 ///
3864 /// Peer of the sibling M3 mesh-slot [`crate::CircuitBreaker::max_failures`]
3865 /// (3a74062) `Copy`-return `u32` sub-struct required-scalar accessor
3866 /// on the per-`:politicas :circuit-breaker :max-failures` Envoy-
3867 /// outlier-detection trip-threshold axis — same "one typed dispatch on
3868 /// the substrate primitive, thin projections at each consumer"
3869 /// discipline extended onto the M2 supervisor-slot per-`:supervisor`
3870 /// restart-budget-count `Copy`-`u32` scalar axis. The two typed axes
3871 /// (`CircuitBreaker::max_failures` on the M3 Aplicacao side,
3872 /// `SupervisorSpec::max_restarts` on the M2 Supervisor side) now share
3873 /// one accessor discipline for the shared substrate concept "a
3874 /// `Copy`-projected required `u32` count that trips the next-higher
3875 /// protection layer after N events in a rolling window" — both are
3876 /// counters with identical degenerate-at-the-high-end shape and share
3877 /// the paired [`crate::POLICY_BREAKER_MAX_FAILURES_MAX`] /
3878 /// [`SUPERVISOR_MAX_RESTARTS_MAX`] `1000` cap. Second `Copy`-return
3879 /// accessor on the M2 supervisor-slot `SupervisorSpec` type, sibling
3880 /// to the [`SupervisorSpec::estrategia`] (eafb619) `Copy`-composite-
3881 /// enum `RestartStrategy` accessor. Named `max_restarts()` to match
3882 /// the storage field's name verbatim and the peer
3883 /// [`crate::CircuitBreaker::max_failures`] method-name discipline; the
3884 /// accessor's identity maps onto the canonical OTP-shape supervision
3885 /// vocabulary the [`SupervisorSpec::max_restarts`] field's docstring
3886 /// already carries.
3887 #[must_use]
3888 pub const fn max_restarts(&self) -> u32 {
3889 self.max_restarts
3890 }
3891
3892 /// Substrate-canonical per-`:supervisor` `:restart-window` OTP-shaped
3893 /// `Period` sliding-window scalar accessor every consumer of the
3894 /// supervisor's `MaxIntensity / Period` restart-intensity denominator
3895 /// keys off — returns the author-declared `:supervisor :restart-window`
3896 /// typed [`Duration`] verbatim as an `Option<Duration>`, copied out of
3897 /// the typed slot's own `Option<Duration>` storage (`Duration` is
3898 /// `Copy`, so `Option<Duration>` is `Copy` and the accessor returns by
3899 /// value; no borrow of `&self` past the call). `None` when the slot is
3900 /// absent (the canonical "never reset — every restart across the
3901 /// supervisor's lifetime counts against the sibling `:max-restarts`
3902 /// budget" sentinel the field's own docstring names and the peer
3903 /// `validate_accepts_none_restart_window` pin locks in on the
3904 /// [`SupervisorSpec::validate`] entry-side).
3905 ///
3906 /// The `:supervisor :restart-window` slot carries the Erlang/OTP
3907 /// `Period` sliding-observation-interval that pairs with the sibling
3908 /// `:max-restarts` `MaxIntensity` restart-budget count to form the
3909 /// `MaxIntensity / Period` restart-intensity ratio the supervisor
3910 /// trips its own escalation on (`theory/RUNTIME-PATTERNS.md` §II.2,
3911 /// Learn You Some Erlang's `{intensity, 5, 60}` worker-supervisor
3912 /// default). The typed slot's `Option<Duration>` accept-set —
3913 /// zero-floor rejected through [`SupervisorError::RestartWindowZero`]
3914 /// (Erlang/OTP's `MaxIntensity / Period` invariant requires
3915 /// `Period > 0`; a zero period either trips on the first failure or
3916 /// never trips depending on operator interpretation, neither of which
3917 /// is the author's intent — omit the slot to express "no reset";
3918 /// carry a positive duration to express the sliding window),
3919 /// integer-millisecond canonical form enforced through
3920 /// [`SupervisorError::RestartWindowNotCanonical`] (the duration
3921 /// codec's canonical form emits `"1500ms"` not `"1.5s"` and the
3922 /// future wasm-operator's per-supervisor restart-intensity counter
3923 /// quantizes at milliseconds), upper-bounded by
3924 /// [`SUPERVISOR_RESTART_WINDOW_MAX`] (1h — the coarsest per-
3925 /// supervisor rolling window any operationally-reachable supervisor
3926 /// can honor without spanning multiple scheduler epochs the
3927 /// hierarchical-reconciliation scheduler treats as independent) —
3928 /// maps onto the future wasm-operator (M3) per-supervisor
3929 /// restart-intensity counter's rolling-observation-interval, the
3930 /// future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
3931 /// per-`spec.restartWindow` admission webhook, and the sibling
3932 /// `duration_codec`-serialized wire scalar every downstream consumer
3933 /// of the supervisor's per-`:supervisor` restart-intensity denominator
3934 /// keys off.
3935 ///
3936 /// Prior to this lift the `.restart_window` field was accessed inline
3937 /// at one production site in `caixa-core/src/supervisor.rs` — the
3938 /// [`SupervisorSpec::validate`] `if let Some(w) = self.restart_window {
3939 /// … }` zero-floor + canonical-form + upper-cap bracket arm — one
3940 /// open-coded field-access that expressed no compile-time link back to
3941 /// the typed slot. A future extension of the `:restart-window` axis to
3942 /// a richer author surface (a per-cluster restart-window override the
3943 /// operator pins through a future `:supervisor :restart-window-overrides`
3944 /// slot the MESH-COMPOSITION §III.2 supervision-canary roadmap
3945 /// acknowledges, a per-tenant restart-window-alias table the M4 CR
3946 /// materializer resolves per-CR, a per-supervisor dynamic
3947 /// restart-window derivation the future adaptive-supervision engine
3948 /// computes from child-failure-history topology, a promotion of the
3949 /// plain `Option<Duration>` window to a richer `{observation, cooldown}`
3950 /// pair once Erlang/OTP's per-child-cohort observation-interval-
3951 /// partition slot comes into scope) would have had to be threaded
3952 /// through every open-coded copy in lockstep or the validate gate and
3953 /// the future M4 emit path would silently disagree on which
3954 /// restart-window a given supervisor resolves to — an author's
3955 /// `:restart-window "60s"` would satisfy validate while the emit path
3956 /// silently read a drifted other value (a `Some(Duration::from_secs(60))`
3957 /// authored slot at the emit boundary would carry the author's
3958 /// declared window verbatim in `feira lint` output while the future
3959 /// wasm-operator's restart-intensity counter operated under a
3960 /// drifted window, or vice versa: an author's `:restart-window ()`
3961 /// would carry the "never reset" sentinel through validate while the
3962 /// emit path silently substituted a default sliding window), a
3963 /// two-consumer split at the validator far from the source
3964 /// `caixa.lisp` with no field naming the restart-window-drift root
3965 /// cause. Lifting the resolution rule to a typed method on the
3966 /// substrate primitive means every downstream consumer of the
3967 /// Supervisor's per-`:supervisor` restart-intensity-denominator
3968 /// surface reaches for exactly one typed dispatch — the resolver's
3969 /// accept-set migrates as a unit on any future axis addition.
3970 ///
3971 /// Third `Copy`-return accessor on the M2 supervisor-slot
3972 /// `SupervisorSpec` type, closing the last unlifted per-`:supervisor`
3973 /// scalar-value axis (`children: Vec<ChildSpec>` carries a `Vec`
3974 /// payload rather than a `Copy`-scalar, and the per-`:children`
3975 /// [`crate::ChildSpec::nome`] (57c61d0) /
3976 /// [`crate::ChildSpec::versao_requirement`] (2c053c8) child-caixa
3977 /// scalar accessors already close the per-element `String`-carry
3978 /// axes). Sibling to the peer M2 [`crate::LimitsSpec::wall_clock`]
3979 /// (8cb717b) `Option<Duration>` accessor on the `:limits` slot's
3980 /// per-outermost-call wall-clock-deadline axis and the peer M3
3981 /// [`crate::MeshPolicy::timeout`] (7073d0f) `Option<Duration>`
3982 /// accessor on the `:politicas` slot's per-call-deadline axis — all
3983 /// three share the shared substrate concept "a `Copy`-projected
3984 /// optional `Duration` that carries a positive integer-millisecond
3985 /// canonical value with a `1ms..=<axis-specific>_MAX` accept-set and
3986 /// the paired zero-floor / non-canonical / above-cap refusal cascade"
3987 /// through the same [`crate::render::require_positive_canonical_bounded_duration`]
3988 /// bracket-helper the three axes each route through. Named
3989 /// `restart_window()` to match the storage field's name verbatim and
3990 /// the peer [`crate::LimitsSpec::wall_clock`] /
3991 /// [`crate::MeshPolicy::timeout`] method-name discipline; the
3992 /// accessor's identity maps onto the canonical OTP-shape supervision
3993 /// vocabulary the [`SupervisorSpec::restart_window`] field's docstring
3994 /// already carries.
3995 #[must_use]
3996 pub const fn restart_window(&self) -> Option<Duration> {
3997 self.restart_window
3998 }
3999
4000 /// Substrate-canonical per-`:supervisor` `:children` OTP-shaped
4001 /// static-child-list slice accessor every consumer that walks the
4002 /// supervisor's declared child set keys off — returns the author-
4003 /// declared `:supervisor :children` `Vec<ChildSpec>` verbatim as a
4004 /// `&[ChildSpec]` slice-view, borrowed from the typed slot's own
4005 /// `Vec<ChildSpec>` storage (a zero-copy slice-view over the same
4006 /// backing buffer the `Serialize`/`Deserialize` derives round-trip
4007 /// through). Non-optional: an empty slice is the load-bearing
4008 /// "author declared `:children ()`" sentinel every consumer of the
4009 /// cross-slot `SimpleOneForOne ↔ children.is_empty()` partition
4010 /// keys off (`SimpleOneForOne` requires the empty slice; the peer
4011 /// three strategies require a non-empty slice — the paired
4012 /// [`SupervisorError::SimpleOneForOneWithStaticChildren`] /
4013 /// [`SupervisorError::NoChildren`] refusal cascade pins the
4014 /// partition on both arms).
4015 ///
4016 /// The `:supervisor :children` slot carries the OTP-shaped static
4017 /// child list the supervisor materializes one ComputeUnit per
4018 /// entry from — the Erlang/OTP `supervisor:init/1`'s
4019 /// `{ok, {SupFlags, ChildSpecs}}` `ChildSpecs` list, projected
4020 /// through the tatara-lisp `:children` author surface onto a typed
4021 /// `Vec<ChildSpec>` whose per-element `(nome(),
4022 /// versao_requirement(), restart)` triple the per-child
4023 /// [`SupervisorSpec::validate`] loop already gates through the
4024 /// lifted [`ChildSpec::nome`] (57c61d0) /
4025 /// [`ChildSpec::versao_requirement`] (2c053c8) scalar accessors.
4026 /// Every downstream consumer that fans on the static child list
4027 /// keys off this slice (the [`SupervisorSpec::validate`]
4028 /// `SimpleOneForOne ↔ non-SimpleOneForOne` partition dispatch's
4029 /// `.is_empty()` probe on both arms, the [`SupervisorSpec::validate`]
4030 /// per-child DNS-1123 / semver-requirement / duplicate-detection
4031 /// fan-out loop, every future wasm-operator (M3) per-supervisor
4032 /// hierarchical-reconciliation scheduler's per-child ComputeUnit
4033 /// materialization loop, the future M4
4034 /// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's per-child
4035 /// admission-webhook fan-out, the future `feira app graph`
4036 /// per-supervisor tree-print traversal).
4037 ///
4038 /// Prior to this lift the `.children` `Vec<ChildSpec>` was accessed
4039 /// inline at three production sites in `caixa-core/src/supervisor.rs`
4040 /// — the [`SupervisorSpec::validate`] `SimpleOneForOne`-arm
4041 /// `!self.children.is_empty()` cross-slot refusal probe, the peer
4042 /// non-`SimpleOneForOne`-arm `self.children.is_empty()`
4043 /// [`SupervisorError::NoChildren`] refusal probe, and the per-child
4044 /// validate loop's `for child in &self.children` traversal head —
4045 /// three open-coded field-accesses that expressed no compile-time
4046 /// link back to the typed slot. A future extension of the
4047 /// `:supervisor :children` axis to a richer author surface (a
4048 /// per-cluster child-set overlay the operator pins through a future
4049 /// `:supervisor :children-overrides` slot the MESH-COMPOSITION §III.2
4050 /// supervision-canary roadmap acknowledges, a per-tenant
4051 /// child-set-alias table the M4 CR materializer resolves per-CR,
4052 /// a per-supervisor dynamic-child derivation the future adaptive-
4053 /// supervision engine computes from child-failure-history topology,
4054 /// a promotion of the plain `Vec<ChildSpec>` to a richer
4055 /// `{static, dynamic}` partition once Erlang/OTP's
4056 /// `simple_one_for_one` dynamic-child slot comes into typed scope)
4057 /// would have had to be threaded through all three open-coded copies
4058 /// in lockstep or one consumer would silently disagree with the
4059 /// peers on which child-set a given supervisor resolves to — the
4060 /// `SimpleOneForOne`-arm probe reading the raw slot while the peer
4061 /// non-`SimpleOneForOne`-arm probe read an operator-resolved slot
4062 /// would silently split the partition-dispatch's two-arm coherence
4063 /// (a supervisor that satisfies neither arm's precondition, or that
4064 /// satisfies both, at the cost of the paired
4065 /// `SimpleOneForOneWithStaticChildren`/`NoChildren` refusal cascade
4066 /// silently drifting from the per-child validate loop's actual
4067 /// traversal input), a three-consumer split at the validator far
4068 /// from the source `caixa.lisp` with no field naming the
4069 /// child-set-drift root cause. Lifting the resolution rule to a
4070 /// typed method on the substrate primitive means every downstream
4071 /// consumer of the Supervisor's per-`:supervisor` static-child-list
4072 /// surface reaches for exactly one typed dispatch — the resolver's
4073 /// accept-set migrates as a unit on any future axis addition.
4074 ///
4075 /// First slice-return (`&[T]`) accessor on any M2 or M3 typed slot
4076 /// — the seed for the same "one typed dispatch on the substrate
4077 /// primitive, thin projections at each consumer" discipline the
4078 /// closed [`crate::LimitsSpec`] / [`BehaviorSpec`] /
4079 /// [`crate::UpgradeFromEntry`] scalar-accessor families each carry
4080 /// on their `Copy` / `Option<Copy>` / `Option<&str>` axes, extended
4081 /// onto the first `Vec`-carry axis on the substrate. The four peer
4082 /// `Vec`-carry axes still unlifted at the time of this seed —
4083 /// [`crate::Placement::clusters`] (`Vec<String>` per-cluster
4084 /// distribution-target list), [`crate::AplicacaoSpec::membros`]
4085 /// (`Vec<Membro>` per-Aplicacao member list),
4086 /// [`crate::AplicacaoSpec::contratos`] (`Vec<WitContract>`
4087 /// per-Aplicacao WIT-typed edge list),
4088 /// [`crate::UpgradeFromEntry::instructions`]
4089 /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
4090 /// — inherit this accessor's discipline as future compounding runs
4091 /// migrate their consumers onto the shared slice-return shape.
4092 /// Fourth (and final) accessor on the M2 supervisor-slot
4093 /// `SupervisorSpec` type, sibling to the three `Copy`-return
4094 /// [`SupervisorSpec::estrategia`] (eafb619) /
4095 /// [`SupervisorSpec::max_restarts`] (7844f4e) /
4096 /// [`SupervisorSpec::restart_window`] (7e7b32f) accessors — closes
4097 /// the last unlifted per-`:supervisor` field axis (the
4098 /// `Vec<ChildSpec>` static-child-list carrier) so every downstream
4099 /// per-`:supervisor` reader now routes through a typed dispatch on
4100 /// the substrate primitive. Named `children()` to match the storage
4101 /// field's name verbatim and the tatara-lisp author-surface term
4102 /// (`:children`) the field's own docstring already carries; the
4103 /// accessor's identity maps onto the canonical OTP-shape
4104 /// supervision vocabulary the [`SupervisorSpec::children`] field's
4105 /// docstring already reaches for ("Static children ..."). Returns
4106 /// `&[ChildSpec]` (not `&Vec<ChildSpec>`) because every downstream
4107 /// consumer of the child list treats it as a read-only sequence —
4108 /// the slice-view is the narrowest borrow that supports every
4109 /// present + roadmapped consumer (`.is_empty()`, `.iter()`,
4110 /// index, `.len()`) without leaking the backing `Vec`'s
4111 /// grow/push/reserve surface that no consumer of the typed view
4112 /// reaches for (the storage-side `Vec` remains reachable through
4113 /// the `pub children` field for the mutation-carrying
4114 /// `Caixa::supervisor_view` fold-in path in
4115 /// `manifest.rs:supervisor_view`).
4116 #[must_use]
4117 pub const fn children(&self) -> &[ChildSpec] {
4118 self.children.as_slice()
4119 }
4120
4121 /// Validate the supervisor's typed shape — strategy ↔ children
4122 /// invariants, max_restarts > 0, restart_window > 0 when set,
4123 /// per-child non-empty + duplicate-free names.
4124 ///
4125 /// Mirrors the value-shape discipline applied to every other
4126 /// typed slot:
4127 ///
4128 /// - `Some(Duration::ZERO)` on a Duration-bearing axis is the
4129 /// same "0 means the opposite of what you think" footgun
4130 /// closed for `:politicas :timeout` (Envoy interprets a zero
4131 /// timeout as `infinite`), `:politicas :circuit-breaker
4132 /// :window`, and `:limits :wall-clock`. The
4133 /// `MaxIntensity / Period` ratio in Erlang/OTP's
4134 /// `supervisor` requires `Period > 0`; a zero period either
4135 /// trips on the first failure or never trips depending on
4136 /// operator interpretation, neither of which is the
4137 /// author's intent. Omit `:restart-window` to express "no
4138 /// reset"; carry a positive duration to express the window.
4139 /// - duplicate `:children` `:caixa` names are the same
4140 /// graph-node-set / multiset distinction closed for
4141 /// `:membros` (4bb3f3d), `:placement :clusters` (c7c7799),
4142 /// and `:entrada :paths` (eb3456d). Two children with the
4143 /// same `:caixa` materialize as two ComputeUnits with the
4144 /// same name in the cluster's HelmRelease values, one
4145 /// silently overwriting the other. Erlang/OTP's
4146 /// `child_spec.id` is required-unique per supervisor;
4147 /// pleme-io enforces the same set-not-multiset shape on
4148 /// `:caixa` (the load-bearing identity in our renderer).
4149 pub fn validate(&self) -> Result<(), SupervisorError> {
4150 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition
4151 // dispatch and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
4152 // error carrier's `estrategia:` field through the lifted
4153 // [`SupervisorSpec::estrategia`] accessor rather than the raw
4154 // `self.estrategia` field access — the two production consumers
4155 // of the per-`:supervisor` sibling-restart-strategy scalar now
4156 // key off exactly one typed dispatch on the substrate primitive,
4157 // so any future rebrand on the axis (a per-cluster strategy
4158 // override the operator pins through a future `:supervisor
4159 // :estrategia-overrides` slot, a per-tenant strategy-alias table
4160 // the M4 CR materializer resolves per-CR) migrates as a single
4161 // caixa-core edit rather than a coordinated rewrite of the two
4162 // call sites — sibling of the peer M3 [`crate::Placement::estrategia`]
4163 // (921fe1b) four-consumer migration on the per-`:placement`
4164 // distribution-strategy axis.
4165 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` partition-
4166 // dispatch's paired `.is_empty()` cross-slot refusal probes
4167 // (the `SimpleOneForOne`-arm
4168 // [`SupervisorError::SimpleOneForOneWithStaticChildren`] refusal
4169 // and the non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
4170 // refusal) through the lifted [`SupervisorSpec::children`]
4171 // slice-return accessor rather than the raw `self.children`
4172 // field access — the two paired production consumers of the
4173 // per-`:supervisor` static-child-list scalar-shape now key off
4174 // exactly one typed dispatch on the substrate primitive, so any
4175 // future rebrand on the axis (a per-cluster child-set overlay
4176 // the operator pins through a future `:supervisor
4177 // :children-overrides` slot, a per-tenant child-set-alias table
4178 // the M4 CR materializer resolves per-CR) migrates as a single
4179 // caixa-core edit rather than a coordinated rewrite of the
4180 // paired arms — first slice-return migration on any typed slot,
4181 // seed for the peer per-`:placement :clusters`,
4182 // per-`:membros`, per-`:contratos`, and per-`:upgrade-from
4183 // :instructions` `Vec`-carry axes.
4184 match self.estrategia() {
4185 RestartStrategy::SimpleOneForOne => {
4186 // SimpleOneForOne: children added at runtime. Static
4187 // list must be empty (one shape declared elsewhere).
4188 if !self.children().is_empty() {
4189 return Err(SupervisorError::SimpleOneForOneWithStaticChildren);
4190 }
4191 }
4192 _ => {
4193 if self.children().is_empty() {
4194 return Err(SupervisorError::no_children(self.estrategia()));
4195 }
4196 }
4197 }
4198 // Zero-floor + upper-cap bracket on the typed `:max-restarts`
4199 // axis. See [`crate::render::require_positive_bounded_u32`] for
4200 // the ordering discipline (zero-floor arm strictly precedes cap
4201 // arm so `0` surfaces the self-locating `ZeroMaxRestarts`
4202 // diagnostic with its counter-axis remediation directly named,
4203 // not the misleading `0 > SUPERVISOR_MAX_RESTARTS_MAX == false`
4204 // cap-arm miss). Until this bracket landed the top edge ran all
4205 // the way to `u32::MAX` and a struct-literal
4206 // `SupervisorSpec { max_restarts: 100_000, .. }` (or the
4207 // equivalent author-surface `:max-restarts 100000` /
4208 // `:max-restarts 4294967295` typo landing in the slot) silently
4209 // passed validate. The runtime substrate consuming the value
4210 // (Erlang/OTP's `MaxIntensity / Period` ratio, the future
4211 // wasm-operator's per-supervisor restart-intensity counter, the
4212 // M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
4213 // admission webhook) then turned a typed `:max-restarts`
4214 // policy into a no-op supervisor: the escalation threshold is
4215 // structurally so high that no realistic
4216 // restarts-per-`:restart-window` traffic shape can reach it,
4217 // the supervisor never escalates to its parent, and a bad
4218 // child can loop inside the window indefinitely with the
4219 // parent supervisor structurally never receiving the "this
4220 // subtree has exceeded its restart budget" signal the typed
4221 // slot is meant to express. The bracket set is
4222 // `1..=SUPERVISOR_MAX_RESTARTS_MAX`, peer with the
4223 // [`crate::aplicacao::POLICY_BREAKER_MAX_FAILURES_MAX`] cap on
4224 // the sibling `:politicas :circuit-breaker :max-failures` axis:
4225 // both are "trip the next-higher protection layer after N
4226 // events in a rolling window" counters with identical
4227 // degenerate-at-the-high-end shape and now share one canonical
4228 // bracket helper. The bracket precedes the sibling
4229 // `:restart-window` zero-floor / canonical-millisecond arms so
4230 // an over-cap `max_restarts` paired with a structurally invalid
4231 // window surfaces the bracket diagnostic first, mirroring the
4232 // `PolicyBreakerMaxFailuresExceedsCap` / window-axis cross-arm
4233 // ordering on the peer `:politicas :circuit-breaker` slot.
4234 // Route the [`SupervisorSpec::validate`] `:max-restarts` zero-floor +
4235 // upper-cap bracket-gate through the lifted [`SupervisorSpec::max_restarts`]
4236 // accessor rather than the raw `self.max_restarts` field access —
4237 // the one production consumer of the per-`:supervisor`
4238 // restart-budget-count scalar now keys off exactly one typed
4239 // dispatch on the substrate primitive, so any future rebrand on
4240 // the axis (a per-cluster restart-budget override the operator
4241 // pins through a future `:supervisor :max-restarts-overrides`
4242 // slot, a per-tenant restart-budget-alias table the M4 CR
4243 // materializer resolves per-CR) migrates as a single caixa-core
4244 // edit rather than a coordinated rewrite — sibling of the peer M3
4245 // [`crate::CircuitBreaker::max_failures`] (3a74062) migration on
4246 // the per-`:politicas :circuit-breaker :max-failures` axis.
4247 crate::render::require_positive_bounded_u32(
4248 self.max_restarts(),
4249 SUPERVISOR_MAX_RESTARTS_MAX,
4250 || SupervisorError::ZeroMaxRestarts,
4251 SupervisorError::max_restarts_exceeds_cap,
4252 )?;
4253 // Route the [`SupervisorSpec::validate`] `:restart-window`
4254 // zero-floor + integer-millisecond canonical-form + upper-cap
4255 // bracket-gate through the lifted [`SupervisorSpec::restart_window`]
4256 // accessor rather than the raw `self.restart_window` field access —
4257 // the one production consumer of the per-`:supervisor`
4258 // restart-intensity-denominator scalar now keys off exactly one
4259 // typed dispatch on the substrate primitive, so any future rebrand
4260 // on the axis (a per-cluster restart-window override the operator
4261 // pins through a future `:supervisor :restart-window-overrides`
4262 // slot, a per-tenant restart-window-alias table the M4 CR
4263 // materializer resolves per-CR) migrates as a single caixa-core
4264 // edit rather than a coordinated rewrite — sibling of the peer M2
4265 // [`crate::LimitsSpec::wall_clock`] (8cb717b) validate-arm-route
4266 // on the per-`:limits :wall-clock` axis and the peer M3
4267 // [`crate::MeshPolicy::timeout`] (7073d0f) accessor-route on the
4268 // per-`:politicas :timeout` axis.
4269 if let Some(w) = self.restart_window() {
4270 // Zero-floor + integer-millisecond canonical-form +
4271 // upper-cap bracket on the typed `:restart-window` axis.
4272 // See
4273 // [`crate::render::require_positive_canonical_bounded_duration`]
4274 // for the full three-arm ordering discipline (zero-floor
4275 // strictly precedes canonical-form so `Duration::ZERO`
4276 // surfaces the self-locating `RestartWindowZero`
4277 // diagnostic; canonical-form strictly precedes the cap arm
4278 // so a sub-millisecond above-cap value surfaces the more
4279 // fundamental round-trip-shape diagnostic first) and the
4280 // three peer typed-`Duration` sites that share this
4281 // canonical bracket ([`crate::MeshPolicy::timeout`],
4282 // [`crate::CircuitBreaker::window`],
4283 // [`crate::LimitsSpec::wall_clock`]). Every validated
4284 // value lies in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`
4285 // (1ms..=1h), integer-millisecond granularity.
4286 crate::render::require_positive_canonical_bounded_duration(
4287 w,
4288 SUPERVISOR_RESTART_WINDOW_MAX,
4289 || SupervisorError::RestartWindowZero,
4290 SupervisorError::restart_window_not_canonical,
4291 SupervisorError::restart_window_exceeds_cap,
4292 )?;
4293 }
4294 // Route the per-child DNS-1123 / semver-requirement / duplicate-
4295 // detection fan-out loop through the lifted named per-slot gate
4296 // [`SupervisorSpec::validate_children`] rather than an inline
4297 // three-per-child cascade — every future consumer that wants to
4298 // re-check only the `:children` slot's per-entry axes (the M4
4299 // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
4300 // admission webhook re-validating one added/renamed child, the
4301 // future wasm-operator's per-child dynamic-add re-validator on
4302 // the `SimpleOneForOne` runtime-add path once dynamic-children
4303 // graduate to a typed slot, a future partial re-validator on a
4304 // per-`:children`-entry patch) reaches every per-entry axis
4305 // through one dispatch rather than re-inlining the three-arm
4306 // cascade in lockstep with `validate` or paying the peer
4307 // `:estrategia`/`:max-restarts`/`:restart-window` gates to
4308 // reach one entry check. Sibling of the peer M3 mesh-slot
4309 // per-slot gate family (`validate_membros` — the exact peer on
4310 // the M3 side, [`crate::AplicacaoSpec::validate_membros`];
4311 // `validate_contratos` — 906a5c6; `validate_entrada` — 20cd523;
4312 // `validate_placement`; `validate_politicas` routing through
4313 // `MeshPolicy::validate` — f03a154) — the M2 supervisor-slot
4314 // per-slot gate discipline now spans both the M3 mesh-slot
4315 // family and the M2 `:children` per-child-cascade axis on one
4316 // shape: one named per-slot gate per typed per-entry loop.
4317 self.validate_children()?;
4318 Ok(())
4319 }
4320
4321 /// Named per-slot gate on the M2 `:supervisor :children` per-entry
4322 /// axis — folds the per-child DNS-1123 name gate, semver-requirement
4323 /// gate, and duplicate-`:caixa` dedup arm into one call every
4324 /// consumer that wants to re-validate one `:children` entry (or the
4325 /// whole list) against the same accept-set [`SupervisorSpec::validate`]
4326 /// admits reaches through.
4327 ///
4328 /// Peer of the M3 mesh-slot [`crate::AplicacaoSpec::validate_membros`]
4329 /// per-slot gate on the analogous per-entry axis (`:membros`) — same
4330 /// three-per-entry shape (DNS-1123 name + semver-requirement +
4331 /// duplicate-`:caixa` dedup), lifted to one named substrate
4332 /// primitive per slot. The M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
4333 /// materializer's admission webhook re-checking one added or renamed
4334 /// child, the future wasm-operator's per-child dynamic-add
4335 /// re-validator on the `SimpleOneForOne` runtime-add path once
4336 /// dynamic-children graduate to a typed slot, a future partial
4337 /// re-validator on a per-`:children`-entry patch — each reaches the
4338 /// three per-entry axes through this one dispatch rather than
4339 /// re-inlining the three-arm cascade in lockstep with `validate`
4340 /// (the duplication the PRIME DIRECTIVE names as a bug) or paying
4341 /// the peer `:estrategia`/`:max-restarts`/`:restart-window` gates to
4342 /// reach one entry check.
4343 ///
4344 /// Self-contained on `&self` — resolves its own dedup `HashSet`
4345 /// through [`SupervisorSpec::children`] rather than borrowing one
4346 /// threaded down from `validate`, the same posture the peer M3
4347 /// mesh-slot per-slot gates ([`crate::AplicacaoSpec::validate_membros`],
4348 /// [`crate::AplicacaoSpec::validate_contratos`],
4349 /// [`crate::AplicacaoSpec::validate_entrada`],
4350 /// [`crate::AplicacaoSpec::validate_placement`]) each carry, so a
4351 /// consumer that reaches this gate directly (without first calling
4352 /// `validate`) still runs the full per-child cascade — pinned by
4353 /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
4354 /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
4355 /// + `validate_children_is_self_contained_on_children_slot`.
4356 ///
4357 /// The three per-entry arms run in the same canonical order the
4358 /// pre-lift inline cascade encoded (DNS-1123 → semver → dedup), so
4359 /// the diagnostic every author-declared per-`:children` entry surfaces
4360 /// through `validate` is byte-equal to the diagnostic this gate
4361 /// surfaces when called directly — the equivalence-pin pair
4362 /// `validate_children_matches_gate_on_per_axis_refusal_shapes` +
4363 /// `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
4364 /// asserts the two altitudes discriminate the same set on every
4365 /// per-entry-covered input.
4366 pub fn validate_children(&self) -> Result<(), SupervisorError> {
4367 let mut seen = std::collections::HashSet::new();
4368 for child in self.children() {
4369 // Every emitted cluster artifact's `metadata.name` for a
4370 // supervised child derives from this `:children :caixa` value
4371 // verbatim — the rendered `wasm.pleme.io/v1alpha1/ComputeUnit
4372 // .metadata.name` per child, the [`crate::LABEL_PROGRAM`]
4373 // label value on every child's pod identity, and the per-
4374 // child K8s [`Service`][svc] `metadata.name` the future
4375 // wasm-operator (M3) provisions for inter-child supervision
4376 // tree wiring. Each apiserver-side schema on each landing
4377 // site enforces the DNS-1123 label rule on admission; a
4378 // structurally invalid child name (`"Worker"`, `"my_worker"`,
4379 // `"team.worker"`, `"-worker"`, `"worker-"`, the >63-byte
4380 // UUID-shaped mistaken-identity slug) silently passes the
4381 // prior empty-/duplicate-only gate and the failure surfaces
4382 // at `kubectl apply` time as a `metadata.name: Invalid value`
4383 // rejection, far from the source caixa.lisp, with no field
4384 // naming the offending `:children` entry. Lifting the gate
4385 // to caixa-build time mirrors the `:membros :caixa` value-
4386 // shape trajectory (3f9d7a0) and the `:placement :clusters`
4387 // trajectory (6cbb900) onto the third DNS-1123-label-shaped
4388 // identifier axis — the supervisor tree's child names —
4389 // through the lifted
4390 // [`crate::render::require_valid_dns_1123_label`] gate the
4391 // seven peer name axes (`:membros :caixa`, `:placement
4392 // :clusters`, `:placement :affinity`, `:contratos :de`/`:para`,
4393 // `:entrada :para`, `:nome`, `:upgrade-from :module`) each
4394 // route through, so drift between the eight axes' accepted
4395 // DNS-1123-label sets is structurally impossible.
4396 //
4397 // [svc]: https://kubernetes.io/docs/concepts/services-networking/service/
4398 crate::render::require_valid_dns_1123_label(
4399 child.nome(),
4400 || SupervisorError::EmptyChildName,
4401 |reason| SupervisorError::child_caixa_invalid(child.nome(), reason),
4402 )?;
4403 // The author surface for `:children :versao` is the same
4404 // Cargo-shaped semver requirement string `:deps :versao` and
4405 // `:membros :versao` carry — and the lacre pipeline resolves
4406 // all three axes through the same
4407 // [`crate::version::parse_requirement`] entry-point. The
4408 // shared [`crate::render::require_valid_versao_requirement`]
4409 // helper brackets the empty-first + parse cascade both peer
4410 // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
4411 // [`crate::AplicacaoSpec::validate_membros`] on `:membros
4412 // :versao`) route through, so drift between the three axes'
4413 // accepted requirement sets is structurally impossible and
4414 // the parse-side no-op the empty-first arm closes (semver's
4415 // empty parse yields an implicit `*`) lives in exactly one
4416 // predicate. Every `ChildSpec::versao` past validate is
4417 // round-trippable through [`crate::parse_requirement`]
4418 // without re-checking at the resolver layer, and the three
4419 // `:versao` typed surfaces (`:deps`, `:membros`, `:children`)
4420 // are now structurally equivalent by construction.
4421 crate::render::require_valid_versao_requirement(
4422 child.versao_requirement(),
4423 || SupervisorError::empty_child_version(child.nome()),
4424 |reason| {
4425 SupervisorError::child_versao_invalid(
4426 child.nome(),
4427 child.versao_requirement(),
4428 reason,
4429 )
4430 },
4431 )?;
4432 crate::render::insert_first_seen(&mut seen, child.nome(), || {
4433 SupervisorError::duplicate_child_caixa(child.nome())
4434 })?;
4435 }
4436 Ok(())
4437 }
4438}
4439
4440/// Cross-slot coherence gate on the supervision tree: no
4441/// `:children :caixa` entry may name the supervisor's own `:nome`.
4442///
4443/// A supervisor that lists itself as a child is a degenerate self-parent
4444/// — the supervision tree is a DAG rooted at the supervisor (OTP child
4445/// specs reference *distinct* child processes; a supervisor is never its
4446/// own child), and the wasm-operator's hierarchical reconciliation would
4447/// otherwise be handed a node that is its own parent: a one-node cycle it
4448/// either rejects far from the source `caixa.lisp` or recurses on. Because
4449/// every `:nome` is a globally-unique substrate identity (DNS-1123 label +
4450/// lacre closure root), a child whose `:caixa` equals the supervisor's
4451/// `:nome` *is* the supervisor itself, not a coincidentally-named peer.
4452///
4453/// Lives outside [`SupervisorSpec::validate`] because the typed view
4454/// carries the children but not the parent `:nome`; mirrors the
4455/// cross-slot precedence gate `validate_upgrade_from_against_versao`
4456/// (which likewise reads one slot against another at the
4457/// [`crate::layout`] wire-up site) and the mesh self-edge gate
4458/// `AplicacaoSpec`'s `ContratoSelfLoop` — the same "an edge from a graph
4459/// node to itself is structurally not a tree/mesh edge" discipline, here
4460/// on the supervision-tree axis.
4461pub fn validate_no_self_supervision(
4462 children: &[ChildSpec],
4463 parent_nome: &str,
4464) -> Result<(), SupervisorError> {
4465 for child in children {
4466 if child.nome() == parent_nome {
4467 return Err(SupervisorError::child_supervises_self(parent_nome));
4468 }
4469 }
4470 Ok(())
4471}
4472
4473#[derive(Debug, Error, PartialEq, Eq)]
4474pub enum SupervisorError {
4475 #[error("supervisor :estrategia {estrategia:?} requires at least one :children entry")]
4476 NoChildren { estrategia: RestartStrategy },
4477 #[error(
4478 "SimpleOneForOne supervisors must declare zero static children (children spawn dynamically)"
4479 )]
4480 SimpleOneForOneWithStaticChildren,
4481 #[error(":max-restarts must be > 0")]
4482 ZeroMaxRestarts,
4483 #[error(
4484 ":supervisor :max-restarts ({max_restarts}) exceeds the supervisor-policy ceiling \
4485 (SUPERVISOR_MAX_RESTARTS_MAX = 1000) — a value above this cap turns the typed \
4486 restart-intensity policy into a no-op supervisor: the escalation threshold is \
4487 structurally so high that no realistic restarts-per-:restart-window traffic shape \
4488 can reach it, so the supervisor never escalates to its parent and a bad child can \
4489 loop inside the window indefinitely. Every typed-slot consumer (Erlang/OTP's \
4490 MaxIntensity/Period ratio, the future wasm-operator's per-supervisor \
4491 restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
4492 materializer's admission webhook) emits a `:max-restarts` declaration that is \
4493 structurally never reached. Pin a value in 1..=1000 (Erlang/OTP / Elixir / Riak \
4494 Core / RabbitMQ production playbooks recommend 3..=100; the OTP `supervisor` \
4495 callback module's `MaxR = 1` minimal-restart default sits at the bottom of the \
4496 band) or restructure the supervision tree (split the flaky child into its own \
4497 sub-supervisor with a tighter budget) if you need a higher restart tolerance."
4498 )]
4499 MaxRestartsExceedsCap { max_restarts: u32 },
4500 #[error(
4501 ":restart-window must be > 0 when set — Erlang/OTP's MaxIntensity/Period \
4502 requires Period > 0; a zero window either trips on the first failure or \
4503 never trips depending on operator interpretation. Omit :restart-window to \
4504 express `never reset`; carry a positive duration to express the window."
4505 )]
4506 RestartWindowZero,
4507 #[error(
4508 ":supervisor :restart-window ({window:?}) carries a sub-millisecond residue the shared `duration_codec` cannot round-trip — \
4509 the codec truncates to `as_millis()` before picking the canonical unit, so a value with `subsec_nanos() % 1_000_000 != 0` either \
4510 truncates on first serialize (e.g. `Duration::from_micros(1500)` → \"1ms\" → `Duration::from_millis(1)` ≠ original) or renders \
4511 as \"0s\" the `RestartWindowZero` arm then rejects on re-validate. Pin an integer-millisecond magnitude in the canonical authoring form \
4512 (`<integer><unit>` for unit ∈ {{ms, s, m, h}}, e.g. `\"500ms\"`, `\"30s\"`, `\"2m\"`, `\"1h\"`) or omit the field for `never reset`"
4513 )]
4514 RestartWindowNotCanonical { window: Duration },
4515 #[error(
4516 ":supervisor :restart-window ({window:?}) exceeds the supervisor-policy ceiling \
4517 (SUPERVISOR_RESTART_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
4518 per-supervisor rolling-window restart-intensity counter into a lifetime counter: the \
4519 failure-counting window is structurally so long that transient restarts are never \
4520 forgotten, the MaxIntensity/Period ratio degenerates from `trip the parent supervisor \
4521 when the child has exceeded its restart budget within the recent window` to `trip the \
4522 parent when the child has exceeded its restart budget over its lifetime`, and the \
4523 supervisor's reset semantic never reaches the child — every typed-slot consumer \
4524 (Erlang/OTP's MaxIntensity/Period reconciler, the future wasm-operator's \
4525 per-supervisor restart-intensity counter, the M4 mesh.pleme.io/v1alpha1/Supervisor CR \
4526 materializer's admission webhook, the caixa-operator's hierarchical reconciliation \
4527 scheduler) emits a `:restart-window` declaration that is structurally a no-op rolling \
4528 window. Pin a value in 1ms..=1h (Learn You Some Erlang's `{{intensity, 5, 60}}` \
4529 worker-supervisor `Period = 60s` default, Elixir's `Supervisor` `max_seconds: 5` \
4530 default, OTP's `supervisor` callback module `MaxT = 5..=60` typical, Riak Core's \
4531 `MaxT ∈ 10s..=300s`, RabbitMQ broker-supervisor `MaxT = 5s` default — every Erlang/OTP \
4532 / Elixir production playbook sits in the 5s..=300s band; the longest documented \
4533 per-supervisor restart-window any pleme-io substrate playbook recommends maxes at \
4534 ~30m) or omit :restart-window to express `never reset` (the supervisor's restart \
4535 budget then becomes a strict lifetime counter by design, not a degenerate one — the \
4536 author surfaces the lifetime-counter semantic explicitly at the slot, rather than \
4537 hiding it behind a rolling-window declaration the cap arm rejects)"
4538 )]
4539 RestartWindowExceedsCap { window: Duration },
4540 #[error("child entry has empty :caixa name")]
4541 EmptyChildName,
4542 #[error(
4543 "child :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
4544 (the K8s apiserver enforces this rule on every `metadata.name` / Service \
4545 name / label value the child name lands in — the per-child \
4546 `wasm.pleme.io/v1alpha1/ComputeUnit.metadata.name`, the `LABEL_PROGRAM` \
4547 label value, and the future wasm-operator per-child Service `metadata.name` \
4548 — each apiserver-side schema rejects names that don't match; use a \
4549 lowercase alphanumeric + hyphen identifier like `\"worker\"` or `\"cache-v2\"`)"
4550 )]
4551 ChildCaixaInvalid { caixa: String, reason: String },
4552 #[error("child {caixa:?} has empty :versao constraint")]
4553 EmptyChildVersion { caixa: String },
4554 #[error(
4555 "child {caixa:?} :versao {versao:?} is not a valid semver requirement: \
4556 {reason} (use Cargo-shaped forms like `\"^0.1\"`, `\"~0.1.2\"`, \
4557 `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` and \
4558 `:membros :versao` carry; the lacre pipeline resolves all three \
4559 through the same parser)"
4560 )]
4561 ChildVersaoInvalid {
4562 caixa: String,
4563 versao: String,
4564 reason: String,
4565 },
4566 #[error(
4567 "child {caixa:?} appears more than once (Erlang/OTP requires unique \
4568 child_spec.id per supervisor; duplicate children materialize as duplicate \
4569 ComputeUnits in the rendered chart, one silently overwriting the other)"
4570 )]
4571 DuplicateChildCaixa { caixa: String },
4572 #[error(
4573 "supervisor {caixa:?} lists itself as a :children entry — a supervisor is \
4574 never its own child (the supervision tree is a DAG rooted at the supervisor; \
4575 OTP child specs reference distinct child processes). Since every :nome is a \
4576 globally-unique substrate identity, a child naming the supervisor's own :nome \
4577 is a one-node reconciliation cycle, not a coincidentally-named peer; drop the \
4578 self-referential :children entry or rename it to the actual child caixa."
4579 )]
4580 ChildSupervisesSelf { caixa: String },
4581}
4582
4583// Fold the three `SupervisorError::<Variant> { caixa: <&str>.to_string() }`
4584// caixa-only struct-variant wire-up sites at [`SupervisorSpec::validate_children`]
4585// and [`validate_no_self_supervision`] onto one substrate primitive per
4586// typed variant — the sibling on `SupervisorError` of the four uniform-shape
4587// `LayoutError`-envelope constructor families the peer
4588// [`crate::layout::layout_violation_ctors!`] macro closed (131ca0d, 16
4589// variants on `{ caixa, issue }`), the [`crate::layout::layout_slot_kind_ctors!`]
4590// macro closed (0419438, 4 variants on `{ caixa, kind, slots }`), the
4591// [`crate::LayoutError::missing_entry`] one-variant ctor closed (1b09f9d,
4592// on `{ kind, path }`), and the [`crate::layout::layout_nome_only_ctors!`]
4593// macro closed (3fe3dd7, 6 variants on `<Variant>(String)`), plus the
4594// [`crate::AplicacaoError::entrada_host_invalid`] one-variant ctor
4595// (17dd504, `{ host, reason }`), the [`crate::aplicacao::contrato_target_ctors!`]
4596// macro (14b81d5, 2 variants on `{ de, para, wit, expected }`), and the
4597// [`crate::aplicacao::contrato_empty_pair_ctors!`] macro (8580068, 4
4598// variants on `{ de, para }`) already at that discipline on the peer
4599// `AplicacaoError` envelopes.
4600//
4601// Each of the three wire-up sites on this shape (`EmptyChildVersion` at
4602// the per-`:children` semver-requirement empty-first arm, `DuplicateChildCaixa`
4603// at the per-`:children` dedup arm, `ChildSupervisesSelf` at the cross-slot
4604// self-supervision arm) opened the identical
4605// `SupervisorError::<Variant> { caixa: <&str>.to_string() }` struct-literal —
4606// the exact "same block re-inlined at every consumer" shape the PRIME
4607// DIRECTIVE names as a bug, on the same altitude the peer `LayoutError` /
4608// `AplicacaoError` families each closed on their sibling envelopes. The
4609// three variants share one `{ caixa: String }` shape, so the fold routes
4610// each wire-up site through one dispatch per typed variant.
4611//
4612// The macro below generates one static constructor per variant of shape
4613// `fn <slot>(caixa: &str) -> SupervisorError`, so every wire-up site
4614// collapses onto one dispatch:
4615// `SupervisorError::<slot>(<&str>)`, byte-equal to the pre-lift
4616// struct-literal on the same `&str` fixture. The uniform one-field
4617// construction (`caixa: caixa.to_string()`) is spelled once — inside the
4618// macro — rather than at every wire-up site. Every constructor is
4619// `#[must_use]` so a caller who mistakenly discards the constructed error
4620// trips a compile warning at the wire-up site.
4621//
4622// Every future consumer that wants to construct one of these three
4623// variants outside `SupervisorSpec::validate_children` /
4624// `validate_no_self_supervision` — a deferred
4625// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
4626// webhook re-checking one added/renamed child, a future
4627// `feira validate --supervisor` per-caixa admission verb, a per-child
4628// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path
4629// once dynamic-children graduate to a typed slot, a per-Supervisor
4630// overlay resolver rejecting a duplicate/self-supervising child against
4631// a cluster-local snapshot — now reaches each variant through one call
4632// rather than re-inlining the three-line struct-literal in lockstep
4633// with the three in-crate wire-up sites.
4634macro_rules! supervisor_caixa_only_ctors {
4635 ($($ctor:ident => $variant:ident),* $(,)?) => {
4636 impl SupervisorError {
4637 $(
4638 #[doc = concat!(
4639 "Construct a [`SupervisorError::",
4640 stringify!($variant),
4641 "`] naming the offending `:children :caixa` (or ",
4642 "supervisor `:nome`, on the self-supervision arm). ",
4643 "Folds the uniform `Self::",
4644 stringify!($variant),
4645 " { caixa: caixa.to_string() }` one-field ",
4646 "struct-literal onto one substrate primitive so ",
4647 "every [`SupervisorSpec::validate_children`] / ",
4648 "[`validate_no_self_supervision`] wire-up on this ",
4649 "variant reads through one dispatch rather than the ",
4650 "pre-lift open-coded struct-literal block."
4651 )]
4652 #[must_use]
4653 pub fn $ctor(caixa: &str) -> Self {
4654 Self::$variant { caixa: caixa.to_string() }
4655 }
4656 )*
4657 }
4658 };
4659}
4660
4661supervisor_caixa_only_ctors! {
4662 empty_child_version => EmptyChildVersion,
4663 duplicate_child_caixa => DuplicateChildCaixa,
4664 child_supervises_self => ChildSupervisesSelf,
4665}
4666
4667// Fold the two `SupervisorError::{ChildCaixaInvalid, ChildVersaoInvalid}`
4668// struct-variant wire-up sites at [`SupervisorSpec::validate_children`] onto
4669// one substrate primitive per typed variant — the M2 supervisor-side siblings
4670// of the peer [`crate::AplicacaoError::membro_caixa_invalid`] two-slot ctor
4671// already lifted through the sibling
4672// [`crate::aplicacao::aplicacao_field_reason_ctors!`] macro (981060b) on the
4673// peer `AplicacaoError { caixa: String, reason: String }` envelope. The
4674// `ChildCaixaInvalid` variant carries the same `{ <name>: String, reason:
4675// String }` two-slot shape the peer seven-variant
4676// [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold closed on the
4677// `AplicacaoError` envelope (`MembroCaixaInvalid`, `EntradaParaInvalid`,
4678// `EntradaHostInvalid`, `EntradaPathInvalid`, `PlacementClusterInvalid`,
4679// `PlacementAffinityInvalid`, `ShardKeyInvalid`); the `ChildVersaoInvalid`
4680// variant carries the `{ caixa: String, versao: String, reason: String }`
4681// three-slot shape the sibling `AplicacaoError::MembroVersaoInvalid` axis
4682// carries on the same `:versao` value-shape.
4683//
4684// Each of the two wire-up sites opened the same closure-shaped
4685// `|reason| SupervisorError::<Variant> { caixa: child.nome().to_string(),
4686// [versao: child.versao_requirement().to_string(),] reason }` block inside
4687// the paired [`crate::render::require_valid_dns_1123_label`] and
4688// [`crate::render::require_valid_versao_requirement`] callbacks — the exact
4689// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE names
4690// as a bug, on the same altitude the peer `AplicacaoError` /
4691// `SupervisorError` / `LayoutError` / `DepError` / `LimitsError` ctor
4692// families already closed on their sibling envelopes.
4693//
4694// The two `#[must_use]` inherent constructors below fold each wire-up onto
4695// one dispatch: `SupervisorError::child_caixa_invalid(<name>, <reason>)`
4696// and `SupervisorError::child_versao_invalid(<name>, <versao>, <reason>)`,
4697// byte-equal to the pre-lift struct-literal on the same scalar fixtures.
4698// The uniform per-field `.to_string()` / `.into()` construction is spelled
4699// once — inside each ctor body — rather than at every wire-up site. The
4700// `reason: impl Into<String>` bound accepts both `&str` literals and
4701// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
4702// diagnostic shape at the lift, matching the peer
4703// [`aplicacao_field_reason_ctors!`] and
4704// [`crate::aplicacao::contrato_pair_value_reason_ctors!`] bounds on the
4705// sibling envelopes.
4706//
4707// Every future consumer that wants to construct one of these two variants
4708// outside `SupervisorSpec::validate_children` — a deferred
4709// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission webhook
4710// re-checking one added/renamed child's `:caixa` or `:versao`, a future
4711// `feira validate --supervisor` per-caixa admission verb, a per-child
4712// dynamic-add re-validator on the `SimpleOneForOne` runtime-add path once
4713// dynamic-children graduate to a typed slot, a per-Supervisor overlay
4714// resolver rejecting a shape-invalid child `:caixa`/`:versao` against a
4715// cluster-local snapshot — now reaches each variant through one call rather
4716// than re-inlining the per-shape struct-literal block in lockstep with the
4717// two in-crate wire-up sites.
4718impl SupervisorError {
4719 /// Construct a [`SupervisorError::ChildCaixaInvalid`] naming the
4720 /// offending `:children :caixa` value under the given `reason`. Folds
4721 /// the uniform `Self::ChildCaixaInvalid { caixa: caixa.to_string(),
4722 /// reason: reason.into() }` two-slot struct-literal onto one substrate
4723 /// primitive so every wire-up on this variant reads through one
4724 /// dispatch, matching the peer
4725 /// [`crate::AplicacaoError::membro_caixa_invalid`] ctor's shape on the
4726 /// sibling `AplicacaoError { caixa: String, reason: String }`
4727 /// envelope. `reason` accepts both `&str` literals and `format!(…)`
4728 /// outputs through the `impl Into<String>` bound.
4729 #[must_use]
4730 pub fn child_caixa_invalid(caixa: &str, reason: impl Into<String>) -> Self {
4731 Self::ChildCaixaInvalid {
4732 caixa: caixa.to_string(),
4733 reason: reason.into(),
4734 }
4735 }
4736
4737 /// Construct a [`SupervisorError::ChildVersaoInvalid`] naming the
4738 /// offending `:children :caixa` and its `:versao` requirement under
4739 /// the given `reason`. Folds the uniform `Self::ChildVersaoInvalid {
4740 /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
4741 /// reason.into() }` three-slot struct-literal onto one substrate
4742 /// primitive so every wire-up on this variant reads through one
4743 /// dispatch, matching the sibling `AplicacaoError::MembroVersaoInvalid
4744 /// { caixa, versao, reason }` three-slot axis on the peer
4745 /// `AplicacaoError` envelope. `reason` accepts both `&str` literals
4746 /// and `format!(…)` outputs through the `impl Into<String>` bound.
4747 #[must_use]
4748 pub fn child_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
4749 Self::ChildVersaoInvalid {
4750 caixa: caixa.to_string(),
4751 versao: versao.to_string(),
4752 reason: reason.into(),
4753 }
4754 }
4755}
4756
4757// Fold the four `SupervisorError::<Variant> { <field>: <Copy> }` one-field
4758// Copy-scalar struct-variant wire-up sites at [`SupervisorSpec::validate`]'s
4759// three bracket-arms — one struct-literal at the `:children`-empty
4760// non-`SimpleOneForOne` refusal cascade (`NoChildren { estrategia }`) plus
4761// three `impl FnOnce(<ty>) -> SupervisorError` bracket-closures at the
4762// [`crate::render::require_positive_bounded_u32`] `:max-restarts` cap arm
4763// (`MaxRestartsExceedsCap { max_restarts }`) and the paired
4764// [`crate::render::require_positive_canonical_bounded_duration`]
4765// `:restart-window` canonical-form + cap arms (`RestartWindowNotCanonical
4766// { window }`, `RestartWindowExceedsCap { window }`) — onto one substrate
4767// primitive per typed variant, matching the sibling
4768// [`crate::aplicacao::aplicacao_policy_scalar_ctors!`] macro (7ef425e, 8
4769// variants on the same `{ <field>: Duration | u32 }` shape) at that
4770// discipline on the peer `AplicacaoError` envelope's per-`:politicas`
4771// scalar axis. Every variant is a one-field `Copy`-pass-through struct-
4772// literal — `RestartStrategy | u32 | Duration` — so the fold routes each
4773// wire-up site through one dispatch per typed variant without a runtime-
4774// work delta.
4775//
4776// Each of the four wire-up sites opened the identical
4777// `SupervisorError::<Variant> { <field>: <val> }` struct-literal — the
4778// exact "same block re-inlined at every consumer" shape the PRIME
4779// DIRECTIVE names as a bug, on the same altitude the peer
4780// `aplicacao_policy_scalar_ctors!` fold closed on the sibling
4781// `AplicacaoError` envelope's per-`:politicas` per-axis cap / canonical-
4782// form arms. The four variants share one `{ <field>: <Copy> }` shape, so
4783// the fold routes each wire-up site through one dispatch per typed
4784// variant.
4785//
4786// The macro below generates one static constructor per variant of shape
4787// `const fn <ctor>(<field>: <ty>) -> SupervisorError`, so every wire-up
4788// site collapses onto one dispatch: `SupervisorError::<ctor>(<val>)`,
4789// byte-equal to the pre-lift struct-literal on the same `Copy`-`<ty>`
4790// fixture — as a direct call at the [`SupervisorSpec::validate`]
4791// `:children`-empty refusal, or as a bare function pointer in the
4792// `impl FnOnce(<ty>) -> SupervisorError` bracket-closure slot every
4793// [`crate::render::require_positive_bounded_u32`] /
4794// [`crate::render::require_positive_canonical_bounded_duration`] gate
4795// carries — rather than the pre-lift open-coded one-line closure over
4796// the same one-field struct-literal. `const fn` preserves the `Copy`-
4797// pass-through's zero-runtime-work property verbatim. Every constructor
4798// is `#[must_use]` so a caller who mistakenly discards the constructed
4799// error trips a compile warning at the wire-up site.
4800//
4801// Every future consumer that wants to construct one of these four
4802// variants outside `SupervisorSpec::validate` — a deferred
4803// `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's admission
4804// webhook re-checking one edited `:estrategia` / `:max-restarts` /
4805// `:restart-window` slot against the cap + canonical-form cascade, a
4806// future `feira validate --supervisor` per-caixa admission verb re-
4807// running the shape gates on demand, a per-Supervisor overlay resolver
4808// rejecting an author-supplied slot against a cluster-local snapshot —
4809// now reaches each variant through one call rather than re-inlining the
4810// per-shape struct-literal block in lockstep with the four in-crate
4811// wire-up sites.
4812macro_rules! supervisor_scalar_ctors {
4813 ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
4814 impl SupervisorError {
4815 $(
4816 #[doc = concat!(
4817 "Construct a [`SupervisorError::",
4818 stringify!($variant),
4819 "`] naming the offending per-`:supervisor` `",
4820 stringify!($field),
4821 "` scalar. Folds the uniform `Self::",
4822 stringify!($variant),
4823 " { ",
4824 stringify!($field),
4825 " }` one-field `Copy`-pass-through struct-literal onto ",
4826 "one substrate primitive so every per-axis wire-up on ",
4827 "this variant reads through one dispatch — as a direct ",
4828 "call (`SupervisorError::",
4829 stringify!($ctor),
4830 "(<val>)`, byte-equal to the pre-lift struct-literal on ",
4831 "the same `Copy`-`",
4832 stringify!($ty),
4833 "` fixture) or as a bare function pointer in the ",
4834 "`impl FnOnce(",
4835 stringify!($ty),
4836 ") -> SupervisorError` bracket-closure slot every ",
4837 "`crate::render::require_positive_bounded_*` / ",
4838 "`crate::render::require_positive_canonical_bounded_*` ",
4839 "gate carries — rather than the pre-lift open-coded ",
4840 "one-line closure over the same one-field struct-",
4841 "literal. `const fn` preserves the `Copy`-pass-through's ",
4842 "zero-runtime-work property verbatim."
4843 )]
4844 #[must_use]
4845 pub const fn $ctor($field: $ty) -> Self {
4846 Self::$variant { $field }
4847 }
4848 )*
4849 }
4850 };
4851}
4852
4853supervisor_scalar_ctors! {
4854 no_children => NoChildren { estrategia: RestartStrategy },
4855 max_restarts_exceeds_cap => MaxRestartsExceedsCap { max_restarts: u32 },
4856 restart_window_not_canonical => RestartWindowNotCanonical { window: Duration },
4857 restart_window_exceeds_cap => RestartWindowExceedsCap { window: Duration },
4858}
4859
4860/// Shared duration string codec for the typed slots that take a
4861/// duration (`restart_window`, `MeshPolicy::timeout`,
4862/// `CircuitBreaker::window`, …). Public so [`crate::aplicacao`] can
4863/// reuse it without duplicating the parser.
4864pub mod duration_codec {
4865 use super::Duration;
4866 use serde::{Deserializer, Serializer};
4867
4868 pub fn serialize<S: Serializer>(v: &Option<Duration>, s: S) -> Result<S::Ok, S::Error> {
4869 // Route through the canonical [`crate::render::serialize_option_via_str`]
4870 // — the substrate-side single-owner primitive for the forward
4871 // arm of the typed-magnitude codec family. See its docstring
4872 // for the full sibling roster.
4873 crate::render::serialize_option_via_str(v, s, render)
4874 }
4875
4876 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
4877 // Route through the canonical [`crate::render::deserialize_option_via_str`]
4878 // — the substrate-side single-owner primitive for the reverse
4879 // arm of the typed-magnitude codec family. See its docstring
4880 // for the full sibling roster.
4881 crate::render::deserialize_option_via_str(d, parse)
4882 }
4883
4884 pub(crate) fn parse(s: &str) -> Result<Duration, String> {
4885 // Paired whitespace-rejection arm — same canonical-form
4886 // render-determinism discipline as the peer
4887 // `limits::parse_byte_size` / `limits::parse_duration` /
4888 // `limits::parse_millicores` /
4889 // `aplicacao::rate_limit_codec::parse` sites: the ASCII
4890 // byte-scan closes the WhatWG-conformant whitespace bytes
4891 // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
4892 // `char::is_whitespace` scan closes the strictly-complementary
4893 // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
4894 // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
4895 // codepoints) that `str::trim` at parse entry silently strips.
4896 // Either drift class would round-trip through `render` to a
4897 // *different* canonical form on next emit — breaking the
4898 // THEORY.md Part V render-determinism contract on three typed-
4899 // duration slots at once (`:supervisor :restart-window`,
4900 // `:politicas :timeout`, `:politicas :circuit-breaker :window`)
4901 // via the shared codec.
4902 //
4903 // Routed through the lifted [`crate::render::reject_whitespace`]
4904 // primitive — the substrate-side single-owner paired-arm gate
4905 // every typed-magnitude codec in caixa-core shares.
4906 crate::render::reject_whitespace::<String, _, _>(
4907 s,
4908 |b| {
4909 format!(
4910 "duration: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
4911 authoring form for the typed duration slots routed through this shared codec \
4912 (`:supervisor :restart-window`, `:politicas :timeout`, \
4913 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
4914 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no whitespace bytes \
4915 anywhere. A whitespace-carrying shape (`\" 30s\"`, `\"30s \"`, `\"30 s\"`, \
4916 `\"\\t30s\"`, `\"30s\\n\"`) round-trips through `render` to a *different* \
4917 canonical form (`\"30s\"`) on first serialize — breaking the THEORY.md \
4918 Part V render-determinism contract every typed slot carries. Strip every \
4919 whitespace byte (write `\"30s\"` verbatim)"
4920 )
4921 },
4922 |ch| {
4923 format!(
4924 "duration: value {s:?} contains non-ASCII Unicode whitespace character \
4925 {ch:?} (U+{cp:04X}) — the canonical authoring form for the typed \
4926 duration slots routed through this shared codec (`:supervisor \
4927 :restart-window`, `:politicas :timeout`, `:politicas :circuit-breaker \
4928 :window`) is `<integer><unit>` (e.g. `\"30s\"`, `\"500ms\"`, `\"2m\"`, \
4929 `\"1h\"`) with no whitespace characters anywhere (ASCII or Unicode). A \
4930 non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}30s\"`, \
4931 `\"30s\\u{{2028}}\"`, `\"30\\u{{2003}}s\"`) survives the ASCII byte-scan \
4932 but `str::trim` (which uses `char::is_whitespace` — the Unicode \
4933 `White_Space` property, strictly wider than the ASCII byte set) silently \
4934 strips it at parse entry, and the value round-trips through `render` to \
4935 a *different* canonical form (`\"30s\"`) on first serialize — breaking \
4936 the THEORY.md Part V render-determinism contract every typed slot \
4937 carries. Strip every non-ASCII whitespace character (write `\"30s\"` \
4938 verbatim with only ASCII bytes)",
4939 cp = ch as u32
4940 )
4941 },
4942 )?;
4943 let s = s.trim();
4944 // Routed through the lifted
4945 // [`crate::render::split_magnitude_and_alpha_unit`] primitive —
4946 // the single-owner split every ASCII-alphabetic-unit typed-
4947 // magnitude codec in caixa-core (`limits::parse_byte_size` /
4948 // `limits::parse_duration` / this shared duration codec) shares.
4949 // See its docstring for the full sibling roster on the same
4950 // primitive altitude.
4951 let (num_part, unit) = crate::render::split_magnitude_and_alpha_unit(s);
4952 let num_trim = num_part.trim();
4953 // The canonical authoring form for every typed slot routed
4954 // through this shared codec — `:supervisor :restart-window`,
4955 // `:politicas :timeout`, `:politicas :circuit-breaker :window`
4956 // — is `<integer><unit>`. Every magnitude [`render`] emits is a
4957 // non-negative integer with no decimal point and no leading
4958 // sign, so the parser's accepted set must match for
4959 // serialize/deserialize to round-trip without canonical-form
4960 // drift. Until this gate landed the parser accepted any
4961 // `f64`-shaped magnitude (`"1.5s"` → 1500ms, `"1.0s"` → 1s,
4962 // `"0.5m"` → 30s, `"+30s"` → 30s) and serde silently round-
4963 // tripped the value to a *different* canonical string on the
4964 // next emit (`"1.5s"` → 1500ms → `"1500ms"`, `"1.0s"` → 1s →
4965 // `"1s"`, `"0.5m"` → 30s → `"30s"`, `"+30s"` → 30s → `"30s"`)
4966 // — breaking the THEORY.md Part V render-determinism contract
4967 // on three typed slots at once. Same canonical-form discipline
4968 // `crate::limits::parse_duration` (818dd38, the immediate
4969 // predecessor on the peer `:limits :wall-clock` codec) applies;
4970 // this gate lifts the discipline onto the shared codec that
4971 // backs the remaining three typed-duration slots in caixa-core.
4972 //
4973 // Strict canonical form: every byte of the magnitude is an
4974 // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
4975 // inputs the gate distinguishes "non-canonical-but-numeric"
4976 // (parses as f64 or i64 — surfaced with a self-locating
4977 // diagnostic naming the canonical authoring form, the
4978 // round-trip drift each rejected shape would produce on first
4979 // serialize, and the canonical-form remediation) from
4980 // "garbage" (parses as neither — surfaced with the existing
4981 // narrower "bad duration magnitude" wording so its diagnostic
4982 // shape remains stable for the parser-shape footgun case).
4983 // The pre-existing `num < 0.0` arm is now unreachable — the
4984 // digit-only gate strictly precedes magnitude parsing, and a
4985 // leading `-` is not an ASCII digit, so `"-30s"` lands on the
4986 // non-canonical-but-numeric branch with the `-30` named
4987 // verbatim in the diagnostic rather than the prior
4988 // value-laundered "negative duration in \"-30s\"" wording.
4989 //
4990 // Routed through the lifted
4991 // [`crate::render::is_digit_only_magnitude`] predicate — the
4992 // same source of truth the four peer typed-magnitude codec
4993 // sites share.
4994 let digit_only = crate::render::is_digit_only_magnitude(num_trim);
4995 if !digit_only {
4996 let numeric = num_trim.parse::<f64>().is_ok() || num_trim.parse::<i64>().is_ok();
4997 if numeric {
4998 return Err(format!(
4999 "duration: magnitude {num_trim:?} is not a non-negative integer — the \
5000 canonical authoring form for the typed duration slots routed through \
5001 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
5002 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
5003 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no decimal point and \
5004 no leading `+` / `-` sign. A fractional / decimal-shaped magnitude \
5005 (`\"1.5s\"`, `\"1.0s\"`, `\"0.5m\"`, `\"+30s\"`, `\"-30s\"`) round-trips \
5006 through `render` to a *different* canonical form (`\"1500ms\"`, `\"1s\"`, \
5007 `\"30s\"`, `\"30s\"`, `\"30s\"`) on first serialize — breaking the \
5008 THEORY.md Part V render-determinism contract every typed slot carries. \
5009 Pick an integer magnitude in the unit that divides cleanly (write \
5010 `\"1500ms\"` instead of `\"1.5s\"`; `\"30s\"` instead of `\"0.5m\"`)"
5011 ));
5012 }
5013 return Err(format!("bad duration magnitude in {s:?}"));
5014 }
5015 // Leading-zero arm — peer with the `rate_limit_codec` leading-
5016 // zero arm (4f46830) on the same canonical-form render-
5017 // determinism axis. The digit-only gate accepts `"030s"`,
5018 // `"00s"`, `"01h"`, `"0500ms"` as `u64::from_str` parses them
5019 // losslessly (= 30, 0, 1, 500), but `render` emits the leading-
5020 // zero-stripped form (`"30s"`, `"0s"`, `"1h"`, `"500ms"`) — a
5021 // *different* canonical string on the next emit, breaking the
5022 // THEORY.md Part V render-determinism contract the same way
5023 // `"+30s"` did before the leading-`+` arm landed. The single-
5024 // byte magnitude `"0"` (or `"0s"` / `"0ms"`) round-trips
5025 // losslessly through `render` (`render(Duration::ZERO)` emits
5026 // `"0s"`) — the downstream semantic-zero gates (e.g.
5027 // `SupervisorError::ZeroRestartWindow` on
5028 // `:supervisor :restart-window`,
5029 // `AplicacaoError::PolicyTimeoutZero` /
5030 // `PolicyCircuitBreakerWindowZero` on the typed `:politicas`
5031 // duration slots) refuse zero-magnitude authoring at the typed-
5032 // validate layer above, so the single-byte `"0"` stays in the
5033 // accepted set at this codec layer and the diagnostic
5034 // partitioning between canonical-form drift (this arm) and
5035 // semantic-zero (the downstream gates) remains stable.
5036 // Peer with the future leading-zero arms on the two remaining
5037 // typed-magnitude codecs the trajectory acknowledges:
5038 // `limits::parse_duration` backing `:limits :wall-clock`,
5039 // `limits::parse_byte_size` backing `:limits :memory` — each
5040 // carries the same canonical-form-drift class today; this
5041 // gate lands the discipline on the shared duration codec
5042 // first because the `rate_limit_codec` predecessor on the
5043 // same canonical-form-drift axis is the closest peer on the
5044 // trajectory.
5045 //
5046 // Routed through the lifted
5047 // [`crate::render::is_leading_zero_padded_magnitude`]
5048 // predicate — the same source of truth the four peer
5049 // typed-magnitude codec sites share.
5050 if crate::render::is_leading_zero_padded_magnitude(num_trim) {
5051 return Err(format!(
5052 "duration: magnitude {num_trim:?} has a non-canonical leading zero — the \
5053 canonical authoring form for the typed duration slots routed through \
5054 this shared codec (`:supervisor :restart-window`, `:politicas :timeout`, \
5055 `:politicas :circuit-breaker :window`) is `<integer><unit>` (e.g. \
5056 `\"30s\"`, `\"500ms\"`, `\"2m\"`, `\"1h\"`) with no leading-zero padding \
5057 on the magnitude. A leading-zero magnitude (`\"030s\"`, `\"00s\"`, \
5058 `\"01h\"`, `\"0500ms\"`) round-trips through `render` to a *different* \
5059 canonical form (`\"30s\"`, `\"0s\"`, `\"1h\"`, `\"500ms\"`) on first \
5060 serialize — breaking the THEORY.md Part V render-determinism contract \
5061 every typed slot carries. Strip the leading zeros (write \
5062 `\"30s\"` instead of `\"030s\"`)"
5063 ));
5064 }
5065 // The digit-only gate guarantees every byte is `[0-9]`, and
5066 // the leading-zero arm above guarantees the magnitude is
5067 // either the single byte `"0"` or starts with `[1-9]`, so
5068 // the only way `u64::from_str` can fail here is overflow (the
5069 // magnitude exceeds `u64::MAX`). Surface that with an
5070 // overflow-shaped wording so the diagnostic names the offending
5071 // magnitude verbatim rather than collapsing onto the
5072 // non-canonical arm. The codec now operates on `u64` end-to-end
5073 // — every accepted magnitude is integer-exact; no f64 mantissa
5074 // drift between author-supplied magnitude and the consumer's
5075 // `Duration` value. Same shape `crate::limits::parse_duration`
5076 // (818dd38) carries on the peer `:limits :wall-clock` axis.
5077 let num: u64 = num_trim.parse::<u64>().map_err(|_| {
5078 format!("bad duration magnitude in {s:?} (digit-only magnitude overflows u64)")
5079 })?;
5080 // Route the `{"ms" | "s" | "" | "m" | "h"} → Duration`
5081 // unit-arm dispatch through the canonical
5082 // [`crate::render::duration_from_integer_magnitude_and_unit`]
5083 // primitive — the substrate-side single-owner unit-dispatch
5084 // table every typed-duration codec in caixa-core routes
5085 // through (peer: `crate::limits::parse_duration` backing
5086 // `:limits :wall-clock`). Every unit conversion is integer-
5087 // exact for an integer magnitude; overflow surfaces via the
5088 // typed `DurationUnitError::Overflow { multiplier }`
5089 // discriminant so this arm reconstructs the pre-lift
5090 // `"duration <num><unit> overflows u64 (magnitude × 60 …)"`
5091 // wording verbatim from `num` / `unit_trim` / the returned
5092 // `multiplier`, and the unknown-unit arm reconstructs the
5093 // pre-lift `"unknown duration unit \"<other>\""` wording from
5094 // the caller-scoped `unit_trim`. Load-bearing pinned by
5095 // `crate::render::tests::duration_from_integer_magnitude_and_unit_matches_pre_lift_unit_dispatch_table`.
5096 let unit_trim = unit.trim();
5097 let dur = crate::render::duration_from_integer_magnitude_and_unit(num, unit_trim).map_err(
5098 |e| match e {
5099 crate::render::DurationUnitError::Overflow { multiplier } => format!(
5100 "duration {num}{unit_trim} overflows u64 (magnitude × {multiplier} > 2^64-1)"
5101 ),
5102 crate::render::DurationUnitError::UnknownUnit => {
5103 format!("unknown duration unit {unit_trim:?}")
5104 }
5105 },
5106 )?;
5107 Ok(dur)
5108 }
5109
5110 /// Render a [`Duration`] in the canonical pleme-io duration string
5111 /// form (`"30s"`, `"1m"`, `"1h"`, `"500ms"`). The same form every
5112 /// caixa typed-duration slot serializes to and the same form K8s
5113 /// Gateway API HTTPRoute `timeouts` / `backendRequest` and Cilium
5114 /// EnvoyConfig per-route timeouts both expect (an integer
5115 /// followed by `s`/`m`/`h`/`ms`, no fractional values, no leading
5116 /// `+`). Lifted to `pub` so caixa-side renderers
5117 /// (`caixa-mesh::gateway_routes`'s :politicas :timeout overlay,
5118 /// the future per-:politicas `CiliumClusterwideEnvoyConfig`
5119 /// emitter, the future caixa-otel collector pipeline emitter) can
5120 /// consume the same canonical formatter without re-inlining the
5121 /// magnitude/unit decision tree (and inheriting the same drift
5122 /// footguns: a subtly different `300ms` vs `0.3s` rendering breaks
5123 /// downstream apply-time parsing in non-obvious ways).
5124 pub fn render(d: Duration) -> String {
5125 let total_ms = d.as_millis();
5126 if total_ms == 0 {
5127 return "0s".into();
5128 }
5129 if total_ms.is_multiple_of(3600 * 1000) {
5130 return format!("{}h", total_ms / (3600 * 1000));
5131 }
5132 if total_ms.is_multiple_of(60 * 1000) {
5133 return format!("{}m", total_ms / (60 * 1000));
5134 }
5135 if total_ms.is_multiple_of(1000) {
5136 return format!("{}s", total_ms / 1000);
5137 }
5138 format!("{total_ms}ms")
5139 }
5140
5141 /// True iff `d` round-trips losslessly through [`render`] + [`parse`].
5142 ///
5143 /// [`render`] truncates a `Duration` to `as_millis()` before picking the
5144 /// largest divisor unit, so any sub-millisecond residue
5145 /// (`d.subsec_nanos() % 1_000_000 != 0`) silently breaks the THEORY.md
5146 /// §V.2.7 render-determinism contract:
5147 ///
5148 /// - `Duration::from_micros(1500)` (= `1_500_000` ns) → `as_millis() == 1`
5149 /// → renders `"1ms"` → parses back to `Duration::from_millis(1)` =
5150 /// `1_000_000` ns ≠ original `1_500_000` ns;
5151 /// - `Duration::from_nanos(1)` (= 1 ns) → `as_millis() == 0` →
5152 /// renders the literal `"0s"`, which the per-axis zero-floor gate
5153 /// on every typed-`Duration` slot then rejects on re-validate.
5154 ///
5155 /// Lifted to a `pub` predicate next to the [`render`] / [`parse`] pair so
5156 /// the codec's round-trippable accepted set lives in exactly one place —
5157 /// every typed-`Duration` slot that routes through this shared codec
5158 /// (`SupervisorSpec::restart_window` via [`super::duration_codec`],
5159 /// [`crate::MeshPolicy::timeout`] / [`crate::CircuitBreaker::window`] via
5160 /// `supervisor::duration_codec` + [`super::duration_codec_required`]) and
5161 /// every typed-`Duration` slot whose own codec shares the same
5162 /// `as_millis()`-truncation shape ([`crate::LimitsSpec::wall_clock`] via
5163 /// [`crate::limits`]'s in-module `parse_duration` / `render_duration`
5164 /// pair) calls this predicate from its `validate()` to bracket the
5165 /// accepted set against the codec's accepted set, structurally. Drift
5166 /// between the codec's granularity and any typed slot's accepted set is
5167 /// then a single-source-of-truth edit at this predicate rather than a
5168 /// silent round-trip break the next consumer discovers at apply time.
5169 ///
5170 /// Peer of [`crate::aplicacao::POLICY_RETRIES_MAX`] /
5171 /// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] and the
5172 /// `is_dns_1123_label` / `is_canonical_rate_limit_window` predicate
5173 /// family — same "typed-slot's valid set matches its codec's accepted
5174 /// set, structurally" discipline carried at the codec layer.
5175 #[must_use]
5176 pub fn is_integer_millisecond_duration(d: Duration) -> bool {
5177 d.subsec_nanos().is_multiple_of(1_000_000)
5178 }
5179}
5180
5181/// Required-Duration variant for fields that aren't Option<Duration>.
5182pub mod duration_codec_required {
5183 use super::Duration;
5184 use serde::{Deserialize, Deserializer, Serializer};
5185
5186 pub fn serialize<S: Serializer>(v: &Duration, s: S) -> Result<S::Ok, S::Error> {
5187 s.serialize_str(&super::duration_codec::render(*v))
5188 }
5189
5190 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Duration, D::Error> {
5191 let s = String::deserialize(d)?;
5192 super::duration_codec::parse(&s).map_err(serde::de::Error::custom)
5193 }
5194}
5195
5196#[cfg(test)]
5197mod tests {
5198 use super::*;
5199
5200 fn child(name: &str, ver: &str, restart: RestartPolicy) -> ChildSpec {
5201 ChildSpec {
5202 caixa: name.into(),
5203 versao: ver.into(),
5204 restart,
5205 }
5206 }
5207
5208 #[test]
5209 fn child_spec_string_scalar_accessor_pair_is_const_fn() {
5210 // Fail-before-pass-after pin on [`ChildSpec::nome`] +
5211 // [`ChildSpec::versao_requirement`]'s `const`-eval-surface
5212 // posture. Each accessor projects the per-`:children :caixa`
5213 // / per-`:children :versao` [`String`] storage through the
5214 // `pub const fn` [`String::as_str`] (const-stable since Rust
5215 // 1.87, well within the workspace MSRV) — any future
5216 // accidental downgrade to non-`const` fails the corresponding
5217 // `<name>_via_const_fn` wrapper at caixa-core build time with
5218 // E0015 (`cannot call non-const method`), strictly stronger
5219 // than a runtime `assert!`. Sibling of the peer
5220 // per-M2/M3/universal-axis `String → &str` scalar-accessor
5221 // family pins on the sibling `const`-eval-surface passes
5222 // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
5223 // top-level manifest, [`crate::CaixaVersion::as_str`] at the
5224 // typed-newtype wrapper, [`crate::aplicacao::Membro::nome`] /
5225 // [`crate::aplicacao::Membro::versao_requirement`] at the M3
5226 // membership axis, [`crate::aplicacao::Entrada::hostname`] /
5227 // [`crate::aplicacao::Entrada::destination`] at the M3
5228 // ingress axis,
5229 // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
5230 // M2 upgrade axis, [`crate::dep::Dep::nome`] /
5231 // [`crate::dep::Dep::versao_requirement`] at the dep-graph
5232 // axis, and the per-`:contratos`
5233 // [`crate::aplicacao::WitContract::source`] /
5234 // [`crate::aplicacao::WitContract::destination`] /
5235 // [`crate::aplicacao::WitContract::world_ref`] trio the
5236 // sibling pin at 279823b already anchors).
5237 const fn nome_via_const_fn(c: &ChildSpec) -> &str {
5238 c.nome()
5239 }
5240 const fn versao_via_const_fn(c: &ChildSpec) -> &str {
5241 c.versao_requirement()
5242 }
5243 for (caixa, versao) in [
5244 ("worker-a", "^0.1"),
5245 ("worker-b", "~0.2.3"),
5246 ("collector", "*"),
5247 ] {
5248 let c = child(caixa, versao, RestartPolicy::Permanent);
5249 assert_eq!(nome_via_const_fn(&c), c.nome());
5250 assert_eq!(versao_via_const_fn(&c), c.versao_requirement());
5251 assert_eq!(c.nome(), caixa);
5252 assert_eq!(c.versao_requirement(), versao);
5253 }
5254 }
5255
5256 #[test]
5257 fn supervisor_children_slice_return_accessor_is_const_fn() {
5258 // Fail-before-pass-after pin on [`SupervisorSpec::children`]'s
5259 // `const`-eval-surface posture. The accessor destructures the
5260 // per-`:children` `Vec<ChildSpec>` storage through the
5261 // `pub const fn` [`Vec::as_slice`] (const-stable since Rust
5262 // 1.66, well within the workspace MSRV) — any future
5263 // accidental downgrade to non-`const` fails
5264 // `children_via_const_fn` at caixa-core build time with E0015
5265 // (`cannot call non-const method`), strictly stronger than a
5266 // runtime `assert!`. Sibling of the peer per-M3-mesh-slot
5267 // `Vec → &[T]` slice-return accessor family pin
5268 // [`crate::aplicacao::tests::m3_reference_return_accessor_family_is_const_fn`]
5269 // on the M3 mesh-slot per-`:clusters` / per-`:paths` /
5270 // per-`:membros` / per-`:contratos` slice-return axes, and of
5271 // the peer M2 upgrade-appup axis pin
5272 // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
5273 // on the per-`:upgrade-from :instructions` slice-return axis.
5274 const fn children_via_const_fn(s: &SupervisorSpec) -> &[ChildSpec] {
5275 s.children()
5276 }
5277 // Sweep both the empty-children (leaf-supervisor with no
5278 // static children — the `SimpleOneForOne` dynamic-child
5279 // arm's canonical shape) and the populated-children
5280 // (`OneForOne` / `OneForAll` / `RestForOne` static-child
5281 // arm's canonical shape) axes so the accessor carries a
5282 // const-dispatch pin on both arms.
5283 let s_empty = SupervisorSpec {
5284 estrategia: RestartStrategy::SimpleOneForOne,
5285 max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
5286 restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
5287 children: vec![],
5288 };
5289 assert!(children_via_const_fn(&s_empty).is_empty());
5290 assert_eq!(children_via_const_fn(&s_empty), s_empty.children());
5291 let s_full = SupervisorSpec {
5292 estrategia: RestartStrategy::OneForOne,
5293 max_restarts: SUPERVISOR_MAX_RESTARTS_DEFAULT,
5294 restart_window: Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
5295 children: vec![
5296 child("worker-a", "^0.1", RestartPolicy::Permanent),
5297 child("worker-b", "~0.2.3", RestartPolicy::Transient),
5298 child("collector", "*", RestartPolicy::Temporary),
5299 ],
5300 };
5301 assert_eq!(children_via_const_fn(&s_full).len(), 3);
5302 assert_eq!(children_via_const_fn(&s_full), s_full.children());
5303 }
5304
5305 #[test]
5306 fn default_has_one_for_one_and_5_restarts_in_60s() {
5307 let s = SupervisorSpec::default();
5308 assert_eq!(s.estrategia, RestartStrategy::OneForOne);
5309 assert_eq!(s.max_restarts, 5);
5310 assert_eq!(s.restart_window, Some(Duration::from_secs(60)));
5311 assert!(s.children.is_empty());
5312 }
5313
5314 #[test]
5315 fn validate_one_for_one_requires_children() {
5316 // Explicit-empty via struct-update rather than `let mut s = default(); s.children = vec![];`
5317 // — the peer `validate_simple_one_for_one_forbids_static_children` below already uses
5318 // struct-update to name the axis under test at construction, and this shape matches
5319 // it. Also keeps the "empty children is the axis under test" intent visible at the
5320 // binding site rather than one line down, and side-steps `clippy::field_reassign_with_default`.
5321 let mut s = SupervisorSpec {
5322 children: vec![],
5323 ..SupervisorSpec::default()
5324 };
5325 assert!(matches!(
5326 s.validate().unwrap_err(),
5327 SupervisorError::NoChildren { .. }
5328 ));
5329 s.children = vec![child("worker", "^0.1", RestartPolicy::Permanent)];
5330 s.validate().unwrap();
5331 }
5332
5333 #[test]
5334 fn validate_simple_one_for_one_forbids_static_children() {
5335 let mut s = SupervisorSpec {
5336 estrategia: RestartStrategy::SimpleOneForOne,
5337 ..SupervisorSpec::default()
5338 };
5339 s.children
5340 .push(child("w", "^0.1", RestartPolicy::Permanent));
5341 assert_eq!(
5342 s.validate().unwrap_err(),
5343 SupervisorError::SimpleOneForOneWithStaticChildren
5344 );
5345 s.children.clear();
5346 s.validate().unwrap();
5347 }
5348
5349 #[test]
5350 fn validate_rejects_zero_max_restarts() {
5351 let s = SupervisorSpec {
5352 max_restarts: 0,
5353 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5354 ..SupervisorSpec::default()
5355 };
5356 assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
5357 }
5358
5359 // ── upper-cap: SUPERVISOR_MAX_RESTARTS_MAX brackets the typed slot ─────
5360 //
5361 // The cap arm lifts the `:politicas :circuit-breaker :max-failures` /
5362 // `POLICY_BREAKER_MAX_FAILURES_MAX` (2b51ace) discipline onto the peer
5363 // `:supervisor :max-restarts` axis — both fields are "trip the
5364 // next-higher protection layer after N events in a rolling window"
5365 // counters with identical degenerate-at-the-high-end shape, so the
5366 // typed-slot's accepted set lies in `1..=1000` on the supervisor side
5367 // exactly as it lies in `1..=1000` on the breaker side.
5368
5369 #[test]
5370 fn validate_rejects_max_restarts_above_cap() {
5371 // The fail-before-pass-after pin: `SUPERVISOR_MAX_RESTARTS_MAX +
5372 // 1` is structurally one past the cap and silently passed
5373 // validate on every pre-gate codebase because the typed slot's
5374 // only check was the zero-floor arm. The no-op-supervisor vector
5375 // only surfaced at the runtime substrate (Erlang/OTP
5376 // MaxIntensity/Period ratio, the future wasm-operator's
5377 // per-supervisor restart-intensity counter) far from the source
5378 // caixa.lisp with no field naming the offending supervisor.
5379 let s = SupervisorSpec {
5380 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5381 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5382 ..SupervisorSpec::default()
5383 };
5384 assert_eq!(
5385 s.validate().unwrap_err(),
5386 SupervisorError::MaxRestartsExceedsCap {
5387 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5388 }
5389 );
5390 }
5391
5392 #[test]
5393 fn validate_rejects_max_restarts_far_above_cap() {
5394 // The `u32::MAX` worst case — the four-billion-restart
5395 // threshold a typo (`:max-restarts 4294967295`) or a
5396 // struct-literal copy-paste lands in the slot. Pin the cap
5397 // arm's coverage explicitly across the full `u32` overflow so
5398 // a future relaxation that drops the upper bound surfaces
5399 // here. Same shape every other typed-cap arm on this surface
5400 // carries (POLICY_BREAKER_MAX_FAILURES_MAX,
5401 // POLICY_RETRIES_MAX, POLICY_RATE_LIMIT_MAX).
5402 let s = SupervisorSpec {
5403 max_restarts: u32::MAX,
5404 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5405 ..SupervisorSpec::default()
5406 };
5407 assert_eq!(
5408 s.validate().unwrap_err(),
5409 SupervisorError::MaxRestartsExceedsCap {
5410 max_restarts: u32::MAX,
5411 }
5412 );
5413 }
5414
5415 #[test]
5416 fn validate_accepts_max_restarts_at_cap() {
5417 // The boundary value — exactly SUPERVISOR_MAX_RESTARTS_MAX —
5418 // must validate. The cap is inclusive on the top edge,
5419 // matching the POLICY_BREAKER_MAX_FAILURES_MAX /
5420 // POLICY_RETRIES_MAX / LIMITS_MEMORY_WASM32_MAX_BYTES
5421 // discipline on the sibling capped axes. Pin the boundary
5422 // explicitly so a future off-by-one tightening
5423 // (`>= SUPERVISOR_MAX_RESTARTS_MAX` instead of `>`) surfaces
5424 // here as a test failure rather than a silent contract
5425 // narrowing.
5426 let s = SupervisorSpec {
5427 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX,
5428 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5429 ..SupervisorSpec::default()
5430 };
5431 s.validate()
5432 .expect("max_restarts == SUPERVISOR_MAX_RESTARTS_MAX must validate");
5433 }
5434
5435 #[test]
5436 fn validate_accepts_max_restarts_typical_values() {
5437 // The documented production-playbook band positive-control
5438 // sweep — every value Erlang/OTP / Elixir / Riak Core /
5439 // RabbitMQ recommend (1..=100) must pass, plus a sweep
5440 // through the hyperscale band (200, 500, 1000) the cap
5441 // accepts. Pin the inclusive validated set explicitly so a
5442 // future tightening of the ceiling surfaces here.
5443 for n in [1u32, 3, 5, 10, 20, 50, 100, 200, 500, 1000] {
5444 let s = SupervisorSpec {
5445 max_restarts: n,
5446 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5447 ..SupervisorSpec::default()
5448 };
5449 s.validate()
5450 .unwrap_or_else(|e| panic!("max_restarts={n} must validate; got {e:?}"));
5451 }
5452 }
5453
5454 #[test]
5455 fn zero_max_restarts_takes_precedence_over_cap() {
5456 // The cross-arm ordering pin: `0` is structurally outside
5457 // both `1..` (zero-floor) and `..=SUPERVISOR_MAX_RESTARTS_MAX`
5458 // (cap), but the zero-floor diagnostic is the more
5459 // self-locating one (it directly names the counter-axis
5460 // remediation), so the validate gate must fire on zero first.
5461 // Same shape every other zero-then-shape ordering on this
5462 // surface uses (PolicyRetriesZero then
5463 // PolicyRetriesExceedsCap; PolicyBreakerZeroFailures then
5464 // PolicyBreakerMaxFailuresExceedsCap).
5465 let s = SupervisorSpec {
5466 max_restarts: 0,
5467 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5468 ..SupervisorSpec::default()
5469 };
5470 assert_eq!(
5471 s.validate().unwrap_err(),
5472 SupervisorError::ZeroMaxRestarts,
5473 "max_restarts == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
5474 );
5475 }
5476
5477 #[test]
5478 fn max_restarts_cap_takes_precedence_over_restart_window_gates() {
5479 // The cross-arm ordering pin between the cap and the sibling
5480 // `:restart-window` gates (zero-window, canonical-window). A
5481 // supervisor carrying both an over-cap `max_restarts` AND a
5482 // structurally invalid window (zero, sub-ms) must surface the
5483 // cap diagnostic first — the cap arm is wired immediately
5484 // after the zero-restart arm and strictly before the window
5485 // arms, so the offending value the diagnostic names matches
5486 // the order the author would discover the gates by reading
5487 // top-to-bottom through `SupervisorSpec::validate`. Pin the
5488 // order so a future refactor that reorders the arms surfaces
5489 // here as a test failure rather than a silent diagnostic
5490 // regression. Peer of
5491 // `circuit_breaker_max_failures_cap_takes_precedence_over_window_gates`
5492 // on the sibling `:politicas :circuit-breaker` slot.
5493 let s = SupervisorSpec {
5494 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5495 restart_window: Some(Duration::ZERO),
5496 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5497 ..SupervisorSpec::default()
5498 };
5499 assert_eq!(
5500 s.validate().unwrap_err(),
5501 SupervisorError::MaxRestartsExceedsCap {
5502 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
5503 },
5504 "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
5505 );
5506 }
5507
5508 #[test]
5509 fn max_restarts_cap_diagnostic_carries_offending_value() {
5510 // The diagnostic-shape pin: the offending `u32` is carried
5511 // verbatim into the `SupervisorError::MaxRestartsExceedsCap`
5512 // variant so the surfaced error message names the value the
5513 // author wrote (`":supervisor :max-restarts (50000) exceeds the
5514 // supervisor-policy ceiling …"`), not just the cap. Same
5515 // self-locating diagnostic shape every other typed-cap arm on
5516 // this surface carries
5517 // (`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` carries
5518 // the offending failure count verbatim,
5519 // `AplicacaoError::PolicyRetriesExceedsCap` carries the offending
5520 // retries count verbatim).
5521 let s = SupervisorSpec {
5522 max_restarts: 50_000,
5523 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
5524 ..SupervisorSpec::default()
5525 };
5526 let err = s.validate().unwrap_err();
5527 assert!(
5528 matches!(
5529 err,
5530 SupervisorError::MaxRestartsExceedsCap {
5531 max_restarts: 50_000
5532 }
5533 ),
5534 "got {err:?}"
5535 );
5536 let msg = err.to_string();
5537 assert!(
5538 msg.contains("50000"),
5539 ":supervisor :max-restarts cap diagnostic must carry the offending value verbatim (got: {msg})"
5540 );
5541 }
5542
5543 #[test]
5544 fn supervisor_max_restarts_default_pins_otp_canonical_value() {
5545 // Pin [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] at `5` — the
5546 // Erlang/OTP-canonical `{intensity, 5, 60}` `MaxIntensity`
5547 // half of Learn You Some Erlang's worker-supervisor default,
5548 // sibling of the `60s` `Period` half that the paired
5549 // [`Default for SupervisorSpec`] impl already pins on the
5550 // sibling `restart_window` axis. Pinning the literal here
5551 // surfaces a future rebrand (a tightening to Elixir's `3`,
5552 // a widening to a per-cluster overlay the operator pins
5553 // through a future `:max-restarts-overrides` slot) as a
5554 // deliberate test edit, not a silent contract migration.
5555 // Peer of the sibling
5556 // [`supervisor_max_restarts_cap_pins_canonical_value`]
5557 // upper-bracket pin on the same axis.
5558 assert_eq!(SUPERVISOR_MAX_RESTARTS_DEFAULT, 5);
5559 }
5560
5561 #[test]
5562 fn default_max_restarts_helper_routes_through_lifted_default() {
5563 // Composition pin: the private `default_max_restarts()`
5564 // serde-`#[serde(default = "…")]` helper on
5565 // [`SupervisorSpec::max_restarts`] must route through the
5566 // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
5567 // typed `pub const` rather than a raw `5` literal. Prior to
5568 // the lift the helper carried an inline `5` with no compile-
5569 // time link back to the shared default, so the wire-format
5570 // author-omitted arm and the caixa-core
5571 // [`crate::manifest::Caixa::supervisor_view`] fold's `unwrap_or(5)`
5572 // arm could silently split on any future default rebrand.
5573 // Byte-parity against the lifted constant closes the split.
5574 assert_eq!(default_max_restarts(), SUPERVISOR_MAX_RESTARTS_DEFAULT);
5575 }
5576
5577 #[test]
5578 fn supervisor_spec_default_max_restarts_routes_through_lifted_default() {
5579 // Composition pin: the [`Default for SupervisorSpec`] impl's
5580 // struct-literal `max_restarts` field must route through the
5581 // substrate-canonical [`SUPERVISOR_MAX_RESTARTS_DEFAULT`]
5582 // typed `pub const` (via the private helper this test's
5583 // sibling `default_max_restarts_helper_routes_through_lifted_default`
5584 // already pins onto the constant). Structurally: every
5585 // `SupervisorSpec::default()` call must yield a
5586 // `max_restarts` field byte-equal to the lifted constant
5587 // (the two paired defaults — the serde-side wire-format arm
5588 // and the struct-literal default arm — cannot silently split
5589 // on any future default rebrand). Peer of the sibling
5590 // `default_has_one_for_one_and_5_restarts_in_60s` shape pin
5591 // — this pin closes the byte-parity arm on the two paired
5592 // altitude entry points onto the shared substrate constant.
5593 assert_eq!(
5594 SupervisorSpec::default().max_restarts(),
5595 SUPERVISOR_MAX_RESTARTS_DEFAULT,
5596 );
5597 }
5598
5599 #[test]
5600 fn supervisor_restart_window_default_pins_otp_canonical_value() {
5601 // Pin [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] at `60s` — the
5602 // Erlang/OTP-canonical `{intensity, 5, 60}` `Period` half of
5603 // Learn You Some Erlang's worker-supervisor default, paired
5604 // with the sibling `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5`
5605 // `MaxIntensity` half this constant is the sliding-window
5606 // denominator of on the same `MaxIntensity / Period`
5607 // restart-intensity ratio. Pinning the literal here surfaces a
5608 // future coherent rebrand of the paired default (Elixir's
5609 // `{max_restarts: 3, max_seconds: 5}`, a per-cluster overlay
5610 // the operator pins through a future
5611 // `:restart-window-overrides` slot) as a deliberate test edit,
5612 // not a silent contract migration. Peer of the sibling
5613 // [`supervisor_max_restarts_default_pins_otp_canonical_value`]
5614 // paired-half pin on the same OTP-canonical default and the
5615 // [`supervisor_restart_window_cap_pins_canonical_value`]
5616 // upper-bracket pin on the same axis.
5617 assert_eq!(SUPERVISOR_RESTART_WINDOW_DEFAULT, Duration::from_secs(60),);
5618 }
5619
5620 #[test]
5621 fn supervisor_spec_default_restart_window_routes_through_lifted_default() {
5622 // Composition pin: the [`Default for SupervisorSpec`] impl's
5623 // struct-literal `restart_window` field must route through the
5624 // substrate-canonical [`SUPERVISOR_RESTART_WINDOW_DEFAULT`]
5625 // typed `pub const` rather than a raw
5626 // `Duration::from_secs(60)` literal. Prior to this lift the
5627 // paired `{intensity, 5, 60}` OTP-canonical default was split
5628 // across two altitudes with no compile-time link between the
5629 // halves — the `MaxIntensity` half rode through the lifted
5630 // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] constant while the
5631 // `Period` half rode as an open-coded literal at the
5632 // composition site, so a future coherent rebrand of the paired
5633 // canonical would have had to migrate one half through the
5634 // constant and the other through a raw literal in lockstep.
5635 // Byte-parity against the lifted constant on the `Period` half
5636 // closes the split — the paired OTP-canonical default now
5637 // migrates as one unit on any future axis change. Peer of the
5638 // sibling
5639 // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
5640 // byte-parity pin on the paired `MaxIntensity` half.
5641 assert_eq!(
5642 SupervisorSpec::default().restart_window(),
5643 Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
5644 );
5645 }
5646
5647 #[test]
5648 fn supervisor_estrategia_default_pins_otp_canonical_value() {
5649 // Pin [`SUPERVISOR_ESTRATEGIA_DEFAULT`] at [`RestartStrategy::OneForOne`]
5650 // — the Erlang/OTP-canonical `one_for_one` half of Learn You Some
5651 // Erlang's `{one_for_one, intensity, 5, 60}` worker-supervisor
5652 // canonical default, paired with the sibling
5653 // `SUPERVISOR_MAX_RESTARTS_DEFAULT` `5` `MaxIntensity` half and the
5654 // sibling `SUPERVISOR_RESTART_WINDOW_DEFAULT` `60s` `Period` half
5655 // this constant is the strategy discriminator of on the same
5656 // OTP-canonical worker-supervisor default. Pinning the arm here
5657 // surfaces a future coherent rebrand of the paired triple (Elixir's
5658 // `{:one_for_one, max_restarts: 3, max_seconds: 5}` on the sibling
5659 // intensity/period axes leaving this strategy arm untouched, an OTP
5660 // `rest_for_one` widening once the substrate discovers startup-
5661 // order-coupled child cohorts as the more common worker-supervisor
5662 // shape, a per-cluster overlay the operator pins through a future
5663 // `:estrategia-overrides` slot the MESH-COMPOSITION §III.2
5664 // supervision-canary roadmap acknowledges) as a deliberate test
5665 // edit, not a silent contract migration. Peer of the sibling
5666 // [`supervisor_max_restarts_default_pins_otp_canonical_value`] +
5667 // [`supervisor_restart_window_default_pins_otp_canonical_value`]
5668 // paired-half pins on the same OTP-canonical default.
5669 assert_eq!(SUPERVISOR_ESTRATEGIA_DEFAULT, RestartStrategy::OneForOne);
5670 }
5671
5672 #[test]
5673 fn restart_strategy_default_routes_through_lifted_default() {
5674 // Composition pin: the [`Default for RestartStrategy`] impl's
5675 // return arm must route through the substrate-canonical
5676 // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
5677 // a raw `Self::OneForOne` arm. Prior to the lift the impl carried
5678 // an inline `Self::OneForOne` with no compile-time link back to
5679 // the shared OTP-canonical `one_for_one` strategy the paired
5680 // [`Default for SupervisorSpec`] impl's struct-literal `estrategia`
5681 // field and the [`crate::manifest::Caixa::supervisor_view`] fold's
5682 // `.unwrap_or_default()` (now
5683 // `.unwrap_or(SUPERVISOR_ESTRATEGIA_DEFAULT)`) arm both key off —
5684 // so a future rebrand of the OTP-canonical strategy default (an
5685 // OTP `rest_for_one` widening once the substrate discovers
5686 // startup-order-coupled child cohorts as the more common worker-
5687 // supervisor shape, a per-cluster overlay the operator pins
5688 // through a future `:estrategia-overrides` slot) would have had to
5689 // be threaded through the `Default` impl and the two peer routes
5690 // in lockstep or the three consumers would silently split. Byte-
5691 // parity against the lifted constant closes the split. Peer of
5692 // the sibling
5693 // [`default_max_restarts_helper_routes_through_lifted_default`] +
5694 // [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
5695 // composition pins on the paired `MaxIntensity` + `Period` halves.
5696 assert_eq!(RestartStrategy::default(), SUPERVISOR_ESTRATEGIA_DEFAULT,);
5697 }
5698
5699 #[test]
5700 fn supervisor_spec_default_estrategia_routes_through_lifted_default() {
5701 // Composition pin: the [`Default for SupervisorSpec`] impl's
5702 // struct-literal `estrategia` field must route through the
5703 // substrate-canonical [`SUPERVISOR_ESTRATEGIA_DEFAULT`] typed
5704 // `pub const` (either directly, or via the
5705 // [`RestartStrategy::default`] impl that the sibling
5706 // `restart_strategy_default_routes_through_lifted_default` pin
5707 // already routes onto the constant). Structurally: every
5708 // `SupervisorSpec::default()` call must yield an `estrategia`
5709 // field byte-equal to the lifted constant (the three paired
5710 // defaults — the [`Default for RestartStrategy`] impl arm, the
5711 // struct-literal default arm here, and the
5712 // [`crate::manifest::Caixa::supervisor_view`] fold arm — cannot
5713 // silently split on any future default rebrand). Peer of the
5714 // sibling
5715 // [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
5716 // + [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
5717 // byte-parity pins on the paired `MaxIntensity` + `Period` halves
5718 // of the same `SupervisorSpec::default()` composed altitude.
5719 assert_eq!(
5720 SupervisorSpec::default().estrategia(),
5721 SUPERVISOR_ESTRATEGIA_DEFAULT,
5722 );
5723 }
5724
5725 #[test]
5726 fn supervisor_spec_default_routes_through_otp_canonical_ctor() {
5727 // Composition pin: the [`Default for SupervisorSpec`] impl must
5728 // route through the substrate-canonical
5729 // [`SupervisorSpec::otp_canonical`] `pub const fn` constructor
5730 // rather than a re-hand-authored struct-literal cascade. Sharpens
5731 // the sibling per-arm
5732 // `supervisor_spec_default_*_routes_through_lifted_default` pins
5733 // from a per-field lift into a whole-struct one-source-of-truth
5734 // pin — the derived-until-now [`Default::default`] and the
5735 // [`SupervisorSpec::otp_canonical`] constructor are byte-equal by
5736 // construction, not by coincidence.
5737 //
5738 // A future extension of the OTP-canonical baseline (a fifth
5739 // `restart_intensity` field the Erlang/OTP `#supervisor` record
5740 // grows, a per-child-cohort split of the `restart_window` /
5741 // `max_restarts` pair, an M4 `mesh.pleme.io/v1alpha1/Supervisor`
5742 // CR materializer's admission-time overlay pass) reaches both
5743 // paths through exactly one edit on
5744 // [`SupervisorSpec::otp_canonical`] — the derived path could
5745 // silently disagree with the constructor's shape on any new
5746 // field whose [`Default::default`] resolves to a different arm
5747 // than the OTP-canonical baseline the constructor names, while
5748 // this delegated impl reaches the constructor directly and
5749 // picks up every future extension by construction.
5750 //
5751 // Fourth peer on the M2 / M3 typed-slot-spec
5752 // [`Default`]-through-const-ctor fold family — sibling of the
5753 // [`crate::LimitsSpec`] [`Default`]-through-[`crate::LimitsSpec::empty`]
5754 // (abd52c2), [`crate::aplicacao::MeshPolicy`]
5755 // [`Default`]-through-[`crate::aplicacao::MeshPolicy::empty`]
5756 // (91641a4), and [`crate::BehaviorSpec`]
5757 // [`Default`]-through-[`crate::BehaviorSpec::empty`] (0c1752c)
5758 // per-`Option`-only-typed-slot folds — extended here onto the
5759 // M2 supervisor-slot [`SupervisorSpec`] whose canonical baseline
5760 // is not "everything `None`" but the Erlang/OTP-canonical
5761 // `{one_for_one, 5, 60}` worker-supervisor triple.
5762 assert_eq!(SupervisorSpec::default(), SupervisorSpec::otp_canonical());
5763 }
5764
5765 #[test]
5766 fn supervisor_spec_otp_canonical_byte_equals_default() {
5767 // Value pin: [`SupervisorSpec::otp_canonical`] must byte-equal
5768 // the hand-authored `{one_for_one, 5, 60, []}` OTP-canonical
5769 // baseline the sibling `default_has_one_for_one_and_5_restarts_in_60s`
5770 // pin already asserts against the [`Default::default`] path.
5771 // Sharpens the pair-invariant into a per-constructor pin so a
5772 // future extension of [`SupervisorSpec`] with a fifth field
5773 // whose OTP-canonical shape is non-`Default::default`-equivalent
5774 // trips at caixa-core test time rather than at a downstream
5775 // consumer that composed [`SupervisorSpec::otp_canonical`] with
5776 // [`SupervisorSpec::validate`] as its "canonical baseline
5777 // seed".
5778 let canonical = SupervisorSpec::otp_canonical();
5779 assert_eq!(canonical.estrategia, RestartStrategy::OneForOne);
5780 assert_eq!(canonical.max_restarts, 5);
5781 assert_eq!(canonical.restart_window, Some(Duration::from_secs(60)));
5782 assert!(canonical.children.is_empty());
5783 }
5784
5785 #[test]
5786 fn supervisor_spec_otp_canonical_is_usable_in_const_context() {
5787 // Const-context pin: [`SupervisorSpec::otp_canonical`] must
5788 // remain callable from a `const`-bound position so downstream
5789 // `const`-context callers wanting a canonical OTP-baseline seed
5790 // can construct one at compile time without runtime dispatch on
5791 // the derived [`Default::default`]. Peer of the sibling
5792 // `pub const fn` [`crate::LimitsSpec::empty`] /
5793 // [`crate::aplicacao::MeshPolicy::empty`] /
5794 // [`crate::BehaviorSpec::empty`] constructors on the sibling
5795 // typed-slot-spec `pub const fn` axis. If a future edit breaks
5796 // the `const`-eligibility of [`SupervisorSpec::otp_canonical`]
5797 // (a non-`const` field-default helper, a non-`const`-stable
5798 // container type promotion), this evaluation fails at
5799 // build time on this file rather than at a downstream
5800 // `const`-context call site.
5801 const CANONICAL: SupervisorSpec = SupervisorSpec::otp_canonical();
5802 assert_eq!(CANONICAL.estrategia, SUPERVISOR_ESTRATEGIA_DEFAULT);
5803 assert_eq!(CANONICAL.max_restarts, SUPERVISOR_MAX_RESTARTS_DEFAULT);
5804 assert_eq!(
5805 CANONICAL.restart_window,
5806 Some(SUPERVISOR_RESTART_WINDOW_DEFAULT),
5807 );
5808 assert!(CANONICAL.children.is_empty());
5809 }
5810
5811 #[test]
5812 fn supervisor_child_restart_default_pins_otp_canonical_value() {
5813 // Pin [`SUPERVISOR_CHILD_RESTART_DEFAULT`] at
5814 // [`RestartPolicy::Permanent`] — Erlang/OTP's `permanent`
5815 // worker-child restart type (`{ChildId, StartFunc, permanent, …}`
5816 // in a `supervisor`'s `init/1` child-spec tuple), the per-child
5817 // half of the same OTP-shape supervisor-tree default set whose
5818 // per-`:supervisor` halves the sibling
5819 // [`SUPERVISOR_ESTRATEGIA_DEFAULT`] /
5820 // [`SUPERVISOR_MAX_RESTARTS_DEFAULT`] /
5821 // [`SUPERVISOR_RESTART_WINDOW_DEFAULT`] constants pin. Pinning the
5822 // arm here surfaces a future rebrand of the per-child default (an
5823 // OTP-`transient` widening once the substrate discovers clean-
5824 // completion-aware children as the more common child shape, a
5825 // per-cluster overlay the operator pins through a future
5826 // `:restart-overrides` slot the MESH-COMPOSITION §III.2
5827 // supervision-canary roadmap acknowledges) as a deliberate test
5828 // edit, not a silent contract migration. Peer of the sibling
5829 // [`supervisor_estrategia_default_pins_otp_canonical_value`] /
5830 // [`supervisor_max_restarts_default_pins_otp_canonical_value`] /
5831 // [`supervisor_restart_window_default_pins_otp_canonical_value`]
5832 // value pins on the per-`:supervisor` halves.
5833 assert_eq!(SUPERVISOR_CHILD_RESTART_DEFAULT, RestartPolicy::Permanent);
5834 }
5835
5836 #[test]
5837 fn restart_policy_default_routes_through_lifted_default() {
5838 // Composition pin: the [`Default for RestartPolicy`] impl's return
5839 // arm must route through the substrate-canonical
5840 // [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const` rather
5841 // than a raw `Self::Permanent` arm. Prior to the lift the impl
5842 // carried an inline `Self::Permanent` with no compile-time link
5843 // back to the OTP-shape supervisor-tree default set whose three
5844 // per-`:supervisor` halves already rode through lifted constants
5845 // — so a future coherent rebrand of the set would have had to
5846 // migrate three halves through typed constants and this fourth
5847 // through a raw enum arm in lockstep or the supervisor-level and
5848 // child-level defaults would silently drift apart. Byte-parity
5849 // against the lifted constant closes the split. Peer of the
5850 // sibling
5851 // [`restart_strategy_default_routes_through_lifted_default`]
5852 // composition pin on the per-`:supervisor` `:estrategia` axis.
5853 assert_eq!(RestartPolicy::default(), SUPERVISOR_CHILD_RESTART_DEFAULT);
5854 }
5855
5856 #[test]
5857 fn child_spec_serde_default_restart_routes_through_lifted_default() {
5858 // Composition pin: the serde-side `#[serde(default)]` on
5859 // [`ChildSpec::restart`] — the wire-format author-omitted
5860 // `:children :restart` arm — must resolve onto the substrate-
5861 // canonical [`SUPERVISOR_CHILD_RESTART_DEFAULT`] typed `pub const`
5862 // (via the [`Default for RestartPolicy`] impl the sibling
5863 // `restart_policy_default_routes_through_lifted_default` pin
5864 // already routes onto the constant). Structurally: a `ChildSpec`
5865 // deserialized from a payload that omits the `restart` key must
5866 // yield a `restart` field byte-equal to the lifted constant, so
5867 // the wire-format author-omitted arm and the
5868 // [`RestartPolicy::default`] impl arm cannot silently split on any
5869 // future default rebrand. Peer of the sibling
5870 // [`supervisor_spec_default_estrategia_routes_through_lifted_default`]
5871 // / [`supervisor_spec_default_max_restarts_routes_through_lifted_default`]
5872 // / [`supervisor_spec_default_restart_window_routes_through_lifted_default`]
5873 // byte-parity pins on the per-`:supervisor` halves of the same
5874 // author-omitted-slot resolution surface.
5875 let omitted: ChildSpec = serde_json::from_str(r#"{"caixa":"worker","versao":"^0.1"}"#)
5876 .expect("ChildSpec must deserialize with the restart key omitted");
5877 assert_eq!(
5878 omitted.restart(),
5879 SUPERVISOR_CHILD_RESTART_DEFAULT,
5880 "an author-omitted :children :restart slot must degrade onto \
5881 the SUPERVISOR_CHILD_RESTART_DEFAULT typed pub const (got \
5882 {:?}, expected {:?})",
5883 omitted.restart(),
5884 SUPERVISOR_CHILD_RESTART_DEFAULT,
5885 );
5886 }
5887
5888 #[test]
5889 fn supervisor_max_restarts_cap_pins_canonical_value() {
5890 // The SUPERVISOR_MAX_RESTARTS_MAX constant pins the value at
5891 // 1000 — the same ceiling the peer
5892 // POLICY_BREAKER_MAX_FAILURES_MAX cap carries on the
5893 // `:politicas :circuit-breaker :max-failures` axis (both are
5894 // "trip the next-higher protection layer after N events in a
5895 // rolling window" counters with identical
5896 // degenerate-at-the-high-end shape; uniform top edge so the
5897 // M4 CR materializers and the wasm-operator reconciler reach
5898 // for either field knowing the value is in `1..=1000`). Two
5899 // orders of magnitude above every documented Erlang/OTP /
5900 // Elixir / Riak Core / RabbitMQ production-playbook
5901 // recommendation band and below the clearly-pathological
5902 // "effectively no escalation" floor (10_000, 100_000,
5903 // u32::MAX). Pinning the literal value here surfaces a future
5904 // drift (a relaxation to 10_000, a tightening to 100) as a
5905 // deliberate test edit, not a silent contract narrowing.
5906 assert_eq!(SUPERVISOR_MAX_RESTARTS_MAX, 1000);
5907 }
5908
5909 #[test]
5910 fn validate_rejects_empty_child_name() {
5911 let s = SupervisorSpec {
5912 children: vec![child("", "^0.1", RestartPolicy::Permanent)],
5913 ..SupervisorSpec::default()
5914 };
5915 assert_eq!(s.validate().unwrap_err(), SupervisorError::EmptyChildName);
5916 }
5917
5918 #[test]
5919 fn validate_rejects_empty_child_version() {
5920 let s = SupervisorSpec {
5921 children: vec![child("w", "", RestartPolicy::Permanent)],
5922 ..SupervisorSpec::default()
5923 };
5924 assert!(matches!(
5925 s.validate().unwrap_err(),
5926 SupervisorError::EmptyChildVersion { .. }
5927 ));
5928 }
5929
5930 // ── value-shape: parse-as-VersionReq on :children :versao ─────────────
5931
5932 #[test]
5933 fn validate_rejects_invalid_child_versao_requirement() {
5934 // The fail-before-pass-after pin: a non-empty but malformed
5935 // semver requirement (`"^bad-version"`) silently passed
5936 // `validate()` on every pre-gate codebase because the prior
5937 // shape only refused the empty string. The parse failure
5938 // surfaced far downstream at lacre-resolve time with a
5939 // `semver::Error` that didn't name which `:children` entry
5940 // carried the typo. The new gate moves the check to caixa-build
5941 // time at the source caixa.lisp — the third `:versao` typed
5942 // axis (`:children`) joins `:deps` and `:membros` (9888b13) at
5943 // structural parity.
5944 let s = SupervisorSpec {
5945 children: vec![
5946 child("worker", "^0.1", RestartPolicy::Permanent),
5947 child("cache", "^bad-version", RestartPolicy::Transient),
5948 ],
5949 ..SupervisorSpec::default()
5950 };
5951 let err = s.validate().unwrap_err();
5952 assert!(
5953 matches!(
5954 err,
5955 SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
5956 if caixa == "cache" && versao == "^bad-version"
5957 ),
5958 "got {err:?}"
5959 );
5960 }
5961
5962 #[test]
5963 fn validate_rejects_child_versao_with_double_caret_typo() {
5964 // `"^^0.1"` is the canonical doubled-caret typo — looks
5965 // Cargo-shaped on first glance but fails the parser because
5966 // semver doesn't accept stacked operators. Pin this
5967 // adjacent-shape footgun explicitly so a future relaxation that
5968 // accepts "looks-canonical-but-isn't" forms surfaces here.
5969 let s = SupervisorSpec {
5970 children: vec![child("worker", "^^0.1", RestartPolicy::Permanent)],
5971 ..SupervisorSpec::default()
5972 };
5973 let err = s.validate().unwrap_err();
5974 assert!(
5975 matches!(
5976 err,
5977 SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
5978 if caixa == "worker" && versao == "^^0.1"
5979 ),
5980 "got {err:?}"
5981 );
5982 }
5983
5984 #[test]
5985 fn validate_rejects_child_versao_with_v_prefixed_tag() {
5986 // `"v0.1"` is the canonical "git-tag-shape leaking into the
5987 // semver requirement slot" typo — an author copies the
5988 // publish-side git-tag string verbatim into `:versao`, but
5989 // Cargo's semver parser rejects the leading `v`. Same
5990 // adjacent-shape footgun pinned for `:membros :versao`
5991 // (9888b13).
5992 let s = SupervisorSpec {
5993 children: vec![child("worker", "v0.1", RestartPolicy::Permanent)],
5994 ..SupervisorSpec::default()
5995 };
5996 let err = s.validate().unwrap_err();
5997 assert!(
5998 matches!(
5999 err,
6000 SupervisorError::ChildVersaoInvalid { ref caixa, ref versao, .. }
6001 if caixa == "worker" && versao == "v0.1"
6002 ),
6003 "got {err:?}"
6004 );
6005 }
6006
6007 #[test]
6008 fn validate_accepts_canonical_child_versao_forms() {
6009 // The Cargo-shaped requirement forms `:deps :versao` and
6010 // `:membros :versao` already accept via
6011 // `crate::parse_requirement` must pass the children gate
6012 // without re-validating at the resolver layer. Pin every leg so
6013 // a future tightening of the canonical set surfaces here as a
6014 // test failure.
6015 for form in [
6016 "^0.1", // caret — minor-range pin (the most common shape)
6017 "~0.1.2", // tilde — patch-range pin
6018 "0.1.0", // exact — single-version pin
6019 "*", // wildcard — any version (semver::VersionReq::STAR)
6020 ">=0.1, <2", // multi-range — comma-separated comparators
6021 ] {
6022 let s = SupervisorSpec {
6023 children: vec![child("worker", form, RestartPolicy::Permanent)],
6024 ..SupervisorSpec::default()
6025 };
6026 s.validate()
6027 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
6028 }
6029 }
6030
6031 #[test]
6032 fn child_versao_empty_takes_precedence_over_invalid() {
6033 // Order pin: the existing `EmptyChildVersion` diagnostic (which
6034 // doesn't try to parse) fires before the new
6035 // `ChildVersaoInvalid` parse-side diagnostic, so an empty
6036 // `:versao` keeps its narrower error message —
6037 // `parse_requirement` would also reject `""`, but the
6038 // empty-string arm is the more self-locating diagnostic for the
6039 // author. Same ordering discipline as
6040 // `membro_versao_empty_takes_precedence_over_invalid` in
6041 // aplicacao.rs.
6042 let s = SupervisorSpec {
6043 children: vec![child("worker", "", RestartPolicy::Permanent)],
6044 ..SupervisorSpec::default()
6045 };
6046 let err = s.validate().unwrap_err();
6047 assert!(
6048 matches!(err, SupervisorError::EmptyChildVersion { ref caixa } if caixa == "worker"),
6049 "got {err:?}"
6050 );
6051 }
6052
6053 #[test]
6054 fn child_versao_invalid_fires_before_duplicate_check() {
6055 // Order pin: a malformed requirement on a non-duplicate entry
6056 // surfaces *its own* diagnostic (which names the offending
6057 // `:versao` string), even when a later entry would otherwise
6058 // collapse onto an earlier name. The per-entry shape gate runs
6059 // inline before the duplicate-key insert — parallel to
6060 // `membro_versao_invalid_fires_before_duplicate_check` in
6061 // aplicacao.rs and the b0c8389 / c4213a4 ordering discipline.
6062 let s = SupervisorSpec {
6063 children: vec![
6064 child("worker", "^bad", RestartPolicy::Permanent),
6065 child("cache", "^0.1", RestartPolicy::Transient),
6066 child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
6067 ],
6068 ..SupervisorSpec::default()
6069 };
6070 let err = s.validate().unwrap_err();
6071 assert!(
6072 matches!(
6073 err,
6074 SupervisorError::ChildVersaoInvalid { ref caixa, .. } if caixa == "worker"
6075 ),
6076 "got {err:?}"
6077 );
6078 }
6079
6080 #[test]
6081 fn child_versao_invalid_diagnostic_carries_offending_versao() {
6082 // The diagnostic-shape pin: the error names the offending
6083 // `:versao` value verbatim so the author can grep their
6084 // caixa.lisp without re-running the build, and carries a
6085 // non-empty `reason` from `semver::VersionReq::parse` so the
6086 // parser's own wording flows through to the diagnostic.
6087 let s = SupervisorSpec {
6088 children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
6089 ..SupervisorSpec::default()
6090 };
6091 let err = s.validate().unwrap_err();
6092 let SupervisorError::ChildVersaoInvalid {
6093 caixa,
6094 versao,
6095 reason,
6096 } = err
6097 else {
6098 panic!("expected ChildVersaoInvalid, got other variant");
6099 };
6100 assert_eq!(caixa, "worker");
6101 assert_eq!(versao, "not-a-req");
6102 assert!(
6103 !reason.is_empty(),
6104 "ChildVersaoInvalid `reason` must carry the parser's wording verbatim"
6105 );
6106 }
6107
6108 // ── value-shape: DNS-1123 label rule on :children :caixa ──────────────
6109
6110 #[test]
6111 fn validate_rejects_child_caixa_with_uppercase() {
6112 // The canonical "I copied the Servico's display name verbatim"
6113 // typo — child caixa names are lowercase per K8s DNS-1123 label
6114 // rule. The diagnostic names the offending name and suggests the
6115 // lower-cased fix in one edit, mirroring the
6116 // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0).
6117 let s = SupervisorSpec {
6118 children: vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
6119 ..SupervisorSpec::default()
6120 };
6121 let err = s.validate().unwrap_err();
6122 let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
6123 panic!("expected ChildCaixaInvalid, got other variant");
6124 };
6125 assert_eq!(caixa, "Worker");
6126 assert!(
6127 reason.contains("uppercase"),
6128 "diagnostic must name the violation as `uppercase` (got: {reason:?})"
6129 );
6130 assert!(
6131 reason.contains("\"worker\""),
6132 "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
6133 );
6134 }
6135
6136 #[test]
6137 fn validate_rejects_child_caixa_with_underscore() {
6138 // The canonical "I'm thinking of a Python module / Postgres
6139 // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
6140 // label schema. K8s rejects `metadata.name: my_worker` at
6141 // admission time with an opaque `field is invalid` (no source-
6142 // citing diagnostic). The gate moves it to caixa-build time.
6143 let s = SupervisorSpec {
6144 children: vec![child("my_worker", "^0.1", RestartPolicy::Permanent)],
6145 ..SupervisorSpec::default()
6146 };
6147 let err = s.validate().unwrap_err();
6148 assert!(
6149 matches!(
6150 err,
6151 SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
6152 if caixa == "my_worker" && reason.contains('_')
6153 ),
6154 "got {err:?}"
6155 );
6156 }
6157
6158 #[test]
6159 fn validate_rejects_child_caixa_with_dot() {
6160 // A `:children :caixa` entry is a single DNS-1123 label, not a
6161 // subdomain. The K8s Service / ComputeUnit `metadata.name` rules
6162 // forbid dots. Same shape as `rejects_membro_caixa_with_dot`
6163 // (3f9d7a0) on the peer name axis.
6164 let s = SupervisorSpec {
6165 children: vec![child("team.worker", "^0.1", RestartPolicy::Permanent)],
6166 ..SupervisorSpec::default()
6167 };
6168 let err = s.validate().unwrap_err();
6169 assert!(
6170 matches!(
6171 err,
6172 SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
6173 if caixa == "team.worker" && reason.contains('.')
6174 ),
6175 "got {err:?}"
6176 );
6177 }
6178
6179 #[test]
6180 fn validate_rejects_child_caixa_with_leading_hyphen() {
6181 // DNS-1123 / DNS-1035 boundary rule: labels must start and end
6182 // with an alphanumeric. The K8s apiserver rejects `-worker`
6183 // outright; the renderer would emit a `metadata.name: "-worker"`
6184 // that fails admission far from the source caixa.lisp.
6185 let s = SupervisorSpec {
6186 children: vec![child("-worker", "^0.1", RestartPolicy::Permanent)],
6187 ..SupervisorSpec::default()
6188 };
6189 let err = s.validate().unwrap_err();
6190 assert!(
6191 matches!(
6192 err,
6193 SupervisorError::ChildCaixaInvalid { ref caixa, ref reason }
6194 if caixa == "-worker" && reason.contains("start and end")
6195 ),
6196 "got {err:?}"
6197 );
6198 }
6199
6200 #[test]
6201 fn validate_rejects_child_caixa_with_trailing_hyphen() {
6202 // The symmetric arm of the boundary rule. Pin separately so
6203 // both ends of the label are covered against a future relaxation
6204 // that only checks one boundary.
6205 let s = SupervisorSpec {
6206 children: vec![child("worker-", "^0.1", RestartPolicy::Permanent)],
6207 ..SupervisorSpec::default()
6208 };
6209 let err = s.validate().unwrap_err();
6210 assert!(
6211 matches!(
6212 err,
6213 SupervisorError::ChildCaixaInvalid { ref caixa, .. }
6214 if caixa == "worker-"
6215 ),
6216 "got {err:?}"
6217 );
6218 }
6219
6220 #[test]
6221 fn validate_rejects_child_caixa_with_unicode() {
6222 // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
6223 // (`xn--…`) by the author before it reaches K8s. The byte-by-
6224 // byte ASCII validity check rejects multi-byte UTF-8 sequences
6225 // by the first byte that fails the `[a-z0-9-]` predicate.
6226 let s = SupervisorSpec {
6227 children: vec![child("café", "^0.1", RestartPolicy::Permanent)],
6228 ..SupervisorSpec::default()
6229 };
6230 let err = s.validate().unwrap_err();
6231 assert!(
6232 matches!(
6233 err,
6234 SupervisorError::ChildCaixaInvalid { ref caixa, .. }
6235 if caixa == "café"
6236 ),
6237 "got {err:?}"
6238 );
6239 }
6240
6241 #[test]
6242 fn validate_rejects_child_caixa_with_whitespace() {
6243 // Whitespace is the canonical "I pasted from a sketch / doc"
6244 // footgun. The apiserver rejects every `metadata.name` value
6245 // carrying whitespace; pin the gate fires at the right boundary.
6246 let s = SupervisorSpec {
6247 children: vec![child("my worker", "^0.1", RestartPolicy::Permanent)],
6248 ..SupervisorSpec::default()
6249 };
6250 let err = s.validate().unwrap_err();
6251 assert!(
6252 matches!(
6253 err,
6254 SupervisorError::ChildCaixaInvalid { ref caixa, .. }
6255 if caixa == "my worker"
6256 ),
6257 "got {err:?}"
6258 );
6259 }
6260
6261 #[test]
6262 fn validate_rejects_child_caixa_too_long() {
6263 // The 64-byte boundary pin. DNS-1123 / DNS-1035 cap labels at
6264 // 63 bytes; the K8s apiserver rejects every `metadata.name`
6265 // axis over the limit at admission time. The diagnostic names
6266 // both the cap and the actual length so the author can shorten
6267 // in one edit, mirroring `rejects_membro_caixa_too_long`
6268 // (3f9d7a0) and `rejects_placement_cluster_too_long` (6cbb900).
6269 let too_long = "a".repeat(64);
6270 let s = SupervisorSpec {
6271 children: vec![child(&too_long, "^0.1", RestartPolicy::Permanent)],
6272 ..SupervisorSpec::default()
6273 };
6274 let err = s.validate().unwrap_err();
6275 let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
6276 panic!("expected ChildCaixaInvalid, got other variant");
6277 };
6278 assert_eq!(caixa, too_long);
6279 assert!(
6280 reason.contains("63"),
6281 "diagnostic must name the 63-byte cap (got: {reason:?})"
6282 );
6283 assert!(
6284 reason.contains("64"),
6285 "diagnostic must name the actual length (got: {reason:?})"
6286 );
6287 }
6288
6289 #[test]
6290 fn child_caixa_max_length_validates() {
6291 // The 63-byte boundary control pin — exactly-at-the-cap is
6292 // accepted, mirroring `membro_caixa_max_length_validates`
6293 // (3f9d7a0) and `placement_cluster_max_length_validates`
6294 // (6cbb900). Pinned separately so a future off-by-one tightening
6295 // surfaces here.
6296 let max_label = "a".repeat(63);
6297 let s = SupervisorSpec {
6298 children: vec![child(&max_label, "^0.1", RestartPolicy::Permanent)],
6299 ..SupervisorSpec::default()
6300 };
6301 s.validate().unwrap();
6302 }
6303
6304 #[test]
6305 fn validate_accepts_canonical_child_caixa_forms() {
6306 // The realistic shapes a supervised child's `:caixa` carries —
6307 // single-word `worker`, version-suffixed `cache-v2`, single-char
6308 // `a`, two-char `db`, digit-start `2-pool`, longer hyphen-joined
6309 // `payment-retry`, all-digit `0`. Pin every leg so a future
6310 // tightening (e.g. requiring a leading lowercase letter) surfaces
6311 // here as a test failure. Mirrors `accepts_canonical_membro_caixa_forms`
6312 // (3f9d7a0) and `accepts_canonical_placement_cluster_forms`
6313 // (6cbb900).
6314 for form in [
6315 "worker",
6316 "cache-v2",
6317 "a",
6318 "db",
6319 "2-pool",
6320 "payment-retry",
6321 "0",
6322 ] {
6323 let s = SupervisorSpec {
6324 children: vec![child(form, "^0.1", RestartPolicy::Permanent)],
6325 ..SupervisorSpec::default()
6326 };
6327 s.validate()
6328 .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
6329 }
6330 }
6331
6332 #[test]
6333 fn child_caixa_empty_takes_precedence_over_invalid() {
6334 // Order pin: the existing `EmptyChildName` diagnostic (which
6335 // doesn't try to parse the DNS-1123 shape) fires before the new
6336 // `ChildCaixaInvalid` per-axis gate, so an empty `:caixa` keeps
6337 // its narrower error message — `is_dns_1123_label` would reject
6338 // the empty string too (boundary check on the first byte), but
6339 // the empty-string arm is the more self-locating diagnostic for
6340 // the author. Same ordering discipline as
6341 // `membro_caixa_empty_takes_precedence_over_invalid` in
6342 // aplicacao.rs.
6343 let s = SupervisorSpec {
6344 children: vec![child("", "^0.1", RestartPolicy::Permanent)],
6345 ..SupervisorSpec::default()
6346 };
6347 let err = s.validate().unwrap_err();
6348 assert_eq!(err, SupervisorError::EmptyChildName);
6349 }
6350
6351 #[test]
6352 fn child_caixa_invalid_fires_before_versao_check() {
6353 // Order pin: the per-axis shape gate runs inline before the
6354 // per-entry versao check, so a malformed `:caixa` on an entry
6355 // whose `:versao` would also fail surfaces the more self-
6356 // locating name-axis diagnostic first. Parallel to
6357 // `membro_versao_invalid_fires_before_duplicate_check` (9888b13)
6358 // and `placement_cluster_invalid_fires_before_duplicate_check`
6359 // (6cbb900).
6360 let s = SupervisorSpec {
6361 children: vec![child("My_Worker", "", RestartPolicy::Permanent)],
6362 ..SupervisorSpec::default()
6363 };
6364 let err = s.validate().unwrap_err();
6365 assert!(
6366 matches!(
6367 err,
6368 SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "My_Worker"
6369 ),
6370 "got {err:?}"
6371 );
6372 }
6373
6374 #[test]
6375 fn child_caixa_invalid_fires_before_duplicate_check() {
6376 // Order pin: a malformed name on a non-duplicate entry surfaces
6377 // its own diagnostic, even when a later entry would otherwise
6378 // collapse onto an earlier name. The per-entry shape gate runs
6379 // inline before the duplicate-key HashSet insert, mirroring
6380 // `placement_cluster_invalid_fires_before_duplicate_check`
6381 // (6cbb900).
6382 let s = SupervisorSpec {
6383 children: vec![
6384 child("Worker", "^0.1", RestartPolicy::Permanent),
6385 child("cache", "^0.1", RestartPolicy::Transient),
6386 child("worker", "^0.2", RestartPolicy::Permanent), // would otherwise raise DuplicateChildCaixa
6387 ],
6388 ..SupervisorSpec::default()
6389 };
6390 let err = s.validate().unwrap_err();
6391 assert!(
6392 matches!(
6393 err,
6394 SupervisorError::ChildCaixaInvalid { ref caixa, .. } if caixa == "Worker"
6395 ),
6396 "got {err:?}"
6397 );
6398 }
6399
6400 #[test]
6401 fn child_caixa_invalid_diagnostic_carries_offending_caixa() {
6402 // The diagnostic-shape pin: the error names the offending
6403 // `:caixa` verbatim plus a non-empty parser-shaped `reason` so
6404 // the author can grep their caixa.lisp without re-running the
6405 // build. Mirrors the diagnostic-shape sweep on every prior
6406 // value-shape gate (3f9d7a0, 6cbb900, c7d05ec).
6407 let s = SupervisorSpec {
6408 children: vec![child("My_Worker", "^0.1", RestartPolicy::Permanent)],
6409 ..SupervisorSpec::default()
6410 };
6411 let err = s.validate().unwrap_err();
6412 let SupervisorError::ChildCaixaInvalid { caixa, reason } = err else {
6413 panic!("expected ChildCaixaInvalid, got other variant");
6414 };
6415 assert_eq!(caixa, "My_Worker");
6416 assert!(
6417 !reason.is_empty(),
6418 "ChildCaixaInvalid `reason` must carry the parser's wording verbatim"
6419 );
6420 }
6421
6422 // ── value-shape: zero restart_window + duplicate child names ──────────
6423
6424 #[test]
6425 fn validate_accepts_none_restart_window() {
6426 // Omitted `:restart-window` is the "never reset" sentinel —
6427 // valid by design. Mirrors :limits axes where None = unbounded.
6428 let s = SupervisorSpec {
6429 restart_window: None,
6430 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6431 ..SupervisorSpec::default()
6432 };
6433 s.validate().unwrap();
6434 }
6435
6436 #[test]
6437 fn validate_rejects_zero_restart_window() {
6438 // Same "0 means the opposite of what you think" footgun closed
6439 // for :politicas :timeout (Envoy treats 0s as infinite) and
6440 // :limits :wall-clock (wasmtime traps before the call starts).
6441 // Erlang/OTP's MaxIntensity/Period requires Period > 0.
6442 let s = SupervisorSpec {
6443 restart_window: Some(Duration::ZERO),
6444 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6445 ..SupervisorSpec::default()
6446 };
6447 assert_eq!(
6448 s.validate().unwrap_err(),
6449 SupervisorError::RestartWindowZero
6450 );
6451 }
6452
6453 // ── value-shape: integer-ms canonical-form on :restart-window ─────────
6454 //
6455 // The fourth (and last) typed-`Duration` axis in caixa-core to get
6456 // the integer-millisecond canonical-form gate — peer with
6457 // `:limits :wall-clock` (82fc3ef), `:politicas :timeout` (a4ae535),
6458 // and `:politicas :circuit-breaker :window` (a4ae535). The serde
6459 // path is already gated at the shared codec layer (see
6460 // `restart_window_serde_rejects_fractional_seconds`); this arm
6461 // closes the programmatic-struct-literal path the codec gate can't
6462 // see.
6463
6464 #[test]
6465 fn validate_rejects_sub_millisecond_restart_window() {
6466 // The fail-before-pass-after pin: a programmatic
6467 // `Duration::from_micros(1500)` (= 1_500_000 ns) silently passed
6468 // `validate` on every pre-gate codebase, then truncated to
6469 // `as_millis() == 1` on first serialize — the shared codec
6470 // emits `"1ms"`, parses it back to `Duration::from_millis(1)` =
6471 // 1_000_000 ns, the typed `restart_window` no longer matches
6472 // its rendered form.
6473 let s = SupervisorSpec {
6474 restart_window: Some(Duration::from_micros(1500)),
6475 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6476 ..SupervisorSpec::default()
6477 };
6478 match s.validate().unwrap_err() {
6479 SupervisorError::RestartWindowNotCanonical { window } => {
6480 assert_eq!(window, Duration::from_micros(1500));
6481 }
6482 other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
6483 }
6484 }
6485
6486 #[test]
6487 fn validate_rejects_one_nanosecond_restart_window() {
6488 // The far-sub-ms case: `Duration::from_nanos(1)` is non-zero
6489 // (so `RestartWindowZero` doesn't fire) but `as_millis() == 0`,
6490 // so the shared codec emits the literal `"0s"` — the next
6491 // serde round-trip would parse back to `Duration::ZERO`, which
6492 // the `RestartWindowZero` arm then rejects on re-validate. The
6493 // canonical-form gate at this layer surfaces a self-locating
6494 // diagnostic naming the offending Duration verbatim rather
6495 // than a downstream `RestartWindowZero` whose remediation
6496 // points at omitting the slot.
6497 let s = SupervisorSpec {
6498 restart_window: Some(Duration::from_nanos(1)),
6499 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6500 ..SupervisorSpec::default()
6501 };
6502 match s.validate().unwrap_err() {
6503 SupervisorError::RestartWindowNotCanonical { window } => {
6504 assert_eq!(window, Duration::from_nanos(1));
6505 }
6506 other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
6507 }
6508 }
6509
6510 #[test]
6511 fn validate_rejects_nanosecond_past_canonical_boundary_restart_window() {
6512 // The 1-ns-past-1ms boundary case: a `Duration` carrying
6513 // 1_000_001 ns is structurally past the integer-ms granularity
6514 // floor — `subsec_nanos() % 1_000_000 == 1`. The codec round-
6515 // trip would truncate to `1ms` and the consumer would observe
6516 // a 1-ns drift on every emit. Same boundary the peer
6517 // `validate_rejects_nanosecond_past_canonical_boundary` test
6518 // in limits.rs pins for the `:limits :wall-clock` axis.
6519 let w = Duration::from_nanos(1_000_001);
6520 let s = SupervisorSpec {
6521 restart_window: Some(w),
6522 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6523 ..SupervisorSpec::default()
6524 };
6525 assert_eq!(
6526 s.validate().unwrap_err(),
6527 SupervisorError::RestartWindowNotCanonical { window: w }
6528 );
6529 }
6530
6531 #[test]
6532 fn validate_accepts_integer_millisecond_restart_window_values() {
6533 // The positive-control sweep: every `Duration` the shared
6534 // codec can round-trip losslessly — the canonical
6535 // `<integer>{ms,s,m,h}` set the codec's `render` / `parse`
6536 // pair emits and accepts — passes `validate` without
6537 // surfacing the new canonical-form arm. Mirrors
6538 // `validate_accepts_integer_millisecond_wall_clock_values` on
6539 // the sibling `:limits :wall-clock` axis.
6540 for w in [
6541 Duration::from_millis(1),
6542 Duration::from_millis(500),
6543 Duration::from_millis(1500),
6544 Duration::from_secs(1),
6545 Duration::from_secs(30),
6546 Duration::from_secs(60),
6547 Duration::from_secs(120),
6548 Duration::from_secs(3600),
6549 ] {
6550 let s = SupervisorSpec {
6551 restart_window: Some(w),
6552 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6553 ..SupervisorSpec::default()
6554 };
6555 s.validate()
6556 .unwrap_or_else(|e| panic!("integer-ms {w:?} must validate, got {e:?}"));
6557 }
6558 }
6559
6560 #[test]
6561 fn validate_restart_window_zero_takes_precedence_over_canonical_gate() {
6562 // Cross-arm ordering pin: `Duration::ZERO` has
6563 // `subsec_nanos() == 0` and would otherwise pass the
6564 // canonical-form arm — the zero-floor arm must fire first so
6565 // the more self-locating `RestartWindowZero` diagnostic (with
6566 // its omit-axis remediation directly named) leads. Same
6567 // posture every peer zero-then-shape gate uses
6568 // (`WallClockZero` → `WallClockNotCanonical`,
6569 // `PolicyTimeoutZero` → `PolicyTimeoutNotCanonical`,
6570 // `PolicyBreakerZeroWindow` → `PolicyBreakerWindowNotCanonical`).
6571 let s = SupervisorSpec {
6572 restart_window: Some(Duration::ZERO),
6573 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6574 ..SupervisorSpec::default()
6575 };
6576 assert_eq!(
6577 s.validate().unwrap_err(),
6578 SupervisorError::RestartWindowZero
6579 );
6580 }
6581
6582 #[test]
6583 fn restart_window_canonical_diagnostic_carries_offending_duration() {
6584 // Diagnostic-shape pin: the canonical-form arm names the
6585 // offending `Duration` verbatim so the author's grep lands on
6586 // the field's value, not a generic "duration not canonical"
6587 // message. Same shape every other typed-canonical-form arm
6588 // on this surface carries (`WallClockNotCanonical` carries
6589 // the offending `Duration` verbatim,
6590 // `PolicyTimeoutNotCanonical` carries the offending
6591 // `Duration` verbatim).
6592 let w = Duration::from_micros(500);
6593 let s = SupervisorSpec {
6594 restart_window: Some(w),
6595 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6596 ..SupervisorSpec::default()
6597 };
6598 let err = s.validate().unwrap_err();
6599 let msg = err.to_string();
6600 assert!(
6601 msg.contains("500"),
6602 "diagnostic must carry the offending magnitude verbatim (got {msg:?})"
6603 );
6604 assert!(
6605 msg.contains("sub-millisecond"),
6606 "diagnostic must name the sub-millisecond residue class (got {msg:?})"
6607 );
6608 }
6609
6610 #[test]
6611 fn restart_window_validated_value_round_trips_through_codec() {
6612 // The structural property the canonical-ms gate enforces:
6613 // every `SupervisorSpec::restart_window` past
6614 // `SupervisorSpec::validate` round-trips losslessly through
6615 // the shared duration codec (serialize → string →
6616 // deserialize → equal value). Pin this end-to-end so a future
6617 // change to either side (the validate gate's accepted
6618 // granularity, the codec's parse/render unit set) that breaks
6619 // the alignment surfaces here. Peer of
6620 // `wall_clock_validated_value_round_trips_through_codec` on
6621 // the sibling `:limits :wall-clock` axis.
6622 for w in [
6623 Duration::from_millis(1),
6624 Duration::from_millis(1500),
6625 Duration::from_secs(30),
6626 Duration::from_secs(3600),
6627 ] {
6628 let s = SupervisorSpec {
6629 restart_window: Some(w),
6630 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6631 ..SupervisorSpec::default()
6632 };
6633 s.validate().unwrap();
6634 let json = serde_json::to_string(&s).unwrap();
6635 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6636 assert_eq!(back.restart_window, Some(w));
6637 }
6638 }
6639
6640 // ── value-shape: upper cap on :restart-window ─────────────────────────
6641 //
6642 // The fourth (and last) typed-`Duration` axis in caixa-core to get
6643 // the 1h upper cap — peer with `:limits :wall-clock` (51e0dbd),
6644 // `:politicas :timeout` (2e8ee7e), and `:politicas
6645 // :circuit-breaker :window` (379a814). Brackets the typed
6646 // `:restart-window` axis structurally: every validated value lies
6647 // in `1ms..=SUPERVISOR_RESTART_WINDOW_MAX`, integer-millisecond
6648 // granularity, closing the
6649 // rolling-window-degenerates-to-lifetime-counter footgun the prior
6650 // zero-floor-and-canonical-form-only checks left open.
6651
6652 #[test]
6653 fn validate_rejects_restart_window_above_cap() {
6654 // The fail-before-pass-after pin: 3601s = 1h + 1s is
6655 // structurally one canonical-tick past the
6656 // [`SUPERVISOR_RESTART_WINDOW_MAX`] ceiling (1h = 3600s) — an
6657 // integer-millisecond magnitude the canonical-form arm above
6658 // accepts cleanly, that the shared duration codec round-trips
6659 // losslessly as `"3601s"`, and that silently passed validate on
6660 // every pre-gate codebase because the typed slot's only checks
6661 // were the zero-floor and canonical-form arms. The runtime
6662 // substrate consuming the value (Erlang/OTP's MaxIntensity/
6663 // Period reconciler, the future wasm-operator's per-supervisor
6664 // restart-intensity counter) reaches for a `Duration` so long
6665 // no realistic restart-recovery pattern resets the counter,
6666 // far from the source caixa.lisp.
6667 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
6668 let s = SupervisorSpec {
6669 restart_window: Some(w),
6670 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6671 ..SupervisorSpec::default()
6672 };
6673 assert_eq!(
6674 s.validate().unwrap_err(),
6675 SupervisorError::RestartWindowExceedsCap { window: w }
6676 );
6677 }
6678
6679 #[test]
6680 fn validate_rejects_restart_window_one_millisecond_above_cap() {
6681 // Boundary case: exactly 1ms past the cap (the granularity the
6682 // canonical-form gate enforces). Catches a future "strictly
6683 // less than" half-measure and pins the diagnostic to name the
6684 // offending `Duration` verbatim. Peer of
6685 // `validate_rejects_wall_clock_one_millisecond_above_cap` /
6686 // `rejects_policy_timeout_one_millisecond_above_cap` /
6687 // `rejects_circuit_breaker_window_one_millisecond_above_cap`
6688 // on the sibling typed-`Duration` axes' top edges.
6689 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
6690 let s = SupervisorSpec {
6691 restart_window: Some(w),
6692 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6693 ..SupervisorSpec::default()
6694 };
6695 assert_eq!(
6696 s.validate().unwrap_err(),
6697 SupervisorError::RestartWindowExceedsCap { window: w }
6698 );
6699 }
6700
6701 #[test]
6702 fn validate_rejects_restart_window_far_above_cap() {
6703 // The "obvious authoring footgun" case: a `(:restart-window "24h")`,
6704 // `(:restart-window "7d")`, or any "I want a lifetime counter
6705 // but wrote a `<integer>h` magnitude anyway" typo — values the
6706 // canonical-form arm accepts as integer-millisecond magnitudes,
6707 // the codec round-trips losslessly through serde, but the
6708 // operator's `MaxIntensity / Period` reconciler cannot honor
6709 // as a meaningful rolling window. Until this gate landed
6710 // validate accepted them. Pin the common above-cap values (24h,
6711 // 7d, ~11.5d) so a future relaxation that drops the upper bound
6712 // surfaces here.
6713 for w in [
6714 Duration::from_secs(86_400), // 24h
6715 Duration::from_secs(604_800), // 7d
6716 Duration::from_secs(1_000_000), // ~11.5 days
6717 ] {
6718 let s = SupervisorSpec {
6719 restart_window: Some(w),
6720 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6721 ..SupervisorSpec::default()
6722 };
6723 assert_eq!(
6724 s.validate().unwrap_err(),
6725 SupervisorError::RestartWindowExceedsCap { window: w }
6726 );
6727 }
6728 }
6729
6730 #[test]
6731 fn validate_accepts_restart_window_at_cap() {
6732 // The boundary value — exactly [`SUPERVISOR_RESTART_WINDOW_MAX`]
6733 // (1h) — must validate. The cap is inclusive on the top edge,
6734 // matching the [`crate::LIMITS_WALL_CLOCK_MAX`] /
6735 // [`crate::POLICY_TIMEOUT_MAX`] /
6736 // [`crate::POLICY_BREAKER_WINDOW_MAX`] discipline on the sibling
6737 // capped axes. Pin the boundary explicitly so a future
6738 // off-by-one tightening (`>= SUPERVISOR_RESTART_WINDOW_MAX`
6739 // instead of `>`) surfaces here as a test failure rather than a
6740 // silent contract narrowing.
6741 let s = SupervisorSpec {
6742 restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
6743 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6744 ..SupervisorSpec::default()
6745 };
6746 s.validate()
6747 .expect("restart_window == SUPERVISOR_RESTART_WINDOW_MAX must validate");
6748 }
6749
6750 #[test]
6751 fn validate_accepts_restart_window_typical_values() {
6752 // The documented Erlang/OTP / Elixir / Riak Core / RabbitMQ
6753 // per-supervisor production-playbook band positive-control
6754 // sweep — every value Learn You Some Erlang's `{intensity, 5,
6755 // 60}` worker-supervisor `Period = 60s` default, Elixir's
6756 // `Supervisor` `max_seconds: 5` default, OTP's `supervisor`
6757 // callback module `MaxT = 5..=60` typical, Riak Core's `MaxT ∈
6758 // 10s..=300s`, and RabbitMQ broker-supervisor `MaxT = 5s`
6759 // default recommend (5s..=300s) must pass, plus a sweep
6760 // through the long-tail-flaky-pool band (5m, 15m, 30m, 1h) the
6761 // cap accepts. Mirrors `validate_accepts_wall_clock_typical_values`
6762 // on the sibling `:limits :wall-clock` axis.
6763 for w in [
6764 Duration::from_millis(1),
6765 Duration::from_millis(500),
6766 Duration::from_secs(1),
6767 Duration::from_secs(5), // RabbitMQ broker-supervisor default
6768 Duration::from_secs(10), // Riak Core lower
6769 Duration::from_secs(30),
6770 Duration::from_secs(60), // Learn You Some Erlang default
6771 Duration::from_secs(120), // OTP supervisor MaxT typical
6772 Duration::from_secs(300), // Riak Core upper
6773 Duration::from_secs(900), // 15m
6774 Duration::from_secs(1800),
6775 Duration::from_secs(3600), // exactly 1h, the cap
6776 ] {
6777 let s = SupervisorSpec {
6778 restart_window: Some(w),
6779 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6780 ..SupervisorSpec::default()
6781 };
6782 s.validate()
6783 .unwrap_or_else(|e| panic!("restart_window={w:?} must validate; got {e:?}"));
6784 }
6785 }
6786
6787 #[test]
6788 fn restart_window_zero_takes_precedence_over_cap() {
6789 // The cross-arm ordering pin: `Duration::ZERO` is structurally
6790 // outside both `>= 1ms` (zero-floor) and `<=
6791 // SUPERVISOR_RESTART_WINDOW_MAX` (cap), but the zero-floor
6792 // diagnostic is the more self-locating one (it directly names
6793 // the omit-axis remediation), so the validate gate must fire
6794 // on zero first. Same shape every other zero-then-cap ordering
6795 // on this surface uses (`WallClockZero` then
6796 // `WallClockExceedsCap`, `PolicyTimeoutZero` then
6797 // `PolicyTimeoutExceedsCap`, `PolicyBreakerZeroWindow` then
6798 // `PolicyBreakerWindowExceedsCap`).
6799 let s = SupervisorSpec {
6800 restart_window: Some(Duration::ZERO),
6801 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6802 ..SupervisorSpec::default()
6803 };
6804 assert_eq!(
6805 s.validate().unwrap_err(),
6806 SupervisorError::RestartWindowZero,
6807 "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
6808 );
6809 }
6810
6811 #[test]
6812 fn restart_window_canonical_takes_precedence_over_cap() {
6813 // The cross-arm ordering pin: a `Duration` that is *both*
6814 // sub-millisecond (non-canonical-form) and structurally above
6815 // the cap surfaces the canonical-form diagnostic first,
6816 // because the round-trip-shape break is the more fundamental
6817 // issue (the value can't even round-trip through the codec,
6818 // so the cap diagnostic naming `1ms..=1h` would be misleading
6819 // — there's no integer-ms form of the offending value). Pin
6820 // the order so a future refactor that reorders the arms
6821 // surfaces here as a test failure rather than a silent
6822 // diagnostic regression. Peer of
6823 // `wall_clock_canonical_takes_precedence_over_cap` /
6824 // `policy_timeout_canonical_takes_precedence_over_cap`.
6825 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_nanos(1);
6826 let s = SupervisorSpec {
6827 restart_window: Some(w),
6828 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6829 ..SupervisorSpec::default()
6830 };
6831 assert_eq!(
6832 s.validate().unwrap_err(),
6833 SupervisorError::RestartWindowNotCanonical { window: w },
6834 "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
6835 );
6836 }
6837
6838 #[test]
6839 fn max_restarts_cap_takes_precedence_over_restart_window_cap() {
6840 // The cross-arm ordering pin between the `:max-restarts` cap
6841 // and the sibling `:restart-window` cap. A supervisor carrying
6842 // both an over-cap `max_restarts` AND an over-cap window must
6843 // surface the `MaxRestartsExceedsCap` diagnostic first — the
6844 // cap arm is wired immediately after the zero-restart arm and
6845 // strictly before every window-axis arm (zero / canonical /
6846 // cap), so the offending value the diagnostic names matches
6847 // the order the author would discover the gates by reading
6848 // top-to-bottom through `SupervisorSpec::validate`. Pin the
6849 // order so a future refactor that reorders the arms surfaces
6850 // here as a test failure rather than a silent diagnostic
6851 // regression. Peer of
6852 // `max_restarts_cap_takes_precedence_over_restart_window_gates`
6853 // on the sibling zero / canonical window arms.
6854 let w = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
6855 let s = SupervisorSpec {
6856 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
6857 restart_window: Some(w),
6858 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6859 ..SupervisorSpec::default()
6860 };
6861 assert_eq!(
6862 s.validate().unwrap_err(),
6863 SupervisorError::MaxRestartsExceedsCap {
6864 max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
6865 },
6866 "over-cap max_restarts must surface the cap diagnostic before any window-axis diagnostic"
6867 );
6868 }
6869
6870 #[test]
6871 fn restart_window_cap_diagnostic_carries_offending_value() {
6872 // The diagnostic-shape pin: the offending `Duration` is
6873 // carried verbatim into the
6874 // [`SupervisorError::RestartWindowExceedsCap`] variant so the
6875 // surfaced error message names the value the author wrote,
6876 // not just the cap. Same self-locating diagnostic shape every
6877 // other typed-cap arm on this surface carries
6878 // (`WallClockExceedsCap` carries the offending `Duration`
6879 // verbatim, `PolicyTimeoutExceedsCap` carries the offending
6880 // `Duration` verbatim, `PolicyBreakerWindowExceedsCap` carries
6881 // the offending `Duration` verbatim).
6882 let w = Duration::from_secs(7200); // 2h
6883 let s = SupervisorSpec {
6884 restart_window: Some(w),
6885 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6886 ..SupervisorSpec::default()
6887 };
6888 let err = s.validate().unwrap_err();
6889 assert!(
6890 matches!(err, SupervisorError::RestartWindowExceedsCap { window } if window == w),
6891 "got {err:?}"
6892 );
6893 let msg = err.to_string();
6894 assert!(
6895 msg.contains("7200"),
6896 ":supervisor :restart-window cap diagnostic must carry the offending value verbatim (got: {msg})"
6897 );
6898 }
6899
6900 #[test]
6901 fn supervisor_restart_window_cap_pins_canonical_value() {
6902 // The SUPERVISOR_RESTART_WINDOW_MAX constant pins the value at
6903 // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
6904 // shared duration codec emits as a clean canonical string
6905 // (`"<n>h"`). Pinning the literal value here surfaces a future
6906 // drift (a relaxation to 24h, a tightening to 5m) as a
6907 // deliberate test edit, not a silent contract narrowing.
6908 //
6909 // The four typed-`Duration` caps on the validation surface
6910 // (`LIMITS_WALL_CLOCK_MAX` per-process, `POLICY_TIMEOUT_MAX`
6911 // per-edge, `POLICY_BREAKER_WINDOW_MAX` per-breaker,
6912 // `SUPERVISOR_RESTART_WINDOW_MAX` per-supervisor) share a
6913 // single uniform top edge at the codec's largest emitted unit
6914 // — a structural-property invariant the equality assertions
6915 // here enshrine, so a future drift on any of the four
6916 // surfaces as a deliberate test edit. Same shape every other
6917 // typed-cap value pin uses
6918 // (`wall_clock_cap_pins_canonical_value`,
6919 // `policy_timeout_cap_pins_canonical_value`,
6920 // `circuit_breaker_window_cap_pins_canonical_value`).
6921 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, Duration::from_secs(3600));
6922 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX.as_millis(), 3_600_000);
6923 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::LIMITS_WALL_CLOCK_MAX);
6924 assert_eq!(SUPERVISOR_RESTART_WINDOW_MAX, crate::POLICY_TIMEOUT_MAX);
6925 assert_eq!(
6926 SUPERVISOR_RESTART_WINDOW_MAX,
6927 crate::POLICY_BREAKER_WINDOW_MAX
6928 );
6929 }
6930
6931 #[test]
6932 fn restart_window_cap_value_round_trips_through_codec() {
6933 // The codec round-trip property the cap arm preserves: the
6934 // [`SUPERVISOR_RESTART_WINDOW_MAX`] constant itself round-trips
6935 // through the shared duration codec — every value at the cap
6936 // serializes to the canonical `"1h"` form and parses back
6937 // identically. Pin the round-trip so a future change to the
6938 // codec's unit set or to the cap's magnitude that breaks the
6939 // round-trip property surfaces here. Peer of
6940 // `wall_clock_cap_value_round_trips_through_codec` on the
6941 // sibling `:limits :wall-clock` axis.
6942 let s = SupervisorSpec {
6943 restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
6944 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
6945 ..SupervisorSpec::default()
6946 };
6947 s.validate().unwrap();
6948 let json = serde_json::to_string(&s).unwrap();
6949 assert!(
6950 json.contains("\"1h\""),
6951 "SUPERVISOR_RESTART_WINDOW_MAX must serialize to the canonical `\"1h\"` form (got {json})"
6952 );
6953 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
6954 assert_eq!(back.restart_window, Some(SUPERVISOR_RESTART_WINDOW_MAX));
6955 }
6956
6957 #[test]
6958 fn validate_rejects_duplicate_child_caixa() {
6959 // Two children with the same :caixa render to two ComputeUnits
6960 // with the same name in the cluster's HelmRelease values —
6961 // one silently overwrites the other. Erlang/OTP's child_spec.id
6962 // is required-unique per supervisor; same set-not-multiset
6963 // discipline applied here as for :membros / :placement
6964 // :clusters / :entrada :paths.
6965 let s = SupervisorSpec {
6966 children: vec![
6967 child("worker", "^0.1", RestartPolicy::Permanent),
6968 child("cache", "^0.1", RestartPolicy::Transient),
6969 child("worker", "^0.2", RestartPolicy::Permanent),
6970 ],
6971 ..SupervisorSpec::default()
6972 };
6973 let err = s.validate().unwrap_err();
6974 assert!(
6975 matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "worker"),
6976 "got {err:?}"
6977 );
6978 }
6979
6980 #[test]
6981 fn validate_duplicate_child_diagnostic_names_first_collision() {
6982 // Iteration walks the :children list in declaration order —
6983 // the diagnostic names the first repeat, deterministically,
6984 // even when multiple names duplicate.
6985 let s = SupervisorSpec {
6986 children: vec![
6987 child("a", "^0.1", RestartPolicy::Permanent),
6988 child("b", "^0.1", RestartPolicy::Permanent),
6989 child("a", "^0.1", RestartPolicy::Permanent),
6990 child("b", "^0.1", RestartPolicy::Permanent),
6991 ],
6992 ..SupervisorSpec::default()
6993 };
6994 let err = s.validate().unwrap_err();
6995 assert!(
6996 matches!(err, SupervisorError::DuplicateChildCaixa { ref caixa } if caixa == "a"),
6997 "got {err:?}"
6998 );
6999 }
7000
7001 // ── self-supervision cross-slot gate ──────────────────────────
7002
7003 #[test]
7004 fn validate_no_self_supervision_rejects_self_referential_child() {
7005 // A supervisor whose `:children` lists its own `:nome` is a
7006 // one-node reconciliation cycle — rejected, naming the parent.
7007 let children = vec![
7008 child("worker", "^0.1", RestartPolicy::Permanent),
7009 child("orquestra", "^0.1", RestartPolicy::Permanent),
7010 ];
7011 let err = validate_no_self_supervision(&children, "orquestra").unwrap_err();
7012 assert!(
7013 matches!(err, SupervisorError::ChildSupervisesSelf { ref caixa } if caixa == "orquestra"),
7014 "got {err:?}"
7015 );
7016 }
7017
7018 #[test]
7019 fn validate_no_self_supervision_accepts_distinct_children() {
7020 // Positive control: distinct child names (including a child that
7021 // is itself a supervisor — nested trees are valid OTP) pass.
7022 let children = vec![
7023 child("worker", "^0.1", RestartPolicy::Permanent),
7024 child("sub-tree", "^0.1", RestartPolicy::Permanent),
7025 ];
7026 validate_no_self_supervision(&children, "orquestra").unwrap();
7027 }
7028
7029 #[test]
7030 fn validate_no_self_supervision_empty_children_is_ok() {
7031 // SimpleOneForOne / no-static-children supervisors have nothing
7032 // to self-reference — the gate is vacuously satisfied.
7033 validate_no_self_supervision(&[], "orquestra").unwrap();
7034 }
7035
7036 #[test]
7037 fn validate_simple_one_for_one_skips_uniqueness_check() {
7038 // SimpleOneForOne supervisors carry no static children — the
7039 // duplicate-child loop never runs. A zero-window declaration
7040 // on a SimpleOneForOne supervisor still trips the window check
7041 // (window applies to dynamic children too).
7042 let s = SupervisorSpec {
7043 estrategia: RestartStrategy::SimpleOneForOne,
7044 restart_window: None,
7045 children: vec![],
7046 ..SupervisorSpec::default()
7047 };
7048 s.validate().unwrap();
7049 let s_zero = SupervisorSpec {
7050 estrategia: RestartStrategy::SimpleOneForOne,
7051 restart_window: Some(Duration::ZERO),
7052 children: vec![],
7053 ..SupervisorSpec::default()
7054 };
7055 assert_eq!(
7056 s_zero.validate().unwrap_err(),
7057 SupervisorError::RestartWindowZero
7058 );
7059 }
7060
7061 #[test]
7062 fn validate_zero_window_runs_after_max_restarts_check() {
7063 // Pin the order: max_restarts == 0 fires before
7064 // restart_window == 0s, so an author with both wrong sees the
7065 // counter-axis diagnostic first (matches the order in the
7066 // struct and in the doc comment).
7067 let s = SupervisorSpec {
7068 max_restarts: 0,
7069 restart_window: Some(Duration::ZERO),
7070 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7071 ..SupervisorSpec::default()
7072 };
7073 assert_eq!(s.validate().unwrap_err(), SupervisorError::ZeroMaxRestarts);
7074 }
7075
7076 #[test]
7077 fn round_trip_all_strategies() {
7078 for &strat in RestartStrategy::ALL {
7079 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
7080 // shape partition through the [`gen_platform::IsVariant`]
7081 // derive-generated [`RestartStrategy::is_simple_one_for_one`]
7082 // predicate rather than the raw
7083 // `matches!(strat, RestartStrategy::SimpleOneForOne)`
7084 // open-coded pattern-match — same closed-set-typed-enum
7085 // arm-discriminator dispatch discipline the sibling
7086 // [`crate::upgrade::UpgradeInstruction::is_restart`] convergence
7087 // (915a934) extended onto its two paired positive / negated
7088 // `matches!` filter sites, and the sibling
7089 // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
7090 // predicate convergence (766ec63) extended onto the M3 mesh-
7091 // slot per-`:placement` distribution-strategy `matches!`
7092 // discriminator axis. See the sibling
7093 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
7094 // fixture and the peer `manifest::tests::
7095 // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
7096 // fixture — all three sites (the last unlifted
7097 // `matches!`-based arm-discriminator axis on the OTP-shape
7098 // supervisor sibling-restart-strategy closed-set typed enum,
7099 // acknowledged in 915a934's Prior-commits footnote as the
7100 // outstanding follow-up) now consult one typed dispatch on
7101 // the substrate primitive.
7102 let s = SupervisorSpec {
7103 estrategia: strat,
7104 children: if strat.is_simple_one_for_one() {
7105 vec![]
7106 } else {
7107 vec![child("w", "^0.1", RestartPolicy::Permanent)]
7108 },
7109 ..SupervisorSpec::default()
7110 };
7111 let json = serde_json::to_string(&s).unwrap();
7112 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
7113 assert_eq!(s, back);
7114 }
7115 }
7116
7117 #[test]
7118 fn round_trip_all_restart_policies() {
7119 for policy in [
7120 RestartPolicy::Permanent,
7121 RestartPolicy::Temporary,
7122 RestartPolicy::Transient,
7123 ] {
7124 let c = child("w", "^0.1", policy);
7125 let json = serde_json::to_string(&c).unwrap();
7126 let back: ChildSpec = serde_json::from_str(&json).unwrap();
7127 assert_eq!(c, back);
7128 }
7129 }
7130
7131 #[test]
7132 fn restart_strategy_is_simple_one_for_one_predicate_partitions_the_arm_set() {
7133 // The fail-before-pass-after pin on the `gen_platform::IsVariant`
7134 // derive's [`RestartStrategy::is_simple_one_for_one`] arm-
7135 // discriminator predicate: [`RestartStrategy::SimpleOneForOne`]
7136 // is the only variant that satisfies `.is_simple_one_for_one()`;
7137 // every static-children-bearing arm (`OneForOne` / `OneForAll`
7138 // / `RestForOne`) returns `false`. This pin makes the partition
7139 // invariant load-bearing at caixa-core test time so a future
7140 // derive regression (a hole that returns `false` for
7141 // `SimpleOneForOne` too, or a byte-collision that flips a second
7142 // variant to `true`) trips here rather than laundering the arm
7143 // at the three test-fixture builder sites (a hole flips the
7144 // `SimpleOneForOne` fixture to carry a non-empty children list
7145 // and the subsequent `SupervisorSpec::validate` would refuse the
7146 // fixture with [`SupervisorError::SimpleOneForOneWithStaticChildren`];
7147 // a collision flips a peer strategy's fixture to carry an empty
7148 // children list and the subsequent `validate` would refuse with
7149 // [`SupervisorError::NoChildren`] — either way, the pin fires
7150 // here, at the derive site, rather than at the fixture-refusal
7151 // site far away). Peer of the sibling
7152 // [`crate::upgrade::tests::upgrade_instruction_is_restart_predicate_partitions_the_arm_set`]
7153 // (915a934) pin on the M2 OTP-appup axis and the sibling
7154 // [`crate::kind::tests::caixa_kind_is_variant_predicates_partition_the_arm_set`]
7155 // pin on the M0 `:kind` axis.
7156 let cases: &[(RestartStrategy, bool)] = &[
7157 (RestartStrategy::OneForOne, false),
7158 (RestartStrategy::OneForAll, false),
7159 (RestartStrategy::RestForOne, false),
7160 (RestartStrategy::SimpleOneForOne, true),
7161 ];
7162 for (variant, expected) in cases {
7163 assert_eq!(
7164 variant.is_simple_one_for_one(),
7165 *expected,
7166 "RestartStrategy::{variant:?}.is_simple_one_for_one() must \
7167 return {expected} (partition invariant on the \
7168 IsVariant-derived arm-discriminator predicate — every \
7169 test-fixture site that partitions the `:children` slot \
7170 shape on `SimpleOneForOne ↔ non-SimpleOneForOne` keys \
7171 off this typed dispatch, so a derive regression must \
7172 surface here rather than at the fixture-refusal site)"
7173 );
7174 }
7175 }
7176
7177 #[test]
7178 fn restart_strategy_fixture_partition_routes_through_is_simple_one_for_one_predicate() {
7179 // Byte-identity pin on the `SimpleOneForOne ↔ non-SimpleOneForOne`
7180 // fixture-shape partition against the pre-lift
7181 // `matches!(strat, RestartStrategy::SimpleOneForOne)` open-coded
7182 // pattern-match every test-fixture builder site previously
7183 // coupled to inline. Asserts the two projections agree byte-for-
7184 // byte on every arm of the enum, so a future derive regression
7185 // that flipped either predicate's arm-set would surface here at
7186 // caixa-core test time rather than at the three fixture-builder
7187 // sites (`supervisor::tests::round_trip_all_strategies`,
7188 // `supervisor::tests::supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`,
7189 // `manifest::tests::caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`)
7190 // far from the derive site. Same peer-shape byte-identity pin
7191 // every sibling `IsVariant`-derive-routed convergence carries on
7192 // the substrate's closed-set typed-enum surface (peer of
7193 // [`crate::upgrade::tests::validate_restart_exclusive_routes_through_is_restart_predicate`]
7194 // on the M2 OTP-appup axis).
7195 for &strat in RestartStrategy::ALL {
7196 let via_predicate = strat.is_simple_one_for_one();
7197 let via_matches = matches!(strat, RestartStrategy::SimpleOneForOne);
7198 assert_eq!(
7199 via_predicate, via_matches,
7200 "RestartStrategy::{strat:?}: is_simple_one_for_one() must \
7201 byte-equal matches!(_, RestartStrategy::SimpleOneForOne) — \
7202 the pre-lift open-coded pattern and the \
7203 IsVariant-derived predicate are the same axis, \
7204 one typed dispatch"
7205 );
7206 }
7207 }
7208
7209 #[test]
7210 fn duration_codec_round_trip_canonical_units() {
7211 // Note the canonical-form rule: durations serialize to the
7212 // *largest* unit that divides cleanly, so 60s ↔ "1m" and not
7213 // "60s" — but the round-trip preserves the underlying Duration.
7214 let cases = [
7215 ("30s", Duration::from_secs(30)),
7216 ("5m", Duration::from_secs(300)),
7217 ("1h", Duration::from_secs(3600)),
7218 ("500ms", Duration::from_millis(500)),
7219 ];
7220 for (lit, dur) in cases {
7221 let s = SupervisorSpec {
7222 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7223 restart_window: Some(dur),
7224 ..SupervisorSpec::default()
7225 };
7226 let json = serde_json::to_string(&s).unwrap();
7227 assert!(
7228 json.contains(&format!("\"{lit}\"")),
7229 "expected \"{lit}\" in {json}"
7230 );
7231 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
7232 assert_eq!(back.restart_window, Some(dur));
7233 }
7234 }
7235
7236 #[test]
7237 fn duration_canonicalizes_to_largest_unit() {
7238 // 60 seconds → "1m" (largest cleanly-divisible unit), but the
7239 // typed Duration still equals 60s on the way back.
7240 let s = SupervisorSpec {
7241 children: vec![child("w", "^0.1", RestartPolicy::Permanent)],
7242 restart_window: Some(Duration::from_secs(60)),
7243 ..SupervisorSpec::default()
7244 };
7245 let json = serde_json::to_string(&s).unwrap();
7246 assert!(json.contains("\"1m\""), "{json}");
7247 let back: SupervisorSpec = serde_json::from_str(&json).unwrap();
7248 assert_eq!(back.restart_window, Some(Duration::from_secs(60)));
7249 }
7250
7251 #[test]
7252 fn three_child_one_for_one_validates() {
7253 let s = SupervisorSpec {
7254 estrategia: RestartStrategy::OneForOne,
7255 max_restarts: 5,
7256 restart_window: Some(Duration::from_secs(60)),
7257 children: vec![
7258 child("worker", "^0.1", RestartPolicy::Permanent),
7259 child("cache", "^0.1", RestartPolicy::Transient),
7260 child("scratch", "^0.1", RestartPolicy::Temporary),
7261 ],
7262 };
7263 s.validate().unwrap();
7264 }
7265
7266 #[test]
7267 fn json_uses_pascal_case_for_strategy_and_policy() {
7268 // Variant names are PascalCase by default in serde, matching
7269 // tatara-lisp's enum convention (`:estrategia OneForOne`).
7270 let c = child("w", "^0.1", RestartPolicy::Permanent);
7271 let json = serde_json::to_string(&c).unwrap();
7272 assert!(json.contains("\"Permanent\""));
7273 assert!(!json.contains("\"permanent\""));
7274
7275 let s = SupervisorSpec {
7276 estrategia: RestartStrategy::OneForOne,
7277 children: vec![c],
7278 ..SupervisorSpec::default()
7279 };
7280 let json = serde_json::to_string(&s).unwrap();
7281 assert!(json.contains("\"estrategia\":\"OneForOne\""));
7282 }
7283
7284 // ── shared duration codec: integer-magnitude canonical-form gate ──
7285 //
7286 // The gate lifts the discipline `crate::limits::parse_duration`
7287 // (818dd38) carries on the peer `:limits :wall-clock` codec onto
7288 // the shared codec backing the remaining three typed-duration
7289 // slots: `:supervisor :restart-window`, `:politicas :timeout`, and
7290 // `:politicas :circuit-breaker :window`. Every magnitude `render`
7291 // emits is a non-negative integer with no decimal point and no
7292 // leading sign, so the codec's accepted set must match for
7293 // serialize/deserialize to round-trip without canonical-form
7294 // drift.
7295
7296 #[test]
7297 fn parse_accepts_integer_canonical_units() {
7298 // Pin the happy-path: every canonical author shape `render`
7299 // ever emits parses to the same `Duration` value, so the
7300 // codec's accepted set is at least a superset of its emitted
7301 // set on the canonical-unit axis.
7302 for (lit, dur) in [
7303 ("30s", Duration::from_secs(30)),
7304 ("500ms", Duration::from_millis(500)),
7305 ("2m", Duration::from_secs(120)),
7306 ("1h", Duration::from_secs(3600)),
7307 ("0s", Duration::ZERO),
7308 ] {
7309 assert_eq!(
7310 duration_codec::parse(lit).unwrap(),
7311 dur,
7312 "parse({lit:?}) should be {dur:?}"
7313 );
7314 }
7315 }
7316
7317 #[test]
7318 fn parse_accepts_bare_integer_as_seconds() {
7319 // The `"s" | ""` arm: a bare integer with no unit is read as
7320 // seconds. Pin this so the unit-empty form keeps parsing (it
7321 // renders to `"<n>s"` on serialize — that's a unit-choice
7322 // drift the integer-magnitude gate does NOT close, matching
7323 // the `parse_byte_size` `"1024"` → `"1KiB"` scope decision in
7324 // the peer `:limits :memory` codec).
7325 assert_eq!(
7326 duration_codec::parse("30").unwrap(),
7327 Duration::from_secs(30)
7328 );
7329 }
7330
7331 #[test]
7332 fn parse_rejects_fractional_seconds_with_canonical_form_diagnostic() {
7333 // `"1.5s"` parses as f64 to 1.5 → renders back as `"1500ms"`
7334 // on first serialize — DRIFT. The integer-magnitude gate names
7335 // the offending `"1.5"` verbatim and points at the canonical
7336 // remediation `"1500ms"`.
7337 let err = duration_codec::parse("1.5s").unwrap_err();
7338 assert!(err.contains("\"1.5\""), "missing magnitude in {err:?}");
7339 assert!(
7340 err.contains("not a non-negative integer"),
7341 "missing canonical-form reason in {err:?}"
7342 );
7343 assert!(
7344 err.contains("\"1500ms\""),
7345 "missing canonical-form remediation in {err:?}"
7346 );
7347 }
7348
7349 #[test]
7350 fn parse_rejects_decimal_shaped_integer_seconds() {
7351 // `"1.0s"` is the trickiest drift class: numerically `1.0s` is
7352 // `1s` exactly, so the round-trip looks correct — but the
7353 // emitted canonical form is `"1s"`, not `"1.0s"`. Gate the
7354 // decimal-shape-with-integer-value form so author intent is
7355 // never silently rewritten.
7356 let err = duration_codec::parse("1.0s").unwrap_err();
7357 assert!(err.contains("\"1.0\""), "missing magnitude in {err:?}");
7358 assert!(
7359 err.contains("not a non-negative integer"),
7360 "missing canonical-form reason in {err:?}"
7361 );
7362 }
7363
7364 #[test]
7365 fn parse_rejects_half_unit_minute() {
7366 // `"0.5m"` is the unit-fraction footgun — author writes a
7367 // human-readable half-minute, serde silently rewrites to
7368 // `"30s"` on next emit. The gate names the offending
7369 // magnitude `"0.5"` and points at the integer-in-smaller-unit
7370 // form.
7371 let err = duration_codec::parse("0.5m").unwrap_err();
7372 assert!(err.contains("\"0.5\""), "missing magnitude in {err:?}");
7373 assert!(
7374 err.contains("\"30s\""),
7375 "missing canonical-form remediation in {err:?}"
7376 );
7377 }
7378
7379 #[test]
7380 fn parse_rejects_leading_plus_sign() {
7381 // `u64::from_str` rejects `"+30"` but `f64::from_str` accepts
7382 // it as `30.0` — the prior parser used f64 so `"+30s"` parsed
7383 // cleanly to 30s and round-tripped to `"30s"` on next emit
7384 // (DRIFT). The digit-only gate closes the leading-sign class
7385 // first; the diagnostic names `"+30"` verbatim.
7386 let err = duration_codec::parse("+30s").unwrap_err();
7387 assert!(err.contains("\"+30\""), "missing magnitude in {err:?}");
7388 assert!(
7389 err.contains("not a non-negative integer"),
7390 "missing canonical-form reason in {err:?}"
7391 );
7392 }
7393
7394 #[test]
7395 fn parse_rejects_leading_minus_sign() {
7396 // The former `num < 0.0` arm: `"-30s"` parsed as f64 to -30,
7397 // rejected with `"negative duration in \"-30s\""`. Under the
7398 // integer-magnitude gate the diagnostic is unified — `-30` is
7399 // non-digit-only, f64-numeric, and surfaces with the canonical-
7400 // form reason (no leading `+` / `-` sign) naming the offending
7401 // `"-30"` verbatim. Same diagnostic shape as every other
7402 // rejected non-integer magnitude.
7403 let err = duration_codec::parse("-30s").unwrap_err();
7404 assert!(err.contains("\"-30\""), "missing magnitude in {err:?}");
7405 assert!(
7406 err.contains("not a non-negative integer"),
7407 "missing canonical-form reason in {err:?}"
7408 );
7409 }
7410
7411 #[test]
7412 fn parse_garbage_still_falls_through_to_bad_magnitude() {
7413 // Non-digit-only AND non-numeric (`"--1s"`, `"abc"`) falls
7414 // through to the narrower "bad duration magnitude" arm — the
7415 // canonical-form diagnostic is reserved for the parser-shape
7416 // footgun case, not the "not a number at all" case. Same
7417 // shape `parse_byte_size`'s `BadByteMagnitude` arm carries on
7418 // the peer `:limits :memory` codec.
7419 let err = duration_codec::parse("--1s").unwrap_err();
7420 assert!(
7421 err.contains("bad duration magnitude"),
7422 "expected bad-magnitude wording in {err:?}"
7423 );
7424 }
7425
7426 #[test]
7427 fn parse_digit_only_magnitude_carries_zero_f64_drift() {
7428 // The accepted set is now closed under `u64`-exact integer
7429 // arithmetic: `"500ms"` → `Duration::from_millis(500)` exactly,
7430 // `"3600s"` → `Duration::from_secs(3600)` exactly, `"1h"` →
7431 // `Duration::from_secs(3600)` exactly, no f64 mantissa drift
7432 // possible. Pin the integer-exact arms across the four unit
7433 // suffixes so a future refactor that reaches back for f64
7434 // (`from_secs_f64`, `mul_f64`) surfaces here.
7435 assert_eq!(
7436 duration_codec::parse("3600s").unwrap(),
7437 Duration::from_secs(3600)
7438 );
7439 assert_eq!(
7440 duration_codec::parse("60m").unwrap(),
7441 Duration::from_secs(3600)
7442 );
7443 assert_eq!(
7444 duration_codec::parse("1h").unwrap(),
7445 Duration::from_secs(3600)
7446 );
7447 assert_eq!(
7448 duration_codec::parse("999ms").unwrap(),
7449 Duration::from_millis(999)
7450 );
7451 }
7452
7453 #[test]
7454 fn restart_window_serde_rejects_fractional_seconds() {
7455 // The shared codec backs `SupervisorSpec::restart_window`
7456 // (`with = "duration_codec"`) — so the gate applies on serde
7457 // deserialize for the typed Supervisor slot. A
7458 // `{"restartWindow":"1.5s"}` payload that previously round-
7459 // tripped to a different canonical string on next serialize
7460 // is now refused at deserialize with the integer-magnitude
7461 // diagnostic.
7462 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
7463 "restartWindow":"1.5s",
7464 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
7465 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7466 let msg = err.to_string();
7467 assert!(
7468 msg.contains("not a non-negative integer"),
7469 "expected integer-magnitude diagnostic in {msg:?}"
7470 );
7471 assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
7472 }
7473
7474 #[test]
7475 fn restart_window_serde_rejects_leading_plus() {
7476 // The `u64::from_str` leading-`+` permissiveness gap that
7477 // motivated the digit-only gate (the `f64`-side accepted
7478 // `"+30"`, the prior parser silently round-tripped to `"30s"`)
7479 // is now closed on the shared codec — surfaces as a structured
7480 // diagnostic at the serde layer for every typed-duration slot.
7481 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
7482 "restartWindow":"+30s",
7483 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
7484 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7485 let msg = err.to_string();
7486 assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
7487 assert!(
7488 msg.contains("not a non-negative integer"),
7489 "missing canonical-form reason in {msg:?}"
7490 );
7491 }
7492
7493 #[test]
7494 fn parse_rejects_leading_zero_magnitude() {
7495 // `"030s"` is digit-only, so the existing non-digit-only / sign
7496 // / fractional arm doesn't catch it — `u64::from_str("030")`
7497 // returns `Ok(30)`, so before this gate `"030s"` parsed to
7498 // `Duration::from_secs(30)` and round-tripped through `render`
7499 // to `"30s"` — a *different* canonical string on the next emit,
7500 // breaking the THEORY.md Part V render-determinism contract
7501 // exactly the way `"+30s"` did before the leading-`+` arm
7502 // landed. Peer with the `rate_limit_codec` leading-zero arm
7503 // (4f46830) on the same canonical-form-drift axis.
7504 let err = duration_codec::parse("030s").unwrap_err();
7505 assert!(
7506 err.contains("non-canonical leading zero"),
7507 "expected leading-zero diagnostic in {err:?}"
7508 );
7509 assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
7510 assert!(
7511 err.contains("\"30s\""),
7512 "missing canonical-form remediation in {err:?}"
7513 );
7514 assert!(
7515 err.contains("THEORY.md"),
7516 "missing render-determinism citation in {err:?}"
7517 );
7518 }
7519
7520 #[test]
7521 fn parse_rejects_multi_digit_zero_magnitude() {
7522 // `"00s"` and `"00ms"` are the all-zero leading-zero footgun —
7523 // digit-only, parse losslessly to `Duration::ZERO`, but render
7524 // back to `"0s"` (the single-byte canonical form) on the next
7525 // emit. The leading-zero arm refuses the drift class at the
7526 // codec layer; the semantic-zero gate downstream
7527 // (`SupervisorError::ZeroRestartWindow`, etc.) would refuse
7528 // the single-byte canonical form `"0s"` separately on the
7529 // typed-validate layer.
7530 let err = duration_codec::parse("00s").unwrap_err();
7531 assert!(
7532 err.contains("non-canonical leading zero"),
7533 "expected leading-zero diagnostic in {err:?}"
7534 );
7535 assert!(err.contains("\"00\""), "missing magnitude in {err:?}");
7536 }
7537
7538 #[test]
7539 fn parse_rejects_leading_zero_per_hour_window() {
7540 // `"01h"` is the per-hour-window footgun — multi-byte magnitude
7541 // starting with `0`, parses losslessly to `Duration::from_secs(3600)`,
7542 // renders to `"1h"` (DRIFT). The arm is unit-agnostic: every
7543 // canonical unit suffix the codec accepts (`ms` / `s` / `m` /
7544 // `h` / bare-integer-as-seconds) inherits the same gate.
7545 let err = duration_codec::parse("01h").unwrap_err();
7546 assert!(
7547 err.contains("non-canonical leading zero"),
7548 "expected leading-zero diagnostic in {err:?}"
7549 );
7550 assert!(err.contains("\"01\""), "missing magnitude in {err:?}");
7551 }
7552
7553 #[test]
7554 fn parse_rejects_leading_zero_bare_integer_as_seconds() {
7555 // The `parse_accepts_bare_integer_as_seconds` happy-path
7556 // (`"30"` → 30s) inherits the leading-zero arm: `"030"` is
7557 // multi-byte starts-with-`0`, parses losslessly to
7558 // `Duration::from_secs(30)`, renders to `"30s"` (DRIFT). The
7559 // bare-integer surface accepts permissive unit-empty
7560 // shorthand but still must reject leading-zero padding.
7561 let err = duration_codec::parse("030").unwrap_err();
7562 assert!(
7563 err.contains("non-canonical leading zero"),
7564 "expected leading-zero diagnostic in {err:?}"
7565 );
7566 assert!(err.contains("\"030\""), "missing magnitude in {err:?}");
7567 }
7568
7569 #[test]
7570 fn parse_accepts_single_zero_magnitude_at_codec_layer() {
7571 // The codec-layer / typed-validate-layer boundary: `"0s"` /
7572 // `"0ms"` / `"0"` are the single-byte canonical-zero forms —
7573 // each round-trips losslessly through `render`
7574 // (`render(Duration::ZERO)` → `"0s"`), so the codec layer
7575 // accepts them. The downstream semantic-zero gates
7576 // (`SupervisorError::ZeroRestartWindow`,
7577 // `AplicacaoError::PolicyTimeoutZero`,
7578 // `AplicacaoError::PolicyCircuitBreakerWindowZero`) refuse
7579 // zero-magnitude authoring at the typed-validate layer above,
7580 // peer with the `rate_limit_codec` codec-layer / typed-
7581 // validate-layer partition for `"0/s"`.
7582 assert_eq!(duration_codec::parse("0s").unwrap(), Duration::ZERO);
7583 assert_eq!(duration_codec::parse("0ms").unwrap(), Duration::ZERO);
7584 assert_eq!(duration_codec::parse("0").unwrap(), Duration::ZERO);
7585 }
7586
7587 #[test]
7588 fn parse_accepts_canonical_magnitude_with_leading_one() {
7589 // The complementary boundary: a future tightening cannot
7590 // drift into rejecting valid canonical magnitudes that
7591 // happen to start with `1` (or any digit `[1-9]`). Pin
7592 // every canonical-unit suffix so the leading-zero arm
7593 // remains strictly narrower than the digit-only arm.
7594 assert_eq!(
7595 duration_codec::parse("100ms").unwrap(),
7596 Duration::from_millis(100)
7597 );
7598 assert_eq!(
7599 duration_codec::parse("100s").unwrap(),
7600 Duration::from_secs(100)
7601 );
7602 assert_eq!(
7603 duration_codec::parse("10m").unwrap(),
7604 Duration::from_secs(600)
7605 );
7606 assert_eq!(
7607 duration_codec::parse("10h").unwrap(),
7608 Duration::from_secs(36_000)
7609 );
7610 }
7611
7612 #[test]
7613 fn restart_window_serde_rejects_leading_zero() {
7614 // The shared codec backs `SupervisorSpec::restart_window`
7615 // (`with = "duration_codec"`) — so the leading-zero arm
7616 // applies on serde deserialize for the typed Supervisor slot.
7617 // A `{"restartWindow":"030s"}` payload that previously round-
7618 // tripped to a different canonical string on next serialize
7619 // is now refused at deserialize with the leading-zero
7620 // diagnostic. Peer with `restart_window_serde_rejects_leading_plus`
7621 // / `restart_window_serde_rejects_fractional_seconds` on the
7622 // same canonical-form-drift axis.
7623 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
7624 "restartWindow":"030s",
7625 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
7626 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7627 let msg = err.to_string();
7628 assert!(
7629 msg.contains("non-canonical leading zero"),
7630 "expected leading-zero diagnostic in {msg:?}"
7631 );
7632 assert!(msg.contains("\"030\""), "missing magnitude in {msg:?}");
7633 }
7634
7635 #[test]
7636 fn parse_rejects_leading_whitespace() {
7637 // `" 30s"` — the canonical paste-from-aligned-doc /
7638 // paste-from-YAML-quoted-plain-scalar footgun. Before this
7639 // gate the top-level `s.trim()` at parse entry silently ate
7640 // the leading space and parsed the value to
7641 // `Duration::from_secs(30)`, which then round-tripped through
7642 // `render` to `"30s"` (a *different* canonical string on the
7643 // next emit) — the exact canonical-form-drift class the
7644 // leading-`+` / leading-zero arms already close, extended
7645 // to the whitespace-byte class. Peer with the sibling
7646 // `rate_limit_codec` whitespace-rejection arm (1ad7755) on
7647 // the M3 `:politicas` axis.
7648 let err = duration_codec::parse(" 30s").unwrap_err();
7649 assert!(
7650 err.contains("contains whitespace byte"),
7651 "expected whitespace diagnostic in {err:?}"
7652 );
7653 assert!(err.contains("0x20"), "missing offending byte in {err:?}");
7654 assert!(
7655 err.contains("THEORY.md"),
7656 "missing render-determinism contract citation in {err:?}"
7657 );
7658 }
7659
7660 #[test]
7661 fn parse_rejects_trailing_whitespace() {
7662 // `"30s "` — the canonical shell-history / trailing-space
7663 // paste footgun. Before this gate the top-level `s.trim()`
7664 // silently ate the trailing space and parsed to
7665 // `Duration::from_secs(30)`, round-tripping to `"30s"` on the
7666 // next emit — same canonical-form drift as the leading-space
7667 // sibling, closed on the same whitespace-byte arm.
7668 let err = duration_codec::parse("30s ").unwrap_err();
7669 assert!(
7670 err.contains("contains whitespace byte"),
7671 "expected whitespace diagnostic in {err:?}"
7672 );
7673 assert!(err.contains("0x20"), "missing offending byte in {err:?}");
7674 }
7675
7676 #[test]
7677 fn parse_rejects_internal_whitespace_between_magnitude_and_unit() {
7678 // `"30 s"` — the canonical typographically-spaced author
7679 // shape (the same idiom every prose reference to a duration
7680 // renders as, mistakenly retained when the value is pasted
7681 // into a codec-shaped slot). Before this gate the per-part
7682 // `num_part.trim()` / `unit.trim()` calls silently ate the
7683 // whitespace between the magnitude and the unit and parsed
7684 // the value to `Duration::from_secs(30)`, round-tripping to
7685 // `"30s"` — the codec's *internal* whitespace-tolerance
7686 // vector, orthogonal to the leading / trailing surface but
7687 // the same canonical-form-drift class. Pins the arm as
7688 // strictly stronger than the pre-existing top-level
7689 // `s.trim()` behavior: it fires on whitespace anywhere in
7690 // the value, not just at the string boundary.
7691 let err = duration_codec::parse("30 s").unwrap_err();
7692 assert!(
7693 err.contains("contains whitespace byte"),
7694 "expected whitespace diagnostic in {err:?}"
7695 );
7696 assert!(err.contains("0x20"), "missing offending byte in {err:?}");
7697 }
7698
7699 #[test]
7700 fn parse_rejects_tab_byte() {
7701 // `"\t30s"` — the canonical paste-from-indented-doc /
7702 // paste-from-YAML-block-scalar footgun where a tab byte leads
7703 // the magnitude. Pins that the gate covers tab (`0x09`) as
7704 // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
7705 // members and both would be silently swallowed by `s.trim()`
7706 // pre-gate. The `is_ascii_whitespace` coverage extends beyond
7707 // space alone to the full ASCII-whitespace set (space `0x20`,
7708 // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
7709 // the tab arm as a representative of the non-space members.
7710 let err = duration_codec::parse("\t30s").unwrap_err();
7711 assert!(
7712 err.contains("contains whitespace byte"),
7713 "expected whitespace diagnostic in {err:?}"
7714 );
7715 assert!(
7716 err.contains("0x09"),
7717 "missing offending tab byte in {err:?}"
7718 );
7719 }
7720
7721 #[test]
7722 fn restart_window_serde_rejects_whitespace() {
7723 // The shared codec backs `SupervisorSpec::restart_window`
7724 // (`with = "duration_codec"`) — so the whitespace arm
7725 // applies on serde deserialize for the typed Supervisor slot.
7726 // A `{"restartWindow":" 30s"}` payload that previously round-
7727 // tripped to a different canonical string on next serialize
7728 // is now refused at deserialize with the whitespace-byte
7729 // diagnostic. Peer with `restart_window_serde_rejects_leading_zero`
7730 // / `restart_window_serde_rejects_leading_plus` /
7731 // `restart_window_serde_rejects_fractional_seconds` on the
7732 // same canonical-form-drift axis.
7733 let payload = r#"{"estrategia":"OneForOne","maxRestarts":5,
7734 "restartWindow":" 30s",
7735 "children":[{"caixa":"w","versao":"^0.1","restart":"Permanent"}]}"#;
7736 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7737 let msg = err.to_string();
7738 assert!(
7739 msg.contains("contains whitespace byte"),
7740 "expected whitespace diagnostic in {msg:?}"
7741 );
7742 assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
7743 }
7744
7745 // ── canonical-form: non-ASCII Unicode `White_Space` duration gate ─────
7746 //
7747 // Successor to the ASCII-whitespace arm (a7ae622) on the shared
7748 // duration codec — closes the strictly-complementary class the
7749 // byte-scan cannot see, through the lifted
7750 // [`crate::render::find_non_ascii_whitespace_char`] predicate.
7751 // Applies to `:supervisor :restart-window`, `:politicas :timeout`,
7752 // and `:politicas :circuit-breaker :window` simultaneously via
7753 // this shared codec.
7754
7755 #[test]
7756 fn duration_codec_parse_rejects_leading_nbsp() {
7757 // NBSP prefix — the strictly-complementary drift class the
7758 // ASCII byte-scan cannot see. `str::trim` strips it silently
7759 // and the value drifts to `"30s"` on next serialize.
7760 let err = duration_codec::parse("\u{00A0}30s").unwrap_err();
7761 assert!(
7762 err.contains("non-ASCII Unicode whitespace character"),
7763 "expected non-ASCII whitespace diagnostic in {err:?}"
7764 );
7765 assert!(err.contains("U+00A0"), "missing codepoint in {err:?}");
7766 }
7767
7768 #[test]
7769 fn duration_codec_parse_rejects_trailing_line_separator() {
7770 // LINE SEPARATOR (`\u{2028}`) trailing — paste-from-web-doc
7771 // footgun.
7772 let err = duration_codec::parse("30s\u{2028}").unwrap_err();
7773 assert!(
7774 err.contains("non-ASCII Unicode whitespace character"),
7775 "expected non-ASCII whitespace diagnostic in {err:?}"
7776 );
7777 assert!(err.contains("U+2028"), "missing codepoint in {err:?}");
7778 }
7779
7780 #[test]
7781 fn duration_codec_parse_accepts_ascii_only_forms_after_unicode_arm() {
7782 // Positive-control pin: every ASCII-only canonical form the
7783 // renderer emits stays accepted through the new arm.
7784 assert_eq!(
7785 duration_codec::parse("30s").unwrap(),
7786 Duration::from_secs(30)
7787 );
7788 assert_eq!(
7789 duration_codec::parse("500ms").unwrap(),
7790 Duration::from_millis(500)
7791 );
7792 assert_eq!(
7793 duration_codec::parse("1h").unwrap(),
7794 Duration::from_secs(3600)
7795 );
7796 }
7797
7798 #[test]
7799 fn restart_window_serde_rejects_non_ascii_whitespace() {
7800 // The shared codec backs `SupervisorSpec::restart_window` — so
7801 // the new non-ASCII Unicode whitespace arm applies on serde
7802 // deserialize for the typed Supervisor slot. A
7803 // `{"restartWindow":" 30s"}` payload that previously
7804 // survived the ASCII byte-scan (only ASCII whitespace was
7805 // refused) is now refused at deserialize with the
7806 // non-ASCII-whitespace-and-codepoint diagnostic.
7807 let payload = "{\"estrategia\":\"OneForOne\",\"maxRestarts\":5,\
7808 \"restartWindow\":\"\u{00A0}30s\",\
7809 \"children\":[{\"caixa\":\"w\",\"versao\":\"^0.1\",\"restart\":\"Permanent\"}]}";
7810 let err = serde_json::from_str::<SupervisorSpec>(payload).unwrap_err();
7811 let msg = err.to_string();
7812 assert!(
7813 msg.contains("non-ASCII Unicode whitespace character"),
7814 "expected non-ASCII whitespace diagnostic in {msg:?}"
7815 );
7816 assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
7817 }
7818
7819 // ── drift-detection: serde-derive-to-SUPERVISOR_KEY_* identity ────────
7820
7821 #[test]
7822 fn supervisor_spec_serde_keys_match_lifted_supervisor_key_consts() {
7823 // Load-bearing invariant: the four `SUPERVISOR_KEY_*` consts
7824 // (`SUPERVISOR_KEY_ESTRATEGIA` / `SUPERVISOR_KEY_MAX_RESTARTS` /
7825 // `SUPERVISOR_KEY_RESTART_WINDOW` / `SUPERVISOR_KEY_CHILDREN`)
7826 // name the exact camelCase JSON keys the
7827 // `#[serde(rename_all = "camelCase")]` attribute on
7828 // `SupervisorSpec` emits. Serialize a fully-populated spec (each
7829 // field carries `Some(_)` / non-empty) and pin that each canonical
7830 // byte-sequence appears verbatim in the JSON — a future accidental
7831 // `rename_all = "snake_case"` / `"kebab-case"` / verbatim-field-
7832 // name flip at the derive attribute (any of which would silently
7833 // break every downstream JSON consumer that reaches for one of the
7834 // four consts via `Value::get(...)`) surfaces here as a build-time
7835 // test failure at `supervisor.rs`, not as an apply-time
7836 // `.get(<stale-canonical-const>)` returning `None` far from the
7837 // derive-attr drift's commit. Peer with the sibling
7838 // `limits_spec_serde_keys_match_lifted_m2_limits_key_consts`
7839 // (d8b8b4f) pin on the M2 `:limits` axis — same discipline the
7840 // M2 typed-slot family established, extended here to close the
7841 // top-level Supervisor axis.
7842 let spec = SupervisorSpec {
7843 estrategia: RestartStrategy::OneForOne,
7844 max_restarts: 5,
7845 restart_window: Some(Duration::from_secs(60)),
7846 children: vec![ChildSpec {
7847 caixa: "w".into(),
7848 versao: "^0.1".into(),
7849 restart: RestartPolicy::Permanent,
7850 }],
7851 };
7852 let json = serde_json::to_string(&spec).unwrap();
7853 for key in [
7854 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7855 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7856 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7857 crate::render::SUPERVISOR_KEY_CHILDREN,
7858 ] {
7859 let quoted = format!("\"{key}\"");
7860 assert!(
7861 json.contains("ed),
7862 "serialized SupervisorSpec must carry the lifted \
7863 SUPERVISOR_KEY_* byte-sequence {quoted} verbatim in \
7864 the JSON emission (got: {json})",
7865 );
7866 }
7867 }
7868
7869 #[test]
7870 fn supervisor_key_consts_are_pairwise_distinct() {
7871 // Cross-axis drift-detection pin: a future collapse of two
7872 // canonical top-level byte-strings onto the same value (e.g. an
7873 // accidental copy-paste flip of `SUPERVISOR_KEY_CHILDREN` to
7874 // also read `"estrategia"`) would silently reroute every
7875 // downstream probe on one axis onto the sibling axis's overlay
7876 // entry and pass every propagation-probe test that expected only
7877 // the stale axis's value. Peer of the sibling four-way distinct
7878 // pin on the `M2_LIMITS_KEY_*` tetrad (d8b8b4f).
7879 let all = [
7880 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7881 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7882 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7883 crate::render::SUPERVISOR_KEY_CHILDREN,
7884 ];
7885 for (i, a) in all.iter().enumerate() {
7886 for b in all.iter().skip(i + 1) {
7887 assert_ne!(
7888 a, b,
7889 "SUPERVISOR_KEY_* consts must be pairwise-distinct \
7890 canonical byte-sequences — got `{a}` == `{b}`",
7891 );
7892 }
7893 }
7894 }
7895
7896 #[test]
7897 fn supervisor_key_consts_are_lower_camel_case_shape() {
7898 // Shape-pin: every `SUPERVISOR_KEY_*` const must be a
7899 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
7900 // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
7901 // capital, no whitespace / dots) — the canonical shape the
7902 // `#[serde(rename_all = "camelCase")]` derive produces on
7903 // `SupervisorSpec`. A future flip to a non-camelCase attribute
7904 // at the derive surfaces both here (this test fails on the
7905 // stale-constant shape) and at
7906 // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
7907 // (that test fails on the mismatch between const and derive).
7908 // Peer with `m2_limits_key_consts_are_lower_camel_case_shape`
7909 // (d8b8b4f) on the sibling M2 `:limits` axis.
7910 for key in [
7911 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7912 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7913 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7914 crate::render::SUPERVISOR_KEY_CHILDREN,
7915 ] {
7916 assert!(
7917 !key.is_empty(),
7918 "SUPERVISOR_KEY_* must be non-empty (got {key:?})"
7919 );
7920 let first = key.chars().next().unwrap();
7921 assert!(
7922 first.is_ascii_lowercase(),
7923 "SUPERVISOR_KEY_* must lead with an ASCII-lowercase byte \
7924 (got {key:?}, leads with {first:?})",
7925 );
7926 assert!(
7927 key.chars().all(|c| c.is_ascii_alphanumeric()),
7928 "SUPERVISOR_KEY_* must be ASCII-alphanumeric only \
7929 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
7930 );
7931 }
7932 }
7933
7934 #[test]
7935 fn supervisor_key_consts_are_byte_distinct_from_supervisor_author_key_peers() {
7936 // Cross-axis drift pin: the four `SUPERVISOR_KEY_*` consts
7937 // (camelCase JSON keys, no leading colon) must never collide
7938 // byte-for-byte with the four peer `SUPERVISOR_AUTHOR_KEY_*`
7939 // consts (kebab-case author-facing labels with leading colon)
7940 // that sit next to them at `caixa_core::render`. Both families
7941 // cover the same four typed Supervisor slots on two distinct
7942 // axes (author-side kebab vs renderer-side camelCase);
7943 // collapsing either family onto the other's byte-shape would
7944 // silently reroute the render-side probe onto the author-facing
7945 // surface, or vice versa. Peer of the byte-distinctness
7946 // discipline the `M3_PLACEMENT_KEY_ESTRATEGIA` docstring names
7947 // against the peer `M3_AUTHOR_KEY_PLACEMENT`.
7948 let pairs = [
7949 (
7950 crate::render::SUPERVISOR_KEY_ESTRATEGIA,
7951 crate::render::SUPERVISOR_AUTHOR_KEY_ESTRATEGIA,
7952 ),
7953 (
7954 crate::render::SUPERVISOR_KEY_MAX_RESTARTS,
7955 crate::render::SUPERVISOR_AUTHOR_KEY_MAX_RESTARTS,
7956 ),
7957 (
7958 crate::render::SUPERVISOR_KEY_RESTART_WINDOW,
7959 crate::render::SUPERVISOR_AUTHOR_KEY_RESTART_WINDOW,
7960 ),
7961 (
7962 crate::render::SUPERVISOR_KEY_CHILDREN,
7963 crate::render::SUPERVISOR_AUTHOR_KEY_CHILDREN,
7964 ),
7965 ];
7966 for (json_key, author_key) in pairs {
7967 assert_ne!(
7968 json_key, author_key,
7969 "SUPERVISOR_KEY_* (JSON side) must differ byte-for-byte \
7970 from the peer SUPERVISOR_AUTHOR_KEY_* (author side); \
7971 got JSON `{json_key}` == author `{author_key}`",
7972 );
7973 }
7974 }
7975
7976 // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_KEY_* identity ──
7977
7978 #[test]
7979 fn child_spec_serde_keys_match_lifted_supervisor_child_key_consts() {
7980 // Load-bearing invariant: the three `SUPERVISOR_CHILD_KEY_*` consts
7981 // (`SUPERVISOR_CHILD_KEY_CAIXA` / `SUPERVISOR_CHILD_KEY_VERSAO` /
7982 // `SUPERVISOR_CHILD_KEY_RESTART`) name the exact camelCase JSON
7983 // keys the `#[serde(rename_all = "camelCase")]` attribute on
7984 // `ChildSpec` emits. Serialize a fully-populated `ChildSpec` and
7985 // pin that each canonical byte-sequence appears verbatim in the
7986 // JSON — a future accidental `rename_all = "snake_case"` /
7987 // `"kebab-case"` / verbatim-field-name flip at the derive
7988 // attribute (any of which would silently break every downstream
7989 // JSON consumer that reaches for one of the three consts via
7990 // `Value::get(...)`) surfaces here as a build-time test failure at
7991 // `supervisor.rs`, not as an apply-time
7992 // `.get(<stale-canonical-const>)` returning `None` far from the
7993 // derive-attr drift's commit. Peer with the enclosing
7994 // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
7995 // (40cc4e5) pin on the M2 supervision-tree top-level axis — same
7996 // discipline the SupervisorSpec top-level lift established,
7997 // extended here to the sibling per-`:children` entry `ChildSpec`
7998 // derive so the last M2 typed-struct sub-block
7999 // `#[serde(rename_all = "camelCase")]` axis on the Supervisor
8000 // surface without a lifted serde-key peer joins the substrate's
8001 // "one canonical byte-string per typed serialized-key axis"
8002 // discipline.
8003 let c = ChildSpec {
8004 caixa: "worker".into(),
8005 versao: "^0.1".into(),
8006 restart: RestartPolicy::Permanent,
8007 };
8008 let json = serde_json::to_string(&c).unwrap();
8009 for key in [
8010 crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
8011 crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
8012 crate::render::SUPERVISOR_CHILD_KEY_RESTART,
8013 ] {
8014 let quoted = format!("\"{key}\"");
8015 assert!(
8016 json.contains("ed),
8017 "serialized ChildSpec must carry the lifted \
8018 SUPERVISOR_CHILD_KEY_* byte-sequence {quoted} verbatim \
8019 in the JSON emission (got: {json})",
8020 );
8021 }
8022 }
8023
8024 #[test]
8025 fn supervisor_child_key_consts_are_pairwise_distinct() {
8026 // Cross-axis drift-detection pin: a future collapse of two
8027 // canonical `ChildSpec` per-entry byte-strings onto the same
8028 // value (e.g. an accidental copy-paste flip of
8029 // `SUPERVISOR_CHILD_KEY_RESTART` to also read `"caixa"`) would
8030 // silently reroute every downstream probe on one axis onto the
8031 // sibling axis's overlay entry and pass every propagation-probe
8032 // test that expected only the stale axis's value. Peer of the
8033 // sibling three-way distinct pin on the `CONTRATO_KEY_*` triad
8034 // (ca463a4) and the two-way distinct pin on the `MEMBRO_KEY_*`
8035 // pair (ce80ca0).
8036 let all = [
8037 crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
8038 crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
8039 crate::render::SUPERVISOR_CHILD_KEY_RESTART,
8040 ];
8041 for (i, a) in all.iter().enumerate() {
8042 for b in all.iter().skip(i + 1) {
8043 assert_ne!(
8044 a, b,
8045 "SUPERVISOR_CHILD_KEY_* consts must be pairwise-\
8046 distinct canonical byte-sequences — got `{a}` == `{b}`",
8047 );
8048 }
8049 }
8050 }
8051
8052 #[test]
8053 fn supervisor_child_key_consts_are_lower_camel_case_shape() {
8054 // Shape-pin: every `SUPERVISOR_CHILD_KEY_*` const must be a
8055 // lowerCamelCase byte-sequence (no `snake_case` underscores, no
8056 // `kebab-case` hyphens, no leading colon, no `PascalCase` leading
8057 // capital, no whitespace / dots) — the canonical shape the
8058 // `#[serde(rename_all = "camelCase")]` derive produces on
8059 // `ChildSpec`. A future flip to a non-camelCase attribute at the
8060 // derive surfaces both here (this test fails on the
8061 // stale-constant shape) and at
8062 // `child_spec_serde_keys_match_lifted_supervisor_child_key_consts`
8063 // (that test fails on the mismatch between const and derive).
8064 // Peer with `supervisor_key_consts_are_lower_camel_case_shape`
8065 // (40cc4e5) on the sibling `SupervisorSpec` top-level axis.
8066 for key in [
8067 crate::render::SUPERVISOR_CHILD_KEY_CAIXA,
8068 crate::render::SUPERVISOR_CHILD_KEY_VERSAO,
8069 crate::render::SUPERVISOR_CHILD_KEY_RESTART,
8070 ] {
8071 assert!(
8072 !key.is_empty(),
8073 "SUPERVISOR_CHILD_KEY_* must be non-empty (got {key:?})"
8074 );
8075 let first = key.chars().next().unwrap();
8076 assert!(
8077 first.is_ascii_lowercase(),
8078 "SUPERVISOR_CHILD_KEY_* must lead with an ASCII-lowercase \
8079 byte (got {key:?}, leads with {first:?})",
8080 );
8081 assert!(
8082 key.chars().all(|c| c.is_ascii_alphanumeric()),
8083 "SUPERVISOR_CHILD_KEY_* must be ASCII-alphanumeric only \
8084 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
8085 );
8086 }
8087 }
8088
8089 // ── drift-detection: serde-derive-to-SUPERVISOR_ESTRATEGIA_* identity ────
8090
8091 #[test]
8092 fn restart_strategy_variants_serialize_to_lifted_scalar_values() {
8093 // The fail-before-pass-after pin: pre-lift there was no
8094 // single-source binding between the [`RestartStrategy`] variant
8095 // name the un-`rename`d `Serialize` derive emits under
8096 // [`crate::render::SUPERVISOR_KEY_ESTRATEGIA`] and the byte-string
8097 // every downstream cluster-side dispatcher (the future
8098 // wasm-operator's per-supervisor sibling-restart branch, the
8099 // future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
8100 // admission-time enum-arm bind, the `caixa-operator`'s
8101 // hierarchical reconciliation scheduler's per-strategy fan-out)
8102 // probes verbatim. A future `#[serde(rename_all = "kebab-case")]`
8103 // attribute on the enum — or a per-variant `#[serde(rename = "…")]`
8104 // override, or a variant rename in the source — would silently
8105 // rebrand the emitted scalar under one spelling while every
8106 // downstream dispatcher still probed the other, with the failure
8107 // surfacing at the operator's reconcile posture (subtrees coming
8108 // up under the `default()` `OneForOne` arm rather than the typed
8109 // slot's declared strategy — a bad child would then only take
8110 // itself down instead of the sibling set the author intended, so
8111 // shared-state children fall out of sync) far from the source
8112 // rebrand commit and with no field naming the drift. Pinning the
8113 // two paths (the `Serialize` derive's serialized string AND the
8114 // [`RestartStrategy::as_str`] helper) to the same four lifted
8115 // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE`] /
8116 // [`crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL`] /
8117 // [`crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`] /
8118 // [`crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE`]
8119 // byte-strings makes any future drift on either endpoint fail
8120 // here at caixa-core build time. Peer of the M3
8121 // `placement_strategy_variants_serialize_to_lifted_scalar_values`
8122 // (3f0e21c) on the sibling `PlacementStrategy` axis — same
8123 // three-path-convergence discipline, extended to close the
8124 // OTP-shaped per-supervisor sibling-restart axis.
8125 for (variant, expected) in [
8126 (
8127 RestartStrategy::OneForOne,
8128 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8129 ),
8130 (
8131 RestartStrategy::OneForAll,
8132 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8133 ),
8134 (
8135 RestartStrategy::RestForOne,
8136 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8137 ),
8138 (
8139 RestartStrategy::SimpleOneForOne,
8140 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8141 ),
8142 ] {
8143 let json = serde_json::to_string(&variant).unwrap();
8144 assert_eq!(
8145 json,
8146 format!("\"{expected}\""),
8147 "RestartStrategy::{variant:?} must serialize to {expected:?}"
8148 );
8149 assert_eq!(
8150 variant.as_str(),
8151 expected,
8152 "RestartStrategy::{variant:?}.as_str() must return the lifted \
8153 SUPERVISOR_ESTRATEGIA_* constant"
8154 );
8155 }
8156 }
8157
8158 #[test]
8159 fn supervisor_estrategia_consts_are_pairwise_distinct() {
8160 // Cross-arm drift-detection pin: a future collapse of two
8161 // canonical variant byte-strings onto the same value (e.g. an
8162 // accidental copy-paste flip of `SUPERVISOR_ESTRATEGIA_REST_FOR_ONE`
8163 // to also read `"OneForOne"`) would silently reroute every
8164 // downstream operator's per-strategy dispatch onto the sibling
8165 // arm's reconcile branch and pass every propagation-probe test
8166 // that expected only the stale arm's value — the mis-strategied
8167 // subtree would come up with the wrong sibling-restart posture
8168 // on every subsequent failure. Peer of the sibling four-way
8169 // distinct pin `supervisor_key_consts_are_pairwise_distinct`
8170 // (40cc4e5) on the top-level `SUPERVISOR_KEY_*` axis.
8171 let all = [
8172 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8173 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8174 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8175 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8176 ];
8177 for (i, a) in all.iter().enumerate() {
8178 for (j, b) in all.iter().enumerate() {
8179 if i != j {
8180 assert_ne!(
8181 a, b,
8182 "SUPERVISOR_ESTRATEGIA_* consts must be pairwise distinct \
8183 — got duplicate {a:?} at indices {i} and {j}",
8184 );
8185 }
8186 }
8187 }
8188 }
8189
8190 #[test]
8191 fn restart_strategy_display_routes_through_as_str_helper() {
8192 // The fail-before-pass-after pin on the first half of the
8193 // three-path convergence: pre-convergence the sibling
8194 // OTP-shape typed enum [`RestartStrategy`] carried a
8195 // [`std::fmt::Display`] surface via its
8196 // `#[discriminant(also_display)]` gen-platform derive route,
8197 // which arrived kebab-case as `"one-for-one"` /
8198 // `"one-for-all"` / `"rest-for-one"` /
8199 // `"simple-one-for-one"` while the wire format ran as
8200 // PascalCase `"OneForOne"` / `"OneForAll"` / `"RestForOne"` /
8201 // `"SimpleOneForOne"` through the un-`rename`d serde derive.
8202 // Every consumer reaching for a strategy byte-string past the
8203 // wire format had to pick between three paths
8204 // ([`RestartStrategy::as_str`], the `Serialize` derive's
8205 // serialized string, or `format!("{v}")` on the
8206 // discriminant-Display route), any two of which a future
8207 // variant rename or `#[serde(rename_all = "kebab-case")]`
8208 // attribute would silently desynchronize. Wiring
8209 // [`std::fmt::Display`] through [`RestartStrategy::as_str`]
8210 // closes the third path: every `format!("{v}")` call reaches
8211 // the same lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
8212 // const the wire format and the [`RestartStrategy::as_str`]
8213 // helper already route through, so a future variant rename
8214 // lands at exactly one place. Pin the routing here so a future
8215 // `impl std::fmt::Display for RestartStrategy`
8216 // reimplementation that hand-rolls the arms instead of
8217 // delegating to [`RestartStrategy::as_str`] fails at
8218 // caixa-core build time. Peer of the M3
8219 // `placement_strategy_display_routes_through_as_str_helper`
8220 // (cc8f749) which the M3 axis converged first.
8221 for &variant in RestartStrategy::ALL {
8222 assert_eq!(
8223 variant.to_string(),
8224 variant.as_str(),
8225 "RestartStrategy::{variant:?} Display must route through \
8226 RestartStrategy::as_str (single source of truth: the lifted \
8227 SUPERVISOR_ESTRATEGIA_* const the wire format also emits)"
8228 );
8229 }
8230 }
8231
8232 #[test]
8233 fn restart_strategy_display_matches_serialized_wire_byte_string() {
8234 // The fail-before-pass-after pin on the second half of the
8235 // three-path convergence: `Display` (user-facing text) agrees
8236 // byte-for-byte with the `Serialize` derive's wire format
8237 // (canonical camelCase-schema `SUPERVISOR_KEY_ESTRATEGIA`
8238 // scalar) on every variant. Pre-convergence the two paths
8239 // were structurally independent — a future
8240 // `#[serde(rename_all = "kebab-case")]` attribute on the
8241 // enum would silently rebrand the emitted wire scalar
8242 // (`one-for-one`, `one-for-all`, `rest-for-one`,
8243 // `simple-one-for-one`) while every consumer that
8244 // pretty-prints the strategy (the future wasm-operator's
8245 // per-supervisor sibling-restart-strategy diagnostic line,
8246 // the future `feira app graph` per-supervisor strategy line,
8247 // the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
8248 // materializer's admission-webhook rejection body) would
8249 // still emit the PascalCase form the `as_str` / `Display`
8250 // route returns, with the mismatch surfacing at consumer
8251 // parse time / operator dispatch time far from the source
8252 // rebrand commit. Pin the two paths byte-for-byte here so any
8253 // future serde-attribute or variant-rename drift is a
8254 // caixa-core-build-time test failure at this call, not a
8255 // silent per-consumer dispatch miss. Peer of the M3
8256 // `placement_strategy_display_matches_serialized_wire_byte_string`
8257 // (cc8f749) which the M3 axis converged first.
8258 for &variant in RestartStrategy::ALL {
8259 let wire = serde_json::to_string(&variant).unwrap();
8260 let unquoted = wire
8261 .strip_prefix('"')
8262 .and_then(|s| s.strip_suffix('"'))
8263 .expect("serialized RestartStrategy is a JSON string");
8264 assert_eq!(
8265 variant.to_string(),
8266 unquoted,
8267 "RestartStrategy::{variant:?} Display byte-string must match the \
8268 Serialize derive's wire byte-string (three-path convergence: \
8269 Display + as_str + Serialize all resolve to the same \
8270 SUPERVISOR_ESTRATEGIA_* const)"
8271 );
8272 }
8273 }
8274
8275 #[test]
8276 fn restart_strategy_as_ref_str_routes_through_as_str_accessor() {
8277 // Fail-before-pass-after byte-parity pin on the lifted
8278 // `impl AsRef<str> for RestartStrategy` — asserts the
8279 // standard-library trait impl and the substrate-primitive
8280 // [`RestartStrategy::as_str`] `pub const fn` accessor resolve
8281 // to the same `&str` per instance across the four-arm
8282 // closed set, so any future silent detour that routes the
8283 // impl through a divergent projection (a per-arm inline
8284 // `match self { RestartStrategy::OneForOne => "OneForOne", … }`
8285 // re-inlining that opens a compile-time link to the un-lifted
8286 // arm-literal, a swap onto the kebab-case
8287 // [`gen_platform::Discriminant`] catalog identity that would
8288 // collide the wire axis with the dispatcher-catalog axis) trips
8289 // at caixa-core test time under `PartialEq` rather than at a
8290 // downstream `impl AsRef<str>`-bound consumer's silent split.
8291 // Sweeps every one of the four arms
8292 // [`RestartStrategy::ALL`] carries so no arm's projection is
8293 // covered only by the sibling wire-format `Serialize` derive
8294 // path. Peer of the sibling
8295 // [`crate::version::tests::caixa_version_as_ref_str_routes_through_as_str_accessor`]
8296 // (16d5c7e) `AsRef<str>`-byte-parity pin on the paired
8297 // top-level `:versao` typed newtype — the two pins together
8298 // cover the substrate primitive's `AsRef<str>` projection axis
8299 // on the paired newtype + closed-set-typed-enum surface.
8300 for &variant in RestartStrategy::ALL {
8301 assert_eq!(
8302 <RestartStrategy as AsRef<str>>::as_ref(&variant),
8303 variant.as_str(),
8304 "AsRef<str> impl on RestartStrategy::{variant:?} must \
8305 byte-equal RestartStrategy::as_str on the same instance \
8306 — divergence signals a silent detour off the substrate-\
8307 primitive accessor"
8308 );
8309 }
8310 }
8311
8312 #[test]
8313 fn restart_strategy_as_ref_str_routes_through_display_via_shared_accessor() {
8314 // Fail-before-pass-after byte-parity pin on the three-path
8315 // convergence discipline the M2 sibling-restart primitive now
8316 // carries on the `&str`-projection axis:
8317 // `<RestartStrategy as AsRef<str>>::as_ref(&s)` (the newly
8318 // lifted impl), `format!("{s}")` (the pre-existing
8319 // [`fmt::Display`] impl), and `s.as_str()` (the substrate-
8320 // primitive `pub const fn` accessor both trait impls delegate
8321 // through) must resolve to the same byte-string on every
8322 // instance across the four-arm closed set. Refuses any future
8323 // divergence between the two trait impls (a stray
8324 // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
8325 // rather than delegating through the shared accessor; a
8326 // hypothetical `AsRef<str>` rewrite that inlines a per-arm
8327 // literal cascade) that would silently split the two
8328 // projection paths of the same closed-set typed enum. Mirrors
8329 // the sibling three-path-convergence discipline the peer
8330 // [`crate::CaixaVersion`] typed newtype carries on its
8331 // `AsRef<str>` / `Display` / `as_str` triple
8332 // (version.rs pin
8333 // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
8334 // 16d5c7e).
8335 for &variant in RestartStrategy::ALL {
8336 let via_as_ref: &str = <RestartStrategy as AsRef<str>>::as_ref(&variant);
8337 let via_display: String = format!("{variant}");
8338 let via_accessor: &str = variant.as_str();
8339 assert_eq!(via_as_ref, via_accessor);
8340 assert_eq!(via_display, via_accessor);
8341 assert_eq!(via_as_ref, via_display.as_str());
8342 }
8343 }
8344
8345 #[test]
8346 fn restart_strategy_all_enumerates_every_variant_exactly_once() {
8347 // Fail-before-pass-after pin on the [`RestartStrategy::ALL`]
8348 // exhaustive-iteration surface: every variant appears exactly
8349 // once, and the slice length matches the arm count of the
8350 // closed set. Every consumer that walks the accepted-strategy
8351 // set (a future `feira supervisor --estrategia …` CLI-side
8352 // arg-parse's "did you mean" hint, a future M4 admission-
8353 // webhook's rejection body naming the accepted-`:estrategia`
8354 // list, the [`RestartStrategy::from_wire`] reverse-projection
8355 // consumers that iterate the accept-set for diagnostic
8356 // rendering) reads through this slice, so a future arm addition
8357 // that grows the enum but forgets to grow [`Self::ALL`]
8358 // silently truncates every downstream consumer's accept-set at
8359 // the same pre-addition boundary — this pin fails at caixa-core
8360 // build time on the pairwise-distinct + arm-count invariants.
8361 //
8362 // Peer of the sibling [`crate::CaixaKind::ALL`] (6b1f4fb) /
8363 // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
8364 // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
8365 // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
8366 // pins on the peer closed-set typed-enum axes.
8367 let all: &[RestartStrategy] = RestartStrategy::ALL;
8368 assert_eq!(
8369 all.len(),
8370 4,
8371 "RestartStrategy::ALL must enumerate every variant of the \
8372 four-arm closed set (OneForOne, OneForAll, RestForOne, \
8373 SimpleOneForOne); got {all:?}"
8374 );
8375 for (i, a) in all.iter().enumerate() {
8376 for (j, b) in all.iter().enumerate() {
8377 if i != j {
8378 assert_ne!(
8379 a, b,
8380 "RestartStrategy::ALL must carry every variant exactly \
8381 once — got duplicate {a:?} at indices {i} and {j}"
8382 );
8383 }
8384 }
8385 }
8386 for variant in [
8387 RestartStrategy::OneForOne,
8388 RestartStrategy::OneForAll,
8389 RestartStrategy::RestForOne,
8390 RestartStrategy::SimpleOneForOne,
8391 ] {
8392 assert!(
8393 all.contains(&variant),
8394 "RestartStrategy::ALL must contain {variant:?} — a future arm \
8395 addition that grows the enum but forgets to grow the ALL slice \
8396 silently truncates every downstream consumer's accept-set at \
8397 the pre-addition boundary"
8398 );
8399 }
8400 }
8401
8402 #[test]
8403 fn restart_strategy_wire_names_covers_every_arm() {
8404 // Load-bearing pin on the substrate-canonical
8405 // [`RestartStrategy::WIRE_NAMES`] exhaustive accept-set roster
8406 // on the `PascalCase` wire byte-string axis: every variant of
8407 // the sibling [`RestartStrategy::ALL`] exhaustive-iteration
8408 // surface must project through [`RestartStrategy::as_str`] onto
8409 // an entry the [`RestartStrategy::WIRE_NAMES`] roster carries,
8410 // and the roster's length must byte-equal
8411 // `RestartStrategy::ALL.len()` so a silent skew between the
8412 // [`RestartStrategy::as_str`] match's arm-set and the roster's
8413 // arm-set trips here at caixa-core test time rather than at a
8414 // downstream M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
8415 // admission-webhook rejection body's wire-form `:estrategia`
8416 // accepted-set enumeration miss / a `feira supervisor
8417 // --estrategia …` "did you mean" hint drift / a future
8418 // wasm-operator per-reconcile-step diagnostic log line's
8419 // accepted-wire-form enumeration miss. A future arm addition
8420 // (an OTP-`rest_for_all` arm the theory
8421 // [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
8422 // might reach for once the four canonical OTP strategies stop
8423 // covering the substrate's discovered load-shape) extends
8424 // [`RestartStrategy::ALL`] as a single edit and this pin
8425 // sweeps the new arm by iteration; the paired
8426 // [`RestartStrategy::WIRE_NAMES`] roster must grow in lockstep
8427 // or this assertion trips. Every entry is further pinned to
8428 // open with an ASCII uppercase byte so a silent collapse of
8429 // the wire-form axis with the peer kebab-case
8430 // dispatcher-catalog axis (an entry byte-identical to a
8431 // sibling [`Self::discriminant`] kebab byte-string that would
8432 // let a wire-axis consumer accept the dispatcher-catalog
8433 // vocabulary) trips here rather than at a downstream K8s-CR
8434 // round-trip miss.
8435 //
8436 // Peer of the sibling
8437 // [`crate::kind::tests::caixa_kind_wire_names_covers_every_arm`]
8438 // (bd708bd) pin on the top-level typed-kind discriminator's
8439 // `PascalCase` wire byte-string axis, and of the sibling
8440 // [`crate::upgrade::tests::upgrade_instruction_wire_forms_covers_every_arm`]
8441 // (cc42c0e) /
8442 // [`crate::upgrade::tests::upgrade_instruction_lisp_forms_covers_every_arm`]
8443 // (1898d77) pins on the OTP-appup discriminator's two-axis
8444 // roster split — the same closed-set exhaustive-roster
8445 // coverage discipline extended here onto the first M2
8446 // OTP-shape sibling-restart closed-set typed enum.
8447 //
8448 // Fail-before-pass-after locally verified by mutating one arm
8449 // of the paired [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
8450 // const family (e.g. dropping the trailing `e` from
8451 // `"OneForOne"` → `"OneForOn"`) — the length pin still passes
8452 // but the `contains` check fires on the mutated arm; and by
8453 // shortening the roster to three entries — the length pin
8454 // fires first.
8455 assert_eq!(
8456 RestartStrategy::WIRE_NAMES.len(),
8457 RestartStrategy::ALL.len(),
8458 "RestartStrategy::WIRE_NAMES.len() must byte-equal \
8459 RestartStrategy::ALL.len() — a mismatch means the roster \
8460 and the enum's arm-set have drifted; downstream consumers \
8461 that fan through both will silently disagree on the \
8462 accepted arm-set"
8463 );
8464 for &variant in RestartStrategy::ALL {
8465 let wire = variant.as_str();
8466 assert!(
8467 RestartStrategy::WIRE_NAMES.contains(&wire),
8468 "RestartStrategy::{variant:?}.as_str() = {wire:?} must \
8469 be a member of RestartStrategy::WIRE_NAMES — the \
8470 emitter and the roster have drifted out of lockstep"
8471 );
8472 }
8473 for tag in RestartStrategy::WIRE_NAMES {
8474 let first = tag.chars().next().unwrap_or_else(|| {
8475 panic!(
8476 "RestartStrategy::WIRE_NAMES entry {tag:?} must be \
8477 a non-empty PascalCase byte-string"
8478 )
8479 });
8480 assert!(
8481 first.is_ascii_uppercase(),
8482 "RestartStrategy::WIRE_NAMES entry {tag:?} must open \
8483 with an ASCII uppercase byte (PascalCase wire form) — \
8484 a lowercase entry would collide the wire-form axis \
8485 with the peer kebab-case dispatcher-catalog axis \
8486 [`RestartStrategy::discriminant`] serves"
8487 );
8488 }
8489 }
8490
8491 #[test]
8492 fn restart_strategy_from_wire_accepts_every_lifted_constant() {
8493 // Fail-before-pass-after pin on the forward accept-set of the
8494 // [`RestartStrategy::from_wire`] reverse projection: every
8495 // canonical [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
8496 // constant the [`RestartStrategy::as_str`] emitter walks parses
8497 // back to its paired variant. Any future arm addition that
8498 // grows the emitter's `as_str` match but forgets to grow the
8499 // parser's `from_wire` match silently splits the two halves of
8500 // the round-trip — the wire byte-string one non-serde consumer
8501 // parses from the one the emitter wrote — with the failure
8502 // surfacing at parse time far from the rebrand commit. Pinning
8503 // the four-arm accept-set here catches the drift at caixa-core
8504 // build time.
8505 //
8506 // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
8507 // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
8508 // accept-set pins on the peer closed-set typed-enum `str → Self`
8509 // axes.
8510 for (wire, expected) in [
8511 (
8512 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8513 RestartStrategy::OneForOne,
8514 ),
8515 (
8516 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8517 RestartStrategy::OneForAll,
8518 ),
8519 (
8520 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8521 RestartStrategy::RestForOne,
8522 ),
8523 (
8524 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8525 RestartStrategy::SimpleOneForOne,
8526 ),
8527 ] {
8528 let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
8529 panic!(
8530 "RestartStrategy::from_wire({wire:?}) must accept every \
8531 SUPERVISOR_ESTRATEGIA_* constant — got None for the \
8532 lifted canonical byte-string that RestartStrategy::{expected:?} \
8533 serializes as under SUPERVISOR_KEY_ESTRATEGIA"
8534 )
8535 });
8536 assert_eq!(
8537 parsed, expected,
8538 "RestartStrategy::from_wire({wire:?}) must return \
8539 RestartStrategy::{expected:?}; got RestartStrategy::{parsed:?}"
8540 );
8541 }
8542 }
8543
8544 #[test]
8545 fn restart_strategy_from_wire_round_trips_through_as_str() {
8546 // Fail-before-pass-after pin on the closed round-trip between
8547 // the forward [`RestartStrategy::as_str`] emitter and the
8548 // reverse [`RestartStrategy::from_wire`] parser: for every
8549 // variant in [`RestartStrategy::ALL`], parsing the emitter's
8550 // output must return exactly the same variant. Any per-arm
8551 // divergence — a future arm added to `as_str` but not
8552 // `from_wire`, an accidental copy-paste flip in one but not
8553 // the other — silently splits the emit and parse halves and
8554 // the failure surfaces at consumer parse time far from the
8555 // drift site. The `ALL`-iterating shape means a future arm
8556 // addition picks up the coverage by construction.
8557 //
8558 // Peer of the sibling
8559 // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
8560 // (18c7342) round-trip pin on
8561 // [`crate::aplicacao::PlacementStrategy::from_wire`] and
8562 // [`crate::kind::tests::caixa_kind_wire_round_trips_through_from_wire`]
8563 // (6b1f4fb) round-trip pin on [`crate::CaixaKind::from_wire`].
8564 for &variant in RestartStrategy::ALL {
8565 let wire = variant.as_str();
8566 let parsed = RestartStrategy::from_wire(wire).unwrap_or_else(|| {
8567 panic!(
8568 "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
8569 must be Some({variant:?}) — the two halves of the round-trip \
8570 dispatch on the same lifted SUPERVISOR_ESTRATEGIA_* consts; \
8571 got None on wire byte-string {wire:?}"
8572 )
8573 });
8574 assert_eq!(
8575 parsed, variant,
8576 "RestartStrategy::from_wire(RestartStrategy::{variant:?}.as_str()) \
8577 must round-trip to the same variant; got {parsed:?}"
8578 );
8579 }
8580 }
8581
8582 #[test]
8583 fn restart_strategy_from_wire_rejects_unknown_byte_strings() {
8584 // Fail-before-pass-after pin on the closed-set refusal
8585 // discipline of [`RestartStrategy::from_wire`]: every
8586 // byte-string outside the four-arm accept-set returns `None`
8587 // rather than silently collapsing onto the [`Default`]
8588 // (`OneForOne`) arm or an arbitrary neighbor. The refusal set
8589 // exercised here sweeps the load-bearing drift shapes: the
8590 // empty string (a stripped serde-attribute drift), all-
8591 // whitespace strings (the canonical text-editor accidental
8592 // padding shape), the kebab-case dispatcher-catalog identities
8593 // (`"one-for-one"` / `"one-for-all"` / `"rest-for-one"` /
8594 // `"simple-one-for-one"` — the [`gen_platform::FromStrKind`]-
8595 // derived [`std::str::FromStr`] accept-set, which parses the
8596 // *other* axis of this enum's two-axis split and must not leak
8597 // into the `from_wire` PascalCase-wire accept-set), the
8598 // lowercased single-word forms (`"oneforone"`), the padded
8599 // canonical scalar (`" OneForOne "`), the trailing-newline
8600 // shapes (`"OneForOne\n"`), and neighboring-but-unknown arms
8601 // (`"AllForOne"` — the canonical typo direction).
8602 //
8603 // Peer of the sibling
8604 // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
8605 // (2aa6d23) +
8606 // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
8607 // (18c7342) refusal pins on the peer closed-set typed-enum
8608 // axes.
8609 for bad in [
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 "OneForOnes",
8620 "one_for_one",
8621 "one for one",
8622 "ONEFORONE",
8623 "OneForOne ",
8624 " OneForOne",
8625 " SimpleOneForOne ",
8626 "OneForOne\n",
8627 "restforone",
8628 "REST_FOR_ONE",
8629 "AllForOne",
8630 "Simple",
8631 "?",
8632 ] {
8633 assert!(
8634 RestartStrategy::from_wire(bad).is_none(),
8635 "RestartStrategy::from_wire({bad:?}) must return None — the \
8636 parser's accept-set is exactly the four RestartStrategy::as_str \
8637 outputs (OneForOne, OneForAll, RestForOne, SimpleOneForOne), \
8638 and this byte-string is outside that closed set"
8639 );
8640 }
8641 }
8642
8643 #[test]
8644 fn restart_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
8645 // Fail-before-pass-after pin on the fourth path of the four-path
8646 // convergence: `from_wire` (the reverse projection) inverts the
8647 // `Serialize` derive's wire byte-string on every variant.
8648 // Together with the pre-existing three-path convergence
8649 // (`Display` + `as_str` + `Serialize` all resolve to the same
8650 // lifted [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const,
8651 // pinned by
8652 // [`restart_strategy_display_matches_serialized_wire_byte_string`])
8653 // this closes the round-trip: the wire byte-string the
8654 // `Serialize` derive emits parses back to the same variant
8655 // through `from_wire`, so any future serde-attribute or variant-
8656 // rename drift on the emit half now surfaces as a matched drift
8657 // on the parse half at caixa-core build time — the two halves
8658 // migrate as a unit through the lifted consts on any future
8659 // rename, and the round-trip cannot silently split.
8660 //
8661 // Peer of the sibling
8662 // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
8663 // (18c7342) wire-format pin on
8664 // [`crate::aplicacao::PlacementStrategy::from_wire`].
8665 for &variant in RestartStrategy::ALL {
8666 let wire = serde_json::to_string(&variant).unwrap();
8667 let unquoted = wire
8668 .strip_prefix('"')
8669 .and_then(|s| s.strip_suffix('"'))
8670 .expect("serialized RestartStrategy is a JSON string");
8671 let parsed = RestartStrategy::from_wire(unquoted).unwrap_or_else(|| {
8672 panic!(
8673 "RestartStrategy::from_wire({unquoted:?}) must accept the \
8674 Serialize derive's wire byte-string for \
8675 RestartStrategy::{variant:?} — the four-path convergence \
8676 (Display + as_str + Serialize + from_wire) resolves through \
8677 the same lifted SUPERVISOR_ESTRATEGIA_* const; got None"
8678 )
8679 });
8680 assert_eq!(
8681 parsed, variant,
8682 "RestartStrategy::from_wire of the Serialize derive's wire \
8683 byte-string for RestartStrategy::{variant:?} must round-trip \
8684 to the same variant; got {parsed:?}"
8685 );
8686 }
8687 }
8688
8689 #[test]
8690 fn restart_strategy_try_from_str_routes_through_from_wire_accessor() {
8691 // Fail-before-pass-after byte-parity pin on the newly lifted
8692 // `impl TryFrom<&str> for RestartStrategy` — asserts the standard-
8693 // library trait impl and the substrate-primitive
8694 // [`RestartStrategy::from_wire`] `Option<Self>` accessor resolve to
8695 // the same four-arm accept-set across every arm the exhaustive
8696 // [`RestartStrategy::ALL`] slice enumerates. Any future silent
8697 // detour that routes the trait impl through a divergent projection
8698 // (a per-arm inline `match s { "OneForOne" => Ok(Self::OneForOne),
8699 // … }` re-inlining that opens a compile-time link to the un-
8700 // lifted arm-literal, a hypothetical `#[serde(rename_all = "…")]`
8701 // attribute drift that silently splits the wire byte-string from
8702 // every consumer that reaches for this typed dispatch, an
8703 // accidental swap onto the kebab-case dispatcher-catalog axis the
8704 // pre-existing [`std::str::FromStr`] impl parses through and which
8705 // would collide the two-axis wire/catalog split the sibling
8706 // [`RestartStrategy::from_wire`] doc block makes load-bearing)
8707 // trips at caixa-core test time under `assert_eq!` rather than at
8708 // a downstream `impl TryFrom<&str>`-bound consumer's silent split.
8709 // Sweeps every one of the four arms [`RestartStrategy::ALL`]
8710 // carries so no arm's projection is covered only by the sibling
8711 // method-named `from_wire` path. Peer of the sibling
8712 // [`crate::kind::tests::caixa_kind_try_from_str_routes_through_from_wire_accessor`]
8713 // (3c83606),
8714 // [`crate::dialeto::tests::caixa_dialeto_try_from_str_routes_through_from_wire_accessor`]
8715 // (bf33136), and the M3
8716 // [`crate::aplicacao::tests::placement_strategy_try_from_str_routes_through_from_wire_accessor`]
8717 // (6fd00cd) — extends the trait-idiomatic reverse-projection axis
8718 // onto the first M2-OTP-shape closed-set typed enum on the caixa
8719 // surface.
8720 for &variant in RestartStrategy::ALL {
8721 let wire = variant.as_str();
8722 assert_eq!(
8723 <RestartStrategy as TryFrom<&str>>::try_from(wire),
8724 Ok(variant),
8725 "TryFrom<&str> impl on RestartStrategy must round-trip \
8726 RestartStrategy::{variant:?}.as_str() = {wire:?} back to \
8727 Ok(RestartStrategy::{variant:?}) — divergence from \
8728 RestartStrategy::from_wire signals a silent detour off \
8729 the substrate-primitive accessor"
8730 );
8731 assert_eq!(
8732 <RestartStrategy as TryFrom<&str>>::try_from(wire).ok(),
8733 RestartStrategy::from_wire(wire),
8734 "TryFrom<&str> ok()-projection on {wire:?} must byte-equal \
8735 RestartStrategy::from_wire on the same input"
8736 );
8737 }
8738 }
8739
8740 #[test]
8741 fn restart_strategy_try_from_str_rejects_unknown_byte_strings() {
8742 // Rejection witness on the `impl TryFrom<&str> for
8743 // RestartStrategy` — sweeps a candidate set of byte-strings
8744 // outside the four-arm PascalCase wire accept-set the sibling
8745 // [`RestartStrategy::as_str`] emits and asserts every one lands on
8746 // `Err(())`, so a future accidental widening of the trait impl's
8747 // accept-set (a stray additional
8748 // `_ if s.eq_ignore_ascii_case("OneForOne") => Ok(…)` case-fold
8749 // path, a silent inclusion of the kebab-case dispatcher-catalog
8750 // byte-string the pre-existing [`std::str::FromStr`] impl the
8751 // [`gen_platform::FromStrKind`] derive installs parses onto the
8752 // wire axis — which would collide the two-axis
8753 // wire/dispatcher-catalog split the sibling
8754 // [`RestartStrategy::from_wire`] doc block makes load-bearing —
8755 // an English-rebrand or plural-arm silent alias that would
8756 // widen the wire accept-set past the OTP-canonical four) trips at
8757 // caixa-core test time. The candidate set includes the empty
8758 // string, whitespace-only padding, the kebab-case dispatcher-
8759 // catalog byte-strings on the sibling axis (a caller who confuses
8760 // the two axes trips here rather than at a downstream consumer's
8761 // silent reject), a lowercase / uppercase / mixed-case fold of
8762 // each PascalCase arm (a caller who assumes case-fold acceptance
8763 // trips here), leading/trailing whitespace padding, the trailing-
8764 // newline shape, quote-wrapped candidates, and a residual set of
8765 // plausible-but-wrong English rebrand candidates. Peer of the
8766 // sibling
8767 // [`crate::kind::tests::caixa_kind_try_from_str_rejects_unknown_byte_strings`]
8768 // (3c83606) and
8769 // [`crate::aplicacao::tests::placement_strategy_try_from_str_rejects_unknown_byte_strings`]
8770 // (6fd00cd) rejection witnesses.
8771 let rejected: &[&str] = &[
8772 "",
8773 " ",
8774 "\n",
8775 "\t",
8776 "one-for-one",
8777 "one-for-all",
8778 "rest-for-one",
8779 "simple-one-for-one",
8780 "oneforone",
8781 "one_for_one",
8782 "OneForOnes",
8783 "ONEFORONE",
8784 "oneforall",
8785 "restforone",
8786 "simpleoneforone",
8787 "OneForOne ",
8788 " OneForOne",
8789 " OneForAll ",
8790 "OneForOne\n",
8791 "RestForOne\t",
8792 "OneForEach",
8793 "AllForOne",
8794 "one for one",
8795 "\"OneForOne\"",
8796 "?",
8797 ];
8798 for &input in rejected {
8799 assert_eq!(
8800 <RestartStrategy as TryFrom<&str>>::try_from(input),
8801 Err(()),
8802 "TryFrom<&str> impl on RestartStrategy must reject the \
8803 non-wire byte-string {input:?} — silent acceptance signals \
8804 an accept-set widening off the paired \
8805 RestartStrategy::from_wire resolver"
8806 );
8807 }
8808 }
8809
8810 #[test]
8811 fn restart_strategy_try_from_str_and_from_wire_partition_the_accept_set() {
8812 // Cross-axis partition pin: the paired `TryFrom<&str>` and
8813 // `from_wire` reverse projections must resolve identically on
8814 // *every* input, not just the ones [`RestartStrategy::ALL`]
8815 // enumerates. Sweeps a mixed candidate set spanning accepted
8816 // (four-arm PascalCase wire byte-strings) and rejected (kebab-case
8817 // dispatcher-catalog byte-strings, empty, whitespace-padded,
8818 // quoted, English-rebrand candidates) inputs and asserts the
8819 // trait's `Result::ok()` projection byte-equals the method-named
8820 // resolver's `Option<Self>` return-shape on each, locking the two
8821 // paths together by construction so any future detour (a stray
8822 // `try_from` special-case that widens or narrows the accept-set
8823 // outside the paired `from_wire` resolver, an accidental swap
8824 // onto the kebab-case [`std::str::FromStr`] impl the
8825 // [`gen_platform::FromStrKind`] derive installs on the sibling
8826 // dispatcher-catalog axis) trips at caixa-core test time. Peer of
8827 // the sibling
8828 // [`crate::kind::tests::caixa_kind_try_from_str_and_from_wire_partition_the_accept_set`]
8829 // pin — extends the round-trip discipline onto the M2-OTP-shape
8830 // sibling-restart axis.
8831 let candidates: &[&str] = &[
8832 "OneForOne",
8833 "OneForAll",
8834 "RestForOne",
8835 "SimpleOneForOne",
8836 "",
8837 "one-for-one",
8838 "one-for-all",
8839 "rest-for-one",
8840 "simple-one-for-one",
8841 "oneforone",
8842 "unknown",
8843 "OneForOne ",
8844 " OneForOne",
8845 "\"OneForOne\"",
8846 "OneForEach",
8847 "?",
8848 ];
8849 for &input in candidates {
8850 let via_trait: Option<RestartStrategy> =
8851 <RestartStrategy as TryFrom<&str>>::try_from(input).ok();
8852 let via_method: Option<RestartStrategy> = RestartStrategy::from_wire(input);
8853 assert_eq!(
8854 via_trait, via_method,
8855 "TryFrom<&str> and from_wire must resolve identically on \
8856 input {input:?} — divergence signals the two reverse-\
8857 projection paths have drifted onto different accept-sets"
8858 );
8859 }
8860 }
8861
8862 #[test]
8863 fn restart_strategy_from_into_static_str_routes_through_as_str_accessor() {
8864 // Fail-before-pass-after byte-parity pin on the newly lifted
8865 // `impl From<RestartStrategy> for &'static str` — asserts the
8866 // standard-library trait impl and the substrate-primitive
8867 // [`RestartStrategy::as_str`] `pub const fn` accessor resolve to
8868 // the same four-arm emit-set across every arm the exhaustive
8869 // [`RestartStrategy::ALL`] slice enumerates. Any future silent
8870 // detour that routes the trait impl through a divergent
8871 // projection (a per-arm inline `match strategy { OneForOne =>
8872 // "OneForOne", … }` re-inlining that opens a compile-time link to
8873 // the un-lifted arm-literal, an accidental swap onto the sibling
8874 // kebab-case [`Self::discriminant`] dispatcher-catalog axis that
8875 // would collide the two-axis wire/catalog split the sibling
8876 // [`RestartStrategy::from_wire`] doc block makes load-bearing) trips
8877 // at caixa-core test time under `assert_eq!` rather than at a
8878 // downstream `impl Into<&'static str>`-bound consumer's silent
8879 // split. Sweeps every one of the four arms
8880 // [`RestartStrategy::ALL`] carries so no arm's projection is
8881 // covered only by the sibling method-named `as_str` /
8882 // [`std::fmt::Display`] / [`AsRef<str>`] paths. Materializes the
8883 // `<&'static str as From<RestartStrategy>>::from` output in a
8884 // `const`-shape binding to make the `'static` lifetime promise a
8885 // build-time invariant — a future accidental downgrade of any of
8886 // the four arms' [`crate::render::SUPERVISOR_ESTRATEGIA_*`]
8887 // constants to a non-`&'static str` (a `String::leak()`-produced
8888 // return, a `Box::leak`-cast) trips at caixa-core build time
8889 // rather than at a downstream `'static`-bound consumer.
8890 const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
8891 const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
8892 const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
8893 const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
8894 for &variant in RestartStrategy::ALL {
8895 let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8896 let via_method: &'static str = variant.as_str();
8897 assert_eq!(
8898 via_trait, via_method,
8899 "From<RestartStrategy> for &'static str impl must round-trip \
8900 RestartStrategy::{variant:?} to the same lifted \
8901 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str returns — \
8902 divergence signals a silent detour off the substrate-primitive \
8903 accessor"
8904 );
8905 let via_into: &'static str = variant.into();
8906 assert_eq!(
8907 via_into, via_method,
8908 "Into<&'static str>::into on RestartStrategy::{variant:?} must \
8909 byte-equal RestartStrategy::as_str on the same input — the \
8910 blanket-derived Into shape must resolve to the same as_str \
8911 dispatch as the explicit From impl"
8912 );
8913 }
8914 assert_eq!(
8915 [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
8916 [
8917 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
8918 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
8919 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
8920 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
8921 ],
8922 "const-context RestartStrategy::as_str must resolve to the four \
8923 lifted SUPERVISOR_ESTRATEGIA_* consts — a future accidental \
8924 downgrade of any arm to a non-const or non-static byte-string \
8925 breaks the `&'static str`-lifetime promise the paired \
8926 From<RestartStrategy> for &'static str impl carries by \
8927 construction"
8928 );
8929 }
8930
8931 #[test]
8932 fn restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set() {
8933 // Cross-axis partition pin: the paired trait-idiomatic
8934 // `From<RestartStrategy> for &'static str` forward projection and
8935 // the method-named [`RestartStrategy::as_str`] forward projection
8936 // must resolve identically on *every* arm, not just the ones
8937 // named in the primary byte-parity pin above. Sweeps every
8938 // [`RestartStrategy::ALL`] arm and asserts the trait's `From::from`
8939 // output byte-equals the method-named accessor's return-value on
8940 // each, locking the two forward-projection paths together by
8941 // construction so any future detour (a stray `From` special-case
8942 // that lands on a divergent per-arm literal outside the paired
8943 // `as_str` dispatch, a hypothetical rebrand touching one axis
8944 // without the other) trips at caixa-core test time. Peer of the
8945 // sibling reverse-projection partition pin
8946 // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
8947 // — extends the round-trip discipline onto the trait-idiomatic
8948 // *forward* axis, closing the two-way `Self ↔ &'static str`
8949 // round-trip on the trait-idiomatic pair
8950 // (`From<Self> for &'static str` + `TryFrom<&str> for Self`) as
8951 // well as the pre-existing method-named pair
8952 // (`as_str` + `from_wire`).
8953 for &variant in RestartStrategy::ALL {
8954 let via_trait: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
8955 let via_method: &'static str = variant.as_str();
8956 assert_eq!(
8957 via_trait, via_method,
8958 "From<RestartStrategy> for &'static str and \
8959 RestartStrategy::as_str must resolve identically on \
8960 RestartStrategy::{variant:?} — divergence signals the \
8961 two forward-projection paths have drifted onto different \
8962 emit-sets"
8963 );
8964 }
8965 // Round-trip witness: every arm's forward `From` output re-parses
8966 // through the paired trait-idiomatic reverse `TryFrom<&str>` back
8967 // to the original variant. Closes the two-way `RestartStrategy ↔
8968 // &'static str` round-trip on the trait-idiomatic axis pair,
8969 // mirroring the pre-existing method-named `as_str` + `from_wire`
8970 // round-trip on the substrate-primitive axis pair.
8971 for &variant in RestartStrategy::ALL {
8972 let emitted: &'static str = variant.into();
8973 let re_parsed: Result<RestartStrategy, ()> =
8974 <RestartStrategy as TryFrom<&str>>::try_from(emitted);
8975 assert_eq!(
8976 re_parsed,
8977 Ok(variant),
8978 "trait-idiomatic axis pair must round-trip \
8979 RestartStrategy::{variant:?} through `.into::<&'static \
8980 str>()` and back through `TryFrom<&str>` — a break signals \
8981 the forward-emit and reverse-parse axes have drifted onto \
8982 different vocabularies"
8983 );
8984 }
8985 }
8986
8987 #[test]
8988 fn restart_strategy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
8989 // Fail-before-pass-after byte-parity pin on the newly lifted
8990 // `impl From<&RestartStrategy> for &'static str` — asserts the
8991 // borrowed-input standard-library trait impl and the substrate-
8992 // primitive [`RestartStrategy::as_str`] `pub const fn` accessor
8993 // resolve to the same four-arm emit-set across every arm the
8994 // exhaustive [`RestartStrategy::ALL`] slice enumerates. Rust's
8995 // `From` trait does not auto-derive the borrowed-input sibling
8996 // from a paired owned-input impl (no `impl<T, U> From<&T> for U
8997 // where T: Copy, U: From<T>` blanket in `core`), so the
8998 // borrowed-input axis is a distinct trait-idiomatic surface
8999 // that a `.iter().map(Into::into)` shape over
9000 // [`RestartStrategy::ALL`] (whose iterator yields
9001 // `&RestartStrategy`, not `RestartStrategy`) reaches through
9002 // this impl and no other — the paired owned-input
9003 // [`From<RestartStrategy>`] impl requires an explicit
9004 // `.copied()` / dereference before the trait fires.
9005 // Materializes the `<&'static str as
9006 // From<&RestartStrategy>>::from` output in a `const`-shape
9007 // binding to make the `'static` lifetime promise a build-time
9008 // invariant.
9009 const ONE_FOR_ONE: &str = RestartStrategy::OneForOne.as_str();
9010 const ONE_FOR_ALL: &str = RestartStrategy::OneForAll.as_str();
9011 const REST_FOR_ONE: &str = RestartStrategy::RestForOne.as_str();
9012 const SIMPLE_ONE_FOR_ONE: &str = RestartStrategy::SimpleOneForOne.as_str();
9013 for variant in RestartStrategy::ALL {
9014 let via_trait: &'static str = <&'static str as From<&RestartStrategy>>::from(variant);
9015 let via_method: &'static str = variant.as_str();
9016 assert_eq!(
9017 via_trait, via_method,
9018 "From<&RestartStrategy> for &'static str impl must \
9019 round-trip &RestartStrategy::{variant:?} to the same \
9020 lifted SUPERVISOR_ESTRATEGIA_* const \
9021 RestartStrategy::as_str returns — divergence signals a \
9022 silent detour off the substrate-primitive accessor"
9023 );
9024 let via_into: &'static str = variant.into();
9025 assert_eq!(
9026 via_into, via_method,
9027 "Into<&'static str>::into on &RestartStrategy::{variant:?} \
9028 must byte-equal RestartStrategy::as_str on the same input — \
9029 the blanket-derived Into shape must resolve to the same \
9030 as_str dispatch as the explicit From impl"
9031 );
9032 }
9033 assert_eq!(
9034 [ONE_FOR_ONE, ONE_FOR_ALL, REST_FOR_ONE, SIMPLE_ONE_FOR_ONE],
9035 [
9036 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ONE,
9037 crate::render::SUPERVISOR_ESTRATEGIA_ONE_FOR_ALL,
9038 crate::render::SUPERVISOR_ESTRATEGIA_REST_FOR_ONE,
9039 crate::render::SUPERVISOR_ESTRATEGIA_SIMPLE_ONE_FOR_ONE,
9040 ],
9041 "const-context RestartStrategy::as_str must resolve to the \
9042 four lifted SUPERVISOR_ESTRATEGIA_* consts — the borrowed-\
9043 input From<&RestartStrategy> for &'static str impl inherits \
9044 its `'static` lifetime promise from the same accessor the \
9045 owned-input sibling routes through"
9046 );
9047 }
9048
9049 #[test]
9050 fn restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
9051 // Cross-axis partition pin: the paired trait-idiomatic
9052 // owned-input `From<RestartStrategy> for &'static str` (523157d
9053 // campaign-shape) and borrowed-input `From<&RestartStrategy> for
9054 // &'static str` (this lift) forward projections must resolve
9055 // identically on every arm, locking the two input-shape paths
9056 // together so any future detour trips at caixa-core test time.
9057 // Then a witness that a `.iter().map(Into::into)` pipe over
9058 // [`RestartStrategy::ALL`] (whose iterator yields
9059 // `&RestartStrategy`) materializes the four-arm accept-set
9060 // through the borrowed-input axis alone — the exact shape a
9061 // future wasm-operator per-supervisor sibling-restart-strategy
9062 // diagnostic line, a future substrate-wide per-arm diagnostic
9063 // column, or a
9064 // `HashMap::<&'static str, RestartStrategy>::from_iter(
9065 // RestartStrategy::ALL.iter().map(|s| (s.into(), *s)))`-style
9066 // per-strategy lookup reaches through — closing the two-way
9067 // owned/borrowed input-shape symmetry on the forward-projection
9068 // trait-idiomatic axis. Peer of the sibling
9069 // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9070 // (64aa742) /
9071 // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9072 // (5ab993a) /
9073 // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
9074 // (807b0b5) partition pins on the sibling closed-set typed-enum
9075 // discriminator axes — extends the borrowed-input axis
9076 // discipline onto the first M2 OTP-shape sibling-restart
9077 // closed-set typed enum on the caixa surface. Also closes the
9078 // direct two-way `&Self → &'static str → Self` round-trip via
9079 // the paired [`TryFrom<&str>`] axis — unlike the peer
9080 // [`crate::CaixaKind`] axis pair (whose forward `From` emits
9081 // lowercase Portuguese diagnostic bytes while the reverse
9082 // `TryFrom` parses `PascalCase` wire bytes, forcing the round-
9083 // trip through an intermediate wire-vocab hop), the
9084 // [`RestartStrategy::as_str`] emit and
9085 // [`RestartStrategy::from_wire`] parse share the same
9086 // `PascalCase` vocabulary by construction, so the borrowed-
9087 // input forward axis and the reverse axis compose directly.
9088 for &variant in RestartStrategy::ALL {
9089 let owned: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
9090 let borrowed: &'static str = <&'static str as From<&RestartStrategy>>::from(&variant);
9091 assert_eq!(
9092 owned, borrowed,
9093 "From<RestartStrategy> and From<&RestartStrategy> for \
9094 &'static str must resolve identically on \
9095 RestartStrategy::{variant:?} — divergence signals the \
9096 owned-input and borrowed-input forward-projection paths \
9097 have drifted onto different emit-sets"
9098 );
9099 }
9100 let via_iter: Vec<&'static str> = RestartStrategy::ALL.iter().map(Into::into).collect();
9101 let via_method: Vec<&'static str> =
9102 RestartStrategy::ALL.iter().map(|s| s.as_str()).collect();
9103 assert_eq!(
9104 via_iter, via_method,
9105 "`.iter().map(Into::into)` over RestartStrategy::ALL must \
9106 byte-equal `.iter().map(|s| s.as_str())` on every arm — the \
9107 borrowed-input `From<&RestartStrategy> for &'static str` \
9108 axis is what makes the `.iter().map(Into::into)` shape route \
9109 through the substrate-primitive `RestartStrategy::as_str` \
9110 accessor rather than through a per-call-site `.copied()` / \
9111 dereference detour"
9112 );
9113 for variant in RestartStrategy::ALL {
9114 let emitted: &'static str = variant.into();
9115 let re_parsed: Result<RestartStrategy, ()> =
9116 <RestartStrategy as TryFrom<&str>>::try_from(emitted);
9117 assert_eq!(
9118 re_parsed,
9119 Ok(*variant),
9120 "trait-idiomatic borrowed-input forward-projection + \
9121 reverse-projection axis pair must round-trip \
9122 &RestartStrategy::{variant:?} through `.into::<&'static \
9123 str>()` (via the borrowed-input axis) and back through \
9124 `TryFrom<&str>` — a break signals the borrowed-input \
9125 forward-emit and reverse-parse axes have drifted onto \
9126 different vocabularies"
9127 );
9128 }
9129 }
9130
9131 #[test]
9132 fn restart_strategy_from_into_owned_string_routes_through_as_str_accessor() {
9133 // Fail-before-pass-after byte-parity pin on the newly lifted
9134 // `impl From<RestartStrategy> for String` — asserts the
9135 // owned-`String`-returning standard-library trait impl and the
9136 // substrate-primitive [`RestartStrategy::as_str`] `pub const fn`
9137 // accessor resolve to the same four-arm emit-set across every
9138 // arm the exhaustive [`RestartStrategy::ALL`] slice enumerates.
9139 // Rust's standard library does not carry a blanket
9140 // `impl<T: AsRef<str>> From<T> for String` (nor an
9141 // `impl<T: fmt::Display> From<T> for String`), so the
9142 // owned-`String` forward-projection axis is a distinct
9143 // trait-idiomatic surface that a
9144 // `let key: String = strategy.into();`-shaped call site
9145 // reaches through this impl and no other — the paired sibling
9146 // `From<RestartStrategy> for &'static str` impl forces every
9147 // owned-`String` call site through an explicit
9148 // `.to_owned()` / `String::from` restatement.
9149 for &variant in RestartStrategy::ALL {
9150 let via_trait: String = <String as From<RestartStrategy>>::from(variant);
9151 let via_method: &'static str = variant.as_str();
9152 assert_eq!(
9153 via_trait.as_str(),
9154 via_method,
9155 "From<RestartStrategy> for String impl must round-trip \
9156 RestartStrategy::{variant:?} to the same lifted \
9157 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
9158 returns — divergence signals a silent detour off the \
9159 substrate-primitive accessor"
9160 );
9161 let via_into: String = variant.into();
9162 assert_eq!(
9163 via_into.as_str(),
9164 via_method,
9165 "Into<String>::into on RestartStrategy::{variant:?} must \
9166 byte-equal RestartStrategy::as_str on the same input — the \
9167 blanket-derived Into shape must resolve to the same as_str \
9168 dispatch as the explicit From impl"
9169 );
9170 }
9171 }
9172
9173 #[test]
9174 fn restart_strategy_from_into_owned_string_and_static_str_agree_on_every_arm() {
9175 // Cross-axis partition pin: the paired trait-idiomatic
9176 // owned-`String` `From<RestartStrategy> for String` (this lift)
9177 // and owned-`&'static str` `From<RestartStrategy> for &'static
9178 // str` (523157d) forward projections must resolve identically
9179 // on every arm, locking the two return-type-shape paths
9180 // together so any future detour trips at caixa-core test time.
9181 // Also byte-parity witness against the sibling
9182 // [`ToString::to_string`] surface routed through
9183 // [`std::fmt::Display`] — the three owned-heap-string paths
9184 // (`.into::<String>()`, `String::from`, `.to_string()`) must
9185 // resolve identically on every arm so a future consumer that
9186 // picks any of the three lands on the same lifted
9187 // SUPERVISOR_ESTRATEGIA_* const. Then a direct round-trip
9188 // witness through the paired trait-idiomatic reverse
9189 // [`TryFrom<&str>`] axis on the owned-`String`'s
9190 // [`String::as_str`] borrow that closes the two-way
9191 // `Self → String → Self` round-trip on the trait-idiomatic
9192 // owned-`String` forward + reverse axis pair.
9193 for &variant in RestartStrategy::ALL {
9194 let owned_string: String = <String as From<RestartStrategy>>::from(variant);
9195 let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
9196 assert_eq!(
9197 owned_string.as_str(),
9198 owned_static,
9199 "From<RestartStrategy> for String and From<RestartStrategy> \
9200 for &'static str must resolve identically on \
9201 RestartStrategy::{variant:?} — divergence signals the \
9202 owned-`String` and owned-`&'static str` forward-projection \
9203 return-type-shape paths have drifted onto different \
9204 emit-sets"
9205 );
9206 let via_to_string: String = variant.to_string();
9207 assert_eq!(
9208 owned_string, via_to_string,
9209 "From<RestartStrategy> for String must byte-equal \
9210 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
9211 divergence signals the trait-idiomatic owned-`String` \
9212 forward-projection axis and the ToString-through-Display \
9213 axis have drifted onto different emit-sets"
9214 );
9215 }
9216 let via_iter: Vec<String> = RestartStrategy::ALL
9217 .iter()
9218 .copied()
9219 .map(String::from)
9220 .collect();
9221 let via_method: Vec<String> = RestartStrategy::ALL
9222 .iter()
9223 .map(|s| s.as_str().to_owned())
9224 .collect();
9225 assert_eq!(
9226 via_iter, via_method,
9227 "`.iter().copied().map(String::from)` over RestartStrategy::ALL \
9228 must byte-equal `.iter().map(|s| s.as_str().to_owned())` on \
9229 every arm — the owned-`String` `From<RestartStrategy> for \
9230 String` axis is what makes the `String::from` composition \
9231 route through the substrate-primitive `RestartStrategy::as_str` \
9232 accessor rather than through a per-call-site `.to_owned()` / \
9233 `String::from(strategy.as_str())` detour"
9234 );
9235 for &variant in RestartStrategy::ALL {
9236 let emitted: String = variant.into();
9237 let re_parsed: Result<RestartStrategy, ()> =
9238 <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
9239 assert_eq!(
9240 re_parsed,
9241 Ok(variant),
9242 "trait-idiomatic owned-`String` forward-projection + \
9243 reverse-projection axis pair must round-trip \
9244 RestartStrategy::{variant:?} through `.into::<String>()` \
9245 and back through `TryFrom<&str>` on the owned-`String`'s \
9246 String::as_str borrow — a break signals the owned-`String` \
9247 forward-emit and reverse-parse axes have drifted onto \
9248 different vocabularies"
9249 );
9250 }
9251 }
9252
9253 #[test]
9254 fn restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
9255 // Fail-before-pass-after byte-parity pin on the newly lifted
9256 // `impl From<&RestartStrategy> for String` — asserts the
9257 // borrowed-input owned-`String`-returning standard-library trait
9258 // impl and the substrate-primitive [`RestartStrategy::as_str`]
9259 // `pub const fn` accessor resolve to the same four-arm emit-set
9260 // across every arm the exhaustive [`RestartStrategy::ALL`] slice
9261 // enumerates. Rust's standard library does not carry a blanket
9262 // `impl<T: AsRef<str>> From<&T> for String` (nor an
9263 // `impl<T: fmt::Display> From<&T> for String`), so the
9264 // borrowed-input owned-`String` forward-projection axis is a
9265 // distinct trait-idiomatic surface that a
9266 // `let key: String = (&strategy).into();`-shaped call site
9267 // reaches through this impl and no other — the paired sibling
9268 // `From<RestartStrategy> for String` impl forces every
9269 // borrowed-input call site through an explicit `Copy` deref
9270 // (`String::from(*strategy)`) or an `.as_str().to_owned()` /
9271 // `.to_string()` detour.
9272 for &variant in RestartStrategy::ALL {
9273 let via_trait: String = <String as From<&RestartStrategy>>::from(&variant);
9274 let via_method: &'static str = variant.as_str();
9275 assert_eq!(
9276 via_trait.as_str(),
9277 via_method,
9278 "From<&RestartStrategy> for String impl must round-trip \
9279 &RestartStrategy::{variant:?} to the same lifted \
9280 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
9281 returns — divergence signals a silent detour off the \
9282 substrate-primitive accessor"
9283 );
9284 let via_into: String = (&variant).into();
9285 assert_eq!(
9286 via_into.as_str(),
9287 via_method,
9288 "Into<String>::into on &RestartStrategy::{variant:?} must \
9289 byte-equal RestartStrategy::as_str on the same input — the \
9290 blanket-derived Into shape must resolve to the same as_str \
9291 dispatch as the explicit From impl"
9292 );
9293 }
9294 }
9295
9296 #[test]
9297 fn restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
9298 // Cross-axis partition pin: the newly lifted trait-idiomatic
9299 // borrowed-input owned-`String` `From<&RestartStrategy> for
9300 // String` (this lift), the paired owned-input owned-`String`
9301 // `From<RestartStrategy> for String` (7baa18a), the paired
9302 // borrowed-input owned-`&'static str` `From<&RestartStrategy>
9303 // for &'static str` (e941836), and the paired owned-input
9304 // owned-`&'static str` `From<RestartStrategy> for &'static str`
9305 // (523157d) — every corner of the `{Self, &Self} × {&'static
9306 // str, String}` 2×2 trait-idiomatic projection family — must
9307 // resolve identically on every arm, locking the four
9308 // return-shape × input-shape paths together so any future
9309 // detour trips at caixa-core test time. Also byte-parity
9310 // witness against the sibling [`ToString::to_string`] surface
9311 // routed through [`std::fmt::Display`] and a direct round-trip
9312 // witness through the paired trait-idiomatic reverse
9313 // [`TryFrom<&str>`] axis on the owned-`String`'s
9314 // [`String::as_str`] borrow that closes the two-way
9315 // `&Self → String → Self` round-trip on the trait-idiomatic
9316 // borrowed-input owned-`String` forward + reverse axis pair.
9317 for &variant in RestartStrategy::ALL {
9318 let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
9319 let owned_string: String = <String as From<RestartStrategy>>::from(variant);
9320 let borrowed_static: &'static str =
9321 <&'static str as From<&RestartStrategy>>::from(&variant);
9322 let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
9323 assert_eq!(
9324 borrowed_string, owned_string,
9325 "From<&RestartStrategy> for String and From<RestartStrategy> \
9326 for String must resolve identically on \
9327 RestartStrategy::{variant:?} — divergence signals the \
9328 borrowed-input and owned-input owned-`String` \
9329 forward-projection input-shape paths have drifted onto \
9330 different emit-sets"
9331 );
9332 assert_eq!(
9333 borrowed_string.as_str(),
9334 borrowed_static,
9335 "From<&RestartStrategy> for String and From<&RestartStrategy> \
9336 for &'static str must resolve identically on \
9337 RestartStrategy::{variant:?} — divergence signals the \
9338 borrowed-input `&'static str` and owned-`String` \
9339 return-shape paths have drifted onto different emit-sets"
9340 );
9341 assert_eq!(
9342 borrowed_string.as_str(),
9343 owned_static,
9344 "From<&RestartStrategy> for String and From<RestartStrategy> \
9345 for &'static str must resolve identically on \
9346 RestartStrategy::{variant:?} — divergence signals a break \
9347 in the diagonal corner of the {{Self, &Self}} × \
9348 {{&'static str, String}} 2×2 trait-idiomatic \
9349 projection family"
9350 );
9351 let via_to_string: String = variant.to_string();
9352 assert_eq!(
9353 borrowed_string, via_to_string,
9354 "From<&RestartStrategy> for String must byte-equal \
9355 RestartStrategy::to_string on RestartStrategy::{variant:?} — \
9356 divergence signals the trait-idiomatic borrowed-input \
9357 owned-`String` forward-projection axis and the \
9358 ToString-through-Display axis have drifted onto different \
9359 emit-sets"
9360 );
9361 }
9362 let via_iter: Vec<String> = RestartStrategy::ALL.iter().map(String::from).collect();
9363 let via_method: Vec<String> = RestartStrategy::ALL
9364 .iter()
9365 .map(|s| s.as_str().to_owned())
9366 .collect();
9367 assert_eq!(
9368 via_iter, via_method,
9369 "`.iter().map(String::from)` over RestartStrategy::ALL — a \
9370 call site whose iteration axis holds `&RestartStrategy` by \
9371 construction — must byte-equal `.iter().map(|s| \
9372 s.as_str().to_owned())` on every arm — the borrowed-input \
9373 owned-`String` `From<&RestartStrategy> for String` axis is \
9374 what makes the `String::from` composition route through the \
9375 substrate-primitive `RestartStrategy::as_str` accessor \
9376 without a spurious `Copy` deref (which would only be \
9377 reachable through the owned-input `From<RestartStrategy> for \
9378 String` axis by first calling `.copied()` on the iterator)"
9379 );
9380 for &variant in RestartStrategy::ALL {
9381 let emitted: String = (&variant).into();
9382 let re_parsed: Result<RestartStrategy, ()> =
9383 <RestartStrategy as TryFrom<&str>>::try_from(emitted.as_str());
9384 assert_eq!(
9385 re_parsed,
9386 Ok(variant),
9387 "trait-idiomatic borrowed-input owned-`String` \
9388 forward-projection + reverse-projection axis pair must \
9389 round-trip &RestartStrategy::{variant:?} through \
9390 `.into::<String>()` on the borrowed-input surface and \
9391 back through `TryFrom<&str>` on the owned-`String`'s \
9392 String::as_str borrow — a break signals the \
9393 borrowed-input owned-`String` forward-emit and \
9394 reverse-parse axes have drifted onto different \
9395 vocabularies"
9396 );
9397 }
9398 }
9399
9400 #[test]
9401 fn restart_strategy_from_into_static_cow_str_routes_through_as_str_accessor() {
9402 // Fail-before-pass-after byte-parity pin on the newly lifted
9403 // `impl From<RestartStrategy> for std::borrow::Cow<'static, str>` —
9404 // asserts the standard-library trait impl and the substrate-
9405 // primitive [`super::RestartStrategy::as_str`] `pub const fn`
9406 // accessor resolve to the same four-arm emit-set across every
9407 // arm the exhaustive [`super::RestartStrategy::ALL`] slice
9408 // enumerates. Rust's standard library does not carry a blanket
9409 // `impl<T: AsRef<str>> From<T> for Cow<'static, str>` (nor an
9410 // `impl<T: fmt::Display> From<T> for Cow<'static, str>`), so
9411 // the `Cow<'static, str>` forward-projection axis is a
9412 // distinct trait-idiomatic surface that a
9413 // `let key: Cow<'static, str> = strategy.into();`-shaped call
9414 // site reaches through this impl and no other — the paired
9415 // sibling `From<RestartStrategy> for &'static str` and
9416 // `From<RestartStrategy> for String` impls force every
9417 // `Cow<'static, str>`-parameterized call site through a
9418 // `Cow::Borrowed(strategy.as_str())` /
9419 // `Cow::Owned(strategy.to_string())` composition whose type
9420 // bounds have no compile-time link back to the substrate
9421 // primitive.
9422 //
9423 // Also asserts the projection lands on the zero-alloc
9424 // [`std::borrow::Cow::Borrowed`] arm (not the
9425 // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
9426 // [`super::RestartStrategy::as_str`] accessor's `&'static str`
9427 // return lifetime by construction makes the borrowed arm the
9428 // type-correct projection with no runtime allocation. Any
9429 // future silent detour that routes the impl through the owned
9430 // arm (an accidental `Cow::Owned(strategy.to_string())` rewrite
9431 // that would allocate on every call site where the
9432 // `&'static str` return of [`super::RestartStrategy::as_str`]
9433 // makes the zero-alloc borrowed projection type-correct) trips
9434 // at caixa-core test time under the
9435 // [`std::borrow::Cow::Borrowed`] discriminator witness rather
9436 // than at a downstream `Cow<'static, str>`-bound consumer's
9437 // silent allocation.
9438 //
9439 // First peer on the substrate-wide trait-idiomatic
9440 // [`std::borrow::Cow<'static, str>`] forward-projection family
9441 // to extend the axis off the top-level [`super::CaixaKind`]
9442 // enum (99c1735 owned-input, d45c409 borrowed-input) onto the
9443 // first M2 OTP-shape closed-set fieldless typed enum on the
9444 // caixa surface.
9445 for &variant in RestartStrategy::ALL {
9446 let via_trait: std::borrow::Cow<'static, str> =
9447 <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
9448 let via_method: &'static str = variant.as_str();
9449 assert_eq!(
9450 via_trait.as_ref(),
9451 via_method,
9452 "From<RestartStrategy> for Cow<'static, str> impl must \
9453 round-trip RestartStrategy::{variant:?} to the same \
9454 lifted SUPERVISOR_ESTRATEGIA_* const \
9455 RestartStrategy::as_str returns — divergence signals a \
9456 silent detour off the substrate-primitive accessor"
9457 );
9458 assert!(
9459 matches!(via_trait, std::borrow::Cow::Borrowed(_)),
9460 "From<RestartStrategy> for Cow<'static, str> impl must \
9461 land on the zero-alloc Cow::Borrowed arm on \
9462 RestartStrategy::{variant:?} — a Cow::Owned outcome \
9463 signals the projection has silently allocated where \
9464 the substrate-primitive RestartStrategy::as_str \
9465 `&'static str` return makes the borrowed arm the \
9466 type-correct projection"
9467 );
9468 let via_into: std::borrow::Cow<'static, str> = variant.into();
9469 assert_eq!(
9470 via_into.as_ref(),
9471 via_method,
9472 "Into<Cow<'static, str>>::into on \
9473 RestartStrategy::{variant:?} must byte-equal \
9474 RestartStrategy::as_str on the same input — the \
9475 blanket-derived Into shape must resolve to the same \
9476 as_str dispatch as the explicit From impl"
9477 );
9478 assert!(
9479 matches!(via_into, std::borrow::Cow::Borrowed(_)),
9480 "Into<Cow<'static, str>>::into on \
9481 RestartStrategy::{variant:?} must land on the \
9482 zero-alloc Cow::Borrowed arm — the blanket-derived \
9483 Into shape must resolve to the same Cow::Borrowed \
9484 dispatch as the explicit From impl"
9485 );
9486 }
9487 }
9488
9489 #[test]
9490 fn restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
9491 // Cross-axis partition pin: the newly lifted trait-idiomatic
9492 // `From<RestartStrategy> for std::borrow::Cow<'static, str>`
9493 // (this lift), the paired owned-input `From<RestartStrategy>
9494 // for &'static str` (523157d), and the paired owned-input
9495 // `From<RestartStrategy> for String` (7baa18a) forward
9496 // projections must resolve identically on every arm, locking
9497 // the three return-shape paths together by construction so any
9498 // future detour trips at caixa-core test time. Also byte-parity
9499 // witness against the sibling [`ToString::to_string`] surface
9500 // routed through [`std::fmt::Display`] — every owned-heap-
9501 // string path (the `Cow::Owned` promotion of this axis's
9502 // `.into_owned()`, `From<RestartStrategy> for String`, and
9503 // `.to_string()`) resolves to the same lifted
9504 // [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const per arm.
9505 //
9506 // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
9507 // witness over [`super::RestartStrategy::ALL`] that
9508 // materializes the four-arm accept-set through the
9509 // [`std::borrow::Cow<'static, str>`] axis alone — the exact
9510 // shape a future `axum::response::IntoResponse` per-strategy
9511 // rejection-body composer, a future M4 admission-webhook
9512 // per-strategy rejection-reason emitter whose typing rules out
9513 // the sibling [`AsRef<str>`] borrowed return, or a future
9514 // substrate-wide per-strategy diagnostic surface that binds
9515 // through a [`Cow<'static, str>`] boundary reaches through.
9516 // The pipe witness also pins the zero-alloc discipline: every
9517 // element in the collected vector satisfies the
9518 // [`std::borrow::Cow::Borrowed`] arm predicate, so a future
9519 // accidental silent-allocation regression on the pipe's
9520 // iteration axis is a caixa-core-test-time failure.
9521 for &variant in RestartStrategy::ALL {
9522 let via_cow: std::borrow::Cow<'static, str> =
9523 <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
9524 let via_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
9525 let via_string: String = <String as From<RestartStrategy>>::from(variant);
9526 assert_eq!(
9527 via_cow.as_ref(),
9528 via_static,
9529 "From<RestartStrategy> for Cow<'static, str> and \
9530 From<RestartStrategy> for &'static str must resolve \
9531 identically on RestartStrategy::{variant:?} — \
9532 divergence signals the Cow<'static, str> and \
9533 &'static str return-shape paths have drifted onto \
9534 different emit-sets"
9535 );
9536 assert_eq!(
9537 via_cow.as_ref(),
9538 via_string.as_str(),
9539 "From<RestartStrategy> for Cow<'static, str> and \
9540 From<RestartStrategy> for String must resolve \
9541 identically on RestartStrategy::{variant:?} — \
9542 divergence signals the Cow<'static, str> and String \
9543 return-shape paths have drifted onto different \
9544 emit-sets"
9545 );
9546 let via_to_string: String = variant.to_string();
9547 assert_eq!(
9548 via_cow.as_ref(),
9549 via_to_string.as_str(),
9550 "From<RestartStrategy> for Cow<'static, str> must \
9551 byte-equal RestartStrategy::to_string on \
9552 RestartStrategy::{variant:?} — divergence signals the \
9553 trait-idiomatic Cow<'static, str> forward-projection \
9554 axis and the ToString-through-Display axis have \
9555 drifted onto different emit-sets"
9556 );
9557 }
9558 let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
9559 .iter()
9560 .copied()
9561 .map(std::borrow::Cow::from)
9562 .collect();
9563 let via_method: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
9564 .iter()
9565 .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
9566 .collect();
9567 assert_eq!(
9568 via_iter, via_method,
9569 "`.iter().copied().map(Cow::from)` over \
9570 RestartStrategy::ALL must byte-equal `.iter().map(|s| \
9571 Cow::Borrowed(s.as_str()))` on every arm — the \
9572 trait-idiomatic `From<RestartStrategy> for Cow<'static, \
9573 str>` axis is what makes the `Cow::from` composition \
9574 route through the substrate-primitive \
9575 `RestartStrategy::as_str` accessor with the zero-alloc \
9576 Cow::Borrowed arm by construction, rather than a \
9577 per-call-site `Cow::Owned(strategy.to_string())` \
9578 allocation"
9579 );
9580 for cow in &via_iter {
9581 assert!(
9582 matches!(cow, std::borrow::Cow::Borrowed(_)),
9583 "every element of the \
9584 .iter().copied().map(Cow::from) pipe over \
9585 RestartStrategy::ALL must land on the zero-alloc \
9586 Cow::Borrowed arm — a Cow::Owned outcome on any arm \
9587 signals the pipe's iteration axis has silently \
9588 allocated where the substrate-primitive \
9589 RestartStrategy::as_str `&'static str` return makes \
9590 the borrowed arm the type-correct projection"
9591 );
9592 }
9593 }
9594
9595 #[test]
9596 fn restart_strategy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
9597 // Fail-before-pass-after byte-parity pin on the newly lifted
9598 // `impl From<&RestartStrategy> for std::borrow::Cow<'static, str>` —
9599 // asserts the borrowed-input standard-library trait impl and
9600 // the substrate-primitive [`super::RestartStrategy::as_str`]
9601 // `pub const fn` accessor resolve to the same four-arm emit-
9602 // set across every arm the exhaustive
9603 // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
9604 // standard library does not carry a blanket
9605 // `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor a
9606 // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
9607 // the borrowed-input `Cow<'static, str>` forward-projection
9608 // axis is a distinct trait-idiomatic surface that a
9609 // `let key: Cow<'static, str> = (&strategy).into();`-shaped
9610 // call site or a
9611 // `RestartStrategy::ALL.iter().map(Cow::from)`-shaped pipe
9612 // reaches through this impl and no other — the paired owned-
9613 // input `From<RestartStrategy> for Cow<'static, str>` impl
9614 // (7dd28b3) forces every borrowed-input call site through an
9615 // explicit `Copy` deref (`Cow::from(*strategy)`) or a
9616 // `Cow::Borrowed(strategy.as_str())` open-code whose type
9617 // bounds have no compile-time link back to the substrate
9618 // primitive.
9619 //
9620 // Also asserts the projection lands on the zero-alloc
9621 // [`std::borrow::Cow::Borrowed`] arm (not the
9622 // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
9623 // [`super::RestartStrategy::as_str`] accessor's `&'static str`
9624 // return lifetime by construction makes the borrowed arm the
9625 // type-correct projection with no runtime allocation on the
9626 // borrowed-input surface just as on the paired owned-input
9627 // surface.
9628 //
9629 // Second peer on the substrate-wide trait-idiomatic
9630 // [`std::borrow::Cow<'static, str>`] forward-projection family
9631 // on this enum — closes the `{Self, &Self}` input-shape
9632 // corner of the [`Cow<'static, str>`] axis on the first M2
9633 // OTP-shape closed-set fieldless typed enum peer on the caixa
9634 // surface (`:supervisor :estrategia`), exactly as d45c409
9635 // closed it on the top-level [`super::CaixaKind`] one commit
9636 // after the owning half (99c1735) landed. Every future
9637 // closed-set fieldless typed enum peer on the substrate is a
9638 // future target of the campaign.
9639 for &variant in RestartStrategy::ALL {
9640 let via_trait: std::borrow::Cow<'static, str> =
9641 <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
9642 let via_method: &'static str = variant.as_str();
9643 assert_eq!(
9644 via_trait.as_ref(),
9645 via_method,
9646 "From<&RestartStrategy> for Cow<'static, str> impl must \
9647 round-trip &RestartStrategy::{variant:?} to the same \
9648 lifted SUPERVISOR_ESTRATEGIA_* const \
9649 RestartStrategy::as_str returns — divergence signals a \
9650 silent detour off the substrate-primitive accessor"
9651 );
9652 assert!(
9653 matches!(via_trait, std::borrow::Cow::Borrowed(_)),
9654 "From<&RestartStrategy> for Cow<'static, str> impl must \
9655 land on the zero-alloc Cow::Borrowed arm on \
9656 &RestartStrategy::{variant:?} — a Cow::Owned outcome \
9657 signals the projection has silently allocated where \
9658 the substrate-primitive RestartStrategy::as_str \
9659 `&'static str` return makes the borrowed arm the \
9660 type-correct projection"
9661 );
9662 let via_into: std::borrow::Cow<'static, str> = (&variant).into();
9663 assert_eq!(
9664 via_into.as_ref(),
9665 via_method,
9666 "Into<Cow<'static, str>>::into on \
9667 &RestartStrategy::{variant:?} must byte-equal \
9668 RestartStrategy::as_str on the same input — the \
9669 blanket-derived Into shape must resolve to the same \
9670 as_str dispatch as the explicit From impl"
9671 );
9672 assert!(
9673 matches!(via_into, std::borrow::Cow::Borrowed(_)),
9674 "Into<Cow<'static, str>>::into on \
9675 &RestartStrategy::{variant:?} must land on the \
9676 zero-alloc Cow::Borrowed arm — the blanket-derived \
9677 Into shape must resolve to the same Cow::Borrowed \
9678 dispatch as the explicit From impl"
9679 );
9680 }
9681 }
9682
9683 #[test]
9684 fn restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
9685 // Cross-axis partition pin: the newly lifted trait-idiomatic
9686 // borrowed-input `From<&RestartStrategy> for
9687 // std::borrow::Cow<'static, str>` (this lift), the paired
9688 // owned-input `From<RestartStrategy> for
9689 // std::borrow::Cow<'static, str>` (7dd28b3), the paired
9690 // borrowed-input owned-`&'static str` `From<&RestartStrategy>
9691 // for &'static str`, and the paired borrowed-input owned-
9692 // `String` `From<&RestartStrategy> for String` must resolve
9693 // identically on every arm, locking the four
9694 // return-shape × input-shape paths together by construction so
9695 // any future detour trips at caixa-core test time. Also byte-
9696 // parity witness against the sibling [`ToString::to_string`]
9697 // surface routed through [`std::fmt::Display`] — every owned-
9698 // heap-string path (this axis's `.into_owned()` promotion, the
9699 // paired [`From<&RestartStrategy> for String`], and
9700 // `.to_string()`) resolves to the same lifted
9701 // [`crate::render::SUPERVISOR_ESTRATEGIA_*`] const per arm.
9702 //
9703 // Then a `.iter().map(std::borrow::Cow::from)` pipe witness
9704 // over [`super::RestartStrategy::ALL`] — whose iterator yields
9705 // `&RestartStrategy` by construction, so the borrowed-input
9706 // [`Cow<'static, str>`] axis is what routes the pipe through
9707 // the substrate-primitive [`super::RestartStrategy::as_str`]
9708 // accessor without a spurious [`Copy`] deref (which would only
9709 // be reachable through the owned-input
9710 // [`From<RestartStrategy> for Cow<'static, str>`] axis by
9711 // first calling `.copied()` on the iterator). The pipe witness
9712 // also pins the zero-alloc discipline: every element in the
9713 // collected vector satisfies the [`std::borrow::Cow::Borrowed`]
9714 // arm predicate, so a future accidental silent-allocation
9715 // regression on the pipe's iteration axis is a caixa-core-
9716 // test-time failure.
9717 for &strategy in RestartStrategy::ALL {
9718 let borrowed_cow: std::borrow::Cow<'static, str> =
9719 <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&strategy);
9720 let owned_cow: std::borrow::Cow<'static, str> =
9721 <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(strategy);
9722 let borrowed_static: &'static str =
9723 <&'static str as From<&RestartStrategy>>::from(&strategy);
9724 let borrowed_string: String = <String as From<&RestartStrategy>>::from(&strategy);
9725 assert_eq!(
9726 borrowed_cow, owned_cow,
9727 "From<&RestartStrategy> for Cow<'static, str> and \
9728 From<RestartStrategy> for Cow<'static, str> must \
9729 resolve identically on RestartStrategy::{strategy:?} — \
9730 divergence signals the borrowed-input and owned-input \
9731 Cow<'static, str> forward-projection input-shape \
9732 paths have drifted onto different emit-sets"
9733 );
9734 assert_eq!(
9735 borrowed_cow.as_ref(),
9736 borrowed_static,
9737 "From<&RestartStrategy> for Cow<'static, str> and \
9738 From<&RestartStrategy> for &'static str must resolve \
9739 identically on RestartStrategy::{strategy:?} — \
9740 divergence signals the borrowed-input Cow<'static, \
9741 str> and &'static str return-shape paths have drifted \
9742 onto different emit-sets"
9743 );
9744 assert_eq!(
9745 borrowed_cow.as_ref(),
9746 borrowed_string.as_str(),
9747 "From<&RestartStrategy> for Cow<'static, str> and \
9748 From<&RestartStrategy> for String must resolve \
9749 identically on RestartStrategy::{strategy:?} — \
9750 divergence signals the borrowed-input Cow<'static, \
9751 str> and owned-`String` return-shape paths have \
9752 drifted onto different emit-sets"
9753 );
9754 let via_to_string: String = strategy.to_string();
9755 assert_eq!(
9756 borrowed_cow.as_ref(),
9757 via_to_string.as_str(),
9758 "From<&RestartStrategy> for Cow<'static, str> must \
9759 byte-equal RestartStrategy::to_string on \
9760 RestartStrategy::{strategy:?} — divergence signals \
9761 the trait-idiomatic borrowed-input Cow<'static, str> \
9762 forward-projection axis and the ToString-through-\
9763 Display axis have drifted onto different emit-sets"
9764 );
9765 }
9766 let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
9767 .iter()
9768 .map(std::borrow::Cow::from)
9769 .collect();
9770 let via_method: Vec<std::borrow::Cow<'static, str>> = RestartStrategy::ALL
9771 .iter()
9772 .map(|s| std::borrow::Cow::Borrowed(s.as_str()))
9773 .collect();
9774 assert_eq!(
9775 via_iter, via_method,
9776 "`.iter().map(Cow::from)` over RestartStrategy::ALL — a \
9777 call site whose iteration axis holds `&RestartStrategy` \
9778 by construction — must byte-equal `.iter().map(|s| \
9779 Cow::Borrowed(s.as_str()))` on every arm — the borrowed-\
9780 input Cow<'static, str> `From<&RestartStrategy> for \
9781 Cow<'static, str>` axis is what makes the `Cow::from` \
9782 composition route through the substrate-primitive \
9783 `RestartStrategy::as_str` accessor with the zero-alloc \
9784 Cow::Borrowed arm by construction and without a spurious \
9785 `Copy` deref (which would only be reachable through the \
9786 owned-input `From<RestartStrategy> for Cow<'static, str>` \
9787 axis by first calling `.copied()` on the iterator)"
9788 );
9789 for cow in &via_iter {
9790 assert!(
9791 matches!(cow, std::borrow::Cow::Borrowed(_)),
9792 "every element of the .iter().map(Cow::from) pipe \
9793 over RestartStrategy::ALL must land on the zero-\
9794 alloc Cow::Borrowed arm — a Cow::Owned outcome on \
9795 any arm signals the pipe's iteration axis has \
9796 silently allocated where the substrate-primitive \
9797 RestartStrategy::as_str `&'static str` return makes \
9798 the borrowed arm the type-correct projection"
9799 );
9800 }
9801 }
9802
9803 #[test]
9804 fn restart_strategy_from_into_box_str_routes_through_as_str_accessor() {
9805 // Fail-before-pass-after byte-parity pin on the newly lifted
9806 // `impl From<RestartStrategy> for Box<str>` — asserts the
9807 // owned-input standard-library trait impl and the
9808 // substrate-primitive [`super::RestartStrategy::as_str`]
9809 // `pub const fn` accessor resolve to the same four-arm emit-
9810 // set across every arm the exhaustive
9811 // [`super::RestartStrategy::ALL`] slice enumerates. Opens the
9812 // substrate-wide `Box<str>` forward-projection campaign tier
9813 // on the first M2 OTP-shape closed-set fieldless typed enum
9814 // peer on the caixa surface (`:supervisor :estrategia`),
9815 // immediately after the paired `Cow<'static, str>` axis
9816 // (7dd28b3 / ee577fd) closed the
9817 // `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
9818 // 2×3 corner on this enum. Rust's standard library carries
9819 // `impl From<&str> for Box<str>` and
9820 // `impl From<String> for Box<str>` but no blanket
9821 // `impl<T: AsRef<str>> From<T> for Box<str>`, so this axis is
9822 // a distinct trait-idiomatic surface that a
9823 // `let key: Box<str> = strategy.into();`-shaped call site
9824 // reaches through this impl and no other — a paired
9825 // `Box::from(strategy.as_str())` open-code has no compile-
9826 // time link back to the substrate primitive.
9827 for &variant in RestartStrategy::ALL {
9828 let via_trait: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
9829 let via_method: &'static str = variant.as_str();
9830 assert_eq!(
9831 via_trait.as_ref(),
9832 via_method,
9833 "From<RestartStrategy> for Box<str> impl must round-\
9834 trip RestartStrategy::{variant:?} to the same lifted \
9835 SUPERVISOR_ESTRATEGIA_* const RestartStrategy::as_str \
9836 returns — divergence signals a silent detour off the \
9837 substrate-primitive accessor"
9838 );
9839 let via_into: Box<str> = variant.into();
9840 assert_eq!(
9841 via_into.as_ref(),
9842 via_method,
9843 "Into<Box<str>>::into on RestartStrategy::{variant:?} \
9844 must byte-equal RestartStrategy::as_str on the same \
9845 input — the blanket-derived Into shape must resolve \
9846 to the same as_str dispatch as the explicit From impl"
9847 );
9848 }
9849 }
9850
9851 #[test]
9852 fn restart_strategy_from_borrowed_into_box_str_routes_through_as_str_accessor() {
9853 // Fail-before-pass-after byte-parity pin on the newly lifted
9854 // `impl From<&RestartStrategy> for Box<str>` — asserts the
9855 // borrowed-input standard-library trait impl and the
9856 // substrate-primitive [`super::RestartStrategy::as_str`]
9857 // `pub const fn` accessor resolve to the same four-arm emit-
9858 // set across every arm the exhaustive
9859 // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
9860 // standard library does not carry a blanket
9861 // `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
9862 // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
9863 // so the borrowed-input `Box<str>` forward-projection axis
9864 // is a distinct trait-idiomatic surface that a
9865 // `let key: Box<str> = (&strategy).into();`-shaped call site
9866 // or a `RestartStrategy::ALL.iter().map(Box::<str>::from)`-
9867 // shaped pipe reaches through this impl and no other — the
9868 // paired owned-input `From<RestartStrategy> for Box<str>`
9869 // impl (69ef45c) forces every borrowed-input call site
9870 // through an explicit `Copy` deref
9871 // (`Box::<str>::from((*strategy).as_str())`) or a
9872 // `Box::<str>::from(strategy.as_str())` open-code whose
9873 // type bounds have no compile-time link back to the
9874 // substrate primitive.
9875 //
9876 // Second peer on the substrate-wide trait-idiomatic
9877 // [`Box<str>`] forward-projection family on this enum —
9878 // closes the `{Self, &Self}` input-shape corner of the
9879 // [`Box<str>`] axis on the first M2 OTP-shape closed-set
9880 // fieldless typed enum peer on the caixa surface
9881 // (`:supervisor :estrategia`), exactly as ee577fd closed
9882 // the paired [`Cow<'static, str>`] axis one commit after
9883 // its owning half (7dd28b3) landed. Every future closed-
9884 // set fieldless typed enum peer on the substrate is a
9885 // future target of the campaign.
9886 //
9887 // Also byte-parity witness against the paired owned-input
9888 // [`From<RestartStrategy> for Box<str>`] and the sibling
9889 // borrowed-input [`From<&RestartStrategy> for &'static str`],
9890 // [`From<&RestartStrategy> for String`], and
9891 // [`From<&RestartStrategy> for Cow<'static, str>`]
9892 // return-shape axes — locking the four
9893 // return-shape × input-shape paths together by construction
9894 // so any future detour trips at caixa-core test time. Then a
9895 // `.iter().map(Box::<str>::from)` pipe witness over
9896 // [`super::RestartStrategy::ALL`] — whose iterator yields
9897 // `&RestartStrategy` by construction, so the borrowed-input
9898 // [`Box<str>`] axis is what routes the pipe through the
9899 // substrate-primitive [`super::RestartStrategy::as_str`]
9900 // accessor without a spurious [`Copy`] deref (which would
9901 // only be reachable through the owned-input
9902 // [`From<RestartStrategy> for Box<str>`] axis by first
9903 // calling `.copied()` on the iterator).
9904 for &variant in RestartStrategy::ALL {
9905 let via_trait: Box<str> = <Box<str> as From<&RestartStrategy>>::from(&variant);
9906 let via_method: &'static str = variant.as_str();
9907 assert_eq!(
9908 via_trait.as_ref(),
9909 via_method,
9910 "From<&RestartStrategy> for Box<str> impl must \
9911 round-trip &RestartStrategy::{variant:?} to the same \
9912 lifted SUPERVISOR_ESTRATEGIA_* const \
9913 RestartStrategy::as_str returns — divergence signals \
9914 a silent detour off the substrate-primitive accessor"
9915 );
9916 let via_into: Box<str> = (&variant).into();
9917 assert_eq!(
9918 via_into.as_ref(),
9919 via_method,
9920 "Into<Box<str>>::into on &RestartStrategy::{variant:?} \
9921 must byte-equal RestartStrategy::as_str on the same \
9922 input — the blanket-derived Into shape must resolve \
9923 to the same as_str dispatch as the explicit From impl"
9924 );
9925 let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
9926 assert_eq!(
9927 via_trait, owned_box,
9928 "From<&RestartStrategy> for Box<str> and \
9929 From<RestartStrategy> for Box<str> must resolve \
9930 identically on RestartStrategy::{variant:?} — \
9931 divergence signals the borrowed-input and owned-input \
9932 Box<str> forward-projection input-shape paths have \
9933 drifted onto different emit-sets"
9934 );
9935 let borrowed_static: &'static str =
9936 <&'static str as From<&RestartStrategy>>::from(&variant);
9937 assert_eq!(
9938 via_trait.as_ref(),
9939 borrowed_static,
9940 "From<&RestartStrategy> for Box<str> and \
9941 From<&RestartStrategy> for &'static str must resolve \
9942 identically on RestartStrategy::{variant:?} — \
9943 divergence signals the borrowed-input Box<str> and \
9944 &'static str return-shape paths have drifted onto \
9945 different emit-sets"
9946 );
9947 let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
9948 assert_eq!(
9949 via_trait.as_ref(),
9950 borrowed_string.as_str(),
9951 "From<&RestartStrategy> for Box<str> and \
9952 From<&RestartStrategy> for String must resolve \
9953 identically on RestartStrategy::{variant:?} — \
9954 divergence signals the borrowed-input Box<str> and \
9955 owned-`String` return-shape paths have drifted onto \
9956 different emit-sets"
9957 );
9958 let borrowed_cow: std::borrow::Cow<'static, str> =
9959 <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
9960 assert_eq!(
9961 via_trait.as_ref(),
9962 borrowed_cow.as_ref(),
9963 "From<&RestartStrategy> for Box<str> and \
9964 From<&RestartStrategy> for Cow<'static, str> must \
9965 resolve identically on RestartStrategy::{variant:?} — \
9966 divergence signals the borrowed-input Box<str> and \
9967 Cow<'static, str> return-shape paths have drifted \
9968 onto different emit-sets"
9969 );
9970 }
9971 let via_iter: Vec<Box<str>> = RestartStrategy::ALL.iter().map(Box::<str>::from).collect();
9972 let via_method: Vec<Box<str>> = RestartStrategy::ALL
9973 .iter()
9974 .map(|s| Box::<str>::from(s.as_str()))
9975 .collect();
9976 assert_eq!(
9977 via_iter, via_method,
9978 "`.iter().map(Box::<str>::from)` over \
9979 RestartStrategy::ALL — a call site whose iteration axis \
9980 holds `&RestartStrategy` by construction — must byte-\
9981 equal `.iter().map(|s| Box::<str>::from(s.as_str()))` \
9982 on every arm — the borrowed-input Box<str> \
9983 `From<&RestartStrategy> for Box<str>` axis is what \
9984 makes the `Box::<str>::from` composition route through \
9985 the substrate-primitive `RestartStrategy::as_str` \
9986 accessor without a spurious `Copy` deref (which would \
9987 only be reachable through the owned-input \
9988 `From<RestartStrategy> for Box<str>` axis by first \
9989 calling `.copied()` on the iterator)"
9990 );
9991 }
9992
9993 #[test]
9994 fn restart_strategy_from_into_arc_str_routes_through_as_str_accessor() {
9995 // Fail-before-pass-after byte-parity pin on the newly lifted
9996 // `impl From<RestartStrategy> for std::sync::Arc<str>` — asserts
9997 // the owned-input standard-library trait impl and the
9998 // substrate-primitive [`super::RestartStrategy::as_str`]
9999 // `pub const fn` accessor resolve to the same four-arm emit-
10000 // set across every arm the exhaustive
10001 // [`super::RestartStrategy::ALL`] slice enumerates. Opens the
10002 // substrate-wide [`std::sync::Arc<str>`] forward-projection
10003 // campaign tier on the first M2 OTP-shape closed-set fieldless
10004 // typed enum peer on the caixa surface
10005 // (`:supervisor :estrategia`), immediately after the paired
10006 // [`Box<str>`] axis (69ef45c / 59ae5dc) closed the
10007 // `{Self, &Self} × {&'static str, String, Cow<'static, str>,
10008 // Box<str>}` 2×4 corner on this enum. Rust's standard library
10009 // carries `impl From<&str> for std::sync::Arc<str>` and
10010 // `impl From<String> for std::sync::Arc<str>` but no blanket
10011 // `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor
10012 // an `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`),
10013 // so this axis is a distinct trait-idiomatic surface that a
10014 // `let key: std::sync::Arc<str> = strategy.into();`-shaped call
10015 // site reaches through this impl and no other — a paired
10016 // `std::sync::Arc::<str>::from(strategy.as_str())` open-code
10017 // has no compile-time link back to the substrate primitive,
10018 // and a two-step `std::sync::Arc::<str>::from(String::from(
10019 // strategy))` composition through the owned-`String` axis
10020 // allocates twice (once into the intermediate `String`, once
10021 // into the [`Arc<str>`] on the `From<String>` conversion)
10022 // where the single-step trait impl allocates once.
10023 //
10024 // Cross-axis byte-parity witness against the sibling owned-
10025 // input `{&'static str, String, Cow<'static, str>, Box<str>}`
10026 // return-shape axes — locking the five return-shape paths on
10027 // the owned-input surface together by construction so any
10028 // future detour off the substrate-primitive
10029 // [`super::RestartStrategy::as_str`] accessor trips at caixa-
10030 // core test time.
10031 for &variant in RestartStrategy::ALL {
10032 let via_trait: std::sync::Arc<str> =
10033 <std::sync::Arc<str> as From<RestartStrategy>>::from(variant);
10034 let via_method: &'static str = variant.as_str();
10035 assert_eq!(
10036 via_trait.as_ref(),
10037 via_method,
10038 "From<RestartStrategy> for std::sync::Arc<str> impl \
10039 must round-trip RestartStrategy::{variant:?} to the \
10040 same lifted SUPERVISOR_ESTRATEGIA_* const \
10041 RestartStrategy::as_str returns — divergence signals \
10042 a silent detour off the substrate-primitive accessor"
10043 );
10044 let via_into: std::sync::Arc<str> = variant.into();
10045 assert_eq!(
10046 via_into.as_ref(),
10047 via_method,
10048 "Into<std::sync::Arc<str>>::into on \
10049 RestartStrategy::{variant:?} must byte-equal \
10050 RestartStrategy::as_str on the same input — the \
10051 blanket-derived Into shape must resolve to the same \
10052 as_str dispatch as the explicit From impl"
10053 );
10054 let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
10055 assert_eq!(
10056 via_trait.as_ref(),
10057 owned_static,
10058 "From<RestartStrategy> for std::sync::Arc<str> and \
10059 From<RestartStrategy> for &'static str must resolve \
10060 identically on RestartStrategy::{variant:?} — \
10061 divergence signals the owned-input std::sync::Arc<str> \
10062 and &'static str return-shape paths have drifted onto \
10063 different emit-sets"
10064 );
10065 let owned_string: String = <String as From<RestartStrategy>>::from(variant);
10066 assert_eq!(
10067 via_trait.as_ref(),
10068 owned_string.as_str(),
10069 "From<RestartStrategy> for std::sync::Arc<str> and \
10070 From<RestartStrategy> for String must resolve \
10071 identically on RestartStrategy::{variant:?} — \
10072 divergence signals the owned-input std::sync::Arc<str> \
10073 and owned-`String` return-shape paths have drifted \
10074 onto different emit-sets"
10075 );
10076 let owned_cow: std::borrow::Cow<'static, str> =
10077 <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
10078 assert_eq!(
10079 via_trait.as_ref(),
10080 owned_cow.as_ref(),
10081 "From<RestartStrategy> for std::sync::Arc<str> and \
10082 From<RestartStrategy> for Cow<'static, str> must \
10083 resolve identically on RestartStrategy::{variant:?} — \
10084 divergence signals the owned-input std::sync::Arc<str> \
10085 and Cow<'static, str> return-shape paths have drifted \
10086 onto different emit-sets"
10087 );
10088 let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
10089 assert_eq!(
10090 via_trait.as_ref(),
10091 owned_box.as_ref(),
10092 "From<RestartStrategy> for std::sync::Arc<str> and \
10093 From<RestartStrategy> for Box<str> must resolve \
10094 identically on RestartStrategy::{variant:?} — \
10095 divergence signals the owned-input std::sync::Arc<str> \
10096 and Box<str> return-shape paths have drifted onto \
10097 different emit-sets"
10098 );
10099 }
10100 }
10101
10102 #[test]
10103 fn restart_strategy_from_borrowed_into_arc_str_routes_through_as_str_accessor() {
10104 // Fail-before-pass-after byte-parity pin on the newly lifted
10105 // `impl From<&RestartStrategy> for std::sync::Arc<str>` —
10106 // asserts the borrowed-input standard-library trait impl and
10107 // the substrate-primitive [`super::RestartStrategy::as_str`]
10108 // `pub const fn` accessor resolve to the same four-arm emit-
10109 // set across every arm the exhaustive
10110 // [`super::RestartStrategy::ALL`] slice enumerates. Rust's
10111 // standard library does not carry a blanket
10112 // `impl<T: AsRef<str>> From<&T> for std::sync::Arc<str>` (nor
10113 // a `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
10114 // so the borrowed-input [`std::sync::Arc<str>`] forward-
10115 // projection axis is a distinct trait-idiomatic surface that a
10116 // `let key: std::sync::Arc<str> = (&strategy).into();`-shaped
10117 // call site or a
10118 // `RestartStrategy::ALL.iter().map(std::sync::Arc::<str>::from)`-
10119 // shaped pipe reaches through this impl and no other — the
10120 // paired owned-input
10121 // `From<RestartStrategy> for std::sync::Arc<str>` impl
10122 // (bca2ec8) forces every borrowed-input call site through an
10123 // explicit `Copy` deref
10124 // (`std::sync::Arc::<str>::from((*strategy).as_str())`) or a
10125 // `std::sync::Arc::<str>::from(strategy.as_str())` open-code
10126 // whose type bounds have no compile-time link back to the
10127 // substrate primitive.
10128 //
10129 // Second peer on the substrate-wide trait-idiomatic
10130 // [`std::sync::Arc<str>`] forward-projection family on this
10131 // enum — closes the `{Self, &Self}` input-shape corner of
10132 // the [`std::sync::Arc<str>`] axis on the first M2 OTP-shape
10133 // closed-set fieldless typed enum peer on the caixa surface
10134 // (`:supervisor :estrategia`), exactly as 59ae5dc closed the
10135 // paired [`Box<str>`] axis one commit after its owning half
10136 // (69ef45c) landed. Every future closed-set fieldless typed
10137 // enum peer on the substrate is a future target of the
10138 // campaign.
10139 //
10140 // Also byte-parity witness against the paired owned-input
10141 // [`From<RestartStrategy> for std::sync::Arc<str>`] and the
10142 // sibling borrowed-input
10143 // [`From<&RestartStrategy> for &'static str`],
10144 // [`From<&RestartStrategy> for String`],
10145 // [`From<&RestartStrategy> for Cow<'static, str>`], and
10146 // [`From<&RestartStrategy> for Box<str>`] return-shape axes —
10147 // locking the five return-shape × input-shape paths together
10148 // by construction so any future detour trips at caixa-core
10149 // test time. Then a
10150 // `.iter().map(std::sync::Arc::<str>::from)` pipe witness over
10151 // [`super::RestartStrategy::ALL`] — whose iterator yields
10152 // `&RestartStrategy` by construction, so the borrowed-input
10153 // [`std::sync::Arc<str>`] axis is what routes the pipe
10154 // through the substrate-primitive
10155 // [`super::RestartStrategy::as_str`] accessor without a
10156 // spurious [`Copy`] deref (which would only be reachable
10157 // through the owned-input
10158 // [`From<RestartStrategy> for std::sync::Arc<str>`] axis by
10159 // first calling `.copied()` on the iterator).
10160 for &variant in RestartStrategy::ALL {
10161 let via_trait: std::sync::Arc<str> =
10162 <std::sync::Arc<str> as From<&RestartStrategy>>::from(&variant);
10163 let via_method: &'static str = variant.as_str();
10164 assert_eq!(
10165 via_trait.as_ref(),
10166 via_method,
10167 "From<&RestartStrategy> for std::sync::Arc<str> impl \
10168 must round-trip &RestartStrategy::{variant:?} to the \
10169 same lifted SUPERVISOR_ESTRATEGIA_* const \
10170 RestartStrategy::as_str returns — divergence signals \
10171 a silent detour off the substrate-primitive accessor"
10172 );
10173 let via_into: std::sync::Arc<str> = (&variant).into();
10174 assert_eq!(
10175 via_into.as_ref(),
10176 via_method,
10177 "Into<std::sync::Arc<str>>::into on \
10178 &RestartStrategy::{variant:?} must byte-equal \
10179 RestartStrategy::as_str on the same input — the \
10180 blanket-derived Into shape must resolve to the same \
10181 as_str dispatch as the explicit From impl"
10182 );
10183 let owned_arc: std::sync::Arc<str> =
10184 <std::sync::Arc<str> as From<RestartStrategy>>::from(variant);
10185 assert_eq!(
10186 via_trait, owned_arc,
10187 "From<&RestartStrategy> for std::sync::Arc<str> and \
10188 From<RestartStrategy> for std::sync::Arc<str> must \
10189 resolve identically on RestartStrategy::{variant:?} — \
10190 divergence signals the borrowed-input and owned-input \
10191 std::sync::Arc<str> forward-projection input-shape \
10192 paths have drifted onto different emit-sets"
10193 );
10194 let borrowed_static: &'static str =
10195 <&'static str as From<&RestartStrategy>>::from(&variant);
10196 assert_eq!(
10197 via_trait.as_ref(),
10198 borrowed_static,
10199 "From<&RestartStrategy> for std::sync::Arc<str> and \
10200 From<&RestartStrategy> for &'static str must resolve \
10201 identically on RestartStrategy::{variant:?} — \
10202 divergence signals the borrowed-input \
10203 std::sync::Arc<str> and &'static str return-shape \
10204 paths have drifted onto different emit-sets"
10205 );
10206 let borrowed_string: String = <String as From<&RestartStrategy>>::from(&variant);
10207 assert_eq!(
10208 via_trait.as_ref(),
10209 borrowed_string.as_str(),
10210 "From<&RestartStrategy> for std::sync::Arc<str> and \
10211 From<&RestartStrategy> for String must resolve \
10212 identically on RestartStrategy::{variant:?} — \
10213 divergence signals the borrowed-input \
10214 std::sync::Arc<str> and owned-`String` return-shape \
10215 paths have drifted onto different emit-sets"
10216 );
10217 let borrowed_cow: std::borrow::Cow<'static, str> =
10218 <std::borrow::Cow<'static, str> as From<&RestartStrategy>>::from(&variant);
10219 assert_eq!(
10220 via_trait.as_ref(),
10221 borrowed_cow.as_ref(),
10222 "From<&RestartStrategy> for std::sync::Arc<str> and \
10223 From<&RestartStrategy> for Cow<'static, str> must \
10224 resolve identically on RestartStrategy::{variant:?} — \
10225 divergence signals the borrowed-input \
10226 std::sync::Arc<str> and Cow<'static, str> return-shape \
10227 paths have drifted onto different emit-sets"
10228 );
10229 let borrowed_box: Box<str> = <Box<str> as From<&RestartStrategy>>::from(&variant);
10230 assert_eq!(
10231 via_trait.as_ref(),
10232 borrowed_box.as_ref(),
10233 "From<&RestartStrategy> for std::sync::Arc<str> and \
10234 From<&RestartStrategy> for Box<str> must resolve \
10235 identically on RestartStrategy::{variant:?} — \
10236 divergence signals the borrowed-input \
10237 std::sync::Arc<str> and Box<str> return-shape paths \
10238 have drifted onto different emit-sets"
10239 );
10240 }
10241 let via_iter: Vec<std::sync::Arc<str>> = RestartStrategy::ALL
10242 .iter()
10243 .map(std::sync::Arc::<str>::from)
10244 .collect();
10245 let via_method: Vec<std::sync::Arc<str>> = RestartStrategy::ALL
10246 .iter()
10247 .map(|s| std::sync::Arc::<str>::from(s.as_str()))
10248 .collect();
10249 assert_eq!(
10250 via_iter, via_method,
10251 "`.iter().map(std::sync::Arc::<str>::from)` over \
10252 RestartStrategy::ALL — a call site whose iteration axis \
10253 holds `&RestartStrategy` by construction — must byte-\
10254 equal `.iter().map(|s| std::sync::Arc::<str>::from(s.as_str()))` \
10255 on every arm — the borrowed-input std::sync::Arc<str> \
10256 `From<&RestartStrategy> for std::sync::Arc<str>` axis is \
10257 what makes the `std::sync::Arc::<str>::from` composition \
10258 route through the substrate-primitive \
10259 `RestartStrategy::as_str` accessor without a spurious \
10260 `Copy` deref (which would only be reachable through the \
10261 owned-input `From<RestartStrategy> for std::sync::Arc<str>` \
10262 axis by first calling `.copied()` on the iterator)"
10263 );
10264 }
10265
10266 #[test]
10267 #[allow(
10268 clippy::too_many_lines,
10269 reason = "cross-axis partition pin folds the substrate-primitive \
10270 as_str accessor's `.as_bytes()` byte-tail plus the \
10271 paired str-view (AsRef<str>, Display, as_str) and \
10272 reverse-projection ({&'static str, String, Cow<'static, \
10273 str>, Box<str>, std::sync::Arc<str>}) return-shape \
10274 axes' `.as_bytes()` byte-tails plus a <T: AsRef<[u8]>>\
10275 -bound-consumer witness plus a blake3::Hasher::update-\
10276 shape byte-input surface witness into one exhaustive \
10277 round-trip over RestartStrategy::ALL — the accepted \
10278 line-count cost of opening the byte-view axis keyed \
10279 to the substrate-primitive as_str accessor at the \
10280 same test-site"
10281 )]
10282 #[allow(
10283 clippy::needless_borrows_for_generic_args,
10284 reason = "the borrowed-input surface (&variant) is exercised \
10285 deliberately: the `<T: AsRef<[u8]>>`-bound consumer \
10286 and the `blake3::Hasher::update`-shape byte-input \
10287 surface both accept either owned or borrowed input \
10288 through the standard-library blanket \
10289 `impl<T: ?Sized + AsRef<[u8]>> AsRef<[u8]> for &T`, \
10290 and this pin round-trips both input shapes to lock \
10291 the borrowed-input path load-bearing against a \
10292 future silent regression"
10293 )]
10294 fn restart_strategy_as_ref_bytes_routes_through_as_str_accessor() {
10295 // `<T: AsRef<[u8]>>`-bound generic-consumer witness: a byte-input
10296 // function that binds its argument through the standard-library
10297 // [`AsRef<[u8]>`] trait bound accepts a [`super::RestartStrategy`]
10298 // directly, without the caller open-coding the two-hop
10299 // `estrategia.as_str().as_bytes()` composition. Lifted to the top
10300 // of the function per `clippy::items_after_statements`.
10301 fn generic_bytes_sink<T: AsRef<[u8]>>(t: T) -> Vec<u8> {
10302 t.as_ref().to_vec()
10303 }
10304 // `blake3::Hasher::update`-shape byte-input surface mock: mirrors
10305 // `blake3::Hasher::update` / `ring::digest::Context::update` /
10306 // `sha2::Sha256::update`'s `impl AsRef<[u8]>`-bound `update`
10307 // signature so a per-supervisor BLAKE3 content-address closure
10308 // that composes `hasher.update(estrategia)` on the
10309 // [`crate::Lacre`] closure builder reaches the substrate-primitive
10310 // `as_str` accessor through the [`super::RestartStrategy`]
10311 // `AsRef<[u8]>` axis and no other. Lifted to the top of the
10312 // function per `clippy::items_after_statements`.
10313 struct MockHasher(Vec<u8>);
10314 impl MockHasher {
10315 fn new() -> Self {
10316 Self(Vec::new())
10317 }
10318 fn update(&mut self, bytes: impl AsRef<[u8]>) -> &mut Self {
10319 self.0.extend_from_slice(bytes.as_ref());
10320 self
10321 }
10322 fn finalize(self) -> Vec<u8> {
10323 self.0
10324 }
10325 }
10326
10327 // Fail-before-pass-after byte-parity pin on the newly lifted
10328 // `impl AsRef<[u8]> for RestartStrategy` — asserts the trait-
10329 // idiomatic byte-view standard-library impl and the substrate-
10330 // primitive [`super::RestartStrategy::as_str`] `pub const fn`
10331 // accessor's `.as_bytes()` byte-tail resolve to the same four-arm
10332 // `PascalCase` wire byte-string emit-set across every arm the
10333 // exhaustive [`super::RestartStrategy::ALL`] slice enumerates.
10334 // Opens the trait-idiomatic byte-view axis onto the first M2
10335 // OTP-shape closed-set fieldless typed enum peer on the caixa
10336 // surface (`:supervisor :estrategia`), extending the substrate-
10337 // wide byte-view campaign the sibling
10338 // [`super::crate::CaixaKind`] first-mover (69d8d86) opened.
10339 //
10340 // Rust's standard library carries `impl AsRef<[u8]> for str` and
10341 // `impl AsRef<[u8]> for String`, so a two-hop composition
10342 // `estrategia.as_str().as_bytes()` (or the equally two-hop
10343 // `AsRef::<str>::as_ref(&estrategia).as_bytes()`) is reachable
10344 // through the pre-existing str-view axis alone. But that two-hop
10345 // shape has no compile-time link back to the byte-projection
10346 // axis, forces every downstream `<T: AsRef<[u8]>>`-bound
10347 // consumer to open-code the two-hop composition at every call
10348 // site, and admits a silent split whenever a future call site
10349 // takes a sibling reverse-projection axis whose `.as_bytes()`
10350 // byte-tail carries no compile-time byte-view surface. This
10351 // impl closes the byte-view axis at the substrate-primitive
10352 // [`super::RestartStrategy::as_str`] accessor so every future
10353 // `<T: AsRef<[u8]>>`-bound consumer reaches the same lifted
10354 // [`super::crate::render::SUPERVISOR_ESTRATEGIA_*`] const roster
10355 // the paired str-view axes already return through — through one
10356 // trait dispatch.
10357 for &variant in RestartStrategy::ALL {
10358 let via_trait: &[u8] = <RestartStrategy as AsRef<[u8]>>::as_ref(&variant);
10359 let via_method_bytes: &[u8] = variant.as_str().as_bytes();
10360 assert_eq!(
10361 via_trait, via_method_bytes,
10362 "AsRef<[u8]> for RestartStrategy impl must byte-equal \
10363 RestartStrategy::as_str().as_bytes() on \
10364 RestartStrategy::{variant:?} — divergence signals a \
10365 silent detour off the substrate-primitive accessor"
10366 );
10367 // Cross-axis witness against the paired str-view axes'
10368 // `.as_bytes()` byte-tails: [`AsRef<str>`] /
10369 // [`std::fmt::Display`] / [`super::RestartStrategy::as_str`]
10370 // all resolve to the same lifted
10371 // [`super::crate::render::SUPERVISOR_ESTRATEGIA_*`] const
10372 // roster, and the byte-view axis must byte-equal each of
10373 // their `.as_bytes()` byte-tails by construction — locking
10374 // the str-view and byte-view axes together at the
10375 // substrate-primitive accessor.
10376 let str_view_ref: &str = <RestartStrategy as AsRef<str>>::as_ref(&variant);
10377 assert_eq!(
10378 via_trait,
10379 str_view_ref.as_bytes(),
10380 "AsRef<[u8]> for RestartStrategy and AsRef<str> for \
10381 RestartStrategy must resolve to byte-equal byte-tails \
10382 on RestartStrategy::{variant:?} — divergence signals \
10383 the byte-view and str-view axes have drifted off the \
10384 same substrate-primitive as_str accessor"
10385 );
10386 let display_bytes = variant.to_string();
10387 assert_eq!(
10388 via_trait,
10389 display_bytes.as_bytes(),
10390 "AsRef<[u8]> for RestartStrategy and \
10391 <RestartStrategy as std::fmt::Display>::to_string must \
10392 resolve to byte-equal byte-tails on \
10393 RestartStrategy::{variant:?} — divergence signals the \
10394 byte-view axis and the Display formatter axis have \
10395 drifted off the same substrate-primitive as_str \
10396 accessor"
10397 );
10398 // Cross-axis witness against the paired reverse-projection
10399 // axes' `.as_bytes()` byte-tails: every one of `{&'static
10400 // str, String, Cow<'static, str>, Box<str>,
10401 // std::sync::Arc<str>}` allocates (or borrows) the same
10402 // `PascalCase` wire byte-string the substrate-primitive
10403 // accessor emits, so the byte-view axis must byte-equal
10404 // each of their `.as_bytes()` byte-tails by construction.
10405 let owned_static: &'static str = <&'static str as From<RestartStrategy>>::from(variant);
10406 assert_eq!(
10407 via_trait,
10408 owned_static.as_bytes(),
10409 "AsRef<[u8]> for RestartStrategy and From<RestartStrategy> \
10410 for &'static str must resolve to byte-equal byte-tails \
10411 on RestartStrategy::{variant:?}"
10412 );
10413 let owned_string: String = <String as From<RestartStrategy>>::from(variant);
10414 assert_eq!(
10415 via_trait,
10416 owned_string.as_bytes(),
10417 "AsRef<[u8]> for RestartStrategy and From<RestartStrategy> \
10418 for String must resolve to byte-equal byte-tails on \
10419 RestartStrategy::{variant:?}"
10420 );
10421 let owned_cow: std::borrow::Cow<'static, str> =
10422 <std::borrow::Cow<'static, str> as From<RestartStrategy>>::from(variant);
10423 assert_eq!(
10424 via_trait,
10425 owned_cow.as_bytes(),
10426 "AsRef<[u8]> for RestartStrategy and From<RestartStrategy> \
10427 for Cow<'static, str> must resolve to byte-equal byte-\
10428 tails on RestartStrategy::{variant:?}"
10429 );
10430 let owned_box: Box<str> = <Box<str> as From<RestartStrategy>>::from(variant);
10431 assert_eq!(
10432 via_trait,
10433 owned_box.as_bytes(),
10434 "AsRef<[u8]> for RestartStrategy and From<RestartStrategy> \
10435 for Box<str> must resolve to byte-equal byte-tails on \
10436 RestartStrategy::{variant:?}"
10437 );
10438 let owned_arc: std::sync::Arc<str> =
10439 <std::sync::Arc<str> as From<RestartStrategy>>::from(variant);
10440 assert_eq!(
10441 via_trait,
10442 owned_arc.as_bytes(),
10443 "AsRef<[u8]> for RestartStrategy and From<RestartStrategy> \
10444 for std::sync::Arc<str> must resolve to byte-equal byte-\
10445 tails on RestartStrategy::{variant:?}"
10446 );
10447 }
10448 // `<T: AsRef<[u8]>>`-bound-consumer witness: the generic byte-
10449 // input function `generic_bytes_sink` (lifted above per
10450 // `clippy::items_after_statements`) accepts a
10451 // [`super::RestartStrategy`] directly through the trait bound,
10452 // without the caller open-coding the two-hop
10453 // `estrategia.as_str().as_bytes()` composition. This is the
10454 // shape that reaches the caixa-lacre BLAKE3 content-address
10455 // closure's `blake3::Hasher::update(impl AsRef<[u8]>)` byte-
10456 // input surface through this impl and no other.
10457 for &variant in RestartStrategy::ALL {
10458 let via_generic = generic_bytes_sink(variant);
10459 let via_borrowed_generic = generic_bytes_sink(&variant);
10460 let via_method_bytes = variant.as_str().as_bytes().to_vec();
10461 assert_eq!(
10462 via_generic, via_method_bytes,
10463 "generic `<T: AsRef<[u8]>>`-bound consumer on \
10464 RestartStrategy::{variant:?} must yield the same byte-\
10465 tail RestartStrategy::as_str().as_bytes() returns — \
10466 divergence signals the byte-view axis fails to bridge \
10467 a generic byte-input trait bound to the substrate-\
10468 primitive accessor"
10469 );
10470 assert_eq!(
10471 via_borrowed_generic, via_method_bytes,
10472 "generic `<T: AsRef<[u8]>>`-bound consumer on \
10473 &RestartStrategy::{variant:?} must yield the same byte-\
10474 tail RestartStrategy::as_str().as_bytes() returns — \
10475 the borrowed-input surface must resolve to the same \
10476 as_str dispatch"
10477 );
10478 }
10479 // `blake3::Hasher::update`-shape byte-input surface witness on
10480 // the caixa-lacre compounding target: the `MockHasher` (lifted
10481 // above per `clippy::items_after_statements`) mirrors
10482 // `blake3::Hasher::update` / `ring::digest::Context::update` /
10483 // `sha2::Sha256::update`'s `impl AsRef<[u8]>`-bound update
10484 // signature and accepts a [`super::RestartStrategy`] directly,
10485 // routing its byte-tail through the substrate-primitive
10486 // `as_str` accessor — the shape a future per-supervisor BLAKE3
10487 // content-address closure composes to fold an `:estrategia`
10488 // discriminator byte-tag into the [`crate::Lacre`] closure
10489 // body.
10490 for &variant in RestartStrategy::ALL {
10491 let mut owned_hasher = MockHasher::new();
10492 owned_hasher.update(variant);
10493 let owned_folded = owned_hasher.finalize();
10494 assert_eq!(
10495 owned_folded,
10496 variant.as_str().as_bytes(),
10497 "`hasher.update(estrategia)`-shape composition on \
10498 RestartStrategy::{variant:?} must fold the same byte-\
10499 tail RestartStrategy::as_str().as_bytes() returns — \
10500 the shape a future per-supervisor BLAKE3 content-\
10501 address closure composes to fold an `:estrategia` \
10502 discriminator byte-tag into the Lacre closure body"
10503 );
10504 let mut borrowed_hasher = MockHasher::new();
10505 borrowed_hasher.update(&variant);
10506 let borrowed_folded = borrowed_hasher.finalize();
10507 assert_eq!(
10508 borrowed_folded,
10509 variant.as_str().as_bytes(),
10510 "`hasher.update(&estrategia)`-shape composition on \
10511 &RestartStrategy::{variant:?} must fold the same byte-\
10512 tail RestartStrategy::as_str().as_bytes() returns — \
10513 the borrowed-input surface must resolve to the same \
10514 as_str dispatch"
10515 );
10516 }
10517 }
10518
10519 #[test]
10520 fn restart_policy_try_from_str_routes_through_from_wire_accessor() {
10521 // Fail-before-pass-after byte-parity pin on the newly lifted
10522 // `impl TryFrom<&str> for RestartPolicy` — asserts the standard-
10523 // library trait impl and the substrate-primitive
10524 // [`RestartPolicy::from_wire`] `Option<Self>` accessor resolve to
10525 // the same three-arm accept-set across every arm the exhaustive
10526 // [`RestartPolicy::ALL`] slice enumerates. Any future silent
10527 // detour that routes the trait impl through a divergent
10528 // projection (a per-arm inline `match s { "Permanent" =>
10529 // Ok(Self::Permanent), … }` re-inlining that opens a compile-time
10530 // link to the un-lifted arm-literal, a hypothetical
10531 // `#[serde(rename_all = "…")]` attribute drift that silently
10532 // splits the wire byte-string from every consumer that reaches
10533 // for this typed dispatch, an accidental swap onto the kebab-case
10534 // dispatcher-catalog axis the pre-existing [`std::str::FromStr`]
10535 // impl parses through and which would collide the two-axis
10536 // wire/catalog split the sibling [`RestartPolicy::from_wire`]
10537 // doc block makes load-bearing) trips at caixa-core test time
10538 // under `assert_eq!` rather than at a downstream
10539 // `impl TryFrom<&str>`-bound consumer's silent split. Sweeps
10540 // every one of the three arms [`RestartPolicy::ALL`] carries so
10541 // no arm's projection is covered only by the sibling method-
10542 // named `from_wire` path. Peer of the sibling
10543 // [`restart_strategy_try_from_str_routes_through_from_wire_accessor`]
10544 // (5b828ed) — extends the trait-idiomatic reverse-projection
10545 // axis onto the third and final M2-OTP-shape closed-set typed
10546 // enum on the caixa surface (the paired per-child restart-
10547 // decision-policy sibling on the same M2 `:supervisor` slot).
10548 for &variant in RestartPolicy::ALL {
10549 let wire = variant.as_str();
10550 assert_eq!(
10551 <RestartPolicy as TryFrom<&str>>::try_from(wire),
10552 Ok(variant),
10553 "TryFrom<&str> impl on RestartPolicy must round-trip \
10554 RestartPolicy::{variant:?}.as_str() = {wire:?} back to \
10555 Ok(RestartPolicy::{variant:?}) — divergence from \
10556 RestartPolicy::from_wire signals a silent detour off \
10557 the substrate-primitive accessor"
10558 );
10559 assert_eq!(
10560 <RestartPolicy as TryFrom<&str>>::try_from(wire).ok(),
10561 RestartPolicy::from_wire(wire),
10562 "TryFrom<&str> ok()-projection on {wire:?} must byte-\
10563 equal RestartPolicy::from_wire on the same input"
10564 );
10565 }
10566 }
10567
10568 #[test]
10569 fn restart_policy_try_from_str_rejects_unknown_byte_strings() {
10570 // Rejection witness on the `impl TryFrom<&str> for
10571 // RestartPolicy` — sweeps a candidate set of byte-strings
10572 // outside the three-arm PascalCase wire accept-set the sibling
10573 // [`RestartPolicy::as_str`] emits and asserts every one lands on
10574 // `Err(())`, so a future accidental widening of the trait impl's
10575 // accept-set (a stray additional
10576 // `_ if s.eq_ignore_ascii_case("Permanent") => Ok(…)` case-fold
10577 // path, a silent inclusion of the kebab-case dispatcher-catalog
10578 // byte-string the pre-existing [`std::str::FromStr`] impl the
10579 // [`gen_platform::FromStrKind`] derive installs parses onto the
10580 // wire axis — which would collide the two-axis
10581 // wire/dispatcher-catalog split the sibling
10582 // [`RestartPolicy::from_wire`] doc block makes load-bearing —
10583 // an English-rebrand or plural-arm silent alias that would widen
10584 // the wire accept-set past the OTP-canonical three) trips at
10585 // caixa-core test time. The candidate set includes the empty
10586 // string, whitespace-only padding, the kebab-case dispatcher-
10587 // catalog byte-strings on the sibling axis (a caller who
10588 // confuses the two axes trips here rather than at a downstream
10589 // consumer's silent reject), a lowercase / uppercase / mixed-case
10590 // fold of each PascalCase arm (a caller who assumes case-fold
10591 // acceptance trips here), leading/trailing whitespace padding,
10592 // the trailing-newline shape, quote-wrapped candidates, and a
10593 // residual set of plausible-but-wrong English rebrand
10594 // candidates. Peer of the sibling
10595 // [`restart_strategy_try_from_str_rejects_unknown_byte_strings`]
10596 // (5b828ed) rejection witness.
10597 let rejected: &[&str] = &[
10598 "",
10599 " ",
10600 "\n",
10601 "\t",
10602 "permanent",
10603 "temporary",
10604 "transient",
10605 "PERMANENT",
10606 "TEMPORARY",
10607 "TRANSIENT",
10608 "Permanents",
10609 "Permanent ",
10610 " Permanent",
10611 " Temporary ",
10612 "Permanent\n",
10613 "Transient\t",
10614 "\"Permanent\"",
10615 "Ephemeral",
10616 "Always",
10617 "Never",
10618 "OnAbnormalExit",
10619 "intrinsic",
10620 "?",
10621 ];
10622 for &input in rejected {
10623 assert_eq!(
10624 <RestartPolicy as TryFrom<&str>>::try_from(input),
10625 Err(()),
10626 "TryFrom<&str> impl on RestartPolicy must reject the \
10627 non-wire byte-string {input:?} — silent acceptance \
10628 signals an accept-set widening off the paired \
10629 RestartPolicy::from_wire resolver"
10630 );
10631 }
10632 }
10633
10634 #[test]
10635 fn restart_policy_try_from_str_and_from_wire_partition_the_accept_set() {
10636 // Cross-axis partition pin: the paired `TryFrom<&str>` and
10637 // `from_wire` reverse projections must resolve identically on
10638 // *every* input, not just the ones [`RestartPolicy::ALL`]
10639 // enumerates. Sweeps a mixed candidate set spanning accepted
10640 // (three-arm PascalCase wire byte-strings) and rejected (kebab-
10641 // case dispatcher-catalog byte-strings, empty, whitespace-
10642 // padded, quoted, English-rebrand candidates) inputs and asserts
10643 // the trait's `Result::ok()` projection byte-equals the method-
10644 // named resolver's `Option<Self>` return-shape on each, locking
10645 // the two paths together by construction so any future detour
10646 // (a stray `try_from` special-case that widens or narrows the
10647 // accept-set outside the paired `from_wire` resolver, an
10648 // accidental swap onto the kebab-case [`std::str::FromStr`]
10649 // impl the [`gen_platform::FromStrKind`] derive installs on the
10650 // sibling dispatcher-catalog axis) trips at caixa-core test
10651 // time. Peer of the sibling
10652 // [`restart_strategy_try_from_str_and_from_wire_partition_the_accept_set`]
10653 // pin — extends the round-trip discipline onto the M2-OTP-shape
10654 // per-child restart-policy axis.
10655 let candidates: &[&str] = &[
10656 "Permanent",
10657 "Temporary",
10658 "Transient",
10659 "",
10660 "permanent",
10661 "temporary",
10662 "transient",
10663 "PERMANENT",
10664 "unknown",
10665 "Permanent ",
10666 " Permanent",
10667 "\"Permanent\"",
10668 "Ephemeral",
10669 "OnAbnormalExit",
10670 "?",
10671 ];
10672 for &input in candidates {
10673 let via_trait: Option<RestartPolicy> =
10674 <RestartPolicy as TryFrom<&str>>::try_from(input).ok();
10675 let via_method: Option<RestartPolicy> = RestartPolicy::from_wire(input);
10676 assert_eq!(
10677 via_trait, via_method,
10678 "TryFrom<&str> and from_wire must resolve identically on \
10679 input {input:?} — divergence signals the two reverse-\
10680 projection paths have drifted onto different accept-sets"
10681 );
10682 }
10683 }
10684
10685 #[test]
10686 fn restart_policy_from_into_static_str_routes_through_as_str_accessor() {
10687 // Fail-before-pass-after byte-parity pin on the newly lifted
10688 // `impl From<RestartPolicy> for &'static str` — asserts the
10689 // standard-library trait impl and the substrate-primitive
10690 // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
10691 // the same three-arm emit-set across every arm the exhaustive
10692 // [`RestartPolicy::ALL`] slice enumerates. Any future silent
10693 // detour that routes the trait impl through a divergent
10694 // projection (a per-arm inline `match policy { Permanent =>
10695 // "Permanent", … }` re-inlining that opens a compile-time link
10696 // to the un-lifted arm-literal, an accidental swap onto the
10697 // sibling kebab-case [`Self::discriminant`] dispatcher-catalog
10698 // axis that would collide the two-axis wire/catalog split the
10699 // sibling [`RestartPolicy::from_wire`] doc block makes
10700 // load-bearing) trips at caixa-core test time under
10701 // `assert_eq!` rather than at a downstream
10702 // `impl Into<&'static str>`-bound consumer's silent split.
10703 // Sweeps every one of the three arms [`RestartPolicy::ALL`]
10704 // carries so no arm's projection is covered only by the sibling
10705 // method-named `as_str` / [`std::fmt::Display`] / [`AsRef<str>`]
10706 // paths. Materializes the `<&'static str as
10707 // From<RestartPolicy>>::from` output in a `const`-shape binding
10708 // to make the `'static` lifetime promise a build-time invariant
10709 // — a future accidental downgrade of any of the three arms'
10710 // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] constants to a
10711 // non-`&'static str` (a `String::leak()`-produced return, a
10712 // `Box::leak`-cast) trips at caixa-core build time rather than
10713 // at a downstream `'static`-bound consumer. Peer of the sibling
10714 // [`restart_strategy_from_into_static_str_routes_through_as_str_accessor`]
10715 // (523157d) — extends the trait-idiomatic forward-projection
10716 // axis onto the second (and second-of-two-in-M2) closed-set
10717 // typed enum on the caixa surface (the paired per-child
10718 // restart-decision-policy sibling on the same M2 `:supervisor`
10719 // slot).
10720 const PERMANENT: &str = RestartPolicy::Permanent.as_str();
10721 const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
10722 const TRANSIENT: &str = RestartPolicy::Transient.as_str();
10723 for &variant in RestartPolicy::ALL {
10724 let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
10725 let via_method: &'static str = variant.as_str();
10726 assert_eq!(
10727 via_trait, via_method,
10728 "From<RestartPolicy> for &'static str impl must round-trip \
10729 RestartPolicy::{variant:?} to the same lifted \
10730 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str returns — \
10731 divergence signals a silent detour off the substrate-primitive \
10732 accessor"
10733 );
10734 let via_into: &'static str = variant.into();
10735 assert_eq!(
10736 via_into, via_method,
10737 "Into<&'static str>::into on RestartPolicy::{variant:?} must \
10738 byte-equal RestartPolicy::as_str on the same input — the \
10739 blanket-derived Into shape must resolve to the same as_str \
10740 dispatch as the explicit From impl"
10741 );
10742 }
10743 assert_eq!(
10744 [PERMANENT, TEMPORARY, TRANSIENT],
10745 [
10746 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
10747 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
10748 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
10749 ],
10750 "const-context RestartPolicy::as_str must resolve to the three \
10751 lifted SUPERVISOR_CHILD_RESTART_* consts — a future accidental \
10752 downgrade of any arm to a non-const or non-static byte-string \
10753 breaks the `&'static str`-lifetime promise the paired \
10754 From<RestartPolicy> for &'static str impl carries by \
10755 construction"
10756 );
10757 }
10758
10759 #[test]
10760 fn restart_policy_from_into_static_str_and_as_str_partition_the_emit_set() {
10761 // Cross-axis partition pin: the paired trait-idiomatic
10762 // `From<RestartPolicy> for &'static str` forward projection and
10763 // the method-named [`RestartPolicy::as_str`] forward projection
10764 // must resolve identically on *every* arm, not just the ones
10765 // named in the primary byte-parity pin above. Sweeps every
10766 // [`RestartPolicy::ALL`] arm and asserts the trait's `From::from`
10767 // output byte-equals the method-named accessor's return-value on
10768 // each, locking the two forward-projection paths together by
10769 // construction so any future detour (a stray `From` special-case
10770 // that lands on a divergent per-arm literal outside the paired
10771 // `as_str` dispatch, a hypothetical rebrand touching one axis
10772 // without the other) trips at caixa-core test time. Peer of the
10773 // sibling forward-projection partition pin
10774 // [`restart_strategy_from_into_static_str_and_as_str_partition_the_emit_set`]
10775 // (523157d) — extends the round-trip discipline onto the
10776 // second-of-two M2-OTP-shape closed-set typed enum on the caixa
10777 // surface, closing the two-way `Self ↔ &'static str` round-trip
10778 // on the trait-idiomatic pair (`From<Self> for &'static str` +
10779 // `TryFrom<&str> for Self`) as well as the pre-existing method-
10780 // named pair (`as_str` + `from_wire`).
10781 for &variant in RestartPolicy::ALL {
10782 let via_trait: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
10783 let via_method: &'static str = variant.as_str();
10784 assert_eq!(
10785 via_trait, via_method,
10786 "From<RestartPolicy> for &'static str and \
10787 RestartPolicy::as_str must resolve identically on \
10788 RestartPolicy::{variant:?} — divergence signals the \
10789 two forward-projection paths have drifted onto different \
10790 emit-sets"
10791 );
10792 }
10793 // Round-trip witness: every arm's forward `From` output re-parses
10794 // through the paired trait-idiomatic reverse `TryFrom<&str>` back
10795 // to the original variant. Closes the two-way `RestartPolicy ↔
10796 // &'static str` round-trip on the trait-idiomatic axis pair,
10797 // mirroring the pre-existing method-named `as_str` + `from_wire`
10798 // round-trip on the substrate-primitive axis pair.
10799 for &variant in RestartPolicy::ALL {
10800 let emitted: &'static str = variant.into();
10801 let re_parsed: Result<RestartPolicy, ()> =
10802 <RestartPolicy as TryFrom<&str>>::try_from(emitted);
10803 assert_eq!(
10804 re_parsed,
10805 Ok(variant),
10806 "trait-idiomatic axis pair must round-trip \
10807 RestartPolicy::{variant:?} through `.into::<&'static \
10808 str>()` and back through `TryFrom<&str>` — a break signals \
10809 the forward-emit and reverse-parse axes have drifted onto \
10810 different vocabularies"
10811 );
10812 }
10813 }
10814
10815 #[test]
10816 fn restart_policy_from_borrowed_into_static_str_routes_through_as_str_accessor() {
10817 // Fail-before-pass-after byte-parity pin on the newly lifted
10818 // `impl From<&RestartPolicy> for &'static str` — asserts the
10819 // borrowed-input standard-library trait impl and the substrate-
10820 // primitive [`RestartPolicy::as_str`] `pub const fn` accessor
10821 // resolve to the same three-arm emit-set across every arm the
10822 // exhaustive [`RestartPolicy::ALL`] slice enumerates. Rust's
10823 // `From` trait does not auto-derive the borrowed-input sibling
10824 // from a paired owned-input impl (no `impl<T, U> From<&T> for U
10825 // where T: Copy, U: From<T>` blanket in `core`), so the
10826 // borrowed-input axis is a distinct trait-idiomatic surface
10827 // that a `.iter().map(Into::into)` shape over
10828 // [`RestartPolicy::ALL`] (whose iterator yields
10829 // `&RestartPolicy`, not `RestartPolicy`) reaches through this
10830 // impl and no other — the paired owned-input
10831 // [`From<RestartPolicy>`] impl requires an explicit `.copied()`
10832 // / dereference before the trait fires. Materializes the
10833 // `<&'static str as From<&RestartPolicy>>::from` output in a
10834 // `const`-shape binding to make the `'static` lifetime promise
10835 // a build-time invariant.
10836 const PERMANENT: &str = RestartPolicy::Permanent.as_str();
10837 const TEMPORARY: &str = RestartPolicy::Temporary.as_str();
10838 const TRANSIENT: &str = RestartPolicy::Transient.as_str();
10839 for variant in RestartPolicy::ALL {
10840 let via_trait: &'static str = <&'static str as From<&RestartPolicy>>::from(variant);
10841 let via_method: &'static str = variant.as_str();
10842 assert_eq!(
10843 via_trait, via_method,
10844 "From<&RestartPolicy> for &'static str impl must round-trip \
10845 &RestartPolicy::{variant:?} to the same lifted \
10846 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
10847 returns — divergence signals a silent detour off the \
10848 substrate-primitive accessor"
10849 );
10850 let via_into: &'static str = variant.into();
10851 assert_eq!(
10852 via_into, via_method,
10853 "Into<&'static str>::into on &RestartPolicy::{variant:?} \
10854 must byte-equal RestartPolicy::as_str on the same input — \
10855 the blanket-derived Into shape must resolve to the same \
10856 as_str dispatch as the explicit From impl"
10857 );
10858 }
10859 assert_eq!(
10860 [PERMANENT, TEMPORARY, TRANSIENT],
10861 [
10862 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
10863 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
10864 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
10865 ],
10866 "const-context RestartPolicy::as_str must resolve to the three \
10867 lifted SUPERVISOR_CHILD_RESTART_* consts — the borrowed-input \
10868 From<&RestartPolicy> for &'static str impl inherits its \
10869 `'static` lifetime promise from the same accessor the \
10870 owned-input sibling routes through"
10871 );
10872 }
10873
10874 #[test]
10875 fn restart_policy_from_owned_and_borrowed_into_static_str_agree_on_every_arm() {
10876 // Cross-axis partition pin: the paired trait-idiomatic
10877 // owned-input `From<RestartPolicy> for &'static str` (9fb37d0
10878 // campaign-shape) and borrowed-input `From<&RestartPolicy> for
10879 // &'static str` (this lift) forward projections must resolve
10880 // identically on every arm, locking the two input-shape paths
10881 // together so any future detour trips at caixa-core test time.
10882 // Then a witness that a `.iter().map(Into::into)` pipe over
10883 // [`RestartPolicy::ALL`] (whose iterator yields
10884 // `&RestartPolicy`) materializes the three-arm accept-set
10885 // through the borrowed-input axis alone — the exact shape a
10886 // future wasm-operator per-child post-exit restart-decision
10887 // diagnostic line, a future substrate-wide per-arm diagnostic
10888 // column, or a
10889 // `HashMap::<&'static str, RestartPolicy>::from_iter(
10890 // RestartPolicy::ALL.iter().map(|p| (p.into(), *p)))`-style
10891 // per-policy lookup reaches through — closing the two-way
10892 // owned/borrowed input-shape symmetry on the forward-projection
10893 // trait-idiomatic axis. Peer of the sibling
10894 // [`crate::dep::tests::dep_list_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
10895 // (64aa742) /
10896 // [`crate::kind::tests::caixa_kind_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
10897 // (5ab993a) /
10898 // [`crate::dialeto::tests::caixa_dialeto_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
10899 // (807b0b5) /
10900 // [`restart_strategy_from_owned_and_borrowed_into_static_str_agree_on_every_arm`]
10901 // (e941836) partition pins on the sibling closed-set typed-enum
10902 // discriminator axes — extends the borrowed-input axis
10903 // discipline onto the second-of-two M2 OTP-shape closed-set
10904 // typed enum on the caixa surface (per-child restart-decision
10905 // policy). Also closes the direct two-way `&Self → &'static
10906 // str → Self` round-trip via the paired [`TryFrom<&str>`] axis
10907 // — unlike the peer [`crate::CaixaKind`] axis pair (whose
10908 // forward `From` emits lowercase Portuguese diagnostic bytes
10909 // while the reverse `TryFrom` parses `PascalCase` wire bytes,
10910 // forcing the round-trip through an intermediate wire-vocab
10911 // hop), the [`RestartPolicy::as_str`] emit and
10912 // [`RestartPolicy::from_wire`] parse share the same
10913 // `PascalCase` vocabulary by construction, so the borrowed-
10914 // input forward axis and the reverse axis compose directly.
10915 for &variant in RestartPolicy::ALL {
10916 let owned: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
10917 let borrowed: &'static str = <&'static str as From<&RestartPolicy>>::from(&variant);
10918 assert_eq!(
10919 owned, borrowed,
10920 "From<RestartPolicy> and From<&RestartPolicy> for \
10921 &'static str must resolve identically on \
10922 RestartPolicy::{variant:?} — divergence signals the \
10923 owned-input and borrowed-input forward-projection paths \
10924 have drifted onto different emit-sets"
10925 );
10926 }
10927 let via_iter: Vec<&'static str> = RestartPolicy::ALL.iter().map(Into::into).collect();
10928 let via_method: Vec<&'static str> = RestartPolicy::ALL.iter().map(|p| p.as_str()).collect();
10929 assert_eq!(
10930 via_iter, via_method,
10931 "`.iter().map(Into::into)` over RestartPolicy::ALL must \
10932 byte-equal `.iter().map(|p| p.as_str())` on every arm — the \
10933 borrowed-input `From<&RestartPolicy> for &'static str` axis \
10934 is what makes the `.iter().map(Into::into)` shape route \
10935 through the substrate-primitive `RestartPolicy::as_str` \
10936 accessor rather than through a per-call-site `.copied()` / \
10937 dereference detour"
10938 );
10939 for variant in RestartPolicy::ALL {
10940 let emitted: &'static str = variant.into();
10941 let re_parsed: Result<RestartPolicy, ()> =
10942 <RestartPolicy as TryFrom<&str>>::try_from(emitted);
10943 assert_eq!(
10944 re_parsed,
10945 Ok(*variant),
10946 "trait-idiomatic borrowed-input forward-projection + \
10947 reverse-projection axis pair must round-trip \
10948 &RestartPolicy::{variant:?} through `.into::<&'static \
10949 str>()` (via the borrowed-input axis) and back through \
10950 `TryFrom<&str>` — a break signals the borrowed-input \
10951 forward-emit and reverse-parse axes have drifted onto \
10952 different vocabularies"
10953 );
10954 }
10955 }
10956
10957 #[test]
10958 fn restart_policy_from_into_owned_string_routes_through_as_str_accessor() {
10959 // Fail-before-pass-after byte-parity pin on the newly lifted
10960 // `impl From<RestartPolicy> for String` — asserts the
10961 // owned-`String`-returning standard-library trait impl and the
10962 // substrate-primitive [`RestartPolicy::as_str`] `pub const fn`
10963 // accessor resolve to the same three-arm emit-set across every
10964 // arm the exhaustive [`RestartPolicy::ALL`] slice enumerates.
10965 // Rust's standard library does not carry a blanket
10966 // `impl<T: AsRef<str>> From<T> for String` (nor an
10967 // `impl<T: fmt::Display> From<T> for String`), so the
10968 // owned-`String` forward-projection axis is a distinct
10969 // trait-idiomatic surface that a `let key: String =
10970 // policy.into();`-shaped call site reaches through this impl
10971 // and no other — the paired sibling `From<RestartPolicy> for
10972 // &'static str` impl forces every owned-`String` call site
10973 // through an explicit `.to_owned()` / `String::from`
10974 // restatement. Peer of the first-mover
10975 // [`restart_strategy_from_into_owned_string_routes_through_as_str_accessor`]
10976 // (7baa18a) — extends the trait-idiomatic owned-`String`
10977 // forward-projection axis onto the second-of-two M2 OTP-shape
10978 // closed-set typed enums on the caixa surface (per-child
10979 // restart-decision-policy sibling on the same M2 `:supervisor`
10980 // slot).
10981 for &variant in RestartPolicy::ALL {
10982 let via_trait: String = <String as From<RestartPolicy>>::from(variant);
10983 let via_method: &'static str = variant.as_str();
10984 assert_eq!(
10985 via_trait.as_str(),
10986 via_method,
10987 "From<RestartPolicy> for String impl must round-trip \
10988 RestartPolicy::{variant:?} to the same lifted \
10989 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
10990 returns — divergence signals a silent detour off the \
10991 substrate-primitive accessor"
10992 );
10993 let via_into: String = variant.into();
10994 assert_eq!(
10995 via_into.as_str(),
10996 via_method,
10997 "Into<String>::into on RestartPolicy::{variant:?} must \
10998 byte-equal RestartPolicy::as_str on the same input — the \
10999 blanket-derived Into shape must resolve to the same as_str \
11000 dispatch as the explicit From impl"
11001 );
11002 }
11003 }
11004
11005 #[test]
11006 fn restart_policy_from_into_owned_string_and_static_str_agree_on_every_arm() {
11007 // Cross-axis partition pin: the paired trait-idiomatic
11008 // owned-`String` `From<RestartPolicy> for String` (this lift)
11009 // and owned-`&'static str` `From<RestartPolicy> for &'static
11010 // str` (9fb37d0) forward projections must resolve identically
11011 // on every arm, locking the two return-type-shape paths
11012 // together so any future detour trips at caixa-core test time.
11013 // Also byte-parity witness against the sibling
11014 // [`ToString::to_string`] surface routed through
11015 // [`std::fmt::Display`] — the three owned-heap-string paths
11016 // (`.into::<String>()`, `String::from`, `.to_string()`) must
11017 // resolve identically on every arm so a future consumer that
11018 // picks any of the three lands on the same lifted
11019 // SUPERVISOR_CHILD_RESTART_* const. Then a `.iter().copied()
11020 // .map(String::from)` pipe witness over [`RestartPolicy::ALL`]
11021 // that materializes the three-arm accept-set through the
11022 // owned-`String` axis alone — the exact shape a future
11023 // wasm-operator per-child post-exit restart-decision
11024 // diagnostic line composer or a
11025 // `HashMap::<String, RestartPolicy>::from_iter(
11026 // RestartPolicy::ALL.iter().copied().map(|p| (p.into(), p)))`-style
11027 // owned-key per-policy lookup reaches through — closing the
11028 // owned-`String` forward-projection axis's iterator-pipe
11029 // shape. Then a direct round-trip witness through the paired
11030 // trait-idiomatic reverse [`TryFrom<&str>`] axis on the
11031 // owned-`String`'s [`String::as_str`] borrow that closes the
11032 // two-way `Self → String → Self` round-trip on the trait-
11033 // idiomatic owned-`String` forward + reverse axis pair —
11034 // unlike the peer [`crate::CaixaKind`] axis pair (whose
11035 // forward `From` emits lowercase Portuguese diagnostic bytes
11036 // while the reverse `TryFrom` parses `PascalCase` wire bytes,
11037 // forcing the round-trip through an intermediate wire-vocab
11038 // hop), the [`RestartPolicy::as_str`] emit and
11039 // [`RestartPolicy::from_wire`] parse share the same
11040 // `PascalCase` vocabulary by construction, so the owned-
11041 // `String` forward axis and the reverse axis compose directly.
11042 for &variant in RestartPolicy::ALL {
11043 let owned_string: String = <String as From<RestartPolicy>>::from(variant);
11044 let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
11045 assert_eq!(
11046 owned_string.as_str(),
11047 owned_static,
11048 "From<RestartPolicy> for String and From<RestartPolicy> \
11049 for &'static str must resolve identically on \
11050 RestartPolicy::{variant:?} — divergence signals the \
11051 owned-`String` and owned-`&'static str` forward-projection \
11052 return-type-shape paths have drifted onto different \
11053 emit-sets"
11054 );
11055 let via_to_string: String = variant.to_string();
11056 assert_eq!(
11057 owned_string, via_to_string,
11058 "From<RestartPolicy> for String must byte-equal \
11059 RestartPolicy::to_string on RestartPolicy::{variant:?} — \
11060 divergence signals the trait-idiomatic owned-`String` \
11061 forward-projection axis and the ToString-through-Display \
11062 axis have drifted onto different emit-sets"
11063 );
11064 }
11065 let via_iter: Vec<String> = RestartPolicy::ALL
11066 .iter()
11067 .copied()
11068 .map(String::from)
11069 .collect();
11070 let via_method: Vec<String> = RestartPolicy::ALL
11071 .iter()
11072 .map(|p| p.as_str().to_owned())
11073 .collect();
11074 assert_eq!(
11075 via_iter, via_method,
11076 "`.iter().copied().map(String::from)` over RestartPolicy::ALL \
11077 must byte-equal `.iter().map(|p| p.as_str().to_owned())` on \
11078 every arm — the owned-`String` `From<RestartPolicy> for \
11079 String` axis is what makes the `String::from` composition \
11080 route through the substrate-primitive `RestartPolicy::as_str` \
11081 accessor rather than through a per-call-site `.to_owned()` / \
11082 `String::from(policy.as_str())` detour"
11083 );
11084 for &variant in RestartPolicy::ALL {
11085 let emitted: String = variant.into();
11086 let re_parsed: Result<RestartPolicy, ()> =
11087 <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
11088 assert_eq!(
11089 re_parsed,
11090 Ok(variant),
11091 "trait-idiomatic owned-`String` forward-projection + \
11092 reverse-projection axis pair must round-trip \
11093 RestartPolicy::{variant:?} through `.into::<String>()` \
11094 and back through `TryFrom<&str>` on the owned-`String`'s \
11095 String::as_str borrow — a break signals the owned-`String` \
11096 forward-emit and reverse-parse axes have drifted onto \
11097 different vocabularies"
11098 );
11099 }
11100 }
11101
11102 #[test]
11103 fn restart_policy_from_into_borrowed_owned_string_routes_through_as_str_accessor() {
11104 // Fail-before-pass-after byte-parity pin on the newly lifted
11105 // `impl From<&RestartPolicy> for String` — asserts the
11106 // borrowed-input owned-`String`-returning standard-library
11107 // trait impl and the substrate-primitive
11108 // [`RestartPolicy::as_str`] `pub const fn` accessor resolve to
11109 // the same three-arm emit-set across every arm the exhaustive
11110 // [`RestartPolicy::ALL`] slice enumerates. Rust's standard
11111 // library does not carry a blanket `impl<T: AsRef<str>>
11112 // From<&T> for String` (nor an `impl<T: fmt::Display> From<&T>
11113 // for String`), so the borrowed-input owned-`String` forward-
11114 // projection axis is a distinct trait-idiomatic surface that a
11115 // `let key: String = (&policy).into();`-shaped call site
11116 // reaches through this impl and no other — the paired sibling
11117 // `From<RestartPolicy> for String` impl forces every borrowed-
11118 // input call site through an explicit `Copy` deref
11119 // (`String::from(*policy)`) or an `.as_str().to_owned()` /
11120 // `.to_string()` detour. Peer of the first-mover
11121 // [`restart_strategy_from_into_borrowed_owned_string_routes_through_as_str_accessor`]
11122 // (579385f) — extends the trait-idiomatic borrowed-input
11123 // owned-`String` forward-projection axis onto the second-of-
11124 // two M2 OTP-shape closed-set typed enums on the caixa surface
11125 // (per-child restart-decision-policy sibling on the same M2
11126 // `:supervisor` slot).
11127 for &variant in RestartPolicy::ALL {
11128 let via_trait: String = <String as From<&RestartPolicy>>::from(&variant);
11129 let via_method: &'static str = variant.as_str();
11130 assert_eq!(
11131 via_trait.as_str(),
11132 via_method,
11133 "From<&RestartPolicy> for String impl must round-trip \
11134 &RestartPolicy::{variant:?} to the same lifted \
11135 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
11136 returns — divergence signals a silent detour off the \
11137 substrate-primitive accessor"
11138 );
11139 let via_into: String = (&variant).into();
11140 assert_eq!(
11141 via_into.as_str(),
11142 via_method,
11143 "Into<String>::into on &RestartPolicy::{variant:?} must \
11144 byte-equal RestartPolicy::as_str on the same input — \
11145 the blanket-derived Into shape must resolve to the \
11146 same as_str dispatch as the explicit From impl"
11147 );
11148 }
11149 }
11150
11151 #[test]
11152 fn restart_policy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm() {
11153 // Cross-axis partition pin: the newly lifted trait-idiomatic
11154 // borrowed-input owned-`String` `From<&RestartPolicy> for
11155 // String` (this lift), the paired owned-input owned-`String`
11156 // `From<RestartPolicy> for String` (7851725), the paired
11157 // borrowed-input owned-`&'static str` `From<&RestartPolicy>
11158 // for &'static str` (842c7f3), and the paired owned-input
11159 // owned-`&'static str` `From<RestartPolicy> for &'static str`
11160 // (9fb37d0) — every corner of the `{Self, &Self} × {&'static
11161 // str, String}` 2×2 trait-idiomatic projection family — must
11162 // resolve identically on every arm, locking the four
11163 // return-shape × input-shape paths together so any future
11164 // detour trips at caixa-core test time. Also byte-parity
11165 // witness against the sibling [`ToString::to_string`] surface
11166 // routed through [`std::fmt::Display`] and a direct round-trip
11167 // witness through the paired trait-idiomatic reverse
11168 // [`TryFrom<&str>`] axis on the owned-`String`'s
11169 // [`String::as_str`] borrow that closes the two-way
11170 // `&Self → String → Self` round-trip on the trait-idiomatic
11171 // borrowed-input owned-`String` forward + reverse axis pair.
11172 // Peer of the first-mover
11173 // [`restart_strategy_from_into_borrowed_owned_string_agrees_with_paired_axes_on_every_arm`]
11174 // (579385f) — closes the whole `{Self, &Self} × {&'static str,
11175 // String}` 2×2 projection corner on both M2 OTP-shape sibling
11176 // peers.
11177 for &variant in RestartPolicy::ALL {
11178 let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
11179 let owned_string: String = <String as From<RestartPolicy>>::from(variant);
11180 let borrowed_static: &'static str =
11181 <&'static str as From<&RestartPolicy>>::from(&variant);
11182 let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
11183 assert_eq!(
11184 borrowed_string, owned_string,
11185 "From<&RestartPolicy> for String and From<RestartPolicy> \
11186 for String must resolve identically on \
11187 RestartPolicy::{variant:?} — divergence signals the \
11188 borrowed-input and owned-input owned-`String` \
11189 forward-projection input-shape paths have drifted onto \
11190 different emit-sets"
11191 );
11192 assert_eq!(
11193 borrowed_string.as_str(),
11194 borrowed_static,
11195 "From<&RestartPolicy> for String and From<&RestartPolicy> \
11196 for &'static str must resolve identically on \
11197 RestartPolicy::{variant:?} — divergence signals the \
11198 borrowed-input `&'static str` and owned-`String` \
11199 return-shape paths have drifted onto different \
11200 emit-sets"
11201 );
11202 assert_eq!(
11203 borrowed_string.as_str(),
11204 owned_static,
11205 "From<&RestartPolicy> for String and From<RestartPolicy> \
11206 for &'static str must resolve identically on \
11207 RestartPolicy::{variant:?} — divergence signals a \
11208 break in the diagonal corner of the {{Self, &Self}} × \
11209 {{&'static str, String}} 2×2 trait-idiomatic \
11210 projection family"
11211 );
11212 let via_to_string: String = variant.to_string();
11213 assert_eq!(
11214 borrowed_string, via_to_string,
11215 "From<&RestartPolicy> for String must byte-equal \
11216 RestartPolicy::to_string on RestartPolicy::{variant:?} \
11217 — divergence signals the trait-idiomatic borrowed-input \
11218 owned-`String` forward-projection axis and the \
11219 ToString-through-Display axis have drifted onto \
11220 different emit-sets"
11221 );
11222 }
11223 let via_iter: Vec<String> = RestartPolicy::ALL.iter().map(String::from).collect();
11224 let via_method: Vec<String> = RestartPolicy::ALL
11225 .iter()
11226 .map(|p| p.as_str().to_owned())
11227 .collect();
11228 assert_eq!(
11229 via_iter, via_method,
11230 "`.iter().map(String::from)` over RestartPolicy::ALL — a \
11231 call site whose iteration axis holds `&RestartPolicy` by \
11232 construction — must byte-equal `.iter().map(|p| \
11233 p.as_str().to_owned())` on every arm — the borrowed-input \
11234 owned-`String` `From<&RestartPolicy> for String` axis is \
11235 what makes the `String::from` composition route through \
11236 the substrate-primitive `RestartPolicy::as_str` accessor \
11237 without a spurious `Copy` deref (which would only be \
11238 reachable through the owned-input `From<RestartPolicy> \
11239 for String` axis by first calling `.copied()` on the \
11240 iterator)"
11241 );
11242 for &variant in RestartPolicy::ALL {
11243 let emitted: String = (&variant).into();
11244 let re_parsed: Result<RestartPolicy, ()> =
11245 <RestartPolicy as TryFrom<&str>>::try_from(emitted.as_str());
11246 assert_eq!(
11247 re_parsed,
11248 Ok(variant),
11249 "trait-idiomatic borrowed-input owned-`String` \
11250 forward-projection + reverse-projection axis pair must \
11251 round-trip &RestartPolicy::{variant:?} through \
11252 `.into::<String>()` on the borrowed-input surface and \
11253 back through `TryFrom<&str>` on the owned-`String`'s \
11254 String::as_str borrow — a break signals the \
11255 borrowed-input owned-`String` forward-emit and \
11256 reverse-parse axes have drifted onto different \
11257 vocabularies"
11258 );
11259 }
11260 }
11261
11262 #[test]
11263 fn restart_policy_from_into_static_cow_str_routes_through_as_str_accessor() {
11264 // Fail-before-pass-after byte-parity pin on the newly lifted
11265 // `impl From<RestartPolicy> for std::borrow::Cow<'static, str>` —
11266 // asserts the standard-library trait impl and the substrate-
11267 // primitive [`super::RestartPolicy::as_str`] `pub const fn`
11268 // accessor resolve to the same three-arm emit-set across every
11269 // arm the exhaustive [`super::RestartPolicy::ALL`] slice
11270 // enumerates. Rust's standard library does not carry a blanket
11271 // `impl<T: AsRef<str>> From<T> for Cow<'static, str>` (nor an
11272 // `impl<T: fmt::Display> From<T> for Cow<'static, str>`), so
11273 // the `Cow<'static, str>` forward-projection axis is a
11274 // distinct trait-idiomatic surface that a
11275 // `let key: Cow<'static, str> = policy.into();`-shaped call
11276 // site reaches through this impl and no other — the paired
11277 // sibling `From<RestartPolicy> for &'static str` and
11278 // `From<RestartPolicy> for String` impls force every
11279 // `Cow<'static, str>`-parameterized call site through a
11280 // `Cow::Borrowed(policy.as_str())` /
11281 // `Cow::Owned(policy.to_string())` composition whose type
11282 // bounds have no compile-time link back to the substrate
11283 // primitive.
11284 //
11285 // Also asserts the projection lands on the zero-alloc
11286 // [`std::borrow::Cow::Borrowed`] arm (not the
11287 // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
11288 // [`super::RestartPolicy::as_str`] accessor's `&'static str`
11289 // return lifetime by construction makes the borrowed arm the
11290 // type-correct projection with no runtime allocation. Any
11291 // future silent detour that routes the impl through the owned
11292 // arm (an accidental `Cow::Owned(policy.to_string())` rewrite
11293 // that would allocate on every call site where the
11294 // `&'static str` return of [`super::RestartPolicy::as_str`]
11295 // makes the zero-alloc borrowed projection type-correct) trips
11296 // at caixa-core test time under the
11297 // [`std::borrow::Cow::Borrowed`] discriminator witness rather
11298 // than at a downstream `Cow<'static, str>`-bound consumer's
11299 // silent allocation.
11300 //
11301 // Second peer on the substrate-wide trait-idiomatic
11302 // [`std::borrow::Cow<'static, str>`] forward-projection family
11303 // to extend the axis off the top-level [`super::CaixaKind`]
11304 // enum (99c1735 owned-input, d45c409 borrowed-input) onto the
11305 // second (and second-of-two-in-M2) M2 OTP-shape closed-set
11306 // fieldless typed enum peer on the caixa surface — closes the
11307 // M2 OTP-shape tier of the campaign on the owned-input axis
11308 // (both sibling peers, `RestartStrategy` and `RestartPolicy`,
11309 // now carry the owned-input Cow<'static, str> forward
11310 // projection).
11311 for &variant in RestartPolicy::ALL {
11312 let via_trait: std::borrow::Cow<'static, str> =
11313 <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
11314 let via_method: &'static str = variant.as_str();
11315 assert_eq!(
11316 via_trait.as_ref(),
11317 via_method,
11318 "From<RestartPolicy> for Cow<'static, str> impl must \
11319 round-trip RestartPolicy::{variant:?} to the same \
11320 lifted SUPERVISOR_CHILD_RESTART_* const \
11321 RestartPolicy::as_str returns — divergence signals a \
11322 silent detour off the substrate-primitive accessor"
11323 );
11324 assert!(
11325 matches!(via_trait, std::borrow::Cow::Borrowed(_)),
11326 "From<RestartPolicy> for Cow<'static, str> impl must \
11327 land on the zero-alloc Cow::Borrowed arm on \
11328 RestartPolicy::{variant:?} — a Cow::Owned outcome \
11329 signals the projection has silently allocated where \
11330 the substrate-primitive RestartPolicy::as_str \
11331 `&'static str` return makes the borrowed arm the \
11332 type-correct projection"
11333 );
11334 let via_into: std::borrow::Cow<'static, str> = variant.into();
11335 assert_eq!(
11336 via_into.as_ref(),
11337 via_method,
11338 "Into<Cow<'static, str>>::into on \
11339 RestartPolicy::{variant:?} must byte-equal \
11340 RestartPolicy::as_str on the same input — the \
11341 blanket-derived Into shape must resolve to the same \
11342 as_str dispatch as the explicit From impl"
11343 );
11344 assert!(
11345 matches!(via_into, std::borrow::Cow::Borrowed(_)),
11346 "Into<Cow<'static, str>>::into on \
11347 RestartPolicy::{variant:?} must land on the \
11348 zero-alloc Cow::Borrowed arm — the blanket-derived \
11349 Into shape must resolve to the same Cow::Borrowed \
11350 dispatch as the explicit From impl"
11351 );
11352 }
11353 }
11354
11355 #[test]
11356 fn restart_policy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
11357 // Cross-axis partition pin: the newly lifted trait-idiomatic
11358 // `From<RestartPolicy> for std::borrow::Cow<'static, str>`
11359 // (this lift), the paired owned-input `From<RestartPolicy>
11360 // for &'static str` (9fb37d0), and the paired owned-input
11361 // `From<RestartPolicy> for String` (7851725) forward
11362 // projections must resolve identically on every arm, locking
11363 // the three return-shape paths together by construction so any
11364 // future detour trips at caixa-core test time. Also byte-parity
11365 // witness against the sibling [`ToString::to_string`] surface
11366 // routed through [`std::fmt::Display`] — every owned-heap-
11367 // string path (the `Cow::Owned` promotion of this axis's
11368 // `.into_owned()`, `From<RestartPolicy> for String`, and
11369 // `.to_string()`) resolves to the same lifted
11370 // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const per arm.
11371 //
11372 // Then a `.iter().copied().map(std::borrow::Cow::from)` pipe
11373 // witness over [`super::RestartPolicy::ALL`] that
11374 // materializes the three-arm accept-set through the
11375 // [`std::borrow::Cow<'static, str>`] axis alone — the exact
11376 // shape a future `axum::response::IntoResponse` per-policy
11377 // rejection-body composer, a future M4 admission-webhook
11378 // per-policy rejection-reason emitter whose typing rules out
11379 // the sibling [`AsRef<str>`] borrowed return, or a future
11380 // substrate-wide per-policy diagnostic surface that binds
11381 // through a [`Cow<'static, str>`] boundary reaches through.
11382 // The pipe witness also pins the zero-alloc discipline: every
11383 // element in the collected vector satisfies the
11384 // [`std::borrow::Cow::Borrowed`] arm predicate, so a future
11385 // accidental silent-allocation regression on the pipe's
11386 // iteration axis is a caixa-core-test-time failure. Peer of
11387 // the first-mover
11388 // [`restart_strategy_from_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
11389 // (7dd28b3) on the sibling M2 OTP-shape sibling-restart axis
11390 // — closes the whole owned-input `Cow<'static, str>` +
11391 // paired `{&'static str, String}` cross-axis-parity corner on
11392 // both M2 OTP-shape sibling peers.
11393 for &variant in RestartPolicy::ALL {
11394 let via_cow: std::borrow::Cow<'static, str> =
11395 <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
11396 let via_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
11397 let via_string: String = <String as From<RestartPolicy>>::from(variant);
11398 assert_eq!(
11399 via_cow.as_ref(),
11400 via_static,
11401 "From<RestartPolicy> for Cow<'static, str> and \
11402 From<RestartPolicy> for &'static str must resolve \
11403 identically on RestartPolicy::{variant:?} — \
11404 divergence signals the Cow<'static, str> and \
11405 &'static str return-shape paths have drifted onto \
11406 different emit-sets"
11407 );
11408 assert_eq!(
11409 via_cow.as_ref(),
11410 via_string.as_str(),
11411 "From<RestartPolicy> for Cow<'static, str> and \
11412 From<RestartPolicy> for String must resolve \
11413 identically on RestartPolicy::{variant:?} — \
11414 divergence signals the Cow<'static, str> and String \
11415 return-shape paths have drifted onto different \
11416 emit-sets"
11417 );
11418 let via_to_string: String = variant.to_string();
11419 assert_eq!(
11420 via_cow.as_ref(),
11421 via_to_string.as_str(),
11422 "From<RestartPolicy> for Cow<'static, str> must \
11423 byte-equal RestartPolicy::to_string on \
11424 RestartPolicy::{variant:?} — divergence signals the \
11425 trait-idiomatic Cow<'static, str> forward-projection \
11426 axis and the ToString-through-Display axis have \
11427 drifted onto different emit-sets"
11428 );
11429 }
11430 let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
11431 .iter()
11432 .copied()
11433 .map(std::borrow::Cow::from)
11434 .collect();
11435 let via_method: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
11436 .iter()
11437 .map(|p| std::borrow::Cow::Borrowed(p.as_str()))
11438 .collect();
11439 assert_eq!(
11440 via_iter, via_method,
11441 "`.iter().copied().map(Cow::from)` over \
11442 RestartPolicy::ALL must byte-equal `.iter().map(|p| \
11443 Cow::Borrowed(p.as_str()))` on every arm — the \
11444 trait-idiomatic `From<RestartPolicy> for Cow<'static, \
11445 str>` axis is what makes the `Cow::from` composition \
11446 route through the substrate-primitive \
11447 `RestartPolicy::as_str` accessor with the zero-alloc \
11448 Cow::Borrowed arm by construction, rather than a \
11449 per-call-site `Cow::Owned(policy.to_string())` \
11450 allocation"
11451 );
11452 for cow in &via_iter {
11453 assert!(
11454 matches!(cow, std::borrow::Cow::Borrowed(_)),
11455 "every element of the \
11456 .iter().copied().map(Cow::from) pipe over \
11457 RestartPolicy::ALL must land on the zero-alloc \
11458 Cow::Borrowed arm — a Cow::Owned outcome on any arm \
11459 signals the pipe's iteration axis has silently \
11460 allocated where the substrate-primitive \
11461 RestartPolicy::as_str `&'static str` return makes \
11462 the borrowed arm the type-correct projection"
11463 );
11464 }
11465 }
11466
11467 #[test]
11468 fn restart_policy_from_borrowed_into_static_cow_str_routes_through_as_str_accessor() {
11469 // Fail-before-pass-after byte-parity pin on the newly lifted
11470 // `impl From<&RestartPolicy> for std::borrow::Cow<'static, str>` —
11471 // asserts the borrowed-input standard-library trait impl and
11472 // the substrate-primitive [`super::RestartPolicy::as_str`]
11473 // `pub const fn` accessor resolve to the same three-arm emit-
11474 // set across every arm the exhaustive
11475 // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
11476 // standard library does not carry a blanket
11477 // `impl<T: AsRef<str>> From<&T> for Cow<'static, str>` (nor a
11478 // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`), so
11479 // the borrowed-input `Cow<'static, str>` forward-projection
11480 // axis is a distinct trait-idiomatic surface that a
11481 // `let key: Cow<'static, str> = (&policy).into();`-shaped
11482 // call site or a
11483 // `RestartPolicy::ALL.iter().map(Cow::from)`-shaped pipe
11484 // reaches through this impl and no other — the paired owned-
11485 // input `From<RestartPolicy> for Cow<'static, str>` impl
11486 // (0612398) forces every borrowed-input call site through an
11487 // explicit `Copy` deref (`Cow::from(*policy)`) or a
11488 // `Cow::Borrowed(policy.as_str())` open-code whose type
11489 // bounds have no compile-time link back to the substrate
11490 // primitive.
11491 //
11492 // Also asserts the projection lands on the zero-alloc
11493 // [`std::borrow::Cow::Borrowed`] arm (not the
11494 // [`std::borrow::Cow::Owned`] arm) — the substrate-primitive
11495 // [`super::RestartPolicy::as_str`] accessor's `&'static str`
11496 // return lifetime by construction makes the borrowed arm the
11497 // type-correct projection with no runtime allocation on the
11498 // borrowed-input surface just as on the paired owned-input
11499 // surface.
11500 //
11501 // Closes the `{Self, &Self}` input-shape corner on the M2
11502 // OTP-shape per-child-restart [`Cow<'static, str>`] axis on
11503 // the second-of-two-in-M2 closed-set fieldless typed enum peer
11504 // on the caixa surface (`:supervisor :children :restart`),
11505 // exactly as d45c409 closed it on the top-level
11506 // [`super::CaixaKind`] one commit after the owning half
11507 // (99c1735) landed and as 9b3e4b3 closed it on the sibling
11508 // M2 OTP-shape [`super::RestartStrategy`] one commit after
11509 // (7dd28b3) landed. This lift closes the whole M2 OTP-shape
11510 // tier of the substrate-wide Cow<'static, str> forward-
11511 // projection campaign on both input-shape corners
11512 // ({Self, &Self}) of both M2 OTP-shape sibling peers.
11513 for &variant in RestartPolicy::ALL {
11514 let via_trait: std::borrow::Cow<'static, str> =
11515 <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
11516 let via_method: &'static str = variant.as_str();
11517 assert_eq!(
11518 via_trait.as_ref(),
11519 via_method,
11520 "From<&RestartPolicy> for Cow<'static, str> impl must \
11521 round-trip &RestartPolicy::{variant:?} to the same \
11522 lifted SUPERVISOR_CHILD_RESTART_* const \
11523 RestartPolicy::as_str returns — divergence signals a \
11524 silent detour off the substrate-primitive accessor"
11525 );
11526 assert!(
11527 matches!(via_trait, std::borrow::Cow::Borrowed(_)),
11528 "From<&RestartPolicy> for Cow<'static, str> impl must \
11529 land on the zero-alloc Cow::Borrowed arm on \
11530 &RestartPolicy::{variant:?} — a Cow::Owned outcome \
11531 signals the projection has silently allocated where \
11532 the substrate-primitive RestartPolicy::as_str \
11533 `&'static str` return makes the borrowed arm the \
11534 type-correct projection"
11535 );
11536 let via_into: std::borrow::Cow<'static, str> = (&variant).into();
11537 assert_eq!(
11538 via_into.as_ref(),
11539 via_method,
11540 "Into<Cow<'static, str>>::into on \
11541 &RestartPolicy::{variant:?} must byte-equal \
11542 RestartPolicy::as_str on the same input — the \
11543 blanket-derived Into shape must resolve to the same \
11544 as_str dispatch as the explicit From impl"
11545 );
11546 assert!(
11547 matches!(via_into, std::borrow::Cow::Borrowed(_)),
11548 "Into<Cow<'static, str>>::into on \
11549 &RestartPolicy::{variant:?} must land on the \
11550 zero-alloc Cow::Borrowed arm — the blanket-derived \
11551 Into shape must resolve to the same Cow::Borrowed \
11552 dispatch as the explicit From impl"
11553 );
11554 }
11555 }
11556
11557 #[test]
11558 fn restart_policy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm() {
11559 // Cross-axis partition pin: the newly lifted trait-idiomatic
11560 // borrowed-input `From<&RestartPolicy> for
11561 // std::borrow::Cow<'static, str>` (this lift), the paired
11562 // owned-input `From<RestartPolicy> for
11563 // std::borrow::Cow<'static, str>` (0612398), the paired
11564 // borrowed-input owned-`&'static str` `From<&RestartPolicy>
11565 // for &'static str`, and the paired borrowed-input owned-
11566 // `String` `From<&RestartPolicy> for String` must resolve
11567 // identically on every arm, locking the four
11568 // return-shape × input-shape paths together by construction so
11569 // any future detour trips at caixa-core test time. Also byte-
11570 // parity witness against the sibling [`ToString::to_string`]
11571 // surface routed through [`std::fmt::Display`] — every owned-
11572 // heap-string path (this axis's `.into_owned()` promotion, the
11573 // paired [`From<&RestartPolicy> for String`], and
11574 // `.to_string()`) resolves to the same lifted
11575 // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const per arm.
11576 //
11577 // Then a `.iter().map(std::borrow::Cow::from)` pipe witness
11578 // over [`super::RestartPolicy::ALL`] — whose iterator yields
11579 // `&RestartPolicy` by construction, so the borrowed-input
11580 // [`Cow<'static, str>`] axis is what routes the pipe through
11581 // the substrate-primitive [`super::RestartPolicy::as_str`]
11582 // accessor without a spurious [`Copy`] deref (which would only
11583 // be reachable through the owned-input
11584 // [`From<RestartPolicy> for Cow<'static, str>`] axis by first
11585 // calling `.copied()` on the iterator). The pipe witness also
11586 // pins the zero-alloc discipline: every element in the
11587 // collected vector satisfies the [`std::borrow::Cow::Borrowed`]
11588 // arm predicate, so a future accidental silent-allocation
11589 // regression on the pipe's iteration axis is a caixa-core-
11590 // test-time failure. Peer of the sibling
11591 // [`restart_strategy_from_borrowed_into_static_cow_str_agrees_with_paired_axes_on_every_arm`]
11592 // (9b3e4b3) on the M2 OTP-shape sibling-restart axis — closes
11593 // the whole borrowed-input `Cow<'static, str>` +
11594 // paired `{&'static str, String}` cross-axis-parity corner on
11595 // both M2 OTP-shape sibling peers.
11596 for &policy in RestartPolicy::ALL {
11597 let borrowed_cow: std::borrow::Cow<'static, str> =
11598 <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&policy);
11599 let owned_cow: std::borrow::Cow<'static, str> =
11600 <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(policy);
11601 let borrowed_static: &'static str =
11602 <&'static str as From<&RestartPolicy>>::from(&policy);
11603 let borrowed_string: String = <String as From<&RestartPolicy>>::from(&policy);
11604 assert_eq!(
11605 borrowed_cow, owned_cow,
11606 "From<&RestartPolicy> for Cow<'static, str> and \
11607 From<RestartPolicy> for Cow<'static, str> must \
11608 resolve identically on RestartPolicy::{policy:?} — \
11609 divergence signals the borrowed-input and owned-input \
11610 Cow<'static, str> forward-projection input-shape \
11611 paths have drifted onto different emit-sets"
11612 );
11613 assert_eq!(
11614 borrowed_cow.as_ref(),
11615 borrowed_static,
11616 "From<&RestartPolicy> for Cow<'static, str> and \
11617 From<&RestartPolicy> for &'static str must resolve \
11618 identically on RestartPolicy::{policy:?} — \
11619 divergence signals the borrowed-input Cow<'static, \
11620 str> and &'static str return-shape paths have drifted \
11621 onto different emit-sets"
11622 );
11623 assert_eq!(
11624 borrowed_cow.as_ref(),
11625 borrowed_string.as_str(),
11626 "From<&RestartPolicy> for Cow<'static, str> and \
11627 From<&RestartPolicy> for String must resolve \
11628 identically on RestartPolicy::{policy:?} — \
11629 divergence signals the borrowed-input Cow<'static, \
11630 str> and owned-`String` return-shape paths have \
11631 drifted onto different emit-sets"
11632 );
11633 let via_to_string: String = policy.to_string();
11634 assert_eq!(
11635 borrowed_cow.as_ref(),
11636 via_to_string.as_str(),
11637 "From<&RestartPolicy> for Cow<'static, str> must \
11638 byte-equal RestartPolicy::to_string on \
11639 RestartPolicy::{policy:?} — divergence signals \
11640 the trait-idiomatic borrowed-input Cow<'static, str> \
11641 forward-projection axis and the ToString-through-\
11642 Display axis have drifted onto different emit-sets"
11643 );
11644 }
11645 let via_iter: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
11646 .iter()
11647 .map(std::borrow::Cow::from)
11648 .collect();
11649 let via_method: Vec<std::borrow::Cow<'static, str>> = RestartPolicy::ALL
11650 .iter()
11651 .map(|p| std::borrow::Cow::Borrowed(p.as_str()))
11652 .collect();
11653 assert_eq!(
11654 via_iter, via_method,
11655 "`.iter().map(Cow::from)` over RestartPolicy::ALL — a \
11656 call site whose iteration axis holds `&RestartPolicy` \
11657 by construction — must byte-equal `.iter().map(|p| \
11658 Cow::Borrowed(p.as_str()))` on every arm — the borrowed-\
11659 input Cow<'static, str> `From<&RestartPolicy> for \
11660 Cow<'static, str>` axis is what makes the `Cow::from` \
11661 composition route through the substrate-primitive \
11662 `RestartPolicy::as_str` accessor with the zero-alloc \
11663 Cow::Borrowed arm by construction and without a spurious \
11664 `Copy` deref (which would only be reachable through the \
11665 owned-input `From<RestartPolicy> for Cow<'static, str>` \
11666 axis by first calling `.copied()` on the iterator)"
11667 );
11668 for cow in &via_iter {
11669 assert!(
11670 matches!(cow, std::borrow::Cow::Borrowed(_)),
11671 "every element of the .iter().map(Cow::from) pipe \
11672 over RestartPolicy::ALL must land on the zero-\
11673 alloc Cow::Borrowed arm — a Cow::Owned outcome on \
11674 any arm signals the pipe's iteration axis has \
11675 silently allocated where the substrate-primitive \
11676 RestartPolicy::as_str `&'static str` return makes \
11677 the borrowed arm the type-correct projection"
11678 );
11679 }
11680 }
11681
11682 #[test]
11683 fn restart_policy_from_into_box_str_routes_through_as_str_accessor() {
11684 // Fail-before-pass-after byte-parity pin on the newly lifted
11685 // `impl From<RestartPolicy> for Box<str>` — asserts the
11686 // owned-input standard-library trait impl and the
11687 // substrate-primitive [`super::RestartPolicy::as_str`]
11688 // `pub const fn` accessor resolve to the same three-arm emit-
11689 // set across every arm the exhaustive
11690 // [`super::RestartPolicy::ALL`] slice enumerates. Extends the
11691 // substrate-wide `Box<str>` forward-projection campaign tier
11692 // opened one commit prior (69ef45c) on the paired sibling-
11693 // restart [`RestartStrategy`] onto the second (and third-and-
11694 // final) M2 OTP-shape closed-set fieldless typed enum peer on
11695 // the caixa surface (`:children :restart`), immediately after
11696 // the paired `Cow<'static, str>` axis (0612398 / b4dc55c)
11697 // closed the
11698 // `{Self, &Self} × {&'static str, String, Cow<'static, str>}`
11699 // 2×3 corner on this enum. Rust's standard library carries
11700 // `impl From<&str> for Box<str>` and
11701 // `impl From<String> for Box<str>` but no blanket
11702 // `impl<T: AsRef<str>> From<T> for Box<str>`, so this axis is
11703 // a distinct trait-idiomatic surface that a
11704 // `let key: Box<str> = policy.into();`-shaped call site
11705 // reaches through this impl and no other — a paired
11706 // `Box::from(policy.as_str())` open-code has no compile-time
11707 // link back to the substrate primitive. Peer of the sibling
11708 // [`restart_strategy_from_into_box_str_routes_through_as_str_accessor`]
11709 // (69ef45c) — extends the trait-idiomatic owned-input
11710 // [`Box<str>`] forward-projection axis onto the third and
11711 // final M2-OTP-shape closed-set typed enum on the caixa
11712 // surface.
11713 for &variant in RestartPolicy::ALL {
11714 let via_trait: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
11715 let via_method: &'static str = variant.as_str();
11716 assert_eq!(
11717 via_trait.as_ref(),
11718 via_method,
11719 "From<RestartPolicy> for Box<str> impl must round-\
11720 trip RestartPolicy::{variant:?} to the same lifted \
11721 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
11722 returns — divergence signals a silent detour off the \
11723 substrate-primitive accessor"
11724 );
11725 let via_into: Box<str> = variant.into();
11726 assert_eq!(
11727 via_into.as_ref(),
11728 via_method,
11729 "Into<Box<str>>::into on RestartPolicy::{variant:?} \
11730 must byte-equal RestartPolicy::as_str on the same \
11731 input — the blanket-derived Into shape must resolve \
11732 to the same as_str dispatch as the explicit From impl"
11733 );
11734 }
11735 }
11736
11737 #[test]
11738 fn restart_policy_from_borrowed_into_box_str_routes_through_as_str_accessor() {
11739 // Fail-before-pass-after byte-parity pin on the newly lifted
11740 // `impl From<&RestartPolicy> for Box<str>` — asserts the
11741 // borrowed-input standard-library trait impl and the
11742 // substrate-primitive [`super::RestartPolicy::as_str`]
11743 // `pub const fn` accessor resolve to the same three-arm emit-
11744 // set across every arm the exhaustive
11745 // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
11746 // standard library does not carry a blanket
11747 // `impl<T: AsRef<str>> From<&T> for Box<str>` (nor a
11748 // `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
11749 // so the borrowed-input `Box<str>` forward-projection axis
11750 // is a distinct trait-idiomatic surface that a
11751 // `let key: Box<str> = (&policy).into();`-shaped call site
11752 // or a `RestartPolicy::ALL.iter().map(Box::<str>::from)`-
11753 // shaped pipe reaches through this impl and no other — the
11754 // paired owned-input `From<RestartPolicy> for Box<str>`
11755 // impl (0a1b313) forces every borrowed-input call site
11756 // through an explicit `Copy` deref
11757 // (`Box::<str>::from((*policy).as_str())`) or a
11758 // `Box::<str>::from(policy.as_str())` open-code whose
11759 // type bounds have no compile-time link back to the
11760 // substrate primitive.
11761 //
11762 // Fourth (and closing) peer on the substrate-wide trait-
11763 // idiomatic [`Box<str>`] forward-projection family on the
11764 // M2 OTP-shape tier — closes the `{Self, &Self}` input-
11765 // shape corner of the [`Box<str>`] axis on the second (and
11766 // third-and-final) M2 OTP-shape closed-set fieldless typed
11767 // enum peer on the caixa surface (`:children :restart`),
11768 // exactly as b4dc55c closed the paired [`Cow<'static, str>`]
11769 // axis one commit after its owning half (0612398) landed
11770 // on this enum. Every remaining closed-set fieldless typed
11771 // enum peer on the M3 mesh-shape / outside-M3 caixa-core /
11772 // render-side / outside-caixa-core tiers is a future
11773 // target of the campaign.
11774 //
11775 // Also byte-parity witness against the paired owned-input
11776 // [`From<RestartPolicy> for Box<str>`] and the sibling
11777 // borrowed-input [`From<&RestartPolicy> for &'static str`],
11778 // [`From<&RestartPolicy> for String`], and
11779 // [`From<&RestartPolicy> for Cow<'static, str>`]
11780 // return-shape axes — locking the four
11781 // return-shape × input-shape paths together by construction
11782 // so any future detour trips at caixa-core test time. Then a
11783 // `.iter().map(Box::<str>::from)` pipe witness over
11784 // [`super::RestartPolicy::ALL`] — whose iterator yields
11785 // `&RestartPolicy` by construction, so the borrowed-input
11786 // [`Box<str>`] axis is what routes the pipe through the
11787 // substrate-primitive [`super::RestartPolicy::as_str`]
11788 // accessor without a spurious [`Copy`] deref (which would
11789 // only be reachable through the owned-input
11790 // [`From<RestartPolicy> for Box<str>`] axis by first
11791 // calling `.copied()` on the iterator).
11792 for &variant in RestartPolicy::ALL {
11793 let via_trait: Box<str> = <Box<str> as From<&RestartPolicy>>::from(&variant);
11794 let via_method: &'static str = variant.as_str();
11795 assert_eq!(
11796 via_trait.as_ref(),
11797 via_method,
11798 "From<&RestartPolicy> for Box<str> impl must round-\
11799 trip &RestartPolicy::{variant:?} to the same lifted \
11800 SUPERVISOR_CHILD_RESTART_* const RestartPolicy::as_str \
11801 returns — divergence signals a silent detour off the \
11802 substrate-primitive accessor"
11803 );
11804 let via_into: Box<str> = (&variant).into();
11805 assert_eq!(
11806 via_into.as_ref(),
11807 via_method,
11808 "Into<Box<str>>::into on &RestartPolicy::{variant:?} \
11809 must byte-equal RestartPolicy::as_str on the same \
11810 input — the blanket-derived Into shape must resolve \
11811 to the same as_str dispatch as the explicit From impl"
11812 );
11813 let owned_box: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
11814 assert_eq!(
11815 via_trait, owned_box,
11816 "From<&RestartPolicy> for Box<str> and \
11817 From<RestartPolicy> for Box<str> must resolve \
11818 identically on RestartPolicy::{variant:?} — \
11819 divergence signals the borrowed-input and owned-input \
11820 Box<str> forward-projection input-shape paths have \
11821 drifted onto different emit-sets"
11822 );
11823 let borrowed_static: &'static str =
11824 <&'static str as From<&RestartPolicy>>::from(&variant);
11825 assert_eq!(
11826 via_trait.as_ref(),
11827 borrowed_static,
11828 "From<&RestartPolicy> for Box<str> and \
11829 From<&RestartPolicy> for &'static str must resolve \
11830 identically on RestartPolicy::{variant:?} — \
11831 divergence signals the borrowed-input Box<str> and \
11832 &'static str return-shape paths have drifted onto \
11833 different emit-sets"
11834 );
11835 let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
11836 assert_eq!(
11837 via_trait.as_ref(),
11838 borrowed_string.as_str(),
11839 "From<&RestartPolicy> for Box<str> and \
11840 From<&RestartPolicy> for String must resolve \
11841 identically on RestartPolicy::{variant:?} — \
11842 divergence signals the borrowed-input Box<str> and \
11843 owned-`String` return-shape paths have drifted onto \
11844 different emit-sets"
11845 );
11846 let borrowed_cow: std::borrow::Cow<'static, str> =
11847 <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
11848 assert_eq!(
11849 via_trait.as_ref(),
11850 borrowed_cow.as_ref(),
11851 "From<&RestartPolicy> for Box<str> and \
11852 From<&RestartPolicy> for Cow<'static, str> must \
11853 resolve identically on RestartPolicy::{variant:?} — \
11854 divergence signals the borrowed-input Box<str> and \
11855 Cow<'static, str> return-shape paths have drifted \
11856 onto different emit-sets"
11857 );
11858 }
11859 let via_iter: Vec<Box<str>> = RestartPolicy::ALL.iter().map(Box::<str>::from).collect();
11860 let via_method: Vec<Box<str>> = RestartPolicy::ALL
11861 .iter()
11862 .map(|p| Box::<str>::from(p.as_str()))
11863 .collect();
11864 assert_eq!(
11865 via_iter, via_method,
11866 "`.iter().map(Box::<str>::from)` over \
11867 RestartPolicy::ALL — a call site whose iteration axis \
11868 holds `&RestartPolicy` by construction — must byte-\
11869 equal `.iter().map(|p| Box::<str>::from(p.as_str()))` \
11870 on every arm — the borrowed-input Box<str> \
11871 `From<&RestartPolicy> for Box<str>` axis is what \
11872 makes the `Box::<str>::from` composition route through \
11873 the substrate-primitive `RestartPolicy::as_str` \
11874 accessor without a spurious `Copy` deref (which would \
11875 only be reachable through the owned-input \
11876 `From<RestartPolicy> for Box<str>` axis by first \
11877 calling `.copied()` on the iterator)"
11878 );
11879 }
11880
11881 #[test]
11882 fn restart_policy_from_into_arc_str_routes_through_as_str_accessor() {
11883 // Fail-before-pass-after byte-parity pin on the newly lifted
11884 // `impl From<RestartPolicy> for std::sync::Arc<str>` — asserts
11885 // the owned-input standard-library trait impl and the
11886 // substrate-primitive [`super::RestartPolicy::as_str`]
11887 // `pub const fn` accessor resolve to the same three-arm emit-
11888 // set across every arm the exhaustive
11889 // [`super::RestartPolicy::ALL`] slice enumerates. Extends the
11890 // substrate-wide [`std::sync::Arc<str>`] forward-projection
11891 // campaign tier opened one projection tier prior (bca2ec8) on
11892 // the paired sibling-restart [`RestartStrategy`] owned-input
11893 // first-mover onto the second (and third-and-final) M2 OTP-
11894 // shape closed-set fieldless typed enum peer on the caixa
11895 // surface (`:children :restart`), immediately after the paired
11896 // [`Box<str>`] axis (0a1b313 / cb1d068) closed the
11897 // `{Self, &Self} × {&'static str, String, Cow<'static, str>,
11898 // Box<str>}` 2×4 corner on this enum. Rust's standard library
11899 // carries `impl From<&str> for std::sync::Arc<str>` and
11900 // `impl From<String> for std::sync::Arc<str>` but no blanket
11901 // `impl<T: AsRef<str>> From<T> for std::sync::Arc<str>` (nor
11902 // an `impl<T: fmt::Display> From<T> for std::sync::Arc<str>`),
11903 // so this axis is a distinct trait-idiomatic surface that a
11904 // `let key: std::sync::Arc<str> = policy.into();`-shaped call
11905 // site reaches through this impl and no other — a paired
11906 // `std::sync::Arc::<str>::from(policy.as_str())` open-code
11907 // has no compile-time link back to the substrate primitive,
11908 // and a two-step `std::sync::Arc::<str>::from(String::from(
11909 // policy))` composition through the owned-`String` axis
11910 // allocates twice (once into the intermediate `String`, once
11911 // into the [`Arc<str>`] on the `From<String>` conversion)
11912 // where the single-step trait impl allocates once.
11913 //
11914 // Cross-axis byte-parity witness against the sibling owned-
11915 // input `{&'static str, String, Cow<'static, str>, Box<str>}`
11916 // return-shape axes — locking the five return-shape paths on
11917 // the owned-input surface together by construction so any
11918 // future detour off the substrate-primitive
11919 // [`super::RestartPolicy::as_str`] accessor trips at caixa-
11920 // core test time.
11921 for &variant in RestartPolicy::ALL {
11922 let via_trait: std::sync::Arc<str> =
11923 <std::sync::Arc<str> as From<RestartPolicy>>::from(variant);
11924 let via_method: &'static str = variant.as_str();
11925 assert_eq!(
11926 via_trait.as_ref(),
11927 via_method,
11928 "From<RestartPolicy> for std::sync::Arc<str> impl \
11929 must round-trip RestartPolicy::{variant:?} to the \
11930 same lifted SUPERVISOR_CHILD_RESTART_* const \
11931 RestartPolicy::as_str returns — divergence signals \
11932 a silent detour off the substrate-primitive accessor"
11933 );
11934 let via_into: std::sync::Arc<str> = variant.into();
11935 assert_eq!(
11936 via_into.as_ref(),
11937 via_method,
11938 "Into<std::sync::Arc<str>>::into on \
11939 RestartPolicy::{variant:?} must byte-equal \
11940 RestartPolicy::as_str on the same input — the \
11941 blanket-derived Into shape must resolve to the same \
11942 as_str dispatch as the explicit From impl"
11943 );
11944 let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
11945 assert_eq!(
11946 via_trait.as_ref(),
11947 owned_static,
11948 "From<RestartPolicy> for std::sync::Arc<str> and \
11949 From<RestartPolicy> for &'static str must resolve \
11950 identically on RestartPolicy::{variant:?} — \
11951 divergence signals the owned-input std::sync::Arc<str> \
11952 and &'static str return-shape paths have drifted onto \
11953 different emit-sets"
11954 );
11955 let owned_string: String = <String as From<RestartPolicy>>::from(variant);
11956 assert_eq!(
11957 via_trait.as_ref(),
11958 owned_string.as_str(),
11959 "From<RestartPolicy> for std::sync::Arc<str> and \
11960 From<RestartPolicy> for String must resolve \
11961 identically on RestartPolicy::{variant:?} — \
11962 divergence signals the owned-input std::sync::Arc<str> \
11963 and owned-`String` return-shape paths have drifted \
11964 onto different emit-sets"
11965 );
11966 let owned_cow: std::borrow::Cow<'static, str> =
11967 <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
11968 assert_eq!(
11969 via_trait.as_ref(),
11970 owned_cow.as_ref(),
11971 "From<RestartPolicy> for std::sync::Arc<str> and \
11972 From<RestartPolicy> for Cow<'static, str> must \
11973 resolve identically on RestartPolicy::{variant:?} — \
11974 divergence signals the owned-input std::sync::Arc<str> \
11975 and Cow<'static, str> return-shape paths have drifted \
11976 onto different emit-sets"
11977 );
11978 let owned_box: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
11979 assert_eq!(
11980 via_trait.as_ref(),
11981 owned_box.as_ref(),
11982 "From<RestartPolicy> for std::sync::Arc<str> and \
11983 From<RestartPolicy> for Box<str> must resolve \
11984 identically on RestartPolicy::{variant:?} — \
11985 divergence signals the owned-input std::sync::Arc<str> \
11986 and Box<str> return-shape paths have drifted onto \
11987 different emit-sets"
11988 );
11989 }
11990 }
11991
11992 #[test]
11993 fn restart_policy_from_borrowed_into_arc_str_routes_through_as_str_accessor() {
11994 // Fail-before-pass-after byte-parity pin on the newly lifted
11995 // `impl From<&RestartPolicy> for std::sync::Arc<str>` —
11996 // asserts the borrowed-input standard-library trait impl and
11997 // the substrate-primitive [`super::RestartPolicy::as_str`]
11998 // `pub const fn` accessor resolve to the same three-arm
11999 // emit-set across every arm the exhaustive
12000 // [`super::RestartPolicy::ALL`] slice enumerates. Rust's
12001 // standard library carries `impl From<&str> for
12002 // std::sync::Arc<str>` and `impl From<String> for
12003 // std::sync::Arc<str>` but no blanket
12004 // `impl<T: AsRef<str>> From<&T> for std::sync::Arc<str>` (nor
12005 // a `Copy`-based `impl<T: Copy, U: From<T>> From<&T> for U`),
12006 // so the borrowed-input [`std::sync::Arc<str>`] forward-
12007 // projection axis is a distinct trait-idiomatic surface that
12008 // a `let key: std::sync::Arc<str> = (&policy).into();`-shaped
12009 // call site or a
12010 // `RestartPolicy::ALL.iter().map(std::sync::Arc::<str>::from)`-
12011 // shaped pipe reaches through this impl and no other — the
12012 // paired owned-input [`From<RestartPolicy> for
12013 // std::sync::Arc<str>`] impl (b05724e) forces every borrowed-
12014 // input call site through an explicit [`Copy`] deref
12015 // (`std::sync::Arc::<str>::from((*policy).as_str())`) or a
12016 // `std::sync::Arc::<str>::from(policy.as_str())` open-code
12017 // whose type bounds have no compile-time link back to the
12018 // substrate primitive.
12019 //
12020 // Closes the `{Self, &Self}` input-shape corner of the
12021 // substrate-wide trait-idiomatic [`std::sync::Arc<str>`]
12022 // forward-projection family on the second (and third-and-
12023 // final) M2 OTP-shape closed-set fieldless typed enum peer
12024 // on the caixa surface (`:children :restart`), one commit
12025 // after b05724e opened the owned-input half — exactly as
12026 // b3e72d7 closed the paired [`std::sync::Arc<str>`] corner on
12027 // the sibling-restart [`RestartStrategy`] first-mover one
12028 // commit after its owning half (bca2ec8) landed, and as
12029 // cb1d068 closed the paired [`Box<str>`] corner on this
12030 // enum one commit after its owning half (0a1b313) landed.
12031 //
12032 // Also byte-parity witness against the paired owned-input
12033 // [`From<RestartPolicy> for std::sync::Arc<str>`] and the
12034 // sibling borrowed-input [`From<&RestartPolicy> for
12035 // &'static str`], [`From<&RestartPolicy> for String`],
12036 // [`From<&RestartPolicy> for Cow<'static, str>`], and
12037 // [`From<&RestartPolicy> for Box<str>`] return-shape axes —
12038 // locking the five return-shape × input-shape paths together
12039 // by construction so any future detour off the substrate-
12040 // primitive [`super::RestartPolicy::as_str`] accessor trips
12041 // at caixa-core test time. Then a
12042 // `.iter().map(std::sync::Arc::<str>::from)` pipe witness
12043 // over [`super::RestartPolicy::ALL`] — whose iterator yields
12044 // `&RestartPolicy` by construction, so the borrowed-input
12045 // [`std::sync::Arc<str>`] axis is what routes the pipe
12046 // through the substrate-primitive
12047 // [`super::RestartPolicy::as_str`] accessor without a
12048 // spurious [`Copy`] deref (which would only be reachable
12049 // through the owned-input
12050 // [`From<RestartPolicy> for std::sync::Arc<str>`] axis by
12051 // first calling `.copied()` on the iterator).
12052 for &variant in RestartPolicy::ALL {
12053 let via_trait: std::sync::Arc<str> =
12054 <std::sync::Arc<str> as From<&RestartPolicy>>::from(&variant);
12055 let via_method: &'static str = variant.as_str();
12056 assert_eq!(
12057 via_trait.as_ref(),
12058 via_method,
12059 "From<&RestartPolicy> for std::sync::Arc<str> impl \
12060 must round-trip &RestartPolicy::{variant:?} to the \
12061 same lifted SUPERVISOR_CHILD_RESTART_* const \
12062 RestartPolicy::as_str returns — divergence signals \
12063 a silent detour off the substrate-primitive accessor"
12064 );
12065 let via_into: std::sync::Arc<str> = (&variant).into();
12066 assert_eq!(
12067 via_into.as_ref(),
12068 via_method,
12069 "Into<std::sync::Arc<str>>::into on \
12070 &RestartPolicy::{variant:?} must byte-equal \
12071 RestartPolicy::as_str on the same input — the \
12072 blanket-derived Into shape must resolve to the same \
12073 as_str dispatch as the explicit From impl"
12074 );
12075 let owned_arc: std::sync::Arc<str> =
12076 <std::sync::Arc<str> as From<RestartPolicy>>::from(variant);
12077 assert_eq!(
12078 via_trait, owned_arc,
12079 "From<&RestartPolicy> for std::sync::Arc<str> and \
12080 From<RestartPolicy> for std::sync::Arc<str> must \
12081 resolve identically on RestartPolicy::{variant:?} — \
12082 divergence signals the borrowed-input and owned-input \
12083 std::sync::Arc<str> forward-projection input-shape \
12084 paths have drifted onto different emit-sets"
12085 );
12086 let borrowed_static: &'static str =
12087 <&'static str as From<&RestartPolicy>>::from(&variant);
12088 assert_eq!(
12089 via_trait.as_ref(),
12090 borrowed_static,
12091 "From<&RestartPolicy> for std::sync::Arc<str> and \
12092 From<&RestartPolicy> for &'static str must resolve \
12093 identically on RestartPolicy::{variant:?} — \
12094 divergence signals the borrowed-input std::sync::Arc<str> \
12095 and &'static str return-shape paths have drifted onto \
12096 different emit-sets"
12097 );
12098 let borrowed_string: String = <String as From<&RestartPolicy>>::from(&variant);
12099 assert_eq!(
12100 via_trait.as_ref(),
12101 borrowed_string.as_str(),
12102 "From<&RestartPolicy> for std::sync::Arc<str> and \
12103 From<&RestartPolicy> for String must resolve \
12104 identically on RestartPolicy::{variant:?} — \
12105 divergence signals the borrowed-input std::sync::Arc<str> \
12106 and owned-`String` return-shape paths have drifted \
12107 onto different emit-sets"
12108 );
12109 let borrowed_cow: std::borrow::Cow<'static, str> =
12110 <std::borrow::Cow<'static, str> as From<&RestartPolicy>>::from(&variant);
12111 assert_eq!(
12112 via_trait.as_ref(),
12113 borrowed_cow.as_ref(),
12114 "From<&RestartPolicy> for std::sync::Arc<str> and \
12115 From<&RestartPolicy> for Cow<'static, str> must \
12116 resolve identically on RestartPolicy::{variant:?} — \
12117 divergence signals the borrowed-input std::sync::Arc<str> \
12118 and Cow<'static, str> return-shape paths have drifted \
12119 onto different emit-sets"
12120 );
12121 let borrowed_box: Box<str> = <Box<str> as From<&RestartPolicy>>::from(&variant);
12122 assert_eq!(
12123 via_trait.as_ref(),
12124 borrowed_box.as_ref(),
12125 "From<&RestartPolicy> for std::sync::Arc<str> and \
12126 From<&RestartPolicy> for Box<str> must resolve \
12127 identically on RestartPolicy::{variant:?} — \
12128 divergence signals the borrowed-input std::sync::Arc<str> \
12129 and Box<str> return-shape paths have drifted onto \
12130 different emit-sets"
12131 );
12132 }
12133 let via_iter: Vec<std::sync::Arc<str>> = RestartPolicy::ALL
12134 .iter()
12135 .map(std::sync::Arc::<str>::from)
12136 .collect();
12137 let via_method: Vec<std::sync::Arc<str>> = RestartPolicy::ALL
12138 .iter()
12139 .map(|p| std::sync::Arc::<str>::from(p.as_str()))
12140 .collect();
12141 assert_eq!(
12142 via_iter, via_method,
12143 "`.iter().map(std::sync::Arc::<str>::from)` over \
12144 RestartPolicy::ALL — a call site whose iteration axis \
12145 holds `&RestartPolicy` by construction — must byte-\
12146 equal `.iter().map(|p| std::sync::Arc::<str>::from(p.as_str()))` \
12147 on every arm — the borrowed-input std::sync::Arc<str> \
12148 `From<&RestartPolicy> for std::sync::Arc<str>` axis is \
12149 what makes the `std::sync::Arc::<str>::from` composition \
12150 route through the substrate-primitive \
12151 `RestartPolicy::as_str` accessor without a spurious \
12152 `Copy` deref (which would only be reachable through the \
12153 owned-input `From<RestartPolicy> for std::sync::Arc<str>` \
12154 axis by first calling `.copied()` on the iterator)"
12155 );
12156 }
12157
12158 // ── drift-detection: serde-derive-to-SUPERVISOR_CHILD_RESTART_* identity ─
12159
12160 #[test]
12161 fn restart_policy_variants_serialize_to_lifted_scalar_values() {
12162 // The fail-before-pass-after pin: pre-lift there was no
12163 // single-source binding between the [`RestartPolicy`] variant
12164 // name the un-`rename`d `Serialize` derive emits under
12165 // [`crate::render::SUPERVISOR_CHILD_KEY_RESTART`] and the
12166 // byte-string every downstream cluster-side dispatcher (the
12167 // future wasm-operator's per-child post-exit restart-decision
12168 // branch, the future M4 `mesh.pleme.io/v1alpha1/Supervisor` CR
12169 // materializer's admission-time enum-arm bind, the
12170 // `caixa-operator`'s hierarchical reconciliation scheduler's
12171 // per-child-policy fan-out) probes verbatim. A future
12172 // `#[serde(rename_all = "kebab-case")]` attribute on the enum —
12173 // or a per-variant `#[serde(rename = "…")]` override, or a
12174 // variant rename in the source — would silently rebrand the
12175 // emitted scalar under one spelling while every downstream
12176 // dispatcher still probed the other, with the failure surfacing
12177 // at the operator's reconcile posture (children coming up under
12178 // the `default()` `Permanent` arm rather than the typed slot's
12179 // declared policy — a `:temporary` `oneShot` child would be
12180 // restarted on clean exit, treating the successful-completion
12181 // signal as failure and re-running the completion-terminal
12182 // one-shot indefinitely; a `:transient` child that clean-exited
12183 // would be restarted, masking the clean-completion contract)
12184 // far from the source rebrand commit and with no field naming
12185 // the drift. Pinning the two paths (the `Serialize` derive's
12186 // serialized string AND the [`RestartPolicy::as_str`] helper)
12187 // to the same three lifted
12188 // [`crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT`] /
12189 // [`crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY`] /
12190 // [`crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT`]
12191 // byte-strings makes any future drift on either endpoint fail
12192 // here at caixa-core build time. Peer of the sibling
12193 // [`restart_strategy_variants_serialize_to_lifted_scalar_values`]
12194 // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
12195 // and the M3
12196 // `placement_strategy_variants_serialize_to_lifted_scalar_values`
12197 // (3f0e21c) on the per-Aplicacao distribution-strategy axis —
12198 // same three-path-convergence discipline, extended to close the
12199 // third OTP-shaped closed-enum discriminator axis on the caixa
12200 // typed surface (per-child restart-decision policy).
12201 for (variant, expected) in [
12202 (
12203 RestartPolicy::Permanent,
12204 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
12205 ),
12206 (
12207 RestartPolicy::Temporary,
12208 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
12209 ),
12210 (
12211 RestartPolicy::Transient,
12212 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
12213 ),
12214 ] {
12215 let json = serde_json::to_string(&variant).unwrap();
12216 assert_eq!(
12217 json,
12218 format!("\"{expected}\""),
12219 "RestartPolicy::{variant:?} must serialize to {expected:?}"
12220 );
12221 assert_eq!(
12222 variant.as_str(),
12223 expected,
12224 "RestartPolicy::{variant:?}.as_str() must return the lifted \
12225 SUPERVISOR_CHILD_RESTART_* constant"
12226 );
12227 }
12228 }
12229
12230 #[test]
12231 fn supervisor_child_restart_consts_are_pairwise_distinct() {
12232 // Cross-arm drift-detection pin: a future collapse of two
12233 // canonical variant byte-strings onto the same value (e.g. an
12234 // accidental copy-paste flip of `SUPERVISOR_CHILD_RESTART_TRANSIENT`
12235 // to also read `"Permanent"`) would silently reroute every
12236 // downstream operator's per-child-policy dispatch onto the
12237 // sibling arm's reconcile branch and pass every propagation-probe
12238 // test that expected only the stale arm's value — a `:transient`
12239 // child would come up under the `:permanent` restart-decision
12240 // posture on every subsequent clean exit, so a completion-terminal
12241 // child would be restarted indefinitely against its declared
12242 // policy. Peer of the sibling
12243 // [`supervisor_estrategia_consts_are_pairwise_distinct`]
12244 // (09ffb2d) on the per-supervisor sibling-restart-strategy axis
12245 // and the four-way distinct pin
12246 // `supervisor_key_consts_are_pairwise_distinct` (40cc4e5) on the
12247 // top-level `SUPERVISOR_KEY_*` axis.
12248 let all = [
12249 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
12250 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
12251 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
12252 ];
12253 for (i, a) in all.iter().enumerate() {
12254 for (j, b) in all.iter().enumerate() {
12255 if i != j {
12256 assert_ne!(
12257 a, b,
12258 "SUPERVISOR_CHILD_RESTART_* consts must be pairwise distinct \
12259 — got duplicate {a:?} at indices {i} and {j}",
12260 );
12261 }
12262 }
12263 }
12264 }
12265
12266 #[test]
12267 fn restart_policy_display_routes_through_as_str_helper() {
12268 // The fail-before-pass-after pin on the first half of the
12269 // three-path convergence: pre-convergence [`RestartPolicy`]
12270 // carried a [`std::fmt::Display`] surface via its
12271 // `#[discriminant(also_display)]` gen-platform derive route,
12272 // which arrived kebab-case as `"permanent"` / `"temporary"`
12273 // / `"transient"` on this three-arm enum (whose variant
12274 // names each collapse to their own lowercase form under the
12275 // kebab-case transform) while the wire format ran as
12276 // PascalCase `"Permanent"` / `"Temporary"` / `"Transient"`
12277 // through the un-`rename`d serde derive. Every consumer
12278 // reaching for a policy byte-string past the wire format had
12279 // to pick between three paths ([`RestartPolicy::as_str`],
12280 // the `Serialize` derive's serialized string, or
12281 // `format!("{v}")` on the discriminant-Display route), any
12282 // two of which a future variant rename or
12283 // `#[serde(rename_all = "kebab-case")]` attribute would
12284 // silently desynchronize. Wiring [`std::fmt::Display`]
12285 // through [`RestartPolicy::as_str`] closes the third path:
12286 // every `format!("{v}")` call reaches the same lifted
12287 // [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const the
12288 // wire format and the [`RestartPolicy::as_str`] helper
12289 // already route through, so a future variant rename lands at
12290 // exactly one place. Pin the routing here so a future
12291 // `impl std::fmt::Display for RestartPolicy`
12292 // reimplementation that hand-rolls the arms instead of
12293 // delegating to [`RestartPolicy::as_str`] fails at
12294 // caixa-core build time. Peer of the sibling
12295 // [`restart_strategy_display_routes_through_as_str_helper`]
12296 // on the per-supervisor sibling-restart-strategy axis and
12297 // the M3
12298 // `placement_strategy_display_routes_through_as_str_helper`
12299 // (cc8f749) — the third of three OTP-shape closed-enum
12300 // discriminator axes on the caixa typed surface now
12301 // converged onto the same three-path
12302 // (Display → as_str → lifted const) discipline.
12303 for variant in [
12304 RestartPolicy::Permanent,
12305 RestartPolicy::Temporary,
12306 RestartPolicy::Transient,
12307 ] {
12308 assert_eq!(
12309 variant.to_string(),
12310 variant.as_str(),
12311 "RestartPolicy::{variant:?} Display must route through \
12312 RestartPolicy::as_str (single source of truth: the lifted \
12313 SUPERVISOR_CHILD_RESTART_* const the wire format also emits)"
12314 );
12315 }
12316 }
12317
12318 #[test]
12319 fn restart_policy_display_matches_serialized_wire_byte_string() {
12320 // The fail-before-pass-after pin on the second half of the
12321 // three-path convergence: `Display` (user-facing text) agrees
12322 // byte-for-byte with the `Serialize` derive's wire format
12323 // (canonical camelCase-schema `SUPERVISOR_CHILD_KEY_RESTART`
12324 // scalar) on every variant. Pre-convergence the two paths
12325 // were structurally independent — a future
12326 // `#[serde(rename_all = "kebab-case")]` attribute on the
12327 // enum would silently rebrand the emitted wire scalar
12328 // (`permanent`, `temporary`, `transient`) while every
12329 // consumer that pretty-prints the policy (the future
12330 // wasm-operator's per-child post-exit restart-decision
12331 // diagnostic line, the future `feira app graph` per-child
12332 // restart column, the future M4
12333 // `mesh.pleme.io/v1alpha1/Supervisor` CR materializer's
12334 // per-child admission-webhook rejection body) would still
12335 // emit the PascalCase form the `as_str` / `Display` route
12336 // returns, with the mismatch surfacing at consumer parse
12337 // time / operator dispatch time far from the source rebrand
12338 // commit. Pin the two paths byte-for-byte here so any future
12339 // serde-attribute or variant-rename drift is a
12340 // caixa-core-build-time test failure at this call, not a
12341 // silent per-consumer dispatch miss. Peer of the sibling
12342 // [`restart_strategy_display_matches_serialized_wire_byte_string`]
12343 // on the per-supervisor sibling-restart-strategy axis and
12344 // the M3
12345 // `placement_strategy_display_matches_serialized_wire_byte_string`
12346 // (cc8f749).
12347 for variant in [
12348 RestartPolicy::Permanent,
12349 RestartPolicy::Temporary,
12350 RestartPolicy::Transient,
12351 ] {
12352 let wire = serde_json::to_string(&variant).unwrap();
12353 let unquoted = wire
12354 .strip_prefix('"')
12355 .and_then(|s| s.strip_suffix('"'))
12356 .expect("serialized RestartPolicy is a JSON string");
12357 assert_eq!(
12358 variant.to_string(),
12359 unquoted,
12360 "RestartPolicy::{variant:?} Display byte-string must match the \
12361 Serialize derive's wire byte-string (three-path convergence: \
12362 Display + as_str + Serialize all resolve to the same \
12363 SUPERVISOR_CHILD_RESTART_* const)"
12364 );
12365 }
12366 }
12367
12368 #[test]
12369 fn restart_policy_as_ref_str_routes_through_as_str_accessor() {
12370 // Fail-before-pass-after byte-parity pin on the lifted
12371 // `impl AsRef<str> for RestartPolicy` — asserts the
12372 // standard-library trait impl and the substrate-primitive
12373 // [`RestartPolicy::as_str`] `pub const fn` accessor resolve
12374 // to the same `&str` per instance across the three-arm
12375 // closed set, so any future silent detour that routes the
12376 // impl through a divergent projection (a per-arm inline
12377 // `match self { RestartPolicy::Permanent => "Permanent", … }`
12378 // re-inlining that opens a compile-time link to the un-lifted
12379 // arm-literal, a swap onto the kebab-case
12380 // [`gen_platform::Discriminant`] catalog identity that would
12381 // collide the wire axis with the dispatcher-catalog axis) trips
12382 // at caixa-core test time under `PartialEq` rather than at a
12383 // downstream `impl AsRef<str>`-bound consumer's silent split.
12384 // Sweeps every one of the three arms
12385 // [`RestartPolicy::ALL`] carries so no arm's projection is
12386 // covered only by the sibling wire-format `Serialize` derive
12387 // path. Peer of the sibling
12388 // [`restart_strategy_as_ref_str_routes_through_as_str_accessor`]
12389 // (63eb1a4) on the paired per-supervisor sibling-restart-
12390 // strategy axis and the [`crate::CaixaVersion`]
12391 // `AsRef<str>`-byte-parity pin (16d5c7e) on the paired
12392 // top-level `:versao` typed newtype — the three pins together
12393 // cover the substrate primitive's `AsRef<str>` projection axis
12394 // on the paired newtype + M2 closed-set-typed-enum surface.
12395 for &variant in RestartPolicy::ALL {
12396 assert_eq!(
12397 <RestartPolicy as AsRef<str>>::as_ref(&variant),
12398 variant.as_str(),
12399 "AsRef<str> impl on RestartPolicy::{variant:?} must \
12400 byte-equal RestartPolicy::as_str on the same instance \
12401 — divergence signals a silent detour off the substrate-\
12402 primitive accessor"
12403 );
12404 }
12405 }
12406
12407 #[test]
12408 fn restart_policy_as_ref_str_routes_through_display_via_shared_accessor() {
12409 // Fail-before-pass-after byte-parity pin on the three-path
12410 // convergence discipline the M2 per-child-restart-policy
12411 // primitive now carries on the `&str`-projection axis:
12412 // `<RestartPolicy as AsRef<str>>::as_ref(&v)` (the newly
12413 // lifted impl), `format!("{v}")` (the pre-existing
12414 // [`fmt::Display`] impl), and `v.as_str()` (the substrate-
12415 // primitive `pub const fn` accessor both trait impls delegate
12416 // through) must resolve to the same byte-string on every
12417 // instance across the three-arm closed set. Refuses any future
12418 // divergence between the two trait impls (a stray
12419 // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
12420 // rather than delegating through the shared accessor; a
12421 // hypothetical `AsRef<str>` rewrite that inlines a per-arm
12422 // literal cascade) that would silently split the two
12423 // projection paths of the same closed-set typed enum. Mirrors
12424 // the sibling three-path-convergence discipline the peer
12425 // [`RestartStrategy`] typed enum carries on its
12426 // `AsRef<str>` / `Display` / `as_str` triple
12427 // (supervisor.rs pin
12428 // `restart_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
12429 // 63eb1a4) and the [`crate::CaixaVersion`] typed newtype
12430 // carries on the same triple (version.rs pin
12431 // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
12432 // 16d5c7e).
12433 for &variant in RestartPolicy::ALL {
12434 let via_as_ref: &str = <RestartPolicy as AsRef<str>>::as_ref(&variant);
12435 let via_display: String = format!("{variant}");
12436 let via_accessor: &str = variant.as_str();
12437 assert_eq!(via_as_ref, via_accessor);
12438 assert_eq!(via_display, via_accessor);
12439 assert_eq!(via_as_ref, via_display.as_str());
12440 }
12441 }
12442
12443 // The `generic_bytes_sink(&variant)` and `borrowed_hasher.update(&variant)`
12444 // shapes below are the borrowed-input witness half of the by-value +
12445 // by-reference partition the paired witness pair carries: the pair proves
12446 // the trait bound accepts both owned (`variant`) and borrowed (`&variant`)
12447 // shapes through the same substrate-primitive `as_str` accessor, which is
12448 // the shape the caixa-lacre BLAKE3 content-address closure composes.
12449 // `clippy::needless_borrows_for_generic_args` would fold the borrowed half
12450 // into the owned half and collapse the by-value/by-reference partition
12451 // this test load-bears; the `#[allow]` documents that the partition is
12452 // deliberate, not an oversight.
12453 #[allow(clippy::needless_borrows_for_generic_args)]
12454 #[test]
12455 fn restart_policy_as_ref_bytes_routes_through_as_str_accessor() {
12456 // `<T: AsRef<[u8]>>`-bound generic-consumer witness: a byte-input
12457 // function that binds its argument through the standard-library
12458 // [`AsRef<[u8]>`] trait bound accepts a [`super::RestartPolicy`]
12459 // directly, without the caller open-coding the two-hop
12460 // `restart.as_str().as_bytes()` composition. Lifted to the top
12461 // of the function per `clippy::items_after_statements`.
12462 fn generic_bytes_sink<T: AsRef<[u8]>>(t: T) -> Vec<u8> {
12463 t.as_ref().to_vec()
12464 }
12465 // `blake3::Hasher::update`-shape byte-input surface mock: mirrors
12466 // `blake3::Hasher::update` / `ring::digest::Context::update` /
12467 // `sha2::Sha256::update`'s `impl AsRef<[u8]>`-bound `update`
12468 // signature so a per-child BLAKE3 content-address closure that
12469 // composes `hasher.update(restart)` on the [`crate::Lacre`]
12470 // closure builder reaches the substrate-primitive `as_str`
12471 // accessor through the [`super::RestartPolicy`] `AsRef<[u8]>`
12472 // axis and no other. Lifted to the top of the function per
12473 // `clippy::items_after_statements`.
12474 struct MockHasher(Vec<u8>);
12475 impl MockHasher {
12476 fn new() -> Self {
12477 Self(Vec::new())
12478 }
12479 fn update(&mut self, bytes: impl AsRef<[u8]>) -> &mut Self {
12480 self.0.extend_from_slice(bytes.as_ref());
12481 self
12482 }
12483 fn finalize(self) -> Vec<u8> {
12484 self.0
12485 }
12486 }
12487
12488 // Fail-before-pass-after byte-parity pin on the newly lifted
12489 // `impl AsRef<[u8]> for RestartPolicy` — asserts the trait-
12490 // idiomatic byte-view standard-library impl and the substrate-
12491 // primitive [`super::RestartPolicy::as_str`] `pub const fn`
12492 // accessor's `.as_bytes()` byte-tail resolve to the same three-
12493 // arm `PascalCase` wire byte-string emit-set across every arm
12494 // the exhaustive [`super::RestartPolicy::ALL`] slice enumerates.
12495 // Extends the trait-idiomatic byte-view axis onto the second
12496 // (and final) M2 OTP-shape closed-set fieldless typed enum peer
12497 // on the caixa surface (the paired per-child restart-decision
12498 // policy sibling on the same M2 `:supervisor` slot), closing
12499 // the byte-view axis across the `:supervisor :estrategia` +
12500 // `:children :restart` M2 slot pair the sibling
12501 // [`super::RestartStrategy`] first-mover (cd4c4e0) opened.
12502 //
12503 // Rust's standard library carries `impl AsRef<[u8]> for str` and
12504 // `impl AsRef<[u8]> for String`, so a two-hop composition
12505 // `restart.as_str().as_bytes()` (or the equally two-hop
12506 // `AsRef::<str>::as_ref(&restart).as_bytes()`) is reachable
12507 // through the pre-existing str-view axis alone. But that two-hop
12508 // shape has no compile-time link back to the byte-projection
12509 // axis, forces every downstream `<T: AsRef<[u8]>>`-bound
12510 // consumer to open-code the two-hop composition at every call
12511 // site, and admits a silent split whenever a future call site
12512 // takes a sibling reverse-projection axis whose `.as_bytes()`
12513 // byte-tail carries no compile-time byte-view surface. This
12514 // impl closes the byte-view axis at the substrate-primitive
12515 // [`super::RestartPolicy::as_str`] accessor so every future
12516 // `<T: AsRef<[u8]>>`-bound consumer reaches the same lifted
12517 // [`super::crate::render::SUPERVISOR_CHILD_RESTART_*`] const
12518 // roster the paired str-view axes already return through —
12519 // through one trait dispatch.
12520 for &variant in RestartPolicy::ALL {
12521 let via_trait: &[u8] = <RestartPolicy as AsRef<[u8]>>::as_ref(&variant);
12522 let via_method_bytes: &[u8] = variant.as_str().as_bytes();
12523 assert_eq!(
12524 via_trait, via_method_bytes,
12525 "AsRef<[u8]> for RestartPolicy impl must byte-equal \
12526 RestartPolicy::as_str().as_bytes() on \
12527 RestartPolicy::{variant:?} — divergence signals a \
12528 silent detour off the substrate-primitive accessor"
12529 );
12530 // Cross-axis witness against the paired str-view axes'
12531 // `.as_bytes()` byte-tails: [`AsRef<str>`] /
12532 // [`std::fmt::Display`] / [`super::RestartPolicy::as_str`]
12533 // all resolve to the same lifted
12534 // [`super::crate::render::SUPERVISOR_CHILD_RESTART_*`] const
12535 // roster, and the byte-view axis must byte-equal each of
12536 // their `.as_bytes()` byte-tails by construction — locking
12537 // the str-view and byte-view axes together at the
12538 // substrate-primitive accessor.
12539 let str_view_ref: &str = <RestartPolicy as AsRef<str>>::as_ref(&variant);
12540 assert_eq!(
12541 via_trait,
12542 str_view_ref.as_bytes(),
12543 "AsRef<[u8]> for RestartPolicy and AsRef<str> for \
12544 RestartPolicy must resolve to byte-equal byte-tails \
12545 on RestartPolicy::{variant:?} — divergence signals \
12546 the byte-view and str-view axes have drifted off the \
12547 same substrate-primitive as_str accessor"
12548 );
12549 let display_bytes = variant.to_string();
12550 assert_eq!(
12551 via_trait,
12552 display_bytes.as_bytes(),
12553 "AsRef<[u8]> for RestartPolicy and \
12554 <RestartPolicy as std::fmt::Display>::to_string must \
12555 resolve to byte-equal byte-tails on \
12556 RestartPolicy::{variant:?} — divergence signals the \
12557 byte-view axis and the Display formatter axis have \
12558 drifted off the same substrate-primitive as_str \
12559 accessor"
12560 );
12561 // Cross-axis witness against the paired reverse-projection
12562 // axes' `.as_bytes()` byte-tails: every one of `{&'static
12563 // str, String, Cow<'static, str>, Box<str>,
12564 // std::sync::Arc<str>}` allocates (or borrows) the same
12565 // `PascalCase` wire byte-string the substrate-primitive
12566 // accessor emits, so the byte-view axis must byte-equal
12567 // each of their `.as_bytes()` byte-tails by construction.
12568 let owned_static: &'static str = <&'static str as From<RestartPolicy>>::from(variant);
12569 assert_eq!(
12570 via_trait,
12571 owned_static.as_bytes(),
12572 "AsRef<[u8]> for RestartPolicy and From<RestartPolicy> \
12573 for &'static str must resolve to byte-equal byte-tails \
12574 on RestartPolicy::{variant:?}"
12575 );
12576 let owned_string: String = <String as From<RestartPolicy>>::from(variant);
12577 assert_eq!(
12578 via_trait,
12579 owned_string.as_bytes(),
12580 "AsRef<[u8]> for RestartPolicy and From<RestartPolicy> \
12581 for String must resolve to byte-equal byte-tails on \
12582 RestartPolicy::{variant:?}"
12583 );
12584 let owned_cow: std::borrow::Cow<'static, str> =
12585 <std::borrow::Cow<'static, str> as From<RestartPolicy>>::from(variant);
12586 assert_eq!(
12587 via_trait,
12588 owned_cow.as_bytes(),
12589 "AsRef<[u8]> for RestartPolicy and From<RestartPolicy> \
12590 for Cow<'static, str> must resolve to byte-equal byte-\
12591 tails on RestartPolicy::{variant:?}"
12592 );
12593 let owned_box: Box<str> = <Box<str> as From<RestartPolicy>>::from(variant);
12594 assert_eq!(
12595 via_trait,
12596 owned_box.as_bytes(),
12597 "AsRef<[u8]> for RestartPolicy and From<RestartPolicy> \
12598 for Box<str> must resolve to byte-equal byte-tails on \
12599 RestartPolicy::{variant:?}"
12600 );
12601 let owned_arc: std::sync::Arc<str> =
12602 <std::sync::Arc<str> as From<RestartPolicy>>::from(variant);
12603 assert_eq!(
12604 via_trait,
12605 owned_arc.as_bytes(),
12606 "AsRef<[u8]> for RestartPolicy and From<RestartPolicy> \
12607 for std::sync::Arc<str> must resolve to byte-equal \
12608 byte-tails on RestartPolicy::{variant:?}"
12609 );
12610 }
12611 // `<T: AsRef<[u8]>>`-bound-consumer witness: the generic byte-
12612 // input function `generic_bytes_sink` (lifted above per
12613 // `clippy::items_after_statements`) accepts a
12614 // [`super::RestartPolicy`] directly through the trait bound,
12615 // without the caller open-coding the two-hop
12616 // `restart.as_str().as_bytes()` composition. This is the shape
12617 // that reaches the caixa-lacre BLAKE3 content-address closure's
12618 // `blake3::Hasher::update(impl AsRef<[u8]>)` byte-input surface
12619 // through this impl and no other.
12620 for &variant in RestartPolicy::ALL {
12621 let via_generic = generic_bytes_sink(variant);
12622 let via_borrowed_generic = generic_bytes_sink(&variant);
12623 let via_method_bytes = variant.as_str().as_bytes().to_vec();
12624 assert_eq!(
12625 via_generic, via_method_bytes,
12626 "generic `<T: AsRef<[u8]>>`-bound consumer on \
12627 RestartPolicy::{variant:?} must yield the same byte-\
12628 tail RestartPolicy::as_str().as_bytes() returns — \
12629 divergence signals the byte-view axis fails to bridge \
12630 a generic byte-input trait bound to the substrate-\
12631 primitive accessor"
12632 );
12633 assert_eq!(
12634 via_borrowed_generic, via_method_bytes,
12635 "generic `<T: AsRef<[u8]>>`-bound consumer on \
12636 &RestartPolicy::{variant:?} must yield the same byte-\
12637 tail RestartPolicy::as_str().as_bytes() returns — the \
12638 borrowed-input surface must resolve to the same as_str \
12639 dispatch"
12640 );
12641 }
12642 // `blake3::Hasher::update`-shape byte-input surface witness on
12643 // the caixa-lacre compounding target: the `MockHasher` (lifted
12644 // above per `clippy::items_after_statements`) mirrors
12645 // `blake3::Hasher::update` / `ring::digest::Context::update` /
12646 // `sha2::Sha256::update`'s `impl AsRef<[u8]>`-bound update
12647 // signature and accepts a [`super::RestartPolicy`] directly,
12648 // routing its byte-tail through the substrate-primitive
12649 // `as_str` accessor — the shape a future per-child BLAKE3
12650 // content-address closure composes to fold a `:restart`
12651 // discriminator byte-tag into the [`crate::Lacre`] closure
12652 // body.
12653 for &variant in RestartPolicy::ALL {
12654 let mut owned_hasher = MockHasher::new();
12655 owned_hasher.update(variant);
12656 let owned_folded = owned_hasher.finalize();
12657 assert_eq!(
12658 owned_folded,
12659 variant.as_str().as_bytes(),
12660 "`hasher.update(restart)`-shape composition on \
12661 RestartPolicy::{variant:?} must fold the same byte-\
12662 tail RestartPolicy::as_str().as_bytes() returns — the \
12663 shape a future per-child BLAKE3 content-address \
12664 closure composes to fold a `:restart` discriminator \
12665 byte-tag into the Lacre closure body"
12666 );
12667 let mut borrowed_hasher = MockHasher::new();
12668 borrowed_hasher.update(&variant);
12669 let borrowed_folded = borrowed_hasher.finalize();
12670 assert_eq!(
12671 borrowed_folded,
12672 variant.as_str().as_bytes(),
12673 "`hasher.update(&restart)`-shape composition on \
12674 &RestartPolicy::{variant:?} must fold the same byte-\
12675 tail RestartPolicy::as_str().as_bytes() returns — the \
12676 borrowed-input surface must resolve to the same as_str \
12677 dispatch"
12678 );
12679 }
12680 }
12681
12682 #[test]
12683 fn restart_policy_all_enumerates_every_variant_exactly_once() {
12684 // Fail-before-pass-after pin on the [`RestartPolicy::ALL`]
12685 // exhaustive-iteration surface: every variant appears exactly
12686 // once, and the slice length matches the arm count of the
12687 // closed set. Every consumer that walks the accepted-policy
12688 // set (a future `feira supervisor --restart …` CLI-side
12689 // arg-parse's "did you mean" hint, a future M4 admission-
12690 // webhook's per-child rejection body naming the accepted-
12691 // `:restart` list, the [`RestartPolicy::from_wire`] reverse-
12692 // projection consumers that iterate the accept-set for
12693 // diagnostic rendering) reads through this slice, so a future
12694 // arm addition that grows the enum but forgets to grow
12695 // [`Self::ALL`] silently truncates every downstream consumer's
12696 // accept-set at the same pre-addition boundary — this pin
12697 // fails at caixa-core build time on the pairwise-distinct +
12698 // arm-count invariants.
12699 //
12700 // Peer of the sibling [`RestartStrategy::ALL`] (4eec29c) /
12701 // [`crate::CaixaKind::ALL`] (6b1f4fb) /
12702 // [`crate::aplicacao::PlacementStrategy::ALL`] (18c7342) /
12703 // [`crate::aplicacao::RateLimitUnit::ALL`] (6bce03d) /
12704 // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
12705 // pins on the peer closed-set typed-enum axes.
12706 let all: &[RestartPolicy] = RestartPolicy::ALL;
12707 assert_eq!(
12708 all.len(),
12709 3,
12710 "RestartPolicy::ALL must enumerate every variant of the \
12711 three-arm closed set (Permanent, Temporary, Transient); \
12712 got {all:?}"
12713 );
12714 for (i, a) in all.iter().enumerate() {
12715 for (j, b) in all.iter().enumerate() {
12716 if i != j {
12717 assert_ne!(
12718 a, b,
12719 "RestartPolicy::ALL must carry every variant exactly \
12720 once — got duplicate {a:?} at indices {i} and {j}"
12721 );
12722 }
12723 }
12724 }
12725 for variant in [
12726 RestartPolicy::Permanent,
12727 RestartPolicy::Temporary,
12728 RestartPolicy::Transient,
12729 ] {
12730 assert!(
12731 all.contains(&variant),
12732 "RestartPolicy::ALL must contain {variant:?} — a future arm \
12733 addition that grows the enum but forgets to grow the ALL slice \
12734 silently truncates every downstream consumer's accept-set at \
12735 the pre-addition boundary"
12736 );
12737 }
12738 }
12739
12740 #[test]
12741 fn restart_policy_wire_names_covers_every_arm() {
12742 // Load-bearing pin on the substrate-canonical
12743 // [`RestartPolicy::WIRE_NAMES`] exhaustive accept-set roster on
12744 // the `PascalCase` wire byte-string axis: every variant of the
12745 // sibling [`RestartPolicy::ALL`] exhaustive-iteration surface
12746 // must project through [`RestartPolicy::as_str`] onto an entry
12747 // the [`RestartPolicy::WIRE_NAMES`] roster carries, and the
12748 // roster's length must byte-equal `RestartPolicy::ALL.len()` so
12749 // a silent skew between the [`RestartPolicy::as_str`] match's
12750 // arm-set and the roster's arm-set trips here at caixa-core
12751 // test time rather than at a downstream M4
12752 // `mesh.pleme.io/v1alpha1/Supervisor` CR admission-webhook
12753 // rejection body's wire-form `:restart` accepted-set
12754 // enumeration miss / a `feira supervisor --restart …` "did you
12755 // mean" hint drift / a future wasm-operator per-reconcile-step
12756 // diagnostic log line's accepted-wire-form enumeration miss.
12757 // A future arm addition (an OTP-`intrinsic` fourth arm the
12758 // theory
12759 // [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
12760 // might reach for once the three canonical OTP restart policies
12761 // stop covering the substrate's discovered load-shape) extends
12762 // [`RestartPolicy::ALL`] as a single edit and this pin sweeps
12763 // the new arm by iteration; the paired
12764 // [`RestartPolicy::WIRE_NAMES`] roster must grow in lockstep or
12765 // this assertion trips. Every entry is further pinned to open
12766 // with an ASCII uppercase byte so a silent collapse of the
12767 // wire-form axis with the peer kebab-case dispatcher-catalog
12768 // axis (an entry byte-identical to a sibling
12769 // [`RestartPolicy::discriminant`] kebab byte-string that would
12770 // let a wire-axis consumer accept the dispatcher-catalog
12771 // vocabulary) trips here rather than at a downstream K8s-CR
12772 // round-trip miss.
12773 //
12774 // Peer of the sibling
12775 // [`restart_strategy_wire_names_covers_every_arm`] (3033f45)
12776 // pin on the first M2 OTP-shape sibling-restart closed-set
12777 // typed enum, the sibling
12778 // [`crate::aplicacao::tests::placement_strategy_wire_names_covers_every_arm`]
12779 // (3e5b194) pin on the first M3 mesh-shape distribution-strategy
12780 // closed-set typed enum, the sibling
12781 // [`crate::kind::tests::caixa_kind_wire_names_covers_every_arm`]
12782 // (bd708bd) pin on the top-level typed-kind discriminator's
12783 // `PascalCase` wire byte-string axis, and the sibling
12784 // [`crate::upgrade::tests::upgrade_instruction_wire_forms_covers_every_arm`]
12785 // (cc42c0e) /
12786 // [`crate::upgrade::tests::upgrade_instruction_lisp_forms_covers_every_arm`]
12787 // (1898d77) pins on the OTP-appup discriminator's two-axis
12788 // roster split — the same closed-set exhaustive-roster coverage
12789 // discipline extended here onto the second and final M2
12790 // OTP-shape sibling-enum on the caixa surface, closing the
12791 // per-child restart-decision-policy axis paired with the peer
12792 // per-supervisor sibling-restart-strategy axis on the same M2
12793 // `:supervisor` slot.
12794 //
12795 // Fail-before-pass-after locally verified by mutating one arm
12796 // of the paired [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
12797 // const family (e.g. dropping the trailing `t` from
12798 // `"Permanent"` → `"Permanen"`) — the length pin still passes
12799 // but the `contains` check fires on the mutated arm; and by
12800 // shortening the roster to two entries — the length pin fires
12801 // first.
12802 assert_eq!(
12803 RestartPolicy::WIRE_NAMES.len(),
12804 RestartPolicy::ALL.len(),
12805 "RestartPolicy::WIRE_NAMES.len() must byte-equal \
12806 RestartPolicy::ALL.len() — a mismatch means the roster \
12807 and the enum's arm-set have drifted; downstream consumers \
12808 that fan through both will silently disagree on the \
12809 accepted arm-set"
12810 );
12811 for &variant in RestartPolicy::ALL {
12812 let wire = variant.as_str();
12813 assert!(
12814 RestartPolicy::WIRE_NAMES.contains(&wire),
12815 "RestartPolicy::{variant:?}.as_str() = {wire:?} must \
12816 be a member of RestartPolicy::WIRE_NAMES — the \
12817 emitter and the roster have drifted out of lockstep"
12818 );
12819 }
12820 for tag in RestartPolicy::WIRE_NAMES {
12821 let first = tag.chars().next().unwrap_or_else(|| {
12822 panic!(
12823 "RestartPolicy::WIRE_NAMES entry {tag:?} must be \
12824 a non-empty PascalCase byte-string"
12825 )
12826 });
12827 assert!(
12828 first.is_ascii_uppercase(),
12829 "RestartPolicy::WIRE_NAMES entry {tag:?} must open \
12830 with an ASCII uppercase byte (PascalCase wire form) — \
12831 a lowercase entry would collide the wire-form axis \
12832 with the peer kebab-case dispatcher-catalog axis \
12833 [`RestartPolicy::discriminant`] serves"
12834 );
12835 }
12836 }
12837
12838 #[test]
12839 fn restart_policy_from_wire_accepts_every_lifted_constant() {
12840 // Fail-before-pass-after pin on the forward accept-set of the
12841 // [`RestartPolicy::from_wire`] reverse projection: every
12842 // canonical [`crate::render::SUPERVISOR_CHILD_RESTART_*`]
12843 // constant the [`RestartPolicy::as_str`] emitter walks parses
12844 // back to its paired variant. Any future arm addition that
12845 // grows the emitter's `as_str` match but forgets to grow the
12846 // parser's `from_wire` match silently splits the two halves of
12847 // the round-trip — the wire byte-string one non-serde consumer
12848 // parses from the one the emitter wrote — with the failure
12849 // surfacing at the operator's reconcile posture (a `:temporary`
12850 // `oneShot` child restarted on clean exit, a `:transient` child
12851 // restarted after clean completion) far from the rebrand
12852 // commit. Pinning the three-arm accept-set here catches the
12853 // drift at caixa-core build time.
12854 //
12855 // Peer of the sibling [`RestartStrategy::from_wire`] (4eec29c)
12856 // + [`crate::CaixaKind::from_wire`] (2aa6d23)
12857 // + [`crate::aplicacao::PlacementStrategy::from_wire`] (18c7342)
12858 // accept-set pins on the peer closed-set typed-enum `str → Self`
12859 // axes.
12860 for (wire, expected) in [
12861 (
12862 crate::render::SUPERVISOR_CHILD_RESTART_PERMANENT,
12863 RestartPolicy::Permanent,
12864 ),
12865 (
12866 crate::render::SUPERVISOR_CHILD_RESTART_TEMPORARY,
12867 RestartPolicy::Temporary,
12868 ),
12869 (
12870 crate::render::SUPERVISOR_CHILD_RESTART_TRANSIENT,
12871 RestartPolicy::Transient,
12872 ),
12873 ] {
12874 let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
12875 panic!(
12876 "RestartPolicy::from_wire({wire:?}) must accept every \
12877 SUPERVISOR_CHILD_RESTART_* constant — got None for the \
12878 lifted canonical byte-string that RestartPolicy::{expected:?} \
12879 serializes as under SUPERVISOR_CHILD_KEY_RESTART"
12880 )
12881 });
12882 assert_eq!(
12883 parsed, expected,
12884 "RestartPolicy::from_wire({wire:?}) must return \
12885 RestartPolicy::{expected:?}; got RestartPolicy::{parsed:?}"
12886 );
12887 }
12888 }
12889
12890 #[test]
12891 fn restart_policy_from_wire_round_trips_through_as_str() {
12892 // Fail-before-pass-after pin on the closed round-trip between
12893 // the forward [`RestartPolicy::as_str`] emitter and the
12894 // reverse [`RestartPolicy::from_wire`] parser: for every
12895 // variant in [`RestartPolicy::ALL`], parsing the emitter's
12896 // output must return exactly the same variant. Any per-arm
12897 // divergence — a future arm added to `as_str` but not
12898 // `from_wire`, an accidental copy-paste flip in one but not
12899 // the other — silently splits the emit and parse halves and
12900 // the failure surfaces at consumer parse time far from the
12901 // drift site. The `ALL`-iterating shape means a future arm
12902 // addition picks up the coverage by construction.
12903 //
12904 // Peer of the sibling
12905 // [`restart_strategy_from_wire_round_trips_through_as_str`]
12906 // (4eec29c) round-trip pin on
12907 // [`RestartStrategy::from_wire`] and the M3
12908 // [`crate::aplicacao::tests::placement_strategy_from_wire_round_trips_through_as_str`]
12909 // (18c7342) round-trip pin on
12910 // [`crate::aplicacao::PlacementStrategy::from_wire`].
12911 for &variant in RestartPolicy::ALL {
12912 let wire = variant.as_str();
12913 let parsed = RestartPolicy::from_wire(wire).unwrap_or_else(|| {
12914 panic!(
12915 "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
12916 must be Some({variant:?}) — the two halves of the round-trip \
12917 dispatch on the same lifted SUPERVISOR_CHILD_RESTART_* consts; \
12918 got None on wire byte-string {wire:?}"
12919 )
12920 });
12921 assert_eq!(
12922 parsed, variant,
12923 "RestartPolicy::from_wire(RestartPolicy::{variant:?}.as_str()) \
12924 must round-trip to the same variant; got {parsed:?}"
12925 );
12926 }
12927 }
12928
12929 #[test]
12930 fn restart_policy_from_wire_rejects_unknown_byte_strings() {
12931 // Fail-before-pass-after pin on the closed-set refusal
12932 // discipline of [`RestartPolicy::from_wire`]: every
12933 // byte-string outside the three-arm accept-set returns `None`
12934 // rather than silently collapsing onto the [`Default`]
12935 // (`Permanent`) arm or an arbitrary neighbor. The refusal set
12936 // exercised here sweeps the load-bearing drift shapes: the
12937 // empty string (a stripped serde-attribute drift), all-
12938 // whitespace strings (the canonical text-editor accidental
12939 // padding shape), the kebab-case dispatcher-catalog identities
12940 // (`"permanent"` / `"temporary"` / `"transient"` — the
12941 // [`gen_platform::FromStrKind`]-derived [`std::str::FromStr`]
12942 // accept-set, which parses the *other* axis of this enum's
12943 // two-axis split and must not leak into the `from_wire`
12944 // PascalCase-wire accept-set — a lowercase leak here would
12945 // silently accept the operator's kebab-case
12946 // dispatcher-catalog probe under the wire-axis parser and mis-
12947 // route a `:permanent` intent), the padded canonical scalar
12948 // (`" Permanent "`), the trailing-newline shapes
12949 // (`"Permanent\n"`), the uppercase-single-word forms
12950 // (`"PERMANENT"`), and neighboring-but-unknown arms
12951 // (`"Restart"` — the canonical typo direction toward the
12952 // sibling [`RestartStrategy`] enum's own wire-arm namespace).
12953 //
12954 // Peer of the sibling
12955 // [`restart_strategy_from_wire_rejects_unknown_byte_strings`]
12956 // (4eec29c) +
12957 // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
12958 // (2aa6d23) +
12959 // [`crate::aplicacao::tests::placement_strategy_from_wire_rejects_unknown_byte_strings`]
12960 // (18c7342) refusal pins on the peer closed-set typed-enum
12961 // axes.
12962 for bad in [
12963 "",
12964 " ",
12965 "\n",
12966 "\t",
12967 "permanent",
12968 "temporary",
12969 "transient",
12970 "PERMANENT",
12971 "TEMPORARY",
12972 "TRANSIENT",
12973 "Permanents",
12974 "Permanent ",
12975 " Permanent",
12976 " Transient ",
12977 "Permanent\n",
12978 "perma",
12979 "Trans",
12980 "OneForOne",
12981 "Restart",
12982 "?",
12983 ] {
12984 assert!(
12985 RestartPolicy::from_wire(bad).is_none(),
12986 "RestartPolicy::from_wire({bad:?}) must return None — the \
12987 parser's accept-set is exactly the three RestartPolicy::as_str \
12988 outputs (Permanent, Temporary, Transient), and this \
12989 byte-string is outside that closed set"
12990 );
12991 }
12992 }
12993
12994 #[test]
12995 fn restart_policy_from_wire_matches_serialize_derive_wire_byte_string() {
12996 // Fail-before-pass-after pin on the fourth path of the four-path
12997 // convergence: `from_wire` (the reverse projection) inverts the
12998 // `Serialize` derive's wire byte-string on every variant.
12999 // Together with the pre-existing three-path convergence
13000 // (`Display` + `as_str` + `Serialize` all resolve to the same
13001 // lifted [`crate::render::SUPERVISOR_CHILD_RESTART_*`] const,
13002 // pinned by
13003 // [`restart_policy_display_matches_serialized_wire_byte_string`])
13004 // this closes the round-trip: the wire byte-string the
13005 // `Serialize` derive emits parses back to the same variant
13006 // through `from_wire`, so any future serde-attribute or variant-
13007 // rename drift on the emit half now surfaces as a matched drift
13008 // on the parse half at caixa-core build time — the two halves
13009 // migrate as a unit through the lifted consts on any future
13010 // rename, and the round-trip cannot silently split.
13011 //
13012 // Peer of the sibling
13013 // [`restart_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
13014 // (4eec29c) wire-format pin on
13015 // [`RestartStrategy::from_wire`] and the M3
13016 // [`crate::aplicacao::tests::placement_strategy_from_wire_matches_serialize_derive_wire_byte_string`]
13017 // (18c7342) wire-format pin on
13018 // [`crate::aplicacao::PlacementStrategy::from_wire`].
13019 for &variant in RestartPolicy::ALL {
13020 let wire = serde_json::to_string(&variant).unwrap();
13021 let unquoted = wire
13022 .strip_prefix('"')
13023 .and_then(|s| s.strip_suffix('"'))
13024 .expect("serialized RestartPolicy is a JSON string");
13025 let parsed = RestartPolicy::from_wire(unquoted).unwrap_or_else(|| {
13026 panic!(
13027 "RestartPolicy::from_wire({unquoted:?}) must accept the \
13028 Serialize derive's wire byte-string for \
13029 RestartPolicy::{variant:?} — the four-path convergence \
13030 (Display + as_str + Serialize + from_wire) resolves through \
13031 the same lifted SUPERVISOR_CHILD_RESTART_* const; got None"
13032 )
13033 });
13034 assert_eq!(
13035 parsed, variant,
13036 "RestartPolicy::from_wire of the Serialize derive's wire \
13037 byte-string for RestartPolicy::{variant:?} must round-trip \
13038 to the same variant; got {parsed:?}"
13039 );
13040 }
13041 }
13042
13043 // ── drift-detection: ChildSpec::nome accessor pins ────────────────────
13044 //
13045 // The M2 supervisor-tree sibling of the M3 `Membro::nome` (4a32abf) pin
13046 // pair (`membro_nome_returns_caixa_byte_equal_across_permutations` +
13047 // `membro_nome_borrows_from_caixa_storage`) — extended here to the M2
13048 // per-`:children` child-caixa `:nome` axis, sibling to the first M2
13049 // slot scalar accessor `UpgradeFromEntry::prior_versao` (75d27a8) on
13050 // the peer per-`:upgrade-from :from` axis. The three pins jointly
13051 // brace the accessor against every future silent detour that would
13052 // desynchronize it from the raw `.caixa` field access every consumer
13053 // previously open-coded.
13054
13055 #[test]
13056 fn child_spec_nome_returns_caixa_byte_equal_across_permutations() {
13057 // The canonical per-`:children` child-caixa `:nome`-scalar pin:
13058 // [`ChildSpec::nome`] must return the `:children :caixa` field
13059 // byte-for-byte across every DNS-1123-label value the upstream
13060 // [`crate::render::require_valid_dns_1123_label`] gate at
13061 // `SupervisorSpec::validate` admits. Peer of the sibling
13062 // `membro_nome_returns_caixa_byte_equal_across_permutations`
13063 // (4a32abf) pin on the M3 per-`:membros` axis — same "the
13064 // substrate-primitive accessor must byte-equal the raw field
13065 // access verbatim across every author-declared value" discipline
13066 // extended to the M2 supervisor-tree per-`:children` arm. Pins
13067 // against a future silent detour that re-normalized the child
13068 // identity (an accidental `.to_lowercase()` — every `:children
13069 // :caixa` is validated as a DNS-1123 label upstream, so any
13070 // re-normalization is redundant + a drift surface between the
13071 // validator and the accessor), a namespace-prefix rewrite (an
13072 // accidental `format!("{namespace}/{caixa}")` per-CR
13073 // fully-qualified rewrite that didn't land on the peer axes), or
13074 // a per-cluster alias stamp the future wasm-operator's
13075 // hierarchical reconciliation scheduler authors on one consumer
13076 // without the others. Five values sweep the accept-set the
13077 // DNS-1123 gate upstream admits (short single-word / dashed /
13078 // v-suffixed / mixed-digit child names).
13079 for name in [
13080 "worker",
13081 "cache-server",
13082 "scratch-job",
13083 "orders-v2",
13084 "session-8080",
13085 ] {
13086 let c = ChildSpec {
13087 caixa: name.into(),
13088 versao: "^0.1".into(),
13089 restart: RestartPolicy::Permanent,
13090 };
13091 assert_eq!(
13092 c.nome(),
13093 name,
13094 "ChildSpec::nome must return :children :caixa verbatim \
13095 (got {:?}, expected {name:?})",
13096 c.nome(),
13097 );
13098 assert_eq!(
13099 c.nome(),
13100 c.caixa.as_str(),
13101 "ChildSpec::nome must byte-equal the .caixa field access",
13102 );
13103 }
13104 }
13105
13106 #[test]
13107 fn child_spec_nome_borrows_from_caixa_storage() {
13108 // The borrow-not-copy pin: [`ChildSpec::nome`] must return a
13109 // `&str` slice that borrows from the typed slot's own [`String`]
13110 // storage — same-address invariant with `c.caixa.as_str()`. Pins
13111 // against a future silent detour that allocated a fresh `String`
13112 // (`self.caixa.clone()` in the body would type-check but silently
13113 // drop the borrow, and every downstream consumer that assumed
13114 // the returned slice outlives `&self` would break on a stale-
13115 // reference use-after-free — the [`crate::render::insert_first_seen`]
13116 // dedup key at [`SupervisorSpec::validate`], the
13117 // [`validate_no_self_supervision`] equality check against the
13118 // parent's `:nome` string slice, the DNS-1123 gate's `&str`
13119 // borrow — each would silently misbehave if this accessor
13120 // produced a detached copy). Peer of the sibling
13121 // `membro_nome_borrows_from_caixa_storage` (4a32abf) pin on the
13122 // M3 per-`:membros` axis and the
13123 // `prior_versao_borrows_from_from_storage` (75d27a8) pin on the
13124 // first M2 slot scalar accessor.
13125 let c = ChildSpec {
13126 caixa: "worker".into(),
13127 versao: "^0.1".into(),
13128 restart: RestartPolicy::Permanent,
13129 };
13130 let name = c.nome();
13131 let caixa_slice = c.caixa.as_str();
13132 assert_eq!(
13133 name.as_ptr(),
13134 caixa_slice.as_ptr(),
13135 "ChildSpec::nome must borrow from the .caixa String's backing \
13136 storage — a fresh allocation here means the accessor no \
13137 longer names the substrate-primitive typed dispatch and \
13138 every downstream consumer would silently carry a detached \
13139 copy",
13140 );
13141 assert_eq!(
13142 name.len(),
13143 caixa_slice.len(),
13144 "ChildSpec::nome and .caixa.as_str() must byte-equal in length \
13145 as well as in address",
13146 );
13147 }
13148
13149 #[test]
13150 fn validate_gates_child_nome_through_lifted_accessor() {
13151 // Bilateral coherence pin: every `:children :caixa` that
13152 // [`SupervisorSpec::validate`] accepts is one
13153 // [`crate::render::require_valid_dns_1123_label`] accepts on the
13154 // accessor-projected value, and vice versa on the reject side.
13155 // This closes the "the validator reads through the accessor"
13156 // contract structurally — a future silent detour that made the
13157 // accessor return a different byte-string than the validator
13158 // gates against would surface here as a coverage mismatch, not
13159 // as an apply-time DNS-1123 rejection at
13160 // `metadata.name: Invalid value` far from the caixa.lisp source.
13161 // Peer of the M2 sibling
13162 // `validate_parses_prior_versao_through_lifted_accessor`
13163 // (75d27a8) on the per-`:upgrade-from :from` axis and the M3
13164 // `validate_membros` peer discipline.
13165 //
13166 // Accept-set sweep: five DNS-1123-label values the upstream gate
13167 // admits.
13168 for ok_name in ["a", "worker", "cache-server", "orders-v2", "svc-8080"] {
13169 let s = SupervisorSpec {
13170 children: vec![ChildSpec {
13171 caixa: ok_name.into(),
13172 versao: "^0.1".into(),
13173 restart: RestartPolicy::Permanent,
13174 }],
13175 ..SupervisorSpec::default()
13176 };
13177 s.validate().unwrap_or_else(|e| {
13178 panic!(
13179 "SupervisorSpec::validate must accept :children :caixa {ok_name:?} \
13180 (upstream DNS-1123 gate accepts it): got {e:?}",
13181 );
13182 });
13183 let c = ChildSpec {
13184 caixa: ok_name.into(),
13185 versao: "^0.1".into(),
13186 restart: RestartPolicy::Permanent,
13187 };
13188 crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| ())
13189 .unwrap_or_else(|()| {
13190 panic!(
13191 "require_valid_dns_1123_label must accept the accessor-projected \
13192 :children :caixa {ok_name:?}",
13193 );
13194 });
13195 }
13196 // Reject-set sweep: five DNS-1123-label-violating shapes the
13197 // upstream gate refuses (empty / uppercase / underscore / dot /
13198 // leading-hyphen). Every rejection at the validator must
13199 // correspond to a rejection when the accessor's projected value
13200 // is fed back through the shared gate.
13201 for bad_name in ["", "Worker", "my_worker", "team.worker", "-worker"] {
13202 let s = SupervisorSpec {
13203 children: vec![ChildSpec {
13204 caixa: bad_name.into(),
13205 versao: "^0.1".into(),
13206 restart: RestartPolicy::Permanent,
13207 }],
13208 ..SupervisorSpec::default()
13209 };
13210 let err = s.validate().unwrap_err();
13211 assert!(
13212 matches!(
13213 err,
13214 SupervisorError::EmptyChildName | SupervisorError::ChildCaixaInvalid { .. }
13215 ),
13216 "SupervisorSpec::validate must reject :children :caixa {bad_name:?} \
13217 via the DNS-1123 gate: got {err:?}",
13218 );
13219 let c = ChildSpec {
13220 caixa: bad_name.into(),
13221 versao: "^0.1".into(),
13222 restart: RestartPolicy::Permanent,
13223 };
13224 assert!(
13225 crate::render::require_valid_dns_1123_label(c.nome(), || (), |_reason| (),)
13226 .is_err(),
13227 "require_valid_dns_1123_label must reject the accessor-projected \
13228 :children :caixa {bad_name:?}",
13229 );
13230 }
13231 }
13232
13233 // ── drift-detection: ChildSpec::versao_requirement accessor pins ──────
13234 //
13235 // Sibling of the peer per-`:membros` `membro_versao_requirement_*`
13236 // (a40b0e3) pin pair on the M3 mesh-slot surface — extended here to the
13237 // M2 supervisor-tree per-`:children` child-`:versao` axis, sibling to
13238 // the just-landed [`ChildSpec::nome`] (57c61d0) child-`:nome` pin
13239 // trio on the peer per-`:children` `String`-carry axis. The three pins
13240 // jointly brace the accessor against every future silent detour that
13241 // would desynchronize it from the raw `.versao` field access the
13242 // requirement gate + error carrier previously open-coded.
13243 //
13244 // Closes the last unlifted per-`:children` `String`-carry axis: the
13245 // pair (`nome`, `versao_requirement`) now jointly projects the
13246 // (`.caixa`, `.versao`) field pair every OTP-shape supervisor-tree
13247 // consumer that fans on per-child identity + version pin reads,
13248 // matching the peer M3 (`Membro::nome`, `Membro::versao_requirement`)
13249 // pair discipline verbatim.
13250 #[test]
13251 fn child_spec_versao_requirement_returns_versao_byte_equal_across_permutations() {
13252 // The canonical per-`:children` child-`:versao`-scalar pin:
13253 // [`ChildSpec::versao_requirement`] must return the `:children
13254 // :versao` field byte-for-byte across every Cargo-shaped semver
13255 // requirement value the upstream
13256 // [`crate::render::require_valid_versao_requirement`] gate admits.
13257 // Peer of the sibling
13258 // `membro_versao_requirement_returns_versao_byte_equal_across_permutations`
13259 // (a40b0e3) pin on the M3 per-`:membros` axis — same "the
13260 // substrate-primitive accessor must byte-equal the raw field
13261 // access verbatim across every author-declared value" discipline
13262 // extended to the M2 supervisor-tree per-`:children` arm. Pins
13263 // against a future silent detour that re-canonicalized the
13264 // requirement (an accidental `.to_string()` via
13265 // [`crate::version::parse_requirement`] → [`std::fmt::Display`]
13266 // round-trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and
13267 // silently drifted the error carrier's quoted requirement away
13268 // from the source `caixa.lisp`, an accidental whitespace trim on
13269 // `"^ 0.1"` that no consumer ever produced from the field-access
13270 // side, an accidental per-cluster lacre-projected concrete-version
13271 // rewrite that didn't land on the peer requirement-gate call).
13272 // Five values sweep the accept-set the shared
13273 // [`crate::render::require_valid_versao_requirement`] gate admits
13274 // (caret / tilde / exact / wildcard / bare-major).
13275 for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
13276 let c = ChildSpec {
13277 caixa: "worker".into(),
13278 versao: req.into(),
13279 restart: RestartPolicy::Permanent,
13280 };
13281 assert_eq!(
13282 c.versao_requirement(),
13283 req,
13284 "ChildSpec::versao_requirement must return :children :versao \
13285 verbatim (got {:?}, expected {req:?})",
13286 c.versao_requirement(),
13287 );
13288 assert_eq!(
13289 c.versao_requirement(),
13290 c.versao.as_str(),
13291 "ChildSpec::versao_requirement must byte-equal the .versao \
13292 field access",
13293 );
13294 }
13295 }
13296
13297 #[test]
13298 fn child_spec_versao_requirement_borrows_from_versao_storage() {
13299 // The borrow-not-copy pin: [`ChildSpec::versao_requirement`] must
13300 // return a `&str` slice that borrows from the typed slot's own
13301 // [`String`] storage — same-address invariant with
13302 // `c.versao.as_str()`. Pins against a future silent detour that
13303 // allocated a fresh `String` (`self.versao.clone()` in the body
13304 // would type-check but silently drop the borrow, and every
13305 // downstream consumer that assumed the returned slice outlives
13306 // `&self` — the [`crate::render::require_valid_versao_requirement`]
13307 // gate's `&str` borrow, the [`SupervisorError::ChildVersaoInvalid`]
13308 // `.to_string()` carrier's byte-length assumption — would silently
13309 // misbehave if this accessor produced a detached copy). Peer of
13310 // the sibling `child_spec_nome_borrows_from_caixa_storage`
13311 // (57c61d0) pin on the per-`:children` `:nome` axis and the M3
13312 // `membro_versao_requirement_borrows_from_versao_storage` (a40b0e3)
13313 // pin on the peer per-`:membros` `:versao` axis.
13314 let c = ChildSpec {
13315 caixa: "worker".into(),
13316 versao: "^0.1".into(),
13317 restart: RestartPolicy::Permanent,
13318 };
13319 let req = c.versao_requirement();
13320 let versao_slice = c.versao.as_str();
13321 assert_eq!(
13322 req.as_ptr(),
13323 versao_slice.as_ptr(),
13324 "ChildSpec::versao_requirement must borrow from the .versao \
13325 String's backing storage — a fresh allocation here means the \
13326 accessor no longer names the substrate-primitive typed \
13327 dispatch and every downstream consumer would silently carry \
13328 a detached copy",
13329 );
13330 assert_eq!(
13331 req.len(),
13332 versao_slice.len(),
13333 "ChildSpec::versao_requirement and .versao.as_str() must \
13334 byte-equal in length as well as in address",
13335 );
13336 }
13337
13338 #[test]
13339 fn validate_gates_child_versao_through_lifted_accessor() {
13340 // Bilateral coherence pin: every `:children :versao` that
13341 // [`SupervisorSpec::validate`] accepts is one
13342 // [`crate::render::require_valid_versao_requirement`] accepts on
13343 // the accessor-projected value, and vice versa on the reject side.
13344 // This closes the "the validator reads through the accessor"
13345 // contract structurally — a future silent detour that made the
13346 // accessor return a different byte-string than the validator gates
13347 // against would surface here as a coverage mismatch, not as a
13348 // resolver-time semver-parse rejection at lacre-closure time far
13349 // from the caixa.lisp source. Peer of the sibling
13350 // `validate_gates_child_nome_through_lifted_accessor` (57c61d0) on
13351 // the per-`:children :caixa` axis and the M2
13352 // `validate_parses_prior_versao_through_lifted_accessor` (75d27a8)
13353 // on the peer per-`:upgrade-from :from` axis.
13354 //
13355 // Accept-set sweep: five Cargo-shaped semver requirement values
13356 // the upstream gate admits (caret / tilde / exact / wildcard /
13357 // bare-major).
13358 for ok_req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
13359 let s = SupervisorSpec {
13360 children: vec![ChildSpec {
13361 caixa: "worker".into(),
13362 versao: ok_req.into(),
13363 restart: RestartPolicy::Permanent,
13364 }],
13365 ..SupervisorSpec::default()
13366 };
13367 s.validate().unwrap_or_else(|e| {
13368 panic!(
13369 "SupervisorSpec::validate must accept :children :versao {ok_req:?} \
13370 (upstream versao-requirement gate accepts it): got {e:?}",
13371 );
13372 });
13373 let c = ChildSpec {
13374 caixa: "worker".into(),
13375 versao: ok_req.into(),
13376 restart: RestartPolicy::Permanent,
13377 };
13378 crate::render::require_valid_versao_requirement(
13379 c.versao_requirement(),
13380 || (),
13381 |_reason| (),
13382 )
13383 .unwrap_or_else(|()| {
13384 panic!(
13385 "require_valid_versao_requirement must accept the accessor-projected \
13386 :children :versao {ok_req:?}",
13387 );
13388 });
13389 }
13390 // Reject-set sweep: five requirement-violating shapes the upstream
13391 // gate refuses. The empty string closes the empty-first arm of the
13392 // shared [`crate::render::require_valid_versao_requirement`]
13393 // cascade; the four non-empty arms exercise distinct semver-parse
13394 // failure modes the M3 peer per-`:membros` reject-set already pins
13395 // (`rejects_invalid_membro_versao_requirement` on `^bad-version`,
13396 // `rejects_membro_versao_with_double_caret_typo` on `^^0.1`,
13397 // `rejects_membro_versao_with_v_prefixed_tag` on `v0.1`) — the
13398 // shared parser routing means the same reject-set must fail
13399 // identically at the M2 supervisor-tree per-`:children` accessor
13400 // arm here. Every rejection at the validator must correspond to a
13401 // rejection when the accessor's projected value is fed back
13402 // through the shared gate.
13403 //
13404 // (Bare partial magnitudes like `"0.1"` and bare identifiers like
13405 // `"not-a-semver"` are intentionally *not* in the reject-set: the
13406 // semver crate accepts `"0.1"` as an implicit `^0.1` requirement,
13407 // and the identifier-tail arm's grammar admits some non-canonical
13408 // shapes — matching what the M3 peer test suite already documents
13409 // as the shared parser's accept-set edges.)
13410 for bad_req in ["", "v0.1.0", "^bad-version", "^^0.1", "v0.1"] {
13411 let s = SupervisorSpec {
13412 children: vec![ChildSpec {
13413 caixa: "worker".into(),
13414 versao: bad_req.into(),
13415 restart: RestartPolicy::Permanent,
13416 }],
13417 ..SupervisorSpec::default()
13418 };
13419 let err = s.validate().unwrap_err();
13420 assert!(
13421 matches!(
13422 err,
13423 SupervisorError::EmptyChildVersion { .. }
13424 | SupervisorError::ChildVersaoInvalid { .. }
13425 ),
13426 "SupervisorSpec::validate must reject :children :versao {bad_req:?} \
13427 via the versao-requirement gate: got {err:?}",
13428 );
13429 let c = ChildSpec {
13430 caixa: "worker".into(),
13431 versao: bad_req.into(),
13432 restart: RestartPolicy::Permanent,
13433 };
13434 assert!(
13435 crate::render::require_valid_versao_requirement(
13436 c.versao_requirement(),
13437 || (),
13438 |_reason| (),
13439 )
13440 .is_err(),
13441 "require_valid_versao_requirement must reject the accessor-projected \
13442 :children :versao {bad_req:?}",
13443 );
13444 }
13445 }
13446
13447 // ── per-`:children` `:restart` typed-accessor coherence pins ──────────
13448 //
13449 // The [`ChildSpec::restart`] accessor lift closes the last unlifted
13450 // per-`:children` axis (the pair `nome()` + `versao_requirement()`
13451 // already project the `String`-carry `(caixa, versao)` fields; the
13452 // `Copy`-composite-enum `restart` field is the third and final axis).
13453 // Peer of the sibling per-`:supervisor` [`SupervisorSpec::estrategia`]
13454 // (eafb619) `Copy`-return [`RestartStrategy`] sibling-restart-strategy
13455 // scalar accessor and the M3 mesh-slot [`crate::Placement::estrategia`]
13456 // (921fe1b) `Copy`-return [`crate::PlacementStrategy`] distribution-
13457 // strategy scalar accessor — same "one typed dispatch on the substrate
13458 // primitive, `Copy`-projected closed-set enum-arm discriminator" shape
13459 // extended onto the M2 supervisor-slot per-`:children` restart-decision
13460 // axis. The pin below covers the accessor's byte-equal projection
13461 // against the raw field access across every variant in the closed
13462 // accept-set (`Permanent`, `Transient`, `Temporary`).
13463
13464 #[test]
13465 fn child_spec_restart_returns_restart_verbatim_across_permutations() {
13466 // The canonical per-`:children` restart-decision-policy-scalar
13467 // pin: [`ChildSpec::restart`] must return the `:children :restart`
13468 // field verbatim as a [`RestartPolicy`], `Copy`-projected from the
13469 // typed slot's own [`RestartPolicy`] storage across every variant
13470 // in the closed accept-set (`Permanent`, `Transient`, `Temporary`).
13471 // Pins against a future silent detour that re-derived the policy
13472 // from a peer axis (an accidental fallback to
13473 // `if is_supervisor_child { Permanent } else { Temporary }` that
13474 // collapsed the child's kind axis into the restart discriminator),
13475 // a variant remap the operator authors on one consumer without the
13476 // other, or a stale-derive detour that substituted
13477 // [`RestartPolicy::default`] when the field held any explicit
13478 // variant (which would silently collapse the distinction between
13479 // "author explicitly declared `:restart Permanent`" and "author
13480 // omitted the slot and inherited the default" the future
13481 // per-cluster restart-decision override slot depends on).
13482 //
13483 // Peer of the sibling per-`:supervisor`
13484 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
13485 // (eafb619) pin on the M2 supervisor-slot sibling-restart-strategy
13486 // axis and the M3
13487 // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
13488 // (921fe1b) pin on the per-`:placement` distribution-strategy axis
13489 // — same "the substrate-primitive accessor must byte-equal the raw
13490 // field access verbatim across every author-declared value"
13491 // discipline extended onto the M2 supervisor-slot per-`:children`
13492 // restart-decision-policy axis, closing the last unlifted axis on
13493 // the per-`:children` [`ChildSpec`] type.
13494 for restart in [
13495 RestartPolicy::Permanent,
13496 RestartPolicy::Transient,
13497 RestartPolicy::Temporary,
13498 ] {
13499 let c = ChildSpec {
13500 caixa: "worker".into(),
13501 versao: "^0.1".into(),
13502 restart,
13503 };
13504 assert_eq!(
13505 c.restart(),
13506 restart,
13507 "ChildSpec::restart must return :children :restart \
13508 verbatim (got {:?}, expected {restart:?})",
13509 c.restart(),
13510 );
13511 assert_eq!(
13512 c.restart(),
13513 c.restart,
13514 "ChildSpec::restart accessor and .restart field access \
13515 must byte-equal — the accessor is the substrate-primitive \
13516 typed dispatch every downstream per-child restart-\
13517 decision consumer must route through",
13518 );
13519 }
13520 }
13521
13522 // ── per-`:supervisor` `:estrategia` typed-accessor coherence pins ─────
13523 //
13524 // The [`SupervisorSpec::estrategia`] accessor lift extends the peer M3
13525 // [`crate::Placement::estrategia`] (921fe1b) `Copy`-return
13526 // distribution-strategy accessor discipline onto the M2 supervisor-slot
13527 // per-`:supervisor` sibling-restart-strategy `Copy`-composite-enum
13528 // scalar axis. The two pins below cover (1) the accessor's byte-equal
13529 // projection against the raw field access across every variant in the
13530 // closed accept-set, and (2) the two-consumer coherence between the
13531 // [`SupervisorSpec::validate`] partition-dispatch `match` arm and the
13532 // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`] error
13533 // carrier's `estrategia:` field — peer of the sibling M3
13534 // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
13535 // / `validate_placement_reads_through_lifted_estrategia_accessor` pin
13536 // pair on the per-`:placement` distribution-strategy axis.
13537
13538 #[test]
13539 fn supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations() {
13540 // The canonical per-`:supervisor` sibling-restart-strategy-scalar
13541 // pin: [`SupervisorSpec::estrategia`] must return the
13542 // `:supervisor :estrategia` field verbatim as a
13543 // [`RestartStrategy`], `Copy`-projected from the typed slot's own
13544 // [`RestartStrategy`] storage across every variant in the closed
13545 // accept-set (`OneForOne`, `OneForAll`, `RestForOne`,
13546 // `SimpleOneForOne`). Pins against a future silent detour that
13547 // re-derived the strategy from a peer axis (an accidental
13548 // fallback to `if children.is_empty() { SimpleOneForOne } else {
13549 // OneForOne }` collapse that read the children-count axis into
13550 // the strategy discriminator), a variant remap the operator
13551 // authors on one consumer without the other, or a stale-derive
13552 // detour that substituted [`RestartStrategy::default`] when the
13553 // field held any explicit variant (which would silently collapse
13554 // the distinction between "author explicitly declared
13555 // `:estrategia OneForOne`" and "author omitted the slot and
13556 // inherited the default" the future per-cluster strategy override
13557 // slot depends on). Peer of the sibling M3
13558 // `placement_estrategia_returns_estrategia_verbatim_across_permutations`
13559 // (921fe1b) pin on the M3 mesh-slot `Copy`-composite-enum scalar
13560 // axis — same "the substrate-primitive accessor must byte-equal
13561 // the raw field access verbatim across every author-declared
13562 // value" discipline extended onto the M2 supervisor-slot
13563 // per-`:supervisor` sibling-restart-strategy axis.
13564 for &estrategia in RestartStrategy::ALL {
13565 // `SimpleOneForOne` requires `children.is_empty()`; the peer
13566 // three strategies require a non-empty static children list.
13567 // Build each shape coherently so the pin's fixture would
13568 // itself pass [`SupervisorSpec::validate`] once fed through
13569 // the sibling coherence pin below — the byte-equal projection
13570 // asserted here is a strictly weaker property (a `Copy` field
13571 // read) that does not depend on `validate` running, but
13572 // keeping the fixture validate-clean means a future extension
13573 // of the pin to exercise `validate` end-to-end does not have
13574 // to re-author the children shape.
13575 //
13576 // Route the `SimpleOneForOne ↔ non-SimpleOneForOne` fixture-
13577 // shape partition through the [`gen_platform::IsVariant`]
13578 // derive-generated
13579 // [`RestartStrategy::is_simple_one_for_one`] predicate rather
13580 // than the raw `matches!(estrategia, RestartStrategy::
13581 // SimpleOneForOne)` open-coded pattern-match — same closed-
13582 // set-typed-enum arm-discriminator dispatch discipline the
13583 // sibling [`crate::upgrade::UpgradeInstruction::is_restart`]
13584 // convergence (915a934) extended onto its two paired positive
13585 // / negated `matches!` sites and the peer
13586 // [`crate::aplicacao::PlacementStrategy`] `IsVariant`-derived
13587 // predicate convergence (766ec63) extended onto the M3 mesh-
13588 // slot per-`:placement` distribution-strategy discriminator
13589 // axis. See the sibling `round_trip_all_strategies` and the
13590 // peer `manifest::tests::
13591 // caixa_estrategia_and_supervisor_view_reads_through_lifted_estrategia_accessor`
13592 // fixture for the two peer sites the same lift closes on.
13593 let children = if estrategia.is_simple_one_for_one() {
13594 Vec::new()
13595 } else {
13596 vec![ChildSpec {
13597 caixa: "worker".into(),
13598 versao: "^0.1".into(),
13599 restart: RestartPolicy::Permanent,
13600 }]
13601 };
13602 let s = SupervisorSpec {
13603 estrategia,
13604 children,
13605 ..SupervisorSpec::default()
13606 };
13607 assert_eq!(
13608 s.estrategia(),
13609 estrategia,
13610 "SupervisorSpec::estrategia must return :supervisor :estrategia \
13611 verbatim (got {:?}, expected {estrategia:?})",
13612 s.estrategia(),
13613 );
13614 assert_eq!(
13615 s.estrategia(),
13616 s.estrategia,
13617 "SupervisorSpec::estrategia accessor and .estrategia field \
13618 access must byte-equal — the accessor is the substrate-\
13619 primitive typed dispatch every downstream sibling-restart-\
13620 strategy consumer must route through",
13621 );
13622 }
13623 }
13624
13625 #[test]
13626 fn validate_reads_through_lifted_estrategia_accessor() {
13627 // Two-consumer coherence pin: the [`SupervisorSpec::validate`]
13628 // `SimpleOneForOne ↔ non-SimpleOneForOne` `match` partition
13629 // dispatch (which reads through [`SupervisorSpec::estrategia`]
13630 // to fan across the strategy-arm shape-gate cascades) and the
13631 // non-`SimpleOneForOne`-arm [`SupervisorError::NoChildren`]
13632 // error carrier's `estrategia:` field (which reads through
13633 // [`SupervisorSpec::estrategia`] to name the strategy the empty
13634 // `:children` list was declared against) must both key off the
13635 // lifted accessor, so any future rebrand on the typed slot's
13636 // reader shape lands at exactly one place. Pins the two-site
13637 // coherence by exercising the `NoChildren` error surface end-to-
13638 // end across every non-`SimpleOneForOne` variant and asserting
13639 // the surfaced `estrategia:` field byte-equals the accessor's
13640 // return. Peer of the sibling M3
13641 // `validate_placement_reads_through_lifted_estrategia_accessor`
13642 // (921fe1b) three-consumer coherence pin on the per-`:placement`
13643 // distribution-strategy axis.
13644 for estrategia in [
13645 RestartStrategy::OneForOne,
13646 RestartStrategy::OneForAll,
13647 RestartStrategy::RestForOne,
13648 ] {
13649 let s = SupervisorSpec {
13650 estrategia,
13651 children: Vec::new(),
13652 ..SupervisorSpec::default()
13653 };
13654 let err = s.validate().unwrap_err();
13655 match err {
13656 SupervisorError::NoChildren { estrategia: e } => {
13657 assert_eq!(
13658 e,
13659 s.estrategia(),
13660 "NoChildren.estrategia must byte-equal \
13661 SupervisorSpec::estrategia() — the empty-`:children` \
13662 refusal reads through the lifted accessor",
13663 );
13664 assert_eq!(
13665 e, estrategia,
13666 "NoChildren.estrategia must carry the author-declared \
13667 :supervisor :estrategia variant verbatim (got {e:?}, \
13668 expected {estrategia:?})",
13669 );
13670 }
13671 other => panic!("expected NoChildren, got {other:?} for estrategia={estrategia:?}"),
13672 }
13673 }
13674 }
13675
13676 // ── per-`:supervisor` `:max-restarts` typed-accessor coherence pins ────
13677 //
13678 // The [`SupervisorSpec::max_restarts`] accessor lift extends the peer M3
13679 // [`crate::CircuitBreaker::max_failures`] (3a74062) `Copy`-return
13680 // required-`u32` scalar accessor discipline onto the M2 supervisor-slot
13681 // per-`:supervisor` restart-budget-count `Copy`-`u32` scalar axis.
13682 // The two pins below cover (1) the accessor's byte-equal projection
13683 // against the raw field access across every representative value in
13684 // the `u32` accept-set (`1` lower boundary, `SUPERVISOR_MAX_RESTARTS_MAX`
13685 // upper boundary, `0` past-the-guard zero sentinel, `u32::MAX`
13686 // past-the-guard cap sentinel), and (2) the [`SupervisorSpec::validate`]
13687 // zero-floor / cap composition — the validate gate and the accessor
13688 // must route through the same substrate-primitive typed dispatch, so
13689 // any future silent detour that had the accessor perform a
13690 // bounds-collapsing clamp would fail here at caixa-core build time.
13691 // Peer of the sibling M3
13692 // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
13693 // (3a74062) pin on the per-`CircuitBreaker :max-failures` axis.
13694
13695 #[test]
13696 fn supervisor_spec_max_restarts_returns_max_restarts_u32_byte_equal_across_permutations() {
13697 // The canonical per-`:supervisor` restart-budget-count scalar pin:
13698 // [`SupervisorSpec::max_restarts`] must return the `:supervisor
13699 // :max-restarts` typed `u32` verbatim, `Copy`-projected from the
13700 // typed slot's own `u32` storage, byte-equal to the raw field
13701 // access across every representative value in the accept-set —
13702 // `1` (the lower boundary of the `1..=SUPERVISOR_MAX_RESTARTS_MAX`
13703 // accept-set the surrounding [`SupervisorSpec::validate`] gate
13704 // carves out on the sibling `ZeroMaxRestarts` refusal),
13705 // `SUPERVISOR_MAX_RESTARTS_MAX` (the upper boundary the same gate
13706 // carves out on the sibling `MaxRestartsExceedsCap` refusal), `0`
13707 // (a past-the-guard sentinel that pins the accessor doesn't
13708 // perform a silent bounds-collapse into `1` on the zero arm —
13709 // validate rejects zero but the accessor must ship the raw slot
13710 // verbatim so a validate-time gate regression surfaces at the
13711 // emit boundary rather than being silently absorbed), `u32::MAX`
13712 // (a past-the-guard sentinel that pins the accessor doesn't
13713 // perform a silent bounds-collapse through
13714 // `SUPERVISOR_MAX_RESTARTS_MAX` at the return path).
13715 //
13716 // Peer of the sibling M3
13717 // `circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations`
13718 // (3a74062) pin on the M3 mesh-slot `Copy`-`u32` sub-struct
13719 // required-scalar axis — same "the substrate-primitive accessor
13720 // must byte-equal the raw field access verbatim across every
13721 // value in the `u32` accept-set" discipline extended onto the M2
13722 // supervisor-slot per-`:supervisor` restart-budget-count axis.
13723 for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX, 0, u32::MAX] {
13724 let s = SupervisorSpec {
13725 max_restarts,
13726 ..SupervisorSpec::default()
13727 };
13728 assert_eq!(
13729 s.max_restarts(),
13730 max_restarts,
13731 "SupervisorSpec::max_restarts must return :supervisor \
13732 :max-restarts verbatim (got {}, expected {max_restarts})",
13733 s.max_restarts(),
13734 );
13735 assert_eq!(
13736 s.max_restarts(),
13737 s.max_restarts,
13738 "SupervisorSpec::max_restarts accessor and .max_restarts \
13739 field access must byte-equal — the accessor is the \
13740 substrate-primitive typed dispatch every downstream \
13741 restart-budget-count consumer must route through",
13742 );
13743 }
13744 }
13745
13746 #[test]
13747 fn validate_max_restarts_zero_floor_and_cap_arms_route_through_accessor() {
13748 // Composition pin: [`SupervisorSpec::validate`]'s `:max-restarts`
13749 // zero-floor + upper-cap bracket must key off
13750 // [`SupervisorSpec::max_restarts`], not the raw `.max_restarts`
13751 // field access. Structurally: a `SupervisorSpec { max_restarts:
13752 // 0, .. }` must surface the `ZeroMaxRestarts` refusal exactly, a
13753 // `SupervisorSpec { max_restarts: SUPERVISOR_MAX_RESTARTS_MAX + 1,
13754 // .. }` must surface the `MaxRestartsExceedsCap` refusal exactly
13755 // (with the offending count carried verbatim from the accessor
13756 // return), and a `SupervisorSpec { max_restarts: 1, .. }` (the
13757 // lower boundary of the accept-set) plus a `SupervisorSpec {
13758 // max_restarts: SUPERVISOR_MAX_RESTARTS_MAX, .. }` (the upper
13759 // boundary) must pass validate. The four together jointly pin the
13760 // accessor + validate-gate composition: any future silent detour
13761 // that had the accessor return a fresh `1` on the zero arm (a
13762 // `.max_restarts().max(1)` collapse) would silently absorb the
13763 // `ZeroMaxRestarts` refusal at the accessor boundary and the
13764 // validate gate would accept a struct-literal `SupervisorSpec {
13765 // max_restarts: 0, .. }` — the composition pin catches that at
13766 // caixa-core build time.
13767 //
13768 // Peer of the sibling M3
13769 // `validate_politicas_max_failures_zero_floor_arm_routes_through_accessor`
13770 // (3a74062) pin on the sibling per-`CircuitBreaker :max-failures`
13771 // composition axis — same "the validate / shape-gate predicate
13772 // must route through the substrate-primitive typed dispatch"
13773 // discipline extended onto the peer M2 supervisor-slot
13774 // required-`u32` composition axis.
13775 let child = ChildSpec {
13776 caixa: "worker".into(),
13777 versao: "^0.1".into(),
13778 restart: RestartPolicy::Permanent,
13779 };
13780 // Zero-floor arm.
13781 let s = SupervisorSpec {
13782 max_restarts: 0,
13783 children: vec![child.clone()],
13784 ..SupervisorSpec::default()
13785 };
13786 assert_eq!(
13787 s.validate().unwrap_err(),
13788 SupervisorError::ZeroMaxRestarts,
13789 "validate must reject max_restarts == 0 with ZeroMaxRestarts \
13790 — the accessor and the validate gate must route through the \
13791 same substrate-primitive typed dispatch on the zero-floor arm",
13792 );
13793 // Cap arm — the surfaced `max_restarts:` field must byte-equal
13794 // the accessor's return so a future rebrand on the accessor
13795 // lands in the diagnostic without a coordinated rewrite.
13796 let over_cap = SUPERVISOR_MAX_RESTARTS_MAX + 1;
13797 let s = SupervisorSpec {
13798 max_restarts: over_cap,
13799 children: vec![child.clone()],
13800 ..SupervisorSpec::default()
13801 };
13802 match s.validate().unwrap_err() {
13803 SupervisorError::MaxRestartsExceedsCap { max_restarts } => {
13804 assert_eq!(
13805 max_restarts,
13806 s.max_restarts(),
13807 "MaxRestartsExceedsCap.max_restarts must byte-equal \
13808 SupervisorSpec::max_restarts() — the cap-arm refusal \
13809 reads through the lifted accessor",
13810 );
13811 assert_eq!(
13812 max_restarts, over_cap,
13813 "MaxRestartsExceedsCap.max_restarts must carry the \
13814 author-declared :supervisor :max-restarts value \
13815 verbatim (got {max_restarts}, expected {over_cap})",
13816 );
13817 }
13818 other => panic!("expected MaxRestartsExceedsCap, got {other:?}"),
13819 }
13820 // Lower + upper accept-set boundaries.
13821 for max_restarts in [1u32, SUPERVISOR_MAX_RESTARTS_MAX] {
13822 let s = SupervisorSpec {
13823 max_restarts,
13824 children: vec![child.clone()],
13825 ..SupervisorSpec::default()
13826 };
13827 assert!(
13828 s.validate().is_ok(),
13829 "validate must accept max_restarts == {max_restarts} \
13830 (an accept-set boundary of \
13831 1..=SUPERVISOR_MAX_RESTARTS_MAX)",
13832 );
13833 }
13834 }
13835
13836 // ── per-`:supervisor` `:restart-window` typed-accessor coherence pins ─
13837 //
13838 // The [`SupervisorSpec::restart_window`] accessor lift extends the peer
13839 // M2 [`crate::LimitsSpec::wall_clock`] (8cb717b) `Option<Duration>`
13840 // accessor discipline and the peer M3 [`crate::MeshPolicy::timeout`]
13841 // (7073d0f) `Option<Duration>` accessor discipline onto the M2
13842 // supervisor-slot per-`:supervisor` restart-intensity-denominator
13843 // `Option<Duration>` scalar axis — third `Copy`-return accessor on the
13844 // M2 supervisor-slot `SupervisorSpec` type, closing the last unlifted
13845 // per-`:supervisor` scalar-value axis. The three pins below cover
13846 // (1) the accessor's byte-equal projection against the raw field
13847 // access across every representative value in the `Option<Duration>`
13848 // accept-set (`None` never-reset sentinel, `Some(Duration::from_millis(1))`
13849 // lower boundary, `Some(SUPERVISOR_RESTART_WINDOW_MAX)` upper boundary,
13850 // `Some(Duration::ZERO)` past-the-guard zero sentinel, `Some(Duration::MAX)`
13851 // past-the-guard above-cap sentinel), (2) the [`SupervisorSpec::validate`]
13852 // `if let Some(w) = self.restart_window() { … }` bracket-arm
13853 // composition — the validate gate and the accessor must route through
13854 // the same substrate-primitive typed dispatch, so any future silent
13855 // detour that had the accessor perform a bounds-collapsing clamp
13856 // would fail here at caixa-core build time, and (3) the accessor's
13857 // by-copy idempotence pin — the returned `Option<Duration>` must
13858 // outlive `&self` and two successive calls must return byte-equal
13859 // values. Peer of the sibling M2
13860 // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
13861 // (8cb717b) pin on the per-`:limits :wall-clock` axis and the sibling
13862 // M3 `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
13863 // (7073d0f) pin on the per-`:politicas :timeout` axis.
13864
13865 #[test]
13866 fn supervisor_spec_restart_window_returns_option_duration_byte_equal_across_permutations() {
13867 // The canonical per-`:supervisor` restart-intensity-denominator
13868 // scalar pin: [`SupervisorSpec::restart_window`] must return the
13869 // `:supervisor :restart-window` typed [`Duration`] verbatim as an
13870 // `Option<Duration>`, `Copy`-projected from the typed slot's own
13871 // `Option<Duration>` storage, byte-equal to the raw field access
13872 // across every representative value in the accept-set — `None`
13873 // (the "never reset — every restart across the supervisor's
13874 // lifetime counts against the sibling `:max-restarts` budget"
13875 // sentinel the field's own docstring names and the peer
13876 // `validate_accepts_none_restart_window` pin locks in on the
13877 // [`SupervisorSpec::validate`] entry-side),
13878 // `Some(Duration::from_millis(1))` (the structural minimum a
13879 // validated `:restart-window` may carry, the integer-millisecond
13880 // floor [`SupervisorError::RestartWindowNotCanonical`] rejects
13881 // everything sub-ms; `Duration::ZERO` is separately rejected by
13882 // [`SupervisorError::RestartWindowZero`]),
13883 // `Some(SUPERVISOR_RESTART_WINDOW_MAX)` (the upper boundary the
13884 // surrounding [`SupervisorSpec::validate`] gate carves out on the
13885 // sibling [`SupervisorError::RestartWindowExceedsCap`] refusal),
13886 // `Some(Duration::ZERO)` (a past-the-guard sentinel that pins the
13887 // accessor doesn't perform a silent bounds-collapse into `None` on
13888 // the zero-Duration arm — validate rejects zero but the accessor
13889 // must ship the raw slot verbatim so a validate-time gate
13890 // regression surfaces at the emit boundary rather than being
13891 // silently absorbed), and `Some(Duration::MAX)` (a past-the-guard
13892 // sentinel that pins the accessor doesn't perform a silent
13893 // bounds-collapse through [`SUPERVISOR_RESTART_WINDOW_MAX`] at the
13894 // return path).
13895 //
13896 // Peer of the sibling M2
13897 // `limits_wall_clock_returns_option_duration_byte_equal_across_permutations`
13898 // (8cb717b) pin on the per-`:limits :wall-clock` axis and the
13899 // sibling M3
13900 // `mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations`
13901 // (7073d0f) pin on the per-`:politicas :timeout` axis — same "the
13902 // substrate-primitive accessor must byte-equal the raw field
13903 // access verbatim across every value in the `Option<Duration>`
13904 // accept-set" discipline extended onto the M2 supervisor-slot
13905 // per-`:supervisor` `Option<Duration>` axis. Pins against a future
13906 // silent detour that re-derived the restart-window from a peer
13907 // axis (an accidental `.max_restarts.into()` collapse that read
13908 // the restart-budget-count as a duration — the two axes serve
13909 // different halves of the `MaxIntensity / Period` restart-
13910 // intensity ratio, and confusing them silently inverts the
13911 // ratio's numerator and denominator), a `None → Some(Duration::ZERO)`
13912 // "zero means never reset" collapse (the canonical
13913 // `Option<Duration>` → `Duration` collapse footgun the
13914 // [`SupervisorError::RestartWindowZero`] validate arm guards on
13915 // the peer zero-floor axis; a zero period either trips on the
13916 // first failure or never trips depending on operator
13917 // interpretation, neither of which is the author's "never reset"
13918 // intent that `None` expresses structurally), or a per-arm
13919 // variant swap that landed on one consumer without the other.
13920 for restart_window in [
13921 None,
13922 Some(Duration::from_millis(1)),
13923 Some(SUPERVISOR_RESTART_WINDOW_MAX),
13924 Some(Duration::ZERO),
13925 Some(Duration::MAX),
13926 ] {
13927 let s = SupervisorSpec {
13928 restart_window,
13929 ..SupervisorSpec::default()
13930 };
13931 assert_eq!(
13932 s.restart_window(),
13933 restart_window,
13934 "SupervisorSpec::restart_window must return :supervisor \
13935 :restart-window verbatim (got {:?}, expected {restart_window:?})",
13936 s.restart_window(),
13937 );
13938 assert_eq!(
13939 s.restart_window(),
13940 s.restart_window,
13941 "SupervisorSpec::restart_window accessor and \
13942 .restart_window field access must byte-equal — the \
13943 accessor is the substrate-primitive typed dispatch every \
13944 downstream restart-intensity-denominator consumer must \
13945 route through",
13946 );
13947 }
13948 }
13949
13950 #[test]
13951 fn validate_restart_window_bracket_arm_routes_through_accessor() {
13952 // Composition pin: [`SupervisorSpec::validate`]'s
13953 // `:restart-window` `if let Some(w) = self.restart_window() { … }`
13954 // zero-floor + integer-millisecond canonical-form + upper-cap
13955 // bracket-arm must key off [`SupervisorSpec::restart_window`], not
13956 // the raw `.restart_window` field access. Structurally: a
13957 // `SupervisorSpec { restart_window: None, .. }` must pass the
13958 // arm gate structurally (the `if let Some(_)` shape returns
13959 // early on the `None` arm — the accessor and the validate gate
13960 // must agree on `None → skip the bracket cascade` so an authored
13961 // `:restart-window ()` structurally routes through the "never
13962 // reset" sentinel path), a `SupervisorSpec { restart_window:
13963 // Some(Duration::ZERO), .. }` must surface the `RestartWindowZero`
13964 // refusal exactly, a `SupervisorSpec { restart_window:
13965 // Some(Duration::from_micros(1500)), .. }` must surface the
13966 // `RestartWindowNotCanonical` refusal exactly (with the offending
13967 // duration carried verbatim from the accessor return), a
13968 // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX
13969 // + Duration::from_millis(1)), .. }` must surface the
13970 // `RestartWindowExceedsCap` refusal exactly (with the offending
13971 // duration carried verbatim from the accessor return), and a
13972 // `SupervisorSpec { restart_window: Some(Duration::from_millis(1)),
13973 // .. }` (the lower boundary of the accept-set) plus a
13974 // `SupervisorSpec { restart_window: Some(SUPERVISOR_RESTART_WINDOW_MAX),
13975 // .. }` (the upper boundary) must pass validate. The six together
13976 // jointly pin the accessor + validate-gate composition: any future
13977 // silent detour that had the accessor return a fresh `None` on any
13978 // `Some` arm (a `.restart_window().filter(|w| !w.is_zero())`
13979 // collapse) would silently absorb the `RestartWindowZero` refusal
13980 // at the accessor boundary and the validate gate would accept a
13981 // struct-literal `SupervisorSpec { restart_window:
13982 // Some(Duration::ZERO), .. }` — the composition pin catches that
13983 // at caixa-core build time.
13984 //
13985 // Peer of the sibling M2 [`crate::LimitsSpec::wall_clock`]
13986 // (8cb717b) validate-arm-route pin on the per-`:limits :wall-clock`
13987 // axis and the peer M3 [`crate::MeshPolicy::timeout`] (7073d0f)
13988 // accessor-composition pin on the per-`:politicas :timeout` axis —
13989 // same "the validate / shape-gate predicate must route through
13990 // the substrate-primitive typed dispatch" discipline extended
13991 // onto the peer M2 supervisor-slot optional-`Duration` axis.
13992 let child = ChildSpec {
13993 caixa: "worker".into(),
13994 versao: "^0.1".into(),
13995 restart: RestartPolicy::Permanent,
13996 };
13997 // None arm — must not surface any :restart-window-shaped refusal;
13998 // the `if let Some(_)` bracket returns early on `None` structurally.
13999 let s = SupervisorSpec {
14000 restart_window: None,
14001 children: vec![child.clone()],
14002 ..SupervisorSpec::default()
14003 };
14004 assert!(
14005 s.validate().is_ok(),
14006 "validate must accept restart_window: None (the never-reset \
14007 sentinel) — the `if let Some(_)` bracket returns early on \
14008 the None arm and the accessor must agree",
14009 );
14010 // Zero-floor arm.
14011 let s = SupervisorSpec {
14012 restart_window: Some(Duration::ZERO),
14013 children: vec![child.clone()],
14014 ..SupervisorSpec::default()
14015 };
14016 assert_eq!(
14017 s.validate().unwrap_err(),
14018 SupervisorError::RestartWindowZero,
14019 "validate must reject restart_window == Some(Duration::ZERO) \
14020 with RestartWindowZero — the accessor and the validate gate \
14021 must route through the same substrate-primitive typed \
14022 dispatch on the zero-floor arm",
14023 );
14024 // Non-canonical (sub-ms) arm — the surfaced `window:` field must
14025 // byte-equal the accessor's return so a future rebrand on the
14026 // accessor lands in the diagnostic without a coordinated rewrite.
14027 let sub_ms = Duration::from_micros(1500);
14028 let s = SupervisorSpec {
14029 restart_window: Some(sub_ms),
14030 children: vec![child.clone()],
14031 ..SupervisorSpec::default()
14032 };
14033 match s.validate().unwrap_err() {
14034 SupervisorError::RestartWindowNotCanonical { window } => {
14035 assert_eq!(
14036 Some(window),
14037 s.restart_window(),
14038 "RestartWindowNotCanonical.window must byte-equal \
14039 SupervisorSpec::restart_window().unwrap() — the \
14040 non-canonical-arm refusal reads through the lifted \
14041 accessor",
14042 );
14043 assert_eq!(
14044 window, sub_ms,
14045 "RestartWindowNotCanonical.window must carry the \
14046 author-declared :supervisor :restart-window value \
14047 verbatim (got {window:?}, expected {sub_ms:?})",
14048 );
14049 }
14050 other => panic!("expected RestartWindowNotCanonical, got {other:?}"),
14051 }
14052 // Cap arm — the surfaced `window:` field must byte-equal the
14053 // accessor's return.
14054 let over_cap = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
14055 let s = SupervisorSpec {
14056 restart_window: Some(over_cap),
14057 children: vec![child.clone()],
14058 ..SupervisorSpec::default()
14059 };
14060 match s.validate().unwrap_err() {
14061 SupervisorError::RestartWindowExceedsCap { window } => {
14062 assert_eq!(
14063 Some(window),
14064 s.restart_window(),
14065 "RestartWindowExceedsCap.window must byte-equal \
14066 SupervisorSpec::restart_window().unwrap() — the \
14067 cap-arm refusal reads through the lifted accessor",
14068 );
14069 assert_eq!(
14070 window, over_cap,
14071 "RestartWindowExceedsCap.window must carry the \
14072 author-declared :supervisor :restart-window value \
14073 verbatim (got {window:?}, expected {over_cap:?})",
14074 );
14075 }
14076 other => panic!("expected RestartWindowExceedsCap, got {other:?}"),
14077 }
14078 // Lower + upper accept-set boundaries.
14079 for restart_window in [Duration::from_millis(1), SUPERVISOR_RESTART_WINDOW_MAX] {
14080 let s = SupervisorSpec {
14081 restart_window: Some(restart_window),
14082 children: vec![child.clone()],
14083 ..SupervisorSpec::default()
14084 };
14085 assert!(
14086 s.validate().is_ok(),
14087 "validate must accept restart_window == Some({restart_window:?}) \
14088 (an accept-set boundary of \
14089 1ms..=SUPERVISOR_RESTART_WINDOW_MAX)",
14090 );
14091 }
14092 }
14093
14094 #[test]
14095 fn supervisor_spec_restart_window_projects_option_duration_by_copy() {
14096 // The by-copy pin: [`SupervisorSpec::restart_window`] returns
14097 // `Option<Duration>` by copy — `Duration` is `Copy` (so
14098 // `Option<Duration>` is `Copy`) and the accessor must return by
14099 // value, not by reference. Peer of the sibling M2
14100 // [`crate::LimitsSpec::wall_clock`] (8cb717b) by-copy pin on the
14101 // per-`:limits :wall-clock` axis and the sibling M3
14102 // [`crate::MeshPolicy::timeout`] (7073d0f) by-copy pin on the
14103 // per-`:politicas :timeout` axis, extended onto the peer M2
14104 // supervisor-slot `Option<Duration>` copy-invariant shape — the
14105 // accessor's returned `Option<Duration>` must outlive `&self`
14106 // (multiple calls must return equal values from a dropped-`&self`
14107 // copy, since the returned Option carries no borrow), and calling
14108 // the accessor twice on the same SupervisorSpec must yield the
14109 // same `Option<Duration>` verbatim (idempotent, no side effects
14110 // on `&self`).
14111 //
14112 // Pins against a future silent detour that returned
14113 // `Option<&Duration>` (which would type-check but silently break
14114 // every downstream caller — the future wasm-operator's
14115 // per-supervisor restart-intensity counter consumes `Duration` by
14116 // value and `&Duration` would fold to a detached copy at the call
14117 // site), an accidental `Option::as_ref()` projection
14118 // (`self.restart_window.as_ref()` would also type-check but
14119 // return `Option<&Duration>`), or a one-arm-only accessor that
14120 // reads `Some(*w)` in the Some arm but reads a fresh
14121 // `Default::default()` (which would collapse to `Duration::ZERO`,
14122 // not `None`) in the None arm — a footgun the
14123 // [`SupervisorError::RestartWindowZero`] validate arm explicitly
14124 // closes since Erlang/OTP's `MaxIntensity / Period` invariant
14125 // requires `Period > 0` and `None` structurally expresses "never
14126 // reset" instead.
14127 for restart_window in [
14128 None,
14129 Some(Duration::from_millis(1)),
14130 Some(Duration::from_secs(60)),
14131 Some(SUPERVISOR_RESTART_WINDOW_MAX),
14132 ] {
14133 let s = SupervisorSpec {
14134 restart_window,
14135 ..SupervisorSpec::default()
14136 };
14137 let first = s.restart_window();
14138 let second = s.restart_window();
14139 assert_eq!(
14140 first, second,
14141 "SupervisorSpec::restart_window must be idempotent — two \
14142 successive calls on the same &self must return the \
14143 same Option<Duration>",
14144 );
14145 assert_eq!(
14146 first, restart_window,
14147 "SupervisorSpec::restart_window must return :supervisor \
14148 :restart-window verbatim by copy — got {first:?}, \
14149 expected {restart_window:?}",
14150 );
14151 }
14152 }
14153
14154 // ── per-`:supervisor` `:children` typed-accessor coherence pins ─────────
14155 //
14156 // The [`SupervisorSpec::children`] accessor lift is the seed of the
14157 // slice-return (`&[T]`) accessor discipline on the substrate — the four
14158 // peer `Vec`-carry axes ([`crate::Placement::clusters`],
14159 // [`crate::AplicacaoSpec::membros`], [`crate::AplicacaoSpec::contratos`],
14160 // [`crate::UpgradeFromEntry::instructions`]) still key off the raw field
14161 // access at the time of this seed, and inherit this pin family's
14162 // discipline as future compounding runs migrate their consumers. The
14163 // three pins below cover (1) the accessor's byte-equal projection
14164 // against the raw field access across the empty / singleton / cohort
14165 // fixtures the [`SupervisorSpec::validate`] partition-dispatch fans
14166 // between, (2) the [`SupervisorSpec::validate`] `SimpleOneForOne ↔
14167 // non-SimpleOneForOne` partition dispatch's paired `.is_empty()`
14168 // consumer routing through the accessor on both arms, and (3) the
14169 // per-child validate loop's traversal reading the same slice-view the
14170 // accessor projects. Peer of the sibling M2
14171 // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
14172 // two-consumer coherence pin on the per-`:supervisor`
14173 // sibling-restart-strategy `Copy`-composite-enum scalar axis, extended
14174 // onto the per-`:supervisor` static-child-list `Vec`-carry axis.
14175
14176 #[test]
14177 fn supervisor_spec_children_returns_children_slice_byte_equal_across_permutations() {
14178 // The canonical per-`:supervisor` static-child-list scalar-shape
14179 // pin: [`SupervisorSpec::children`] must return the `:supervisor
14180 // :children` typed `Vec<ChildSpec>` verbatim as a `&[ChildSpec]`
14181 // slice-view over the same backing buffer the raw
14182 // `self.children.as_slice()` field access borrows from, byte-
14183 // equal across every representative fixture in the accept-set —
14184 // the empty slice (the `SimpleOneForOne`-arm sentinel),
14185 // the singleton slice (the minimal non-`SimpleOneForOne` shape),
14186 // and a two-child cohort (a peer non-`SimpleOneForOne` shape
14187 // with the peer three restart-policy variants in play).
14188 //
14189 // Pins against a future silent detour that returned
14190 // `&Vec<ChildSpec>` (which would type-check but leak the
14191 // storage-side `Vec`'s grow/push/reserve surface no consumer of
14192 // the typed view reaches for), a fresh-allocated
14193 // `Vec<ChildSpec>` copy (which would type-check via a coercion
14194 // but silently break every downstream caller that relied on the
14195 // slice sharing the backing buffer's identity), or an
14196 // out-of-order or length-drifted projection (which would silently
14197 // split the per-child validate loop's traversal input from the
14198 // paired partition-dispatch `.is_empty()` probe's input).
14199 //
14200 // Peer of the sibling
14201 // `supervisor_spec_estrategia_returns_estrategia_verbatim_across_permutations`
14202 // (eafb619) `Copy`-composite-enum byte-equal pin on the
14203 // per-`:supervisor` sibling-restart-strategy axis, extended onto
14204 // the per-`:supervisor` static-child-list `Vec`-carry axis.
14205 let fixtures: Vec<Vec<ChildSpec>> = vec![
14206 Vec::new(),
14207 vec![child("worker", "^0.1", RestartPolicy::Permanent)],
14208 vec![
14209 child("worker", "^0.1", RestartPolicy::Permanent),
14210 child("cache-server", "^0.1", RestartPolicy::Transient),
14211 ],
14212 vec![
14213 child("worker", "^0.1", RestartPolicy::Permanent),
14214 child("cache-server", "^0.1", RestartPolicy::Transient),
14215 child("scratch-job", "^0.1", RestartPolicy::Temporary),
14216 ],
14217 ];
14218 for children in fixtures {
14219 let s = SupervisorSpec {
14220 children: children.clone(),
14221 ..SupervisorSpec::default()
14222 };
14223 assert_eq!(
14224 s.children(),
14225 children.as_slice(),
14226 "SupervisorSpec::children must return :supervisor \
14227 :children verbatim (got {:?}, expected {:?})",
14228 s.children(),
14229 children.as_slice(),
14230 );
14231 assert_eq!(
14232 s.children(),
14233 s.children.as_slice(),
14234 "SupervisorSpec::children accessor and \
14235 .children.as_slice() field access must byte-equal — \
14236 the accessor is the substrate-primitive typed \
14237 dispatch every downstream static-child-list consumer \
14238 must route through",
14239 );
14240 assert_eq!(
14241 s.children().len(),
14242 s.children.len(),
14243 "SupervisorSpec::children().len() must byte-equal \
14244 self.children.len() — a length-drift would silently \
14245 split the paired partition-dispatch `.is_empty()` \
14246 probe input from the per-child validate loop's \
14247 traversal input",
14248 );
14249 }
14250 }
14251
14252 #[test]
14253 fn validate_reads_through_lifted_children_accessor() {
14254 // Three-consumer coherence pin: the [`SupervisorSpec::validate`]
14255 // `SimpleOneForOne`-arm `!self.children().is_empty()` refusal
14256 // probe (which must trip [`SupervisorError::SimpleOneForOneWithStaticChildren`]
14257 // when the accessor projects a non-empty slice under a
14258 // `SimpleOneForOne` estrategia), the peer non-`SimpleOneForOne`-arm
14259 // `self.children().is_empty()` refusal probe (which must trip
14260 // [`SupervisorError::NoChildren`] when the accessor projects the
14261 // empty slice under any peer estrategia), and the per-child
14262 // validate loop's `for child in self.children()` traversal
14263 // (which must reach every entry in the same order the accessor
14264 // projects) must all key off the lifted accessor, so any future
14265 // rebrand on the typed slot's reader shape lands at exactly one
14266 // place. Pins the three-site coherence by exercising each
14267 // production consumer end-to-end: (1) the
14268 // `SimpleOneForOneWithStaticChildren` refusal under a non-empty
14269 // slice + `SimpleOneForOne` estrategia, (2) the `NoChildren`
14270 // refusal under the empty slice + non-`SimpleOneForOne`
14271 // estrategia across every peer variant, and (3) the per-child
14272 // duplicate-detection surface fires on the second entry of a
14273 // two-child cohort that shares a `:caixa` name (which requires
14274 // the loop to reach both entries — a first-entry-only projection
14275 // would silently pass since the dedup HashSet has room for the
14276 // first insert).
14277 //
14278 // Peer of the sibling M2
14279 // [`validate_reads_through_lifted_estrategia_accessor`] (eafb619)
14280 // two-consumer coherence pin on the per-`:supervisor`
14281 // sibling-restart-strategy axis, extended onto the
14282 // per-`:supervisor` static-child-list `Vec`-carry axis.
14283
14284 // (1) `SimpleOneForOne`-arm probe: a non-empty slice under a
14285 // `SimpleOneForOne` estrategia must trip
14286 // `SimpleOneForOneWithStaticChildren`.
14287 let s = SupervisorSpec {
14288 estrategia: RestartStrategy::SimpleOneForOne,
14289 children: vec![child("worker", "^0.1", RestartPolicy::Permanent)],
14290 ..SupervisorSpec::default()
14291 };
14292 assert_eq!(
14293 s.validate().unwrap_err(),
14294 SupervisorError::SimpleOneForOneWithStaticChildren,
14295 "SimpleOneForOne + non-empty children must trip \
14296 SimpleOneForOneWithStaticChildren — the accessor projects \
14297 a non-empty slice, and the SimpleOneForOne-arm refusal \
14298 probe reads through the lifted accessor",
14299 );
14300 assert!(
14301 !s.children().is_empty(),
14302 "the SimpleOneForOne-arm refusal input must be a non-empty \
14303 slice per the accessor's projection",
14304 );
14305
14306 // (2) Peer non-`SimpleOneForOne`-arm probe: the empty slice
14307 // under any peer estrategia must trip `NoChildren`.
14308 for estrategia in [
14309 RestartStrategy::OneForOne,
14310 RestartStrategy::OneForAll,
14311 RestartStrategy::RestForOne,
14312 ] {
14313 let s = SupervisorSpec {
14314 estrategia,
14315 children: Vec::new(),
14316 ..SupervisorSpec::default()
14317 };
14318 match s.validate().unwrap_err() {
14319 SupervisorError::NoChildren { estrategia: e } => {
14320 assert_eq!(
14321 e, estrategia,
14322 "NoChildren.estrategia must carry the author-\
14323 declared :supervisor :estrategia variant \
14324 verbatim (got {e:?}, expected {estrategia:?})",
14325 );
14326 }
14327 other => panic!(
14328 "expected NoChildren, got {other:?} for \
14329 estrategia={estrategia:?}"
14330 ),
14331 }
14332 assert!(
14333 s.children().is_empty(),
14334 "the non-SimpleOneForOne-arm refusal input must be the \
14335 empty slice per the accessor's projection",
14336 );
14337 }
14338
14339 // (3) Per-child validate loop: a two-child cohort that shares a
14340 // `:caixa` name must trip `DuplicateChildCaixa` — the loop must
14341 // reach both entries through the accessor.
14342 let s = SupervisorSpec {
14343 estrategia: RestartStrategy::OneForOne,
14344 children: vec![
14345 child("worker", "^0.1", RestartPolicy::Permanent),
14346 child("worker", "^0.2", RestartPolicy::Transient),
14347 ],
14348 ..SupervisorSpec::default()
14349 };
14350 match s.validate().unwrap_err() {
14351 SupervisorError::DuplicateChildCaixa { caixa } => {
14352 assert_eq!(
14353 caixa, "worker",
14354 "DuplicateChildCaixa.caixa must carry the shared \
14355 child `:caixa` name verbatim",
14356 );
14357 }
14358 other => panic!("expected DuplicateChildCaixa, got {other:?}"),
14359 }
14360 assert_eq!(
14361 s.children().len(),
14362 2,
14363 "the per-child validate loop's traversal input must be a \
14364 two-element slice per the accessor's projection",
14365 );
14366 }
14367
14368 // Shared helper for the M2 per-`:children` per-slot-gate ≡
14369 // `validate` equivalence pins: builds an `OneForOne`-estrategia
14370 // one-cohort spec whose peer `:estrategia`↔`:children.is_empty()`
14371 // partition, `:max-restarts` zero-floor/cap, and `:restart-window`
14372 // bracket all pass cleanly so the sole failing surface is the
14373 // per-child cascade [`SupervisorSpec::validate_children`] owns, and
14374 // pins the two-altitude equivalence on the paired probe.
14375 fn assert_validate_children_matches_gate(children: Vec<ChildSpec>, expected: &SupervisorError) {
14376 let s = SupervisorSpec {
14377 estrategia: RestartStrategy::OneForOne,
14378 children,
14379 ..SupervisorSpec::default()
14380 };
14381 let via_gate = s.validate_children().unwrap_err();
14382 let via_validate = s.validate().unwrap_err();
14383 assert_eq!(&via_gate, expected, "validate_children direct dispatch",);
14384 assert_eq!(&via_validate, expected, "validate() end-to-end dispatch",);
14385 assert_eq!(
14386 via_gate, via_validate,
14387 "per-slot gate ≡ validate() must discriminate the same \
14388 refusal shape",
14389 );
14390 }
14391
14392 #[test]
14393 fn validate_children_matches_gate_on_per_axis_refusal_shapes() {
14394 // Fail-before-pass-after equivalence pin on the M2
14395 // per-`:children` per-slot gate ≡ [`SupervisorSpec::validate`]
14396 // convergence — sibling of the M3 mesh-slot
14397 // `validate_membros_*` / `validate_contratos_*` /
14398 // `validate_entrada_*` per-slot-gate ≡ `validate` pins on the
14399 // peer per-entry axes. Sweeps four of the five refusal shapes
14400 // the per-slot gate owns: (1) `EmptyChildName` on an empty-
14401 // `:caixa` child, (2) `ChildCaixaInvalid` on a structurally
14402 // invalid `:caixa` DNS-1123 label, (3) `EmptyChildVersion` on
14403 // an empty-`:versao` child, (4) `DuplicateChildCaixa` on a
14404 // duplicate-`:caixa` fan-out. Companion pin
14405 // `validate_children_matches_gate_on_versao_invalid_and_clean_pass`
14406 // covers `ChildVersaoInvalid` (whose parser-owned reason string
14407 // needs pattern-matching, not equality) and the clean-pass
14408 // canonical fixture; together the two pins guarantee the
14409 // per-slot gate and `validate` discriminate the same set on
14410 // every per-child-covered input.
14411 assert_validate_children_matches_gate(
14412 vec![child("", "^0.1", RestartPolicy::Permanent)],
14413 &SupervisorError::EmptyChildName,
14414 );
14415 assert_validate_children_matches_gate(
14416 vec![child("Worker", "^0.1", RestartPolicy::Permanent)],
14417 &SupervisorError::ChildCaixaInvalid {
14418 caixa: "Worker".into(),
14419 reason: "contains uppercase character 'W' (K8s DNS-1123 label names are lowercase-only; use \"worker\")".into(),
14420 },
14421 );
14422 assert_validate_children_matches_gate(
14423 vec![child("worker", "", RestartPolicy::Permanent)],
14424 &SupervisorError::EmptyChildVersion {
14425 caixa: "worker".into(),
14426 },
14427 );
14428 assert_validate_children_matches_gate(
14429 vec![
14430 child("worker", "^0.1", RestartPolicy::Permanent),
14431 child("worker", "^0.2", RestartPolicy::Transient),
14432 ],
14433 &SupervisorError::DuplicateChildCaixa {
14434 caixa: "worker".into(),
14435 },
14436 );
14437 }
14438
14439 #[test]
14440 fn validate_children_matches_gate_on_versao_invalid_and_clean_pass() {
14441 // Second half of the two-altitude equivalence pin — covers the
14442 // one refusal shape whose reason string is parser-owned
14443 // (`ChildVersaoInvalid`, whose reason comes from the shared
14444 // [`crate::version::parse_requirement`] impl and may drift) and
14445 // the clean-pass canonical fixture. Sibling pin
14446 // `validate_children_matches_gate_on_per_axis_refusal_shapes`
14447 // covers the four equality-comparable refusal shapes.
14448 let s_bad_versao = SupervisorSpec {
14449 estrategia: RestartStrategy::OneForOne,
14450 children: vec![child("worker", "not-a-req", RestartPolicy::Permanent)],
14451 ..SupervisorSpec::default()
14452 };
14453 let via_gate = s_bad_versao.validate_children().unwrap_err();
14454 let via_validate = s_bad_versao.validate().unwrap_err();
14455 match (&via_gate, &via_validate) {
14456 (
14457 SupervisorError::ChildVersaoInvalid {
14458 caixa: cg,
14459 versao: vg,
14460 ..
14461 },
14462 SupervisorError::ChildVersaoInvalid {
14463 caixa: cv,
14464 versao: vv,
14465 ..
14466 },
14467 ) => {
14468 assert_eq!(cg, "worker", "per-slot gate :caixa carrier");
14469 assert_eq!(vg, "not-a-req", "per-slot gate :versao carrier");
14470 assert_eq!(cv, "worker", "validate() :caixa carrier");
14471 assert_eq!(vv, "not-a-req", "validate() :versao carrier");
14472 }
14473 other => panic!("expected ChildVersaoInvalid on both altitudes, got {other:?}"),
14474 }
14475 assert_eq!(
14476 via_gate, via_validate,
14477 "per-slot gate ≡ validate() on ChildVersaoInvalid full envelope",
14478 );
14479
14480 let s_ok = SupervisorSpec {
14481 estrategia: RestartStrategy::OneForOne,
14482 children: vec![
14483 child("worker-a", "^0.1", RestartPolicy::Permanent),
14484 child("worker-b", "~0.2.3", RestartPolicy::Transient),
14485 child("collector", "*", RestartPolicy::Temporary),
14486 ],
14487 ..SupervisorSpec::default()
14488 };
14489 s_ok.validate_children()
14490 .expect("per-slot gate must accept the clean-pass fixture");
14491 s_ok.validate()
14492 .expect("validate() must accept the clean-pass fixture");
14493 }
14494
14495 #[test]
14496 fn validate_children_is_self_contained_on_children_slot() {
14497 // Self-containment pin: [`SupervisorSpec::validate_children`]
14498 // resolves the per-child cascade against `&self` alone, without
14499 // depending on the peer `:estrategia`/`:max-restarts`/
14500 // `:restart-window` gates having run first — same posture the M3
14501 // peer per-slot gates carry (`validate_membros`,
14502 // `validate_contratos`, `validate_entrada`, `validate_placement`,
14503 // routing through their own oracles rather than borrowing state
14504 // threaded down from `validate`). A future consumer that reaches
14505 // the per-slot gate directly on a spec whose peer slots would
14506 // fail `validate` still surfaces the per-child refusal, not the
14507 // peer refusal.
14508 //
14509 // Construct a spec whose `:max-restarts` is `0` (which would
14510 // trip [`SupervisorError::ZeroMaxRestarts`] at `validate` after
14511 // the partition-dispatch) and whose `:children` carries a
14512 // `DuplicateChildCaixa` shape: the per-slot gate called directly
14513 // must surface `DuplicateChildCaixa`, proving it does not depend
14514 // on the peer `:max-restarts` gate running first.
14515 let s = SupervisorSpec {
14516 estrategia: RestartStrategy::OneForOne,
14517 max_restarts: 0,
14518 restart_window: Some(Duration::from_secs(60)),
14519 children: vec![
14520 child("worker", "^0.1", RestartPolicy::Permanent),
14521 child("worker", "^0.2", RestartPolicy::Transient),
14522 ],
14523 };
14524 assert_eq!(
14525 s.validate_children().unwrap_err(),
14526 SupervisorError::DuplicateChildCaixa {
14527 caixa: "worker".into(),
14528 },
14529 "per-slot gate must resolve per-child refusal directly against \
14530 `&self` — a dependency on the peer `:max-restarts` gate \
14531 running first would surface ZeroMaxRestarts here instead",
14532 );
14533 // The peer gate is still the surface `validate` reaches — pin
14534 // the ordering to establish that `validate_children` truly runs
14535 // last in `validate`'s dispatch, so a direct call bypasses the
14536 // peer gates on any spec whose per-child cascade would fail.
14537 assert_eq!(
14538 s.validate().unwrap_err(),
14539 SupervisorError::ZeroMaxRestarts,
14540 "validate() must surface the peer `:max-restarts` gate before \
14541 reaching the per-child cascade — this pins the dispatch \
14542 ordering the per-slot gate's self-containment complements",
14543 );
14544 }
14545
14546 #[test]
14547 fn child_spec_restart_accessor_is_const_fn() {
14548 // The [`ChildSpec::restart`] per-`:children` restart-decision-
14549 // policy `Copy`-return scalar accessor is declared
14550 // `#[must_use] pub const fn` — matching the sibling M2
14551 // per-`:supervisor` [`SupervisorSpec::estrategia`] (pinned by
14552 // [`supervisor_spec_estrategia_accessor_is_const_fn`] below,
14553 // both converted in this commit), the sibling M2
14554 // per-`:supervisor` [`SupervisorSpec::max_restarts`] (b698ec0)
14555 // `Copy`-`u32` accessor already `pub const fn`, and the peer M3
14556 // mesh-slot per-`:entrada` [`crate::Entrada::port`] (bafa004) /
14557 // per-`:placement` [`crate::Placement::estrategia`] (bafa004)
14558 // `Copy`-return `pub const fn` scalar accessors on the sibling
14559 // M3 surface. Pin the `const`-eval posture here so a future
14560 // accidental downgrade to non-`const` (an added runtime helper
14561 // reachable only from a non-`const` context, an
14562 // `Option<RestartPolicy>`-shape migration on the per-child
14563 // restart-decision axis once heterogeneous per-cluster
14564 // restart-policy overlays land that would silently drop the
14565 // `const` qualifier, a manual hand-rolled shadow) trips at
14566 // caixa-core build time rather than surfacing as a downstream
14567 // `const`-context regression far from the declaration.
14568 //
14569 // Same shape as the sibling M3
14570 // [`crate::aplicacao::tests::placement_estrategia_accessor_is_const_fn`]
14571 // and [`crate::aplicacao::tests::entrada_port_accessor_is_const_fn`]
14572 // (bafa004) pins on the peer M3 mesh-slot `Copy`-return scalar
14573 // accessor axis — the load-bearing witness lives in the
14574 // module-scope `const fn` wrapper `restart_via_const_fn` below:
14575 // a body that calls [`ChildSpec::restart`] under a `const fn`
14576 // signature is well-formed only when the callee is itself
14577 // `const fn`, so any future accidental downgrade of
14578 // [`ChildSpec::restart`] to non-`const` fails at caixa-core
14579 // build time (const-eval E0015 `cannot call non-const method`),
14580 // strictly stronger than a runtime `assert!(CONST)` and
14581 // side-stepping the destructor-in-const restriction that
14582 // blocks direct `const _: RestartPolicy = FIXTURE.restart()`
14583 // items on `ChildSpec`'s `String` carriers.
14584 //
14585 // The runtime body sweeps every closed-set [`RestartPolicy`]
14586 // arm and asserts the wrapped and direct dispatches agree.
14587 const fn restart_via_const_fn(c: &ChildSpec) -> RestartPolicy {
14588 c.restart()
14589 }
14590 for restart in [
14591 RestartPolicy::Permanent,
14592 RestartPolicy::Transient,
14593 RestartPolicy::Temporary,
14594 ] {
14595 let c = ChildSpec {
14596 caixa: "worker".into(),
14597 versao: "^0.1".into(),
14598 restart,
14599 };
14600 assert_eq!(
14601 restart_via_const_fn(&c),
14602 c.restart(),
14603 "const-fn-wrapped and direct dispatch on \
14604 ChildSpec::restart must agree for {restart:?}",
14605 );
14606 assert_eq!(
14607 c.restart(),
14608 restart,
14609 "ChildSpec::restart must return the storage-side \
14610 RestartPolicy verbatim for {restart:?} (a violation \
14611 means the accessor stopped being a raw field-return \
14612 copy)",
14613 );
14614 }
14615 }
14616
14617 #[test]
14618 fn supervisor_spec_estrategia_accessor_is_const_fn() {
14619 // The [`SupervisorSpec::estrategia`] per-`:supervisor`
14620 // sibling-restart-strategy `Copy`-return scalar accessor is
14621 // declared `#[must_use] pub const fn` — matching the sibling M2
14622 // per-`:children` [`ChildSpec::restart`] (pinned by
14623 // [`child_spec_restart_accessor_is_const_fn`] above, both
14624 // converted in this commit), the sibling M2 per-`:supervisor`
14625 // [`SupervisorSpec::max_restarts`] (b698ec0) `Copy`-`u32`
14626 // accessor already `pub const fn`, and mirroring the peer M3
14627 // mesh-slot per-`:placement`
14628 // [`crate::Placement::estrategia`] (bafa004) `Copy`-return
14629 // `pub const fn` scalar accessor whose method-name discipline
14630 // the [`SupervisorSpec::estrategia`] method was authored to
14631 // match. Pin the `const`-eval posture here so a future
14632 // accidental downgrade to non-`const` (an added runtime helper
14633 // reachable only from a non-`const` context, an
14634 // `Option<RestartStrategy>`-shape migration once the substrate
14635 // grows per-cluster strategy overlays that would silently drop
14636 // the `const` qualifier, a manual hand-rolled shadow) trips at
14637 // caixa-core build time rather than surfacing as a downstream
14638 // `const`-context regression far from the declaration.
14639 //
14640 // Same shape as the sibling
14641 // [`child_spec_restart_accessor_is_const_fn`] pin above — the
14642 // load-bearing witness lives in the module-scope `const fn`
14643 // wrapper `estrategia_via_const_fn` below: a body that calls
14644 // [`SupervisorSpec::estrategia`] under a `const fn` signature
14645 // is well-formed only when the callee is itself `const fn`,
14646 // side-stepping the destructor-in-const restriction that would
14647 // otherwise block a direct
14648 // `const _: RestartStrategy = FIXTURE.estrategia()` item on
14649 // `SupervisorSpec`'s `Vec<ChildSpec>` / `Option<Duration>`
14650 // carriers.
14651 //
14652 // The runtime body sweeps every closed-set [`RestartStrategy`]
14653 // arm via [`RestartStrategy::ALL`] and asserts the wrapped and
14654 // direct dispatches agree.
14655 const fn estrategia_via_const_fn(s: &SupervisorSpec) -> RestartStrategy {
14656 s.estrategia()
14657 }
14658 for &estrategia in RestartStrategy::ALL {
14659 let s = SupervisorSpec {
14660 estrategia,
14661 max_restarts: 5,
14662 restart_window: Some(Duration::from_secs(60)),
14663 children: Vec::new(),
14664 };
14665 assert_eq!(
14666 estrategia_via_const_fn(&s),
14667 s.estrategia(),
14668 "const-fn-wrapped and direct dispatch on \
14669 SupervisorSpec::estrategia must agree for {estrategia:?}",
14670 );
14671 assert_eq!(
14672 s.estrategia(),
14673 estrategia,
14674 "SupervisorSpec::estrategia must return the storage-side \
14675 RestartStrategy verbatim for {estrategia:?} (a violation \
14676 means the accessor stopped being a raw field-return \
14677 copy)",
14678 );
14679 }
14680 }
14681
14682 // Per-variant equivalence pins for the [`supervisor_caixa_only_ctors!`]
14683 // macro definition (see the paired doc-block above the macro
14684 // definition) — every generated `<ctor>(caixa: &str) -> Self`
14685 // constructor folds the uniform `Self::<Variant> { caixa:
14686 // caixa.to_string() }` one-field struct-literal onto one substrate
14687 // primitive. The three per-variant equivalence pins below
14688 // (fail-before-pass-after by construction — a byte-mismatched macro
14689 // arm would trip its equivalence pin first) lock each generated
14690 // constructor to its struct-literal peer under `PartialEq`, so
14691 // every wire-up in [`SupervisorSpec::validate_children`] and
14692 // [`validate_no_self_supervision`] on that variant produces a
14693 // byte-equal `SupervisorError` to the pre-lift open-coded
14694 // struct-literal. The cross-axis pin that follows (non-default
14695 // caixa name) routes the sole constructor input axis through
14696 // `.to_string()`, so the fold does not silently collapse onto a
14697 // fixed name.
14698 //
14699 // Peer of the sibling `<slot>_ctor_matches_tuple_literal_wrap` /
14700 // `<slot>_violation_ctor_matches_struct_literal_wrap` /
14701 // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
14702 // `missing_entry_ctor_matches_struct_literal_wrap` /
14703 // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
14704 // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
14705 // `contrato_missing_target_ctor_matches_struct_literal_wrap` /
14706 // `<variant>_ctor_matches_struct_literal_wrap` equivalence pins
14707 // on the six sibling ctor families the recent trajectory closed
14708 // on the peer `LayoutError` / `AplicacaoError` envelopes.
14709
14710 #[test]
14711 fn empty_child_version_ctor_matches_struct_literal_wrap() {
14712 assert_eq!(
14713 SupervisorError::empty_child_version("worker"),
14714 SupervisorError::EmptyChildVersion {
14715 caixa: "worker".to_string(),
14716 },
14717 "generated empty_child_version ctor must produce byte-equal \
14718 SupervisorError to the open-coded struct-literal wrap on the \
14719 same &str fixture",
14720 );
14721 }
14722
14723 #[test]
14724 fn duplicate_child_caixa_ctor_matches_struct_literal_wrap() {
14725 assert_eq!(
14726 SupervisorError::duplicate_child_caixa("worker"),
14727 SupervisorError::DuplicateChildCaixa {
14728 caixa: "worker".to_string(),
14729 },
14730 "generated duplicate_child_caixa ctor must produce byte-equal \
14731 SupervisorError to the open-coded struct-literal wrap on the \
14732 same &str fixture",
14733 );
14734 }
14735
14736 #[test]
14737 fn child_supervises_self_ctor_matches_struct_literal_wrap() {
14738 assert_eq!(
14739 SupervisorError::child_supervises_self("orquestra"),
14740 SupervisorError::ChildSupervisesSelf {
14741 caixa: "orquestra".to_string(),
14742 },
14743 "generated child_supervises_self ctor must produce byte-equal \
14744 SupervisorError to the open-coded struct-literal wrap on the \
14745 same &str fixture",
14746 );
14747 }
14748
14749 // Per-variant equivalence pins for the two lifted
14750 // [`SupervisorError::child_caixa_invalid`] /
14751 // [`SupervisorError::child_versao_invalid`] inherent constructors
14752 // (fail-before-pass-after by construction — a byte-mismatched ctor body
14753 // would trip its equivalence pin first). Each pins the ctor output to
14754 // its pre-lift struct-literal peer under `PartialEq`, so every wire-up
14755 // in [`SupervisorSpec::validate_children`] on the two variants
14756 // produces a byte-equal `SupervisorError` to the pre-lift open-coded
14757 // struct-literal on the same scalar fixtures. Peers of the sibling
14758 // `membro_caixa_invalid_ctor_matches_struct_literal_wrap` /
14759 // `entrada_para_invalid_ctor_matches_struct_literal_wrap` / … pins on
14760 // the peer `AplicacaoError` envelope's
14761 // [`crate::aplicacao::aplicacao_field_reason_ctors!`] fold.
14762
14763 #[test]
14764 fn child_caixa_invalid_ctor_matches_struct_literal_wrap() {
14765 let caixa = "Worker";
14766 let reason = "sample reason text";
14767 assert_eq!(
14768 SupervisorError::child_caixa_invalid(caixa, reason),
14769 SupervisorError::ChildCaixaInvalid {
14770 caixa: caixa.to_string(),
14771 reason: reason.to_string(),
14772 },
14773 "lifted child_caixa_invalid ctor must produce byte-equal \
14774 SupervisorError to the open-coded struct-literal wrap on the \
14775 same (&str, reason) fixture",
14776 );
14777 }
14778
14779 #[test]
14780 fn child_versao_invalid_ctor_matches_struct_literal_wrap() {
14781 let caixa = "worker";
14782 let versao = "not-a-req";
14783 let reason = "sample reason text";
14784 assert_eq!(
14785 SupervisorError::child_versao_invalid(caixa, versao, reason),
14786 SupervisorError::ChildVersaoInvalid {
14787 caixa: caixa.to_string(),
14788 versao: versao.to_string(),
14789 reason: reason.to_string(),
14790 },
14791 "lifted child_versao_invalid ctor must produce byte-equal \
14792 SupervisorError to the open-coded struct-literal wrap on the \
14793 same (&str, &str, reason) fixture",
14794 );
14795 }
14796
14797 #[test]
14798 fn supervisor_child_reason_ctors_route_reason_through_into_uniformly() {
14799 // Cross-axis pin: sweep the two lifted `{ …, reason }` ctors
14800 // against a `&str`-literal vs. `format!(…)` reason input to pin
14801 // both constructors accept the `impl Into<String>` bound
14802 // uniformly, so neither wire-up site drifts under a per-arm
14803 // wrapper transformation on the caller-side `reason` axis. Peer
14804 // of the sibling
14805 // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
14806 // sweep on the peer `AplicacaoError` envelope.
14807 let via_literal = "literal reason text";
14808 let via_format = format!("{} reason text", "literal");
14809 assert_eq!(
14810 SupervisorError::child_caixa_invalid("Worker", via_literal),
14811 SupervisorError::child_caixa_invalid("Worker", via_format.clone()),
14812 );
14813 assert_eq!(
14814 SupervisorError::child_versao_invalid("worker", "not-a-req", via_literal),
14815 SupervisorError::child_versao_invalid("worker", "not-a-req", via_format),
14816 );
14817 }
14818
14819 #[test]
14820 fn supervisor_caixa_only_ctors_route_caixa_through_to_string() {
14821 // Cross-axis pin: sweep the sole constructor input axis (`caixa:
14822 // &str`) through a non-default fixture name against every
14823 // generated arm in the [`supervisor_caixa_only_ctors!`] macro,
14824 // so any wrapper-side lowercase / trim / truncate / re-order on
14825 // the `caixa.to_string()` sole-field construction surfaces
14826 // here rather than at a downstream diagnostic-shape mismatch.
14827 // Peer of the sibling `nome_only_ctor_routes_caixa_through_
14828 // nome_accessor` / `entrada_host_invalid_ctor_routes_host_
14829 // through_to_string` / `contrato_target_ctors_route_edge_
14830 // triple_through_verbatim` / `contrato_empty_pair_ctors_
14831 // route_edge_pair_through_verbatim` cross-axis routing pins on
14832 // the peer `LayoutError` / `AplicacaoError` envelopes; extended
14833 // here onto the `SupervisorError` `{ caixa: String }` envelope
14834 // so every substrate-primitive ctor family in caixa-core
14835 // guarantees the sole-field construction routes the caller's
14836 // `&str` through `.to_string()` verbatim.
14837 let name = "cache-v2";
14838 assert_eq!(
14839 SupervisorError::empty_child_version(name),
14840 SupervisorError::EmptyChildVersion {
14841 caixa: name.to_string(),
14842 },
14843 );
14844 assert_eq!(
14845 SupervisorError::duplicate_child_caixa(name),
14846 SupervisorError::DuplicateChildCaixa {
14847 caixa: name.to_string(),
14848 },
14849 );
14850 assert_eq!(
14851 SupervisorError::child_supervises_self(name),
14852 SupervisorError::ChildSupervisesSelf {
14853 caixa: name.to_string(),
14854 },
14855 );
14856 }
14857
14858 // ── supervisor_scalar_ctors! per-variant + cross-axis pins ──────────────
14859 //
14860 // Per-variant byte-equality pins guaranteeing every generated ctor arm in
14861 // the [`supervisor_scalar_ctors!`] macro produces a `SupervisorError`
14862 // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
14863 // one-line struct-literal on the same `Copy`-`RestartStrategy | u32 |
14864 // Duration` fixture, plus one cross-axis sweep that routes each per-variant
14865 // `<field>: <ty>` scalar through the sole `$field:ident: $ty:ty` axis the
14866 // macro exposes so any wrapper-side truncation / re-order / silent `.into()`
14867 // / silent constant-substitution on any one variant surfaces here rather
14868 // than at a downstream per-`:supervisor` diagnostic-shape drift. Peer of the
14869 // sibling per-variant pins on `aplicacao_policy_scalar_ctors!` (7ef425e,
14870 // the 8-variant `AplicacaoError` `{ <field>: Duration | u32 }` fold on the
14871 // per-`:politicas` per-axis cap / canonical-form arms), plus the sibling
14872 // `supervisor_caixa_only_ctors!` (db09650), `SupervisorError::
14873 // {child_caixa_invalid,child_versao_invalid}` (d2ef2ec), and the peer
14874 // `DepError` / `AplicacaoError` / `LayoutError` / `LimitsError` /
14875 // `BehaviorError` / `UpgradeError` per-envelope ctor-macro pins.
14876 #[test]
14877 fn no_children_ctor_matches_struct_literal_wrap() {
14878 let estrategia = RestartStrategy::OneForAll;
14879 assert_eq!(
14880 SupervisorError::no_children(estrategia),
14881 SupervisorError::NoChildren { estrategia },
14882 "generated no_children ctor must produce byte-equal \
14883 `SupervisorError::NoChildren` to the pre-lift struct-literal wrap \
14884 on the same `Copy`-`RestartStrategy` fixture",
14885 );
14886 }
14887
14888 #[test]
14889 fn max_restarts_exceeds_cap_ctor_matches_struct_literal_wrap() {
14890 let max_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 1;
14891 assert_eq!(
14892 SupervisorError::max_restarts_exceeds_cap(max_restarts),
14893 SupervisorError::MaxRestartsExceedsCap { max_restarts },
14894 "generated max_restarts_exceeds_cap ctor must produce byte-equal \
14895 `SupervisorError::MaxRestartsExceedsCap` to the pre-lift \
14896 struct-literal wrap on the same `Copy`-`u32` fixture",
14897 );
14898 }
14899
14900 #[test]
14901 fn restart_window_not_canonical_ctor_matches_struct_literal_wrap() {
14902 let window = Duration::from_micros(1_500);
14903 assert_eq!(
14904 SupervisorError::restart_window_not_canonical(window),
14905 SupervisorError::RestartWindowNotCanonical { window },
14906 "generated restart_window_not_canonical ctor must produce \
14907 byte-equal `SupervisorError::RestartWindowNotCanonical` to the \
14908 pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
14909 );
14910 }
14911
14912 #[test]
14913 fn restart_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
14914 let window = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_millis(1);
14915 assert_eq!(
14916 SupervisorError::restart_window_exceeds_cap(window),
14917 SupervisorError::RestartWindowExceedsCap { window },
14918 "generated restart_window_exceeds_cap ctor must produce \
14919 byte-equal `SupervisorError::RestartWindowExceedsCap` to the \
14920 pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
14921 );
14922 }
14923
14924 #[test]
14925 fn supervisor_scalar_ctors_route_field_through_copy_uniformly() {
14926 // Cross-axis routing pin: sweep each generated `<field>: <ty>`
14927 // constructor input axis through a non-default `Copy` fixture against
14928 // every arm in the [`supervisor_scalar_ctors!`] macro, so any wrapper-
14929 // side silent `.into()` / silent constant-substitution / silent field
14930 // re-name away from the canonical `estrategia | max_restarts | window`
14931 // axes on any one variant, or a `RestartStrategy | u32 | Duration`
14932 // axis silently rerouted through some other `Copy` coercion, surfaces
14933 // here rather than at a downstream per-`:supervisor` diagnostic-shape
14934 // drift. Peer of the sibling
14935 // `aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly`
14936 // (7ef425e) cross-axis routing pin on the peer `AplicacaoError`
14937 // envelope's per-`:politicas` per-axis ctor family, extended here onto
14938 // the last M2 per-`:supervisor` `Copy`-scalar `SupervisorError`
14939 // variant family folded onto a substrate primitive.
14940 //
14941 // Fixtures picked out of each variant's accept-set boundary rather
14942 // than the default value so a silent constant-substitution to a per-
14943 // variant sentinel surfaces here on the structural-equality assertion.
14944 // The `RestartStrategy` fixture picks `RestForOne` (a non-default arm
14945 // that isn't the `OneForOne` [`SUPERVISOR_ESTRATEGIA_DEFAULT`] and
14946 // isn't the `SimpleOneForOne` arm the sibling
14947 // `SimpleOneForOneWithStaticChildren` unit variant intercepts). The
14948 // `max_restarts` fixture picks an above-cap magnitude the cap arm
14949 // rejects; the two `Duration` fixtures pick the sub-millisecond and
14950 // above-cap ends of the `:restart-window` canonical-form + cap
14951 // bracket respectively.
14952 let estrategia = RestartStrategy::RestForOne;
14953 let above_cap_restarts = SUPERVISOR_MAX_RESTARTS_MAX + 137;
14954 let sub_ms = Duration::from_micros(1_500);
14955 let above_hour = SUPERVISOR_RESTART_WINDOW_MAX + Duration::from_secs(1);
14956 assert_eq!(
14957 SupervisorError::no_children(estrategia),
14958 SupervisorError::NoChildren { estrategia },
14959 );
14960 assert_eq!(
14961 SupervisorError::max_restarts_exceeds_cap(above_cap_restarts),
14962 SupervisorError::MaxRestartsExceedsCap {
14963 max_restarts: above_cap_restarts,
14964 },
14965 );
14966 assert_eq!(
14967 SupervisorError::restart_window_not_canonical(sub_ms),
14968 SupervisorError::RestartWindowNotCanonical { window: sub_ms },
14969 );
14970 assert_eq!(
14971 SupervisorError::restart_window_exceeds_cap(above_hour),
14972 SupervisorError::RestartWindowExceedsCap { window: above_hour },
14973 );
14974 }
14975
14976 #[test]
14977 fn supervisor_scalar_ctors_are_const_zero_runtime_work() {
14978 // Const-eval pin: the [`supervisor_scalar_ctors!`] macro spells every
14979 // generated ctor `const fn` so a caller can pin a `SupervisorError`
14980 // at compile time — the same zero-runtime-work property the pre-lift
14981 // `|<slot>| SupervisorError::<Variant> { <slot> }` closure carried on
14982 // its `Copy`-pass-through construction path (no `.to_string()` /
14983 // `.into()` allocation, no branching). If any future edit silently
14984 // drops the `const` qualifier from the macro body the per-arm `const`
14985 // bindings below fail to compile, which surfaces the regression at
14986 // the substrate-primitive definition rather than at some downstream
14987 // consumer that had come to rely on the `const`-constructibility.
14988 // Peer of the sibling
14989 // `aplicacao_policy_scalar_ctors_are_const_zero_runtime_work`
14990 // (7ef425e) const-eval pin on the peer `AplicacaoError` envelope's
14991 // per-`:politicas` per-axis ctor family.
14992 const NO_CHILDREN: SupervisorError =
14993 SupervisorError::no_children(RestartStrategy::OneForAll);
14994 const MAX_RESTARTS_CAP: SupervisorError = SupervisorError::max_restarts_exceeds_cap(1_337);
14995 const WINDOW_NC: SupervisorError =
14996 SupervisorError::restart_window_not_canonical(Duration::from_micros(1));
14997 const WINDOW_CAP: SupervisorError =
14998 SupervisorError::restart_window_exceeds_cap(Duration::from_secs(3_601));
14999 assert!(matches!(NO_CHILDREN, SupervisorError::NoChildren { .. }));
15000 assert!(matches!(
15001 MAX_RESTARTS_CAP,
15002 SupervisorError::MaxRestartsExceedsCap { .. }
15003 ));
15004 assert!(matches!(
15005 WINDOW_NC,
15006 SupervisorError::RestartWindowNotCanonical { .. }
15007 ));
15008 assert!(matches!(
15009 WINDOW_CAP,
15010 SupervisorError::RestartWindowExceedsCap { .. }
15011 ));
15012 }
15013}